source
list
text
stringlengths
99
98.5k
[ "stackoverflow", "0035177937.txt" ]
Q: How can I load two custom tableview cells for one table view I would like to use the two custom tableviewcells(two nib files) like first custom view for first row and second for second row. But the first tableviewcell is not loading. Each row is showing with the second one only. Below is the code I used, In viewdidload, I have registered like UINib *nib = [UINib nibWithNibName:@"TableViewCell" bundle:nil]; [self.mainTableView registerNib:nib forCellReuseIdentifier:CellIdentifier1]; nib = [UINib nibWithNibName:@"SecondTableViewCell" bundle:nil]; [self.mainTableView registerNib:nib forCellReuseIdentifier:CellIdentifier2]; - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //UITableViewCell *cell; static NSString *CellIdentifier1 = @"TableViewCell"; static NSString *CellIdentifier2 = @"SecondTableViewCell"; if (indexPath == 0) { TableViewCell *cell = (TableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1]; return cell; } else { SecondTableViewCell* cell = (SecondTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier2]; // Load the top-level objects from the custom cell XIB. cell.questionLbl.text = [NSString stringWithFormat:@"%ld",indexPath.row+1]; //cell.questionName.text = [self.questionsArray objectAtIndex:indexPath.row]; // Grab a pointer to the first object (presumably the custom cell, as that's all the XIB should contain). return cell; } return nil; } A: Try indexpath.row. If you youse if(indexpath==0), it will not check with the row value.
[ "stackoverflow", "0051463875.txt" ]
Q: Fetch data from api(RESTful) db(mongodb) according to user input I have created an api using nodejs, express and mongodb. I am fetching data now without sending any query. But in my frontend I have an input where the user can search for a recipe. So for example if a user types "Today" i should get response related to today only. How to check that in db and retrieve data? module.exports = function(app, db) { app.get("/dates/", (req, res) => { db .collection("dates") .find() .toArray((err, item) => { if (err) { res.send({ error: "An error has occured" }); } else { res.send(item); } }); }); A: While making the api call , pass the dish as query parameter For example '/recipes/?dish="Pizza" ' and in the express use the following. module.exports = function(app, db) { app.get("/recipes/", (req, res) => { let queryDish = req.query.dish; // assuming /recipes/?dish="Pizza" let query = { 'title' : { '$regex' : queryDish, '$options' : 'i' } }; db .collection("recipes") .find(query) .toArray((err, item) => { if (err) { res.send({ error: "An error has occured" }); } else { res.send(item); } }); });
[ "stackoverflow", "0009634760.txt" ]
Q: Can not connect slave to master I set up Jenkins on a Windows 7 64 bit PC, and installed a Jenkins slave service on another Win7 64 PC. The master PC gives this error: Connection was broken java.net.SocketException: Connection reset at java.net.SocketInputStream.read(Unknown Source) at java.io.BufferedInputStream.fill(Unknown Source) at java.io.BufferedInputStream.read(Unknown Source) at java.io.ObjectInputStream$PeekInputStream.peek(Unknown Source) at java.io.ObjectInputStream$BlockDataInputStream.peek(Unknown Source) at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source) at java.io.ObjectInputStream.readObject0(Unknown Source) at java.io.ObjectInputStream.readObject(Unknown Source) at hudson.remoting.Channel$ReaderThread.run(Channel.java:1127) What can I do to diagnose the problem? [Update] The error is shown when I go to the Nodes page. The added slave is displayed as being disconnected. And when I click on the node Name, the above error is displayed. [Update 2] When a job was forced to run on the slave, it just worked. And afterwards, the slave was displayed as being connected in the node page. Now I come to think of it, I did not try to queue multiple jobs. Perhaps that would have triggered the execution to the slave as well? Anyway, I've got my CI farm up & running now :-) A: I suggest you to start the slave via browser, log as administrator to the slave machine and go to the node page on jenkins, if you are logged as jenkins admin you'll see a slave start icon, this will download and execute the slave process. start slave screenshot Once you get this working you can update it as a windows service via the slave java application menu “File->Install as Windows Service”.
[ "stackoverflow", "0021858970.txt" ]
Q: can not print address of a pointer in c++ I'm new in c++. I wrote this program. #include <iostream> using namespace std; int main(void) { int x=24; char y='A'; char* pchar=&y; int* pint=&x; cout <<"pchar= "<<hex<<&pchar<<endl; cout <<"pint = "<<hex<<&pint<<endl; cout <<endl; cout <<"pchar= "<<hex<<pchar<<endl; cout <<"pint = "<<hex<<pint<<endl; pchar=NULL; pint=NULL; getchar(); return 0; } and its result Can you help me to understand why I can't print the address of variables without &? I think pchar is already the address of y. thanks A: When you use a char* (like your variable pchar) the string overload of operator<< function is used, and when treating it as a string it will print characters until it find the string terminator character ('\0'). Unfortunately in this case pchar points only to a single character, so you have undefined behavior as the function goes out looking for characters in memory not allocated to you. To print a pointer you have to cast it to void*: std::cout << "pchar = " << std::hex << reinterpret_cast<void*>(pchar) << '\n'; It works when you print the address of the variable pchar (when you print &pchar) because then the type of the expression is of type char** which have no direct overload, and instead uses the generic pointer overload (case 7 in this reference).
[ "stackoverflow", "0003917766.txt" ]
Q: How can I remotely read binary registry data using Delphi 2010? I am trying to remotely read a binary (REG_BINARY) registry value, but I get nothing but junk back. Any ideas what is wrong with this code? I'm using Delphi 2010: function GetBinaryRegistryData(ARootKey: HKEY; AKey, AValue, sMachine: string; var sResult: string): boolean; var MyReg: TRegistry; RegDataType: TRegDataType; DataSize, Len: integer; sBinData: string; bResult: Boolean; begin bResult := False; MyReg := TRegistry.Create(KEY_QUERY_VALUE); try MyReg.RootKey := ARootKey; if MyReg.RegistryConnect('\\' + sMachine) then begin if MyReg.KeyExists(AKey) then begin if MyReg.OpenKeyReadOnly(AKey) then begin try RegDataType := MyReg.GetDataType(AValue); if RegDataType = rdBinary then begin DataSize := MyReg.GetDataSize(AValue); if DataSize > 0 then begin SetLength(sBinData, DataSize); Len := MyReg.ReadBinaryData(AValue, PChar(sBinData)^, DataSize); if Len <> DataSize then raise Exception.Create(SysErrorMessage(ERROR_CANTREAD)) else begin sResult := sBinData; bResult := True; end; end; end; except MyReg.CloseKey; end; MyReg.CloseKey; end; end; end; finally MyReg.Free; end; Result := bResult; end; And I call it like this: GetBinaryRegistryData( HKEY_LOCAL_MACHINE, '\SOFTWARE\Microsoft\Windows NT\CurrentVersion', 'DigitalProductId', '192.168.100.105', sProductId ); WriteLn(sProductId); The result I receive from the WriteLn on the console is: ñ ♥ ???????????6Z ????1 ???????☺ ???♦ ??3 ? ??? ? ?? A: You're using Delphi 2010, so all your characters are two bytes wide. When you set the length of your result string, you're allocating twice the amount of space you need. Then you call ReadBinaryData, and it fills half your buffer. There are two bytes of data in each character. Look at each byte separately, and you'll probably find that your data looks less garbage-like. Don't use strings for storing arbitrary data. Use strings for storing text. To store arbitrary blobs of data, use TBytes, which is an array of bytes. A: Assuming that you are already connected remotely, try using the GetDataAsString function to read binary data from the registry. sResult := MyReg.GetDataAsString(AValue);
[ "stackoverflow", "0053095843.txt" ]
Q: NodeJS script to modify a JSON file I need to write a NodeJS script for the following task: I have a temp.json file with content like: { "name": "foo", "id": "1.2.15" } When we run the script, I want the temp.json files content changed. Specifically, I want the number after the 2nd decimal in id to be incremented as follows: { "name": "foo", "id": "1.2.16" } I don't know JavaScript and would appreciate any help. Thanks! A: "use strict"; const fs = require('fs'); const data = JSON.parse(fs.readFileSync("file.json")); const nums = data.id.split('.'); ++nums[2]; data.id = nums.join('.'); fs.writeFileSync("file.json", JSON.stringify(data, null, 4));
[ "stackoverflow", "0050743018.txt" ]
Q: How to conditionally display drawerLabel within a DrawerNavigator I recently added a new screen to the app and this screen needs to only be accessed by specific kind of users who are logged in. class DemoScreen extends Component { static navigationOptions = { title: 'Title', drawerLabel: ({ tintColor, focused }) => { return ( <MainMenuItem textKey={TEXTKEY} iconName="cellphone-settings" focused={focused} tintColor={tintColor} /> ); } }; // Skipping rest of the code } This component is connected to the redux store, so it has access to the users information. But this.props.<FIELD> cannot be accessed inside the navigationOptions. My routes look like this const MainMenu = DrawerNavigator( { // Other screens here Demo: { screen: DemoScreen }, }, { drawerWidth: 250, drawerPosition: 'left', contentComponent: MenuDrawerContent, contentOptions: drawerContentOptions } ); export const Routes = { // Other routes here Main: { screen: MainMenu, navigationOptions: { gesturesEnabled: false } } }; What I want is to display DemoScreen MainManuItem only to a specific type of logged in user. How do I accomplish that? Where should that logic reside? Thanks. A: I managed to solve this by moving the navigationOptions from the screen to the Routes. It looks like this now const MainMenu = DrawerNavigator( { // Other screens here Demo: { screen: DemoScreen, navigationOptions: { title: 'Title', drawerLabel: ({ tintColor, focused }) => { const id = store.getState().field; const valid = [1234, 2345]; if (!valid.includes(id)) { return null; } return ( <MainMenuItem textKey={TEXT} iconName="cellphone-settings" focused={focused} tintColor={tintColor} /> ); } } }, }, { drawerWidth: 250, drawerPosition: 'left', contentComponent: MenuDrawerContent, contentOptions: drawerContentOptions } ); export const Routes = { // Other routes here Main: { screen: MainMenu, navigationOptions: { gesturesEnabled: false } } }; I'm not sure if this is the best approach, but it works. I do have some eslint warnings which I don't know how to solve. Those are: 1. component definition is missing display name 2. 'focused' and 'tintColor' is missing in props validation Both warnings are on this line: drawerLabel: ({ tintColor, focused }) => {. For the moment I've ignored them, but does someone know how to fix them for this case?
[ "stackoverflow", "0020599300.txt" ]
Q: HTML local storage I am trying to store information on local storage after filling the form with data , I want to save the form with its contents in the local storage, but for some reason it doesn't work once i submit information and refresh the page the information is not saved any suggestions <!--local Storage--> <!DOCTYPE html> <html> <head> <script> function info() { if(typeof(Storage)!=="undefined"){ var fn = document.getElementById("FirstName").value; var ln = document.getElementById("LastName").value; var zc = document.getElementById("zipcode").value; localStorage.FastName = fn; localStorage.FirstName = ln; localStorage.Zipcode = zc; document.getElementById("result").innerHTML=localStorage.FastName+" "+" "+localStorage.FirstName+" "+localStorage.Zipcode; }else{ document.getElementById("result").innerHTML="Sorry, your browser does not support web storage..."; } } </script> </head> <body> <p>fill in your information:</p> First name: <input type="text" id="FirstName" value=""><br> Last name: <input type="text" id="LastName" value=""><br> Zip Code: <input type="text" id="zipcode" value="" > <p><button onclick="info();" type="button">Submit</button></p> <div id="result"></div> </body> </html> A: You probably want to use localStorage.setItem("FirstName", fn); to write the values to localStorage. If you want the values back in the input fields on reload, you need to populate the input fields at application startup by reading back the values from localStorage (via getItem) . e.g. append at the end <script> document.getElementById("FirstName").value = localStorage.getItem("FirstName"); ... </script>
[ "stackoverflow", "0007890962.txt" ]
Q: silverlight enabled wcf service retuning value This is my service which checks username and password [OperationContract] public bool LoginCheck(string username, string password) { RoadTransDataContext db = new RoadTransDataContext(); var _Pass = (from d in db.users where d.username == username select d.password).SingleOrDefault(); if (_Pass == password) { return true; } else { return false; } } And this is child window private void LoginCheckCompleted(object sender, ServiceReference.LoginCheckCompletedEventArgs e) { _Log = e.Result; } private void OKButton_Click(object sender, RoutedEventArgs e) { ServiceReference.ServiceClient webservice = new ServiceReference.ServiceClient(); webservice.LoginCheckCompleted += new EventHandler<ServiceReference.LoginCheckCompletedEventArgs>(LoginCheckCompleted); webservice.LoginCheckAsync(txtUserName.Text, txtPassword.Password); if (_Log == true) { this.DialogResult = true; this.Close(); } } problem is that LoginCheckCompleted method is calling when OKButton_Click method finished. so if it input correct username, pass and press button it doing nothing if i click onece again window closing A: Silverlight uses the async model of invoking web services and it takes some time to wait until the response is returned. In your example the assigment _Log = e.Result; will be called, let's assume, after 1-2 seconds, whereas the check if (_Log == true) will be called immideately and of course before the assignment. That's why you should put all the necessary code in the callback and remove all the code after the async call. I've fixed it for you: private void LoginCheckCompleted(object sender, ServiceReference.LoginCheckCompletedEventArgs e) { _Log = e.Result; if (_Log == true) { this.DialogResult = true; this.Close(); } } private void OKButton_Click(object sender, RoutedEventArgs e) { ServiceReference.ServiceClient webservice = new ServiceReference.ServiceClient(); webservice.LoginCheckCompleted += new EventHandler<ServiceReference.LoginCheckCompletedEventArgs>(LoginCheckCompleted); webservice.LoginCheckAsync(txtUserName.Text, txtPassword.Password); }
[ "stackoverflow", "0050865125.txt" ]
Q: Pymongo, TypeError : expected a character buffer object I'm trying to connect and to read data in a MongoDB database, to learn Python. I'm using Pymongo and I have this error : Traceback (most recent call last): File "secondtest.py", line 107, in <module> user_info = dbco.find({}) TypeError: expected a character buffer object This is my database.ini : [postgresql] host=monhostname database=monpass port=15000 user=monuser password=monpass [mongodb] hostname=127.0.0.1 database=Mydatabase username=Myname password=Myn@me! collection=measure port=27017 And my code using it : # -*- coding: utf-8 -*- # secondtest.py import psycopg2 import sys import pymongo from urllib import quote_plus from pymongo import MongoClient from configparser import ConfigParser # Connection information in database.ini params = '' mongollection = '' # Variables to connect to a database, to use a cursor object and to fetch all results from a query mongoClient = '' pgsqlClient = '' pgsqlCursor = '' pgsqlRecords = '' mongoRecords = '' dbco = '' # Retrieve connection information from ini file def dbConfig(section, filename='database.ini'): # Create a parser parser = ConfigParser() # Read config file parser.read(filename) # Get section, depending on the database engine db = {} if parser.has_section(section): params = parser.items(section) for param in params: db[param[0]] = param[1] else: raise Exception('Section {0} not found in the {1} file'.format(section, filename)) # Return data or directly as a string if section == 'postgresql': return db elif section == 'mongodb': host = '' username = '' passwd = '' port = '' dbmongo = '' connectstring = '' # Make a string to connect to MongoDB for key, value in db.iteritems(): if key == 'hostname': host = value.encode("utf-8") elif key == 'username': username = value elif key == 'password': passwd = value elif key == 'database': dbmongo = value elif key == 'collection': mongollection = value elif key == 'port': port = value connectstring = "mongodb://" + username + ":" + quote_plus(passwd) + "@" + host + ":" + port print("Internal test = " + connectstring) return connectstring.encode('iso-8859-1') # Connection to MongoDB def connectToMongoDb(): # The f-string is only available in Python >= 3.6 params = dbConfig('mongodb') print("Parameters : " + params) mongoClient = MongoClient(params) try: # print("Connection to database") dbco = mongoClient.mongollection print("Here") print("Test dbco : " + dbco) print("Connected to MongoDB !") return dbco except: return "Error : can't connect to MongoDB !" # Close MongoDB connection def closeMongoDbConnection(): # try: mongoClient.close() return 'Connection closed' # except: # return "Can't close the connection. See if you already had one or if you didn't mispell its name." # Make a query in MongoDB def mongoDbQuery(): #mongocursor = mongoClient.mongollection.find() #for document in cursor: #print(document) mongoClient.database_names() if __name__ == '__main__': dataconnect = connectToMongoDb() print("Connection\n") #mongoDbQuery() #collec = mongoClient.measure user_info = dbco.find({}) print(user_info) print(closeMongoDbConnection()) Could you help me with this problem ? I think quote_plus() or even dbco = mongoClient.mongollection is what makes this error occurs. But I'm not 100% sure and I don't see, even with the documentation, how could I resolve this. Thank you. A: I made it again and changed some little things. Now, it works. Here is the code, for people who'd need it in the future. import sys import pymongo from urllib import quote_plus from pymongo import MongoClient from configparser import ConfigParser client = MongoClient() connected = '' # Retrieve connection information from ini file def dbConfig(section, filename='database.ini'): # Keep result in global variable when the function is finished global client # Create a parser parser = ConfigParser() # Read config file parser.read(filename) # Get section, depending on the database engine db = {} if parser.has_section(section): params = parser.items(section) for param in params: db[param[0]] = param[1] else: raise Exception('Section {0} not found in the {1} file'.format(section, filename)) # Return data or directly as a string if section == 'postgresql': return db elif section == 'mongodb': # Variables for the connection host = '' username = '' passwd = '' port = '' connectstring = '' # Make a string to connect to MongoDB for key, value in db.iteritems(): if key == 'hostname': host = value.encode("utf-8") elif key == 'username': username = value elif key == 'password': passwd = value elif key == 'database': dbmongo = value elif key == 'collection': mongollection = value elif key == 'port': port = value # Make the URI needed for the connection to Mongo DB passwing = "mongodb://" + username + ":" + quote_plus(passwd) + "@" + host + ":" + port client = MongoClient(passwing) return client # Close MongoDB connection def closeMongoDbConnection(): # Try to close the connection to Mongo DB try: client.close() return 'Connection closed' except: return "Can't close the connection. See if you already had one or if you didn't mispell its name." # Connection to MongoDB def connectToMongoDb(mydb): db = client.get_database(mydb) return db.measure # Make a query in MongoDB def mongoDbQuery(): docs = connected.find().count() #for document in docs: #print(document) print(docs) if __name__ == '__main__': connected = connectToMongoDb('neocampus') #docs = connected.find() # print(test) #for document in docs: #print(document) mongoDbQuery() # Show if the connection to Mongo DB is a success or not print(closeMongoDbConnection()) The problems were : - about global variables in and out of functions - the database variable empty (because of that) - a first call of MongoClient()
[ "stackoverflow", "0007571579.txt" ]
Q: make dropdown list of person i have a model : public class person { public int id{get;set;} public string name{get;set;} } how can i make a drop down list, from list of person in mvc3 razor by this syntax : @Html.DropDownListFor(...) ? what type must be my persons list? sorry I'm new in mvc3 thanks all A: public class PersonModel { public int SelectedPersonId { get; set; } public IEnumerable<Person> persons{ get; set; } } public class Person { public int Id { get; set; } public string Name { get; set; } } then in the controller public ActionResult Index() { var model = new PersonModel{ persons= Enumerable.Range(1,10).Select(x=>new Person{ Id=(x+1), Name="Person"+(x+1) }).ToList() <--- here is the edit }; return View(model);//make a strongly typed view } your view should look like this @model Namespace.Models.PersonModel <div> @Html.DropDownListFor(x=>x.SelectedPersonId,new SelectList(Model.persons,"Id","Name","--Select--")) </div>
[ "stackoverflow", "0056539885.txt" ]
Q: How to select each option in dropdown list and click a button (same origin policy issue - permission denied on the second iteration) I need a code that loops through options in a < select > object on a web page, selects each option and clicks "Show" button to show some data related to the selected option. I started with this code: Set periodSelector = ie.document.getElementById("period") For Each Period In periodSelector.Options Period.Selected = True Application.Wait (Now + TimeValue(waittime)) Next Period It works well - the browser selects each option just fine. But when I add button.click to show the data related to the selected option, an error "Permission denied" occurs on the second selector loop (seems like it cannot use .select command anymore). Set periodSelector = ie.document.getElementById("period") For Each Period In periodSelector.Options Period.Selected = True Application.Wait (Now + TimeValue(waittime)) ie.document.getElementsByTagName("input")(17).Click Application.Wait (Now + TimeValue(waittime)) Next Period I guess it is due to same origin policy. Probably, when I click on the "Show" button, the page gets refreshed (although it is not really reloaded - the button uses scripts to retrieve some information and show it in a table below the button). How can I avoid this same origin policy issue and loop through the dropdown options? A: In cases like this I try a slightly different approach which is to work off the page and not a variable. You can get your number of options from an initial variable, but after that keep working off the current document which may have refreshed. Amongst other things, you want to avoid underlying stale element exceptions. Dim periodSelector As Object, i As Long, optionsLength As Long Set periodSelector = ie.document.querySelectorAll("#period option") optionsLength = periodSelector.Length -1 For i = 0 to optionsLength ie.document.querySelectorAll("#period option").item(i).Selected = True Application.Wait Now + TimeValue(waittime) ie.document.getElementsByTagName("input")(17).Click Application.Wait Now + TimeValue(waittime) '<== this I would replace with proper page load wait While ie.Busy Or ie.readyState < 4: DoEvents: Wend Next
[ "stackoverflow", "0039272728.txt" ]
Q: Plot multiple fits lines in base graphics in r I'm trying to plot multiple fitted lm lines in an only plot: library(lme4) fits <- lmList(Sepal.Length ~ Petal.Width | Species, data=iris) coefs <- data.frame(coef(fits)); names(coefs) = c("Int", "slopes") Then I plot all the fits at once via ggplot: ggplot(iris, aes(x = Petal.Width, y=Sepal.Length)) + geom_point(shape=1,size = 0.5)+ geom_abline(aes(intercept= Int , slope=slopes), color='grey', data=coefs) Can someone help me to do it in the base graphics way? A: plot(Sepal.Length ~ Petal.Width, data = iris) lapply(fits, abline)
[ "stackoverflow", "0001897838.txt" ]
Q: "read more" link in mootools I need a plugin for mootools like this. It's just a simple button which, when clicked, opens up a hidden portion of a div with an animation. When the page is loaded it closes to a point (truncating to some x characters) in the same div. If you take a look at the link, you'll understand... But I need it for mootools, not jQuery. :( Thanks. :) A: The best place to look at is the official Mootools plugin repository but it doesn't look like there is a Mootools equivalent. Converting the jQuery plugin to Mootools may not be that difficult, at least porting the minimal features you want to use. Good luck. EDIT: see this expander experiment
[ "stackoverflow", "0004901313.txt" ]
Q: Use Android GPS to detect and connect with other phones So I asked something similar yesterday and did receive an answer to my question, however I don't really think I asked it correctly and therefore didn't receive the exact information I needed. I'm in search of an API, some open source code, or even just a way that someone else has achieved this on the Android. I'm making an app that needs to find all other Android devices within a specified radius. For example, when you open your Android Google Maps App, and you search for say "Restaurants [ZipCode]", it uses a radius modified from your zip code and finds all of those places. The GPS gets YOUR location, and maps uses that information to find restaurants within an address close to that passed in location. Instead, I want to be able to use the GPS to find my location (as it can now easily), but instead of finding things on a map (which is already built in), I want to be able to find other GPS enabled Android phones. I get that they will have to be broadcasting their GPS signal at the same time as well (since they don't have their data stored with some sort of central database as a restaurant would). However, I don't just want to FIND these phones, I want to send/receive data from these phones (with correct permissions obviously). Now, I've found things like the Bump API. However, BUMP uses the phones sensors to spark this search. So basically, if you "bump" your phone with another and have the app running, it will THEN go ahead and use GPS to find the location of the other phone you just bumped with and exchange data between them. This is like EXACTLY what I want to do however in their API, they do not provide the functionality to just say, "Hey, give me all phones within a mile from me." I've also found API's that can do exactly what I need but they have to be on the same Bluetooth range or on the same Wi-Fi network, which doesn't suit what I need at all. Do you guys know of anything that can fit exactly what I need that already exists? Or a way to maybe modify Bump API (if you've done it), to not have to use the phone sensors and find phone information directly through GPS for phones around you? Or is there something that exists over a 3g/4g network instead of only wi-fi/Bluetooth? Thanks guys. A: Instead of frequently posting locations to an external server, couldn't the GPS realize other things broadcasting a GPS signal at a very specific time and send/receive data from them? The only things that are "broadcasting a GPS signal" are satellites. We would like to accomplish this without the use of an external server. You have no choice but to use an external server, whether you like it or not, both for discovery and for later communication. Do you guys know of anything that can fit exactly what I need that already exists? Foursquare, Google Latitude, Yahoo Fire Eagle, and so on. A: To do this via GPS, you would have to have all the phones frequently posting their locations to a network server, which could then inform them of others nearby. Needless to say this would be opt-in only! And it may have negative consequences for battery life, unless you make it update infrequently, which may limit its usability. The advantage of having an explicit trigger action to both phones is that they only need to query the GPS and inform the server to find each other by location when they've both been triggered.
[ "stackoverflow", "0001592209.txt" ]
Q: WPF Architecture and Direct3D graphics acceleration After reading the wikipedia article on WPF architecture, I am a bit confused with the benefits that WPF will offer me. (wikipedia is not a good research reference, but i found it useful). I have some questions 1) WPF uses d3d surfaces to render. However, the scenegraph is rendered into the d3d surface by the media integrated layer, which runs on the CPU. Is this true ? 2) I just found out by asking a question here that bitmaps dont use native resources. Does this mean that if i use alot of images, the MIL will copy each when rendering, rather than storing the bitmaps on the video card as a texture ? 3) The article mentions that WPF uses the painters algorithm which is back to front. Thats painfully slow. Is there any rational why WPF omits using Z-buffering and rendering front to back ? I am guessing its because the simplest way to handle transparency, but it seems weak. The reason i ask is that i am thinking it wont be wise for me to put hundreds of buttons on a screen even though my colleagues are saying its directx accelerated. I dont quite believe that whole directx accelerated bit about WPF. I used to work on video games and my memory of writing d3d and opengl code tells me to be cautious. A: For questions #1 and #3 you might want to check out this section of the SDK that discusses the Visual class and how it's rendering instructions are exchanged between the higher level framework and the media integration layer (MIL). It also discusses why the painters algorithm is used. For #2, no that is most definitely not the case. The bitmap data will be moved to the hardware and cached there.
[ "stackoverflow", "0022513140.txt" ]
Q: ZF2 Translation I have two modules - Application and StickyNotes. I need to use translation on all pages. What I do: 1) In view: <?=$this->translate('Home');?> 2) In Application\Module.php: public function onBootstrap(MvcEvent $e) { $translator = $e->getApplication()->getServiceManager()->get('translator'); $eventManager = $e->getApplication()->getEventManager(); $moduleRouteListener = new ModuleRouteListener(); $moduleRouteListener->attach($eventManager); $app = $e->getParam('application'); $app->getEventManager()->attach('render', array($this, 'setLayoutTitle')); $translator->setLocale('ru_RU'); echo $translator->getLocale(); //ru_RU } 3) In StickyNotes\Module.php: public function onBootstrap(MvcEvent $e) { $translator = $e->getApplication()->getServiceManager()->get('translator'); $translator->setLocale('ru_RU'); echo $translator->getLocale(); //ru_RU } 4) Application\..\module.config.php: 'service_manager' => array( 'factories' => array( 'translator' => 'Zend\I18n\Translator\TranslatorServiceFactory', ), ), 'aliases' => array( 'translator' => 'MvcTranslator', ), 'translator' => array( 'locale' => 'en_US', 'translation_file_patterns' => array( array( 'type' => 'gettext', 'base_dir' => __DIR__ . '/../language', 'pattern' => '%s.mo', ), ), ), 5) StickyNotes\..\module.config.php same: 'service_manager' => array( 'factories' => array( 'translator' => 'Zend\I18n\Translator\TranslatorServiceFactory', ), ), 'aliases' => array( 'translator' => 'MvcTranslator', ), 'translator' => array( 'locale' => 'en_US', 'translation_file_patterns' => array( array( 'type' => 'gettext', 'base_dir' => __DIR__ . '/../language', 'pattern' => '%s.mo', ), ), ), If i try $translator->getLocale(); output 'ru_RU', but translation don`t work. Also, if I manually change 'locale' => 'en_US', to 'locale' => 'ru_RU', translation work fine. Thanks for the answers! A: in Application\Module.php public function onBootstrap(MvcEvent $e) { $translator = $e->getApplication()->getServiceManager()->get('translator'); $lang = $e->getRequest()->getQuery('lang'); // new language $session = new Container('base'); if($lang == null && $lang == ''){ if ($session->offsetExists('lang')) { $lang = $session->offsetGet('lang'); // current language }else{ $lang = Settings::DEFAULT_LANGUAGE; // default language } } $session->offsetSet('lang', $lang); $loc = Settings::$locations[$lang]; $translator ->setLocale($loc) ->setFallbackLocale(Settings::DEFAULT_LANGUAGE .'_' . Settings::DEFAULT_LOCATION); } and Settings class class Settings{ const DEFAULT_LOCATION = 'IR'; const DEFAULT_LANGUAGE = 'fa'; public static $locations = array( 'fa'=>'fa_IR', 'sa'=>'sa_SA',//Arabic (sa, sa-SA) 'tr'=>'tr_TR', 'en'=>'en_US' ); }
[ "stackoverflow", "0020825229.txt" ]
Q: Android: actionbar triggers spinner issue Android: I would like to create an Spinner triggered from the ActionBar. I am using the following code. What I see is that on initialisation the menu-item 0 (without a click) is run. I also see that selecting a further menu-item-1 is not working. What's wrong with the following code? Both problems I have localized in the code: Res/menu/main.xml: <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menu_spinner1" android:showAsAction="always" android:orderInCategory="1" android:actionViewClass="android.widget.Spinner"> </item> The code in the MainActivity: public boolean onCreateOptionsMenu(Menu menu) { String[] spinnerEntries = new String[]{ "Item-1", "Item-2", "Item-3"}; MenuInflater mi=getMenuInflater(); mi.inflate( R.menu.main, menu); mSpinnerItem1 = menu.findItem( R.id.menu_spinner1); View view1 = mSpinnerItem1.getActionView(); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, spinnerEntries); adapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item); if (view1 instanceof Spinner) { final Spinner spinner = (Spinner) view1; spinner.setAdapter( adapter); spinner.setPopupBackgroundResource(R.drawable.spinner); spinner.setOnItemSelectedListener( new OnItemSelectedListener() { @Override public void onItemSelected( AdapterView<?> arg0, View arg1, int arg2, long arg3) { switch( arg2) { case 0: // Problem 1: // first this code is executed before any click happened // // Problem 2: // then ... the code is executed only after I clicked first // on item-2 or item-3 and then to item-1 break; case 1: // code for option 2 etc. } } } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); } return true; } A: First, when you set Adapter to Spinner and when Spinner is added to window(added to ActionBar), then Spinner will pick the first item View (whose position is zero in Adapter) from the Adapter and call OnItemSelectedListener(first received callback from Spinner irrespective of you have selected or not, Spinner will select). Second, If you select the item from the Spinner which is already previously selected, then you won't receive OnItemSelectedListener callback from the Spinner...
[ "stackoverflow", "0037587689.txt" ]
Q: The app crashes while trying to load notification 06-02 06:43:35.978 4227-4227/? I/art: Late-enabling -Xcheck:jni 06-02 06:43:36.088 4227-4227/meet.projectoklahoma W/System: ClassLoader referenced unknown path: /data/app/meet.projectoklahoma-1/lib/x86 06-02 06:43:36.183 4227-4227/meet.projectoklahoma I/GMPM: App measurement is starting up, version: 8487 06-02 06:43:36.183 4227-4227/meet.projectoklahoma I/GMPM: To enable debug logging run: adb shell setprop log.tag.GMPM VERBOSE 06-02 06:43:36.473 4227-4254/meet.projectoklahoma D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true 06-02 06:43:36.516 4227-4254/meet.projectoklahoma D/libEGL: loaded /system/lib/egl/libEGL_emulation.so 06-02 06:43:36.517 4227-4254/meet.projectoklahoma D/libEGL: loaded /system/lib/egl/libGLESv1_CM_emulation.so 06-02 06:43:36.532 4227-4254/meet.projectoklahoma D/libEGL: loaded /system/lib/egl/libGLESv2_emulation.so 06-02 06:43:36.575 4227-4254/meet.projectoklahoma I/OpenGLRenderer: Initialized EGL, version 1.4 06-02 06:43:36.658 4227-4254/meet.projectoklahoma W/EGL_emulation: eglSurfaceAttrib not implemented 06-02 06:43:36.658 4227-4254/meet.projectoklahoma W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xed6fcd40, error=EGL_SUCCESS 06-02 06:44:56.177 4227-4254/meet.projectoklahoma W/EGL_emulation: eglSurfaceAttrib not implemented 06-02 06:44:56.177 4227-4254/meet.projectoklahoma W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xed6ff6c0, error=EGL_SUCCESS 06-02 06:44:56.585 4227-4227/meet.projectoklahoma I/Choreographer: Skipped 30 frames! The application may be doing too much work on its main thread. 06-02 06:44:57.062 4227-4254/meet.projectoklahoma E/Surface: getSlotFromBufferLocked: unknown buffer: 0xf3dd7240 06-02 06:44:59.933 4227-4227/meet.projectoklahoma D/AndroidRuntime: Shutting down VM 06-02 06:44:59.934 4227-4227/meet.projectoklahoma E/AndroidRuntime: FATAL EXCEPTION: main Process: meet.projectoklahoma, PID: 4227 android.app.RemoteServiceException: Bad notification posted from package meet.projectoklahoma: Couldn't expand RemoteViews for: StatusBarNotification(pkg=meet.projectoklahoma user=UserHandle{0} id=1 tag=null score=0 key=0|meet.projectoklahoma|1|null|10060: Notification(pri=0 contentView=meet.projectoklahoma/0x7f04001c vibrate=null sound=null defaults=0x0 flags=0x0 color=0x00000000 vis=PRIVATE)) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1507) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) After the user logs in, the app should load notification with the waiting events for him, but it crushes instead. The code above is the error that I get after it crashes. This is the code in order to send the notification: private void sendNotification() { if (!LocalDataBase.getCurrentUser().getWaitingList().isEmpty()) { int notificationID=1; setContentView(R.layout.activity_events_status_bar2); TextView eventName=(TextView)findViewById(R.id.incomingEventsNameText2) ; Event eventToDisplay=LocalDataBase.getCurrentUser().getWaitingList().get(0); eventName.setTag(eventToDisplay); Intent showEvents=new Intent(this, EventsStatusBarActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, showEvents, 0); RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.activity_events_status_bar2); contentView.setTextViewText(R.id.incomingEventsNameText2, eventToDisplay.getName()); contentView.setOnClickPendingIntent(R.id.attendButton,pendingIntent); contentView.setOnClickPendingIntent(R.id.declineButton,pendingIntent); NotificationCompat.Builder eventsNotification= new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.notification_template_icon_bg) .setContentText("Incoming notifications") .setContent(contentView); eventsNotification.setContentIntent(pendingIntent); NotificationManager notificationManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(notificationID,eventsNotification.build()); } } This is the code for activity_events_status_bar2: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="match_parent" android:weightSum="1"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Event Name" android:tag="event" android:id="@+id/incomingEventsNameText2" android:layout_gravity="left" android:textColor="@android:color/black" android:textSize="22sp" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignBottom="@+id/attendButton" /> <Button style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Going" android:id="@+id/attendButton" android:layout_alignParentTop="true" android:layout_toLeftOf="@+id/declineButton" android:layout_toStartOf="@+id/declineButton" android:onClick="selectGoing"/> <Button style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Not Going" android:id="@+id/declineButton" android:layout_alignBottom="@+id/attendButton" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:onClick="selectNotGoing"/> </RelativeLayout> A: You may have to work around it by applying the contentView directly: NotificationCompat.Builder eventsNotification= new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.notification_template_icon_bg) .setContentText("Incoming notifications") .setContent(contentView); eventsNotification.setContentIntent(pendingIntent); NotificationManager notificationManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Notification myNotification = eventsNotification.build(); notification.contentView = contentView; notificationManager.notify(notificationID,myNotification);
[ "travel.stackexchange", "0000104584.txt" ]
Q: Are nursing rooms free at Changi? The airport's website shows there are baby care rooms at Changi. But I cannot find anywhere if there is a fee to use the room. Are the baby care rooms free to use? Their website also says there are strollers that can be loaned on a first-come first-serve basis (assuming they are fee free). Does anyone know if the airport has enough strollers? Are they easily available? This is for a traveller on an international flight, transiting through Changi. A: This article complains about a man barging into a baby care room at Changi airport to fill up his hot water flask, which strongly implies there is no charge to use the rooms.
[ "stackoverflow", "0021302976.txt" ]
Q: Data Image base 64 Could someone please explain how does this work? data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAACDUlEQVR4Xu2Yz6/BQBDHpxoEcfTjVBVx4yjEv+/EQdwa14pTE04OBO+92WSavqoXOuFp+u1JY3d29rvfmQ9r7Xa7L8rxY0EAOAAlgB6Q4x5IaIKgACgACoACoECOFQAGgUFgEBgEBnMMAfwZAgaBQWAQGAQGgcEcK6DG4Pl8ptlsRpfLxcjYarVoOBz+knSz2dB6vU78Lkn7V8S8d8YqAa7XK83ncyoUCjQej2m5XNIPVmkwGFC73TZrypjD4fCQAK+I+ZfBVQLwZlerFXU6Her1eonreJ5HQRAQn2qj0TDukHm1Ws0Ix2O2260RrlQqpYqZtopVAoi1y+UyHY9Hk0O32w3FkI06jkO+74cC8Dh2y36/p8lkQovFgqrVqhFDEzONCCoB5OSk7qMl0Gw2w/Lo9/vmVMUBnGi0zi3Loul0SpVKJXRDmphvF0BOS049+n46nW5sHRVAXMAuiTZObcxnRVA5IN4DJHnXdU3dc+OLP/V63Vhd5haLRVM+0jg1MZ/dPI9XCZDUsbmuxc6SkGxKHCDzGJ2j0cj0A/7Mwti2fUOWR2Km2bxagHgt83sUgfcEkN4RLx0phfjvgEdi/psAaRf+lHmqEviUTWjygAC4EcKNEG6EcCOk6aJZnwsKgAKgACgACmS9k2vyBwVAAVAAFAAFNF0063NBAVAAFAAFQIGsd3JN/qBA3inwDTUHcp+19ttaAAAAAElFTkSuQmCC And how does this generate an image and how to create it? I found this a lot of times in html. Follow up question How does this differ on a url as a src in terms of loading time and http request? does this make loading time faster? How would it scale if i am to use, say 50 images? Also. if this is better in uploading, converting images to base64 and saving it on database rather than a url would make a site better? A: You can use it like this: <img alt="Embedded Image" src="data:image/png;base64,{base64 encoding}" /> It's used to generate new images, or to store images as plain text. You can read more about base64 encoding here on Wikipedia: http://nl.wikipedia.org/wiki/Base64 How does it work? The characters are converted to binair They take a group of 6 bits The groups will be converted to decimal For each decimal they take the number on the position n+1 which is in the base64 character table, the numbers variate between 0 and 63. It does not always come out correctly, since the number of bits must be a multiple of 6. If this is the case, there will be, depending on the required number of additional bits, put 2 or 4 zeros at the end. If so, there will be added a = at the end. Base64 character table ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ Different languages and usage PHP <?php base64_encode($source); // Or decode: base64_decode($source); Python >>> import base64 >>> encoded = base64.b64encode('data to be encoded') >>> encoded 'ZGF0YSB0byBiZSBlbmNvZGVk' >>> data = base64.b64decode(encoded) >>> data 'data to be encoded' Objective C // Encoding NSData *plainData = [plainString dataUsingEncoding:NSUTF8StringEncoding]; NSString *base64String = [plainData base64EncodedStringWithOptions:0]; NSLog(@"%@", base64String); // Zm9v // Decoding NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0]; NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding]; NSLog(@"%@", decodedString); // foo
[ "stackoverflow", "0048924928.txt" ]
Q: Can someone explain how this weightsum work? and why When i check the design for this code. this WeightSum act totally opposite the way i want. when i set my button weightSum for 70 it takes 30 (total weightSum is 100) vise-versa. <LinearLayout android:weightSum="100" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:layout_weight="70" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Button" /> <ToggleButton android:layout_weight="30" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="ToggleButton" /> </LinearLayout> A: So android:weightSum defines the maximum weight sum of Layout, and it is calculate total sum of the layout_weight of all the its children views. Example:- a LinearLayout having 3 Views(Which can be anything). Now you want to show 3 views equally in screen. So need to put layout_weight to views 1 and your weightSum is 3. <LinearLayout android:weightSum="100" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <View android:layout_weight="70" android:layout_width="0dp" android:layout_height="wrap_content" android:text="Button" /> <View android:layout_weight="30" android:layout_width="fill_parent" android:layout_height="0dp`enter code here`" android:text="ToggleButton" /> </LinearLayout> or You can also put your android:layout_weight in points also like below :- <LinearLayout android:weightSum="1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <View android:layout_weight=".7" android:layout_width="0dp" android:layout_height="wrap_content" android:text="Button" /> <View android:layout_weight=".3" android:layout_width="fill_parent" android:layout_height="0dp`enter code here`" android:text="ToggleButton" /> </LinearLayout> Remember 3 thing before use android:weightSum :- set the android:layout_width of the children to "0dp" set the android:weightSum of the parent (edit: as Jason Moore noticed, this attribute is optional, because by default it is set to the children's layout_weight sum) set the android:layout_weight of each child proportionally (e.g. weightSum="5", three children: layout_weight="1", layout_weight="3", layout_weight="1") A: You need set android:layout_width="0dp" of Button and ToggleButton.
[ "stackoverflow", "0010877903.txt" ]
Q: Check if text in cell is bold I have a table in html. Some cells is bold and some is normal. How I can check if some cell is bold (for example i,j) and get text of that cell without tag . Cells can have only text. If it bold - it should contain tag <b>. For example: <tr> <td> Not bold text </td> <td> <b> Bold text </b> </td> </tr> PS I can't use class or id properties. PSS It would be better without jQuery code, we are not using it for now A: See this answer how to get a reference to the cell: https://stackoverflow.com/a/3052862/34088 You can get the first child with cell.firstChild. This gives you a text node or a <B> node. You can check this with the node.nodeType which is 1 for DOM nodes or 3 for text nodes. Which gives: function isBold(table, rowIdx, columnIdx) { var row = table.rows[rowIdx]; var cell = row.cells[columnIdx]; var node = cell.firstChild; if( node.nodeType === 3 ) { return false; } return node.nodeName === 'b' || node.nodeName === 'B'; }
[ "stackoverflow", "0062077084.txt" ]
Q: How do I dispatch two different properties to the selector? I have a selector that is dependent on another one, which they need the userId to be able to "work". But now I would like to create a selector that receives the "userId" and also receives another property called "userFriend". What happens is that he is complaining about this parameter pass, as he is only finding one property, which is the "userId". ERROR 1: Property 'userFriend' does not exist on type '{ userId: any; }' ERROR 2: TS2339: Property 'userFriend' does not exist on type '{userId: any; } '. 34 (latestReadMessages, totalUnreadMessages, {userId, userFriend}) => { ~~~~~~~~~~ src / app / services / store / chat / chat-selectors.service.ts: 34: 26 - error TS2769: No overload matches this call. Overload 1 of 8, '(mapFn: (state: object, props: {userId: any;}) => IChatFriendLatestMessageList, props ?: {userId: any;}): (source $: Observable <object>) => Observable <...> ', gave the following error. Argument of type '{userId: string; userFriend: IUser; } 'is not assignable to parameter of type' {userId: any; } '. Object literal may only specify known properties, and 'userFriend' does not exist in type '{userId: any; } '. Overload 2 of 8, '(key1: "user" | "chat", key2: "loading" | "data" | "dataError" | "ids" | "entities"): (source $: Observable <IStoreState>) = > Observable <any> ', gave the following error. Argument of type 'MemoizedSelectorWithProps <object, {userId: any; }, IChatFriendLatestMessageList, DefaultProjectorFn <IChatFriendLatestMessageList>> 'is not assignable to parameter of type' "user" | "chat" '. Type 'MemoizedSelectorWithProps <object, {userId: any; }, IChatFriendLatestMessageList, DefaultProjectorFn <IChatFriendLatestMessageList>> 'is not assignable to type' "chat" '. 34 return this.store.pipe (select (selector.getFriendLatestMessageList, {userId, userFriend})); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~ SELECTORS: export const messagesById = createSelector(selectAll, (chat: IChat[], { userId }) => { let messageIndex = 0; return chat.map((props, index) => { if (props.id === userId) { messageIndex = index; return props.messages; } else { return []; } })[messageIndex]; }); export const isLoading = createSelector(FEATURE_SELECTOR, ({ loading }) => loading); export const error = createSelector(FEATURE_SELECTOR, ({ dataError }) => dataError); export const friendMessages = createSelector(messagesById, messages => messages.filter(msg => !msg.isMain)); export const friendLatestMessage = createSelector(friendMessages, messages => messages[messages.length - 1]); export const friendLatestReadMessages = createSelector(friendMessages, messages => messages.filter(msg => msg.isRead)); export const friendLatestUnreadMessages = createSelector(friendMessages, messages => messages.filter(msg => !msg.isRead) ); export const totalUnreadMessagesFriend = createSelector(friendLatestUnreadMessages, messages => messages.length); export const getFriendLatestMessageList = createSelector( friendLatestMessage, totalUnreadMessagesFriend, (latestReadMessages, totalUnreadMessages, { userId, userFriend }) => { const latestMessageList: IChatFriendLatestMessageList = { user: userFriend.id, informations: { chatMessage: [latestReadMessages], isNewLastMessage: !userFriend.isClicked && totalUnreadMessages > 0, total: totalUnreadMessages, }, }; return latestMessageList; } ); SERVICE FOR DISPATCH SELECTORS: getFriendLatestMessageListById(userId: string, user: IUser): Observable<IChatFriendLatestMessageList> { return this.store.pipe(select(selector.getFriendLatestMessageList, { userId, user })); } INTERFACE: export interface IChatFriendLatestMessageList { userFriend: IUser; informations: { chatMessage: IChatMessage[]; isNewLastMessage: boolean; total: number; }; } ERROR SCREENSHOT A: The problem is caused because this selector has own props and in the same time it uses parent selectors that also have own props. NGRX doesn't support it and to make it working we need to incapsulate the parent selectors. export const getFriendLatestMessageList = createSelector( s => s, // selecting the whole store. (store, { userId, userFriend }) => { // selecting our state. const latestReadMessages = friendLatestMessage(store, { userId }); const totalUnreadMessages = totalUnreadMessagesFriend(store, { userId }); // using them. const latestMessageList: IChatFriendLatestMessageList = { user: userFriend, informations: { chatMessage: [latestReadMessages], isNewLastMessage: !userFriend.isClicked && totalUnreadMessages > 0, total: totalUnreadMessages, }, }; return latestMessageList; } );
[ "tex.stackexchange", "0000542196.txt" ]
Q: two column AND multi-line align I am trying to get the 3rd equality (from the top, the equations for delta \phi^i) to align. \begin{align*} U(x) &= e^{i\theta^a(x)T^a} & U(x) &= e^{-\theta^a(x)(t_a)^i{}_j} \\ [T^a,T^b] &= if^{abc}T^c & [t^a,t^b] &= f_{ab}{}^c t^c \\ \delta \phi_i &= i\theta^a(T^a)_{ij} \phi_j & \begin{split} \delta \phi^i &= -\theta^a(t_a)^i{}_j \phi^j \\ &= -\theta^af_{aj}{}^i \phi^j \\ &= \theta^af_{ja}{}^i \phi^j \end{split} \\ A_\mu &= A_\mu{}^a T^a & A_\mu &= A_\mu{}^a t_a \\ A_\mu &\rightarrow U(x) A_\mu U(x)^{-1} - \frac{i}{g} [\partial_\mu U(x)] U(x)^{-1} & A_\mu &\rightarrow U(x) A_\mu U(x)^{-1} - \frac{1}{g} [\partial_\mu U(x)] U(x)^{-1} \end{align*} Here are two related questions How to align a set of multiline equations Aligning two multiline equations A: Use aligned with [t] option? Is this what you're after? \documentclass{extarticle} \usepackage{amsmath} \begin{document} \begin{align*} U(x) &= e^{i\theta^a(x)T^a} & U(x) &= e^{-\theta^a(x)(t_a)^i{}_j} \\ [T^a,T^b] &= if^{abc}T^c & [t^a,t^b] &= f_{ab}{}^c t^c \\ \delta \phi_i &= i\theta^a(T^a)_{ij} \phi_j & \delta \phi^i & \begin{aligned}[t] &= -\theta^a(t_a)^i{}_j \phi^j \\ &= -\theta^af_{aj}{}^i \phi^j \\ &= \theta^af_{ja}{}^i \phi^j \end{aligned} \\ A_\mu &= A_\mu{}^a T^a & A_\mu &= A_\mu{}^a t_a \\ A_\mu &\rightarrow U(x) A_\mu U(x)^{-1} - \frac{i}{g} [\partial_\mu U(x)] U(x)^{-1} & A_\mu &\rightarrow U(x) A_\mu U(x)^{-1} - \frac{1}{g} [\partial_\mu U(x)] U(x)^{-1} \end{align*} \end{document}
[ "stackoverflow", "0009869590.txt" ]
Q: How to set the first letter in a line to caps in notepad++ I want to set the first letter in each line to caps in notepad++..how do I do this? A: You could select the block consisting of only the first column: hold Alt while selecting with the mouse. Then press Ctrl-Shift-U to convert the selected letters to uppercase. This kind of selection is called rectangular selection in the Notepad++ help. You can also define the selection with the keyboard by pressing Alt and Shift and using the cursor keys.
[ "english.stackexchange", "0000267827.txt" ]
Q: What would you call this "double entry" principle in English? There is a system for entering the number of the ball that falls out in a lottery game. It consists of two computers operated by two different people. They each have to enter the ball number they see so it is double-checked. What would you call such thing in English? Double-entry? Double-check? A: I think "double-checked" or "cross-checked" would be more accurate than "redundant" here. If the intention was that the system was still usable even if one of the computers fails altogether, that would be a redundant system, but (I assume) it isn't; the cross-checking that both operators agree on the numbers is a necessary part of the system if we want to detect errors. "cross-checked" is perhaps more precise; the point is to have two independent sources to check against each other, whereas "double-checked" could be a single source being looked at twice. (Though ultimately there's one source, the actual ball with the number.) Compare cross-check and double-check. (The next stage would be to have three operators, and to accept results if two out of three agree. Then the third computer is redundant for error detection, but not for error correction.) A: In engineering, we would call it a redundant system. redundancy: (1b) (engineering) The inclusion of extra components that are not strictly necessary to functioning, in case of failure in other components {ODO} A: This kind of entry is called Two Pass Verification or Double Data Entry. Two people key data into a system, and then the differences are displayed at the end for verification. Two-pass verification, also called double data entry, is a data entry quality control method that was originally employed when data records were entered onto sequential 80-column Hollerith cards with a keypunch. In the first pass through a set of records, the data keystrokes were entered onto each card as the data entry operator typed them. On the second pass through the batch, an operator at a separate machine, called a verifier, entered the same data. The verifier compared the second operator's keystrokes with the contents of the original card. If there were no differences, a verification notch was punched on the right edge of the card. You can read more about it here: https://en.wikipedia.org/wiki/Two_pass_verification.
[ "stackoverflow", "0016796559.txt" ]
Q: Emberjs1.0.0-RC3: undefined when calling and storing controller method in view variable In this jsfiddle, inside the didInsertElement hook, I am trying to call a controller method called eventJSON, which is defined in CalendarsController, I am storing or passing that call to the controller action in a variable called calendarJSON that i declared inside the didInsertElement hook in the CalendarsView. But when I log the result, it gives undefined. Also if I put a debugger inside the didInsertElement hook and inspect the variable in the console, it returns undefined. I want to store the data returned from var calendarJSON = this.get('controller').send('eventJSON'); in variable because I want to subsequently passed that data to fullcalendar jquery. The jsfiddle The controller: App.CalendarsController = Em.ArrayController.extend({ eventJSON: function() { //returns the json of controller's content this.invoke('toJSON'); return this.get('content'); } }); The view: App.CalendarsView = Ember.View.extend({ templateName: 'calendars', attributeBindings: ['id'], id: "mycalendar", didInsertElement: function() { debugger; this._super(); //Right here is the problem var calendarJSON = this.get('controller').send('eventJSON'); console.log(calendarJSON); this.$().fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, editable: true, events: calendarJSON }); } }); A: I modified to what is pasted below to get it to run. Basically, I wasn't using the keyword return to return anything from the controller. Secondly, I broke the steps to accessing the controller action into 2 steps. In step 1, I fetch the controller and then I call the event on it as shown below: var controller = this.get('controller'); var calendarJSON = controller.eventJSON(); The working jsfiddle. The adjusted code: App.CalendarsController = Em.ArrayController.extend({ eventJSON: function() { m = this.get('content'); m.invoke('toJSON'); console.log(m); return m; } }); The view: App.CalendarsView = Ember.View.extend({ templateName: 'calendars', attributeBindings: ['id'], id: "mycalendar", didInsertElement: function() { this._super(); var controller = this.get('controller'); var calendarJSON = controller.eventJSON(); console.log(calendarJSON); this.$().fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, editable: true, events: calendarJSON }); } });
[ "stackoverflow", "0062540126.txt" ]
Q: how to get group by dataframe on the basis of year or week and how to combine two dataset in python Dataset 1 : Sales Representative ID, Customer ID, Order Date, Revenue Dataset 2 : Manager ID, Sales Representative ID, Create Date, Termination date Given Above 2 datasets where “Dataset 1” represents daily revenue data related to a customer and the sales representative associated with that customer AND “Dataset 2” has mapping of sales representative with the manager id associated with it in that particular point in time where “Create Date” represents when new association is created and “Termination date” represents when association is terminated. i have to calculate year,month,week and day wise revenue for each manager id for every date. Output Dataset: Order Date, Year/Month/Week/Day,Manager ID, Total Revenue I am confused with two things here how to combine these two dataset and secondly how to get the revenue week,year and day wise like i dont know any way in pandas to group by them according to above. Please help dataset1 = { 'srid':[1,2,3,1,5], 'custid':[11,12,43,12,34], 'orderdate':["1/2/2019","1/2/2019","2/2/2019","1/2/2019","1/2/2019"], 'Rev':[100,101,102,103,17] } dataset2 = { 'manid':[101,102,103,104,105], 'srid':[1,2,1,3,5], 'CreateDate':["1/1/2019","1/1/2019","3/1/2019","1/1/2019","1/1/2019"], 'TerminationDate':["2/1/2019","3/1/2019","5/1/2019","2/1/2019","2/1/2019"] } A: Try this: df1 = pd.DataFrame(dataset1) df2 = pd.DataFrame(dataset2) df = df1.merge(df2, on=['srid']) df['orderdate'] = pd.to_datetime(df['orderdate']) df['CreateDate'] = pd.to_datetime(df['CreateDate']) df['TerminationDate'] = pd.to_datetime(df['TerminationDate']) # Daily df_d = df.groupby(by=['manid', pd.Grouper(key='orderdate', freq='D')]).agg({'Rev': 'sum'}) # Monthly df_m = df.groupby(by=['manid', pd.Grouper(key='orderdate', freq='M')]).agg({'Rev': 'sum'}) # Weekly df_w = df.groupby(by=['manid', pd.Grouper(key='orderdate', freq='W')]).agg({'Rev': 'sum'}) # Yearly df_y = df.groupby(by=['manid', pd.Grouper(key='orderdate', freq='Y')]).agg({'Rev': 'sum'}) print(df_y) Rev manid orderdate 101 2019-12-31 203 102 2019-12-31 101 103 2019-12-31 203 104 2019-12-31 102 105 2019-12-31 17
[ "cstheory.stackexchange", "0000002147.txt" ]
Q: UGC hardness of the predicate $NAE(x_1, ..., x_\ell)$ for $x_i \in GF(k)$? Background: In Subhash Khot's original UGC paper (PDF), he proves the UG-hardness of deciding whether a given CSP instance with constraints all of the form Not-all-equal(a, b, c) over a ternary alphabet admits an assignment satisfying 1-$\epsilon$ of the constraints or whether there exist no assignments satisying $\frac{8}{9}+\epsilon$ of the constraints, for arbitrarily small $\epsilon > 0$. I'm curious whether this result has been generalized for any combination of $\ell$-ary constraints for $\ell \ge 3$ and variable domains of size $k \ge 3$ where $\ell \ne k \ne 3$. That is, Question: Are there any known hardness of approximation results for the predicate $NAE(x_1, \dots, x_\ell)$ for $x_i \in GF(k)$ for $\ell, k \ge 3$ and $\ell \ne k \ne 3$? I'm especially interested in the combination of values $\ell = k$; e.g., the predicate Not-all-equal($x_1, \dots, x_k$) for $x_1 \dots, x_k \in GF(k)$. A: I landed on this page from a search about NAE-3SAT. I am pretty sure that for the problem you are asking, it should be NP-hard to tell if the instance is satisfiable, or if at most $1-1/k^{\ell-1}+\epsilon$ fraction of constraints can be satisfied. That is, a tight hardness result (matching what simply picking a random assignment would achieve), for satisfiable instances, and no need for the UGC. For $k=2$ and $\ell \ge 4$, this follows from Hastad's factor 7/8+epsilon inapproximability result for 4-set-splitting (which can then be reduced to k-set splitting for $k > 4$). If negations are okay, one can also use his tight hardness result for Max ($\ell-1$)-SAT. For $k=\ell=3$, Khot proved this in a FOCS 2002 paper "Hardness of coloring 3-colorable 3-uniform hypergraphs." (That is, he removed the original UGC assumption.) For $\ell=3$ and arbitrary $k\ge 3$, Engebretsen and I proved such a result in "Is constraint satisfaction over two variables always easy? Random Struct. Algorithms 25(2): 150-178 (2004)". However, I think our result required "folding" i.e., the constraints will actually be of the form NAE($x_i+a,x_j+b,x_k$) for some constants $a,b$. (This is the analog of allowing negations of Boolean variables.) For the general case, I don't know if this has been written down anywhere. But if you really need it, I can probably find something or check the claim. A: Prasad Raghavendra in his STOC'08 Best Paper proved, assuming the Unique Games Conjecture, that a simple semidefinite programming algorithm gives the best approximation for any constraint satisfaction problem (including NAE) with constraints on constant number of variables each and with constant alphabet. To actually know what is the hardness factor for NAE, you need to understand how well the simple algorithm does for it, i.e., prove an integrality gap for the program. I don't know whether someone already did that for NAE in its full generality, or not. A: I realized that what I claimed above is in fact known. For $\ell = 3$ and arbitrary $k \ge 3$, this is in Khot's FOCS 2002 paper "Hardness of coloring 3-colorable 3-uniform hypergraphs" (the paper actually talks about general $k$, though the title only talks about the 3-colorable case). For $\ell \ge 4$ and $k \ge 2$, in fact a stronger hardness is known. Even if there is in fact an assignment of just two values to the variables that satisfies all NAE constraints (in other words the $\ell$-uniform hypergraph can be colored using 2 colors without any monochromatic hyperedge), it is still NP-hard to find an assignment from a domain size $k$ which satisfies at least $1-1/k^{\ell-1}+\epsilon$ NAE constraints (for arbitrary constant $\epsilon > 0$). This follows easily from the fact that the known inapproximability result for hypergraph 2-coloring gives a strong density statement in the soundness case. The formal statement appears in my SODA 2011 paper with Ali Sinop "The complexity of finding independent sets in bounded degree (hyper)graphs of low chromatic number" (Lemma 2.3 in the SODA final version, and Lemma 2.8 in the older version available on ECCC http://eccc.hpi-web.de/report/2010/111/).
[ "stackoverflow", "0034679845.txt" ]
Q: Cassandra Lightweight Transaction rpc_timeout I have Cassandra 2.0.10 cqlsh 4.1.1 cassandra-driver-core-2.1.6 write_request_timeout_in_ms: 2000 ONE node with SimpleStrategy replication I have table CREATE TABLE aaa ( serial text, time timestamp, id bigint, source text, PRIMARY KEY ((serial)) ) WITH bloom_filter_fp_chance=0.010000 AND caching='KEYS_ONLY' AND comment='' AND dclocal_read_repair_chance=0.100000 AND gc_grace_seconds=864000 AND index_interval=128 AND read_repair_chance=0.000000 AND replicate_on_write='true' AND populate_io_cache_on_flush='false' AND default_time_to_live=0 AND speculative_retry='99.0PERCENTILE' AND memtable_flush_period_in_ms=0 AND compaction={'class': 'SizeTieredCompactionStrategy'} AND compression={'sstable_compression': 'LZ4Compressor'}; I tried to use Cassandra Lightweight Transaction to put some data to this table insert into aaa (serial, id, source, time) values ('123', 456, 'test source', '2000-01-01 00:00:00+0000') IF NOT EXISTS; If I use cqlsh I have reply Request did not complete within rpc_timeout. If I use datastax java driver I have an exception com.datastax.driver.core.exceptions.WriteTimeoutException: Cassandra timeout during write query at consistency SERIAL (1 replica were required but only 0 acknowledged the write) at com.datastax.driver.core.exceptions.WriteTimeoutException.copy(WriteTimeoutException.java:54) ~[cassandra-driver-core-2.1.6.jar:na] at com.datastax.driver.core.Responses$Error.asException(Responses.java:98) ~[cassandra-driver-core-2.1.6.jar:na] at com.datastax.driver.core.DefaultResultSetFuture.onSet(DefaultResultSetFuture.java:140) ~[cassandra-driver-core-2.1.6.jar:na] ... So it seems I have a problem with cassandra configuration Maybe somebody helps me :) Thanks in advance A: I think the timeout error is probably misleading and making the timeout bigger won't help. For some reason the replica that owns that key isn't responding to the request, but I don't see enough information to know what would be causing that. The insert statement itself looks valid. One thing I see is that you are using an old version of Cassandra and might want to consider upgrading to a newer release.
[ "stackoverflow", "0008897456.txt" ]
Q: Android - Keystores, In-App purchasing, and outsourced development I am currently having an Android application developed by an outside third party. We are at the point where we are ready to implement/test In-App purchasing, but in order to proceed with that we must upload the application to the market first (so we can make the In-App Purchase ID's). In order to upload to the Market, you must sign the application with a non-debug key. My questions are: What is the best way to go about this and maintain the privacy of my keystore? Can the keystore be changed later without affecting functionality of the app? What is a good back-and-forth process that would make this work, assuming I will not be coding the In-App purchasing myself? A: The keypair used for signing must remain unchanged, otherwise you can't update existing application in Market. Consequently right approach is that the developer gives you an unsigned APK and you sign it locally, then submit to Market. As Bruno Oliveira suggested in another answer, for debug purposes you can create an application and sign it with the key shared between you and developer. But in this case be ready to create and submit a brand new application for release for the reason I mentioned above.
[ "stackoverflow", "0002860905.txt" ]
Q: How can I set the class for a element in a Zend_Form? I'm trying to set the width of the style for a group of < dt > elements in a Zend_Form. Is there a way to set a class for a dt element, so the end result would be something like this: <dt id="name-label" class="xyz" > // trying to add the 'class="xyz" <label class="required" for="name">Name:</label> </dt> <dd id="name-element"> <input type="text" maxlength="255" size="30" value="" id="name" name="name"> </dd> A: I finally found the solution - i needed to wrap the dt,dd elements in a < dl > tag and set the class of the < dl > tag. then i set the css for the < dt > elements through the < dl > class, like so: Sample element: $question = new Zend_Form_Element_TextArea('question'.$i); $question->setLabel('Question '.$i.':') ->setAttrib('rows', 10)->setAttrib('cols', 40)->setAttrib('class', 'richtexteditor') ->addFilter('StringTrim') ->addDecorator('HtmlTag', array('tag' => 'dd','id'=> 'question'.$i.'-element', 'style'=>'width:350px;max-height:202px;' ) ) ->addDecorator(array('dlTag'=>'HtmlTag'), array('tag' => 'dl','class'=> 'xyz')) //added this line ->addDecorator('Errors', array('class'=>'custom-errors')) ->setOptions(array('onkeyup'=>'textCounter();', 'onkeydown'=>'textCounter();' ) ); Then, i added the following to my css file: dl.xyz{ margin: 0; } .xyz dt { width:97px; padding-left: 0px; margin-left: -15px; } this achieves what i was aiming for all along - modifying certain dt elements' style while retaining a general/default < dt >style for the entire form.
[ "travel.stackexchange", "0000013497.txt" ]
Q: Is my social security number from a previous temporary work visa still valid? I worked in America as a snowboard instructor for a few months in 2008, on an H2B visa. For that I obtained a social security number. The card has printed on it "Valid for work only with DHS authorization". I haven't worked in America since then, but have recently been approved for an H1B visa so will be moving there shortly. Is my social security number from 2008 still valid, or will I need to get a new one? A: If you have ever had an SSN, that is your number for life. Even if you become ineligible to apply for one, if you had it, you don't lose it. “Valid for work only with DHS authorization” indicates that having a social security card isn't in itself proof that you are entitled to work in the US. For example, you might still have a valid social security card after your work visa has expired, or you might have been issued a social security card without being allowed to work in the US.
[ "stackoverflow", "0051141066.txt" ]
Q: How to get field which has fifth in the order of the highest value in pandas I am using pandas and I have dataset something like this: **ID name total-cost** 1 a 7 2 b 4 3 c 1 4 e 6 5 f 80 6 k 85 So I need to get the fifth value in the order of the highest of total-cost, which is here 4 [85 80 7 6 4 1]. Not name, not ID, just a value. A: You could sort and then use iloc to get the fifth value: df.sort_values('total-cost', ascending=False)['total-cost'].iloc[4] Or use nlargest(5) to get the 5 largest , and then use iloc to get the last value from that: df['total-cost'].nlargest(5).iloc[-1]
[ "stackoverflow", "0004345563.txt" ]
Q: Rails in depth plugin tutorial I want to learn rails plugins, in a very detailed way so I can understand how the rails plugins at github are designed. I'm looking for something that goes over things at a high level, but then goes detailed. plugins, generators, etc. does this exist? A: I think what you are really looking for is deep understanding of Ruby Object Model and Ruby Metaprogramming. Crystal clear understanding of both of them is critical to be able to build variety of useful rails plugins. I would not recommend diving head first into rails plugin development without these two. Unfortunately, I don't have many resources that would give you deep insights in them but here is something to get you started. http://www.hokstad.com/ruby-object-model.html http://www.ruby-doc.org/docs/Understanding%20Ruby%27s%20Object%20Model/ChrisPine_UROM.ppt http://www.rubyfleebie.com/3-steps-to-understand-how-classes-and-objects-work-in-ruby/ Also, I highly recommend this book - Ruby Metaprogramming by Dave Thomas and also careful reading of The Ruby Way. Once you are thorough with the object model and metaprogramming, understanding the design of rails becomes easier and with experience, it starts to come naturally. Extending the same with plugins and gems would whole lot easier as well.
[ "stackoverflow", "0013331016.txt" ]
Q: Andengine array of Sprites error I am new to android game development and I'm using AndEngine GLES 2 Java. I get an error which is to do with my array(face1) having an illegal index. I can't solve the problem so I need some help. Code: @Override public Scene onCreateScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new Background(0.09804f, 0.6274f, 0.8784f)); final float centerX1 = 400; final float centerY1 = 50; final Sprite[] face1 = new Sprite[i]; face1[i] = new Sprite(centerX1, centerY1, this.m2FaceTextureRegion, this.getVertexBufferObjectManager()); final float centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final float centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion, this.getVertexBufferObjectManager()) { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { if(!face1[i].collidesWith(this)) { x+=1; this.setPosition(x, 50 ); } else { x=60; this.setPosition(x, 50 ); } return true; } }; scene.attachChild(face); scene.registerTouchArea(face); scene.setTouchAreaBindingOnActionDownEnabled(true); face.setScale(4); scene.attachChild(face1[i]); face1[i].setScale(2); return scene; } The Error: 11-11 12:12:42.690: E/AndEngine(13291): java.lang.ArrayIndexOutOfBoundsException Thanks. A: from the logs it looks like exception is getting raised at com.example.sheeprun1.BaseActivity.onCreateScene(BaseActivity.java:89). Can you check the code at this line and what array operation is getting performed there... EDIT1: when you are creating the array final Sprite[] face1 = new Sprite[i]; at this time the value of i should not be zero. When you are accessing the values from the array always check that the index is less then the size/length of the array if(face!=null && i<face.length){ face1[i] = new Sprite(centerX1, centerY1, this.m2FaceTextureRegion, this.getVertexBufferObjectManager()); }
[ "stackoverflow", "0055049615.txt" ]
Q: How can I let Apache JMeter use (password protected) keys from a (password protected) jks keystore Context I have a keystore (keystore.jks) that is protected by a password. I can get jmeter to use keys from that store by providing -Djavax.net.ssl.keyStore -Djavax.net.ssl.keyStorePassword with the appropriate values as long as the keys themselves are not password protected. However, my particular keystore contains multiple keys that each require a password to retrieve them. How I access the key in plain old Java: String keyStorePath = "/keystore.jks"; char[] keyStorePassword = "keyStorePassword".toCharArray(); String keyAlias = "keyAlias"; char[] keyPassword= "keyPassword".toCharArray(); KeyStore keyStore = KeyStore.getInstance("JKS"); try (InputStream is = this.getClass().getResourceAsStream(keyStorePath )) { keyStore.load(is, keyStorePassword); } PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, keyPassword); X509Certificate certificate = (X509Certificate) keyStore.getCertificate(keyAlias); How would I retrieve and use such keys in JMeter? That is the question. JMeter's Keystore Configuration does not allow you to specify a key's password. A: After looking around I concluded that this is currently (JMeter 5.0) not possible. Get jmeter to use certificates from a key store by providing these properties at startup: -Djavax.net.ssl.keyStore -Djavax.net.ssl.keyStorePassword The certificates inside the store should have the same password as the store, then they are picked up without problems when you use a Keystore Configuration specifying (a variable that holds) the certificate alias.
[ "stackoverflow", "0015274163.txt" ]
Q: ACTION_SEND Intent with custom extras causing other apps to crash I'm implementing an option for sharing content from my app. When the user presses the share button the following code is executed. public static void openShareIntent(Context context, String text, Wish wish) { Intent share = new Intent(Intent.ACTION_SEND); share.setType("text/plain"); share.putExtra(Intent.EXTRA_TEXT, text); share.putExtra("share_wish", wish); startIntent(context, share); } I'm setting one special extra for my Intent, that is object wish witch implements the Parcelable interface. This object contains some extra information. I want to use this information if the user selects my app (current app actually sharing content) from the available apps for sharing text/plain. But the problem is that all other popular apps (Facebook, Twitter, ...) and built-in apps (Messaging) crash when I include my Parcable object. It's not my applications that crashes, other apps are throwing quit unexpectedly error. When I call my SharingActivity with some extra name that is not known to this Activity, it does not crash. It just ignore that extra. Wish object source code Am I doing something wrong or what? Is this not possible because other apps don't know my Wish object? A: But the problem is that all other popular apps (Facebook, Twitter, ...) and built-in apps (Messaging) crash when I include my Parcable object. Never pass a custom Parcelable object to an app that lacks your Parcelable class definition. Is this not possible because other apps don't know my Wish object? Correct. Instead, pass an identifier (string, int, whatever) that SharingActivity can use to find your Wish from your central data model. Or, instead of creating a custom Wish, use a Bundle to represent the "wish", as Bundle has a common class definition across all apps.
[ "stackoverflow", "0054042973.txt" ]
Q: dynamically apply timezone offset to a highchart I have a chart which ultimately I'd like to apply timezone offsets to from a dropdown list of timezones. The incoming times from json will all be UTC. Is there a way to let highcharts handle the offset with the global timezoneOffset property, something along the lines of this when a button is clicked or dropdown selected: Highcharts.setOptions({ global : { timezoneOffset : 300 } }); Maybe I also need to redraw the chart after doing this? Example here: https://plnkr.co/edit/oqOAmUnH2LZzAX3a7vpV A: The global.timezoneOffset option is deprecated so I suggest using time.timezoneOffset instead for a chart. With the chart-sentric option you can do a normal chart update to set a new timezoneOffset. For example (JSFiddle demo): let chart = Highcharts.chart('container', { time: { timezoneOffset: -120 } // ... }); And upon doing a dropdown selection: chart.update({ time: { timezoneOffset: 0 } });
[ "stackoverflow", "0032974953.txt" ]
Q: Delete from database I want to delete a specific attribute from each and every table in the database. For an example: I want to delete CustomerID (column name) with a value of '2' from each and every table in the database I am trying to delete records where there is a customer field and it has a value of 2 but I get an error that says there is incorrect syntax near keyword delete declare @SearchTerm nvarchar(4000) declare @ColumnName sysname set @SearchTerm = N'2' -- Term to be searched for set @ColumnName = N'customerID' --**column** set nocount on declare @TabCols table ( id int not null primary key identity , table_schema sysname not null , table_name sysname not null , column_name sysname not null , data_type sysname not null ) insert into @TabCols (table_schema, table_name, column_name, data_type) select t.TABLE_SCHEMA, c.TABLE_NAME, c.COLUMN_NAME, c.DATA_TYPE from INFORMATION_SCHEMA.TABLES t join INFORMATION_SCHEMA.COLUMNS c on t.TABLE_SCHEMA = c.TABLE_SCHEMA and t.TABLE_NAME = c.TABLE_NAME where 1 = 1 and t.TABLE_TYPE = 'base table' and c.DATA_TYPE not in ('image', 'sql_variant') and c.COLUMN_NAME like case when len(@ColumnName) > 0 then @ColumnName else '%' end order by c.TABLE_NAME, c.ORDINAL_POSITION declare @table_schema sysname , @table_name sysname , @column_name sysname , @data_type sysname , @exists nvarchar(4000) -- Can be max for SQL2005+ , @sql nvarchar(4000) -- Can be max for SQL2005+ , @where nvarchar(4000) -- Can be max for SQL2005+ , @run nvarchar(4000) -- Can be max for SQL2005+ while exists (select null from @TabCols) begin select top 1 @table_schema = table_schema , @table_name = table_name -- , @exists = 'select null from [' + table_schema + '].[' + table_name + '] where 1 = 0' , @sql = 'delete''' + '[' + table_schema + '].[' + table_name + ']' + ''' as TABLE_NAME, from [' + table_schema + '].[' + table_name + '] where 1 = 0' , @where = '' from @TabCols order by id while exists (select null from @TabCols where table_schema = @table_schema and table_name = @table_name) begin select top 1 @column_name = column_name , @data_type = data_type from @TabCols where table_schema = @table_schema and table_name = @table_name order by id -- Special case for money if @data_type in ('money', 'smallmoney') begin if isnumeric(@SearchTerm) = 1 begin set @where = @where + ' or [' + @column_name + '] = cast(''' + @SearchTerm + ''' as ' + @data_type + ')' -- could also cast the column as varchar for wildcards end end -- Special case for xml else if @data_type = 'xml' begin set @where = @where + ' or cast([' + @column_name + '] as nvarchar(max)) like ''' + @SearchTerm + '''' end -- Special case for date else if @data_type in ('date', 'datetime', 'datetime2', 'datetimeoffset', 'smalldatetime', 'time') begin set @where = @where + ' or convert(nvarchar(50), [' + @column_name + '], 121) like ''' + @SearchTerm + '''' end -- Search all other types else begin set @where = @where + ' or [' + @column_name + '] like ''' + @SearchTerm + '''' end delete from @TabCols where table_schema = @table_schema and table_name = @table_name and column_name = @column_name end set @run = 'if exists(' + @exists + @where + ') begin ' + @sql + @where + ' print ''' + @table_name + ''' end' print @run exec sp_executesql @run end set nocount off A: Here is another method based on the example posted by ewahner. The big difference is this doesn't use a cursor because you really don't need one for this. declare @columnName nvarchar(255) declare @intValue int set @columnName = 'CustomerId' set @intValue = 1 declare @DeleteValue varchar(10) set @DeleteValue = convert(varchar(10), @intValue) declare @sql nvarchar(max) = '' select @sql = @sql + 'delete ' + object_name(c.object_id) + ' where ' + @columnName + ' = ' + @DeleteValue + ';' from sys.columns c where c.name = @columnName select @sql /* Uncomment the line below in order to run */ --exec sp_executesql @sql
[ "gardening.stackexchange", "0000031173.txt" ]
Q: Is this a type of jelly bean plant or something else? The difference between this and the well known "jelly bean plant" (Sedum rubrotinctum) is that this is edgy/pointy. I was searching for it everywhere on Google, but no trace found. Can someone tell me this plant's name? A: I found it in a botanical garden and it is Sedum rupestre/Sedum reflexum. There are two varieties of this species and you can tell them apart when they bloom. One has upright flower stems, the other one has somewhat curved flower stems.
[ "tex.stackexchange", "0000316896.txt" ]
Q: Plot that shows that largest root tends to 1 I am considering x^{i+2}-x^{i+1}-1. As i goes to infinity, the largest root tends to 1. I would like to have a plot in latex, for example with pgfplots, that shows this, maybe one could plot the graphs for i=1, i=10, i=100 or something like that in order to see that. Unfortunately I do not know how to plot this is in a good way such that one can see the largest roots and that it tends to 1. A: You can do the math first: your equation is equivalent to x^2 - x = 1/x^i. So, on the same axis, draw the graph of y = x^2 -x and y = 1/x^i for some values of i, for example, i = 1,10,50,200. The x-coordinates of the intersections are the largest roots of the orginal equation (You should be able to prove this). \documentclass{beamer} \usepackage{pgfplots} \usepackage[tightpage,active]{preview} \PreviewEnvironment{tikzpicture} \begin{document} \begin{tikzpicture} \begin{axis} [xmin=.9,xmax=2, ymax=1, ymin=-.1, ] \addplot[thick,black,samples=100,domain=.99:2] {x^2 - x} node[above,sloped,pos=.25] {$x^2 - x$} ; \addplot[thick,red,samples=100,domain=1:2] {1/x} node[above,sloped,pos=.2] {$i=1$} ; \addplot[thick,green,samples=100,domain=.99:2] {1/x^10} node[above,sloped,pos=.3] {$i=10$} ; \addplot[thick,cyan,samples=200,domain=.99:2] {1/x^50} node[above,sloped,pos=.52] {$i=50$} ; \addplot[thick,blue,samples=300,domain=.99:2] {1/x^200} ; \node[blue,rotate=270] at (axis cs:.96,.2) {$i=200$}; \end{axis} \end{tikzpicture} \end{document}
[ "stackoverflow", "0015033416.txt" ]
Q: How to create file at specified directory with touch command In Linux the touch-command creates files. But it always creates it in the current directory. How can I create files in a specified directory? For example touch file ../my_directory A: Try touch ../my_directory/file it won't create ../my_directory though, but I think this is not what you asked for.
[ "math.stackexchange", "0000507017.txt" ]
Q: Showing that an unbounded set has an unbounded sequence Suppose I have an unbounded set $S$ of Real numbers. I want to show that I can find a sequence $\{a_n\}$ in $S$ such that $ \lim_{n \rightarrow \infty}a_n=\infty$. Here is what I have so far: Since $S$ is unbounded, either $S$ is unbounded above or $S$ is unbounded below. Case 1: $S$ is not bounded above If there is no sequence $\{a_n\}$ in $S$ such that $ \lim_{n \rightarrow \infty}a_n=\infty$ then there must be a number $M$ such that $\forall n$ in any sequence $\{a_n\}$ in $S$, $a_n\leq M$. This implies that $S$ is bounded by $M$, a contradiction. Case 2: $S$ is not bounded below The same argument as Case 1. It seems obvious to me that I can always find such sequence but then I am not satisfied with my explanation. Any ideas? Thank you! By the way, I'm trying to prove that a subset of the Real numbers is compact if and only if every sequence in subset has a sub-sequence converging to point in the subset. I'm in the last part of my proof. I want to show that S is bounded and I am going to use the answer to this question to finish the proof. Thanks! A: If you know that there is no sequence $\{a_n\}$ such that $\lim_{n\to\infty} a_n = +\infty$, how do you conclude that there is a number $M$ such that all sequences are bounded by the same number $M$? Doesn't that assume what you are trying to prove? That said, what you are trying to prove is as follows : Suppose $S$ is not bounded above, then for any natural number $n \in \mathbb{N}$, $$ S\cap[n, \infty) \neq \emptyset $$ Hence, we may choose any number $a_n \in S\cap[n,\infty)$, and consider the sequence $\{a_n\}$. Can you show that this sequence must be going to $\infty$?
[ "gaming.stackexchange", "0000145988.txt" ]
Q: Will I eventually finish licking the candy cane? In the ‘How the Saints Save Christmas’ DLC mission, “The Fight Before Christmas”, an objective gives me the option to 'Go to Stables' or 'Lick Door'. I tried licking the candy cane which bars the door, but it seems that this will take forever (although the progress bar appears to move when I mash the E key). I opted to just go to the stables. I would like to know if it is possible to finish licking the candy cane. If yes, what will happen afterwards? Also, how long will it take? (I'll take an approximation.) A: It is indeed possible, and you will also get the 'Minty Fresh!' achievement. The text that appears while you are licking it is pretty funny also. You don't get any actual items as far as I know though. After you finish licking (and it does take a long time) you find that the door is locked.
[ "stackoverflow", "0045663692.txt" ]
Q: Equivalent of C programming syntax "#define" in Julia language In the C Programming Language, the #define directive allows the definition of macros within the source code. These macro definitions allow constant values to be declared for use throughout the code. Macro definitions are not variables and cannot be changed by the program code like variables. We generally use this syntax when creating constants that represent numbers, strings or expressions. like this #include <stdio.h> #define NAME "Jack" #define AGE 10 int main() { printf("%s is over %d years old.\n", NAME, AGE); return 0; } The beauty is that if I have multiple functions in my code I don't need to input the constant variable into every function, and the compiler simply replaces the defined expression with proceeding value. Now my question is: Is there any equivalent command in Julia programming for this? for example density = 1 # somehow a defined variabe. function bar(g) t = density +g end function foo() r = dencity + 2 end main() g = 10; foo() bar(g) end A: You can emulate the C #define behavior with a macro in Julia. macro NAME() return :("Jack") end macro AGE() return :(10) end In the Julia REPL, typing @NAME will return "Jack". julia> @NAME "Jack" julia> @AGE 10 Remember to enclose the macro call in parentheses for safety, e.g., julia> println("Hello ", (@NAME)) Hello Jack julia> println(@NAME * " is " * repr(@AGE) * " years old") ERROR: syntax: "*" is not a unary operator julia> println((@NAME) * " is " * repr(@AGE) * " years old") Jack is 10 years old But is this really necessary? The idiomatic way in Julia is to define global const variables. Although the documentation discourages the use of global variable for performance reasons, a macro like this does not help you on performance, and you can tell it from the LLVM code. macro NAME() return :("Jack") end const name = "Jack" function f_hello_global() println("Hello ", name) end function f_hello_macro() println("Hello ", (@NAME)) end For trivial functions like these, you'll find that the LLVM codes look exactly the same (too long; not shown here). julia> @code_llvm f_hello_global() . . . julia> @code_llvm f_hello_macro() . . . Edit: By the way, I would argue that if you have a need to use the global variable, then use it. The argument made in the Julia documentation (current stable version: 0.6.2) is that it may slow down the performance sometimes. However, imagine if a constant is used in 100 functions spread in 20 modules, would you prefer to write the same line of code 100 times and painstakingly check if the numbers are consistent across modules, or would you define it once and use it in all places? I'd think that the proper use of global constants makes the code clean and easy to maintain, and this concern often prevails over a small gain in performance.
[ "stackoverflow", "0027925929.txt" ]
Q: Is there a consistent way to deal with libraries being extrenalized in Scala 2.11? I have painfully come across the facts that scala.util.parsing and scala.swing are apparently no more bundled in Scala 2.11. Each time, I had to google for the right line to add to an sbt configuration, or to find the right link for where to download the jar file. In case there are other libraries that moved out, how am I supposed to know these things? Or am I supposed to rely only on questions from people having the same problem on Stackoverflow? The Scala Swing project on github does not even document these info. I like creating Eclipse projects on the fly, and making them depend on other projects in the same workspace, without going through sbt, and it is annoying to run into these library disappearance cases on every computer/workspace where I do this. A: The modularization (what you call externalizing) has been discussed for a good while on the scala-users mailing list. But the canonical place where to find this information is in the release notes. While you may not want to read all of those, I would strongly advise reading at least the release notes for a major version of any language you use. Case in point, the release notes for Scala 2.11.0: Modularization The core Scala standard library jar has shed 20% of its bytecode. The modules for xml, parsing, swing as well as the (unsupported) continuations plugin and library are available individually or via scala-library-all. Note that this artifact has weaker binary compatibility guarantees than scala-library – as explained above. The compiler has been modularized internally, to separate the presentation compiler, scaladoc and the REPL. We hope this will make it easier to contribute. In this release, all of these modules are still packaged in scala-compiler.jar. We plan to ship them in separate JARs in 2.12.x.
[ "stackoverflow", "0034315318.txt" ]
Q: Hiding API URLs and Prevent Brute Force Attacks I've just built an API in node. I'm calling this API in my angular app to do basics like login and register, for example: self.register = function(username, password) { return $http.post(API + '/auth/register', { username: username, password: password }) } So my question is, anyone could see that API URL, so whats stopping them from 'bashing' it to create users at there will. (Note API is a constant in my JS file). The same goes for the login, whats to stop someone from brute force trying millions of username and password combinations. And what would you recommend in securing this? Thanks. A: You can use some DDoS protection, for example put nginx proxy in front of your nodejs API and use e.g. limit_req module: http://nginx.org/en/docs/http/ngx_http_limit_req_module.html For brute force you can implement some lock-out logic, that after number of errors will block account for some time, e.g. 15-30 minutes or even will require an admin action. For APIs that require to be logged in you can use token protection. The token should be issued when authentication API is called and set via HTTP only secure cookie in response. Then you can pass this token in API request headers and before each protected API execution in nodejs just check if it's valid and reject the call if it's not.
[ "stackoverflow", "0015869190.txt" ]
Q: Excel VBA - how to handle many cell references without creating a mess Suppose you have an Excel workbook and you need to write a macro that takes inputs from many different cell references, and updates values at many different cell references, how do you keep the code neat and maintainable? It would be helpful to know: best practices useful tricks unavoidable difficulties necessary trade offs If there are links to existing guides or discussions that would be helpful too. I haven't been able to find any. Edit: I found http://www.eusprig.org/best-practice.htm very useful - from the European Spreadsheet Risk Interest Group (EuSPRIG). A: It slightly depends om what the macro is going to do, but I use 'calculation' sheets, where I gather together the data I need for the macro, and output the results there. I tend to do this do in defined ranges. The result data can then be referenced from elsewhere. Tricks: One thing I do is to create a visual 'check off' for each piece of input data as it's used. This just enables me to make sure that all the data I thought I was going to use, I have used.
[ "stackoverflow", "0041916263.txt" ]
Q: Developing a static website I am trying to develop a static website . So far as what I have understood and setup is a folder which contains the css,images folder and a index.html. Since I am trying to host it on amazon s3 I have also made the index.html as the landing page. So I have a projects tab which clicked on would go to a new page where I could display my projects . So my question is should I be having a projects.html under which I have my projects introduction . When clicked on read more for each project should I be redirecting it to a new html. root/ css/ images/ index.html resume.html projects/ projects_landing_page.html project1.html project2.html project3.html Is this the right folder structure to maintain a static website. Thank You. A: "Should I be having a projects.html under which I have my projects introduction . When clicked on read more for each project should I be redirecting it to a new html." In my opinion, each project should occupy its own page, as I'm assuming each page could get quite complex. On top of this, you don't want data about a particular project on the same page as data about an unrelated project. If they have synonymous data (such as a navbar), it would be best to inject that with a server-side language such as PHP. "Is this the right folder structure to maintain a static website." "Right folder structure" is highly subjective. Technically, there is no wrong structure, as you can access any file from any other file, regardless of how complex the action to do so becomes. Having said that, you generally want to keep all 'associated' files together in a folder that describes what the files are. You have an excellent structure yourself -- pages are very clearly separated. However, I would typically move the projects_landing_page.html file to the root level myself: root/ css/ style.css images/ image1.jpg image2.png index.html resume.html projects_landing_page.html projects/ project1.html project2.html project3.html In your projects_landing_page.html, I would then refer to each link with the following syntax: <a href="projects/project1.html"> <a href="projects/project2.html"> This really comes down to personal preference though, as either approach is perfectly valid. Hope this helps! :)
[ "stackoverflow", "0000141780.txt" ]
Q: KornShell (ksh) wraparound Okay, I am sure this is simple but it is driving me nuts. I recently went to work on a program where I have had to step back in time a bit and use Redhat 9. When I'm typing on the command line from a standard xterm running KornShell (ksh), and I reach the end of the line the screen slides to the right (cutting off the left side of my command) instead of wrapping the text around to a new line. This makes things difficult for me because I can't easily copy and paste from the previous command straight from the command line. I have to look at the history and paste the command from there. In case you are wondering, I do a lot of command-line awk scripts that cause the line to get quite long. Is there a way to force the command line to wrap instead of shifting visibility to the right side of the command I am typing? I have poured through man page options with no luck. I'm running: XFree86 4.2.99.903(174) KSH 5.2.14. Thanks. A: Did you do man ksh? You want to do a set -o multiline. Excerpt from man ksh: multiline: The built-in editors will use multiple lines on the screen for lines that are longer than the width of the screen. This may not work for all terminals. A: eval $(resize) should do it.
[ "stackoverflow", "0003005095.txt" ]
Q: Can I get name of all tables of SQL Server database in C# application? I want to get name of all table of SQL Server database in my C# application. Is It possible? Plz tell me Solution. A: It is as simple as this: DataTable t = _conn.GetSchema("Tables"); where _conn is a SqlConnection object that has already been connected to the correct database. A: Just another solution: public IList<string> ListTables() { List<string> tables = new List<string>(); DataTable dt = _connection.GetSchema("Tables"); foreach (DataRow row in dt.Rows) { string tablename = (string)row[2]; tables.Add(tablename); } return tables; } A: Run a sql command for: SELECT name FROM sysobjects WHERE xtype = 'U'
[ "stackoverflow", "0061430946.txt" ]
Q: Recycler View not showing jason data in kotlin here is my main class where i'm adding json data in ArrayList using volley. Toast show the json data but array does not show any data. i'm trying to solve my error from last 3 days i also read many questions on stack but i have no solution for this please help me var item = ArrayList<dumy_item_list>() var url = "https://apps.faizeqamar.website/charity/api/organizations" var rq: RequestQueue = Volley.newRequestQueue(this) var sr = StringRequest(Request.Method.GET, url, Response.Listener { response -> var jsonResponse = JSONObject(response) var jsonArray: JSONArray = jsonResponse.getJSONArray("data") for (i in 0..jsonArray.length() - 1) { var jsonObject: JSONObject = jsonArray.getJSONObject(i) var name = jsonObject.getString("name") val data = dumy_item_list() data.setName(jsonObject.getString(name)) item.add(data) Toast.makeText(applicationContext, "NGO Name is : $name", Toast.LENGTH_LONG).show() } }, Response.ErrorListener { error -> Toast.makeText(applicationContext, error.message, Toast.LENGTH_LONG).show() }) rq.add(sr) var away_recycler = findViewById<RecyclerView>(R.id.away_recycler) var adaptor = custom_adopter(item, applicationContext) away_recycler.layoutManager = GridLayoutManager(applicationContext, 1) away_recycler.adapter = adaptor } here is my adapter class wher i'm using getName() function class custom_adopter(data: ArrayList<dumy_item_list>, var context: Context) : RecyclerView.Adapter<custom_adopter.viewHolder>() { var data: List<dumy_item_list> init { this.data = data } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): custom_adopter.viewHolder { var layout = LayoutInflater.from(context).inflate(R.layout.dumy_item, parent, false) return viewHolder(layout) } override fun onBindViewHolder(holder: custom_adopter.viewHolder, position: Int) { holder.tv_dummy_name_donnor.text = data[position].getName() holder.card.setOnClickListener { var intent = Intent(context, ngosProfile::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK startActivity(context, intent, null) } } override fun getItemCount(): Int { return data.size } class viewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { internal var tv_dummy_name_donnor: TextView internal var card: CardView init { tv_dummy_name_donnor = itemView.findViewById(R.id.tv_dummy_name_donnor) card = itemView.findViewById(R.id.card) } } } A: follow this code this work for me. (var adaptor = custom_adopter(item, applicationContext) away_recycler.adapter = adaptor progressBar2?.visibility = View.INVISIBLE ) singe the value to adaptor after the loop. class MainActivity : AppCompatActivity() { var progressBar2:ProgressBar?=null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) var item = ArrayList<dumy_item_list>() var progressBar2 = findViewById<ProgressBar>(R.id.progressBar2) var away_recycler = findViewById<RecyclerView>(R.id.away_recycler) away_recycler.layoutManager = GridLayoutManager(applicationContext, 1) var url = "https://apps.faizeqamar.website/charity/api/organizations" var rq: RequestQueue = Volley.newRequestQueue(this) var sr = StringRequest(Request.Method.GET, url, Response.Listener { response -> var jsonResponse = JSONObject(response) var jsonArray: JSONArray = jsonResponse.getJSONArray("data") for (i in 0..jsonArray.length() - 1) { var jsonObject: JSONObject = jsonArray.getJSONObject(i) var name = jsonObject.getString("ngo_name") var about = jsonObject.getString("ngo_desc") item.add(dumy_item_list(name,about)) } var adaptor = custom_adopter(item, applicationContext) away_recycler.adapter = adaptor progressBar2?.visibility = View.INVISIBLE }, Response.ErrorListener { error -> }) rq.add(sr) }
[ "stackoverflow", "0023140033.txt" ]
Q: How to get value of string? { * * AControl: Control handle determined by Spy++ (e.g. 0037064A) * ANewText: Text to assign to control * AWinTitle: Window Title/Caption * } function ControlSetText(const AControl, ANewText, AWinTitle: string): boolean; function EnumChildren(AWindowHandle: HWND; ALParam: lParam): bool; stdcall; begin ShowMessage(AControl); // if commented out - code works fine TStrings(ALParam).Add(IntToStr(GetDlgCtrlID(AWindowHandle))); Result := true; end; var _MainWindowHandle: HWND; _WindowControlList: TStringlist; i: integer; _ControlHandle: integer; begin Result := false; _MainWindowHandle := FindWindow(nil, PWideChar(AWinTitle)); if _MainWindowHandle <> 0 then begin _WindowControlList := TStringlist.Create; try if TryStrToInt('$' + Trim(AControl), _ControlHandle) then try EnumChildWindows(_MainWindowHandle, @EnumChildren, UINT_PTR(_WindowControlList)); for i := 0 to _WindowControlList.Count - 1 do begin if (StrToInt(_WindowControlList[i]) = _ControlHandle) then begin SendMessage(StrToInt(_WindowControlList[i]), WM_SETTEXT, 0, integer(PCHAR(ANewText))); Result := true; end; end; except on E: Exception do MessageDlg(E.Message, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0) end; finally FreeAndNil(_WindowControlList); end; end; end; The debugger raises an exception with the message --------------------------- Debugger Exception Notification --------------------------- Project Default_project.exe raised exception class $C0000005 with message 'access violation at 0x00406fae: write of address 0x00408dbb'. It breaks at: for i := 0 to _WindowControlList.Count - 1 do I call it like this: ControlSetText('00070828', 'New TEdit text', 'Delphi_test_app'); I am planning an update, so, not only control handle could be passed, but also control type+identifier e.g. 'Edit1'. EDIT: What I am trying is to do is to implement http://www.autohotkey.com/docs/commands/ControlSetText.htm A: The problem is that your callback is a local nested function. That is it is nested inside ControlSetText. It must be declared at global scope. Any extra state information must be passed in through the lParam parameter. I also find it odd that you store integers and pointers in strings. Store them as integers or pointers. In fact it is more than odd. You put control ids in the list, as strings, but then use them as window handles. So once you get past the crash the code won't work. I don't want to get into debugging that in this question. A: The root cause of your crash is that your are using an inner function as the EnumChildWindows() callback and it is referencing a parameter from its outer function, which will not work (and why it does work when you comment out the access of that parameter). The call stack frame is not what EnumChildWindows() is expecting. You need to make the inner function be a standalone function instead. With that said, there is another bug in your code. Even if the above worked, your code would still fail because you are storing child Control IDs in your TStringList but then using them as if they were HWND values instead. They are not! Try something more like this: uses ..., System.Generics.Collections; { * * AControl: Control handle determined by Spy++ (e.g. 0037064A) * ANewText: Text to assign to control * AWinTitle: Window Title/Caption * } type THWndList = TList<HWND>; function EnumChildren(AWindowHandle: HWND; AParam: LPARAM): BOOL; stdcall; begin THWndList(AParam).Add(AWindowHandle); Result := TRUE; end; function TryStrToHWnd(const AStr: String; var Wnd: HWND): Boolean; begin {$IFDEF WIN64} Result := TryStrToInt64(AStr, Int64(Wnd)); {$ELSE} Result := TryStrToInt(AStr, Integer(Wnd)); {$ENDIF} end; function ControlSetText(const AControl, ANewText, AWinTitle: String): Boolean; var _MainWindowHandle: HWND; _WindowControlList: THWndList; i: integer; _ControlHandle: HWND; EnumInfo: TEnumInfo; begin Result := False; _MainWindowHandle := FindWindow(nil, PChar(AWinTitle)); if _MainWindowHandle <> 0 then begin _WindowControlList := THWndList; try if TryStrToHWnd('$' + Trim(AControl), _ControlHandle) then try EnumChildWindows(_MainWindowHandle, @EnumChildren, LPARAM(_WindowControlList)); for i := 0 to _WindowControlList.Count - 1 do begin if (_WindowControlList[i] = _ControlHandle) then begin Result := SendMessage(_WindowControlList[i], WM_SETTEXT, 0, LPARAM(PChar(ANewText))) = 1; Break; end; end; except on E: Exception do MessageDlg(E.Message, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0); end; finally FreeAndNil(_WindowControlList); end; end; end; Alternatively: { * * AControl: Control handle determined by Spy++ (e.g. 0037064A) * ANewText: Text to assign to control * AWinTitle: Window Title/Caption * } type PEnumInfo = ^TEnumInfo; TEnumInfo = record Control: HWND; Found: Boolean; end; function EnumChildren(AWindowHandle: HWND; AParam: LPARAM): BOOL; stdcall; begin PEnumInfo(AParam).Found := (AWindowHandle = PEnumInfo(AParam).Control); Result := not PEnumInfo(AParam).Found; end; function TryStrToHWnd(const AStr: String; var Wnd: HWND): Boolean; begin {$IFDEF WIN64} Result := TryStrToInt64(AStr, Int64(Wnd)); {$ELSE} Result := TryStrToInt(AStr, Integer(Wnd)); {$ENDIF} end; function ControlSetText(const AControl, ANewText, AWinTitle: String): Boolean; var _MainWindowHandle: HWND; _ControlHandle: HWND; EnumInfo: TEnumInfo; begin Result := False; _MainWindowHandle := FindWindow(nil, PChar(AWinTitle)); if _MainWindowHandle <> 0 then begin if TryStrToHWnd('$' + Trim(AControl), _ControlHandle) then try EnumInfo.Control := _ControlHandle; EnumInfo.Found := False; EnumChildWindows(_MainWindowHandle, @EnumChildren, LPARAM(@EnumInfo)); if EnumInfo.Found then begin Result := SendMessage(_ControlHandle, WM_SETTEXT, 0, LPARAM(PChar(ANewText))) = 1; end; except on E: Exception do MessageDlg(E.Message, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0); end; end; end; Or just get rid of EnumChilWindows() and let Windows validate the HWND you try to send to: { * * AControl: Control handle determined by Spy++ (e.g. 0037064A) * ANewText: Text to assign to control * } function TryStrToHWnd(const AStr: String; var Wnd: HWND): Boolean; begin {$IFDEF WIN64} Result := TryStrToInt64(AStr, Int64(Wnd)); {$ELSE} Result := TryStrToInt(AStr, Integer(Wnd)); {$ENDIF} end; function ControlSetText(const AControl, ANewText: String): Boolean; var _ControlHandle: HWND; begin Result := TryStrToHWnd('$' + Trim(AControl), _ControlHandle) and (SendMessage(_ControlHandle, WM_SETTEXT, 0, LPARAM(PChar(ANewText))) = 1); end;
[ "stackoverflow", "0010424247.txt" ]
Q: Android: How to download RSS when a website contains: link rel="alternate" type="application/rss+xml" I am making a RSS related app. I want to be able to download RSS(xml) given only website URL that contains: link rel="alternate" type="application/rss+xml" For example, http://www.engaget.com source contains: <link rel="alternate" type="application/rss+xml" title="Engadget" href="http://www.engadget.com/rss.xml"> I am assuming if I open this site as RSS application, it will re-direct me to http://www.engadget.com/rss.xml page. My code to download xml is following: private boolean downloadXml(String url, String filename) { try { URL urlxml = new URL(url); URLConnection ucon = urlxml.openConnection(); ucon.setConnectTimeout(4000); ucon.setReadTimeout(4000); InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is, 128); FileOutputStream fOut = openFileOutput(filename + ".xml", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE); OutputStreamWriter osw = new OutputStreamWriter(fOut); int current = 0; while ((current = bis.read()) != -1) { osw.write((byte) current); } osw.flush(); osw.close(); } catch (Exception e) { return false; } return true; } without me knowing 'http://www.engadget.com/rss.xml' url, how can I download RSS when I input 'http://www.engadget.com"? A: To accomplish this, you need to: Detect whether the URL points to an HTML file. See the isHtml method in the code below. If the URL points to an HTML file, extract an RSS URL from it. See the extractRssUrl method in the code below. The following code is a modified version of the code you pasted in your question. For I/O, I used Apache Commons IO for the useful IOUtils and FileUtils classes. IOUtils.toString is used to convert an input stream to a string, as recommended in the article "In Java, how do I read/convert an InputStream to a String?" extractRssUrl uses regular expressions to parse HTML, even though it is highly frowned upon. (See the rant in "RegEx match open tags except XHTML self-contained tags.") With this in mind, let extractRssUrl be a starting point. The regular expression in extractRssUrl is rudimentary and doesn't cover all cases. Note that a call to isRss(str) is commented out. If you want to do RSS detection, see "How to detect if a page is an RSS or ATOM feed." private boolean downloadXml(String url, String filename) { InputStream is = null; try { URL urlxml = new URL(url); URLConnection ucon = urlxml.openConnection(); ucon.setConnectTimeout(4000); ucon.setReadTimeout(4000); is = ucon.getInputStream(); String str = IOUtils.toString(is, "UTF-8"); if (isHtml(str)) { String rssURL = extractRssUrl(str); if (rssURL != null && !url.equals(rssURL)) { return downloadXml(rssURL, filename + ".xml"); } } else { // if (isRss(str)) { // For now, we'll assume that we're an RSS feed at this point FileUtils.write(new File(filename), str); return true; } } catch (Exception e) { // do nothing } finally { IOUtils.closeQuietly(is); } return false; } private boolean isHtml(String str) { Pattern pattern = Pattern.compile("<html", Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE); Matcher matcher = pattern.matcher(str); return matcher.find(); } private String extractRssUrl(String str) { Pattern pattern = Pattern.compile("<link(?:\\s+href=\"([^\"]*)\"|\\s+[a-z\\-]+=\"[^\"]*\")*\\s+type=\"application/rss\\+(?:xml|atom)\"(?:\\s+href=\"([^\"]*)\"|\\s+[a-z\\-]+=\"[^\"]*\")*?\\s*/?>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE); Matcher matcher = pattern.matcher(str); if (matcher.find()) { for (int i = 1; i <= matcher.groupCount(); i++) { if (matcher.group(i) != null) { return matcher.group(i); } } } return null; } The above code works with your Engadget example: obj.downloadXml("http://www.engadget.com/", "rss");
[ "superuser", "0000204868.txt" ]
Q: Windows 7 access control explained I'm getting a little confused with Windows 7 access control. I'm aware of why access control is in Windows 7, and I'm relatively familiar with Linux access control. Does Windows 7 access control work in a similar way (i.e. changing the ownership of particular file/directory)? Can anybody point me in the direction of a good guide to Windows 7 access control? A: Yes the UAC works by borrowing ownership from the Admin To help prevent malicious software from silently installing and causing computer-wide infection. UAC is similar to Linux Sudo. Hopefully this guide will help. http://technet.microsoft.com/en-us/library/cc709691%28WS.10%29.aspx
[ "stackoverflow", "0052367275.txt" ]
Q: Generic function using an abstract class I am trying to create a static function replacing the instance of an abstract class by an other one. (I simplified the code to focus on where it does not work) : abstract class AbstractData { public int MaxValue; public int[] GivenValues; } static class AnalyzeData { static void Analyze<T>(int limitValue, AbstractData abstractData) where T : AbstractData { T.GivenValues = abstractData.GivenValues; //error : T is a type parameter which is not valid in the given context T.MaxValue= abstractData.GivenValues[0]; // same error foreach (var data in abstractData.GivenValues) { if (data<limitValue){ T.MaxValue = data; } } abstractData = T; //same error } } I have tried to replace T by AbstractData in the definition of the function, or to cast T, but non of that worked. The only solution I have found is to use an other instance of Abstract Data as parameter (and having 'in' and 'out' instances) : static void Analyze<T>(int limitValue, AbstractData abstractDataIn, AbstractData abstractDataOut) But then I would lose the advantage of the generic part of the function. Do you know why I have this error, and how I can correct it? Thx ! A: T is a Type, not an instance of a type. If you want to create and return a new instance, you have to write that like this: static T Analyze<T>(int limitValue, AbstractData abstractData) where T : AbstractData, new() { T t = new T(); t.GivenValues = abstractData.GivenValues; t.MaxValue= abstractData.GivenValues[0]; foreach (var data in abstractData.GivenValues) { if (data<limitValue){ t.MaxValue = data; } } return t; } Where you have the return value of type T. Another option is to pass in an instance of T: static void Analyze<T>(int limitValue, AbstractData abstractData, T t) where T : AbstractData { t.GivenValues = abstractData.GivenValues; t.MaxValue= abstractData.GivenValues[0]; foreach (var data in abstractData.GivenValues) { if (data<limitValue){ t.MaxValue = data; } } } Then there is no need to return the newly created instance.
[ "stackoverflow", "0026263351.txt" ]
Q: Why does this code stop running when it hits the pipe? When this program runs it goes through the loop in the parent then switches to the child when it writes to the pipe. In the child the pipe that reads just causes the program to stop. Current example output: Parent 4741 14087 (only this line when 5 more lines are expected) Expected output(with randomly generated numbers): Parent 4741 14087 Child 4740 47082 Parent 4741 11345 Child 4740 99017 Parent 4741 96744 Child 4740 98653 (when given the variable 3 and the last number is a randomly generated number) #include <stdio.h> #include <iostream> #include <unistd.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include <time.h> #include <ctime> using namespace std; int main (int argc, char *argv[]) { int pid = fork(), temp, randNum, count, pipeName[2], pipeName2[2]; string conver; pipe(pipeName); conver = argv[1]; temp = atoi(conver.c_str()); char letter; if (pid == 0) { //child srand((unsigned)time(NULL) * getpid() ); //closing unused pipes close(pipeName2[1]); close(pipeName[0]); //loop to switch between processes for(int i=0; i<temp; i++) { count = read(pipeName2[0], &letter, 20); randNum = rand(); cout << "Child " << getpid() << " " << randNum << endl; write(pipeName[1], "x", 1); } close(pipeName2[0]); close(pipeName[1]); } else { //parent srand((unsigned)time(NULL) * getpid() ); pipe(pipeName2); //closing unused pipes close(pipeName2[0]); close(pipeName[1]); //loop to switch between processes for(int i=0; i<temp; i++) { if(i != 0) count = read(pipeName[0], &letter, 20); randNum = rand(); cout << "Parent " << getpid() << " " << randNum << endl; write(pipeName2[1], "x", 1); } close(pipeName[0]); close(pipeName2[1]); } } The program ends when it hits the read from pipe line in the child. A: Your principal mistake is fork()ing before you initialize the pipes. Both parent and child thus have their own private (not shared via fd inheritance) pipe pair named pipeName, and only the parent initializes pipeName2 with pipe fds. For the parent, there's simply no data to read behind pipeName[0]. For the child ... who knows what fd it is writing to in pipeName2[1]? If you're lucky that fails with EBADF. So, first pipe() twice, and then fork(), and see if that improves things.
[ "stackoverflow", "0005389362.txt" ]
Q: .htaccess: Unable to catch rule using RewriteCond Facebook returns the following result: http://www.mydomain.com/some-text-here-auth-login.html?session={%22session_key%22%3A%2295da8e65851d8ec74c381171-650901429%22%2C%22uid%22%3A%22650901429%22%2C%22expires%22%3A0%2C%22secret%22%3A%223chidden%22%2C%22base_domain%22%3A%22mydomain.com%22%2C%22access_token%22%3A%22171372936213670|95da8e65851d8ec74c381171-650901429|x_1y78ix4VU8Wr9qytDqV-DWBk0%22%2C%22sig%22%3A%22708bf3fd1703e4c368afe22fc70ed08c%22} On my .htaccess are the following lines: RewriteCond %{QUERY_STRING} session=\{(.*)\} RewriteRule ^some-text-here-(\w+)-(\w+).html /index.php?c=$1&m=$2&session=%1 [L] But it's not falling into the rule. Could you please help a dumber like me figure it out? Thanks! A: OK I've figured it out. The 1st line should be: RewriteCond %{QUERY_STRING} session=(.*)
[ "stackoverflow", "0030777179.txt" ]
Q: How to find servlet API version for glassfish server? While coding a servlet I found a method that says Since: Servlet 3.1 I guess that if I have the autohint from NetBeans to use it is because I have that Servlet version. But I cannot find a place to confirm that. I'm using glassfish4.1 as container. If I go to mypathtoglassfish4.1\glassfish\modules there I can see javax.servlet-api.jar and inside a manifest that says: Implementation-Version: 3.1.0 Is that the proper way to check that? I'm especially interested in being able to tell my colleagues "go to that jar and check that property" so I'm sure that my code will run on their server. As alternative, I found a webpage Oracle GlassFish Server 3.1 Application Development Guide that says: "GlassFish Server supports the Java Servlet Specification version 3.0." but obviously for Glassfish 3.1, and I couldn't find one of those for every glassfish version (not even for mine -4.1 ) A: Look at Java EE version. Servlet (and JSP, JSF, EJB, JPA, etc) version goes hand in hand with Java EE version. Java EE 8 = Servlet 4.0 Java EE 7 = Servlet 3.1 Java EE 6 = Servlet 3.0 Java EE 5 = Servlet 2.5 J2EE 1.4 = Servlet 2.4 J2EE 1.3 = Servlet 2.3 J2EE 1.2 = Servlet 2.2 Look at the server homepage/documentation how it presents itself. For GlassFish, that is currently (with 4.1): World's first Java EE 7 Application Server So, it's Servlet 3.1. But, with a big but, that's one thing. The second thing is, the webapp's web.xml version also plays a role. Not everyone knows that. If your webapp's web.xml is declared conform Servlet 3.1 like below, <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <!-- Config here. --> </web-app> then your webapp will also really run in Servlet 3.1 modus. However, if it's declared conform Servlet 3.0 like below or even older, <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <!-- Config here. --> </web-app> then your webapp will run in Servlet 3.0 compatibility modus, even when deployed to a Servlet 3.1 compatible container! The above influences the ServletContext#getMajorVersion() and getMinorVersion(), so they actually say nothing about the container, but only about the webapp itself. If your webapp's web.xml contains a <!DOCTYPE>, regardless of the DTD and the version, then it will run in Servlet 2.3 compatibility modus, even when there's a newer XSD declared! <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "java.sun.com/dtd/web-app_2_3.dtd"> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <!-- This is WRONG! The DOCTYPE must be removed! --> </web-app>
[ "mathematica.stackexchange", "0000193157.txt" ]
Q: Forcing divisions to be a machine-precision floating point divisions instead of multiplication by inverse I want to imitate machine-precision, de facto IEEE division on Mathematica. On my quick trials I find this surprisingly hard to accomplish, since Mma rewrites a / b as a (b^-1) and these are not identical on finite-precision math. For an explicit example, consider the following: 49. / 49. // FullForm 0.9999999999999999` EDIT: As @J.M. points out, this works: Divide[49., 49.] // FullForm 1.` ... but if I do the following, for instance, the finite-precision multiplication by inverse is seen again: Divide[x, 49.] // FullForm Times[0.02040816326530612`, x] ... which is bad. How would I implement a "use native (IEEE) division semantics on machine-precision arguments of this division, even later down the evaluation chain" operation instead of Mma being too clever for its' own sake? EDIT: In this specific case I'm not interested in other IEEE semantics, for instance strict order of operations (a + b + c is not the same as c + b + a!). I just want divisions to stay as divisions, which may be a bit of a half-way goal, but sounds more feasible to implement that the whole shebang. A: You can define your own divide function: divide[a_Real, b_Real] := Divide[a, b] MakeBoxes[divide[a_, b_], StandardForm] := MakeBoxes[Divide[a, b], StandardForm] Then: divide[49., 49.] 1. And: r = divide[x, 49.] r /. x->49. x/49. 1. Some more work is needed to define how divide works with other arithmetical operations.
[ "stackoverflow", "0029900040.txt" ]
Q: How to get several value in once enter ?(Number of uncertainty) How can I get several values input from the keyboard (an integer type and many number of uncertainty) ? I need to write a program which allow users to enter any number , Each number is delimited by the Space and when the user presses Enter, The number was placed in each of the variables Array. For example, input number: 1 2 8 9 (Enter) if input the fourth (numbers), it will build up four variables to get that value. number [0] = 1, number [1] = 2, number [2] = 8, number [3] = 9. input number: 3 4 7 (Enter) if input the third (numbers), it will have to build up three variables to get that value. number [0] = 3, number [1] = 4, number [2] = 7. I tried to use the scan f function,but it's not work , If have any good advice ,please tell me #include <stdio.h> #include <windows.h> int n, number[10]; main() { printf("Enter Number of integer : "); scanf("%d", &n); if (n == 1) { printf("Enter integer : "); scanf("%d", &number[0]); } else if (n == 2) { printf("Enter integer : "); scanf("%d %d", &number[0], &number[1]); } else if (n == 3) { printf("Enter integer : "); scanf("%d %d %d", &number[0], &number[1], &number[2]); } system("pause"); } A: Have you considered doing this using a combination of scanf(), fgets() and strtok()? For example, you can use scanf() to simple query the number of inputs expected. Then use a loop around `strtok() to tokenize user's input: int main() { char line[1024]; char *token = {0}; char delim[]={" \r\n\t"}; long telPos = 0; int count, i; int *array = {0}; printf("Enter Number of integers, <return> then line of integers : \n"); scanf("%d",&count); getchar();//eat the newline (from <return>) while (fgets(line, 1024, stdin) != NULL) { array = malloc(sizeof(int)*count); token = strtok(line, delim); i = -1; while(token) { if((count - 1) > i++) { array[i] = atoi(token); token = strtok(NULL, delim); } else { for(i=0;i<count;i++) printf("value %d: %d\n", i, array[i]); } } //do something here with array, then free it. free(array); } return 0; }
[ "stackoverflow", "0032297955.txt" ]
Q: JavaScript website vulnerability this morning I noticed a possible vulnerability on my web site; I'm not sure at all if my site can be damaged with it but well... On my site I use a JavaScript code to open(display) different sections (other pages) inside the main page; On the main index.php I've this code where the other pages are displayed: In the head: <?php $section = "default"; if (isset($_GET["page"])) { $section = $_GET["page"]; } ?> In the Body: <script type="text/javascript"> openPage('<?php echo($page); ?>'); </script> And the JavaScript function is this one: function openPage(page, form) { var data = "page=" + page; if (form != null) data += "&" + $("#" + form).serialize(); $("#content").html("<center>Wait..</center>"); $.ajax({ type: "POST", url: "content.php", data: data, success: function(result) { $("#content").html(result); } }) } The content.php <? if (file_exists("pages/".$page.".php")) include("pages/".$page.".php"); else { include("pages/default.php"); } ?> My problem is that if I write in the url: url.com/index.php?page=</script><script>alert(1)</script> An alert message appear, what I could do? Is this dangerous? How I can fix it? Thank you all. A: This is not JS vulnerability, this is your code vulnerability. You can use htmlspecialchars: <?php $section = "default"; if (isset($_GET["page"])) { $section = htmlspecialchars($_GET["page"]); } ?> http://www.w3schools.com/php/func_string_htmlspecialchars.asp
[ "stackoverflow", "0040471962.txt" ]
Q: Extract single value from JSON Dump response Python I'm having some difficulties with extracting a single value from a JSON dump. I'm trying to extract the single value of a stock from JSON output generated by using the GoogleFinance package, but I keep getting this error message: expected string or buffer. I've tried to find a solution on the forum but nothing seems to be working. One thing I've tried is loading the JSON in to a string by using json.loads, but I keep running in to the same wall. from googlefinance import getQuotes import json import sys Apple = json.dumps(getQuotes('AAP'), indent=2) #gets the quote from Apple stock. I know I should use the json.loads but that doesn't seem to be working for the getQuotes. #JSON output [ { "Index": "NYSE", "LastTradeWithCurrency": "137.24", "LastTradeDateTime": "2016-11-07T13:09:43Z", "LastTradePrice": "137.24", "LastTradeTime": "1:09PM EST", "LastTradeDateTimeLong": "Nov 7, 1:09PM EST", "StockSymbol": "AAP", "ID": "668575" } ] #Trying to solve the issue by loading the json to a string resp = json.loads(Apple) #print the resp print (resp) #extract an element in the response print (resp["LastTradeWithCurrency"]) A: change resp = json.loads(Apple) to resp = json.loads(Apple)[0]
[ "stackoverflow", "0040312306.txt" ]
Q: INSERT SELECT loop I am trying to transfer data from one table to another. But in the process I need to do something extra I am just wondering is it possible to do something like this in SQL or PL/SQL alone. source target ------------------- ------------------------ | id | name | qty | | id | source_id | qty | ------------------- ------------------------ | 1 | test | 2 | | 1 | 1 | 1 | ------------------- ------------------------ | 2 | ago | 1 | | 2 | 1 | 1 | ------------------- ------------------------ | 3 | 2 | 1 | ----------------------- Here based on the quantity in source table I will have to insert multiple records. Quantity could be of any number. ID in target table is auto incremented. I tried this INSERT INTO target (SELECT id, qty FROM source); But this does not take care of the qty loop. A: Plain SQL: with inputs ( id, qty ) as ( select 1, 2 from dual union all select 2, 1 from dual union all select 3, 5 from dual ) -- end of test data; solution (SQL query) begins below this line select row_number() over (order by id) as id, id as source_id, 1 as qty from inputs connect by level <= qty and prior id = id and prior sys_guid() is not null ; NOTE - if the id is generated automatically, just drop the row_number().... as id column; the rest is unchanged. ID SOURCE_ID QTY -- --------- -- 1 1 1 2 1 1 3 2 1 4 3 1 5 3 1 6 3 1 7 3 1 8 3 1
[ "stackoverflow", "0060724759.txt" ]
Q: Run docker commands from gitlab-ci I have this gitlab-ci file: services: - docker:18.09.7-dind variables: SONAR_TOKEN: "$PROJECT_SONAR_TOKEN" GIT_DEPTH: 0 MAVEN_CLI_OPTS: "-s .m2/settings.xml --batch-mode" MAVEN_OPTS: "-Dmaven.repo.local=.m2/repository" DOCKER_HOST: "tcp://docker:2375" DOCKER_DRIVER: overlay2 sonarqube-check: image: maven:latest stage: test before_script: - "docker version" - "mkdir $PWD/.m2" - "cp -f /cache/settings.xml $PWD/.m2/settings.xml" script: - mvn $MAVEN_CLI_OPTS clean verify sonar:sonar -Dsonar.qualitygate.wait=true -Dsonar.login=$SONAR_TOKEN -Dsonar.projectKey="project-key" after_script: - "rm -rf $PWD/.m2" allow_failure: false only: - merge_requests For some reason docker in docker service does not find the binaries for docker (the docker version command, line 16): /bin/bash: line 111: docker: command not found I'm wondering if there is a way of doing this inside of the gitlab-ci file because I need to run docker for the tests, if there is an image that contains both maven and docker binaries or if I'll have to create my own docker image. It has to be all in one stage, I cannot divide it in two stages (or at least I don't know how to compile in maven in one stage and run the tests witha docker image in another stage) Thank you! A: As you correctly pointed out. You need mvn and docker binaries in the image you are using for that GitLab-CI job. The quickest win is probably to install docker in your maven:latest build image during run time in the before_script section. before_script: - apt-get update && apt-get install -y docker.io - docker version If that's slowing down your job too much you might want to build your own custom docker image that contains both Maven and Docker. Also have a look at the article about dind on Gitlab if you end up moving to Docker 19.03+
[ "stackoverflow", "0008163714.txt" ]
Q: How would I write css to access the following class "total total_plus hidden_elem" or "total total_plus"? How would I write css to access the following class "total total_plus hidden_elem" or "total total_plus"? I have class="total total_plus" and class="total total_plus_elem" and I need to access them via css. What would be the proper way to access them? .total total_plus { display:none; } is not working for me. Here is the context of what I am trying to access: <div class="bigbox"> <div class="full_widget"> <div class="connections"> <span class="total total_plus"></span> <span class="total hidden_elem"></span> </div> </div> </div> Thanks A: To do this, all classes in CSS must be written directly after each another – with no white space. .total.total_plus and .total.hidden_elem
[ "stackoverflow", "0044489404.txt" ]
Q: Powershell Try Catch and retry? I have this script #Change hostname [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') Write-Host "Change hostname " -NoNewLine $ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox('Insert the desired computername:', 'Change hostname') Write-Host "- DONE" -ForegroundColor DarkGreen -BackgroundColor green -NoNewline Write-Host " hostname = $ComputerName " Rename-Computer -NewName $ComputerName when the computer name gets spaces, it fails cause a hostname cant have spaces. Can i block the form to have any spaces or does anyone knows how to get back to the inputbox when a error has been created for a re-try A: do { $ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox('Insert the desired computername:','Change hostname') } while ($ComputerName -match "\s") using a do{}while() loop and checking the Input doesn't have any whitespace should resolve your issue, this will re-prompt until a valid hostname is input, if you want to check for any errors at all: do{ $Failed = $false Try{ $ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox('Insert the desired computername:', 'Change hostname') Write-Host "- DONE" -ForegroundColor DarkGreen -BackgroundColor green -NoNewline Write-Host " hostname = $ComputerName " Rename-Computer -NewName $ComputerName -ErrorAction Stop } catch { $Failed = $true } } while ($Failed) A: Very satisfied with the end result, much thanks #Change hostname Write-Host "Change hostname " -NoNewLine do{ $Failed = $false Try{ $ComputerName = [Microsoft.VisualBasic.Interaction]::InputBox('Insert the desired computername:', 'Change hostname') Rename-Computer -NewName $ComputerName -ErrorAction Stop Write-Host "- DONE -" -ForegroundColor DarkGreen -BackgroundColor green -NoNewline Write-Host "Hostname = $ComputerName" -ForegroundColor DarkGreen -BackgroundColor yellow } catch { $Failed = $true } } while ($Failed) #Change workgroupname Write-Host "Change Workgroup " -NoNewLine do{ $Failed = $false Try{ $WorkGroup = [Microsoft.VisualBasic.Interaction]::InputBox("Insert the Workgroupname:", 'Change WorkGroupName', 'werkgroep') Add-Computer -WorkGroupName $WorkGroup -ErrorAction Stop Write-Host "- DONE -" -ForegroundColor DarkGreen -BackgroundColor green -NoNewline Write-Host "Workgroup = $WorkGroup" -ForegroundColor DarkGreen -BackgroundColor yellow } catch { $Failed = $true } } while ($Failed)
[ "stackoverflow", "0052700066.txt" ]
Q: Elastic Search with laravel for multiple fields I have integrated elastic search in laravel with help of below tutorial. https://appdividend.com/2018/06/30/laravel-elasticsearch-tutorial-example/ According to this tutorial search with single fields is working fine. i.e. // Article table has column 'title','body' and 'tags'. Route::get('/search', function() { $articles = Article::searchByQuery(['match' => ['title' => 'Test']]); return $articles; }); But i want to search with multiple column values like 'title' ,'body' etc. Anyone suggest an idea how to search with multiple column? A: You can use the multimatch query, above is some sample how this can be done. GET _search { "query": { "bool": { "must": { "multi_match" : { "query": "stuff you want to seach", "type": "cross_fields", "fields": [ "title^10", "body^9", "tags^8" ] } } } } }
[ "stackoverflow", "0025600614.txt" ]
Q: XamNumericEditor format and mask I'm using a XamNumericEditor control and I would like to display the value 0.000 as default. When I click on the spin button it should increment by 0.005 points. It should also support negative numbers. The maximum limit should be 100.000. Kindly let me know what would be the format and mask for this scenario. Also, kindly point me to a link where I can learn about using the right mask and format. Thanks. A: I guess I found out this. I don't require the format property. Mask is -nn.nnn and Value is set to 0.000 by default and spinincrement is set to .005 Thanks
[ "blender.stackexchange", "0000050414.txt" ]
Q: Where are clouds, stucci, wood textures in cycles materials? So I want to use the extra settings for the musgrave setting (where you can pick blender original or voronoi f2 etc.) in a material but it seems you can only use it in the texture panel. Is there any way of using these textures in materials? A: Cycles is a completely different rendering engine, with its own system, separate settings, materials and different workflow. Blender internal materials and textures are not available under Cycles and the opposite is also true. Cycles has it's own musgrave texture accessible through the node editor Add Menu > Textures > Musgrave. It has it's own set of settings and can be tweaked as just like Blender Internal. You can even use other textures com combine, mix or deform the current one.
[ "stackoverflow", "0020553669.txt" ]
Q: Batch Insert Objects With Relations in Laravel-4 I've come into a situation where I need to batch-save objects with their related objects in laravel 4. Essentially what I am doing is a bulk insertion of objects where each object can have many tags (many-to-many relation). Here is some sample code, notice the TODO comments: [...] $batchData = array(); $rowCount = 0; foreach ($dataArray as $key => $row) { [...] // parsing row from CSV $obj = array(); foreach ($row as $attribute => $value) { $obj['template_id'] = $templateId; $obj['batch_id'] = $batchId; $obj['user_id'] = $confideUserId; $obj['created_at'] = new \DateTime; $obj['updated_at'] = new \DateTime; // Attach Tags if any exist if ($attribute === 'tags') { if (!is_null($value) || !is_empty($value)) { $tags = explode(":", $value); // TODO: Get tag ID for each tag and add to $obj['tags'] array } } } // add object to array $batchData[$rowCount] = $obj; ++$rowCount; if ($rowCount == \Config::get('app.maxCSV')) { try { // TODO: Batch Insert With Related tags?? $obj_model_name::insert($batchData); } catch (Exception $e) { return false; } $rowCount = 0; $batchData = array(); } } [...] I could insert each object one-by-one with their relations, but the issue is that we bulk insert these objects via CSV, where we can have anywhere from hundreds to hundreds of thousands of objects. Anyone have any tips? FYI the database being used is MSSQL 2012. Cheers, A: After looking into this further, I came to the conclusion that it would be best to re-factor my logic. I now save each object individually before assigning the tags to that object and repeat for all objects. This might not be efficient when there are many objects, but as of now that is not a foreseeable issue.
[ "ru.stackoverflow", "0000943415.txt" ]
Q: Оставить только фамилии и подставить их в теги Есть фамилии и инициалы авторов: authors = ['Пупкин М.И.', 'Скутина О.Л.'] Пытаюсь оставить только фамилии обоих авторов: def get_ln(authors): for i in authors: a = i.split()[0] return '<SUBFIELD.A>' + str(a) + '</SUBFIELD.A>' get_ln = get_ln(authors) print(get_ln) Но получается только фамилия второго автора. Подскажите, пожалуйста, как подставить в теги обе фамилии? Желаемый результат: <SUBFIELD.A>Пупкин</SUBFIELD.A> <SUBFIELD.A>Скутина</SUBFIELD.A> A: Возвращается фамилия последнего автора, потому что в конце цикла в a хранится только она, т.к. каждую итерацию переменная а перезаписывается. Нужно в цикле сохранять фамилии в другой список, например. Возвращает список, элементами которого являются нужные строки: def get_ln(authors): names = [] # пустой список, куда будем складывать фамилии for i in authors: a = i.split()[0] # добавляем полученную фамилию в список вместе с тэгами names.append('<SUBFIELD.A>' + a + '</SUBFIELD.A>') return names Результат: ['<SUBFIELD.A>Пупкин</SUBFIELD.A>', '<SUBFIELD.A>Скутина</SUBFIELD.A>'] PS. Обратите внимание на эту строчку: get_ln = get_ln(authors) Ни в коем случае, НИКОГДА!, не делайте так. После этой строчки нельзя будет использовать функцию get_ln(), потому что get_ln теперь не функция, а список фамилий. Не нужно давать переменным и функциям одинаковые имена.
[ "stackoverflow", "0032007403.txt" ]
Q: JSP, show results from two tables in for each In JSP I have simple foreach, which should display the information from two tables. First table "Organizations" as "country" parameter keeps id of country as a foreign key to another table "Countries". How can I show country name in this foreach, which keeps in “Organizations" as id of country? <c:forEach items=“${organizations}" var=“organization"> <c:url var="edit" value="/edit/${organization.id}" /> <c:url var="remove" value="/remove/${organization.id}" /> <tr> <td><c:out value="${organization.name}" /></td> <td><c:out value="${organization.country}" /></td> // In this line <td><c:out value="${organization.address}" /></td> <td><c:out value="${organization.phone}" /></td> <td><c:out value="${organization.market_cap}" /></td> <td valign = "top"><a href="${edit}">Edit</a></td> <td valign = "top"><a href="${remove}">Remove</a></td> </tr> </c:forEach> Tables: CREATE TABLE IF NOT EXISTS Organization (id int auto_increment , name varchar(255), country int, address varchar(255), phone varchar(255)primary key(id), foreign key (country) references public.country(id_country)); CREATE TABLE IF NOT EXISTS Country (id_country int auto_increment , name varchar(255), primary key(id_country)); Model, Organization: import javax.persistence.*; @Entity public class Organization { @Id @GeneratedValue private Integer id; private String name; private Integer country; private String address; private String phone; private Long market_cap; public Organization(Integer id, String name, Integer country, String address, String phone, Long market_cap) { this.id = id; this.name = name; this.country = country; this.address = address; this.phone = phone; this.market_cap = market_cap; } public Organization() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getCountry() { return country; } public void setCountry(Integer country) { this.country = country; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Long getMarket_cap() { return market_cap; } public void setMarketCap(Long market_cap) { this.market_cap = market_cap; } } Model, Country: import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Country { @Id @GeneratedValue private Integer id_country; private String name; private String isocode; public Country() { } public Country(Integer id_country, String name, String isocode) { this.id_country = id_country; this.name = name; this.isocode = isocode; } public Integer getId_country() { return id_country; } public void setId_country(Integer id_country) { this.id_country = id_country; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getIsocode() { return isocode; } public void setIsocode(String isocode) { this.isocode = isocode; } } Controller: @Controller @RequestMapping("/") public class HomeController { private final OrganizationService organizationService; private final CountryService countryService; @Autowired public HomeController(final OrganizationService organizationService, final CountryService countryService) { this.organizationService = organizationService; this.countryService = countryService; } @RequestMapping(value="add", method=RequestMethod.GET) public ModelAndView addOrganization() { ModelAndView modelAndView = new ModelAndView("add"); Organization organization = new Organization(); modelAndView.addObject("organization", organization); List<Country> countries = countryService.listOfCountries(); modelAndView.addObject("countries", countries); return modelAndView; } @RequestMapping(value="add", method=RequestMethod.POST) public ModelAndView addingConfirm(Organization organization) { ModelAndView modelAndView = new ModelAndView("confirm"); organizationService.addOrganization(organization); String message = "Organization was successfully added."; modelAndView.addObject("message", message); return modelAndView; } @RequestMapping(method = RequestMethod.GET) public ModelAndView list() { ModelAndView modelAndView = new ModelAndView("index"); List<Organization> organizations = organizationService.listOfOrganizations(); modelAndView.addObject("organizations", organizations); return modelAndView; } @RequestMapping(value="/edit/{id}", method=RequestMethod.GET) public ModelAndView editOrganization(@PathVariable Integer id) { ModelAndView modelAndView = new ModelAndView("edit"); Organization organization = organizationService.getOrganization(id); modelAndView.addObject("organization", organization); List<Country> countries = countryService.listOfCountries(); modelAndView.addObject("countries", countries); return modelAndView; } @RequestMapping(value="/edit/{id}", method=RequestMethod.POST) public ModelAndView editConfirm(@ModelAttribute Organization organization, @PathVariable Integer id) { ModelAndView modelAndView = new ModelAndView("confirm"); organizationService.editOrganization(organization); String message = "Organization was successfully edited."; modelAndView.addObject("message", message); return modelAndView; } @RequestMapping(value="/remove/{id}", method=RequestMethod.GET) public ModelAndView removeOrganization(@PathVariable Integer id) { ModelAndView modelAndView = new ModelAndView("confirm"); organizationService.removeOrganization(id); String message = "Organization was successfully deleted."; modelAndView.addObject("message", message); return modelAndView; } } A: Your model is inadequate for that kind operation. What you need to do is: Your model must change: import javax.persistence.*; @Entity public class Organization { @Id @GeneratedValue private Integer id; private String name; //This will load automatically when you load your Organization entity. @OneToOne(cascade=CascadeType.ALL,fetch=FetchType.EAGER) @JoinColumn(name="country") private Country country; private String address; private String phone; private Long market_cap; public Organization(Integer id, String name, Country country, String address, String phone, Long market_cap) { this.id = id; this.name = name; this.country = country; this.address = address; this.phone = phone; this.market_cap = market_cap; } public Organization() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Long getMarket_cap() { return market_cap; } public void setMarketCap(Long market_cap) { this.market_cap = market_cap; } } and in you view in that case jsp: <c:forEach items=“${organizations}" var=“organization"> <c:url var="edit" value="/edit/${organization.id}" /> <c:url var="remove" value="/remove/${organization.id}" /> <tr> <td><c:out value="${organization.name}" /></td> <td><c:out value="${organization.country.name}" /></td> //Should do the trick <td><c:out value="${organization.address}" /></td> <td><c:out value="${organization.phone}" /></td> <td><c:out value="${organization.market_cap}" /></td> <td valign = "top"><a href="${edit}">Edit</a></td> <td valign = "top"><a href="${remove}">Remove</a></td> </tr> </c:forEach>
[ "stackoverflow", "0032105906.txt" ]
Q: How to verify password with Spring I have found out how to hash the password of some one and persist it in the database with SpringMVC: BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String pw = passwordEncoder.encode("test"); Now the question is, how I can verify the password coming from the request to let the user login my web app? After some research I saw, that there are a lot of ways to do this. Some solutions works with user roles. What my webapps should do is to offer my users a login page where they can register (here I would persist the password with the code shown above). After registering they should be able to login, which means I need to verify the password from the login form. Is there any state of the art example out there? A: This is how a raw password can be matched to an encoded one: passwordEncoder.matches("rawPassword", user.getPassword()), But as others say, coding Security on your own is cumbersome, and so I'd recommend using Spring Security instead. Yes, it does take effort to learn, but you can find good tutorials on it. Here is a unique tutorial on it (disclaimer: I'm the author).
[ "pt.stackoverflow", "0000334997.txt" ]
Q: Melhorando código jquery Tenho um código em jquery que faz o seguinte, ele cria uma classe após o hover, até ai tá funcionando normalmente, mas como vou ter que replicar essa ação em outros lugares mas vai mudar as propriedades css de cada section, no caso são quatro, só que não queria ter que ficar replicando o mesmo código varias vezes, alguém sabe uma maneira de melhorar esse código para não ficar repetitivo ? $('.bg_hover').hover( function(){ $(this).addClass('ativo'); }, function(){ $(this).removeClass('ativo'); } ); $('.bg_hover_dois').hover( function(){ $(this).addClass('ativo_dois'); }, function(){ $(this).removeClass('ativo_dois'); } ); A: Adiciona um ID único a cada um dos seus elementos, e nessa função você pega esse id e adiciona a classe e remove a mesma, conforme o ID dele. E todos os elementos que você quer q tenham esse comportamento precisam ter a classe bg_hover, apenas bg_hover $('.bg_hover').hover( function(){ var id = $(this).attr("id"); $(this).addClass('ativo'+ id); }, function(){ var id = $(this).attr("id"); $(this).removeClass('ativo' + id); } ); Assim não precisa ficar replicando, somente alterar o id de cada elemento que você quer que tenha esse comportamento
[ "tex.stackexchange", "0000073327.txt" ]
Q: £ = $ with OT4 and tgpagella loaded There seems to be a incompatibility between the OT4 font encoding and the tgpagella package. When I load either of the packages, the pound sign comes out as $ (a dangarous thing since we are in a financial crisis already =;-). I have these two packages pre-loaded by a journal file. Can I do anything about this? \documentclass{article} \usepackage{tgpagella} %\usepackage[OT4]{fontenc} \usepackage[utf8]{inputenc} \usepackage{textcomp} \begin{document} 15€ + \$17 = 13£? \end{document} A: The OT* font encodings have the problem that the they have 128 slot positions only. There is no place in the OT4 encoding for the sterling. The symbol is supported by a crude hack. The symbols sterling and dollar share the same slot. The italics shape it and a special shape for the upright form ui contains the sterling and the other shapes the dollar: \DeclareTextCommand{\textdollar}{OT4}{\hmode@bgroup \ifdim \fontdimen\@ne\font >\z@ \slshape \else \upshape \fi \char`\$\egroup} \DeclareTextCommand{\textsterling}{OT4}{\hmode@bgroup \ifdim \fontdimen\@ne\font >\z@ \itshape \else \fontshape{ui}\selectfont \fi \char`\$\egroup} However, TeX Gyre Pagella does not support this and always uses the dollar sign. The font shape ui is not even defined: LaTeX Font Warning: Font shape `OT4/qpl/m/ui' undefined (Font) using `OT4/qpl/m/n' instead on input line 12. As solution \textsterling can be redefined for the OT4 encoding to use a different encoding without such trouble: \DeclareTextCommand{\textsterling}{OT4}{% \begingroup\fontencoding{T1}\selectfont\textsterling}\endgroup } A better solution is to use a better encoding like T1 as suggested by Herbert. This can also be done after the class is loaded: \documentclass{...} \usepackage[T1]{fontenc} Package fontenc is the exception in the package management system of LaTeX. It can be loaded several times with different options. For the case that some text is still using OT4, I would add the redefinition of \textsterling for OT4 and use a better encoding like T1.
[ "stackoverflow", "0052968577.txt" ]
Q: How to fix the javascript Date object I have a website with an automatic updating footer, where you can find the date. But the footer gives the complete wrong date. This is the code behind it: $(function(){ var now = new Date(); var mm = now.getMonth() + 1; $("#footer").html(`&copy; NekoLuka ${now.getFullYear()}/${mm}/${now.getDay()}`); } Today is 2018/10/24, But the footer gives 2018/10/3. Does anyone know how to solve this? A: Look at the documentation on MDN. You are using getDay: Returns the day of the week (0-6) for the specified date according to local time. You should be using getDate: Returns the day of the month (1-31) for the specified date according to local time. A: now.getDay() gets the date of the week, you need now.getDate() to get the current day
[ "gis.stackexchange", "0000360356.txt" ]
Q: QGIS cluster character symbol visibility based on cluster size I want to display the cluster size with a condition : I don't want to display this information for small clusters. The expression is working fine but I don't know I can add else... case when @cluster_size > 30 then @cluster_size end Is my case, cluster size of the clusters with a size > 30 are displayed. BUT cluster <30 are labelled with a A letter AND I want to display NOTHING. Not working : case when @cluster_size > 30 then @cluster_size else @cluster_size = NULL end Returns me 0 but not empty : case when @cluster_size > 30 then @cluster_size else @cluster_size = ' ' end If I remove A letter from the assistant, nothing is displayed. A: I am not sure what is wrong in your case but I can confirm that Else '' removed the A and got empty cluster: case when @cluster_size > 30 then @cluster_size else '' end Output I am using QGIS 3.10.4.
[ "stackoverflow", "0061878783.txt" ]
Q: How to truncate very long tick labels on y-axis of subplots and fit plot and labels neatly in one fig using matplotlib? Below is my code. I would like to truncate the y-axis tick labels. I can't truncate the field that is being used for the labels because then the data will aggregate improperly. I need to truncate the strings being used for the label. Let's say the first 100 characters per string. How would I truncate for each subplot in this manner to be able to neatly show all the labels and subplots in one figure? fig, ax = plt.subplots(2,2, sharex = True, figsize=(15,10)) a = q3[:10].plot(kind='barh',stacked=True,colormap='Reds',rot=0, legend = None, ax = ax[0,0]) b = q1[:10].plot(kind='barh',stacked=True,colormap='Reds',rot=0, legend = None,ax = ax[0,1]) c = q4[:10].plot(kind='barh',stacked=True,colormap='Reds',rot=0, legend = None,ax = ax[1,0]) d = q2[:10].plot(kind='barh',stacked=True,colormap='Reds',rot=0, legend = None,ax = ax[1,1]) plt.show() A: I can't truncate the field that is being used for the labels because then the data will aggregate improperly. By default, pandas uses the index to set the tick labels. However, you can create another column of truncated labels and then tell pandas to use that for setting the y-tick labels. q3.plot(kind='barh', ..., yticks=q3['my_column_with_truncated_strings']) Alternatively, you can use matplotlib directly: axes[0,0].set_yticklabels(q3['my_column_with_truncated_strings'])
[ "physics.stackexchange", "0000231649.txt" ]
Q: What is the relation between centripetal acceleration and radius in uniform circular motion? In uniform circular motion we know that $a_c=\frac {v^2}r=\omega^2r$.So,is $a_c$ directly or inversely proportional with $r$ and why not the other is true? Thanks for any help. A: In uniform circular motion, $v = v(r)$ so that $a_{c} \propto r$, not $a_{c} \propto r^{-1}$. In other words, $v$ is not a constant at all radii while $\omega$ is constant for all radii. So the second part of the expression is the one you want to look at in this regard. Though the first half of the expression states that $a_{c}$ is only explicitly dependent upon $r^{-1}$, it is still implicitly proportional to $r$. A: In the first expression $v$ is the speed of a single point on the disk, actually any point that is a distance $r$ from the center. In the second expression, $\omega$ is the angular speed of the entire disk. Since $v$ and $\omega$ have very different definitions, the interpretation of those two equations is quite different.
[ "stackoverflow", "0046862893.txt" ]
Q: update one checkbox when clicking another I have two checkboxes for capturing the delivery/collection methods. Checkbox 1 visible for desktop: <input type="radio" value="COLLECTION" id="coldelcheck1" name="coldelcheck1" class="icheck" checked onclick="coldel_pref()" onchange="coldel_pref()" > <input type="radio" value="DELIVERY" id="coldelcheck1" name="coldelcheck1" class="icheck" checked onclick="coldel_pref()" onchange="coldel_pref()" > Checkbox 2 visible for mobile: <input type="radio" value="COLLECTION" id="coldelcheck2" name="coldelcheck2" class="icheck" checked onclick="coldel_pref()" onchange="coldel_pref()" > <input type="radio" value="DELIVERY" id="coldelcheck2" name="coldelcheck2" class="icheck" checked onclick="coldel_pref()" onchange="coldel_pref()" > If the user clicks the desktop version then I want the corresponding hidden mobile value to checked and vice versa. If delivery on desktop is checked then I want the delivery on mobile to be checked. How can I do this using jquery/javascript? A: The closest way (not very good though - not a good pratice to have same ids). Please note the this as first argument of function calls. function coldel_pref(theRadio){ var theOtherId = theRadio.id == 'coldelcheck1' ? '2' : '1'; var theOtherDomId = "coldelcheck"+theOtherId; var theOtherSelector = 'input#'+theOtherDomId+'[type="radio"][value="'+theRadio.value+'"]'; var e = document .querySelector(theOtherSelector) .checked = true; } <table border="0" cellspacing="5" cellpadding="5"><tr><th>Desktop</th><th>Mobile</th></tr><tr><td> <input type="radio" value="COLLECTION" id="coldelcheck1" name="coldelcheck1" class="icheck" checked onclick="coldel_pref(this)" onchange="coldel_pref(this)" /><input type="radio" value="DELIVERY" id="coldelcheck1" name="coldelcheck1" class="icheck" checked onclick="coldel_pref(this)" onchange="coldel_pref(this)" /></td><td> <input type="radio" value="COLLECTION" id="coldelcheck2" name="coldelcheck2" class="icheck" checked onclick="coldel_pref(this)" onchange="coldel_pref(this)" /><input type="radio" value="DELIVERY" id="coldelcheck2" name="coldelcheck2" class="icheck" checked onclick="coldel_pref(this)" onchange="coldel_pref(this)" /></td></tr> </table> A better and shorter one? function cpref(theRadio) { var specs = theRadio.id.split('-'); specs[1] = specs[1] == 'mobile' ? 'desktop' : 'mobile'; document.getElementById(specs.join('-')).checked = true ; } <table border="0" cellspacing="5" cellpadding="5"><tr><th>Desktop</th><th>Mobile</th></tr><tr><td> <input type="radio" value="COLLECTION" id="rad-desktop-1" name="coldelcheck1" class="icheck" onclick="cpref(this)" onchange="cpref(this)" /> <input type="radio" value="DELIVERY" id="rad-desktop-2" name="coldelcheck1" class="icheck" onclick="cpref(this)" onchange="cpref(this)" /></td><td> <input type="radio" value="COLLECTION" id="rad-mobile-1" name="coldelcheck2" class="icheck" onclick="cpref(this)" onchange="cpref(this)" /> <input type="radio" value="DELIVERY" id="rad-mobile-2" name="coldelcheck2" class="icheck" onclick="cpref(this)" onchange="cpref(this)" /></td></tr> </table>
[ "stackoverflow", "0057262217.txt" ]
Q: How do you use EC.presence_of_element_located((By.ID, "myDynamicElement")) except to specify class not ID I am trying to use Python to web scrape a website that loads it's HTML dynamically by using embedded javascript files that render the data as a Response into the HTML. Therefore, if I use BeautifulSoup alone, I will not be able to retrieve that data that I need as my program will scrape it before the Javascript loads the data. Due to this, I am integrating the selenium library into my code, to make my program wait until a certain element is found before it scrapes the website. I had originally done this: element = WebDriverWait(driver,100).until(EC.presence_of_element_located((By.ID, "tabla_evolucion"))) But I want to specify a class instead by doing something like: element = WebDriverWait(driver,100).until(EC.presence_of_element_located((By.class, "ng-binding ng-scope"))) Here is the rest of my code: driver_path = 'C:/webDrivers/chromedriver.exe' driver = webdriver.Chrome(executable_path=driver_path) driver.header_overrides = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36'} url = "myurlthatIamscraping.com" response = driver.get(url) html = driver.page_source characters = len(html) element = WebDriverWait(driver,100).until(EC.presence_of_element_located((By.class, "ng-binding ng-scope"))) print(html) print(characters) time.sleep(10) driver.quit() It is not working for me and I can not find the right syntax anywhere. A: The relevant HTML would have helped us to construct a more canonical answer. However to start with your first line of code: element = WebDriverWait(driver,100).until(EC.presence_of_element_located((By.ID, "tabla_evolucion"))) is pretty much legitimate where as the second line of code: element = WebDriverWait(driver,100).until(EC.presence_of_element_located((By.class, "ng-binding ng-scope"))) Will raise an error as: Message: invalid selector: Compound class names not permitted as you can't pass multiple classes through By.class. You can find a detailed discussion in Invalid selector: Compound class names not permitted using find_element_by_class_name with Webdriver and Python Solution You need to take care of a couple of things as follows: Without any visibility to your usecase, functionally inducing WebDriverWait in association with EC as presence_of_element_located() merely confirms the presence of the element within the DOM Tree. Presumably moving ahead either you need to get the attributes e.g. value, innerText, etc or you would interact with the element. So instead of presence_of_element_located() you need to use either visibility_of_element_located() or element_to_be_clickable() You can find a detailed discussion in WebDriverWait not working as expected For an optimum result you can club up the ID and CLASS attributes and you can use either of the following Locator Strategies: Using CSS_SELECTOR: element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".ng-binding.ng-scope#tabla_evolucion"))) Using XPATH: element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//*[@class='ng-binding ng-scope' and @id='tabla_evolucion']")))
[ "stackoverflow", "0062711156.txt" ]
Q: Unable to create Maven Projects and unable to download maven dependencies I am unable to create Maven projects and none of the dependencies are getting downloaded. Whenever I am creating new project, I am receiving below error screenshot: Eclipse Error Also, none of the maven commands are working, like mvn clean. Getting below error: Maven Error A: Unable to find valid certification path to requested target This is usually a sign that someone or something is intercepting HTTPS traffic, and is messing with the certification path. I have this problem with my company's network because our Cyber team use a magic HTTPS sniffing tool that replaces the certificate of the site you're trying to access with the company's certificate so that traffic can be monitored. (Forgive my noddy explanation) If you're not behind a corporate proxy or a proxy owned by someone who you know manages your internet connection, then you may have security issues that are way beyond the scope of what I'm explaining here! Anyway, the solution for me was to go to the URL maven is trying to download from (in your case, https://repo.spring.io ) and download the certificate from your web browser (this varies by browser type, but you can google 'how to download certificate from mybrowser. You can then add that certificate to your local JDK certificate store. Here are the Oracle instructions for installing a root CA in your truststore: https://docs.oracle.com/cd/E19906-01/820-4916/geygn/index.html
[ "gis.stackexchange", "0000343657.txt" ]
Q: Shapefile reprojection with "sf" R package doesn't work I am using the sf R package to work with a shapefile (with a species distribution). > sp #this is the shapefile returns: Simple feature collection with 1 feature and 1 field geometry type: MULTIPOLYGON dimension: XY bbox: xmin: -11539950 ymin: 4933183 xmax: 11985800 ymax: 8012809 epsg (SRID): NA proj4string: +proj=moll +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs scntfcN geometry 3096 Myodes rutilus MULTIPOLYGON (((5070195 797... These are the shapefile crs and plot: > crs(sp) #show the original crs [1] "+proj=moll +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs" > plot(sp) #plot the original shapefile I want to reproject the shapefile from the Mollweide projection to the WGS84 geographic crs: > sp_reproj <- st_transform(sp, 4326) #reproject the shapefile > crs(sp_reproj) returns: [1] "+proj=longlat +datum=WGS84 +no_defs" but when I try to plot it, I get this error: > plot(sp_reproj) Error in CPL_geos_is_empty(st_geometry(x)) : Evaluation error: IllegalArgumentException: point array must contain 0 or 1 elements. Furthermore, if I write the shapefile > st_write(sp_reproj, "Reprojection.shp") and open it with QGIS, I have this: Strangely, the holes (lakes) seems to have been filled. Further notes: 1) the original sp shapefile seems to be valid and not empty > st_is_valid(sp) [1] TRUE > st_is_empty(sp) [1] FALSE 2) My final aim is not just to plot the reprojected shapefile, but to intersect it with a raster. However, I get the same error as when plotting, so the problem should be in the shapefile not in the operation. 3) Actually, the sp shapefile come from a bigger shapefile with thousand of sf features. This one is the only one that gives me that error. 4) Here the original and reprojected shapefiles Why I get this error? And why the reprojection fill the holes in the original shapefile? A: Your sp object is a MULTIPOLYGON - lets break it into POLYGON objects and see if there's something afoot: > sp2 = st_cast(sp$geometry,"POLYGON") > length(sp2) [1] 40 Its 40 separate POLYGON units. At this point plot(sp2) works and looks fine. Now transform those 40 units and plot: > sp2t = st_transform(sp2, 4326) > plot(sp2t) Error in CPL_geos_is_empty(st_geometry(x)) : Evaluation error: IllegalArgumentException: point array must contain 0 or >1 elements. Great, we've reproduced your error, which is the first step to fixing it. Now which of the 40 units is the problem? A little testing reveals: > plot(sp2t[1:39]) works fine. but... > plot(sp2t[40]) Error in CPL_geos_is_empty(st_geometry(x)) : Evaluation error: IllegalArgumentException: point array must contain 0 or >1 elements. What is that pesky object? > sp2t[40] Geometry set for 1 feature geometry type: POLYGON dimension: XY bbox: xmin: 179.9987 ymin: 67.11926 xmax: 179.9987 ymax: 67.11926 epsg (SRID): 4326 proj4string: +proj=longlat +datum=WGS84 +no_defs POLYGON ((179.9987 67.11926)) It appears to be a polygon with only one point. What did it start out as? > sp2[40] Geometry set for 1 feature geometry type: POLYGON dimension: XY bbox: xmin: 9936218 ymin: 7483013 xmax: 10072890 ymax: 7528533 epsg (SRID): NA proj4string: +proj=moll +lon_0=0 +x_0=0 +y_0=0 +ellps=WGS84 +units=m +no_defs POLYGON ((9936320 7528522, 10072891 7483013, 99... which is a polygon of four coordinates: > st_coordinates(sp2[40]) X Y L1 L2 [1,] 9936320 7528522 1 1 [2,] 10072891 7483013 1 1 [3,] 9936218 7528533 1 1 [4,] 9936320 7528522 1 1 which transformed becomes one point: > st_coordinates(sp2t[40]) X Y L1 L2 [1,] 179.9987 67.11926 1 1 The original polygon is a tiny sliver at the top right. It has an area that is about one ten-millionth of the total area: > sum(st_area(sp2)) 1.846842e+13 [m^2] > st_area(sp2[40]) 1600110 [m^2] and it is probably being reprojected to a point because of edge problems with the transformation. Let's try projecting each point in polygon 40: > p40pts = st_cast(sp2[40],"POINT") > st_transform(p40pts, 4326) Geometry set for 4 features (with 3 geometries empty) geometry type: POINT dimension: XY bbox: xmin: 179.9987 ymin: 67.11926 xmax: 179.9987 ymax: 67.11926 epsg (SRID): 4326 proj4string: +proj=longlat +datum=WGS84 +no_defs POINT EMPTY POINT EMPTY POINT (179.9987 67.11926) POINT EMPTY Empty geometries. These are probably right on the edge or even over the edge of that Mollweide projection. So what to do? I reckon this sliver is negligible, so you can rebuild your spatial data by dropping it and remaking a MULTIPOLYGON object if you need it: > spfix = sp2t[1:39] > spfixu = st_union(spfix) > plot(spfixu, col="brown") and the lakes are preserved as holes.
[ "stackoverflow", "0022192427.txt" ]
Q: replace symbol .= php hello i have this code: $thread_qry5= "SELECT * FROM xenProve_prove ORDER BY view_count DESC LIMIT 5"; $row5 = XenForo_Application::get('db')->fetchAll($thread_qry5); foreach ( $row5 AS $rows5 ) { $viewid = $rows5['thread_id']; $viewtitle = $rows5['title']; $viewuser = $rows5['username']; $MostView .= 'div style="height:30px; width:640px; border-bottom:1px solid #999;padding:5px;"> <div style="height:40px; width:500px;float:left"> <div style="height:20px; width:650px; font-size:16px;color:#6d3f03;">'.$viewtitle.'</div> <div style="height:20px; width:650px; font-size:12px;color:#6d3f03;">'.$viewuser.'</div> </div> </div>'; how can replace this symbol .= ? Xenforo system don't read this symbol (.=) I tried : $MostView = 'div style="height:30px; width:640px; border-bottom:1px solid #999;padding:5px;"> <div style="height:40px; width:500px;float:left"> <div style="height:20px; width:650px; font-size:16px;color:#6d3f03;">'.$viewtitle.'</div> <div style="height:20px; width:650px; font-size:12px;color:#6d3f03;">'.$viewuser.'</div> </div> </div>' . $MostView; but don't work. And i tried the For cycle anche the While cycle but don't work. Thanks you A: You are trying to add a string to another string (by a concatenating assignment operator) that doesn't exist (yet). You have to define the string first: $MostView = ''; and then: foreach ( $row5 AS $rows5 ) { $viewid = $rows5['thread_id']; $viewtitle = $rows5['title']; $viewuser = $rows5['username']; $MostView .= 'div style="height:30px; width:640px; border-bottom:1px solid #999;padding:5px;"> <div style="height:40px; width:500px;float:left"> <div style="height:20px; width:650px; font-size:16px;color:#6d3f03;">'.$viewtitle.'</div> <div style="height:20px; width:650px; font-size:12px;color:#6d3f03;">'.$viewuser.'</div> </div> </div>'; I don't think this problem is related to XenForo. If you turn on error reporting (just check Google or Stack Overflow) you will get more usefull information about this error.
[ "math.stackexchange", "0000134370.txt" ]
Q: Taylor expansions at $x=\infty$ How do you expand, say, $\frac{1}{1+x}$ at $x=\infty$? (or for those nit-pickers, as $x\rightarrow\infty$. I know it doesn't strictly make sense to say "at infinity", but I think it is standard to say it anyway). I have a couple of interesting questions to follow... I might as well say them now. Question 1. According to WolframAlpha, the Taylor expansion of, say, $\frac{1}{(1+x-3x^{2}+x^{3})}$ at $x=\infty$ is $\frac{1}{x^{3}}+\frac{3}{x^{4}}+\frac{8}{x^{5}}+...$ . We see that the expansion starts at $\frac{1}{x^{3}}$ and has higher order terms. I suspect this occurs for any fraction of the form 1/(polynomial in x). Why is this? (I don't see how dividing all the terms on the LHS by $\frac{1}{x^{3}}$ helps, for example). Question 2. My motivation behind all this Taylor series stuff was originally: Can an infinite expansion $\frac{1}{a_{0}+a_{1}x+a_{1}x^{2}+...}$ be written in the form $b_{0}+\frac{b_{1}}{x}+\frac{b_{2}}{x^{2}}+...$ ? If so, when (i.e. what conditions must we have on the $a_{n}$)? A: Hint: Perform the substitution $y=x^{-1}$ and perform the Maclaurin of $y$ expansion (=Taylor expansion of $y$ around $y=0$). At the end of the day, you may substitute $x$ back...
[ "stackoverflow", "0007304183.txt" ]
Q: Completion in NSTextView I am looking for a way (or code) to have a completion list close to the one of xcode Do you know how to achieve this? Thanks and regards, A: Use the - (NSArray *)textView:(NSTextView *)textView completions:(NSArray *)words forPartialWordRange:(NSRange)charRange indexOfSelectedItem:(NSInteger *)index method of NSTextViewDelegate. This is called whenever text completion is initiated (either by the user, by pressing Esc or F5, or programmatically, by calling -[NSTextView complete:]. You'll need to do some fancy overriding to make it look like the one in Xcode, however. The stock implementation displays only plain text in the system font.
[ "stackoverflow", "0033520137.txt" ]
Q: How to change text inside a label tag using jquery How can I change text Add Your Image to Change Your Image. <label class="control-label col-md-offset-4 col-md-4 btn green feedbackImg" style="text-align:center;"> Add Your Image <input type="file" name="data[Feedback][img]" class="form-control hide single_img_btn" id="1" style="display: none;"> </label> $('.feedbackImg').text('Change Your Image'); But it changed the label as follows : <label class="control-label col-md-offset-4 col-md-4 btn green feedbackImg" style="text-align:center;"> Add Your Image </label> That means it remove input tag also. How can I keep all same except the text only? A: If you can change your HTML then simply wrap the text you want to change in a span to make it easier to select: <label class="control-label col-md-offset-4 col-md-4 btn green feedbackImg" style="text-align:center;"> <span>Add Your Image</span> <input type="file" name="data[Feedback][img]" class="form-control hide single_img_btn" id="1" style="display: none;"> </label> $('.feedbackImg span').text('Change Your Image'); If you can't change the HTML, then you would need to amend your JS code to retreive and amend the textNode itself: $('.feedbackImg').contents().first()[0].textContent = 'Change Your Image'; A: You need to update the textNode contents() - for getting all nodes including text and comments eq() - get first element , which is textNode(label) replaceWith() - update the text content with new text CODE: $('.feedbackImg').contents().eq(0).replaceWith('Change Your Image'); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <label class="control-label col-md-offset-4 col-md-4 btn green feedbackImg" style="text-align:center;"> Add Your Image <input type="file" name="data[Feedback][img]" class="form-control hide single_img_btn" id="1" style="display: none;"> </label> OR $('.feedbackImg').contents()[0].nodeValue = 'Change Your Image'; <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <label class="control-label col-md-offset-4 col-md-4 btn green feedbackImg" style="text-align:center;"> Add Your Image <input type="file" name="data[Feedback][img]" class="form-control hide single_img_btn" id="1" style="display: none;"> </label>
[ "math.stackexchange", "0000486617.txt" ]
Q: Möbius transformations forming a group and isomorphism with $S_{3}(D_{6})$ My task is to prove that the Möbius transformations defined by $z,\frac{1}{z},1-z,\frac{1}{1-z},\frac{z}{z-1},\frac{z-1}{z}$ make up a group that is isomorphic to the group $S_{3}(D_{6})$. Identify the involutions i.e elements of order 2. We are also given a hint: Show that the group permutes the elements, $0,1,\infty$ My solution. 1) First I made the composition of all the above functions and I got $\frac{1}{z}$ so I stay within the set thus the composition is an operation on this set. 2) associativity holds at the composition of functions is associative 3) as the identity element I have set the function $f(z)=z$ and I have checked with the other elements from the set. 4) I have found inverses to each of the elements and these are also elements of the set Thus the set of these transformations together with $\circ$ is a group. I have a problem though with the second part. Firstly I have no idea what is the group $S_{3}(D_{6})$ how does it look like? What elements? Is this a direct product??? In practice it is much easier to show that two groups are non isomorphic, so I need to find a bijective function between my Möbius transformations and the $S_{3}(D_{6})$ Can someone help me with the identification of the involutions and proving the isomorphism? Any help appreciated A: Let $H$ be your group of Möbius transformations. We get a group homomorphism $$H\rightarrow S_3, f\mapsto [x\mapsto f(x)],$$ where $S_3$ denotes the symmetric group in the three elements 0,1,$\infty$. Check that this is injective because only the identity fixes all the three elements. As $H$ has 6 elements and $S_3$ has also $3!=6$ elements, this map is even bijective, hence a group isomorphism. Remark: Composing all functions in your solution doesn't suffice to show, that the set is closed. Each composition of two elements has to be an element of the set again. By $S_3(D_6)$ they mean $S_3$ respectivly $D_6$ as $D_6$ is isomorphic to $S_3$. Take a look at wikipedia.
[ "stackoverflow", "0009171041.txt" ]
Q: Calling a Page Method using jQuery - Backbone.Js now With the below javascript code i am trying some BackboneJs concepts. Couldn't figure out why the response after invoking a XHR request is HTML of full page rather than the serialized version of Person class. Have a look below Server Side Code is of C# and ASP.NET 2.0 note: forget the urland urlroot on the model, i am using the backbonejs Sync Javascript window.Person = Backbone.Model.extend({ defaults: { id: Math.random(), name: "Type your name" }, initialize: function (model) { this.bind("change", this.ModelChanged); }, ModelChanged: function () { }, url: "CreatePerson", urlRoot: "/index.aspx/" }); Backbone.sync = function (met, mod, op) { switch (met) { case "create": break; case "update": break; case "delete": break; case "read": break; default: break; } }; Server side code [WebMethod(EnableSession = true)] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public static Person CreatePerson(Person newPerson) { List<Person> peopleList = HttpContext.Current.Session["People"] as List<Person>; if (peopleList == null) { peopleList = new List<Person>(); } Person p1 = new Person(); p1 = newPerson; peopleList.Add(p1); HttpContext.Current.Session["People"] = peopleList; return p1; } Person class public class Person { public string Id { get; set; } public string Name { get; set; } } Finally the test code var x = new Person({ name: "StackOverflow" }); $.post("index.aspx/CreatePerson", "{" + JSON.stringify(x) + "}", function () { console.log(arguments) }); A: I don't understand why but jQuery made me follow this weird procedure to get this done. It serializes valid json to URL encoded format & not json string which is wrong. $.ajaxSetup({ contentType: "application/json; charset=utf-8" }); Backbone.sync = function (met, mod, op) { console.log("method", met, "model", mod); switch (met) { case "create": $.post("index.aspx/CreatePerson", { "newPerson": mod.attributes }, function () { console.log(arguments) }, "json"); break; case "update": var x = { "newPerson": mod.attributes }; x = JSON.stringify(x); $.post("index.aspx/CreatePerson", x, function () { console.log(arguments) }); break; case "delete": break; case "read": break; default: break; } };
[ "stackoverflow", "0015321306.txt" ]
Q: TYPO3 6.0: PHP_SCRIPT was removed. How can I fix this? It was years ago when I last used TYPO3 intensively. So I don't remember much TYPO-Script. When I updated to 6.0, I found out, that this code is no longer working: marks.CONTENT.30 = PHP_SCRIPT marks.CONTENT.30.file = fileadmin/db/db.php It simply inserted the html output of the db.php (which did some database requests and formed a customized html/css table out of it). How can I fix this quickly? I've heard that PHP_SCRIPT was deprecated, and that there is another keyword (USER), but I don't know, how to use it. Remember: I'm really no TYPO-Script expert any more, so feel free to explain in detail. ;-) Thanks! Ingo. A: Looks like you need a basic extension, which, as you mentioned, is simply USER or USER_INT content objects. First one is cached within a page content, so, if you script outputs some static or rarely changed info, you should consider to choose USER type. If you have dynamic data, which changes frequently (every new page load brings new output), then you'd rather take USER_INT, but be aware: USER_INT script is called every time your page loads, so you must optimize it as much, as possible. I advise you to read this basic info about usage of these two types. So, at the end you need a PHP class, which name starts from 'user_' or 'tx_' with a main() method, which takes two params $content and $conf. These params will not be used by you, but FYI, $content may contain pre-processed content, and $conf contains any configuration data, needed for your script. Inside of main() you create your HTML output and just return it (as string). TS part will be following in case of USER: includeLibs.something = fileadmin/db/db.php marks.CONTENT.30 = USER marks.CONTENT.30 { userFunc = user_db->main } For USER_INT: marks.CONTENT.30 = USER_INT marks.CONTENT.30 { includeLibs = fileadmin/db/db.php userFunc = user_db->main } NOTE: I've described dirty, but easy way for your case. Much better will be consider using CONTENT cObject, because it does exactly, what you need: fetches records from DB and outputs them on page in a way, that you like.
[ "stackoverflow", "0036672652.txt" ]
Q: start with a random function and then alternate (Python) I created a set of functions to find the probability that Luke, a sleepwalker, would escape from his room, represented by 9 boxes. Luke starts in the center of the 3x3 square, (0,0) and can move right/left or up/down (he must alternate between right/left and up/down with every step, eg cannot go right left or right right). Luke escapes by walking out of the doors on either side of him (2,0) or (-2,0) I have the basic game written out, but I'm tying my head into knots on how to get Luke to start in a random direction. As code shows below i have him going right/left first. I'd like it to have an equal chance going either direction for Luke's first step, and then alternating directions. Any idea how to do this? import random def checkXState(x): right=x+1; left=x-1; xc = random.choice([right,left]) return xc def checkYState(y): up=y+1; down=y-1; yc = random.choice([up,down]); return yc def theRule(x,y): #the Rule determines whether Luke is awake or not, and is applied to each step if (x==2 and y == 0) or (x==-2 and y==0): return 'Luke has ESCAPED'; elif (x==2 or x==-2 or y==2 or y==-2): return 'Luke is AWAKE'; def theGame(): x=0; y=0; while True: x = checkXState(x); #Luke goes right or left, new x coord stored in x print(x,y); a = theRule(x,y); if a==('Luke is AWAKE' or 'Luke has ESCAPED'): print(a) break; y = checkYState(y); print(x,y); b = theRule(x,y); if b==('Luke is AWAKE' or 'Luke has ESCAPED'): print(b) break; A: directions = ["up", "down", "left", "right"] start_dir = random.choice(directions) if start_dir == "left" or start_dir == "right": checkXstate(x) else: checkYstate(y)
[ "stackoverflow", "0006771331.txt" ]
Q: What's the advantages and disadvantages of PowerVR? My game engine recently added PowerVR (PVR) support, after some search on Google and Wikipedia, I only know the definition of PVR, but I don't know what is it use for, what are its advantages and disadvantages. I'm developing game for Android, what should I use, PNG or PVR? A: (PowerVR is a brand name of Imagination Technologies Ltd. referring to their graphics acceleration technology. PVR is a texture container format used in the PowerVR Insider SDK. PVRTC is PowerVR's texture compression scheme which is what I think you're interested in... apologies if you're not) PVRTC is a runtime texture compression format for use with PowerVR graphics accelerators (a lot of the Android platforms have one of these). Compared to uncompressed 32bit textures, PVRTC offers a 8x or 16x compression in 4 bit per pixel or 2 bits per pixel mode. Because it's a runtime texture compression scheme it doesn't need to be decompressed at any stage outside the graphics core itself (and there's dedicated circuitry for that bit on there) so that data is smaller on disk, smaller to upload to GL, smaller in memory and smaller in use when rendering - better and faster in almost every way. On mobile systems, where memory bandwidth is precious and is often the performance bottleneck for graphics, it can make a huge difference to your framerate (and also power use - memory accesses take power). Downsides: PVRTC tends to be larger than PNG on disk - PVRTC data zips (for instance) quite well for disk storage. PVRTC is lossy compression - sometimes artifacts can be seen in PVRTC textures when compared to source images. PNG is lossless so that problem isn't there PVRTC is not available for use with other graphics acceleration than PowerVR (at the moment) - look at DXT/S3TC (larger) or ETC (no alpha) compression for other platforms. Only square, power-of-two dimension textures are likely to work - e.g. 32x32, 512x512 etc. Compression can be pretty slow PNG isn't a runtime format so the only place that there is an advantage in PNG compression over uncompressed images is storage on disk (or sending over a network etc.) - PNG image data has to be decompressed by the CPU before it can be passed to GL or drawn in any way i.e. PNG is as slow as you can get for textures on these platforms. PNG is lossless and also supports an alpha channel. So... For best performance, use PVRTC where you can and have other versions of your textures available if you can't - e.g. where compression artefacts are too obvious or the platform that you're running on doesn't support it. Further reading: http://imgtec.com/powervr/insider/powervr-faq.asp http://imgtec.com/powervr/insider/docs/PVRTextureCompression.pdf http://imgtec.com/forum/default.asp To make PVRTC textures: http://imgtec.com/powervr/insider/powervr-pvrtextool.asp Hope that helps...
[ "stackoverflow", "0013402279.txt" ]
Q: Rails: Issue with less after bootstrap update -- Cannot load such file -- less It all was working fine before bootstrap update but now i have this error: cannot load such file -- less (in /home/warch/development/railcast_196/app/assets/stylesheets/bootstrap_and_overrides.css.less)` i tried to google this with no luck, i already added the less gems specified in the latest bug resolve: Gemfile extract: gem 'less-rails' gem 'therubyracer' ... gem 'twitter-bootstrap-rails' A: add in your Gemfile in assets group gem 'less', '2.2.2' # (at this date) A: This was gladly a resolved duplicate of: Adding twitter-bootstrap-rails with an existing rails app I only need to restart as @danieleds answered.
[ "stackoverflow", "0051200077.txt" ]
Q: Adding two 4 digit binary numbers using adder circuits I need to write a program that adds two 4 digit binary numbers using an adder circuit that gives us an answer. I need to use the int() function to convert this from binary to decimal (both values need to be displayed). I am struggling to create a code that creates a correct binary AND decimal output. We're entering 2 sets of four digits. The digits are supposed to go through the circuit and the results should be them added together. Right now the gates are all good. But, I cannot get the digits to add together correctly. The binary addition through the circuit is incorrect. The converter and inputs are all correct. The user needs to input a 4 digit binary number for x (x1,x2,x3,x4) and y (y1,y2,y3,y4), and ci = 0. For example: x = 1111 y = 0000 This is the adder circuit along with the diagram that shows how the circuit will look after adding the two binary numbers(I can't embed images yet) this is my current code: import string print('Simple Circuits for Final Project') x = input('x| enter 4 digits: ') y = input('y| enter 4 digits: ') list1 = list(x) print(list1) list2 = list(y) print(list2) #define all the gates def xorgate(x,y): if x == y: return '0' else: return '1' def andgate (x,y): if x == '1' and y == '1': return '1' else: return '0' def orgate (x,y): if x == '1' or y == '1': return '1' else: return '0' #define the entire circuit and input the list of inputs for the circuit. #include the outputs based on the gates defined above. def circuit(x,y,ci): a = 3 #starting value for the while loop, get approp position for our list adder = ['0','0','0','0','0']#adder list only has strings of zero. list to hold binary numbers from the output of the adding circuit b = 4 while a >= 0: xorout = xorgate(x[a],y[a]) print("xor:",(xorout)) s = xorgate(ci,xorout) print("Ci:",ci) andout = andgate(xorout, ci) print("and1:",andout) and2out = andgate(x[a],y[a]) print("and2:",and2out) co = orgate(andout,and2out) print('s:',s) print('co:',co) print('-----------------') ci = co adder[b] = str(s) a-=1 b-=1 adder[4]=ci #print(final) print('The Final Binary Output is:', adder[::-1]) #OUR CONVERTER IS RIGHT, BUT WE CAN'T GET THE BINARY ADDITION ACCURATE outputfinal = ((int(adder[4]) * 16) + (int(adder[3]) * 8)+(int(adder[2]) * 4)+(int(adder[1]) * 2)+(int(adder[0]) * 1)) print('The Final Decimal Output is:', outputfinal) hold = '0' circuit(list1,list2,hold)# 3 value for circuit This is the part we feel is wrong: ci = co adder[b] = str(s) a-=1 b-=1 adder[4]=ci #print(final) print('The Final Binary Output is:', adder[::-1]) This is how my current output is, which is wrong: x| enter 4 digits: 1111 y| enter 4 digits: 0000 ['1', '1', '1', '1'] ['0', '0', '0', '0'] xor: 1 Ci: 0 and1: 0 and2: 0 s: 1 co: 0 ----------------- xor: 1 Ci: 0 and1: 0 and2: 0 s: 1 co: 0 ----------------- xor: 1 Ci: 0 and1: 0 and2: 0 s: 1 co: 0 ----------------- xor: 1 Ci: 0 and1: 0 and2: 0 s: 1 co: 0 ----------------- The Final Binary Output is: ['0', '1', '1', '1', '0'] The Final Decimal Output is: 14 A: You are confusing the order of your adder list. It should be that first address is 0, not 4: adder[0]=ci #print(final) Don't reverse the list yet print('The Final Binary Output is:', adder) Since your converter is expecting it to be in the opposite order, I reverse it here rather than rewrite your converter: adder = adder[::-1] #OUR CONVERTER IS RIGHT, BUT WE CAN'T GET THE BINARY ADDITION ACCURATE outputfinal = ((int(adder[4]) * 16) + (int(adder[3]) * 8)+(int(adder[2]) * 4)+(int(adder[1]) * 2)+(int(adder[0]) * 1)) print('The Final Decimal Output is:', outputfinal) You can try out the whole program (since you are getting a different result) in an online repl: https://repl.it/repls/CompetitiveSerpentineAccess
[ "stackoverflow", "0031328593.txt" ]
Q: How to populate multidimensional array in Perl? I'm getting a Use of uninitialized value error. I don't know if I'm populating my multidimensional array correctly. my @matrix; for (my $i=1; $i<=3;$i++){ $matrix[$i][0] = 4; } for (my $j=1; $j<=3;$j++){ $matrix[0][$j] = 4; } print $matrix[0][0]; I don't understand why this doesn't work. The way I wrote it, the matrix is supposed to populate like so: 1 0 2 0 3 0 0 1 0 2 0 3 A: You're populating $matrix[1][0] and $matrix[0][1], but you don't store anything in $matrix[0][0].
[ "stackoverflow", "0053893414.txt" ]
Q: catch statement is executed every time even if element is displayed in Selenium Receiving no element exception when for below code. I want to Print "Entered the admin block" if adminsearchuserid is displayed AND if element emailtextbox displayed then "Entered the LOGIN block" but my code is showing catch statement even if emailtextbox is displayed. I dont understand where i am doing mistake Case "User ID": try { System.out.println("Entered the try block"); if (adminSearchPo.adminSearchUserId.isDisplayed()) { System.out.println("Entered the admin block"); } else if (lpo.emailTextBox.isDisplayed()) { System.out.println("Entered the LOGIN block"); } } catch (org.openqa.selenium.NoSuchElementException e) { System.out.println("Entered the exception block"); } break; A: You need to handle each if condition with try/catch. Let say, as you said emailtextbox is displayed, code is executing line by line and came to if (adminSearchPo.adminSearchUserId.isDisplayed()) { here element in if condition is not displayed,leads to exception, then it will go to catch. So there is no way to go another if as two if conditions are in try.
[ "tex.stackexchange", "0000215194.txt" ]
Q: Incompatible color package and defining a xfloat environment -> " Too many }'s" I am pepping up a thesis. Among others I am using a package based on Modified UDO thesis by; Jose A. Flores, November 2011. Unfortunately, I cannot find the original. One part of the package seems to redefine the float definition and I boiled the error down to the following code. I created a small style file: (killer.sty) containing: \def\@xfloat#1[#2]{\ifhmode \@bsphack\@floatpenalty -\@Mii\else \@floatpenalty-\@Miii\fi\def\@captype{#1}\ifinner \@parmoderr\@floatpenalty\z@ \else\@next\@currbox\@freelist{\@tempcnta\csname ftype@#1\endcsname \multiply\@tempcnta\@xxxii\advance\@tempcnta\sixt@@n \@tfor \@tempa :=#2\do {\if\@tempa h\advance\@tempcnta \@ne\fi \if\@tempa t\advance\@tempcnta \tw@\fi \if\@tempa b\advance\@tempcnta 4\relax\fi \if\@tempa p\advance\@tempcnta 8\relax\fi }\global\count\@currbox\@tempcnta}\@fltovf\fi \global\setbox\@currbox\vbox\bgroup \def\baselinestretch{1}\@normalsize \boxmaxdepth\z@ \hsize\columnwidth \@parboxrestore } Actually, I have no experience with TeX programming, but from my point of view braces and if-fi are ok. In the most simple case it compiles (pdflatex) and looks ok. If I put the color package, however, it produces following error messages: mini.tex(16): Error: Too many }'s. mini.tex(16): Error: LaTeX Error: \begin{document} ended by \end{figure}. mini.tex(16): Error: Extra \endgroup. A minimal non-working example looks like this (put your pdf figure): mini.tex \documentclass[12pt,a4paper,twoside,openright]{report} % %==== \usepackage{graphicx} \usepackage{killer} \usepackage{color}%this works if this line is commented %==== \begin{document} \begin{figure}[H] \centering\includegraphics[width=1\columnwidth]{your.pdf} \caption[]{Schematic representation} \label{fig:yourFig} \end{figure} \end{document} Why is this incompatible with color. I was expecting a lot, but not that. (MikTex 2.9 on Win7 64, SP1) A: The problem seems very similar to the one in Problems with TikZ when I change document class The solution given there should work also for your setting: \documentclass[12pt,a4paper,twoside,openright]{report} % %==== \usepackage{graphicx} % save a copy of \@xfloat \makeatletter\let\latex@xfloat\@xfloat\makeatother \usepackage{killer} % redefine \@xfloat to have the intended behavior \usepackage{etoolbox} \makeatletter \let\@xfloat\latex@xfloat \apptocmd{\@xfloat}{\linespread{1}\normalsize}{}{} \makeatother \usepackage{color}%this works if this line is commented %==== \begin{document} \begin{figure} \centering\includegraphics[width=1\columnwidth]{your.pdf} \caption[]{Schematic representation} \label{fig:yourFig} \end{figure} \end{document} (Don't use [H], you'll regret it if you do.) If the bad code is in the class (I'll call it killer), then do % save a copy of \@xfloat \makeatletter\let\latex@xfloat\@xfloat\makeatother \documentclass{killer} \usepackage{graphicx} % redefine \@xfloat to have the intended behavior \usepackage{etoolbox} \makeatletter \let\@xfloat\latex@xfloat \apptocmd{\@xfloat}{\linespread{1}\normalsize}{}{} \makeatother \usepackage{color}%this works if this line is commented \begin{document} \begin{figure} \centering\includegraphics[width=1\columnwidth]{your.pdf} \caption[]{Schematic representation} \label{fig:yourFig} \end{figure} \end{document}