text
stringlengths
15
59.8k
meta
dict
Q: WSDL UNKNOWN for input/output I've recently started developing a SOAP web service but running through some issues I can't resolve. So I've built a PHP client to test out the service. When I invoke __getFunctions using soapclient through my php script, I receive the following array(1) { [0]=> string(31) "UNKNOWN doOrder(UNKNOWN $order)" } Why are my input and output data types unknown? WSDL: <?xml version="1.0"?> <definitions name="PlaceOrders" targetNamespace="urn:PlaceOrders" xmlns:tns="urn:PlaceOrders" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <types> <xsd:schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:Orders"> <xsd:element name="orderXML" type="xsd:base64Binary" /> <xsd:element name="orderResponse" type="xsd:string" /> </xsd:schema> </types> <message name="doOrder"> <part name="order" type="tns:orderXML" /> </message> <message name="doOrderResponse"> <part name="return" type="tns:orderResponse" /> </message> <portType name="OrderPort"> <operation name="doOrder"> <input message="tns:doOrder" /> <output message="tns:doOrderResponse" /> </operation> </portType> <binding name="OrderBinding" type="tns:OrderPort"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" /> <operation name="doOrder"> <soap:operation soapAction="urn:OrderAction" /> <input> <soap:body use="encoded" namespace="urn:Orders" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" /> </input> <output> <soap:body use="literal" namespace="urn:Orders" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" /> </output> </operation> </binding> <service name="OrderService"> <port name="OrderPort" binding="tns:OrderBinding"> <soap:address location="[MYLINK]" /> </port> </service> </definitions> SOAP Client: ini_set('display_errors',1); ini_set('soap.wsdl_cache_enabled', 0); $client = new SoapClient([MYLINK]); var_dump($client->__getFunctions());
{ "language": "en", "url": "https://stackoverflow.com/questions/10076498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JPA/Hibernate How to add duplicate values to a List<> with a @OneToMany mapping I am getting an error every time I try to add duplicate products to the Client class. org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "uk_8opk6otadh2pkvi9bghguwp89" Detail: Key (products_id)=(500010) already exists. My entities @Entity public class Client { @Id private String id; @OneToMany private List<Product> products; } @Entity public class Product { @Id private String id; private Boolean foreign; private Integer price; } When I call .save() hibernate is trying to re-save an already existing Product. I believe this is due to the how it cascades things. public Client addNewProduct(Client client, Product newProduct) { List<Product> products = client.getProducts(); products.add(newProduct); client.setProducts(products); return clientRepository.save(client); } I just want to be able to add duplicates to a List<>. I believe this is & should be a uni-directional relationship. A: This does not work with your current relationship, I don't understand why you would want to add duplicates, but if you have to, then you'd have to create a new entity for that. One example would be something like this: @Entity public class ProductBatch { @Id private String id; @OneToOne private Product product; private Integer count; // getter & setter } and then you change your Client like this: @Entity public class Client { @Id private String id; @OneToMany private List<ProductBatch> products; } this makes something like this possible for your addNewProduct function: public Client addNewProduct(Client client, Product newProduct) { List<ProductBatch> products = client.getProducts(); boolean exists = false; for(ProductBatch product : products) { if(product.getProduct().equals(newProduct)) { product.setCount(product.getCount() + 1); exists = true; } } if(!exists) { BatchProduct product = new BatchProduct(); product.setProduct(newProduct); product.setCount(0); products.add(product); } client.setProducts(products); return clientRepository.save(client); } A: That has nothing to do with JPA or Hibernate. A constraint is a Database constraint and it is right. If a Foreign Key is already part of the table, trying to add it again, violates this constraint. An ID is unique and it should stay that way. So adding duplicates (at least with the same ID) will not work.
{ "language": "en", "url": "https://stackoverflow.com/questions/70748890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript ! and !! differences Possible Duplicate: What is the !! operator in JavaScript? What is the difference between these two operators? Does !! have special meaning, or does it simply mean you are doing two '!' operations. I know there are "Truth" and "Truthy" concepts in Javascript, but I'm not sure if !! is meant for "Truth" A: !! is just double ! !true // -> false !!true // -> true !! is a common way to cast something to boolean value !!{} // -> true !!null // -> false A: Writing !! is a common way of converting a "truthy" or "falsey" variable into a genuine boolean value. For example: var foo = null; if (!!foo === true) { // Code if foo was "truthy" } After the first ! is applied to foo, the value returned is true. Notting that value again makes it false, meaning the code inside the if block is not entered.
{ "language": "en", "url": "https://stackoverflow.com/questions/6177370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Efficient iteration through AD Group Membership I'm just going to five straight in with what I have, the scenario is a little too complex to explain off the mark. XML config: <Groups> <Group priority="1" name="testGroup1" profile="testProfile1"/> <Group priority="2" name="testGroup2" profile="testProfile2"/> <Group priority="3" name="testGroup3" profile="testProfile3"/> <Group priority="4" name="testGroup4" profile="testProfile4"/> </Groups> Powershell: $userProfileHash = [ordered]@{} # Itterate through groups foreach ($group in ($homeNode.ApplicationMethod | ? {$_.id -eq "adgroup"}).Groups.Group | Sort-Object $_.priority) { # Get group members, Itterate through them Get-ADGroupMember -Identity $group.name | ForEach-Object { # Add to ordered hash try { $userProfileHash.Add($($_.samaccountname),$group.profile) } catch {#don't want to see errors, there may be many} } } Now I'll to to explain: To protect against a user being a member of more than 1 of the defined groups. I sort the groups by priority (in the foreach expression) and then use the hashtable rule that the key must be unique. This ensures that each user is only added once and that they will be assigned the profile of the group they appeared in first. I don't really like this approach, but it was the quickest of the approaches I tried: 5 Seconds with 1100 test users. Question: How can I speed up this code? (there may be tens of thousands of users when this is in production) A: Hash table operations are very efficient, and if you're getting a lot of errors due to duplicate adds you might be better off eliminating the error handling. If you sort the priorities in descending order then you can do this: $userProfileHash[$_.samaccountname] = $group.profile and eliminate the Try/Catch. Duplicate memberships will just get overwritten and the last entry written for each user will be the highest priority group profile they belong to. Edit: the original command I posted used the += operator. That's not correct for this application, and I've corrected the code.
{ "language": "en", "url": "https://stackoverflow.com/questions/23564958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript files getting included multiple times For some reason my javascript files are getting included in my source 12 times. Other members of my team, using the same source, do not have this problem. Any ideas what could cause this? A: Have you made sure that you are precompiling all of your assets? Try using: bundle exec rake assets:precompile
{ "language": "en", "url": "https://stackoverflow.com/questions/11438744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cancelling a background worker without worker.CancellationPending check? I have a Validator class which has a Validate function, This validate function loops over bunch of file and validates them. User can cancel the validate process. For cancelling the back ground worker I need ta reference of the background worker instance in Validtor class (for cancelling the validation process) and call CancellationPending on it. But the problem is Validator class can't have reference to background worker because there are times when we call the "Validate" function synchronously and Validator class does not have to know this. So far I have tried replacing backgroundworker.CancellationPending check with some flag e.g. IsCanceled which do not seems to work. A: You have two options: * *Make two overloads of the Validate method. One that is synchronous and one that is asynchronous and cancellable. *Change your Validate method so that the calling code is responsible for looping over the files (consider an iterator method, using yield) I'd go with option 1 as it is a smaller change.
{ "language": "en", "url": "https://stackoverflow.com/questions/22325574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use std::chrono::milliseconds as a default parameter Scenario I have a C++ function which intakes a parameter as std::chrono::milliseconds. It is basically a timeout value. And, it is a default parameter set to some value by default. Code #include <iostream> #include <chrono> void Fun(const std::chrono::milliseconds someTimeout = std::chrono::milliseconds(100)) { if (someTimeout > 0) { std::cout << "someNumberInMillis is: " << someNumberInMillis.count() << std::endl; } } int main() { unsigned int someValue = 500; Fun(std::chrono::milliseconds(someValue)) } Issue All of above is okay but, when I call Fun with a value then fails to compile and I get the following error: No viable conversion from 'bool' to 'std::chrono::milliseconds' (aka 'duration >') Question: What am I doing wrong here? I want the caller of Fun to be explicitly aware that it is using std::chrono::milliseconds when it invokes Fun. But the compiler doesn't seem to allow using std::chrono::milliseconds as a parameter? How use std::chrono::milliseconds as a default parameter? Environment Compiler used is clang on macOS High Sierra A: With the other syntax errors fixed, this compiles without warnings in GCC 9: #include <iostream> #include <chrono> void Fun(const std::chrono::milliseconds someNumberInMillis = std::chrono::milliseconds(100)) { if (someNumberInMillis > std::chrono::milliseconds{0}) { std::cout << "someNumberInMillis is: " << someNumberInMillis.count() << std::endl; } } int main() { unsigned int someValue = 500; Fun(std::chrono::milliseconds(someValue)); }
{ "language": "en", "url": "https://stackoverflow.com/questions/58730696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: use gruntjs in root file my file tree |- root |-- gruntfile.js |-- package.json |-- lib (jQuery & other) |-- webapp |---- App-1 |------- src(app src) |---------- js |---------- css |---------- images |------- package.json(use to require other modules) |---- App-2 |------- src(app src) |---------- js |---------- css |---------- images |------- package.json(use to require other modules) ... ... |---- App-n In my file system,most app use a same task.Make gruntfile in every "App" file is not easy. so,how can i use a gruntfile on "root",and use it on my "App" file? thanks~:) A: Unless all your apps are going to be exactly the same, use a new gruntfile for each app. I'm guessing each of your apps will all be different as you've duplicated the src folder within each in anticipation. I don't recommend a global dependency setup. As time goes on, each of your apps will diverge and the amount of your apps will increase. When it comes time to upgrade jQuery or any other dependency in your root/lib folder... you will be forced to upgrade every single app. The small convenience now is totally not worth it later. Instead, just install everything locally and then you can upgrade each app as needed without breaking the other apps. If you come across duplicate code in your apps, consider moving it into a module. Create your module just like another app, then type npm link to make it installable. Then in each of your apps do npm link mymodule to install your module to the node_modules/mymodule folder. Here is an example file tree: my file tree |- root |-- devmodules |---- mymodule |------ index.js |------ package.json |-- webapps |---- App-1 |------- src(app src) |---------- js |---------- css |---------- images |------- node_modules (jQuery & other) |------- Gruntfile.js |------- package.json(use to require other modules) |---- App-2 |------- src(app src) |---------- js |---------- css |---------- images |------- node_modules (jQuery & other) |------- Gruntfile.js |------- package.json(use to require other modules) ... ... |---- App-n
{ "language": "en", "url": "https://stackoverflow.com/questions/17743783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Aggregate by name and average value per day in SQL I have data of the following format in a table (I have only shown values for two hours, but in reality I have values for all 24 hours): Name Availability Date ItemID -------------------------------------------------------- S1 75 2014-11-11 19:00:00.000 1124023 S1 80 2014-11-11 20:00:00.000 1124023 S2 60 2014-11-11 19:00:00.000 1124010 S2 50 2014-11-11 20:00:00.000 1124010 I would like to get the average availability for the entire day in the following format in a view: Name Availability Date ItemID -------------------------------------------------------- S1 77.5 2014-11-11 1124023 S2 55 2014-11-11 1124010 It's okay if Date in the output shows up as 2014-11-11 0:00:00.000 as well. I tried the following, but it doesn't work. Any help would be greatly appreciated. SELECT Name, AVG(Availability), CAST(FLOOR(CAST(Date AS FLOAT)) AS DATETIME) AS Expr1, ItemID FROM dbo.ServiceAvailability GROUP BY CAST(FLOOR(CAST(Date AS FLOAT)) AS DATETIME) A: Your current query is very close, you are missing a few columns in your GROUP BY clause. I'd also suggest a shorter way to get the date without time. SELECT Name, AVG(cast(Availability as decimal(10, 2))), CAST([Date] as date) AS Expr1, ItemID FROM dbo.ServiceAvailability GROUP BY Name, CAST([Date] as date), ItemID See Demo. Since you are using SQL Server 2014, you can just cast your datetime column as a date - which drops the time portion. I'd also suggest casting your Availability column to something other than an int so you get a decimal. Since you are using an aggregate function any columns in the SELECT list that aren't being aggregated need to be included in the GROUP BY clause, so you need to include Name and ItemID.
{ "language": "en", "url": "https://stackoverflow.com/questions/27255528", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Silverlight 4.0 - image cropping with mouse events I have a task to build image cropping functionality in Silverlight 4.0 application. What I need to do is to have user on the left button mouse click select area to remain after cropping is applied and then call some other event (button click maybe) to apply that cropping itself. I did develop similar functionality for rotation. I am pretty sure it is possible to do for cropping as well but that task is probably rare at this point for I can't find tutorials on the topic in the net. If you guys can get me a snippet to begin with or point to some good tutorial about Silverlight 4.0 image cropping, I would appreciate it. Thanks! A: As far as cropping images are concerned you can use the WriteableBitmapEx library on codeplex. Now you just need to draw a rectangle on a canvas containing the image to describe the crop region.
{ "language": "en", "url": "https://stackoverflow.com/questions/3782262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: TIdTCPServer gets stuck when connecting the second time I am using TIdTCPClient to get a file list all works well but when i close the client application and open it again i don't receive any event on TCPServer onExecute though the TIdTCPClient successfully connects to it and i am not able to send the file list. What am i doing wrong ? Some code : procedure TTaifun.csConnected(Sender: TObject); begin cs.IOHandler.WriteLn('FILE_LIST|NOW'); //Sending a request to server for the files fname := cs.IOHandler.ReadLn(nil); //Got the file names files := ExplodeString(fname,'|'); // Parse the files end; procedure TTaifun.svExecute(AContext: TIdContext); var cmds, flist: TStringList; i: Integer; tmp: string; FS : TFileStream; begin CSection.Enter; //Enter critical section cmds := ExplodeString(AContext.Connection.IOHandler.ReadLn(nil), '|'); try if cmds[0] = 'FILE_LIST' then //Check command received begin flist := TStringList.Create; flist.LoadFromFile(MyPath + 'files.dat'); tmp := ''; for i := 0 to flist.Count - 1 do begin tmp := tmp + flist[i] + ',' + GetFileSize(flist[i]) + ',' + BoolToStr(FileExists(MyPath + 'Thumbs\' + ChangeFileExt(ExtractFileName(flist[i]), '.thb')),true) + '|'; //Do some parsing end; AContext.Connection.IOHandler.WriteLn(tmp); //Send the string end finally CSection.Leave; //Leave critical section end; end; A: You are not protecting your critical section from exceptions. When the client disconnects, an exception will be raised by either ReadLn() or WriteLn() (depending on timing) to terminate the thread for that client. The next time the OnExecute event is called for a different thread, the critical section will still be locked and cannot be re-entered again, deadlocking your code. Add a try/finally to your code to guard against that, eg: procedure TTaifun.svExecute(AContext: TIdContext); var ... begin CSection.Enter; //Enter critical section try ... finally CSection.Leave; //Leave critical section end; end; With that said, why are you using a critical section to begin with? The code you showed is thread-safe by itself, it does not need to be protected from concurrent access: procedure TTaifun.svExecute(AContext: TIdContext); var cmds, flist: TStringList; i: Integer; tmp: string; begin cmds := ExplodeString(AContext.Connection.IOHandler.ReadLn, '|'); if cmds[0] = 'FILE_LIST' then //Check command received begin tmp := ''; flist := TStringList.Create; try flist.LoadFromFile(MyPath + 'files.dat'); for i := 0 to flist.Count - 1 do begin tmp := tmp + flist[i] + ',' + GetFileSize(flist[i]) + ',' + BoolToStr(FileExists(MyPath + 'Thumbs\' + ChangeFileExt(ExtractFileName(flist[i]), '.thb')),true) + '|'; //Do some parsing end; finally flist.Free; end; AContext.Connection.IOHandler.WriteLn(tmp); //Send the string end; end; Alternatively: procedure TTaifun.svExecute(AContext: TIdContext); var cmds, flist: TStringList; i: Integer; begin cmds := ExplodeString(AContext.Connection.IOHandler.ReadLn, '|'); if cmds[0] = 'FILE_LIST' then //Check command received begin flist := TStringList.Create; try flist.LoadFromFile(MyPath + 'files.dat'); for i := 0 to flist.Count - 1 do begin flist[i] := flist[i] + ',' + GetFileSize(flist[i]) + ',' + BoolToStr(FileExists(MyPath + 'Thumbs\' + ChangeFileExt(ExtractFileName(flist[i]), '.thb')),true); //Do some parsing end; flist.Delimiter := '|'; flist.StrictDelimiter := True; AContext.Connection.IOHandler.WriteLn(flist.DelimitedText); //Send the string finally flist.Free; end; end; end;
{ "language": "en", "url": "https://stackoverflow.com/questions/8768692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Why no type mismatch in call to CoCreateInstance function in the Windows API? I'm trying to translate this example of calling the WMI/COM using winapi from C++ to Rust, but there's something I don't understand in the original code. Here's a function call in the C++ code: hres = CoCreateInstance( CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *) &pLoc); What puzzles me is the type of the first and fourth arguments. Take the fourth argument, for example. If we look at the definition of CoCreateInstance, the fourth argument is of type REFIID which in turn is defined as a *IID where an IID is defined as a GUID. So the fourth argument should be a pointer to a GUID object. But if you look at what I think is the definition of IID_IWbemLocator, it's defined as a GUID (using the DEFINE_GUID macro). So it looks like we're passing a GUID as an argument when really we should be passing a pointer to a GUID. Why does this code compile? By comparison, in Rust I have to pass a reference to IID_IWbemLocator. Apologies if the answer is really simple, I'm pretty unfamiliar with both C++ and the Winapi. A: the third argument is of type REFIID which in turn is defined as a *IID where an IID is defined as a GUID. So the third argument should be a pointer to a GUID object. The documentation you linked is incorrect. I suspect it was written for C. In C++, REFIID and REFCLSID are defined as IID references in Windows headers, like so: #ifdef __cplusplus #define REFIID const IID & #else #define REFIID const IID * __MIDL_CONST #endif #ifdef __cplusplus #define REFCLSID const IID & #else #define REFCLSID const IID * __MIDL_CONST #endif
{ "language": "en", "url": "https://stackoverflow.com/questions/59362354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: replacing elements in a vector of vectors C++ i have a vector of vector that contain just periods (".") so far and I want to replace certain coordinates on the grid with a symbol that I am taking in from an input file. I am using the replace method but keep getting this error " error: no matching function for call to replace(std::basic_string, std::allocator >&, std::basic_string, std::allocator >&, const char [2], const char*)" I am not sure what that error means. I appreciate any and all help. Thanks in advance here is my code #include <vector> #include <string> #include <fstream> #include <iostream> #include <algorithm> using namespace std; int main() { string locationfilename, filenames,symbol; int numRows, numCols, startRow, startCol, endRow, endCol, possRow, possCol, id; cout<< "Enter Locations Filename"<<endl; cin>>locationfilename; cout<< "Enter Names Filename"<<endl; cin>>filenames; ifstream locations(locationfilename.c_str()); ifstream names(filenames.c_str()); locations>>numRows>>numCols>>startRow>>startCol>>endRow>>endCol; vector <string> rows(numCols,"."); vector< vector<string> > grid(numRows,rows); locations>>possRow>>possCol>>symbol>>id; while(!locations.fail()) { if(possRow>numRows || possCol>numCols) { cout<<id<< " out of bounds-ignoring"<<endl; } else { replace(grid.at(possRow).front(),grid.at(possRow).back(),".",symbol.c_str()); } locations>>possRow>>possCol>>symbol>>id; } } A: As pointed by Chris, the parameters you passed in std::replace are not the correct ones. std::replace expects iterators for its first two parameters but you are passing references. You can use begin() and end() to get the iterators: std::replace(grid.at(possRow).begin(), grid.at(possRow).end(), ".", symbol.c_str());
{ "language": "en", "url": "https://stackoverflow.com/questions/19748326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Soap Request as String convert it into java object I'm getting a SOAP request as string, from which I want to extract a Java object. Is it possible? If yes, then how? What API can be used for this? A: I'm getting a SOAP request as string, from which I want to extract a Java object. Is it possible? Yes. If yes, then how? You need to convert the String into something that JAXB can unmarshal. Examples include a StringReader or XMLStreamReader. What API can be used for this? Since a SOAP message contains more information than what corresponds to the domain model I would recommend using JAXB with a StAX XMLStreamReader. You use StAX to parser the String. Then you advance the XMLStreamReader to the element that contains the content you wish to unmarshal. Then you unmarshal the XMLStreamReader at that point. * *http://blog.bdoughan.com/2012/08/handle-middle-of-xml-document-with-jaxb.html
{ "language": "en", "url": "https://stackoverflow.com/questions/20471093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: PostgreSQL using constants in foreign key The syntax for Foreign Key, as described in official documentation, includes set of column from table A referencing set of column from table B. Is it possible to use Constant in foreign key declaration? The problem is, I have table DICTIONARIES which contains all dictionary values, discriminated by TYPE. I know it's not good design, but unfortunatelly, I have not much to say, as the DB admin wants to 'minimize the number of tables'... Is it possible to achieve something like that: CREATE TABLE PERSON ( id integer primary key, country_id integer, ... FOREIGN KEY ('COUNTRY', country_id) REFERENCES DICTIONARIES(TYPE, ID) ) It would effectively solve the issue. I'm aware I can add column to the table person, which will has only one possible value 'COUNTRY', or I could write a trigger, but I'd prefer to avoid that to keep design cleaner. A: A foreign key constraint is from one table's columns to another's columns, so, no. Of course the database should have a table COUNTRY(country_id). Commenters have pointed out that your admin is imposing an anti-pattern. Good, you are aware that you can define a column and set it to the value you want and make the foreign key on that. That is an idiom used for avoiding triggers in constraining some subtyping schemes. You may be able to compute a 'COUNTRY' column depending on your DBMS, at least. Your question is essentially this one, see the end of the question & the comments & answers. (Lots of functionality would be trivial to implement. Perhaps the difficulty (besides ignorance of consumers) is that arbitrary constraints become quickly expensive computationally. That might just get vendors aggravation. Also, optimization in SQL is impeded by its differences from the relatonal model.) A: For Posrgres not having computed (or constant) columns, you can force them to a fixed value column, using DEFAULT plus (maybe) a check. This may be ugly, but it works: CREATE TABLE dictionaries ( id integer primary key , typename varchar NOT NULL CHECK ( typename IN ('person' ,'animal' ,'plant' )) , content varchar NOT NULL -- ... , UNIQUE (typename, id) , UNIQUE (typename, content) ); CREATE TABLE person ( id integer primary key , typename varchar NOT NULL DEFAULT 'person' CHECK( typename IN ('person' )) , species_id integer -- ... , FOREIGN KEY (typename, species_id) REFERENCES dictionaries(typename, id) -- DEFERRABLE INITIALLY DEFERRED ); INSERT INTO dictionaries( id, typename, content) VALUES ( 1 , 'person' , 'Bob') ,( 2 , 'person' , 'Alice') ,( 11 , 'animal' , 'monkey') ,( 12 , 'animal' , 'cat') ,( 13 , 'animal' , 'dog') ,( 21 , 'plant' , 'cabbage') ; SELECT * FROM dictionaries; -- this should succeed INSERT INTO person( id, species_id) VALUES ( 1,1 ) ,( 2,2 ) ; -- this should fail INSERT INTO person( id, species_id) VALUES ( 3,11 ) ,( 4,12 ) ;
{ "language": "en", "url": "https://stackoverflow.com/questions/24550698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: CocoaPodspec unresolved identifier error I am trying to create my own framework by CocoaPodspec. I need some help to resolve the issue. And I got an error after run command pod lib lint --no-clean --verbose interminal : error: use of unresolved identifier 'GlobalLoaderView' This is Podspec file content : Pod::Spec.new do |s| s.platform = :ios s.ios.deployment_target = '11.0' s.name = "HalBase" s.swift_version = '4.0' s.summary = "This is example" s.requires_arc = true s.version = "1.0" s.license = { :type => "MIT", :file => "LICENSE" } s.author = { "ntancnit@gmail.com" => "ntancnit@gmail.com" } s.homepage = "https://github.com/ntancnit/HalBase" s.source = { :git => "https://github.com/ntancnit/HalBase.git", :tag => "#{s.version}"} s.ios.framework = "UIKit" s.ios.framework = "CoreLocation" s.ios.framework = "Foundation" s.dependency 'RxSwift', '~> 4.0.0' s.dependency 'RxCocoa', '~> 4.0.0' s.dependency 'RxDataSources', '~> 3.0' s.dependency 'Action' s.dependency 'Alamofire', '~> 4.0' s.dependency 'AlamofireImage', '~> 3.0' s.dependency 'ObjectMapper', '~> 3.0' s.dependency 'IQKeyboardManagerSwift', '~> 5.0.0' s.dependency 'SVProgressHUD' s.dependency 'PureLayout' s.dependency 'KeychainAccess' s.source_files = "HalBase/**/*.{swift,h,m}" s.resources = "HalBase/**/*.{png,jpeg,jpg,storyboard,xib,plist,swift}" end GlobalLoaderView is my custome class inhered from UIControl. I am using swift 4, Xcode 9.4 Thank you!
{ "language": "en", "url": "https://stackoverflow.com/questions/50873362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to take screen shot of a web page in PHP and show it in model popup and submit it into database function screenshot(){ html2canvas(document.body).then(function(canvas) { //document.body.appendChild(canvas); // Get base64URL var base64URL = canvas.toDataURL('').replace( 'image/octet-stream'); // AJAX request $.ajax({ url: 'screen_shot.php', type: 'post', data: {image: base64URL}, success: function(data){ alert('Upload successfully'); } }); }); } A: 1) You can use HTML5 & javaScript to take screenshots. This will work for sure. check more details here (function (exports) { function urlsToAbsolute(nodeList) { if (!nodeList.length) { return []; } var attrName = 'href'; if (nodeList[0].__proto__ === HTMLImageElement.prototype || nodeList[0].__proto__ === HTMLScriptElement.prototype) { attrName = 'src'; } nodeList = [].map.call(nodeList, function (el, i) { var attr = el.getAttribute(attrName); if (!attr) { return; } var absURL = /^(https?|data):/i.test(attr); if (absURL) { return el; } else { return el; } }); return nodeList; } function screenshotPage() { urlsToAbsolute(document.images); urlsToAbsolute(document.querySelectorAll("link[rel='stylesheet']")); var screenshot = document.documentElement.cloneNode(true); var b = document.createElement('base'); b.href = document.location.protocol + '//' + location.host; var head = screenshot.querySelector('head'); head.insertBefore(b, head.firstChild); screenshot.style.pointerEvents = 'none'; screenshot.style.overflow = 'hidden'; screenshot.style.webkitUserSelect = 'none'; screenshot.style.mozUserSelect = 'none'; screenshot.style.msUserSelect = 'none'; screenshot.style.oUserSelect = 'none'; screenshot.style.userSelect = 'none'; screenshot.dataset.scrollX = window.scrollX; screenshot.dataset.scrollY = window.scrollY; var script = document.createElement('script'); script.textContent = '(' + addOnPageLoad_.toString() + ')();'; screenshot.querySelector('body').appendChild(script); var blob = new Blob([screenshot.outerHTML], { type: 'text/html' }); return blob; } function addOnPageLoad_() { window.addEventListener('DOMContentLoaded', function (e) { var scrollX = document.documentElement.dataset.scrollX || 0; var scrollY = document.documentElement.dataset.scrollY || 0; window.scrollTo(scrollX, scrollY); }); } function generate() { window.URL = window.URL || window.webkitURL; window.open(window.URL.createObjectURL(screenshotPage())); } exports.screenshotPage = screenshotPage; exports.generate = generate; })(window); 2) You can also use html2canvas below is the simple example of how to implement. JS html2canvas(document.querySelector("#capture")).then(canvas => { document.body.appendChild(canvas) }); HTML <div id="capture" style="padding: 10px; background: #f5da55"> <h4 style="color: #000; ">Hello world!</h4> </div> download & include in the head section //* <script src="Scripts/jquer_latest_2.11_.min.js" type="text/javascript"></script> <script src="Scripts/html2canvas.js" type="text/javascript"></script> //*
{ "language": "en", "url": "https://stackoverflow.com/questions/57160178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Differences between query using LINQ and IQueryable interface directly? Using Entity Framework 4, and given: ObjectSet<Thing> AllThings = Context.CreateObjectSet<Thing>; public IQueryable<Thing> ByNameA(String name) { IQueryable<Thing> query = from o in AllThings where o.Name == name select o; return query; } public IQueryable<Thing> ByNameB(String name) { return AllThings.Where((o) => o.Name == name); } Both return IQueryable<> instances, and thus the query doesn't hit the server until something like ToList() is called, right? Is it purely readability that is the difference, or are the using fundamentally different technologies on the back-end? A: These compile to nearly identical code. The first syntax translates directly, by the compiler, into methods with the names provided in the second syntax. The main difference between these two methods is really just that you're using a different syntax, and that you're assigning to a temporary variable (query) instead of just returning the result directly. However, they are, for all practical purposes, identical.
{ "language": "en", "url": "https://stackoverflow.com/questions/4572460", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Filling content from bottom and right to left order Inside my page I have div which I want to populate with some content like it's on image. How can I do this without shrinking div content and populate inside div from bottom to up? A: Best approach for this layout would be the Flexbox Technique You can wrap the rows in the reverse order using wrap-reverse $(document).ready(function() { $('.create').on('click', function() { $('.container').append('<div class="circle"></div>'); }) }); .container { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; background: #6CC4DA; -webkit-flex-wrap: wrap-reverse; -ms-flex-wrap: wrap-reverse; flex-wrap: wrap-reverse; align-items: baseline; align-content: flex-start; height: 280px; width: 770px; } .circle { background: #C78DEF; border-radius: 50%; width: 60px; height: 60px; margin: 5px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div class="circle"></div> <div class="circle"></div> <div class="circle"></div> <div class="circle"></div> <div class="circle"></div> <div class="circle"></div> <div class="circle"></div> <div class="circle"></div> <div class="circle"></div> <div class="circle"></div> </div> <button class="create">Create a circle</button> JSfiddle A: You can flip horizontal parent div and flip horizontal back each child block: $(document).ready(function() { $(document).on('click', 'button', function() { var items = $('.content-item').size(), space = document.createTextNode(' '); $('.container').append($('<div class="content-item">' + (items + 1) + '</div>')).append(space); }); }); .container { width: 400px; height: 200px; background: cyan; transform: ScaleY(-1); } .content-item { display: inline-block; width: 50px; height: 50px; border-radius: 50%; margin: 5px; text-align: center; line-height: 50px; background: purple; color: #fff; transform: ScaleY(-1); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>Increase population</button> <div class="container"> <div class="content-item">1</div> <div class="content-item">2</div> <div class="content-item">3</div> <div class="content-item">4</div> <div class="content-item">5</div> <div class="content-item">6</div> <div class="content-item">7</div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/30934560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: meteorjs -- Problems with the accounts-twitch package & OAuth2 Today, I started a new project (IRC Bot, etc.) to be used with Twitch.TV's chat servers. I wanted to use the accounts-twitch package that I found on Atmosphere, and had to manually install it (editing the package.js file) due to a deprecated dependency on accounts-oauth2-helper. After getting it to properly install, my app crashes on startup now. It tosses the following error before dying, and I don't know how to fix it: [[[[[ ~/projects/wasdbot ]]]]] => Started MongoDB. => Starting your app... W20140605-15:22:42.283(-4)? (STDERR) W20140605-15:22:42.350(-4)? (STDERR) /home/misutowolf/.meteor/tools/5bf1690853/lib/node_modules/fibers/future.js:173 W20140605-15:22:42.350(-4)? (STDERR) throw(ex); W20140605-15:22:42.350(-4)? (STDERR) ^ W20140605-15:22:42.351(-4)? (STDERR) TypeError: Cannot call method 'registerService' of undefined W20140605-15:22:42.351(-4)? (STDERR) at Package (packages/accounts-twitch/twitch_server.js:2) W20140605-15:22:42.351(-4)? (STDERR) at Package (packages/accounts-twitch/twitch_server.js:82) W20140605-15:22:42.351(-4)? (STDERR) at packages/accounts-twitch.js:123:4 W20140605-15:22:42.351(-4)? (STDERR) at packages/accounts-twitch.js:130:3 W20140605-15:22:42.352(-4)? (STDERR) at /home/misutowolf/projects/wasdbot/.meteor/local/build/programs/server/boot.js:155:10 W20140605-15:22:42.352(-4)? (STDERR) at Array.forEach (native) W20140605-15:22:42.352(-4)? (STDERR) at Function._.each._.forEach (/home/misutowolf/.meteor/tools/5bf1690853/lib/node_modules/underscore/underscore.js:79:11) W20140605-15:22:42.352(-4)? (STDERR) at /home/misutowolf/projects/wasdbot/.meteor/local/build/programs/server/boot.js:82:5 => Exited with code: 8 W20140605-15:22:43.456(-4)? (STDERR) W20140605-15:22:43.457(-4)? (STDERR) /home/misutowolf/.meteor/tools/5bf1690853/lib/node_modules/fibers/future.js:173 W20140605-15:22:43.457(-4)? (STDERR) throw(ex); W20140605-15:22:43.458(-4)? (STDERR) ^ W20140605-15:22:43.463(-4)? (STDERR) TypeError: Cannot call method 'registerService' of undefined W20140605-15:22:43.463(-4)? (STDERR) at Package (packages/accounts-twitch/twitch_server.js:2) W20140605-15:22:43.464(-4)? (STDERR) at Package (packages/accounts-twitch/twitch_server.js:82) W20140605-15:22:43.464(-4)? (STDERR) at packages/accounts-twitch.js:123:4 W20140605-15:22:43.464(-4)? (STDERR) at packages/accounts-twitch.js:130:3 W20140605-15:22:43.465(-4)? (STDERR) at /home/misutowolf/projects/wasdbot/.meteor/local/build/programs/server/boot.js:155:10 W20140605-15:22:43.465(-4)? (STDERR) at Array.forEach (native) W20140605-15:22:43.465(-4)? (STDERR) at Function._.each._.forEach (/home/misutowolf/.meteor/tools/5bf1690853/lib/node_modules/underscore/underscore.js:79:11) W20140605-15:22:43.466(-4)? (STDERR) at /home/misutowolf/projects/wasdbot/.meteor/local/build/programs/server/boot.js:82:5 => Exited with code: 8 W20140605-15:22:44.622(-4)? (STDERR) W20140605-15:22:44.624(-4)? (STDERR) /home/misutowolf/.meteor/tools/5bf1690853/lib/node_modules/fibers/future.js:173 W20140605-15:22:44.625(-4)? (STDERR) throw(ex); W20140605-15:22:44.625(-4)? (STDERR) ^ W20140605-15:22:44.628(-4)? (STDERR) TypeError: Cannot call method 'registerService' of undefined W20140605-15:22:44.629(-4)? (STDERR) at Package (packages/accounts-twitch/twitch_server.js:2) W20140605-15:22:44.629(-4)? (STDERR) at Package (packages/accounts-twitch/twitch_server.js:82) W20140605-15:22:44.630(-4)? (STDERR) at packages/accounts-twitch.js:123:4 W20140605-15:22:44.630(-4)? (STDERR) at packages/accounts-twitch.js:130:3 W20140605-15:22:44.630(-4)? (STDERR) at /home/misutowolf/projects/wasdbot/.meteor/local/build/programs/server/boot.js:155:10 W20140605-15:22:44.631(-4)? (STDERR) at Array.forEach (native) W20140605-15:22:44.631(-4)? (STDERR) at Function._.each._.forEach (/home/misutowolf/.meteor/tools/5bf1690853/lib/node_modules/underscore/underscore.js:79:11) W20140605-15:22:44.631(-4)? (STDERR) at /home/misutowolf/projects/wasdbot/.meteor/local/build/programs/server/boot.js:82:5 => Exited with code: 8 => Your application is crashing. Waiting for file change. Seems like the problem is this call to Accounts.oauth.registerService, in twitch_server.js, but I don't really know how to go about fixing it. I also can't seem to find anything about this oauth stuff in their API docs, anywhere, or maybe I'm looking in the wrong place, or maybe I'm missing a package that I should have included? All I added to my project is accounts-twitch, accounts-ui, and coffeescript, as of right now. I haven't written any code yet, just trying to fire up Meteor. Any help would be amazing. I really appreciate everyone's time beforehand.
{ "language": "en", "url": "https://stackoverflow.com/questions/24068671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Mule ESB + RabbitMQ reliability and up-time: how to re-create a deleted exchange automatically at runtime I've got a Large mule application that receives on multiple queues and publishes to at least one exchange. I'm manually QA'ing the application by deleting the queues and exchanges to see if mule will retry to connect (and also shut down rabbit altogether) This question is for when an exchange is deleted. The messages go into a locked anonymous queue named something like: amq.gen-gFs6-7sP2nw1ntgobO6cBg I'm looking for a way to reconnect the exchange and still pass through the messages. Is this even possible? I've set options like exchangeDurable="true" queueDurable="true" Is there any other things (or rabbit configs) that I need to do or would be beneficial to me? Next Test: Shutdown RabbitMQ in the middle of processing. Code: <mule xmlns:jdbc-ee="http://www.mulesoft.org/schema/mule/ee/jdbc" xmlns:vm="http://www.mulesoft.org/schema/mule/vm" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:amqp="http://www.mulesoft.org/schema/mule/amqp" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:spring="http://www.springframework.org/schema/beans" version="EE-3.4.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mulexml="http://www.mulesoft.org/schema/mule/xml" xmlns:file="http://www.mulesoft.org/schema/mule/file" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/ee/jdbc http://www.mulesoft.org/schema/mule/ee/jdbc/current/mule-jdbc-ee.xsd http://www.mulesoft.org/schema/mule/xml http://www.mulesoft.org/schema/mule/xml/current/mule-xml.xsd http://www.mulesoft.org/schema/mule/vm http://www.mulesoft.org/schema/mule/vm/current/mule-vm.xsd http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd http://www.mulesoft.org/schema/mule/amqp http://www.mulesoft.org/schema/mule/amqp/current/mule-amqp.xsd http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd" xmlns:context="http://www.springframework.org/schema/context"> <amqp:connector name="amqpAutoAckLocalhostConnector" host="${config.status_reporting.host}" port="${config.status_reporting.port}" virtualHost="${config.status_reporting.virtual_host}" username="${config.status_reporting.username}" password="${config.status_reporting.password}" requestedHeartbeat="${config.status_reporting.requestedHeartbeat}" doc:name="AMQP Connector for Status Messages"/> <flow name="send_status" doc:name="send_status"> <vm:inbound-endpoint path="send_status" exchange-pattern="one-way" responseTimeout="10000" doc:name="VM" /> <logger message="starting send status" level="DEBUG" doc:name="Logger"/> <!-- some code here has been removed for stackoverflow question --> <flow-ref name="cwm_send" doc:name="flow ref"/> </flow> <flow name="cwm_send" doc:name="cwm_send"> <amqp:outbound-endpoint exchangeName="${config.status_reporting.exchange_name}" exchangeType="topic" exchangeDurable="${config.status_reporting.exchange_is_durable}" routingKey="${config.status_reporting.routing_key}" connector-ref="amqpAutoAckLocalhostConnector" doc:name="AMQP Out" queueDurable="true" responseTimeout="10000"/> </flow> <flow name="send_ingest_status" doc:name="send_ingest_status"> <vm:inbound-endpoint exchange-pattern="request-response" responseTimeout="10000" doc:name="VM" path="send_ingest_status"/> <vm:outbound-endpoint path="send_status" exchange-pattern="one-way" doc:name="Send Status"> <set-payload value="#[[ 'status_code': 'foo', 'status_descr': 'test description.', 'status_final': '0', 'version': '1.0']]"/> </vm:outbound-endpoint> </flow> </mule> Thank you. A: This problem also seems to occur when an exchange is declared only in an outbound endpoint. There is an open bug concerning this in the Mulesoft JIRA, and you can vote for it to help them prioritize it. I took a look at the source code, and the problem seems to be that there is simply no code to declare exchanges when an outbound endpoint is started. In your case, you'd probably want the code to run at the time the message is sent, or maybe at the time the exchange is deleted. This timing wouldn't be covered by the aforementioned bug, but you might open a new issue describing the use case and the desired functionality. And a pull request would probably be even better! ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/33833420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Show ajaxloader on the time of $.getJson call i want to show ajaxloader icon on the time of executing $.getJSON. it should disappear after $.getJSON completes. $.getJSON("url", function(data){ ........ ........ }); A: Try this pattern: $("#someAnimatedGif").show(); $.getJSON("url", function (data) { $("#someAnimatedGif").hide(); }); The animated gif will initially be hidden, and you can use JQuery to hide/show it. The key is to show it right before you execute the Ajax call, and hide it again when the callback returns.
{ "language": "en", "url": "https://stackoverflow.com/questions/18502993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Servlets and synchronization Servlets runs in several threads, so my question is: If I have a lot of servlets which call some utility class (DbUtils, for example Connection c = DbUtils.getConnection(); //....some action with db here should I assume additional actions for synchronization inside DbUtils? Actually I'd like to inherit HttpServlet into something like DatabaseInvokerServlet: public abstract class DatabaseInvokerServlet extends HttpServlet with methods: public abstract void getResultSets(Connection connection) throws SQLException; private AbstractUser currentUser; private HttpServletRequest request; private HttpServletResponse response; protected void processData() {} protected void afterRequestProcessed() throws ServletException, IOException {} protected void beforeRequestProcessed() throws ServletException, IOException {} protected void execute() { Connection c = null; try { c = DbUtils.getConnection(); getResultSets(c); processData(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (c != null) { c.close(); } } catch (SQLException e) { e.printStackTrace(); } } } public HttpServletRequest getRequest() { return request; } public HttpServletResponse getResponse() { return response; } public AbstractUser getCurrentUser() { return currentUser; } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); this.request = request; this.response = response; this.currentUser = (AbstractUser) request.getSession().getAttribute("currentUser"); } Then I'd just inherit my DatabaseInvokerServlet to new servlets to do custom stuff. The reason is not to copy-paste database invoke block with try-catch-finally in a lot of places. But as I can see such approach won't work because of synchronization issues. Am I right? A: If the DbUtils creates the connection in the same thread, like as: public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, username, password); } Then it's threadsafe. But if the connection is a class variable, like as: private static Connection connection = DriverManager.getConnection(url, username, password); public static Connection getConnection() throws SQLException { return connection; } Then it is definitely not threadsafe because the same connection will be shared among all threads. Also when it's closed in a thread, all subsequent threads won't be able to use the connection because it's not open anymore. Also when it's never closed, the DB will timeout the connection sooner or later, usually after a few hours, and your application won't work anymore because the connection is not open anymore. As to the servlet, public abstract class DatabaseInvokerServlet extends HttpServlet { private AbstractUser currentUser; private HttpServletRequest request; private HttpServletResponse response; // ... } it's definitely not threadsafe. You're assigning the current user, request and response as instance variables. From each servlet class, there is only one instance during the application's lifetime. This instance is shared among all visitors/sessions throughout the entire application's lifetime. Each HTTP request operates in a separate thread and uses the same instance. Imagine two simultaneous visitors: visitor A will set the current user, request and response. The DB process however takes a long time. Before the response of visitor A has returned, visitor B calls the same servlet and thus the current user, request and response will be overriden. Then, the query of visitor A finishes and wants to write to the response, it is instead writing to the response of visitor B! Visitor B sees the result of the query of visitor A and visitor A sees nothing on his screen! You should never assign request/session-specific data as instance variable of the servlet. You should keep them method (thread) local. public abstract class DatabaseInvokerServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { AbstractUser currentUser = request.getSession().getAttribute("user"); // Keep the variables in the method block! // Do not assign them as instance variable! } } As to the complete picture, this approach is clumsy. The database access layer should have nothing to do with servlets. It should operate in its own standalone classes which you could just construct/invoke in every other Java class, any servlet class, or a normal application with main(), or whatever. You should not have any single line of java.sql.* imports in your servlet classes (expect of maybe SQLException if it is not abstracted away). You should not have any single line of javax.servlet.* imports in your database classes. See also: * *Servlet instantiation and (session) variables *Basic DAO tutorial A: If the utility class has state (example: class or instance variables) most probably yes. A: If I guess right the DBUtils is returning new instance for each call of getConnection(). And as the DBUtils class is a utility class so it shouldn't be maintaining any state. In this scenario no you dont need any addition efforts for synchronization. A: Servlets runs in several threads. The J2EE spec says there is only one instance per servlet class running in one web container for non single thread servlet. Servlet 2.3 specs A servlet container may send concurrent requests through the service method of the servlet. To handle the requests the developer of the servlet must make adequate provisions for concurrent processing with multiple threads in the service method. Synchronisation in servlet. Never have an member variable in a servlet, it is not thread safe.
{ "language": "en", "url": "https://stackoverflow.com/questions/5348991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: java: NoSuchElementException: Reading to arrayList sorry if my formatting is garbage. I'm trying to add 2 strings and a boolean to an arrayList doing the following. while((in.hasNextLine())){ list.add(new Task(in.next(),in.next(), in.hasNextBoolean())); } I keep getting a no such element exception. If I take the while loop away like so list.add(new Task(in.next(),in.next(), in.hasNextBoolean())); It functions fine but I can only add the first line of the text file. Is there something wrong in the loop or with the Scanner? try { in = new Scanner(f1); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } while((in.hasNextLine())){ list.add(new Task(in.next(),in.next(), in.hasNextBoolean())); } f1 is declared as File f1 = new File ("src/mylist.txt"); Any help would be great! Thanks! A: NoSuchElementException exception is throwed by in.next(), in list.add(new Task(in.next(),in.next(), in.hasNextBoolean())),. and for in.next(), if you don't use any Pattern in Scanner to match the next token. it will use default Pattern private static Pattern FIND_ANY_PATTERN = Pattern.compile("(?s).*") to match whole line. it will cause in.next() will read whole line. so list.add(new Task(in.next(),in.next(), in.hasNextBoolean())) will throw NoSuchElementException, you have read twice but you only check once.
{ "language": "en", "url": "https://stackoverflow.com/questions/36614058", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get node value xml with LINQ c# I can't get the value of this XML node. I need to get the <LimitValue> value and give the user the possibility to change it. I have already tried this solution, but it doesn't work: namefile = Files[select].Name; XDocument document = XDocument.Load(@"C:\Users\lab\Desktop\copy\spectro\" + namefile); Console.WriteLine("Inserisci lelemento chimico da modificare:"); var chimical = Console.ReadLine(); var nodes = (from n in document.Descendants("ControlItems") where n.Element("ControlItem").Attribute("Name").Value == chimical select new { nodeLimitValueLW = (string)n.Element("LimitValue").Attribute("Type") == "LowerWarningLimit", nodeLimitValueUW = (string)n.Element("LimitValue").Attribute("Type") == "UpperWarningLimit", nodeLimitValueLA = (string)n.Element("LimitValue").Attribute("Type") == "LowerAcceptanceLimit", nodeLimitValueUA = (string)n.Element("LimitValue").Attribute("Type") == "UpperAcceptanceLimit" }).ToList(); foreach (var n in nodes) { Console.WriteLine(n.nodeLimitValueLW); Console.WriteLine(n.nodeLimitValueUW); Console.WriteLine(n.nodeLimitValueLA); Console.WriteLine(n.nodeLimitValueUA); } This is my XML: <GradeLimits GradeName="1.5217" GradeDescription="20MnV6" Norm="TXC03" BaseElement="Fe"> <ControlItems> <ControlItem Name="C" DisplayUnit="%"> <LimitValue Type="LowerWarningLimit" Kind="Absolute" Unit="%">0.15999999642372131</LimitValue> <LimitValue Type="UpperWarningLimit" Kind="Absolute" Unit="%">0.2199999988079071</LimitValue> <LimitValue Type="LowerAcceptanceLimit" Kind="Absolute" Unit="%">0.15000000596046448</LimitValue> <LimitValue Type="UpperAcceptanceLimit" Kind="Absolute" Unit="%">0.23000000417232513</LimitValue> </ControlItem> <ControlItem Name="Si" DisplayUnit="%"> <LimitValue Type="LowerWarningLimit" Kind="Absolute" Unit="%">0.10000000149011612</LimitValue> <LimitValue Type="UpperWarningLimit" Kind="Absolute" Unit="%">0.5</LimitValue> <LimitValue Type="LowerAcceptanceLimit" Kind="Absolute" Unit="%">0.090000003576278687</LimitValue> <LimitValue Type="UpperAcceptanceLimit" Kind="Absolute" Unit="%">0.51999998092651367</LimitValue> </ControlItem> <ControlItem Name="Pb" DisplayUnit="%"> <LimitValue Type="UpperWarningLimit" Kind="Absolute" Unit="%">0.05000000074505806</LimitValue> <LimitValue Type="UpperAcceptanceLimit" Kind="Absolute" Unit="%">0.05000000074505806</LimitValue> </ControlItem> </ControlItems> </GradeLimits> For example: The user wants to edit the <LimitValue> of the <ControlItem> with the attribute Name="Si" They would type in the console "Si", and I would need to iterate on all <ControlItem>, until I find the <ControlItem> with the attribute Name="Si". I would then need to take all the <LimitValue> and give the possibility to edit it. I hope I have explained it well. Thanks in advance for the help. A: Does not fully use Linq, but works for what you need. public class Limits { public string LowerWarningLimit = ""; public string UpperWarningLimit = ""; public string LowerAcceptanceLimit = ""; public string UpperAcceptanceLimit = ""; } public static void GetLimits(string nameFile) { XDocument document = XDocument.Load(nameFile); if (document == null) { Console.WriteLine("Document not found."); return; } XElement root = document.Descendants("ControlItems").FirstOrDefault(); if (root == null) { Console.WriteLine("Could not find ControlItems."); return; } Console.WriteLine("Inserisci lelemento chimico da modificare:"); var chimical = Console.ReadLine(); XElement nameSearch = root.Descendants("ControlItem").FirstOrDefault(x => x.Attribute("Name") != null && x.Attribute("Name").Value.ToLower() == chimical.ToLower()); if (nameSearch == null) { Console.WriteLine("Name not found."); return; } Limits limits = new Limits(); foreach (XElement elements in nameSearch.Descendants()) { string typeResult = elements.Attribute("Type").Value; if (typeResult == null) { continue; } switch (typeResult) { case "LowerWarningLimit": limits.LowerWarningLimit = elements.Value; break; case "UpperWarningLimit": limits.UpperWarningLimit = elements.Value; break; case "LowerAcceptanceLimit": limits.LowerAcceptanceLimit = elements.Value; break; case "UpperAcceptanceLimit": limits.UpperAcceptanceLimit = elements.Value; break; } } Console.WriteLine(limits.LowerWarningLimit); Console.WriteLine(limits.UpperWarningLimit); Console.WriteLine(limits.LowerAcceptanceLimit); Console.WriteLine(limits.UpperAcceptanceLimit); } A: static void Main(string[] args) { string xmlFilePath = @"C:\Users\vincenzo.lanera\Desktop\test.xml"; XmlDocument document = new XmlDocument(); document.Load(xmlFilePath); Console.WriteLine("Inserisci l'elemento chimico da modificare:"); var chimical = Console.ReadLine(); //Searches the limit values of the selected element XmlNodeList limitValues = document.SelectNodes($"//ControlItem[@Name='{chimical}']/LimitValue"); //Prints all limit values Console.WriteLine($"Limit values of {chimical}:"); foreach (XmlNode limVal in limitValues) { Console.WriteLine($"{limVal.Attributes["Type"].Value} {limVal.InnerText}"); }; //Ask the user wich limit value wants to edit Console.WriteLine("Inserisci il limit value da modificare:"); var limitValueToEdit = Console.ReadLine(); //Ask the user the new value Console.WriteLine("Inserisci il nuovo valore:"); var newVal = Console.ReadLine(); //Edit the limit value var nodeToEdit = document.SelectSingleNode($"//ControlItem[@Name='{chimical}']/LimitValue[@Type='{limitValueToEdit}']"); nodeToEdit.InnerText = newVal; //Save the changes to the xml file document.Save(xmlFilePath); } } You should also handle the errors if the user inserts an invalid text.
{ "language": "en", "url": "https://stackoverflow.com/questions/57203387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What PHP/Shell Framework can be used to access HTTP-POST/-GET Forms (besides curl)? I'm searching an abstraction layer from pure HTTP-POST/-GET using curl. It should somehow make it easy to define the Targeted script and it's variables. I read something exists in the FreeX (german unix/programming magazine), but don't have the named magazine at hand. What can I do? Stick with curl? What alternatives do exist? Thank you in advance :) A: As you tagged you question with "perl", you can use Perl. Try LWP - popular module, and much more convenient than curl. For more complex tasks, try WWW::Mechanize. A: You might want to look at the HTTP Extension. It looks like a pretty complete abstraction implemented over curl. A: If you want something more sophisticated, there is the Zend_Http_Client ZF Component. A: You can use Streams to POST also. I generally prefer that over an extension or even cURL since it's core PHP and more likely to be there. Though, I build open source software that gets installed on machines where the user has low privileges and likely zero control. Your users' options may be different.
{ "language": "en", "url": "https://stackoverflow.com/questions/3166900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to dynamically add Proto Members in Protobuf-net Long time ago as @Marc stated in one of the threads that protobuf-net has no support for dynamic. Is that statement still valid? If not then can someone share an example how we can dynamically add the members in Protobuf-net. A: That is still correct. protobuf-net supports unexpected data via the IExtensible / Extensible API, but this is to support a different scenario. There is currently no support for having the DTO types themselves as dynamic. To do so would require significant work: that isn't a problem if there is a genuine problem to address (for example, the meta-programming re-work to allow for full pre-compilation, to support mobile / metro was significant work - but still happened). But in the case of dynamic it is not obvious to me what scenario this would usefully target.
{ "language": "en", "url": "https://stackoverflow.com/questions/18968625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Calculating Averages and Determining Lowest and Highest Values I have split up a list with names and corresponding scores and have stored them in a dictionary called students. But with these scores, I have been asked to figure out the average score, minimum score and maximum score. I am a beginner and a student so a step by step explanation would be greatly appreciated. def getStatistics(students): # Initialize properly the values of the average score, minimum score, and maximum score. average = 0 lowest = True highest = True scoreTotal = 0 The reason why the variables above were labeled that way is because in my main function, which calls on this function, had a built in call with those names. But whenever I go to run the program, it doesn't print any of it. # loop through the dictionary, and # calculate the average score, the highest score and the lowest score # of the students in the dictionary. i = 0 for grade in students: scoreTotal += grade[i] i = i + 1 average = scoreTotal/i lowest = min(grade[i]) highest = max(grade[i]) # The function must return back the average, highest and lowest score. return average, highest, lowest In the main function it had this: (the "nameToMarksMap" is the function from the previous part with the dictionary students) average, highest, lowest = getStatistics(nameToMarksMap) print "Average:", average, "Highest:", highest, "Lowest:", lowest Nothing is being printed, can anyone explain why? I keep getting errors. A: finish the function with def getStatistics(students) ... # snip ... return average, highest, lowest
{ "language": "en", "url": "https://stackoverflow.com/questions/22441696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WebLogic 12.1.2 bad record MAC on HTTPS I'm trying to use WebLogic with HTTPS default keystore for development and I get the following error when I try to connect to the server via web browser: ExecuteThread: '0' for queue: 'weblogic.socket.Muxer', fatal: engine already closed. Rethrowing javax.net.ssl.SSLException: bad record MAC <13-nov-2014 11H48' COT> <Debug> <SecuritySSL> <BEA-000000> <[Thread[ExecuteThread: '0' for queue: 'weblogic.socket.Muxer',5,Thread Group fo r Queue: 'weblogic.socket.Muxer']]weblogic.security.SSL.jsseadapter: SSLENGINE: Exception occurred during SSLEngine.unwrap(ByteBuffer,ByteBu ffer[]). javax.net.ssl.SSLException: bad record MAC at sun.security.ssl.Alerts.getSSLException(Alerts.java:208) at sun.security.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1605) at sun.security.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1573) at sun.security.ssl.SSLEngineImpl.readRecord(SSLEngineImpl.java:971) at sun.security.ssl.SSLEngineImpl.readNetRecord(SSLEngineImpl.java:876) at sun.security.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:750) at javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:664) at weblogic.security.SSL.jsseadapter.JaSSLEngine$5.run(JaSSLEngine.java:134) at weblogic.security.SSL.jsseadapter.JaSSLEngine.doAction(JaSSLEngine.java:732) at weblogic.security.SSL.jsseadapter.JaSSLEngine.unwrap(JaSSLEngine.java:132) at weblogic.socket.JSSEFilterImpl.unwrap(JSSEFilterImpl.java:603) at weblogic.socket.JSSEFilterImpl.unwrapAndHandleResults(JSSEFilterImpl.java:507) at weblogic.socket.JSSEFilterImpl.unwrapAndHandleResults(JSSEFilterImpl.java:474) at weblogic.socket.JSSEFilterImpl.isMessageComplete(JSSEFilterImpl.java:313) at weblogic.socket.SocketMuxer.readReadySocketOnce(SocketMuxer.java:991) at weblogic.socket.SocketMuxer.readReadySocket(SocketMuxer.java:928) at weblogic.socket.NIOSocketMuxer.process(NIOSocketMuxer.java:507) at weblogic.socket.NIOSocketMuxer.processSockets(NIOSocketMuxer.java:473) at weblogic.socket.SocketReaderRequest.run(SocketReaderRequest.java:30) at weblogic.socket.SocketReaderRequest.execute(SocketReaderRequest.java:43) at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:147) at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:119) > I found some links about this, but nothing important. Is there any solution for this? A: Remove the WebLogic Domain data folder and setup it again. This time I restart the WebLogic server domain after the WebLogic Domain data folder setup and enable the SSL after. Next open the browser with the https address and it work.
{ "language": "en", "url": "https://stackoverflow.com/questions/26914682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pointer of QVector pointer This is my class constructor: UndoRedo::UndoRedo(QList<vector_t*> v, QUndoCommand *parent) : QUndoCommand(parent) { ... QStringList *sl = &v[0][0]; ... } Where vector_t is typedef QVector<QStringList> vector_t ; Whwn I try to set "sl" in this way, the IDE raises this error: no match for ‘operator*’ (operand type is ‘QList<QVector<QStringList>*>’) Where I’m doing wrong? Can you help me? A: The biggest problem I see in your questions is that you seem to be severly overcomplicating simple things. First and foremost, Qt's containers are implicitly shared. Thus taking their copies is cheap if said copies are not modified. Thus you can freely pass the outermost container by reference, and have it take the innards by value. It'd be reasonably cheap, for example, to simply pass QList<vector_t> to your method. It would involve no copying of any kind. Even then, it costs a tiny bit less to pass a const reference instead of a value, namely const QList<vector_t> &. Why are you taking the address of v? Let's dissect the type of v: QList<vector_t*> = QList<QVector<QStringList>>*> To access the innermost element you need to: * *Access a list element: v[0] *Dereference the pointer: *exp *Access the vector element: exp[0] By exp I mean the preceding expression, taken as a unit. Thus: QStringList & sl = (*(v[0]))[0]; This is C++, not C, you should use a reference instead of a pointer. If you insist on a pointer: QStringList * sl = *((*(v[0]))[0]); But then you can do silly things like delete sl or free(sl) and it will compile but will result in, maybe, your hard drive getting formatted.
{ "language": "en", "url": "https://stackoverflow.com/questions/24897898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: TypeError on Angular form submit I'm getting the error TypeError: Cannot set property 'songname' of null, when trying to submit an update to a row in firebase. The console error is saying that its happening with the record.songname in the edit function. I'm able to add, but not edit rows. myApp.controller('ProductsCtrl', ['$scope', '$firebaseArray', function($scope, $firebaseArray, $http){ var myProducts = new Firebase('https://url-to-db.firebaseio.com/songs'); $scope.products = $firebaseArray(myProducts); $scope.showForm = function(){ $scope.addFormShow = true; $scope.editFormShow = false; clearForm(); window.scrollTo(0, 0); } $scope.hideForm = function(){ $scope.addFormShow = false; } function clearForm(){ $scope.songname = ''; $scope.artist = ''; $scopt.tags = ''; } $scope.addFormSubmit = function(){ $scope.products.$add({ songname:$scope.songname, artist:$scope.artist, tags:$scope.tags, date:Date.now() }); $('.messages').addClass('alert alert-success').slideDown().show().html('The song has been added').fadeOut(2000); clearForm(); } $scope.dateFormat = 'MM-dd-yy @ HH:mm:ss'; $scope.showProduct = function(product){ $scope.editFormShow = true; $scope.addFormShow = false; $scope.songname = product.songname; $scope.artist = product.artist; $scope.tags = product.tags; $scope.date = product.date; } $scope.editFormSubmit = function(){ var id = $scope.id; var record = $scope.products.$getRecord(id); record.songname = $scope.songname; record.artist = $scope.artist; record.tags = $scope.tags; $scope.products.$save(record); $('.messages').addClass('alert alert-info').slideDown().show().html('The job has been edited').fadeOut(2000); clearForm(); $('.edit-form').toggle(); } }]); A: The $scope.id attribute is probably not getting set. Try setting the id in the scope in your showProduct function or whichever function initializes the $scope variables for the item. $scope.showProduct = function(product){ $scope.id = product.id; ..............
{ "language": "en", "url": "https://stackoverflow.com/questions/44162406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use a Node.js module in CoffeScript in a JavaScript project I have been recommended this Node.js module. It is implemented in CoffeeScript, but I want to use it in my JavaScript project. Of course I will get an error message like this: What do I have to do to use the module in my project?
{ "language": "en", "url": "https://stackoverflow.com/questions/30003964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Assert IsMenu exception when attempting to populate a dynamic menu I'm attempting to populate a "submenu" in my dialog box from an array of strings as shown in this answer. My attempt looks like the following: #define ID_APP0 14000 #define ID_APP1 14001 #define ID_APP2 14002 #define ID_APP3 14003 #define ID_APP4 14004 #define ID_APP5 14005 #define ID_APP6 14006 #define ID_APP7 14007 void SoftwareDlg::DynamicAppMenu() { CMenu MyMainMenu; VERIFY(MyMainMenu.LoadMenu(IDR_MENU1)); CMenu* SomeMenu = MyMainMenu.GetSubMenu(0); if (SomeMenu) { for (auto i = 0; i < 1; i++) { SomeMenu->AppendMenu(MF_STRING, 14000+i, Client::m_vszAppArr[i]); } } } ...but I'm getting an exception from the assert below immediately after(during?) the AppendMenu() function. _AFXWIN_INLINE BOOL CMenu::AppendMenu(UINT nFlags, UINT_PTR nIDNewItem, LPCTSTR lpszNewItem) { ASSERT(::IsMenu(m_hMenu)); return ::AppendMenu(m_hMenu, nFlags, nIDNewItem, lpszNewItem); } I no longer know how to continue debugging this issue because the LoadMenu() function appears to work correctly, and none of the variables are populated where the exception takes place. Am I possibly just calling this in the wrong place? It's happening(conditionally) inside of a scheduled member function of the dialog box... does it need to happen somewhere like OnDraw(), OnPaint(), or something? Edit1: Value of SettingsMenu->m_hMenu Edit2: IDR_MENU1 resource definition: IDR_MENU1 MENU BEGIN POPUP "Tools" BEGIN MENUITEM "New Test F11", ID_TOOLS_NEWTEST MENUITEM "Export Data", ID_TOOLS_EXPORTDATA MENUITEM "Upload Data", ID_TOOLS_UPLOADDATA MENUITEM "Test Control", ID_TOOLS_TESTCONTROL END POPUP "Settings" BEGIN POPUP "USB_PORT" BEGIN MENUITEM "Serial Ports", ID_PORT_SERIALPORTS, INACTIVE MENUITEM "COM1", ID_PORT_COM1 MENUITEM "COM2", ID_PORT_COM2 MENUITEM "COM3", ID_PORT_COM3 MENUITEM "COM4", ID_PORT_COM4 MENUITEM "COM5", ID_PORT_COM5 MENUITEM "COM6", ID_PORT_COM6 MENUITEM "COM7", ID_PORT_COM7 MENUITEM "COM8", ID_PORT_COM8 END MENUITEM "Debug Mode", ID_SETTINGS_DEBUGMODE MENUITEM "Display in OSD", ID_SETTINGS_DISPLAYINOSD MENUITEM "Test Upload Mode", ID_SETTINGS_TESTUPLOADMODE MENUITEM "Preferences", ID_SETTINGS_PREFERENCES POPUP "Target Window" BEGIN MENUITEM "Placeholder", ID_TARGETWINDOW_PLACEHOLDER END END END A: As hinted to by @Vlad Feinstein's comment, CMenu MyMainMenu; should not have been declared inside the function... That fix allowed me to get past the assertion, but the new menu items were still not appearing. I began catching and logging the return values from the creation and deletion functions which lead me to realize that because I already had an existing menu, I needed to use a pointer to that menu(as opposed to creating my own that I then left un-used). My final function ended up looking like this: void SoftwareDlg::DynamicAppMenu(){ CMenu* MainMenu = GetMenu(); CMenu* SettingsMenu = MainMenu->GetSubMenu(1); CMenu* TargetAppMenu = SettingsMenu->GetSubMenu(5); if (TargetAppMenu) { BOOL appended = false; BOOL deleted = false; for (auto i = 0; i < Client::m_vszAppArr.size(); i++) { appended = TargetAppMenu->AppendMenu(MF_STRING, 14000+i, Client::m_vszAppArr[i].c_str()); } deleted = TargetAppMenu->DeleteMenu(ID_TARGETWINDOW_PLACEHOLDER, MF_BYCOMMAND); OutputDebugString(("String appended: " + std::to_string(appended)).c_str()); OutputDebugString(("Placeholder deleted: " + std::to_string(deleted)).c_str()); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/65569414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL datetime compare I want to get some values from my table an there are some conditions about its datetime columns. I want to get all hotel values of a stated city from my table, which is named "LocalHotels". Also I should declare two DateTimevalues. First value should be less than or equal to hotel's value in "start" column, which is datetime data type. Second value should be greater than or equal to hotel's value in "deadline" column, which is datetime data type, either. All datetime values in these two columns are inserted in German CultureInfo format. When I stated query below, there are no problems; string query = "SELECT * FROM LocalHotels WHERE city='LONDON' AND start <='5.12.2015 00:00:00' AND deadline >='8.12.2015 00:00:00' ORDER BY city"; However when I changed day value of DateTime values from one digit to two digits, as I stated in below; string query "SELECT * FROM LocalHotels WHERE city='LONDON' AND start <='15.12.2015 00:00:00' AND deadline >='18.12.2015 00:00:00' ORDER BY city" I got an SQLException which indicates; The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. A: Try changing 15.12.2015 00:00:00 to 2015-12-15 00:00:00 and same format for the other date also. A: You can view SQL Server's date and time format for yourself by running this query: SELECT GETDATE() As you can see the format is YYYY-MM-DD HH:MM:SS.MMM. Stick to this and you won't run into any unexpected conversion errors. EDIT ISO 8601 is a standard date format. From MS Docs: The advantage in using the ISO 8601 format is that it is an international standard with unambiguous specification. Also, this format isn't affected by the SET DATEFORMAT or SET LANGUAGE setting. For this reason I would recommend it above all other formats. Examples: 2020-02-25 20200225 2020-02-25T18:37:00 A: SELECT CONVERT(char(10), GetDate(),126) or select convert(varchar,getDate(),112) or select replace(convert(varchar, getdate(), 111), '/','-') Test out the queries above to get the date in the desired format (replace GetDate() with your date, or dateColumn). As others pointed out you need the format YYYY-MM-DD. A: Even though in Europe and everywhere in the world it makes perfect sense to use the month as the second of three items in the date. In the US and in this case, apparently, SQL's date time is MM.DD.YYYY, so you're going for the 15th month and 18th month Therefore you should use string query "SELECT * FROM LocalHotels WHERE city='LONDON' AND start <='12.15.2015 00:00:00' AND deadline >='12.18.2015 00:00:00' ORDER BY city" or string query "SELECT * FROM LocalHotels WHERE city='LONDON' AND start <='2015-12-15' AND deadline >='2015-12-18' ORDER BY city"
{ "language": "en", "url": "https://stackoverflow.com/questions/34174524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Stop pandas to_excel() prepending apostrophe on strings I have a pandas dataframe which has only strings, although some are date strings like '2019-01-01', others are ints or bools as strings such as '1084' and 'FALSE'. When I try to write this to a sheet in an xlsx file I find it is prepending apostrophes in some cases, presumably to stop excel trying to evaluate the dates/ints/bools and so on. Is there a way to stop this? I need to upload this generated .xlsx to a system which will reject it if these apostrophes are there. Currently I import a xlsx file as a template which has two sheets and I want to overwrite the 2nd one. Export code snippet: exp_dict['ScheduleDetails'] = df with pd.ExcelWriter(f"{uploads_folder}{name}_FORMATTED.xlsx",engine='xlsxwriter', options={'encoding':'utf-8'}) as writer: for k,v in exp_dict.items(): v.to_excel(writer, sheet_name = k, index = False) A: Not sure what your problem is but if you want to convertdtypes to str the try this: df.astype({'col_name': 'str'})
{ "language": "en", "url": "https://stackoverflow.com/questions/58195986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Curl request in python I'm a newbie to python program. I want to get trending topics in google trends. How do i make this curl request from python curl --data "ajax=1&htd=20131111&pn=p1&htv=l" http://www.google.com/trends/hottrends/hotItems I tried following code param = {"data" :"ajax=1&htd=20131111&pn=p1&htv=l"} value = urllib.urlencode(param) req = urllib2.Request("https://www.google.co.in/trends/hottrends/hotItems", value) response = urllib2.urlopen(req) result = response.read() print result But it is not returning expected values, which is the current Google trends. Any help would be appreciated. Thanks. A: You are misinterpreting the data element in your curl command line; that is the already encoded POST body, while you are wrapping it in another data key and encoding again. Either use just the value (and not encode it again), or put the individual elements in a dictionary and urlencode that: value = "ajax=1&htd=20131111&pn=p1&htv=l" req = urllib2.Request("https://www.google.co.in/trends/hottrends/hotItems", value) or param = {'ajax': '1', 'htd': '20131111', 'pn': 'p1', 'htv': 'l'} value = urllib.urlencode(param) req = urllib2.Request("https://www.google.co.in/trends/hottrends/hotItems", value) Demo: >>> import json >>> import urllib, urllib2 >>> value = "ajax=1&htd=20131111&pn=p1&htv=l" >>> req = urllib2.Request("https://www.google.co.in/trends/hottrends/hotItems", value) >>> response = urllib2.urlopen(req) >>> json.load(response).keys() [u'trendsByDateList', u'lastPage', u'summaryMessage', u'oldestVisibleDate', u'dataUpdateTime'] >>> param = {'ajax': '1', 'htd': '20131111', 'pn': 'p1', 'htv': 'l'} >>> value = urllib.urlencode(param) >>> value 'htv=l&ajax=1&htd=20131111&pn=p1' >>> req = urllib2.Request("https://www.google.co.in/trends/hottrends/hotItems", value) >>> response = urllib2.urlopen(req) >>> json.load(response).keys() [u'trendsByDateList', u'lastPage', u'summaryMessage', u'oldestVisibleDate', u'dataUpdateTime'] A: Easiest using the requests library in Python. Here's an example using Python 2.7: import requests import json payload = {'ajax': 1, 'htd': '20131111', 'pn':'p1', 'htv':'l'} req = requests.post('http://www.google.com/trends/hottrends/hotItems', data=payload) print req.status_code # Prints out status code print json.loads(req.text) # Prints out json data
{ "language": "en", "url": "https://stackoverflow.com/questions/25895013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Row counter in sub report - Jaspersoft I have a subreport that receives two parameters and therefore generates as many reports as there are combinations of parameters, I have to put a row counter in the sub report but this must not reset every report generated by the sub report but must continue the numbering. This is a conversion from a crystal report In crystal report do this: shared numberVar J; if trim({field}) <> '' then J:=J+1; I have a subreport to which I pass in the sql query two parameters whose values ​​are generated by the main report, the combination of these parameters in the subreport generates a series of reports in the main report because the subreport is in the detail band. In the subreport I have to insert a variable that counts the number of rows, but when I insert this variable the numeric counter is reset and starts counting in the new report generated by the subreport, I would like the counter not to reset Main report * *Detail of the band *subreport Subreport *report 1 1 row 2 rows 3 rows *report 2 1 row 2 rows 3 rows I would like to have - report 1 1 row 2 rows 3 rows -report 2 4 rows 5 rows 6 rows I hope I was clear Do you have any ideas? Can someone help me? Please Thanks a lot to everyone A: You can pass back and forth a running row count variable to the subreport using parameters and return variables. You'd need something like this: (in the master report) <!-- variable that stores the running row count in the master report --> <variable name="SubreportRowCount" class="java.lang.Integer" calculation="System"> <initialValueExpression>0</initialValueExpression> </variable> ... <subreport> ... <!-- pass the current value to the subreport --> <subreportParameter name="InitialRowCount"> <subreportParameterExpression>$V{SubreportRowCount}</subreportParameterExpression> </subreportParameter> ... <!-- get back the updated value from the subreport --> <returnValue subreportVariable="RunningRowCount" toVariable="SubreportRowCount"/> ... </subreport> (in the subreport) <!-- parameter that receives the initial value from the master --> <parameter name="InitialRowCount" class="java.lang.Integer"/> ... <!-- running row count variable --> <variable name="RunningRowCount" class="java.lang.Integer"> <variableExpression>$P{InitialRowCount} + $V{REPORT_COUNT}</variableExpression> </variable> ... <!-- show the running count in a text element --> <textField> ... <textFieldExpression>$V{RunningRowCount}</textFieldExpression> </textField>
{ "language": "en", "url": "https://stackoverflow.com/questions/61373263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I delete every n-th row from a dataframe in R, according to grouping variable? I wish to take every second measurement from a data.frame according to a grouping variable. For example, in the data.frame Input, take every second Sample for each ID: head(Input, 10) Sample X ID 15918 1 -1.326285 EABE_D5 15919 2 -1.315783 EABE_D5 15920 3 -1.313245 EABE_D5 15921 4 -1.304670 EABE_D5 15922 5 -1.309060 EABE_D5 15923 1 -1.292412 EABE_D4 15924 2 -1.294728 EABE_D4 15925 3 -1.282006 EABE_D4 15926 4 -1.287245 EABE_D4 15927 5 -1.278444 EABE_D4 and create a new data.frame named Output: Output Sample X ID 15919 2 -1.315783 EABE_D5 15921 4 -1.304670 EABE_D5 15924 2 -1.294728 EABE_D4 15926 4 -1.287245 EABE_D4 Is this possible? Thank you. A: We can use dplyr. After grouping by 'ID', we slice the rows based on the even index returned by seq library(dplyr) Input %>% group_by(ID) %>% slice(seq(2, n(), by =2)) # Sample X ID # <int> <dbl> <chr> #1 2 -1.294728 EABE_D4 #2 4 -1.287245 EABE_D4 #3 2 -1.315783 EABE_D5 #4 4 -1.304670 EABE_D5 Or we can use data.table for efficiency library(data.table) setDT(Input)[Input[, .I[seq(2, .N, by = 2)], by = ID]$V1] Or with ave from base R, we group by 'ID', apply the modulo operator %% with y as 2, convert to logical by negating (!) and with this logical vector, we subset the rows. Input[with(Input, !ave(Sample, ID, FUN = function(x) x %%2)),] # Sample X ID #15919 2 -1.315783 EABE_D5 #15921 4 -1.304670 EABE_D5 #15924 2 -1.294728 EABE_D4 #15926 4 -1.287245 EABE_D4 A: This might be inefficient. However, you can do this in one more way using lapply do.call(rbind, lapply(split(df, df$ID), function(x) x[seq(2, nrow(x), by=2),])) # Sample X ID #EABE_D4.15924 2 -1.294728 EABE_D4 #EABE_D4.15926 4 -1.287245 EABE_D4 #EABE_D5.15919 2 -1.315783 EABE_D5 #EABE_D5.15921 4 -1.304670 EABE_D5 splitting the dataframe based on ID and then selecting every 2nd row in each group and finally rbinding them using do.call to convert the list returned as dataframe. If you do not want the row names, you can take the dataframe in one variable (say a) and then rownames(a) <- NULL
{ "language": "en", "url": "https://stackoverflow.com/questions/38822053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there any way to get all product variation prices to display? I have WordPress woo-commerce site with product selling, and i have three variation price for the product like (1 kg -420, 500 grams - 220 and 250 gram- 100). currently it prices are showing like 100-420, but i need all three variation price to be display below the product, can any one help for this issue https://imgur.com/a/gJtAU6D $formatted_price = ( $negative ? '-' : '' ) . sprintf( $args['price_format'], '<span class="woocommerce-Price-currencySymbol">' . get_woocommerce_currency_symbol( $args['currency'] ) . '</span>', $price ); $return = '<span class="woocommerce-Price-amount amount">' . $formatted_price . '</span>'; if ( $args['ex_tax_label'] && wc_tax_enabled() ) { $return .= ' <small class="woocommerce-Price-taxLabel tax_label">' . WC()->countries->ex_tax_or_vat() . '</small>'; }
{ "language": "en", "url": "https://stackoverflow.com/questions/54747520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: please help to sort it out error: Command "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.35.32215\bin\HostX86\x64\cl.exe /c /nologo /O2 /W3 /GL /DNDEBUG /MD -IC:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2800.0_x64__qbz5n2kfra8p0\include -IC:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2800.0_x64__qbz5n2kfra8p0\Include -IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.35.32215\include -IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.35.32215\ATLMFC\include -IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\VS\include -IC:\Program Files (x86)\Windows Kits\10\include\10.0.22000.0\ucrt -IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\um -IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\shared -IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\winrt -IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\cppwinrt /EHsc /Tppystan/_misc.cpp /Fobuild\temp.win-amd64-cpython-310\Release\pystan\_misc.obj /EHsc -DBOOST_DATE_TIME_NO_LIB /std:c++14" failed with exit status 2 note: This error originates from a subprocess, and is likely not a problem with pip. error: legacy-install-failure × Encountered error while trying to install package. ╰─> pystan ............................................
{ "language": "en", "url": "https://stackoverflow.com/questions/75563379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Is it good to have all the setter functions return a reference to the object in c++? Is it good to have all the setter functions return a reference to the object in c++? A: The typical purpose for this style is in use for object construction. Person* pPerson = &(new Person())->setAge(34).setId(55).setName("Jack"); instead of Person* pPerson = new Person( 34, 55, "Jack" ); Using the second more traditional style one might forget if the first value passed to the constructor was the age or the id? This may also lead to multiple constructors based on the validity of some properties. Using the first style one might forget to set some of the object properties and and may lead bugs where objects are not 'fully' constructed. (A class property is added at a later point but not all the construction locations got updated to call the required setter.) As code evolves I really like the fact that I can use the compiler to help me find all the places where an object is created when changing the signature of a constructor. So for that reason I prefer using regular C++ constructors over this style. This pattern might work well in applications that maintain their datamodel over time according to rules similar to those used in many database applications: * *You can add a field/attribute to a table/class that is NULL by default. (So upgrading existing data requires just a new NULL column in the database.) *Code that is not changes should still work the same with this NULL field added. A: Not all the setters, but some of them could return reference to object to be useful. kind of a.SetValues(object)(2)(3)(5)("Hello")(1.4); I used this once long time ago to build SQL expression builder which handles all the Escapes problems and other things. SqlBuilder builder; builder.select( column1 )( column2 )( column3 ). where( "=" )( column1, value1 ) ( column2, value2 ). where( ">" )( column3, 100 ). from( table1 )( "table2" )( "table3" ); I wasn't able to reproduce sources in 10 minutes. So implementation is behind the curtains. A: If your motivation is related to chaining (e.g. Brian Ensink's suggestion), I would offer two comments: 1. If you find yourself frequently settings many things at once, that may mean you should produce a struct or class which holds all of these settings so that they can all be passed at once. The next step might be to use this struct or class in the object itself...but since you're using getters and setters the decision of how to represent it internally will be transparent to the users of the class anyways, so this decision will relate more to how complex the class is than anything. 2. One alternative to a setter is creating a new object, changing it, and returning it. This is both inefficient and inappropriate in most types, especially mutable types. However, it's an option that people sometimes forget, despite it's use in the string class of many languages. A: This technique is used in the Named parameter Idiom. A: IMO setters are a code smell that usually indicate one of two things: Making A Mountian Out Of A Molehill If you have a class like this: class Gizmo { public: void setA(int a) { a_ = a; } int getA() const { return a_; } void setB(const std::string & b) { v_ = b; } std::string getB() const { return b_; } private: std::string b_; int a_; }; ... and the values really are just that simple, then why not just make the data members public?: class Gizmo { public: std::string b_; int a_; }; ...Much simpler and, if the data is that simple you lose nothing. Another possibility is that you could be Making A Molehill Out Of A Mountian Lots of times the data is not that simple: maybe you have to change multiple values, do some computation, notify some other object; who knows what. But if the data is non-trivial enough that you really do need setters & getters, then it is non-trivial enough to need error handling as well. So in those cases your getters & setters should be returning some kind of error code or doing something else to indicate something bad has happened. If you are chaining calls together like this: A.doA().doB().doC(); ... and doA() fails, do you really want to be calling doB() and doC() anyway? I doubt it. A: It's a usable enough pattern if there's a lot of things that need to be set on an object. class Foo { int x, y, z; public: Foo &SetX(int x_) { x = x_; return *this; } Foo &SetY(int y_) { y = y_; return *this; } Foo &SetZ(int z_) { z = z_; return *this; } }; int main() { Foo foo; foo.SetX(1).SetY(2).SetZ(3); } This pattern replaces a constructor that takes three ints: int main() { Foo foo(1, 2, 3); // Less self-explanatory than the above version. } It's useful if you have a number of values that don't always need to be set. For reference, a more complete example of this sort of technique is refered to as the "Named Parameter Idiom" in the C++ FAQ Lite. Of course, if you're using this for named parameters, you might want to take a look at boost::parameter. Or you might not... A: You can return a reference to this if you want to chain setter function calls together like this: obj.SetCount(10).SetName("Bob").SetColor(0x223344).SetWidth(35); Personally I think that code is harder to read than the alternative: obj.SetCount(10); obj.SetName("Bob"); obj.SetColor(0x223344); obj.SetWidth(35); A: I would not think so. Typically, you think of 'setter' object as doing just that. Besides, if you just set the object, dont you have a pointer to it anyway?
{ "language": "en", "url": "https://stackoverflow.com/questions/752762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Create a function for add_new_field in Python I am trying to create a function for a task I mentioned earlier for adding a new field to some files that are stored in one folder. I read about the function method in Python and followed but it does not work. I would be happy if someone could guide me about it. def newfield(infile,outfile): infile.readlines() outfile = ["%s\t%s" %(item.strip(),2) for item in infile] outfile.write("\n".join(output)) outfile.close() return outfile and then I try to call it: a = open("E:/SAGA/data/2006last/test/325145404.all","r") b = open("E:/SAGA/data/2006last/test/325145404_edit.all","w") newfield(a,b) Moreover, when we create a function, should we call it in a same python shell or we can same it as a file and then call it? A: Looks like the problem is you're assigning the list you build to the same name as the output file. You're also reading all of the lines out of the file and not assigning the result anywhere, so when your list comprehension iterates over it, it's already at the end of the file. So you can drop the readlines line. def newfield(infile,outfile): output = ["%s\t%s" %(item.strip(),2) for item in infile] outfile.write("\n".join(output)) outfile.close() return outfile A: The line infile.readlines() consumes the whole input file. All lines are read and forgotten because they are not assigned to a variable. The construct ["%s\t%s" %(item.strip(),2) for item in infile] is a list comprehension. This expression returns a list. By assigning it to the variable outfile the old value of outfile - probably a file object - is forgotten and replaced by the list returned by the list comprehension. This list object does not have a write method. By assigning the list to another variable the file object in outfile is preserved. Try this: def newfield(infile,outfile): items = ["%s\t%s" %(item.strip(),2) for item in infile] outfile.write("\n".join(items)) outfile.close() return outfile
{ "language": "en", "url": "https://stackoverflow.com/questions/15786220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problems with w3 total cache I installed the plugin W3 total cache but It crashed an important plugin, so I have to delete it. The roblem is that my site is still running a cache version. I follow the instruction for delete the plugin: unchecked all options, disable and delete the plugin. I look up for the folders: cache and w3cache and proceed to delete it. I check the .htaccess and is ok. But still the cache version is loading. The web is: https://noia.pe/ A: I finally solve the problem. I don't know why W3 Total Cache create problems with the jquerys. This was the error on some parts of the web: Uncaught TypeError: $ is not a function So I fix it adding this: jQuery(function($)...) instead of function() and now is ok. I don't know why this happened, all the other pages are working ok, and as I said the only thing that was diferent with this was that plugin.
{ "language": "en", "url": "https://stackoverflow.com/questions/54603658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to make a MFC Visual Studio C++ program use both CPUs in a dual processor setup I recently built a workstation with a dual Xeon E5-2699v4 CPUs. This provides me with a total of 88 threads. I have a program that can benefit from using these threads. However when I tested it out, it seemed that it was only utilising 1 processor in the setup. Trying to use more than 44 threads, would cause the system to have momentary lockups. The program uses MFC Visual Studio C++. What would need to be done to code the program to use both processors? A: What would need to be done to code the program to use both processors? You need to understand how the code is spending the cpu-cycles, i.e. benchmark. Read on about simple method duration versus context-switch duration. "C++ has no notion of cores". Thus, the idea of associating a thread with a particular core is delegated to the operating system (in which the program is executing), and I have not seen the C++ language semantics for the issue. I have read of os calls to associate a thread with a core, but I have never grokked why, nor experimented. On Ubuntu, I simply start the threads, and rely on the OS (Linux) to assign each running thread to an available processor resource. Linux seems to do a reasonable job. I have measure two threads to perform the 'same' comparison work on two independent data's to cut the duration in half, and both cores are often fully utilized. (small to no i/o actions mixed in) Contexts switches are about an order of magnitude slower than method invocations. So perhaps your code design should avoid switching. Or, perhaps it is an effort of balance, code granularity, i.e. how much code to finish for each switch. On my Ubuntu 17.10 system I have measured the combined duration of '::sem_wait()' and '::sem_post()' (both small methods) to about 31 ns (103.7 M events in 3,237,099 us), [with no context switches, of course]. On my 2 core processor, one of my tests runs 10 threads for 10 seconds, and does not force a context switch, leaving a single critical section for the thread-to-thread interaction. I was surprised that the same thread often runs multiple times before one of the 'starving' threads gets to run (it is not a problem on that 'Linux minor benchmark' - lmbm). The code reports 297 ns per context switch. (33 M switches in 10 secs, 297 ns per). When I enforce a 'balanced-sharing-of-cores' (by using two semaphores per thread), every thread runs as often as any other. The switch duration is quite a bit longer (but not available to me at this moment). I don't have the opportunity to measure 10 threads on 44 cores, it sounds like fun. I estimate the range of performance would be 'big' - perhaps from "stalled" to "10x" the duration of 1 thread. Depending not on which core the code runs on, but on what the code does when it runs.
{ "language": "en", "url": "https://stackoverflow.com/questions/48591572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: Set default 'host' value for `php artisan serve` I am building a Laravel site, and want to test it on other devices as I build it (phone, ipad etc). As I understand it, the way to do this is to run php artisan serve --host=0.0.0.0. My question is... is there a way to define a default value for the host, and set it to 0.0.0.0, so that I can simply run php artisan serve and it will automatically run on 0.0.0.0? A: You can do next thing: * *php artisan make:command CustomServeCommand *Then delete all from file and use this code: <?php namespace App\Console\Commands; use Illuminate\Foundation\Console\ServeCommand; use Symfony\Component\Console\Input\InputOption; class CustomServeCommand extends ServeCommand { /** * Get the console command options. * * @return array */ protected function getOptions() { return [ ['host', null, InputOption::VALUE_OPTIONAL, 'The host address to serve the application on.', '0.0.0.0'],//default 127.0.0.1 ['port', null, InputOption::VALUE_OPTIONAL, 'The port to serve the application on.', 8000], ]; } } *php artisan serve Link to the core file. Basically, you will extend default class and adapt method to fit your own needs. This way you can set host and port per requirements.
{ "language": "en", "url": "https://stackoverflow.com/questions/50639622", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Angular9: Getting Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays I have created a simple app to call backend services using HttpClientModule,, but data is not showing into the log, I did the following steps and I am using angular-9 could you please check the code. Thanks in Advance. * *app.module file import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule} from '@angular/common/http'; import {RestAPIServices} from './services/rest-api.service'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [RestAPIServices], bootstrap: [AppComponent] }) export class AppModule { } *model.ts export class Employee{ id:number; name:string; gender:string; email? :string; // ? means optional property mobile:string; department:string; isActive:boolean; photo? :string; } *service.ts import {Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import {HttpClient} from '@angular/common/http'; import { Employee } from '../models/employee.model'; @Injectable() export class RestAPIServices{ constructor(private httpClient:HttpClient){} getEmployee():Observable<Employee[]>{ //this.httpClient.get<Employee[]>("http://127.0.0.1/angularCRUDservices/user/getEmployees").subscribe(res=> console.log(res)); return this.httpClient.get<Employee[]>("http://127.0.0.1/angularCRUDservices/user/getEmployees"); } } *app.component.ts import { Component } from '@angular/core'; import {RestAPIServices} from './services/rest-api.service'; import {Employee} from './models/employee.model'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { listEmployee : Employee[]; title = 'simple-rest-app'; constructor(private _employeeService:RestAPIServices){} ngOnInit(){ this._employeeService.getEmployee().subscribe( data=>{ console.log(data) this.listEmployee = data; } ) console.log(this.listEmployee); } } servire is tested from postman and it's working fine {"response":[{"id":"1","name":"Anand","gender":"Male","email":"a@gmail.com","mobile":"111111111","department":"2","isActive":"1","photo":"assets\/images\/emp1.jpg"},{"id":"2","name":"Kiran","gender":"Female","email":"k@gmail.com","mobile":"2222222222","department":"2","isActive":"1","photo":"assets\/images\/emp1.jpg"},{"id":"3","name":"Ravi","gender":"Male","email":"r@gmail.com","mobile":"3333333333","department":"2","isActive":"1","photo":"assets\/images\/emp2.jpg"},{"id":"4","name":"Kumar","gender":"Male","email":"k@gmail.com","mobile":"4444444444","department":"3","isActive":"1","photo":"assets\/images\/emp4.jpg"}]} A: Looks like the problem is that the server response is an object, but not an array. // try to replace this.httpClient.get<Employee[]>(...); // by this.httpClient.get<{ response: Employee[] }>(...).pipe( map(response => response.response) );
{ "language": "en", "url": "https://stackoverflow.com/questions/61304121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I cannot find javadoc or source files for JDK 8 Update 321 on the net In the projects in IntelliJ IDEA I am using JDK 8 Update 321, but I am missing javadoc or source for the SDK. OS is Windows 10. I realy tried, but wasn't able to find either on the internet. A: Javadoc: https://javadl.oracle.com/webapps/download/AutoDL?BundleId=245778_df5ad55fdd604472a86a45a217032c7d The source should be part of the JDK, search for src.zip in your JDK directory. How to attach JDK source code to IntelliJ IDEA A: I didn't know that patch releases don't change the public API, so both Thomas Behr's comment and sinclair's answer are valid. Only thing to add is that the javadoc zip should be included in IntelliJ IDA via File -> Project Structure -> Platform Settings -> SDKs -> Documentation Paths (instead of Sourcepath).
{ "language": "en", "url": "https://stackoverflow.com/questions/74221033", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook OAuth access_token error Full code. public function indexAction(){ echo '<a href="https://www.facebook.com/dialog/oauth?client_id=475302972487577&redirect_uri=http://bp.mysite.com/en/social/fblogin" target="_blank">Login met facebook</a> '; } const FB_GRAPH_URL = "https://graph.facebook.com/"; public function fbloginAction() { $fbCode = $this->_getParam("code"); $getStr = self::FB_GRAPH_URL. 'oauth/access_token?' .http_build_query(array( 'client_id' => 'APP_ID', 'type' => 'client_cred', 'client_secret' => 'SECRET_KEY', 'code' => $fbCode) ); $accessToken = file_get_contents( $getStr ); krumo($accessToken) ; $dbpath = "https://graph.facebook.com/me?$accessToken" ; $cont = file_get_contents($dbpath ) ; krumo($cont); } When i try make GET query to Facebook. $dbpath = "https://graph.facebook.com/me?$accessToken" ; $cont = file_get_contents($dbpath ) ; I receive the error : failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in /home..... When paste manually the $dbpath value(path) to web browser, i got next error: { "error": { "message": "An active access token must be used to query information about the current user.", "type": "OAuthException", "code": 2500 } } How fix that error? A: You probably want to use the Server-Side Authentication flow. By checking the calls in the documentation it is quite clear, which of your calls are wrong. First, your call to the oauth/access_token endpoint takes no argument 'type' => 'client_cred', but it needs the parameter for your redirect_uri again: $getStr = self::FB_GRAPH_URL . 'oauth/access_token?' . http_build_query(array( 'client_id' => 'APP_ID', 'redirect_uri' => 'REDIRECT_URI', 'client_secret' => 'SECRET_KEY', 'code' => $fbCode) ); Then, you can't just take the answer of this call as your access_token, as there is much more in it: access_token=USER_ACCESS_TOKEN&expires=NUMBER_OF_SECONDS_UNTIL_TOKEN_EXPIRES and you only want the access_token part of it: $response = file_get_contents($getStr); $params = null; parse_str($response, $params); $dbpath = "https://graph.facebook.com/me?access_token=" . $params['access_token'];
{ "language": "en", "url": "https://stackoverflow.com/questions/12134213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Run a single test with multiple configs in parallel using pytest I have to run the same test against different hosts in parallel. Currently, i'm making a bunchof pytest.main() calls. But this is not run in parallel and results are not aggregated. This is the content of runtest.py: pytest.main('--conf=c1.txt') pytest.main('--conf=c2.txt') pytest.main('--conf=c3.txt') I have just one test_host.py which looks something like: test_pinghost(conf): # pings a host in config Is there a way to run this in parallel and aggregate results? PS:the config filejust contains the host IP A: Please use http://pytest.readthedocs.org/en/2.0.3/xdist.html, it enables pytest to run tests across multiple processes/machines
{ "language": "en", "url": "https://stackoverflow.com/questions/24944263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Classes with String Switches class AddItemOption { //Fields that contain class data string input = Console.ReadLine(); //Methods that define class functionality public string myFunction(string Value) { switch (input) { case "Umbrella": Console.WriteLine("Umbrella is selected"); break; case "Rain Coat": Console.WriteLine("Raincoat is selected"); break; case "Boots": Console.WriteLine("Boots is selected"); break; case "Hood": Console.WriteLine("Hood is selected"); break; default: Console.WriteLine("Input not reconized, please choose another item"); break; } } I get the error "Not all code paths return a value". It is from myFunction(string Value). I'm not sure how to return this, or what to put in the parameter to get it to work. Do I need something below it too? I am new to classes. Please tell me if I'm doing this all wrong or if that is where the switch statement should go! public AddItemOption(string input) { } FROM Shyju I changed it to: class AddItemOptionOne { //Fields that contain class data string input = Console.ReadLine(); //Methods that define class functionality public string myFunction(string Value) { switch (input) { case "Key Chain": return "Key Chain is selected"; break; case "Leather Armor": return "Leather Armor is selected"; break; case "Boots": return "Boots is selected"; break; case "Sword": return "Sword is selected"; break; default: return "Input not reconized, please choose another item"; break; } } However, it does not recognize the breaks. "Unreachable Code Detected" A: Your method has a return type of string. That means your method should always return some string. But you are not returning a string. instead you are Writing it to the console using WriteLine method. So Change Console.WriteLine("Umbrella is selected"); to return "Umbrella is selected"; OR You can change your method's return type to void. public void myFunction(string Value) { //your current fancy stuff here Console.WriteLine("My method dont have a return type"); } EDIT : AS per the question edit. return statement will take the control out from your method. that means the next line (break) won't be executed. So remove the break statement. case "Key Chain": return "Key Chain is selected"; A: Well... You don't return anything from your function, so change it to public void myFunction(string Value) A: Try this: class AddItemOptionOne { //Methods that define class functionality public string myFunction(string input) { string result = string.Empty; switch (input) { case "Key Chain": result = "Key Chain is selected"; break; case "Leather Armor": result = "Leather Armor is selected"; break; case "Boots": result = "Boots is selected"; break; case "Sword": result = "Sword is selected"; break; default: result = "Input not reconized, please choose another item"; break; } return result; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/13243138", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does explicit template instantiation go in cpp or header file? Does explicit template instantiation go in cpp or header file? A: Assuming by "explicit template instantiation" you mean something like template class Foo<int>; // explicit type instantiation // or template void Foo<int>(); // explicit function instantiation then these must go in source files as they considered definitions and are consequently subject to the ODR. A: I've always done it in a cpp file. In a header, it would violate the one definition rule, at least (in the usual case) when the header was included in more than one cpp file (though there are ways to avoid that, which can be useful under a few, specific circumstances). A: Either one. If you are declaring a specific instance, you might declare it in your cpp file. However, if you are declaring a class member or something that will be referenced from multiple cpp files, that would go in your header file.
{ "language": "en", "url": "https://stackoverflow.com/questions/5864401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: How can I supply an AntiForgeryToken when posting JSON data using $.ajax? I am using the code as below of this post: First I will fill an array variable with the correct values for the controller action. Using the code below I think it should be very straightforward by just adding the following line to the JavaScript code: data["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val(); The <%= Html.AntiForgeryToken() %> is at its right place, and the action has a [ValidateAntiForgeryToken] But my controller action keeps saying: "Invalid forgery token" What am I doing wrong here? Code data["fiscalyear"] = fiscalyear; data["subgeography"] = $(list).parent().find('input[name=subGeography]').val(); data["territories"] = new Array(); $(items).each(function() { data["territories"].push($(this).find('input[name=territory]').val()); }); if (url != null) { $.ajax( { dataType: 'JSON', contentType: 'application/json; charset=utf-8', url: url, type: 'POST', context: document.body, data: JSON.stringify(data), success: function() { refresh(); } }); } A: You can set $.ajax 's traditional attribute and set it to true, to send json data as url encoded form. Make sure to set type:'POST'. With this method you can even send arrays and you do not have to use JSON.stringyfy or any changes on server side (e.g. creating custom attributes to sniff header ) I have tried this on ASP.NET MVC3 and jquery 1.7 setup and it's working following is the code snippet. var data = { items: [1, 2, 3], someflag: true}; data.__RequestVerificationToken = $(':input[name="__RequestVerificationToken"]').val(); $.ajax({ url: 'Test/FakeAction' type: 'POST', data: data dataType: 'json', traditional: true, success: function (data, status, jqxhr) { // some code after succes }, error: function () { // alert the error } }); This will match with MVC action with following signature [HttpPost] [Authorize] [ValidateAntiForgeryToken] public ActionResult FakeAction(int[] items, bool someflag) { } A: You don't need the ValidationHttpRequestWrapper solution since MVC 4. According to this link. * *Put the token in the headers. *Create a filter. *Put the attribute on your method. Here is my solution: var token = $('input[name="__RequestVerificationToken"]').val(); var headers = {}; headers['__RequestVerificationToken'] = token; $.ajax({ type: 'POST', url: '/MyTestMethod', contentType: 'application/json; charset=utf-8', headers: headers, data: JSON.stringify({ Test: 'test' }), dataType: "json", success: function () {}, error: function (xhr) {} }); [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class ValidateJsonAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } var httpContext = filterContext.HttpContext; var cookie = httpContext.Request.Cookies[AntiForgeryConfig.CookieName]; AntiForgery.Validate(cookie != null ? cookie.Value : null, httpContext.Request.Headers["__RequestVerificationToken"]); } } [HttpPost] [AllowAnonymous] [ValidateJsonAntiForgeryToken] public async Task<JsonResult> MyTestMethod(string Test) { return Json(true); } A: What is wrong is that the controller action that is supposed to handle this request and which is marked with the [ValidateAntiForgeryToken] expects a parameter called __RequestVerificationToken to be POSTed along with the request. There's no such parameter POSTed as you are using JSON.stringify(data) which converts your form to its JSON representation and so the exception is thrown. So I can see two possible solutions here: Number 1: Use x-www-form-urlencoded instead of JSON for sending your request parameters: data["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val(); data["fiscalyear"] = fiscalyear; // ... other data if necessary $.ajax({ url: url, type: 'POST', context: document.body, data: data, success: function() { refresh(); } }); Number 2: Separate the request into two parameters: data["fiscalyear"] = fiscalyear; // ... other data if necessary var token = $('[name=__RequestVerificationToken]').val(); $.ajax({ url: url, type: 'POST', context: document.body, data: { __RequestVerificationToken: token, jsonRequest: JSON.stringify(data) }, success: function() { refresh(); } }); So in all cases you need to POST the __RequestVerificationToken value. A: You can't validate an content of type contentType: 'application/json; charset=utf-8' because your date will be uploaded not in the Form property of the request, but in the InputStream property, and you will never have this Request.Form["__RequestVerificationToken"]. This will be always empty and validation will fail. A: You won't ever have to validate an AntiForgeryToken when you receive posted JSON. The reason is that AntiForgeryToken has been created to prevent CSRF. Since you can't post AJAX data to another host and HTML forms can't submit JSON as the request body, you don't have to protect your app against posted JSON. A: I have resolved it globally with RequestHeader. $.ajaxPrefilter(function (options, originalOptions, jqXhr) { if (options.type.toUpperCase() === "POST") { // We need to add the verificationToken to all POSTs if (requestVerificationTokenVariable.length > 0) jqXhr.setRequestHeader("__RequestVerificationToken", requestVerificationTokenVariable); } }); where the requestVerificationTokenVariable is an variable string that contains the token value. Then all ajax call send the token to the server, but the default ValidateAntiForgeryTokenAttribute get the Request.Form value. I have writed and added this globalFilter that copy token from header to request.form, than i can use the default ValidateAntiForgeryTokenAttribute: public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new GlobalAntiForgeryTokenAttribute(false)); } public class GlobalAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter { private readonly bool autoValidateAllPost; public GlobalAntiForgeryTokenAttribute(bool autoValidateAllPost) { this.autoValidateAllPost = autoValidateAllPost; } private const string RequestVerificationTokenKey = "__RequestVerificationToken"; public void OnAuthorization(AuthorizationContext filterContext) { var req = filterContext.HttpContext.Request; if (req.HttpMethod.ToUpperInvariant() == "POST") { //gestione per ValidateAntiForgeryToken che gestisce solo il recupero da Request.Form (non disponibile per le chiamate ajax json) if (req.Form[RequestVerificationTokenKey] == null && req.IsAjaxRequest()) { var token = req.Headers[RequestVerificationTokenKey]; if (!string.IsNullOrEmpty(token)) { req.Form.SetReadOnly(false); req.Form[RequestVerificationTokenKey] = token; req.Form.SetReadOnly(true); } } if (autoValidateAllPost) AntiForgery.Validate(); } } } public static class NameValueCollectionExtensions { private static readonly PropertyInfo NameObjectCollectionBaseIsReadOnly = typeof(NameObjectCollectionBase).GetProperty("IsReadOnly", BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Instance); public static void SetReadOnly(this NameValueCollection source, bool readOnly) { NameObjectCollectionBaseIsReadOnly.SetValue(source, readOnly); } } This work for me :) A: I hold the token in my JSON object and I ended up modifying the ValidateAntiForgeryToken class to check the InputStream of the Request object when the post is json. I've written a blog post about it, hopefully you might find it useful. A: Check out Dixin's Blog for a great post on doing exactly that. Also, why not use $.post instead of $.ajax? Along with the jQuery plugin on that page, you can then do something as simple as: data = $.appendAntiForgeryToken(data,null); $.post(url, data, function() { refresh(); }, "json"); A: AJAX based model posting with AntiForgerytoken can be made bit easier with Newtonsoft.JSON library Below approach worked for me: Keep your AJAX post like this: $.ajax({ dataType: 'JSON', url: url, type: 'POST', context: document.body, data: { '__RequestVerificationToken': token, 'model_json': JSON.stringify(data) };, success: function() { refresh(); } }); Then in your MVC action: [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(FormCollection data) { var model = JsonConvert.DeserializeObject < Order > (data["model_json"]); return Json(1); } Hope this helps :) A: I was just implementing this actual problem in my current project. I did it for all Ajax POSTs that needed an authenticated user. First off, I decided to hook my jQuery Ajax calls so I do not to repeat myself too often. This JavaScript snippet ensures all ajax (post) calls will add my request validation token to the request. Note: the name __RequestVerificationToken is used by the .NET framework so I can use the standard Anti-CSRF features as shown below. $(document).ready(function () { securityToken = $('[name=__RequestVerificationToken]').val(); $('body').bind('ajaxSend', function (elm, xhr, s) { if (s.type == 'POST' && typeof securityToken != 'undefined') { if (s.data.length > 0) { s.data += "&__RequestVerificationToken=" + encodeURIComponent(securityToken); } else { s.data = "__RequestVerificationToken=" + encodeURIComponent(securityToken); } } }); }); In your Views where you need the token to be available to the above JavaScript code, just use the common HTML-Helper. You can basically add this code wherever you want. I placed it within a if(Request.IsAuthenticated) statement: @Html.AntiForgeryToken() // You can provide a string as salt when needed which needs to match the one on the controller In your controller simply use the standard ASP.NET MVC anti-CSRF mechanism. I did it like this (though I actually used a salt). [HttpPost] [Authorize] [ValidateAntiForgeryToken] public JsonResult SomeMethod(string param) { // Do something return Json(true); } With Firebug or a similar tool you can easily see how your POST requests now have a __RequestVerificationToken parameter appended. A: I had to be a little shady to validate anti-forgery tokens when posting JSON, but it worked. //If it's not a GET, and the data they're sending is a string (since we already had a separate solution in place for form-encoded data), then add the verification token to the URL, if it's not already there. $.ajaxSetup({ beforeSend: function (xhr, options) { if (options.type && options.type.toLowerCase() !== 'get' && typeof (options.data) === 'string' && options.url.indexOf("?__RequestVerificationToken=") < 0 && options.url.indexOf("&__RequestVerificationToken=") < 0) { if (options.url.indexOf('?') < 0) { options.url += '?'; } else { options.url += '&'; } options.url += "__RequestVerificationToken=" + encodeURIComponent($('input[name=__RequestVerificationToken]').val()); } } }); But, as a few people already mentioned, the validation only checks the form - not JSON, and not the query string. So, we overrode the attribute's behavior. Re-implementing all of the validation would have been terrible (and probably not secure), so I just overrode the Form property to, if the token were passed in the QueryString, have the built-in validation THINK it was in the Form. That's a little tricky because the form is read-only, but doable. if (IsAuth(HttpContext.Current) && !IsGet(HttpContext.Current)) { //if the token is in the params but not the form, we sneak in our own HttpContext/HttpRequest if (HttpContext.Current.Request.Params != null && HttpContext.Current.Request.Form != null && HttpContext.Current.Request.Params["__RequestVerificationToken"] != null && HttpContext.Current.Request.Form["__RequestVerificationToken"] == null) { AntiForgery.Validate(new ValidationHttpContextWrapper(HttpContext.Current), null); } else { AntiForgery.Validate(new HttpContextWrapper(HttpContext.Current), null); } } //don't validate un-authenticated requests; anyone could do it, anyway private static bool IsAuth(HttpContext context) { return context.User != null && context.User.Identity != null && !string.IsNullOrEmpty(context.User.Identity.Name); } //only validate posts because that's what CSRF is for private static bool IsGet(HttpContext context) { return context.Request.HttpMethod.ToUpper() == "GET"; } ... internal class ValidationHttpContextWrapper : HttpContextBase { private HttpContext _context; private ValidationHttpRequestWrapper _request; public ValidationHttpContextWrapper(HttpContext context) : base() { _context = context; _request = new ValidationHttpRequestWrapper(context.Request); } public override HttpRequestBase Request { get { return _request; } } public override IPrincipal User { get { return _context.User; } set { _context.User = value; } } } internal class ValidationHttpRequestWrapper : HttpRequestBase { private HttpRequest _request; private System.Collections.Specialized.NameValueCollection _form; public ValidationHttpRequestWrapper(HttpRequest request) : base() { _request = request; _form = new System.Collections.Specialized.NameValueCollection(request.Form); _form.Add("__RequestVerificationToken", request.Params["__RequestVerificationToken"]); } public override System.Collections.Specialized.NameValueCollection Form { get { return _form; } } public override string ApplicationPath { get { return _request.ApplicationPath; } } public override HttpCookieCollection Cookies { get { return _request.Cookies; } } } There's some other stuff that's different about our solution (specifically, we're using an HttpModule so we don't have to add the attribute to every single POST) that I left out in favor of brevity. I can add it if necessary. A: Unfortunately for me, the other answers rely on some request formatting handled by jquery, and none of them worked when setting the payload directly. (To be fair, putting it in the header would have worked, but I did not want to go that route.) To accomplish this in the beforeSend function, the following works. $.params() transforms the object into the standard form / url-encoded format. I had tried all sorts of variations of stringifying json with the token and none of them worked. $.ajax({ ...other params..., beforeSend: function(jqXHR, settings){ var token = ''; //get token data = { '__RequestVerificationToken' : token, 'otherData': 'value' }; settings.data = $.param(data); } }); ``` A: You should place AntiForgeryToken in a form tag: @using (Html.BeginForm(actionName:"", controllerName:"",routeValues:null, method: FormMethod.Get, htmlAttributes: new { @class="form-validator" })) { @Html.AntiForgeryToken(); } Then in javascript modify the following code to be var DataToSend = []; DataToSend.push(JSON.stringify(data), $('form.form-validator').serialize()); $.ajax({ dataType: 'JSON', contentType: 'application/json; charset=utf-8', url: url, type: 'POST', context: document.body, data: DataToSend, success: function() { refresh(); } }); Then you should be able to validate the request using ActionResult annotations [ValidateAntiForgeryToken] [HttpPost] I hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/2906754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "81" }
Q: Videojs original timeline not coming I am using videojs in my application. I wrapped video tag inside video-wrapper div to make it as the size of parent div which is video-wrapper. But the problem is I am not able to see the actual timeline of videojs which comes with it. Chrome is adding it's own timeline I guess. This is my code return ( <div className="video-wrapper"> <video id="example_video_1" controls preload="auto" className="video-js vjs-default-skin" data-setup='{"fluid":true}'> <source src={videoSrc} type="video/mp4"/> </video> </div>) and this is css .video-wrapper { background: white; position: relative; padding-bottom: 50% ; /* 16:8 */ padding-top: 25px; height: 0; } .video-wrapper > video { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } This is the result I get (look at the video timeline. It's not videojs's timeline) This is how I want the player timeline to look like. Also it should fit in the video-wrapper. (In the below picture size is screwed up though) The code for this was (but not responsive) render() { var props = blacklist(this.props, 'children', 'className', 'src', 'type', 'onPlay'); props.className = cx(this.props.className, 'videojs', 'video-js vjs-default-skin', 'vjs-big-play-centered'); assign(props, { ref: 'video', controls: true, height:"650", width:"800" }); if (this.props.tags.flag) { this.jumpToSpecificMarker(); console.log("card clicked was" + this.props.card_Reducer.card_id); } return ( <div> <video{... props}> <source src={this.props.src} type="video/mp4"/> </video> {/*<button onClick={this.jumpToSpecificMarker.bind(this)}>next</button>*/} {/*<button onClick={this.prev.bind(this)}>prev</button>*/} </div>) }
{ "language": "en", "url": "https://stackoverflow.com/questions/41811961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does Rails generate a SQL query for an "include?" call in a view but not in the console? In my app a Position has_many Questions. In my position edit view, I create a set of checkboxes by looping over an array of Questions and checking those that the current position already includes. Looks like this: - @questions.each do |question| = check_box_tag :question_ids, question.id, @position.questions.include?(question), name: 'position[question_ids][]', id: "question_check_#{question.id}" = label_tag "question_check_#{question.id}", question.text I noticed loading this page took an unusually long time and my logs had these (I've snipped it for space): LOG: duration: 827.370 ms statement: SELECT 1 FROM "questions" INNER JOIN "required_questions" ON "questions"."id" = "required_questions"."question_id" WHERE "required_questions"."position_id" IS NULL AND "questions"."id" = 1 ORDER BY account_id desc, "questions".id asc LIMIT 1 LOG: duration: 821.666 ms statement: SELECT 1 FROM "questions" INNER JOIN "required_questions" ON "questions"."id" = "required_questions"."question_id" WHERE "required_questions"."position_id" IS NULL AND "questions"."id" = 2 ORDER BY account_id desc, "questions".id asc LIMIT 1 LOG: duration: 713.379 ms statement: SELECT 1 FROM "questions" INNER JOIN "required_questions" ON "questions"."id" = "required_questions"."question_id" WHERE "required_questions"."position_id" IS NULL AND "questions"."id" = 3 ORDER BY account_id desc, "questions".id asc LIMIT 1 I tracked the problem to this code: @position.questions.include?(question) I thought this was a simple Array.include? check so I was surprised by my findings. I was also surprised when I fixed it by adding an explicit .to_a call: @position.questions.to_a.include?(question) I was surprised a third time when I tested the original code in the Rails console and no SQL query was generated. At this point I'm just curious - why did my original code generate a SQL query for each iteration when the same code in Rails console (albeit without the iteration and inside Rails console) did not? Why didn't it just do an Array.include? check? A: This happens because @position.questions is not an array. It's actually an ActiveRecord::Relation. The problem is that the console actually behaves differently from your server application. For example, in your console position.questions returns an array. That is because the console is actually evaluating this expression as position.questions.all which is equivalent to position.questions.to_a. In your server application the to_a or all is not called until you actually use the query. This is a good thing because it means you can continue to build up a query and it will only actually get executed when it's called. For instance: query = @position.questions query.first query.last Will actually generate two queries that return two records in your server application because the query variable will be assigned an ActiveRecord::Relation instead of an Array. In your console this will generate a single query, but the query will load all of the questions into an Array and assign that to query and then select the first and last elements. The all, first, last, count and even include? keywords are all triggers that actually execute the query, so in your application when you call @position.questions.include? you are executing a single query on the @position.questions relation. Adding the to_a causes this query to be executed immediately.
{ "language": "en", "url": "https://stackoverflow.com/questions/8126464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Vb.net 2 decimals double I want to place all my doubles to 2 decimals after the comma. At this moment when the value is 0.30, my Datagridview shows 0.3..any idea? This is my code: eenheidsprijs = Math.Round(eenheidsprijs, 2) basisbedrag = Math.Round(basisbedrag, 2) kortingbedrag = Math.Round(kortingbedrag, 2) netto = Math.Round(netto, 2) btwbedrag = Math.Round(btwbedrag, 2) totaal = Math.Round(totaal, 2) Dim streenheidsprijs, strbasisbedrag, strkortingbedrag, strnetto, strbtwbedrag, strtotaal As String streenheidsprijs = Format(eenheidsprijs, "0.00") strbasisbedrag = Format(basisbedrag, "0.00") strkortingbedrag = Format(kortingbedrag, "0.00") strnetto = Format(netto, "0.00") strbtwbedrag = btwbedrag.ToString("N", CultureInfo.InvariantCulture) strtotaal = Format(totaal, "0.00") eenheidsprijs = Double.Parse(streenheidsprijs) basisbedrag = Double.Parse(strbasisbedrag) kortingbedrag = Double.Parse(strkortingbedrag) netto = Double.Parse(strnetto) btwbedrag = Double.Parse(strbtwbedrag) totaal = Double.Parse(strtotaal) A: Which value is bound to your datagrid? streenheidsprijs or eenheidsprijs? The string value is formatted to 2 decimal places, but the double variable doesn't inherit the number of decimal places to show. In actual fact, there is no value in the lines to re-parse the string values that have been formatted: eenheidsprijs = Double.Parse(streenheidsprijs) The data grid columns should either be bound to the string values that have been formatted to 2 dp, or you should configure the display properties of the columns in the data grid so that they only show two decimal places. A: You can provide a format string to the default cell style of the column. In your case, the format F2 would be preferable. At run-time: myDataGridView.Columns("myColumnName").DefaultCellStyle.Format = "F2" At design-time: Sample form Public Class Form1 Public Sub New() Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US") Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US") Me.InitializeComponent() Me.ClientSize = New Size(350, 400) Me.column1 = New DataGridViewTextBoxColumn With {.Name = "Column1", .HeaderText = "Double (F2)", .ValueType = GetType(Double), .Width = 100} Me.column1.DefaultCellStyle.Format = "F2" Me.column2 = New DataGridViewTextBoxColumn With {.Name = "Column2", .HeaderText = "Double (F8)", .ValueType = GetType(Double), .AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill, .MinimumWidth = 100} Me.column2.DefaultCellStyle.Format = "F8" Me.grid = New DataGridView With {.Dock = DockStyle.Fill} Me.grid.Columns.AddRange(Me.column1, Me.column2) For i As Double = 0.0R To 9.0R : Me.grid.Rows.Add(i, i) : Next Me.Controls.Add(Me.grid) End Sub Private WithEvents grid As DataGridView Private WithEvents column1 As DataGridViewTextBoxColumn Private WithEvents column2 As DataGridViewTextBoxColumn End Class
{ "language": "en", "url": "https://stackoverflow.com/questions/24722638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Unity Google Play Services: Authentication Failed always: I have a problem with authenticate. The authenticate always fail and I can't understand the cause (not only fail in the editor, in my device too). Here is the code: using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; using UnityEngine.Advertisements; using System.Collections; using System.Collections.Generic; using GooglePlayGames; using UnityEngine.SocialPlatforms; using GooglePlayGames.BasicApi; using UnityEngine.Analytics; public class Menu : MonoBehaviour { public Text record; /** Menu when the player isn´t authenticate */ public GameObject signIn; public GameObject test; void Awake() { PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder ().Build (); PlayGamesPlatform.InitializeInstance(config); GooglePlayGames.PlayGamesPlatform.DebugLogEnabled = false; GooglePlayGames.PlayGamesPlatform.Activate (); } void Start() { Advertisement.Initialize ("CORRECT_NUMBER", true); if (PlayerPrefs.HasKey("record")) { record.text = "Record actual: " + PlayerPrefs.GetInt("record"); Analytics.CustomEvent ("Start Play", new Dictionary<string, object>{ { "Record", PlayerPrefs.GetInt("record")} }); if (Social.localUser.authenticated) { Social.ReportScore (PlayerPrefs.GetInt ("record"), "CORRECT_CODE", (bool success) => { }); } } else { record.text = "Consigue un record!!"; } if (Social.localUser.authenticated) { signIn.SetActive (false); } test.SetActive (false); } public void OnPlay() { ShowAd (); SceneManager.LoadScene("Play"); Time.timeScale = 0; } public void OnArchievements() { if (Social.localUser.authenticated) { Social.ShowAchievementsUI (); } else { Social.localUser.Authenticate ((bool success) => { if (success) { Social.ShowAchievementsUI (); } }); } } public void OnMatching() { if (Social.localUser.authenticated) { Social.ShowLeaderboardUI (); } else { Social.localUser.Authenticate ((bool success) => { if (success) { Social.ShowLeaderboardUI (); } }); } } public void OnExit() { Analytics.CustomEvent ("Stop Play", new Dictionary<string, object>{ { "Record", PlayerPrefs.GetInt("record")} }); Application.Quit(); } public void SignIn() { Social.localUser.Authenticate((bool success) => { if (success) { Debug.Log ("Sign in"); signIn.SetActive (false); } else { Debug.Log ("Fail for some reason..."); test.SetActive (true); } }); } public void Later() { signIn.SetActive (false); } public void ShowAd() { if (Advertisement.IsReady()) { Advertisement.Show(); } } } The object "test" is only a white box that appears to know the authentication fail. The console don't show me any type of error, so I don't know where find the problem... Any idea what's the problem? PD: I use version 0.9.34 and Unity 5.3.5f1 Thanks in advance! A: Not a problem. I am going to write the response here because it may be quite long. Unity has the default ISocialPlatform set to Apple. Doing the "PlayGamesClientConfiguration" you change the default ISocialPlatform to Google+. My comment was talking about your Awake() function. I recommended you to put it in Start() as follows: void Start() { //added code PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder ().Build (); PlayGamesPlatform.InitializeInstance(config); GooglePlayGames.PlayGamesPlatform.DebugLogEnabled = false; //GooglePlayGames.PlayGamesPlatform.Activate (); //this is wrong //WHAT YOU ARE MISSING PlayGamesPlatform.Activate(); //END OF WHAT YOU ARE MISSING Advertisement.Initialize ("CORRECT_NUMBER", true); if (PlayerPrefs.HasKey("record")) { record.text = "Record actual: " + PlayerPrefs.GetInt("record"); Analytics.CustomEvent ("Start Play", new Dictionary<string, object>{ { "Record", PlayerPrefs.GetInt("record")} }); //you should do this once the user is authenticated and logged in if (Social.localUser.authenticated) { Social.ReportScore (PlayerPrefs.GetInt ("record"), "CORRECT_CODE", (bool success) => { }); } } else { record.text = "Consigue un record!!"; } if (Social.localUser.authenticated) { signIn.SetActive (false); } test.SetActive (false); } Then, you can create a button in the inspector inside your scene and call this: public void SignIn() { Social.localUser.Authenticate( ProcessAuthentication) } The CallBackFunction is a void function that takes in a bool. (You were doing this correctly) I like making my code readable and easy to understand. void ProcessAuthentication (bool success) { if (true == success) { Debug.Log ("AUTHENTICATED!"); if (Social.localUser.authenticated) { Social.ReportScore (PlayerPrefs.GetInt ("record"), "CORRECT_CODE", (bool success) => { }); } } else { record.text = "Consigue un record!!"; } if (Social.localUser.authenticated) { signIn.SetActive (false); //EDIT: you need to load the achievements to use them Social.LoadAchievements (ProcessLoadedAchievements); Social.LoadScores(leaderboardID, CALLBACK) // Callback has to be a Action<IScore[]> callback } test.SetActive (false); } else { Debug.Log("Failed to authenticate"); signIn.SetActive (true); } } void ProcessLoadedAchievements (IAchievement[] achievements) { if (achievements.Length == 0) { Debug.Log ("Error: no achievements found"); } else { Debug.Log ("Got " + achievements.Length + " achievements"); } } Let me know. (I can explain it to you in Spanish too if you want) Saludos! A: I follow this tutorial: google tutorial in GitHub (README) and the tutorial don't say I must implement that method, in fact, when I read it, I understand these method are part of the engine. Here is my new code: using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; using UnityEngine.Advertisements; using System.Collections; using System.Collections.Generic; using GooglePlayGames; using UnityEngine.SocialPlatforms; using GooglePlayGames.BasicApi; using UnityEngine.Analytics; public class Menu : MonoBehaviour { public Text record; public GameObject test; /** Indicador del jugador de que no ha iniciado sesión, y no podrá acceder al ranking ni a los logros. */ public GameObject signIn; void Start() { PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder ().Build (); PlayGamesPlatform.InitializeInstance(config); GooglePlayGames.PlayGamesPlatform.DebugLogEnabled = true; PlayGamesPlatform.Activate(); Advertisement.Initialize ("NUMBER", true); test.SetActive (false); //EDIT: SignIn (); if (PlayerPrefs.HasKey("record")) { record.text = "Record actual: " + PlayerPrefs.GetInt("record"); Analytics.CustomEvent ("Start Play", new Dictionary<string, object>{ { "Record", PlayerPrefs.GetInt("record")} }); } else { record.text = "Consigue un record!!"; } } public void OnPlay() { ShowAd (); SceneManager.LoadScene("Jugar"); Time.timeScale = 0; } public void OnArchievements() { if (Social.Active.localUser.authenticated) { Social.Active.ShowAchievementsUI (); } else { Social.Active.localUser.Authenticate ((bool success) => { if (success) { Social.Active.ShowAchievementsUI (); } }); } } public void OnMatching() { if (Social.Active.localUser.authenticated) { Social.Active.ShowLeaderboardUI (); } else { Social.Active.localUser.Authenticate ((bool success) => { if (success) { Social.Active.ShowLeaderboardUI (); } }); } } public void OnExit() { Analytics.CustomEvent ("Stop Play", new Dictionary<string, object>{ { "Record", PlayerPrefs.GetInt("record")} }); Application.Quit(); } public void SignIn() { Social.Active.localUser.Authenticate (ProcessAuthentication); } public void Later() { signIn.SetActive (false); } public void ShowAd() { if (Advertisement.IsReady()) { Advertisement.Show(); } } //EDIT: void ProcessAuthentication (bool success) { if (true == success) { Debug.Log ("AUTHENTICATED!"); if (Social.Active.localUser.authenticated) { Social.Active.LoadAchievements (ProcessLoadedAchievements); Social.Active.LoadScores (Fireball.GPGSIds.leaderboard_ranking, ProcessLoadedScores ); if (PlayerPrefs.HasKey ("record")) { Social.Active.ReportScore (PlayerPrefs.GetInt ("record"),Fireball.GPGSIds.leaderboard_ranking, (bool report) => { }); } signIn.SetActive (false); test.SetActive (true); } } else { Debug.Log("Failed to authenticate"); signIn.SetActive (true); } } void ProcessLoadedAchievements (IAchievement[] achievements) { if (achievements.Length == 0) { Debug.Log ("Error: no achievements found"); } else { Debug.Log ("Got " + achievements.Length + " achievements"); } } void ProcessLoadedScores (IScore[] scores) { if (scores.Length == 0) { Debug.Log ("Error: no scores found"); } else { Debug.Log ("Got " + scores.Length + " scores"); } } } EDIT: Again in the editor I can't authenticate (in my device it fail too), I really don't understand the cause... Here the debug log (I active it, may can help): DEBUG: Activating PlayGamesPlatform. DEBUG: PlayGamesPlatform activated: GooglePlayGames.PlayGamesPlatform. DEBUG: Creating platform-specific Play Games client. DEBUG: Creating IPlayGamesClient in editor, using DummyClient. DEBUG: Received method call on DummyClient - using stub implementation. The last message, is when I try to authenticate, maybe you know the problem with the debug log. PD: I read de documentation you send me, but is oriented to GameCenter (iOS), but I understand now more thing about that, really thanks. Again thanks a lot for your time.
{ "language": "en", "url": "https://stackoverflow.com/questions/37987556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Import Excel sheet into database using MVC .net Web Application Im new to programming and i am trying to import excel sheet into my database using mvc. I am able to import into my database but i need to find out how do i add validation for example email and duplicates. It seems like if i upload the same excel sheet twice, the data will be imported twice into my database. Also i would like to display the number of rows on the web page updated after importing . How do i do it ? This is my controller code. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Data.OleDb; using System.IO; namespace excelimport.Controllers { public class HomeController : Controller { // GET: /Home/ SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString); OleDbConnection Econ; public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(HttpPostedFileBase file) { string filename = Guid.NewGuid() + Path.GetExtension(file.FileName); string filepath = "/excelfolder/" + filename; file.SaveAs(Path.Combine(Server.MapPath("/excelfolder"), filename)); InsertExceldata(filepath, filename); return View(); } private void ExcelConn(string filepath) { string constr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", filepath); Econ = new OleDbConnection(constr); } private void InsertExceldata(string fileepath, string filename) { string fullpath = Server.MapPath("/excelfolder/") + filename; ExcelConn(fullpath); String query = string.Format("Select * from [{0}]", "Sheet1$"); OleDbCommand Ecom = new OleDbCommand(query, Econ); Econ.Open(); DataSet ds = new DataSet(); OleDbDataAdapter oda = new OleDbDataAdapter(query, Econ); Econ.Close(); oda.Fill(ds); DataTable dt =ds.Tables[0]; SqlBulkCopy objbulk = new SqlBulkCopy(con) { DestinationTableName = "UserInformation" }; objbulk.ColumnMappings.Add("Email", "Email"); objbulk.ColumnMappings.Add("Name", "Name"); objbulk.ColumnMappings.Add("PhoneNo", "PhoneNo"); objbulk.ColumnMappings.Add("Address", "Address"); objbulk.ColumnMappings.Add("ZipCode", "ZipCode"); objbulk.ColumnMappings.Add("Country", "Country"); objbulk.ColumnMappings.Add("State", "State"); objbulk.ColumnMappings.Add("City", "City"); con.Open(); objbulk.WriteToServer(dt); con.Close(); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/53333935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: remove from a draggable when being dragged - jquery I have this site which is a grid of draggable links. When dragged a drop down appears where the user can drag to trash the draggable. Problem is that when they drop it on the droppble, the link opens up! Which is not supposed to be happening. I've tried adding ui.draggable.find('a').removeAttr('href') to my handleDropEvent function, but it didn't help. Any javascript geniuses care to take a look? EDIT I tried also adding : ui.draggable.find('a').click(function(e) { e.preventDefault(); to the following like so: $('.draggable').draggable({ start: function( event, ui ) {$('#dropdownAddTile').slideDown();ui.draggable.find('a').click(function(e) { e.preventDefault(); });}, stop: function() {$('#dropdownAddTile').slideUp();}, containment: '#container', snap:'.droppable', snapMode:'inner', revert:'invalid',snapTolerance: 32}); ANOTHER EDIT I should point out (just figured out) that I have the draggable class applied to an href like this : <a href class="draggable"> So solutions so far have caused the problem where we remove the link and it stops the draggable from being draggable! Is there another way? A: When they are dragged set a click handler to prevent the default action, like so: ui.draggable.find('a').click(function(e) { e.preventDefault(); }); As I said, do it when they are dragged in case it's too late when doing it in the dropped event. UPDATE: $('.draggable').draggable({ start: function( event, ui ) { $('#dropdownAddTile').slideDown(); ui.draggable.find('a').click(function(e) { e.preventDefault(); }); }, stop: function() { $('#dropdownAddTile').slideUp(); }, containment: '#container', snap:'.droppable', snapMode:'inner', revert:'invalid', snapTolerance: 32 }); so you can call ui.draggable.find('a').click(function(e) { e.preventDefault(); A: The issue didn't arise in Chrome, Firefox, or IE10 but it did happen in IE9 and lower. My advice would be to run preventDefault on the event. Using your code, function handleDropEvent( event, ui ) { event.preventDefault(); var draggable = ui.draggable; var droppable = $(this); var droppableId = $(this).attr("id"); var draggableId = ui.draggable.attr("id"); $('.draggable').draggable({containment: '#container', snap:'.droppable', snapMode:'inner', revert:'invalid',snapTolerance: 32}); $('.droppable').droppable({drop: handleDropEvent, accept: function(e){if(e.hasClass('draggable')) { if (!$(this).hasClass('occupied')) {return true; }}}}); var initPosit = ui.draggable.parent().attr('id'); $.post("tiles/updateTilePosition", { draggableId:draggableId, droppableId: droppableId }).done(function(data) { }) $(this).addClass('occupied'); ui.draggable.parent().removeClass('occupied'); if($(ui.draggable).parent() !==$(this)){ $(ui.draggable).appendTo($( this )); } } Also, if you view your source code, everything is encoded (apostrophes, quotes, etc.) Not sure how that happened but I'd fix that. A: If I understood correctly you just want the a link not to be drag able right? Do this: <a href="#test" draggable="false">Test</a> This is basically how you disable the drag function idk why everyone writes such a long code for this.... A: Try setting the onclick to return false;
{ "language": "en", "url": "https://stackoverflow.com/questions/15705863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I remove extra whitespaces created by iniparser? Recently I'm taking iniparser as primary choice. However, with its API creating too many whitespaces resulting in waste of memory. For example, iniparser_set() will create /*test.ini*/ [section] key = value instead /*test.ini*/ [section] key = value From the point of embedded system's view, removing those extra whitespaces is a great thing for saving memory space. So, how to fix it? A: As per the source code of iniparser (https://github.com/ndevilla/iniparser/blob/deb85ad4936d4ca32cc2260ce43323d47936410d/src/iniparser.c#L312): in iniparser_dumpsection_ini function, there is this line: fprintf(f, "%-30s = %s\n", d->key[j]+seclen+1, d->val[j] ? d->val[j] : ""); As you can see, key is printed with format specifier %-30s which is probably causing this issue. So, you can clone the repo source code and make the changes. Example, replace format specifier with %s, like: fprintf(f, "%s = %s\n", // CHANGE HERE d->key[j]+seclen+1, d->val[j] ? d->val[j] : "");
{ "language": "en", "url": "https://stackoverflow.com/questions/70445252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use replace regex in Komodo? I am trying to create a regex to find and replace (keep empty) different names in an txt file. I use Komodo, as it is part of the examen. Here the text sample: *Cassidy: What's your name again? Chrissie Watkins: Chrissie! Cassidy: Where are we going? Chrissie: Swimming! Cassidy: Slow up, slow down! I'm not drunk! Slow down! Wait I'm coming! I'm coming! I'm definitely coming! Wait, slow up! I can swim -- just can't walk or dress myself. Chrissie: Come on in the water! Cassidy: Take it easy. Take it easy. Chrissie: Oh! God help me! God! Argh! God help! Cassidy: I'm coming... I'm coming. Chrissie: It hurts! It hurts! Oh my god! God help me! God please help! Martin Brody: How come the sun didn't use to shine in here. Ellen Brody: We bought the house in the fall, this is summer. Ellen: Somebody feed the dogs, huh? Martin: Right. Ellen: See the kids? Martin: They must be in the backyard. Ellen: In Amity, you say: yahd. The text must be cleaned up, meaning all names at the beginning of each line must be deleted (replaced by nothing). If I use this: \w.¨: Also names in texts (not the person speaking) are gone / deleted. Is it possible to use just one regular expression for cleaning up? A: You may use (?m)^\*?[A-Z][\w' -]*:\s* See the regex demo Details * *(?m) - re.M flag, it makes ^ match start of a line *^ - start of a line *\*? - an optional * char *[A-Z] - an uppercase letter *[\w' -]* - 0 or more word chars, spaces, - or apostrophes *: - a colon *\s* - 0+ whitespaces.
{ "language": "en", "url": "https://stackoverflow.com/questions/53621053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby on Rails tutorial Chapter 11: Rspec tests fail on follower/following section I'm working on Chapter 11 of Hartl's tutorial, trying to get the non-logged-in users in the Users controller visiting the followers and following page to pass. I'm running into an error where Rails would complain about an undefined admin? method despite it being only used in a User partial. Rails local server Rendered users/_user.html.erb (9.4ms) Rendered users/show_follow.html.erb within layouts/application (33.0ms) Completed 500 Internal Server Error in 43ms ActionView::Template::Error (undefined method `admin?' for nil:NilClass): 1: <li> 2: <%= gravatar_for user, size: 52 %> 3: <%= link_to user.name, user %> 4: <% if current_user.admin? && !current_user?(user) %> 5: | <%= link_to 'delete', user, method: :delete, 6: data: { confirm: 'Are you sure?' } %> 7: <% end %> app/views/users/_user.html.erb:4:in `_app_views_users__user_html_erb___4000670281664801561_70099451578240' app/views/users/show_follow.html.erb:25:in `_app_views_users_show_follow_html_erb__2024448610717183111_70099484108000' app/controllers/users_controller.rb:68:in `followers' RSpec failures 1) Authentication authorization for non-logged-in users in the Users controller visiting the following page Failure/Error: it { should have_selector('title', text: 'Login') } expected css "title" with text "Login" to return something # ./spec/requests/authentication_pages_spec.rb:122:in `block (6 levels) in <top (required)>' 2) Authentication authorization for non-logged-in users in the Users controller visiting the followers page Failure/Error: it { should have_selector('title', text: 'Login') } expected css "title" with text "Login" to return something # ./spec/requests/authentication_pages_spec.rb:127:in `block (6 levels) in <top (required)>' authorization_pages_spec.rb describe "authorization" do . . . describe "for non-logged-in users" do let(:user) { FactoryGirl.create(:user) } . . . describe "in the Users controller" do . . . describe "visiting the following page" do before { visit following_user_path(user) } it { should have_selector('title', text: 'Login') } end describe "visiting the followers page" do before { visit followers_user_path(user) } it { should have_selector('title', text: 'Login') } end end show_follow.html.erb <% provide(:title, @title) %> <div class="row"> <aside class="span4"> <section> <%= gravatar_for @user %> <h1><%= @user.name %></h1> <span><%= link_to "view my profile", @user %></span> <span><b>Posts:</b> <%= @user.posts.count %></span> </section> <section> <%= render 'shared/stats' %> <% if @users.any? %> <div class="user_avatars"> <% @users.each do |user| %> <%= link_to gravatar_for(user, size: 30), user %> <% end %> </div> <% end %> </section> </aside> <div class="span8"> <h3><%= @title %></h3> <% if @users.any? %> <ul class="users"> <%= render @users %> </ul> <%= will_paginate %> <% end %> </div> </div> _user.html.erb <li> <%= gravatar_for user, size: 52 %> <%= link_to user.name, user %> <% if current_user.admin? && !current_user?(user) %> | <%= link_to 'delete', user, method: :delete, data: { confirm: 'Are you sure?' } %> <% end %> </li> I tried copy and pasting all the problematic files from the tutorial itself to no avail. It's mentioned that by assigning the :admin attribute to the User class, a method admin? is made available to use. I'm guessing it's somehow I'm passing a nil object into the partials, but I'm having trouble debugging where exactly that's happening. A: Okay, I finally figured it out. I forgot to put the :following and :followers actions in the before_filter for :logged_in_user in the User controller. class UsersController < ApplicationController before_filter :logged_in_user, only: [:index, :edit, :update, :destroy, :following, :followers] That took a while. A: Your code is checking current_user.admin? and changing what is displayed based on that. However from the title of your specs it appears that you are testing the behaviour when a non logged in user visits the page: current_user will be nil Sounds like the if statement in the _user partial needs an extra condition to check that there is a logged in user before checking that that user is an admin A: Try looking in the users_controller, your code in the partials looks okay to me which means it's possibly something behind the scenes that is missing. The local server trace seems to point to line 68 and the followers method. Mine looks like this, fyi: def followers @title = "Followers" @user = User.find(params[:id]) @users = @user.followers.paginate(page: params[:page]) render 'show_follow' end Hope that helps. A: I also forgot to put the :following and :followers actions in the before_filter for :logged_in_user in the User controller, but I was curious about this error. Like Frederick Cheung points in is response there is bug in the code of the parcial: _user.html.erb. We should check if current_user is nil before calling the admin? method on it. So instead of: <% if current_user.admin? && !current_user?(user) %> you should have: <% if current_user && current_user.admin? && !current_user?(user) %> This removes the "undefined method admin?" error and gives us the correct test error: Expected response to be a <redirect>, but was <200> This last one we remove by putting the :following and :followers actions in the before_filter for :logged_in_user.
{ "language": "en", "url": "https://stackoverflow.com/questions/15874039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to create/add multiple tittles and border lines to one text table in Tableau Desktop I have a text table in Tableau Desktop that looks like this. I want to partition it to add multiple tittles with border lines to separate into three parts within one tableau sheet, expecting result to look like this. Any ideas on how to achieve that? or if it's even possible in Tableau Desktop? Version 2022.1.10
{ "language": "en", "url": "https://stackoverflow.com/questions/75174909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unable to call F# Extension in VB.Net Solved: IntelliSense just doesn't show the Extension! Lets say we got the following extension method in F#: [<Extension>] module Extension = [<Extension>] let Increment(value : System.Int32) = value + 1 In C# I can call it like this way: x.Increment(); //Result x=1 But the equivalent VB code to this returns an error, it doesn't find the extension method for the type integer: x.Increment() 'No method called "Increment()" for type Int32 While it's possible to call the method by the standard way: Increment(x) 'Works So where is the difference between handling VB and C# on calling F# code, why isn't the VB environment able to resolve the extension methods? A: If you build a regular F# library project namespace A open System.Runtime.CompilerServices [<Extension>] module Extension = [<Extension>] let Increment(value : System.Int32) = value + 1 and then refer to this library from VB project Imports A.Extension Module Module1 Sub Main() Console.WriteLine((1).Increment()) End Sub End Module then VB treats F# extension method as expected <Extension>Public Function Increment() As Integer and works correctly, giving 2 as output. A clean experiment does not indicate any VB-specific idiosyncrasy to F#-defined extension methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/17152187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Generic ListView Adapter I am trying to create a Custom Adapter which can handle any kind of layout to be inflated. By generic I mean any kind of data to be set in an adapter and any kind of a layout could be used with Event Listeners to be set for an item. For example: I have a contact list and a country list. The Contact list has four items in its layout i.e person image, name, number and a checkBox. The Country List contains a CountryName(TextView) and a checkbox. Is it possible for both to use the same adapter and that adapter handle all kind of items? I wish the tick images would reset after clicking on any item. A: If you have an List with different object that can be of different kinds and need different views to display. Do it that way: Let the object define the view by themselves. Implement an interface ViewProvider on every object. This interface should provide the method getView() which then can be called in the adapter. The adapter has now only to get the element out of the list full of ViewProviders and call the method getView to get the view. You will not have to worry about the recycling off the views as the views are stored in every ViewProvider and will be created only once. The update of the fields (if any) can then also be made on the Object side and not in the adapter. But you have to notify the adapter about the data change by calling notifyDataSetChanged()
{ "language": "en", "url": "https://stackoverflow.com/questions/11509572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why the return type of getchar() is int? I searched for the answer on Internet but I could not understand what is this 'EOF'? Please let me know from basic about what is getchar() and what are it's uses? Note that I am just a beginner of C language. A: In C there's really no difference between a char and an int. Even character literals, like e.g. 'A', are almost universally promoted to int. But the most important thing is that EOF is an int value. If char is unsigned (it's implementation-specific if char is signed or unsigned) then when the char value -1 is promoted to int it becomes 0x000000ff, which is very different from the int value -1 which is 0xffffffff (assuming normal two's complement systems).
{ "language": "en", "url": "https://stackoverflow.com/questions/60332668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: row layout not set on on Main Activity Recycler View I am just parse some data and display on my ListProperty Class. I am using RecyclerView and CardView as a row layout. Somehow all is working fine i don't see any error in verbose. But the Data and row layout dosent display in my main activity. Activity is showing blank. I am trying from hours but kind find the error. Please someone help My MainActivity.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin"> <android.support.v7.widget.RecyclerView android:id="@+id/cardList" android:layout_width="match_parent" android:layout_height="match_parent"/> </RelativeLayout> This is row.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" > <ImageView android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/imageViewFront" /> </LinearLayout> <LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_marginLeft="100dp" android:layout_height="wrap_content"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:text="New Text" android:textColor="#0055CC" android:id="@+id/textViewPropertyname" /> <TextView android:layout_marginTop="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Text" android:textColor="#0055CC" android:layout_columnWeight="1" android:id="@+id/textViewPropertyDescription"/> </LinearLayout> </android.support.v7.widget.CardView> </LinearLayout> This is myAdapter.java public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> { List<Bean> DataList; public MyAdapter(List<Bean> List){ super(); DataList = List; } public class MyViewHolder extends RecyclerView.ViewHolder { // each data item is just a string in this case public TextView propertyName; public TextView propertyDesc; public ImageView ImageFront; public MyViewHolder(View v) { super(v); propertyName = (TextView) v.findViewById(R.id.textViewPropertyname); propertyDesc = (TextView) v.findViewById(R.id.textViewPropertyDescription); ImageFront = (ImageView) v.findViewById(R.id.imageViewFront); } } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()). inflate(R.layout.list_card_view,parent,false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(MyAdapter.MyViewHolder holder, int position) { Bean bean = DataList.get(position); holder.propertyName.setText(bean.getPropertyName()); holder.propertyDesc.setText(bean.getPropertyDescription()); holder.ImageFront.setImageResource(R.drawable.agriculture); } @Override public int getItemCount() { return DataList.size(); } } And this is my MainActivity.java public class ListProperty extends AppCompatActivity { private RecyclerView mRecyclerView; private MyAdapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; Bean bean; AQuery aQuery; JSONObject jsonObject; List<Bean> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list_property); aQuery= new AQuery(getApplicationContext()); String URL = "http://192.168.0.107/propertyapp/service/simpleservice.php"; list = new ArrayList<Bean>(); mRecyclerView = (RecyclerView) findViewById(R.id.cardList); mRecyclerView.setHasFixedSize(true); mLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(mLayoutManager); mAdapter = new MyAdapter(list); mRecyclerView.setAdapter(mAdapter); aQuery.ajax(URL, JSONObject.class,new AjaxCallback<JSONObject>(){ @Override public void callback(String url, JSONObject object, AjaxStatus status) { try { bean = new Bean(); list = new ArrayList<Bean>(); String string = object.getString("data"); JSONArray jsonArray = new JSONArray(string); for (int i=0;i<jsonArray.length();i++) { jsonObject = jsonArray.getJSONObject(i); bean.setPropertyName("property_name"); bean.setPropertyDescription("property_desc"); list.add(bean); } } catch (JSONException e) { e.printStackTrace(); } } }); } } A: Try to remove parent LinearLayout. Because you have CardView which is acting as list item. Try this row.xml - <?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" > <ImageView android:layout_width="100dp" android:layout_height="100dp" android:id="@+id/imageViewFront" /> </LinearLayout> <LinearLayout android:orientation="vertical" android:layout_width="wrap_content" android:layout_marginLeft="100dp" android:layout_height="wrap_content"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:text="New Text" android:textColor="#0055CC" android:id="@+id/textViewPropertyname" /> <TextView android:layout_marginTop="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Text" android:textColor="#0055CC" android:layout_columnWeight="1" android:id="@+id/textViewPropertyDescription"/> </LinearLayout> </android.support.v7.widget.CardView> Hope it will help :) A: Just add notifyDataSetChanged() to your Activity as below: aQuery.ajax(URL, JSONObject.class,new AjaxCallback<JSONObject>(){ @Override public void callback(String url, JSONObject object, AjaxStatus status) { try { bean = new Bean(); list = new ArrayList<Bean>(); String string = object.getString("data"); JSONArray jsonArray = new JSONArray(string); for (int i=0;i<jsonArray.length();i++) { jsonObject = jsonArray.getJSONObject(i); bean.setPropertyName("property_name"); bean.setPropertyDescription("property_desc"); list.add(bean); } //here notify your adapter //is to Notify any registered observers that the data set has changed. mAdapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); } } }); A: Because on your callback you have created new instance of list list = new ArrayList<Bean>(); then in fact, the new created list and DataList in your adapter are pointing to 2 difference objects => calling notifyDataSetChanged here won't work. Try writing method updateData on MyAdapter and call it from your callback method public void updateData(List<Bean> List){ DataList = List; notifyDataSetChanged(); } On your callback: aQuery.ajax(URL, JSONObject.class,new AjaxCallback<JSONObject>(){ @Override public void callback(String url, JSONObject object, AjaxStatus status) { try { bean = new Bean(); list = new ArrayList<Bean>(); String string = object.getString("data"); JSONArray jsonArray = new JSONArray(string); for (int i=0;i<jsonArray.length();i++) { jsonObject = jsonArray.getJSONObject(i); bean.setPropertyName("property_name"); bean.setPropertyDescription("property_desc"); list.add(bean); } // update data mAdapter.updateData(list); } catch (JSONException e) { e.printStackTrace(); } } });
{ "language": "en", "url": "https://stackoverflow.com/questions/38119908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change the text of textview more than one Hi and sorry for my English! :) I want to change the text of Text View after 3 second by random number but it's just show last number and I didn't see last numbers in Text View What should I do? Thanks... :) import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.widget.TextView; public class TestActivity extends Activity { int rand; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final TextView txtShow = (TextView) findViewById(R.id.txtShow); Handler handler = new Handler(); for (int i = 0; i < 5; i++) { rand = (int) (Math.random() * 9); handler.postDelayed(new Runnable() { @Override public void run() { txtShow.setText("" + rand); } }, 3000); } } } A: you don't need a loop. In this case you can use postDealyed to repost a runnable in the ui thread queue: public class TestActivity extends Activity { int rand; int counter; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final TextView txtShow = (TextView) findViewById(R.id.txtShow); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { if (counter > 4) { handler.removeCallbacks(this); return; } ++counter; rand = (int) (Math.random() * 9); txtShow.setText("" + rand); handler.postDelayed(this, 3000); } }, 3000); } } When counter reaches 5, removeCallbacks cancel all the runnables still present in the handler queue and returns. Otherwise counter is increased and handler.postDelayed add the runnable to the handler queue, A: I think this should work. private Handler handler; private TextView txt; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); handler = new Handler(); txt = (TextView) findViewById(R.id.txt); new Thread(new Task()).start(); } class Task implements Runnable { @Override public void run() { for (int i = 0; i <= 5; i++) { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } handler.post(new Runnable() { @Override public void run() { int rand = (int) (Math.random() * 9); txt.setText("" + rand); } }); } } } A: The problem is that all of the Runnables that are changing the TextView are executing right after one another; the change is so fast that you cannot see the intermediate values and instead only see the final value. To fix your problem change the delay in postDelayed() from 3000 to 3000 * i. This will ensure that the updates are spaced with 3 seconds between each one instead of just all executing 3 seconds after onCreate() finishes (as it is now). For things like this you may also want to look into Timer (http://developer.android.com/reference/java/util/Timer.html)
{ "language": "en", "url": "https://stackoverflow.com/questions/29433116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: 'Access attribute not allowed in generic body with external package I'm having some issues with generics in Ada. Given the below example, gnatmake results in: g_package.adb:13:33: 'Access attribute not allowed in generic body g_package.adb:13:33: because access type "t_callback_p" is declared outside generic unit (RM 3.10.2(32)) g_package.adb:13:33: move 'Access to private part, or (Ada 2005) use anonymous access type instead of "t_callback_p" gnatmake: "g_package.adb" compilation error With the assumption that the external package cannot be changed, is there a way to solve this? I get the reason for the error message in the first place (compiler doesn't know the proper type of the generic package, but it's a bit annoying when the passed function in question doesn't touch any part of the generic..) g_package.adb with Ada.Text_IO; use Ada.Text_IO; with external; package body g_package is procedure quix (f : String) is begin Put_Line ("Does a thing"); end quix; procedure foo (bar : String) is begin Put_Line ("baz" & bar & Boolean'Image(flag)); external.procedure_f (quix'Access); end foo; end g_package; g_package.ads generic flag : Boolean; package g_package is procedure foo (bar : String); end g_package; external.ads package external is type t_callback_p is access procedure (s : String); procedure procedure_f (proc : t_callback_p); end external; A: You can (as mentioned in the error message) move the 'Access to the private part of the package spec: private with external; generic flag : Boolean; package g_package is procedure foo (bar : String); private procedure quix (f : String); quix_access : constant external.t_callback_p := quix'Access; end g_package; and the use the constant in the body: external.procedure_f (quix_access); A: There's no way to do this in Ada. If you wish to be non-portable and are using (as it appears) GNAT, you can use the GNAT-specific attribute 'Unrestricted_Access.
{ "language": "en", "url": "https://stackoverflow.com/questions/48174233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does insert invalidate the std::set reverse iterator My understanding is the iterators of associative containers are not invalidated during insert or erase (unless the node pointed by iterator is erased). But in the below program the insert seems to invalidate the iterator. Is my understanding wrong? typedef std::set<unsigned int> myset_t; int main(int argc, char **argv) { myset_t rs; myset_t::reverse_iterator rit; myset_t::reverse_iterator srit; int ii = 500; rs.insert(10); rs.insert(11); rs.insert(12); rs.insert(13); rs.insert(14); rs.insert(100000); rs.insert(102000); rs.insert(103000); rit = rs.rbegin(); while(rit != rs.rend()) { srit = rit; if (*rit < 100000) { cout << "bailing here " << *rit << endl; return 0; } rit++; cout << "Before erase " << *rit << endl; rs.erase(*srit); cout << "Before insert " << *rit << endl; rs.insert(ii); cout << "After insert " << *rit << endl; ii++; } cout << "Out of loop" << endl; } === The output is Before erase 102000 Before insert 102000 After insert 14 bailing here 14 ===== A: The promised behavior for iterators of a standard container does not hold for reverse iterators of that container. A reverse iterator actually stores, as a member, the normal (forward moving) iterator which comes after the element to which the reverse iterator refers when dereferenced. Then when you dereference the reverse iterator, essentially it decrements a copy of this stored normal iterator and dereferences that. So this is a problem: rit = rs.rbegin(); // rit stores rs.end() srit = rit; // srit also stores rs.end() rit++; // rit stores a normal iterator pointing to the last element rs.erase(*srit); // this deletes the last element, invalidating the normal // iterator which is stored in rit. Funnily enough, the // one stored in srit remains valid, but now *srit is a // different value Reverse iterators behave this way because there is no "before begin" iterator. If they stored the iterator to the element to which they actually refer, what would rs.rend() store? I'm sure there are ways around this, but I guess they required compromises which the standards committee was not willing to make. Or perhaps they never considered this problem, or didn't consider it significant enough.
{ "language": "en", "url": "https://stackoverflow.com/questions/19826255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Text transition on hover image I'am trying to set css transition on the text on hover image like this -> https://victorthemes.com/themes/glazov/portfolio-grid/ I tried to do this with cubic-bezier() function, but without result. Here's my code. * { margin: 0; padding: 0; border: 0; } .img__wrap { position: relative; height: 200px; width: 257px; } .img__description { position: absolute; top: 0; bottom: 0; left: 0; right: 0; background: rgba(29, 106, 154, 0.72); color: #fff; visibility: hidden; opacity: 0; transition: opacity .2s, visibility .2s; } .img__wrap:hover .img__description { visibility: visible; opacity: 1; } <div class="img__wrap"> <img class="img__img" src="http://placehold.it/257x200.jpg" /> <p class="img__description">Teext.</p> </div> Please give me some hints how to do this. A: I used transform: translate(); to move object. Play with cubic-bezier here to achieve perfect animation. But I used the same which was on the website you posted in example. Also I removed opacity, visibility * { margin: 0; padding: 0; border: 0; } .img__wrap { position: relative; height: 200px; width: 257px; } .img__description { position: absolute; top: 0; bottom: 0; left: 0; right: 0; background: rgba(29, 106, 154, 0.72); color: #fff; transform: translateX(-100%); transition: all 600ms cubic-bezier(0.645, 0.045, 0.095, 1.08); } .img__wrap:hover .img__description { transform: translate(0); } <div class="img__wrap"> <img class="img__img" src="http://placehold.it/257x200.jpg" /> <p class="img__description">Teext.</p> </div> A: Ok, first, I would suggest using "all" for the transition element instead of defining the same values for all of the proprieties you want to transition. transition: all .2s; Second, let's get the bezier right. I think this is close enough: cubic-bezier(1.000, 0.215, 0.355, 0.990) So the transition propriety should look like this: transition: all .2s cubic-bezier(1.000, 0.215, 0.355, 0.990); For the text animation I suggest using animate.css and use fadeInLeft. A: To darken the image, you need to change the opacity of it. To zoom the image, use a scale transform and to move the caption text, you need a translateX transform. Apply those css styles and their respective transitions (you need a transition in the image as well as in the text) and you're left with the following: * { margin: 0; padding: 0; border: 0; } .img__wrap { position: relative; background: black; height: 200px; width: 257px; overflow: hidden; } .img__img { opacity: 1; transition: all 0.2s; } .img__description { position: absolute; color: #fff; transition: all .2s; left: 15px; right: 0; bottom: 15px; transform: translateX(-100%); } .img__wrap:hover .img__img { opacity: 0.5; transform: scale(1.2); } .img__wrap:hover .img__description { transform: translateX(0); } <div class="img__wrap"> <img class="img__img" src="http://placehold.it/257x200.jpg" /> <p class="img__description">Teext.</p> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/53197474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Delphi DLL Modal Form causes AV on Second Call I am trying to show a modal (FMX) form from a DLL. Eventually this will be ported to OSX so I'm trying to keep the 'Windows' code to a minimum. Based on what's in the forum I have tried to keep the code as simple possible. I know that the first time showmodal is called, the code works as expected, but if I subsequently call the DLL function, I get an AV trying to create the form. I then tried to (without exiting the function) create and free the form several times, this works without issue. And it works if I call the function, create and free the form and DO NOT showmodal. In all my tests, if I showmodal I get the AV trying to create the form the second time and the application hangs. Of course, if I just show the form I do not get the issue, ie. I can create the form, show it and free it in a loop and it works fine. The issue is of course that the code just continues through destroying the form and I need the form to be modal. THE DLL EMPSECURE_UI.DLL function dAbout_UI:boolean; {$IFDEF MSWINDOWS}stdcall{$ELSE}cdecl{$ENDIF} export; var dAbout: TfAbout; begin try try Result := True; dAbout := TfAbout.Create(nil); dAbout.Showmodal; except Result := False; end; finally FreeandNil(dAbout); end; The UNIT in the ABOUT Form procedure TfAbout.bOKClick(Sender: TObject); begin ModalResult := mrOK; Close; end; procedure TfAbout.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := System.UITypes.TCloseAction.caFree; end; The Test program that calls the function in the DLL uTESTEMPSECURE_UI.pas, ie. the main program, the simple call to the function that displays the modal form: const {$IFDEF MSWINDOWS} EMPSecureUI = 'empsecure_ui.dll'; {$ENDIF MSWINDOWS} {$IFDEF MACOS} EMPSecureUI = 'libempsecure_ui.dylib'; {$ENDIF MACOS} // EMPSecure_UI Functions function dAbout_UI: boolean; {$IFDEF MSWINDOWS}stdcall{$ELSE}cdecl{$ENDIF}; external EMPSecureUI; procedure TForm1.Button1Click(Sender: TObject); begin dAbout_UI; end; So the first time I run this code and call the function which shows the modal form it works as expected, a modal form is shown. When I click OK on the form, the form is freed and control is returned to the main test program. This is exactly as expected. If I then execute a second call to the DLL function an AV occurs when trying to create the form the second time. IF, OTOH, the form is simply shown (not modal), no AV occurs when I try to create the form a second or subsequent time.
{ "language": "en", "url": "https://stackoverflow.com/questions/57228715", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DateTime::__construct(): Failed to parse time string (//) at position 0 (/): Unexpected character Could not pass date to MySQL using php POST method. Got the error as given in the title. Here is my code. <code> date_default_timezone_set("Asia/Kolkata"); $dd = substr($dob,0,2)."/"; $mm = substr($dob,3,2)."/"; $yyyy = substr($dob,6,4); $fd = $yyyy.$mm.$dd; $date = new DateTime($fd); $formDateConverted = $date->format('Y-m-d'); <code> A: Are you sure you are getting data ? Your substr() must be returning empty strings. You are adding a slash to your day and month and putting them back together in the wrong order. Just run your code with a fixed string: $dob = 'dd/mm/yyyy'; $dd = substr($dob,0,2)."/"; $mm = substr($dob,3,2)."/"; $yyyy = substr($dob,6,4); $fd = $yyyy.$mm.$dd; var_dump($fd); Result: string(10) "yyyymm/dd/" To me, $dob is clearly empty, as all three variables resulting from the substr() are as well, except for the slashes you add back, which is what you get on the error. Run the code again with an empty variable and you'll get: string(2) "//". Once you fix your $dob issue, you can use the DateTime class directly as suggested by Chayan: $date = DateTime::createFromFormat('d/m/Y', $dob); echo $date->format('Y-m-d'); A: By default PHP can't parse date having '/' in it. Use DateTime::createFromFormat function. $date = DateTime::createFromFormat('Y/m/d', $fd); echo $date->format('Y-m-d');
{ "language": "en", "url": "https://stackoverflow.com/questions/52579952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Compare one col with another containing multiple entries We need to compare one col with another in a df and identify if the entry from col"a" matches any of the entries in col"b". The result would be a new col with T = match or F = no match. # task df df <- data.frame( a = c("ABC", 'ABB', 'ACC', 'AAG'), b = c("XXC TTZ", "XCT ABB", "TTG WHO ACC", 'AAG') ) # expected result df <- data.frame( a = c("ABC", 'ABB', 'ACC', 'AAG'), b = c("XXC", "XCT ABB", "TTG WHO ACC", 'AAG'), match = c("F", "T", "T", "T") ) I just come out of one year clinical rotation so my coding got a bit rusty. Could not find an answer here, excuse the hustle if this has been asked before. I guess the solution is rather straight forward but I can't wrap my head around it. Thanks a lot for helping (dplyr solutions much appreciated). A: Use str_detect from stringr which is vectorized for both string and pattern library(stringr) library(dplyr) df %>% mutate(match = str_detect(b, a)) a b match 1 ABC XXC FALSE 2 ABB XCT ABB TRUE 3 ACC TTG WHO ACC TRUE 4 AAG AAG TRUE A: A base R option transform( df, match = mapply(grepl, a, b, USE.NAMES = FALSE) ) gives a b match 1 ABC XXC TTZ FALSE 2 ABB XCT ABB TRUE 3 ACC TTG WHO ACC TRUE 4 AAG AAG TRUE
{ "language": "en", "url": "https://stackoverflow.com/questions/70869912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: im getting a error message parse error: syntax error, unexpected " I get this error can someone help please Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C:\Users\packardbell\Desktop\hdd\htdocs\qr\index.php on line 217 this is line 217 $username = $_REQUEST['username']; $password = $_REQUEST['pass']; $good=0; if(isset($username) && isset($password)) A: If what you are using being your actual code that you posted in a comment, you're missing a closing brace } and one too many after mysqlerror()); <= Consult "footnotes" about this. Your code from a comment: $db_selected = mysql_select_db('qrcodes'); if(!$db_selected) { die ('cant\'t connect :' . mysqlerror()); } } else { this is line 217 $username = $_REQUEST['username']; $password = $_REQUEST['pass']; Sidenote: You have mysqlerror which should read as mysql_error as per the manual New code: $db_selected = mysql_select_db('qrcodes'); if(!$db_selected) { die ('cant\'t connect :' . mysql_error()); } else { $username = $_REQUEST['username']; $password = $_REQUEST['pass']; } Footnotes: I agree with Andy Lester's comment in regards to actual errors coming from a line or lines further above. Error messages pointing to a certain line number, doesn't necessarily mean it's on "that" line. Showing full code will take the guesswork out of things, however from what you did post in your comment, it's a bracing mismatch issue, and using mysqlerror instead of mysql_error (you forgot the underscore between mysql and error) would have provided more information which failed in doing so because of it. mysql_* functions deprecation notice: http://www.php.net/manual/en/intro.mysql.php This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API. These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/. Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
{ "language": "en", "url": "https://stackoverflow.com/questions/22816318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Discord.js how to delete a message if they have too many capital letters I want to block my user from using too many capital letters in the same message (i.e typing in full CAPS LOCK). I tried this, but it doesn't seem to work if they put spaces between capital letters; here is my current code: client.on("message", async (msg) => { let sChannel = msg.guild.channels.find((c) => c.name === "guard-log"); if (msg.channel.type === "dm") return; if (msg.author.bot) return; if (msg.content.length > 15) { if (db.fetch(`capslock_${msg.guild.id}`)) { let caps = msg.content.replace(" ", "").toUpperCase(); if (msg.content == caps) { if (!msg.member.hasPermission("ADMINISTRATOR")) { if (!msg.mentions.users.first()) { msg.delete(); let embed = new Discord.RichEmbed() .setColor(0xffa300) .setFooter("Retro Guard", client.user.avatarURL) .setTitle("Caps-lock Engel") .setDescription("Fazla caps lock kullanımı yakalandı!") .addField("Kanal Adı", msg.channel.name, true) .addField( "Kişi", "Kullanıcı: " + msg.author.tag + "\nID: " + msg.author.id, true ) .addField("Engellenen mesaj", "```" + msg.content + "```", true) .setTimestamp(); sChannel.send(embed); return msg.channel .send(`${msg.author} fazla caps kullanıyorsun.`) .then((m) => m.delete(5000)); } } } } } }); A: Use .toUpperCase() on each letter and compare it to the letter capitalized, if it is the same, then it's in capital. Otherwise it's not, you don't actualy need any databases. Try following this code: client.on("message", async msg => { let sChannel = msg.guild.channels.find(c => c.name === "guard-log"); if (msg.channel.type === "dm" || msg.author.bot || msg.content.length < 15) return; // Use `||` (OR) to make it cleaner. let non_caps, caps; // Create the variables. for (x=0;x<msg.content.length;x++) { if (msg.content[x].toUpperCase() === msg.content[x]) caps++; else non_caps++; } // `caps` is the amount of capital letters, while `non_caps` is the amount of non-capital letters. This checks for each letter of the message and gets the amount of `caps` and `non_caps`. const textCaps = (caps / message.content.length) * 100; // Gets a percentage of the capital letters. if (textCaps >= 60 && !msg.member.permissions.has('ADMINISTRATOR')) { // If the capital letters is over or equals to 60% of the message, // and if the user isn't an ADMINISTRATOR, then... let embed = new Discord.RichEmbed() .setColor(0xffa300) .setFooter('Retro Guard', client.user.avatarURL) .setTitle("Caps-lock Engel") .setDescription("Fazla caps lock kullanımı yakalandı!") .addField("Kanal Adı", msg.channel.name, true) .addField('Kişi', 'Kullanıcı: '+ msg.author.tag +'\nID: '+ msg.author.id, true) .addField('Engellenen mesaj', "```" + msg.content + "```", true) .setTimestamp() sChannel.send(embed); msg.delete(); // Deletes the capped message. return msg.reply(`fazla caps kullanıyorsun.`) // `message.reply()` mentions the user that sent the message and is cleaner. .then(m => m.delete(5000)) } }) Do be careful, since this will delete the message if they put too much caps, including them quoting someone, whether they mean it or not. If you still don't understand, here are some reference: * *How can I test if a letter in a string is uppercase or lowercase using JavaScript?
{ "language": "en", "url": "https://stackoverflow.com/questions/63820651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Android Kotlin - Unit test a delayed coroutine that invokes a lambda action when delay is finished Ive been struggling with this for quite some time now, perhaps someone could help... I have this function in my class under test: fun launchForegroundTimer(context: Context) { helper.log("AppRate", "[$TAG] Launching foreground count down [10 seconds]") timerJob = helper.launchActionInMillisWithBundle(Dispatchers.Main, TimeUnit.SECOND.toMillis(10), context, this::showGoodPopupIfAllowed) } So in that function, I first write to some log and then I call a coroutine function that expects a Dispatcher param, how long to wait before running the action, Any object that I would like to pass on to the action and the actual action function that is invoked when time has passed. So in this case, the this::showGoodPopupIfAllowed which is a private method in the class, gets called when the 10,000 ms have passed. Here is that function: private fun showGoodPopupIfAllowed(context: Context?) { if (isAllowedToShowAppRate()) { showGoodPopup(context) } } In that first if, there are a bunch of checks that occur before I can call showGoodPopup(context) Now, here is the helper.launchActionInMillisWithBundle function: fun <T> launchActionInMillisWithBundle(dispatcher: CoroutineContext, inMillis: Long, bundle: T, action: (T) -> Unit): Job = CoroutineScope(dispatcher).launchInMillisWithBundle(inMillis, bundle, action) And here is the actual CoroutineScope extension function: fun <T> CoroutineScope.launchInMillisWithBundle(inMillisFromNow: Long, bundle: T, action: (T) -> Unit) = this.launch { delay(inMillisFromNow) action(bundle) } What I am trying to achieve is a UnitTest that calls the launchForegroundTimer function, calls the helper function with the appropriate arguments and also continue through and call that lambda showGoodPopupIfAllowed function where I can also provide mocked behaviour to all the IF statments that occur in isAllowedToShowAppRate. Currently my test stops right after the launchActionInMillisWithBundle is called and the test just ends. I assume there is no real call to any coroutine because I am mocking the helper class... not sure how to continue here. I read a few interesting articles but none seems to resolve such state. My current test function looks like this: private val appRaterManagerHelperMock = mockkClass(AppRaterManagerHelper::class) private val timerJobMock = mockkClass(Job::class) private val contextMock = mockkClass(Context::class) @Test fun `launch foreground timer`() { every { appRaterManagerHelperMock.launchActionInMillisWithBundle(Dispatchers.Main, TimeUnit.SECOND.toMillis(10), contextMock, any()) } returns timerJobMock val appRaterManager = AppRaterManager(appRaterManagerHelperMock) appRaterManager.launchForegroundTimer(contextMock) verify(exactly = 1) { appRaterManagerHelperMock.log("AppRate", "[AppRaterManager] Launching foreground count down [10 seconds]") } } I'm using mockk as my Mocking lib. AppRaterManager is the class under test I'd like to also mention that, in theory I could have moved the coroutine invocation outside the class under test. So an external class like activity.onResume() could launch some sort of countdown and then call directly a function that checks showGoodPopupIfAllowed(). But currently, please assume that I do not have any way to change the calling code so the timer and coroutine should remain in the class under test domain. Thank you! A: Alright, I read a bit deeper into capturing/answers over at https://mockk.io/#capturing and saw there is a capture function. So I captured the lambda function in a slot which enables me invoke the lambda and then the actual code continues in the class under test. I can mock the rest of the behavior from there. Here is my test function for this case (for anyone who gets stuck): @Test fun `launch foreground timer, not participating, not showing good popup`() { val slot = slot<(Context) -> Unit>() every { appRaterManagerHelperMock.launchActionInMillisWithBundle(Dispatchers.Main, TimeUnit.SECOND.toMillis(10), contextMock, capture(slot)) } answers { slot.captured.invoke(contextMock) timerJobMock } every { appRaterManagerHelperMock.isParticipating() } returns false val appRaterManager = AppRaterManager(appRaterManagerHelperMock) appRaterManager.launchForegroundTimer(contextMock) verify(exactly = 1) { appRaterManagerHelperMock.log("AppRate", "[AppRaterManager] Launching foreground count down [10 seconds]") } verify(exactly = 1) { appRaterManagerHelperMock.isParticipating() } verify(exactly = 0) { appRaterManagerHelperMock.showGoodPopup(contextMock, appRaterManager) } } So what's left now is how to test the coroutine actually invokes the lambda after the provided delay time is up.
{ "language": "en", "url": "https://stackoverflow.com/questions/70904977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Changing the working directory for a process remotely I've got an application that has a bug right now, but we're unable to update the end-user to get the fix out. What a possible workaround would be is to change the working directory to the application's install directory, but from what I can tell, there's no way to do that outside of the program itself. Is there some sort of Windows API call that can change other processes' working directories, or is that not available due to security issues? I figure it's not possible. A: You can change the directory that it initially starts in with a shortcut. If that is not enough, I don't believe what you want is possible without injecting a custom dll into the process after the fact. A: Why do you want to change the working directory? Maybe you could modify the PATH environment variable in some way to change the order of directories your app searches for files.
{ "language": "en", "url": "https://stackoverflow.com/questions/2539675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Content in scrollview as a list item disappears when scrolling (swiftui), why? Solution by @Asperi, ScrollView().id(UUID().uuidString). There is a scrollview in the list item, when I scroll the list, the content in scrollview disappears. I think the issue is about scrollview & list reusable item conflict. If I remove scrollview(just hstack{}), nothing disappears. So I think it's scrollview's issue. Any ideal? struct ContentView: View { var body: some View { List { ForEach(0...100, id: \.self) { _ in ItemView().padding() } } } } struct ItemView: View { var body: some View { VStack(alignment: .leading) { Text("Tag list:") ScrollView(.horizontal, showsIndicators: false) { HStack { ForEach(0...8, id: \.self) { _ in TagView1() } } }.id(UUID().uuidString) /// <- fix } } } struct TagView1: View { var body: some View { Text("Tag\(String(UUID().uuidString.prefix(5)))") .foregroundColor(.secondary) .padding(.horizontal, 2) .background(RoundedRectangle(cornerRadius: 4).stroke(Color.secondary.opacity(0.5))) .padding(1) } } A: If I correctly understood what disappears (I assume you meant list rows on vertical scrolling), then yes it is due to List reuse/cache optimisation issue. The following approach should work (tested with Xcode 11.2 / iOS 13.2) struct ItemView: View { var body: some View { VStack { Text("Tag list:") ScrollView(.horizontal, showsIndicators: false) { HStack { ForEach(0...8, id: \.self) { _ in TagView().padding() } } }.id(UUID().uuidString) // << here is a fix ! } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/59810913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Swift - How to correctly set up a Weak Variable I have an app with a lot of Astronomical calculations in them. For sanity they are separated into individual methods/functions. Run individually there are no memory runaways. HOWEVER when I need to calculate something complex like the angle of incidence of the sun's rays to any place on the Earth I have to call 19 methods in a row and the memory usage goes through the roof. Clearly variables are still live so the ARC can't evaporate them. So I presumed the solution was to create a weak link. If I change my call from var angleIncidence = Celestial().calculateAngleIncidence(....) to weak var angleIncidence = Celestial().calculateAngleIncidence(....) I get a "Weak cannot be applied to a non class type Double". I am clearly being too naive. A: Doubles are not objects, so referring to them as strong and weak does not make sense because they do not have reference counts. In practice, they obey the typical rules of variable scope. However, they should really not be a cause for significant memory usage, unless you are using very large arrays of them. My feeling is that something else is probably going on - probably to do with other data types present and how data is being passed between the functions.
{ "language": "en", "url": "https://stackoverflow.com/questions/32841544", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ibm-cloud-private dashboard first record does not look like a TLS handshake I'm trying to use ibm-private-cloud dashboard to install ibm-chart. And after selecting any chart, and proceed to configure, I'm pressing "install". Then i got the following error in the bottom of the page: Internal service error : rpc error: code = Internal desc = connection error: desc = "transport: authentication handshake failed: tls: first record does not look like a TLS handshake" Does anybody have a solution? A: May be try to use http_s_:// when making api requests or opening the web-interface
{ "language": "en", "url": "https://stackoverflow.com/questions/51078340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python 3 taking multiple data types in input, separated by space So i need to find a way to take multiple data types as an input and store them in variables. Lets say i have 3 variables, each of them should store a fixed data type a - float b - str c - int and if the user enters a wrong, he will be asked to type again. The user will enter all of them, separated by space but i can't think of a way to store them in the variables, while keeping the data type. I've tried with .split(), but it just transforms them into strings. It's probably something quite obvious, but can't figure it out right now. Thanks in advance! A: Maybe: def myfucn(vars): vars = vars.split() try: float(vars[0]) if not "." in vars[0]: raise Exception("First var should be INT not Float") except ValueError: print("Error not Float found") try: int(vars[2]) except ValueError: print("Error Int no found") #answer a_float, b_str, c_int = vars print(" Yes ") greetings A: You are on the right track if the split() function. The problem is that when you say that user will give three values separated by ' ', you are taking in a string. The following is a string: '34.44 35.45 5' Maybe what you can do is after using split, you can cast each returned item to a variable. If you still need to check the type of variable, you can use the type() function. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/47024444", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Generating every outcome possible when parsing a list : element(N, L,X) I am trying to implement a simple element(N,L,X) predicate, where L is a list, X an element of the list, and N the position of this element in the list. I want to be able to do that : element(3, [a,b,c,d,e], X). yes : X=c. element(N, [a,b,c,d,e], X). yes : { N=1, X=a}; { N=2, X=b}; ... { N=5, X=e}; I am sure I have seen this somewhere, but I can't find it. Thanks. A: Since you're trying to describe a relation between a list, a potential element of that list and its position, why not give the predicate a more descriptive name, e.g. list_element_position/3. Then consider what the relation should describe. Basically there are two cases: 1) The head of the list matches the element. In that case you already know a position for that element. But there might be other occurrences as well, so: 2) Regardless whether the head matches the element or not, we should take a look at the tail of the list as well, since there might be further occurrences. An accumlator can be used to count the positions. I take it from your first example that you'd like to start counting at 1. Putting all that together you could write something like: list_element_position(L,E,P) :- list_element_position_(L,E,P,1). % start counting at 1 list_element_position_([X|Xs],X,P,P). % case 1) list_element_position_([X|Xs],Y,R,P0) :- % case 2) P1 is P0+1, list_element_position_(Xs,Y,R,P1). Your example queries: ?- list_element_position([a,b,c,d,e],E,3). E = c ? ; no ?- list_element_position([a,b,c,d,e],E,X). E = a, X = 1 ? ; E = b, X = 2 ? ; E = c, X = 3 ? ; E = d, X = 4 ? ; E = e, X = 5 ? ; no Multiple occurrences of an element: ?- list_element_position([a,b,c,d,e,a],a,X). X = 1 ? ; X = 6 ? ; no If you only intend to use the predicate with the first argument being ground, this already works fine. However, if you want to ask questions like: What lists are there with a certain element, say a, at a certain position, say 1?: ?- list_element_position(L,a,1). L = [a|_A] ? ; You get one answer and then the predicate loops. You can avoid that by adding a goal with length/2 to list_element_position/3: list_element_position(L,E,P) :- length(L,_), % <- here list_element_position_(L,E,P,1). The above query now produces additional solutions: ?- list_element_position(L,a,1). L = [a] ? ; L = [a,_A] ? ; L = [a,_A,_B] ? ; L = [a,_A,_B,_C] ? ; ... Or even better, you can avoid the loop by using clpfd and adding a goal in list_element_position_/4 to ensure that the accumlator does not become larger than the actual position: :- use_module(library(clpfd)). list_element_position(L,E,P) :- list_element_position_(L,E,P,1). list_element_position_([X|Xs],X,P,P). list_element_position_([X|Xs],Y,R,P0) :- R #> P0, % <- here P1 #= P0+1, list_element_position_(Xs,Y,R,P1). This way the query yields a single solution and terminates subsequently: ?- list_element_position(L,a,1). L = [a|_A] ? ; no
{ "language": "en", "url": "https://stackoverflow.com/questions/37863853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: rails postgres some of the sequence not start from 1 I am using ruby on rails with postgresql database. A weird thing happened that some of the tables_id_seq are not starting from 1, but 980190963. But some of the seq are correctly starting from 1. The problem is when I tried to insert data into those table which seq not start from 1, unique primary key violation raised occasionally. --EDIT-- I found that when I do rake db:migrate test The problem happens. If I do rake db:migrate RAILS_ENV=test The problem has gone. A: If you don't need to keep the data in those tables, you can run the following which will reset the table (THIS WILL REMOVE ANY DATA THERE) and restart the tables id to start at 1. THIS IS ONLY VIABLE IF YOU DON"T NEED THE DATA IN THAT TABLE! ActiveRecord::Base.connection.execute("TRUNCATE TABLE table_name_here RESTART IDENTITY") As far as why your tables are starting at that id value I would start by checking your migrations. Maybe somewhere in the code there is an "Alter Sequence" sql statement but again not sure.
{ "language": "en", "url": "https://stackoverflow.com/questions/36813189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is my Apollo Client optimistic reply failing? I'm recording this to document the answer to a problem that took me several hours to solve. Scenario: I'm using two mutation queries on a single component in React Apollo-Client. This is a component wrapped into a larger component to form a page. Something like this (this is not the actual code, but it should give the idea): import { compose } from 'react-apollo'; // submitNewUser contains // postedBy // createdAt // content // submitRepository contains // otherProp const thisProps1 = { name: 'mutation1', props: ({ ownProps, mutation1 }) => ({ submit: ({ repoFullName, commentContent }) => mutation1({ variables: { repoFullName, commentContent }, optimisticResponse: { __typename: 'Mutation', submitNewUser: { __typename: 'Comment', postedBy: ownProps.currentUser, content: commentContent, }, }, }), }), }; const thisProps2 = { name: 'mutation2', props: ({ ownProps, mutation2 }) => ({ submit: ({ repoFullName, commentContent }) => mutation2({ variables: { repoFullName, commentContent }, optimisticResponse: { __typename: 'Mutation', submitRepository: { __typename: 'Comment', otherProp: 'foobar', }, }, }), }), }; const ComponentWithMutations = compose( graphql(submitNewUser, thisProps1), graphql(submitRepository, thisProps2) )(Component); Whenever the optimistic response fires, only the second result is fed back to into the query-response in the outer component. In other words, the first query gives an 'undefined' response (but no error), while the second returns an object as expect. Why?? A: The property "createdAt" is not included in the optimistic reply. __typename: 'Comment', postedBy: ownProps.currentUser, content: commentContent, Should be: __typename: 'Comment', postedBy: ownProps.currentUser, createdAt: Date(), content: commentContent, A missing field in an optimistic reply will silently fail to return anything to any queries that call that data.
{ "language": "en", "url": "https://stackoverflow.com/questions/48513854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error in model.frame.default(formula = meansharelocal ~ meanshareglobal) : invalid type (list) for variable 'meansharelocal' Trying to conduct a t.test of two sets of data. The code I am writing for this is: t.test(meansharelocal ~ meanshareglobal) Each data set has 4 pieces of data, in a column like this in a table: mean(Share_1) mean(Share_2) mean(Share_3) mean(Share_4) 1.396552 1.034483 1.189655 1.396552 When I run t.test(meansharelocal ~ meanshareglobal) I receive this error. Error in model.frame.default(formula = meansharelocal ~ meanshareglobal) : invalid type (list) for variable 'meansharelocal' Can someone tell me what is going wrong? I am trying to see if the two piece of data are statistically different enough. This is what I got from Reprex, again, I am new to this so don't know if I accessed this wrong as it is coming up with more errors? But the only error I actually have is the last line! globalshare <- global %>% mutate_at(c("Share_1", "Share_2", "Share_3", "Share_4"), funs(recode(.,"Extremely likely" = 4, "Somewhat likely" = 3, "Neither likely nor unlikely" = 2, "Somewhat unlikely" = 1, "Extremely unlikely" = 0))) #> Error in tbl_vars_dispatch(x): object 'global' not found localshare <- local %>% mutate_at(c("Share_1", "Share_2", "Share_3", "Share_4"), funs(recode(.,"Extremely likely" = 4, "Somewhat likely" = 3, "Neither likely nor unlikely" = 2, "Somewhat unlikely" = 1, "Extremely unlikely" = 0))) #> Error in UseMethod("tbl_vars"): no applicable method for 'tbl_vars' applied to an object of class "function" boxplot(globalshare$Share_1, globalshare$Share_2, globalshare$Share_3, globalshare$Share_4, localshare$Share_1, localshare$Share_2, localshare$Share_3, localshare$Share_4, names=c ("Global1", "Global2", "Global3", "Global4", "Local1", "Local2","Local3", "Local4")) #> Error in boxplot(globalshare$Share_1, globalshare$Share_2, globalshare$Share_3, : object 'globalshare' not found meanshareglobal <- globalshare %>% summarise(mean(Share_1), mean(Share_2), mean(Share_3), mean(Share_4)) #> Error in summarise(., mean(Share_1), mean(Share_2), mean(Share_3), mean(Share_4)): object 'globalshare' not found meansharelocal <- localshare %>% summarise(mean(Share_1), mean(Share_2), mean(Share_3), mean(Share_4)) #> Error in summarise(., mean(Share_1), mean(Share_2), mean(Share_3), mean(Share_4)): object 'localshare' not found t.test(meanshareglobal ~ meansharelocal) #> Error in eval(predvars, data, env): object 'meanshareglobal' not found A: If I am understanding from your comments correctly you have wide dataframes of 1 row. Assuming they are the same dimensions you can just transpose and bind them then do your t test. t.globalshare = t(globalshare) t.localshare = t(localshare) combined = cbind(t.globalshare, t.localshare) t.test(combined, t.globalshare ~ t.localshare)
{ "language": "en", "url": "https://stackoverflow.com/questions/71677755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Laravel show maintenance mode during composer update I'm have a question extremely similar to this unanswered one: laravel 5 maintenance page broken during composer update I am new to Laravel (using version 5.2) and am trying to work out the deployment process. From what I've gathered, the workflow that I want to use (once I've made and thoroughly tested changes on a development server, of course) is to put the production site into maintenance mode, deploy changes via git, run composer/artisan tasks (composer update, php artisan migrate, etc.) and then take the production site out of maintenance mode. The problem I'm running into is that if I have new providers in config/app.php, the live site displays an error message (until I run composer update) even while in maintenance mode. Is there a way to have the maintenance mode view override the error view so that I can perform my updates in peace without the site telling the world that there are errors? I turned off error reporting so it at least doesn't show the specifics, but I'd love it if it kept any mention of errors on the DL while maintenance mode was enabled. Alternatively, is there a better deployment workflow that I can use to eliminate this problem all together? A: Why not use symlinks for releases? Below is an example of a deployment process that I've used on Laravel applications with Envoy. Aside from the PHP variable notation, it would be straightforward to substitute a purely bash/shell script if you are not using Envoy. Essentially, having a script automates the deployment, and using symlinks can make the update nearly instantaneous. Additional benefits include previous releases existing for the unfortunate time when a rollback is necessary. Note: The below script makes some basic assumptions: * *Your .env file is in the $root_dir (ex: /var/www/my-website/.env). *Your vhost points to the site/public directory within the $root_dir (ex: /var/www/my-website/site/public). However, if you can not update the vhost, you can simply add the following to number 4 below in the empty line: ln -nfs {{ $app_dir }}/public {{ $root_dir }}/public ; sudo chgrp -h www-data {{ $root_dir }}/public; *You have added SSH keys to pull from Git repo *(optional) nodejs is installed Here are the relevant example variables for the script: $repo = 'git@bitbucket.org:myusername/my-repo.git'; $root_dir = '/var/www/my-website'; $release_dir = '/var/www/my-website/releases'; $app_dir = '/var/www/my-website/site'; $release = 'release_' . date('YmdHis'); $branch = 'master'; Here is the gist of the deployment process with code: * *Fetch the updated code into a new release directory: @task('fetch_repo') [ -d {{ $release_dir }} ] || mkdir {{ $release_dir }}; cd {{ $release_dir }}; git clone {{ $repo }} -b {{ $branch }} {{ $release }}; @endtask *Install the dependencies by running composer: @task('run_composer') cd {{ $release_dir }}/{{ $release }}; composer install; @endtask *(optional) If we are using asset precompiler like Elixir, we will want to fetch npm dependencies, reset permissions, and run gulp: @task('npm_install') cd {{ $release_dir }}/{{ $release }}; sudo npm install; @endtask @task('update_permissions') cd {{ $release_dir }}; sudo chgrp -R www-data {{ $release }}; sudo chmod -R ug+rwx {{ $release }}; @endtask @task('compile_assets') cd {{ $release_dir }}/{{ $release }}; gulp --production; @endtask *Update symlinks @task('update_symlinks') ln -nfs {{ $root_dir }}/.env {{ $release_dir }}/{{ $release }}/.env; ln -nfs {{ $release_dir }}/{{ $release }} {{ $app_dir }}; sudo chgrp -h www-data {{ $app_dir }}; sudo service php5-fpm restart; @endtask *(Optional) Prune old release folders (30+ days old) so we don't fill up the server. @task('prune_old') sudo find {{ $release_dir }} -maxdepth 1 -type d -mtime +30 -exec rm -rf {} \; @endtask Note: Restarting the php5-fpm service clears the cache that ensures the new symlink is followed. I found it somewhat difficult to find deployment script examples (like the aforementioned) when I initially began developing with Laravel, so hopefully this will help alleviate some searching.
{ "language": "en", "url": "https://stackoverflow.com/questions/35397928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Python CSV - optimizing CSV Read and Write I am currently fiddling around with Python when my boss assigned me with a quite daunting task. He gave me a CSV file with around 14GB in size, and ask me if I can inflate that CSV to a delimited file with 4TB of size, by replicating itself several times. For example, take this CSV: TIME_SK,ACCOUNT_NUMBER,ACCOUNT_TYPE_SK,ACCOUNT_STATUS_SK,CURRENCY_SK,GLACC_BUSINESS_NAME,PRODUCT_SK,PRODUCT_TERM_SK,NORMAL_BAL,SPECIAL_BAL,FINAL_MOV_YTD_BAL,NO_OF_DAYS_MTD,NO_OF_DAYS_YTD,BANK_FLAG,MEASURE_ID,SOURCE_SYSTEM_ID 20150131,F290006G93996,7,1,12,DEPOSIT INSURANCE EXPENSE,502,0,865.57767676670005,0,865.57767676670005,30,121,N,DEPOSIT INSURANCE EXPENSE,1 20150131,F2900F036FF90,7,9,12,GWM BALANCE,502,0,-139.0556,0,-139.0556,30,121,N,GWM BALANCE,1 20150131,F070007GG6790,7,1,12,DEPOSIT INSURANCE EXPENSE,1008,0,14100.016698793699,0,14100.016698793699,30,121,N,DEPOSIT INSURANCE EXPENSE,1 20150131,F2F00040FG982,7,1,12,DEPOSIT INSURANCE EXPENSE,502,0,8410.4009848750993,0,8410.4009848750993,30,121,N,DEPOSIT INSURANCE EXPENSE,1 20150131,FF30009944863,7,9,12,ACCOUNT PRINCIPAL,502,0,-2367.9400000000001,0,-2367.9400000000001,30,121,N,GL BALANCE,1 20150131,F240002FG722F,7,1,12,ACCOUNT PRINCIPAL,502,0,-28978292.390000001,0,-28978292.390000001,30,121,N,GL BALANCE,1 20150131,F0G00FFF74293,7,1,12,ACCOUNT PRINCIPAL,1008,0,-855196.81000000006,0,-855196.81000000006,30,121,N,GL BALANCE,1 20150131,FF20007947687,7,9,12,GWM BALANCE,2425,0,-368.45897600000001,0,-368.45897600000001,30,121,N,GWM BALANCE,1 20150131,F200007938744,7,1,12,GWM BALANCE,502,0,-19977.173964000001,0,-19977.173964000001,30,121,N,GWM BALANCE,1 He wants me to inflate the size by replicating the contents of the CSV, with altering the TIME_SK header, like below: TIME_SK,ACCOUNT_NUMBER,ACCOUNT_TYPE_SK,ACCOUNT_STATUS_SK,CURRENCY_SK,GLACC_BUSINESS_NAME,PRODUCT_SK,PRODUCT_TERM_SK,NORMAL_BAL,SPECIAL_BAL,FINAL_MOV_YTD_BAL,NO_OF_DAYS_MTD,NO_OF_DAYS_YTD,BANK_FLAG,MEASURE_ID,SOURCE_SYSTEM_ID 20150131,F290006G93996,7,1,12,DEPOSIT INSURANCE EXPENSE,502,0,865.57767676670005,0,865.57767676670005,30,121,N,DEPOSIT INSURANCE EXPENSE,1 20150131,F2900F036FF90,7,9,12,GWM BALANCE,502,0,-139.0556,0,-139.0556,30,121,N,GWM BALANCE,1 20150131,F070007GG6790,7,1,12,DEPOSIT INSURANCE EXPENSE,1008,0,14100.016698793699,0,14100.016698793699,30,121,N,DEPOSIT INSURANCE EXPENSE,1 20150131,F2F00040FG982,7,1,12,DEPOSIT INSURANCE EXPENSE,502,0,8410.4009848750993,0,8410.4009848750993,30,121,N,DEPOSIT INSURANCE EXPENSE,1 20150131,FF30009944863,7,9,12,ACCOUNT PRINCIPAL,502,0,-2367.9400000000001,0,-2367.9400000000001,30,121,N,GL BALANCE,1 20150131,F240002FG722F,7,1,12,ACCOUNT PRINCIPAL,502,0,-28978292.390000001,0,-28978292.390000001,30,121,N,GL BALANCE,1 20150131,F0G00FFF74293,7,1,12,ACCOUNT PRINCIPAL,1008,0,-855196.81000000006,0,-855196.81000000006,30,121,N,GL BALANCE,1 20150131,FF20007947687,7,9,12,GWM BALANCE,2425,0,-368.45897600000001,0,-368.45897600000001,30,121,N,GWM BALANCE,1 20150131,F200007938744,7,1,12,GWM BALANCE,502,0,-19977.173964000001,0,-19977.173964000001,30,121,N,GWM BALANCE,1 20150201,F290006G93996,7,1,12,DEPOSIT INSURANCE EXPENSE,502,0,865.57767676670005,0,865.57767676670005,30,121,N,DEPOSIT INSURANCE EXPENSE,1 20150201,F2900F036FF90,7,9,12,GWM BALANCE,502,0,-139.0556,0,-139.0556,30,121,N,GWM BALANCE,1 20150201,F070007GG6790,7,1,12,DEPOSIT INSURANCE EXPENSE,1008,0,14100.016698793699,0,14100.016698793699,30,121,N,DEPOSIT INSURANCE EXPENSE,1 20150201,F2F00040FG982,7,1,12,DEPOSIT INSURANCE EXPENSE,502,0,8410.4009848750993,0,8410.4009848750993,30,121,N,DEPOSIT INSURANCE EXPENSE,1 20150201,FF30009944863,7,9,12,ACCOUNT PRINCIPAL,502,0,-2367.9400000000001,0,-2367.9400000000001,30,121,N,GL BALANCE,1 20150201,F240002FG722F,7,1,12,ACCOUNT PRINCIPAL,502,0,-28978292.390000001,0,-28978292.390000001,30,121,N,GL BALANCE,1 20150201,F0G00FFF74293,7,1,12,ACCOUNT PRINCIPAL,1008,0,-855196.81000000006,0,-855196.81000000006,30,121,N,GL BALANCE,1 20150201,FF20007947687,7,9,12,GWM BALANCE,2425,0,-368.45897600000001,0,-368.45897600000001,30,121,N,GWM BALANCE,1 20150201,F200007938744,7,1,12,GWM BALANCE,502,0,-19977.173964000001,0,-19977.173964000001,30,121,N,GWM BALANCE,1 and so on. I was able to make the Python script to do the task, however when used on the real CSV file with tens of Gigabytes in size and hundred millions of row, the task was proved to be too long to complete (there was a time constraint at that time; however, he asked me to do it again now). I am using the Python built in CSV Writer. After a bit of research, I came up with two different approach: 1. The Old and Trusted Iterator This is the first version of my script; it does the job all right, however it took too long for tackling the humongous CSV. . . . omitted . . . with open('../csv/DAILY_DDMAST.csv', 'rb') as csvinput: with open('../result/DAILY_DDMAST_result1'+name_interval+'.csv', 'wb') as csvoutput: reader = csv.reader(csvinput) writer = csv.writer(csvoutput, lineterminator='\r\n') # This part copies the original CSV to a new file for row in reader: writer.writerow(row) print("Done copying. Time elapsed: %s seconds, Total time: %s seconds" % ((time.time() - start_time), (time.time() - start_time))) i = 0 while i &lt; 5: # This part replicates the content of CSV, with modifying the TIME_SK value counter_time = time.time() for row in reader: newdate = datetime.datetime.strptime(row[0], "%Y%m%d") + datetime.timedelta(days=i) row[0] = newdate.strftime("%Y%m%d") writer.writerow(row) csvinput.seek(0) next(reader, None) print("Done processing for i = %d. Time elapsed: %s seconds, Total time: %s seconds" % (i+1, (counter_time - start_time), (time.time() - start_time))) i += 1 . . . omitted . . . In my understanding, the script will iterate each row inside the CSV by for row in reader, and then write each row to the new file with writer.writerow(row). I also found that by iterating the source file, it is a bit repetitive and time consuming, so I thought it could have been more efficient with other approach... 2. The Bucket This was intended as an "upgrade" to the first version of the script. . . . omitted . . . with open('../csv/DAILY_DDMAST.csv', 'rb') as csvinput: with open('../result/DAILY_DDMAST_result2'+name_interval+'.csv', 'wb') as csvoutput: reader = csv.reader(csvinput) writer = csv.writer(csvoutput, lineterminator='\r\n') csv_buffer = list() for row in reader: # Here, rather than directly writing the iterated row, I stored it in a list. # If the list reached 1 mio rows, then it writes to the file and empty the "bucket" csv_buffer.append(row) if len(csv_buffer) > 1000000: writer.writerows(csv_buffer) del csv_buffer[:] writer.writerows(csv_buffer) print("Done copying. Time elapsed: %s seconds, Total time: %s seconds" % ((time.time() - start_time), (time.time() - start_time))) i = 0 while i &lt; 5: counter_time = time.time() del csv_buffer[:] for row in reader: newdate = datetime.datetime.strptime(row[0], "%Y%m%d") + datetime.timedelta(days=i) row[0] = newdate.strftime("%Y%m%d") # Same goes here csv_buffer.append(row) if len(csv_buffer) > 1000000: writer.writerows(csv_buffer) del csv_buffer[:] writer.writerows(csv_buffer) csvinput.seek(0) next(reader, None) print("Done processing for i = %d. Time elapsed: %s seconds, Total time: %s seconds" % (i+1, (counter_time - start_time), (time.time() - start_time))) i += 1 . . . omitted . . . I thought, by storing it in memory then writing them altogether with writerows, I could've saved time. However, that was not the case. I found out that even if I store the rows to be written to the new CSV, writerows iterates the list then write them to the new file, thus it consumes nearly as long as the first script... At this point, I don't know if I should come up with better algorithm or there is something that I could use - something like the writerows, only it does not iterate, but writes them all at once. I don't know if such thing is possible or not, either Anyway, I need help on this, and if anyone could shed some lights, I would be very thankful! A: I don't have a 14GB file to try this with, so memory footprint is a concern. Someone who knows regex better than myself might have some performance tweaking suggestions. The main concept is don't iterate through each line when avoidable. Let re do it's magic on the whole body of text then write that body to the file. import re newdate = "20150201," f = open('sample.csv', 'r') g = open('result.csv', 'w') body = f.read() ## keeps the original csv g.write(body) # strip off the header -- we already have one. header, mainbody = body.split('\n', 1) # replace all the dates newbody = re.sub(r"20150131,", newdate, mainbody) #end of the body didn't have a newline. Adding one back in. g.write('\n' + newbody) f.close() g.close() A: Batch writing your rows isn't really going to be an improvement because your write IO's are still going to be the same size. Batching up writes only gives you an improvement if you can increase your IO size, which reduces the number of system calls and allows the IO system to deal with fewer but larger writes. Honestly, I wouldn't complicate the code with batch writing for maintainability reasons, but I can certainly understand the desire to experiment with trying to improve the speed, if only for educational reasons. What you want to do is batch up your writes -- batching up your csv rows doesn't really accomplish this. [Example using StringIO removed .. there's a better way.] Python write() uses buffered I/O. It just by default buffers at 4k (on Linux). If you open the file with a buffering parameter you can make it bigger: with open("/tmp/x", "w", 1024*1024) as fd: for i in range(0, 1000000): fd.write("line %d\n" %i) Then your writes will be 1MB. strace output: write(3, "line 0\nline 1\nline 2\nline 3\nline"..., 1048576) = 1048576 write(3, "ine 96335\nline 96336\nline 96337\n"..., 1048576) = 1048576 write(3, "1\nline 184022\nline 184023\nline 1"..., 1048576) = 1048576 write(3, "ne 271403\nline 271404\nline 27140"..., 1048576) = 1048576 write(3, "58784\nline 358785\nline 358786\nli"..., 1048576) = 1048576 write(3, "5\nline 446166\nline 446167\nline 4"..., 1048576) = 1048576 write(3, "ne 533547\nline 533548\nline 53354"..., 1048576) = 1048576 [...] Your simpler original code will work and you only need to change the blocksize for the open() calls (I would change it for both source and destination.) My other suggestion is to abandon csv, but that potentially takes some risks. If you have quoted strings with commas in them you have to create the right kind of parser. BUT -- since the field you want to modify is fairly regular and the first field, you may find it much simpler to just have a readline/write loop where you just replace the first field and ignore the rest. #!/usr/bin/python import datetime import re with open("/tmp/out", "w", 1024*1024) as fdout, open("/tmp/in", "r", 1024*1024) as fdin: for i in range(0, 6): fdin.seek(0) for line in fdin: if i == 0: fdout.write(line) continue match = re.search(r"^(\d{8}),", line) if match: date = datetime.datetime.strptime(match.group(1), "%Y%m%d") fdout.write(re.sub("^\d{8},", (date + datetime.timedelta(days=i)).strftime("%Y%m%d,"), line)) else: if line.startswith("TIME_SK,"): continue raise Exception("Could not find /^\d{8},/ in '%s'" % line) If order doesn't matter, then don't reread the file over and over: #!/usr/bin/python import datetime import re with open("/tmp/in", "r", 1024*1024) as fd, open("/tmp/out", "w", 1024*1024) as out: for line in fd: match = re.search("^(\d{8}),", line) if match: out.write(line) date = datetime.datetime.strptime(match.group(1), "%Y%m%d") for days in range(1, 6): out.write(re.sub("^\d{8},", (date + datetime.timedelta(days=days)).strftime("%Y%m%d,"), line)) else: if line.startswith("TIME_SK,"): out.write(line) continue raise Exception("Could not find /^\d{8},/ in %s" % line) I went ahead and profiled one of these with python -mcProfile and was surprised how much time was spent in strptime. Also try caching your strptime() calls by using this memoized strptime(): _STRPTIME = {} def strptime(s): if s not in _STRPTIME: _STRPTIME[s] = datetime.datetime.strptime(s, "%Y%m%d") return _STRPTIME[s] A: First of all, you're going to be limited by the write speed. Typical write speed for a desktop machine is on the order of about 40 seconds per gigabyte. You need to write 4,000 gigabytes, so it's going to take on the order of 160,000 seconds (44.5 hours) just to write the output. The only way to reduce that time is to get a faster drive. To make a 4 TB file by replicating a 14 GB file, you have to copy the original file 286 (actually 285.71) times. The simplest way to do things is: open output file starting_date = date on first transaction for pass = 1 to 286 open original file while not end of file read transaction replace date write to output increment date end while end for close output file But with a typical read speed of about 20 seconds per gigabyte, that's 80,000 seconds (22 hours and 15 minutes) just for reading. You can't do anything about the writing time, but you probably can reduce the reading time by a lot. If you can buffer the whole 14 GB input file, then reading time becomes about five minutes. If you don't have the memory to hold the 14 GB, consider reading it into a compressed memory stream. That CSV should compress quite well--to less than half of its current size. Then, rather than opening the input file every time through the loop, you just re-initialize a stream reader from the compressed copy of the file you're holding in memory. In C#, I'd just use the MemoryStream and GZipStream classes. A quick Google search indicates that similar capabilities exist in python, but since I'm not a python programmer I can't tell you exactly how to use them.
{ "language": "en", "url": "https://stackoverflow.com/questions/37732466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python Multiple Assignment Statements In One Line (Don't worry, this isn't another question about unpacking tuples.) In python, a statement like foo = bar = baz = 5 assigns the variables foo, bar, and baz to 5. It assigns these variables from left to right, as can be proved by nastier examples like >>> foo[0] = foo = [0] Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'foo' is not defined >>> foo = foo[0] = [0] >>> foo [[...]] >>> foo[0] [[...]] >>> foo is foo[0] True But the python language reference states that assignment statements have the form (target_list "=")+ (expression_list | yield_expression) and on assignment the expression_list is evaluated first and then the assigning happens. So how can the line foo = bar = 5 be valid, given that bar = 5 isn't an expression_list? How are these multiple assignments on one line getting parsed and evaluated? Am I reading the language reference wrong? A: bar = 5 is not an expression. The multiple assignment is a separate statement from the assignment statement; the expression is everything to the right of the right-most =. A good way to think about it is that the right-most = is the major separator; everything to the right of it happens from left to right, and everything to the left of it happens from left to right as well. A: All credit goes to @MarkDickinson, who answered this in a comment: Notice the + in (target_list "=")+, which means one or more copies. In foo = bar = 5, there are two (target_list "=") productions, and the expression_list part is just 5 All target_list productions (i.e. things that look like foo =) in an assignment statement get assigned, from left to right, to the expression_list on the right end of the statement, after the expression_list gets evaluated. And of course the usual 'tuple-unpacking' assignment syntax works within this syntax, letting you do things like >>> foo, boo, moo = boo[0], moo[0], foo[0] = moo[0], foo[0], boo[0] = [0], [0], [0] >>> foo [[[[...]]]] >>> foo[0] is boo True >>> foo[0][0] is moo True >>> foo[0][0][0] is foo True A: Mark Dickinson explained the syntax of what is happening, but the weird examples involving foo show that the semantics can be counter-intuitive. In C, = is a right-associative operator which returns as a value the RHS of the assignment so when you write x = y = 5, y=5 is first evaluated (assigning 5 to y in the process) and this value (5) is then assigned to x. Before I read this question, I naively assumed that roughly the same thing happens in Python. But, in Python = isn't an expression (for example, 2 + (x = 5) is a syntax error). So Python must achieve multiple assignments in another way. We can disassemble rather than guess: >>> import dis >>> dis.dis('x = y = 5') 1 0 LOAD_CONST 0 (5) 3 DUP_TOP 4 STORE_NAME 0 (x) 7 STORE_NAME 1 (y) 10 LOAD_CONST 1 (None) 13 RETURN_VALUE See this for a description of the byte code instructions. The first instruction pushes 5 onto the stack. The second instruction duplicates it -- so now the top of the stack has two 5s STORE_NAME(name) "Implements name = TOS" according to the byte code documentation Thus STORE_Name(x) implements x = 5 (the 5 on top of the stack), popping that 5 off the stack as it goes, after which STORE_Name(y) implements y = 5 with the other 5 on the stack. The rest of the bytecode isn't directly relevant here. In the case of foo = foo[0] = [0] the byte-code is more complicated because of the lists but has a fundamentally similar structure. The key observation is that once the list [0] is created and placed on the stack then the instruction DUP_TOP doesn't place another copy of [0] on the stack, instead it places another reference to the list. In other words, at that stage the top two elements of the stack are aliases for the same list. This can be seen most clearly in the somewhat simpler case: >>> x = y = [0] >>> x[0] = 5 >>> y[0] 5 When foo = foo[0] = [0] is executed, the list [0] is first assigned to foo and then an alias of the same list is assigned to foo[0]. This is why it results in foo being a circular reference. A: https://docs.python.org/3/reference/simple_stmts.html#grammar-token-assignment_stmt An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right. A: The assignment order is that right most value is assigned to the first variable from left to right. Please note below: >>> foo[0] = foo = [1,2,3] # line 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'foo' is not defined >>> foo = foo[0] = [1,2,3] # line 2 >>> foo [[...], 2, 3] The assignment at line 1 fails because it is trying assign a value to foo[0] but foo is never initialized or defined so it fails. The assignment at line 2 works because foo is first initialized to be [1,2,3] and then foo[0] is assigned [1,2,3]
{ "language": "en", "url": "https://stackoverflow.com/questions/32156515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "48" }
Q: How to ensure data security even if postgres data can be accessed I am installing postgres along side a intranet application. The data folder of postgres can be accessed by the user. I have seen here how one can reset the postgres user password and thus compromising data security. Am I correct in understanding pg_hba.conf is data specific? Is it possible to lock down modifications to pg_hba.conf or hard code the configuration somewhere so that one cant follow the steps described to the question linked above?
{ "language": "en", "url": "https://stackoverflow.com/questions/41511110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Play Framework super Class i want to create two table using a abstract super class i have 3 user's -> Full Time User, part-time user, they have almost the same data I create the models but the table User is not created :( how do i do? thanks in advance Model Full time User @Entity public class User extends Model{ public String name; public Date start; public Date end; public boolean status; ...... public Project() { super(); } } Model Part-time User @Entity public class partTimeUser extends User { public Time startTime ; public Time endTime; } ----------------------------------- 2º REPLY---------------------------------------- Can i do like this? or is diferent when getting the objects? Model User @MappedSuperclass public class User extends Model{ public String name; public Date start; public Date end; public boolean status; ...... public Project() { super(); } } Model Part-time User @Entity public class partTimeUser extends User { public Time startTime ; public Time endTime; } } Class Full User @Entity public class partTimeUser extends User { } A: In JPA you should add some annotations about the type of inheritence. @Inheritance(strategy = InheritanceType.JOINED) @Table(name = "USER") @Entity public class User ... @Table(name = "PART_TIME_USER") @Entity public class PartTimeUser extends User ... P.S. The @Table annotation is not necessary. Nevertheless I prefer to define it. It makes the code and its connection to database objects more readable.
{ "language": "en", "url": "https://stackoverflow.com/questions/9820420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP _REQUEST redirect? I am reading a script but am stuck on understanding this: $redirect = base64_decode($_REQUEST['redirect']); header("Location:$redirect");exit; because the redirect variable in REQUEST isn't defined anywhere in the script. Prior to this a POST form has been filled in, but there is NO mention of the redirect variable anywhere in the script so I am confused how it is not empty... EDIT: here's the form code below. btw like I said, the word 'redirect' doesn't appear ANYWHERE in the script, which is what is confusing me. <form name="login" action="{$baseurl}/login" method="post"> {$lang12} <input type="text" name="username" /> {$lang11} <input type="password" name="password" /> <input type="submit" value="{$lang18}" /> <div class="test"><a href="{$baseurl}/signup"><b>{$lang30}</b></a> - <a href="{$baseurl}/password">{$lang19}</a></div> <input type="hidden" name="authenticate" value="1" /> </form> </div> The $lang stuff is commonly appearing words from an array, e.g login, etc. A: $_REQUEST An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE. So if you have $_POST['redirect'], $_GET['redirect'] or $_COOKIE['redirect'], $_REQUEST['redirect'] will be defined. Try to put: var_dump($_POST['redirect']); var_dump($_GET['redirect']); var_dump($_COOKIE['redirect']); To find out where it's coming from. A: I don't think this is possible to answer for certain without seeing the actual code but $_REQUEST holds all the variables in $_GET, $_POST and $_COOKIE. A form can actually populate both $_GET and $_POST if its method is set to 'post' and its action is a url with url encoded variables. Thus the form might be posting all of its data to a url and then adding get variables to the end of that url. For example: <form method='post' action='example.php?var=test'> <input name='var2' id='var2' /> </form> If that form were submitted, the following would be defined: $_POST['var2'], $_GET['var'], $_REQUEST['var2'], $_REQUEST['var']. $_COOKIE could also be putting hidden variables in $_REQUEST. A: it have so much possibility that the redirect variable is a cookies. if you cannot find it at the form. var_dump($_REGISTER); that will list all your input variable associated with POST, GET and COOKIES. A: If it's not empty what's the content of it? I think it should be something like this... $redirect = base64_decode($_GET['redirect']); if(!empty($redirect){ header("Location: $redirect"); exit; } It doesn't matter that it's not in the script, you can set it via GET, eg /yourform.php?redirect=index.php Is it causing unwanted redirection?
{ "language": "en", "url": "https://stackoverflow.com/questions/3517345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: makefile compile with -g and -O0 automatically Now I got a makefile like this: #-------------------------------------------------------- # Choose a compiler #-------------------------------------------------------- CC = gcc #-------------------------------------------------------- # Set your source file and your target executable #-------------------------------------------------------- SRC = main.c TARGET = main2 all: $(TARGET) #-------------------------------------------------------- # Compile the program #-------------------------------------------------------- $(TARGET): $(SRC) $(CC) -o $@ $(SRC) #-------------------------------------------------------- # Clean up (remove the executable) #-------------------------------------------------------- clean: rm -f $(TARGET) How can I modify my Makefile so that it compiles with -g and -O0 (that's oh-zero) options automatically? I am really confused with the makefile stuff. A: Add CFLAGS=-g -O0 below CC and change the line $(CC) -o @ (SRC) into $(CC) -o $@ $(CFLAGS) $(SRC) This would produce a final Makefile that looks like: CC = gcc CFLAGS = -g -O0 SRC = main.c TARGET = main2 all: $(TARGET) $(TARGET): $(SRC) $(CC) -o $@ $(CFLAGS) $(SRC) clean: rm -f $(TARGET) A: If you're looking for a very simple (if we define simple by very few lines of code), then all I ask is that you rename your source file to main.c instead of main2.c. CFLAGS = -g -O0 all: main Which we can run: $ cat Makefile CFLAGS = -g -O0 all: main $ cat main.c int main() {} $ make gcc -g -O0 main.c -o main
{ "language": "en", "url": "https://stackoverflow.com/questions/36637481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to convert from a string to pure code in C++? I know that its possible to read from a .txt file and then convert various parts of that into string, char, and int values, but is it possible to take a string and use it as real code in the program? Code: string codeblock1="cout<<This is a test;"; string codeblock2="int array[5]={0,6,6,3,5};}"; int i; cin>>i; if(i) { execute(codeblock1); } else { execute(codeblock2); } Where execute is a function that converts from text to actual code (I don't know if there actually is a function called execute, I'm using it for the purpose of my example). A: In C++ there's no simple way to do this. This feature is available in higher-level languages like Python, Lisp, Ruby and Perl (usually with some variation of an eval function). However, even in these languages this practice is frowned upon, because it can result in very unreadable code. It's important you ask yourself (and perhaps tell us) why you want to do it? Or do you only want to know if it's possible? If so, it is, though in a hairy way. You can write a C++ source file (generate whatever you want into it, as long as it's valid C++), then compile it and link to your code. All of this can be done automatically, of course, as long as a compiler is available to you in runtime (and you just execute it with system). I know someone who did this for some heavy optimization once. It's not pretty, but can be made to work. A: You can create a function and parse whatever strings you like and create a data structure from it. This is known as a parse tree. Subsequently you can examine your parse tree and generate the necessary dynamic structures to perform the logic therin. The parse tree is subsequently converted into a runtime representation that is executed. All compilers do exactly this. They take your code and they produce machine code based on this. In your particular case you want a language to write code for itself. Normally this is done in the context of a code generator and it is part of a larger build process. If you write a program to parse your language (consider flex and bison for this operation) that generates code you can achieve the results you desire. A: Many scripting languages offer this sort of feature, going all the way back to eval in LISP - but C and C++ don't expose the compiler at runtime. There's nothing in the spec that stops you from creating and executing some arbitrary machine language, like so: char code[] = { 0x2f, 0x3c, 0x17, 0x43 }; // some machine code of some sort typedef void (FuncType*)(); // define a function pointer type FuncType func = (FuncType)code; // take the address of the code func(); // and jump to it! but most environments will crash if you try this, for security reasons. (Many viruses work by convincing ordinary programs to do something like this.) In a normal environment, one thing you could do is create a complete program as text, then invoke the compiler to compile it and invoke the resulting executable. If you want to run code in your own memory space, you could invoke the compiler to build you a DLL (or .so, depending on your platform) and then link in the DLL and jump into it. A: First, I wanted to say, that I never implemented something like that myself and I may be way off, however, did you try CodeDomProvider class in System.CodeDom.Compiler namespace? I have a feeling the classes in System.CodeDom can provide you with the functionality you are looking for. Of course, it will all be .NET code, not any other platform Go here for sample A: Yes, you just have to build a compiler (and possibly a linker) and you're there. Several languages such as Python can be embedded into C/C++ so that may be an option. A: It's kind of sort of possible, but not with just straight C/C++. You'll need some layer underneath such as LLVM. Check out c-repl and ccons A: One way that you could do this is with Boost Python. You wouldn't be using C++ at that point, but it's a good way of allowing the user to use a scripting language to interact with the existing program. I know it's not exactly what you want, but perhaps it might help. A: Sounds like you're trying to create "C++Script", which doesn't exist as far as I know. C++ is a compiled language. This means it always must be compiled to native bytecode before being executed. You could wrap the code as a function, run it through a compiler, then execute the resulting DLL dynamically, but you're not going to get access to anything a compiled DLL wouldn't normally get. You'd be better off trying to do this in Java, JavaScript, VBScript, or .NET, which are at one stage or another interpreted languages. Most of these languages either have an eval or execute function for just that, or can just be included as text. Of course executing blocks of code isn't the safest idea - it will leave you vulnerable to all kinds of data execution attacks. My recommendation would be to create a scripting language that serves the purposes of your application. This would give the user a limited set of instructions for security reasons, and allow you to interact with the existing program much more dynamically than a compiled external block. A: Not easily, because C++ is a compiled language. Several people have pointed round-about ways to make it work - either execute the compiler, or incorporate a compiler or interpreter into your program. If you want to go the interpreter route, you can save yourself a lot of work by using an existing open source project, such as Lua
{ "language": "en", "url": "https://stackoverflow.com/questions/823207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Loop end condition with iterators and custom step size I am adding some functionality to a previously built code. I have to loop over a list is steps of 2 and process the elements elements differently. Here's my attempt. for(auto list_it = std::next(list.begin()); list_it != list.end() ; std::advance(list_it,2)){ // Do something } I am initializing list_it to point to the second element using next(list.begin()) Each iteration it moves forward by 2 advance(list_it,2)). [Q] I am unsure how to test the loop exit condition. list_it != list.end() might not work if we skip over list.end() when advancing forward by 2. Is there any standard way to deal with this issue? I might check skipped iterators for being list.end(), but I don't see this as a nice, scalable way with larger step sizes. (unless it turns out to be the only way). A: Update : Modifying for generic size. For step size of k, You can get size of List in O(n) or O(1) - depending upon C++ compiler. After that compute steps you're allowed to take by: size_t steps_allowed = list.size()/k; // list.size() is O(n) for C++98 and O(1) for standard C++ 11. Then loop over another variable i and inside loop termination condition check for i against steps_allowed. A: You can't advance past the .end() iterator. You have to use either a counter, or check all intermediate iterators. For example: template<class It> void checked_advance(It& it, It last, std::size_t n) { while (n-- > 0 && it != last) ++it; } assert(!list.empty()); for (auto it = std::next(list.begin()); it != list.end(); checked_advance(it, list.end(), step)) { // ... } A: You can change you condition to check and make sure the difference between the current iterator and the end iterator is more then the step amount. That would look like for(auto list_it = std::next(list.begin()); std::distance(list_it, list.end()) > step; std::advance(list_it, step)) { // Do something } A: With range-v3, you might do: for (auto& e : list | ranges::view::drop(1) | ranges::views::stride(2)) { // e }
{ "language": "en", "url": "https://stackoverflow.com/questions/59566298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Qt : How to generate .h and .cpp from a .ui file - Vim and Qt is it practical? I have been using Qt for a while in Windows with Visual Studio on Windows using the Qt Addin. For creating forms I would use Qt Designer and when I would save the form which I would get a *.ui file, a *.cpp file and a *.h file. Now on GNU/Linux I plan to use Vim for development. I could create Qt based programs using Vim however I would like to design forms using Qt Designer and integrate the saved *.ui file into my project and use those forms. How can I use the *.ui designed form in my C++ project? A: Use uic to compile the .ui file would do. Some instruction here. You can also use qtcreator on linux, which includes the vim editing mode plugin. A: AFAIK if you add all your files to your *.pro project file, qmake it and compile the result with cl everything should work fine. Just for the task of processing *.ui files you can use the Qt UI Compiler. From experience I would say that trying to use Vim this way is a real challenge and I wish you good luck with that. In case you change your mind maybe you should know that Qt Creator has a Vim mode called FakeVim, maybe you should take a look at that as well. Update: You don't create a header file that inherits from the generated header, you create a class that inherits from or uses the generated class. Considering that, I would really recommend you use Qt Creator or, if you really want Vim, use FakeVim. Using Vim in this situation is hard and if you're not an advanced, or at least intermediate Vim user you will find it very painful. Vim is powerful but hard to setup for beginners. You will need plug-ins for autocomplete, project tree or neat jumps from header to source just to name a few and setting these up is not very user friendly/straight forward. My advice: Use Qt Creator or FakeVim.
{ "language": "en", "url": "https://stackoverflow.com/questions/26989441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Remove duplicate from large lists efficiently? I have a list which contains ids and values and I need to remove ids duplication. I am looking for an efficiently way preferable in LINQ, instead of my loop and if condition. Thank you for any help and advise. var list = new List<Tuple<int, double>>(); Current values: 1, 3.6 1, 3.8 2, 5.6 3, 8.1 Wished values: 1, 3.6 2, 5.6 3, 8.1 for (int i = 0; i < list.Count - 1; i++) { if (list[i].Item1 == list[i + 1].Item1) list.RemoveAt(i+ 1); } A: If Id and Values are same as the other one. It will remove that item from list. distinctList = list.Distinct().ToList(); If you are okay with converting the Tuple to Dictionary: Try This: If Only Id's are duplicate removes that item from list. It will not consider the value duplication. var distinctDictionary = list.GroupBy(id => id.Item1) .Select(group => group.First()) .ToDictionary(id => id.Item1, val => val.Item2); Look at the Screen shots: Solution 1: Solution 2: A: Why are you a List with tuples? With the requested functionality I would use a Dictionary so you won't have duplicates. A: Given your opinion that LINQ is generally more readable / maintainable and is generally equitable to efficiency, I present the following solution, which uses LINQ, and (IMHO compared to others presented so far) is more efficient in execution as well - list = list.Where((entry, i) => i == 0 || entry.Item1 != list[i - 1].Item1).ToList(); A: DistinctByKey = list.Select(x => x.Keys).Distinct(); DistinctByValue= DistinctByKey.Select(x => x.Values).Distinct();
{ "language": "en", "url": "https://stackoverflow.com/questions/27033742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: FlashBuilder4 RIA on GAE I want to build a highly scalable "facebook for business" and after much testing am pretty set on FlashBuilder4 (Flex) with Google App Engine (GAE). What are your thoughts on the need/advisability of also using Spring/Cairngorm/etc frameworks? Frankly I don't have extensive experience coding, however feel the "MVC utopia" universally aspired to becomes convoluting when duplicating between front and back ends as envisioned above (i.e. Flex/ActionScript and GAE/Java respectively). A: The purpose of using a framework is that the long-term maintenance of your application is more easily done because you have coded consistently with specific standards. You can also have multiple developers working in parallel and easily "piece" the parts back together if they are done consistently. At least that is part of the promise frameworks provide, in theory. A framework is built to solve a specific problem in development. Before choosing a framework, you should review your application and decide if a framework will help you solve those problems. If it can great; if it can't you shouldn't force your app to use a framework. If you are duplicating a lot of code between the front and back end, that seems problematic to me. I'm not surprised that value objects would be mirrored between the front and back end, but their whole purpose is transferring data between different systems. Other code, or business logic, should ideally only exist in one system. As an aside; What an oddly phrased question. If you read specific blogs of experts and want their opinions, why are you posting here instead of contacting them directly? A: The combination of Flex and GAE can be very powerful. However GAE does have limitations that may impact what you are trying to build. For instance GAE doesn't support Spring last time I checked. Another cloud alternative that may work better is the new partnership between VMWare (SpringSource) and Salesforce.com called VMforce.
{ "language": "en", "url": "https://stackoverflow.com/questions/2748595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I use Youtube dataAPI Version 3 on zend framework 2.X version Not able to find any details on the net on whether Zend framework 2.X supports youtube dataAPI 3 ? A: ZF2 doesn't support YouTube like ZF1. However there is a module https://github.com/snapshotpl/ZfSnapGoogle to using Google APIs.
{ "language": "en", "url": "https://stackoverflow.com/questions/29278901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Inferring types in Lambda Calculus I was wondering in anyone would have some decent resources on lambda calculus, specifically on type inference. I am studying for an exam and I can't seem to find any info on lambda types and how to infer in any tutorials I've done. I have an exam question which I'm trying to get my head around for Tuesday.. Infer the types of all variables and parenthesized sub expressions in the below lambda calculus expression: (\denotes lambda) (((\x.(\y.(x,y)y))g)h) I promise it's not homework! Any help would be very welcome. A: Inferring (most general, simple) types for lambda terms is a very simple and highly instructive activity. When you try to decipher a lambda term, starting from guessing its type is a very good approach. The general idea behind type inference is that you start attributing a generic type (a type variable) to any identifier, and then refine this type according to the use you make of the identifier inside the term. This is very easy in the lambda calculus, since an identifier can only be used in two ways: as an argument for a function or as a function. For instance, in your example, suppose x: α and y: β. But x is applied to y, hence it must have a functional type, and moreover its input must be compatible with the type of the argument y, hence we refine α to (β -> γ), where γ is the (so fa unknown) result type of the application (x y). The term (x y) is in turn applied to y. This implies that γ must actually be a functional type too, that is, say, γ = β -> δ. This essentially concludes the analysis, in this case. I report below the type of all subterms, for clarity (please, observe that all applications are well typed): x : β -> β -> γ y : β (x y) : β -> γ ((x y) y) : γ \y.((x y) y) : β -> γ \x.\y.((x y) y) : (β -> β -> γ) -> β -> γ Additionally, we conclude g:β -> β -> γ, and h:β. The whole expression has type γ. A slightly more interesting example is provided by the term \y.\x.(y (y x)). Suppose x: α. Then y must have type α -> β where β is the type of the result (y x). This term is passed again as an input to y, that means that α=β. So, \y.\x.(y (y x)) : (α -> α) -> α -> α In general, in some cases, when you have multiple uses of a same identifier, you will need need to unify their types, inferring the most general instance between them. The wikipage about the Damas-Milner type inference algorithm is reasonably fine, but in my opinion exceedingly technical for such a simple and intuitive topic.
{ "language": "en", "url": "https://stackoverflow.com/questions/21064214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Manipulate text file - change multiple lines Have been looking at what I thought would be a really simple task this morning.... and turns out it wasn't, at least not for me. What I am trying to do is get powershell to read through an ini-file, and change multiple values under specific headers only. [Datoformat] Separator=. [Database] Path=servername:d:\mycompany\nextsys_db\next.fdb DokumentDbPath= FireBird25=Nei [Pictures] Path=T:\nextsys_bilde DbExtractFolder= [Brukerinnstillinger] Prioriter=Ja �pneJournalAuto=Nei TillatBrukerBytte=Ja EnkelJournal=Nei AvtBokRadHoyde= AvtBokMndKolonneBredde= Resepsjonsmaskin=Nei Tilgangsoversikt=Nei AvtaleHentPasientAutomatisk=Ja VisFargeForAnsvarlig=Nei [Eksport] Automatisk=Nei [Import] Automatisk=Nei [Skjerm] HuskSkjermPosisjon=Ja ProgramSkjermPosX=-8 ProgramSkjermPosY=-8 ProgramSkjermBredde=1936 ProgramSkjermHoyde=1056 MaksimertSkjermPosisjon=Ja EgenDefSkjermSizeX=1919 EgenDefSkjermSizeY=1080 UtvidetAvtalebok=Ja UtvidetJournal=Ja UtvidetRecall=Ja UtvidetOmsetning=Ja UtvidetUtestaaende=Ja UtvidetRegnskap=Ja UtvidetFakturaOversikt=Ja UtvidetGenerelleModuler=Ja UtvidetAlleModuler=Ja 1280800=Nei 1440900=Nei 16801050=Nei 19201080=Nei Egendefinert=Ja AutomaticSize=Nei [Spesialinnstillinger] EnForekomst=Nei TestModusInfo=Nei AktiverRegningskortJournalSjekk=Nei IkkeSpmOmHelseskjema=Nei IkkeSpmOmBrukerBytteAvtale=Nei IkkeSpmOmBrukerBytteAnsvarlig=Nei [Vedlegg] Path= [Avtalebok] Utseende= Bakgrunn= [Journal] JournalTextSize=8 JournalTextFont= JournalTextStyle= FetSkrift=Nei [Rontgen] AlternativAapning=Nei [Utseende] IkkeVisDagensPasienter=Nei [MediLink] BenyttMediLink=Nei AutomatiskInnlesing=Nei MediLinkInnlesingIntervall= [AutomatiskOppdatering] VedOppstart=Nei Alltid=Nei FraLokaltNettverk=Nei NettverkPath= UtenBekreftelse=Nei [BankTerminal] PosPay=Nei BetTermAlwaysOn=Ja BBSFlerBrukerTerminal=Nei ThisMerchantHighest=Nei MerchantId= TerminalId= BrukerBoPosDrivere=Nei BrukerBaxiDrivere=Ja BaxiAktiverXReport=Ja BaxiAktiverZReport=Nei BaxiAktiverReversal=Nei [EasyPanel] Benytt=Nei Notat=Nei Diagnose=Nei Epikriser=Nei Sykemelding=Nei Resept=Nei Henvisning=Nei Helseskjema=Nei Endo=Nei Perio=Nei Bilder=Nei Tekn.skjema=Nei Skjema=Nei Dokumentmodul=Nei [Oppstartsbilde] VisesVedOppstart=Nei [Printer] LokaltOppsett=Ja TryktA5Resept=Nei TryktA5ReseptDesign2=Nei TimeKortKvittSkriver=Nei VisMinimalBaxInfo=Nei ReseptKvittSkriver=Nei JusteringVenstreMargX= JusteringToppMargY= Faktura=HP LaserJet Pro MFP M125-M126 PCLmS Recallkort=HP LaserJet Pro MFP M125-M126 PCLmS Timekort=HP LaserJet Pro MFP M125-M126 PCLmS Kvittering=HP LaserJet Pro MFP M125-M126 PCLmS Resept=HP LaserJet Pro MFP M125-M126 PCLmS Standard=HP LaserJet Pro MFP M125-M126 PCLmS Tekniker=HP LaserJet Pro MFP M125-M126 PCLmS FakturaStorrelse=A4 RecallKortStorrelse=A4 TimekortStorrelse=A4 KvitteringStorrelse=A4 ReseptStorrelse=A4 TeknikerStorrelse=A4 StandardStorrelse=A4 FakturaOppsettKode= RecallkortOppsettKode= TimekortOppsettKode= KvitteringOppsettKode= ReseptOppsettKode= TeknikerOppsettKode= StandardOppsettKode= FakturaPapirretning=St�ende RecallKortPapirretning=St�ende TimekortPapirretning=St�ende KvitteringPapirretning=St�ende ReseptPapirretning=St�ende TeknikerPapirretning=St�ende StandardPapirretning=St�ende FakturaPreview=Ja RecallKortPreview=Ja TimekortPreview=Ja KvitteringPreview=Ja ReseptPreview=Ja TeknikerPreview=Ja StandardPreview=Ja [Paaminnelse] Automatisk=Nei AutomatiskService=Nei Tidspunkt= Dagens=Nei KunMerketOnsker=Nei AutomatiskEpost=Nei AntallDagerFrem=Nei AntallDagerFremAntall=2 ErstattTekst=Nei PaaminnelseTekst=Hei [fornavn], minner om time reservert til deg: [dato] kl. [tid]. Timer som ikke passer m� avbestilles senest 24 timer i forveien. Mvh. [tittel] [brukernavn] [SMS] Testmodus=Nei VisAdvarslerVedIkkeSendtSMS=Nei [Innlogging] TillatInnloggingMedEldreProgramversjonEnnDatabase=Nei I want to change the values "Automatisk=Nei" to "Automatisk=Ja", "Tidspunkt=" to "Tidspunkt=10:00" and "AntallDagerFrem=Nei" to "AntallDagerFrem=Ja"... The Tidspunkt and AntallDagerFrem values shouldn't be that hard since they only appear once in the file, but "Automatisk=Nei" appears 4 times, and I only want to change the one below [Paaminnelse] $content = @(if ((Get-Content $inifile) -join "`n" -match '\[Paaminnelse\]([\s\S]*)\[SMS\]') { $Matches[1] }) $newcontent = $test -replace 'Automatisk=Nei','Automatisk=Ja' -replace 'Tidspunkt=','Tidspunkt=10:00' -replace 'AntallDagerFrem=Nei','AntallDagerFrem=Ja' This finds the correct lines from the ini-file and changes the values I want to change, but using Set-Content $inifile -Value $newcontent will of course remove all everything else from the file which is not what I want :) More used to cat, grep, awk and sed than PowerShell to be honest so any pointers would be helpful. A: As Theo notes, consider using a dedicated INI file parser, such as the one provided by the third-party PsIni module - see this answer for how to install and use it. * *Update: Your own answer now shows how to use it to solve your specific problem. If installing a module isn't an option, I suggest using a -switch statement, which has awk-like capabilities: # Array of sample lines, as would be returned by: # Get-Content $inifile $iniFileLines = @' [Datoformat] Separator=. [Eksport] Automatisk=Nei [Paaminnelse] Automatisk=Nei AutomatiskService=Nei Tidspunkt= [Printer] AutomatiskEpost=Nei AntallDagerFrem=Nei AntallDagerFremAntall=2 '@ -split '\r?\n' $inPaaminnelseSect = $false # Note: To operate directly on your file, replace # ($iniFileLines) with -File $iniFile switch -Regex ($iniFileLines) { '^(Tidspunkt)=$' { '{0}=10:00' -f $Matches[1]; continue } '^(AntallDagerFrem)=Nei' { '{0}=Ja' -f $Matches[1]; continue } '^(Automatisk)=Nei' { if ($inPaaminnelseSect) { '{0}=Ja' -f $Matches[1] } else { $_ }; continue } '^\[(.+)\]' { $inPaaminnelseSect = $Matches[1] -eq 'Paaminnelse'; $_ } default { $_ } # pass through } Note: * *The above assumes: * *that your file has exactly the format as shown in your question. However, it would be easy to make parsing more flexible with respect to optional whitespace. *that you only want to replace entries if they have a specific current value (or none); this too could easily be changed to replace the values irrespective of the current value. *Matching is case-insensitive, as PowerShell generally is by default; add the -CaseSensitive switch to make it case-sensitive. Output: [Datoformat] Separator=. [Eksport] Automatisk=Nei [Paaminnelse] Automatisk=Ja AutomatiskService=Nei Tidspunkt=10:00 [Printer] AutomatiskEpost=Nei AntallDagerFrem=Ja AntallDagerFremAntall=2 A: Theo and mklement0 have both pointed to the PsIni-module which does exactly what I wanted to do - so consider the question answered. Set-IniContent $inifile -Sections 'Paaminnelse' -NameValuePairs @{ Automatisk='Ja'; Tidspunkt='10:00'; AntallDagerFrem='Ja' } | Out-IniFile $inifile -Force
{ "language": "en", "url": "https://stackoverflow.com/questions/71772551", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }