text
stringlengths
64
89.7k
meta
dict
Q: SQL Loader- data not uploaded to the table. All went to .bad I tried to upload some records into my table ABC. None of the records went through and they all showed up in the .bad log. I am pretty new to sqlldr. Not quite sure where did I messed up. Let me show you the steps I took. First, I created an empty table called ABC. create table abc ( location_id varchar2(10), sold_month date, item_name varchar2(30), company_id varchar2(10), qty_sold number(10), total_revenue number(14,3), promotional_code varchar2(10) ); Here is my flat file abcflat.dat. The columns correspond to the columns in the table above. "1000","02/01/1957","Washing Machine","200011","10","10000","ABCDE" "1000","05/02/2013","Computer","200012","5","5000","ABCDE" "1000","05/01/2013","Bolt","200010","100","500","ABCDE" "1000","05/03/2013","Coca Cola","200011","1000","1000","ABCDE" Here is my control file abc.ctl LOAD DATA INFILE 'C:\Users\Public\abcflat.dat' INTO TABLE ABC FIELDS TERMINATED BY "," enclosed by '"' ( Location_ID , Sold_month , item_name , Company_id , QTY_Sold , Total_revenue , Promotional_Code ) And my last step sqlldr hr/open@xe control=c:\users\public\abc.ctl It says Commit point reached - logical record count 3 Commit point reached - logical record count 4 but none of the record showed up on my ABC table. Thank You A: It's most probably the date format, try this: LOAD DATA INFILE 'C:\Users\Public\abcflat.dat' INTO TABLE ABC FIELDS TERMINATED BY "," enclosed by '"' ( Location_ID , Sold_month DATE "DD/MM/YYYY" , item_name , Company_id , QTY_Sold , Total_revenue , Promotional_Code )
{ "pile_set_name": "StackExchange" }
Q: installed django-cors-headers still cross origin images error occuring cors-header using pip on Django 2.0.6 . Still same origin error is occuring. I installed a chrome extension Allow-Controll-Allow-Origin:* when I enable all things are fine. My setting files are MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ) still in browser I am getting Failed to load https://s3.amazonaws.com/django/Events/Test1/1.jpg: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8002' is therefore not allowed access. And this 19:367 Uncaught Error: InvalidStateError: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'arraybuffer'). at XMLHttpRequest.xhr.onreadystatechange (19:328) **Full settings.py** """ Django settings for demo project. Generated by 'django-admin startproject' using Django 1.11. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os from os.path import dirname, abspath, join, normpath # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '<key>' import ssl # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cruds_adminlte', 'testapp', 'django_ajax', # 'storages', 'django_dropbox', 'django_select2', 'corsheaders' ] AWS_S3_ACCESS_KEY_ID = '<access key>' # enter your access key id AWS_S3_SECRET_ACCESS_KEY = '<key>' # enter your secret access key AWS_STORAGE_BUCKET_NAME = 'ais-django' AWS_ACCESS_KEY_ID = '<id>' AWS_SECRET_ACCESS_KEY = '<access key>' # DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' # AWS_S3_SECURE_URLS = False # use http instead of https # AWS_QUERYSTRING_AUTH = False # don't add complex authentication-related query parameters for requests # AWS_S3_ACCESS_KEY_ID = '<access key>' # enter your access key id # AWS_S3_SECRET_ACCESS_KEY = '<key>' # enter your secret access key # AWS_STORAGE_BUCKET_NAME = 'ais-django' # AWS_ACCESS_KEY_ID = '<key>' # AWS_SECRET_ACCESS_KEY = '<key>' # AWS_SECRET_ACCESS_KEY = '' # AWS_STORAGE_BUCKET_NAME = '' # AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME # AWS_S3_OBJECT_PARAMETERS = { # 'CacheControl': 'max-age=86400', # } # AWS_LOCATION = '/static/' # # STATICFILES_DIRS = [ # os.path.join(BASE_DIR, 'testapp/static/img'), # ] # STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) # # STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' # if hasattr(ssl, '_create_unverified_context'): # ssl._create_default_https_context = ssl._create_unverified_context MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ) ROOT_URLCONF = 'demo.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ normpath(join(dirname(dirname(abspath(__file__))), 'demo', 'templates')), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'demo.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # 'ENGINE': 'django.db.backends.postgresql_psycopg2', # 'NAME':'aisdb', # 'USER' : 'root', # 'PASSWORD':'admin123', # 'HOST':'localhost', # 'PORT':'', } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' # django-crispy-forms CRISPY_TEMPLATE_PACK = 'bootstrap3' # django-crispy-forms INTERNAL_IPS = ('127.0.0.1',) from easy_thumbnails.conf import Settings as thumbnail_settings THUMBNAIL_PROCESSORS = ( 'image_cropping.thumbnail_processors.crop_corners', ) + thumbnail_settings.THUMBNAIL_PROCESSORS IMAGE_CROPPING_JQUERY_URL = None LOGIN_REDIRECT_URL = '/login' TIME_FORMAT = 'h:i A' DATETIME_FORMAT = 'm/d/Y H:i:s' DATE_FORMAT = "m/d/Y" TIME_INPUT_FORMATS = ['%I:%M %p'] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') if not os.path.exists(MEDIA_ROOT): os.makedirs(MEDIA_ROOT) A: What is about ALLOWED_HOSTS = ['*'] ? This should solve your problem. Another reason could be that, you also have to set the CORS in your Amazon storage. One of these two things should work for you.
{ "pile_set_name": "StackExchange" }
Q: Haskell passing empty Character to a function I'm working in Haskell in two functions: Basically I want to get the character before matching a specific character in a given string This is my code: before :: Char -> [Char] -> Char before x str = trackelement x ' ' str trackelement :: Char -> Char -> [Char] -> Char trackelement x y (z:zs) | x == z = y | otherwise = trackelement x z (zs) My problem is when I try: before 'l' "luis" The answer is : ' ' (of course, before 'l' there is nothing), and I would like to be '' or Nothing I tried passing trackelement x '' str instead of trackelement x ' ' str but I have this error Syntax error on ''str Could you suggest me something? A: The answers shown already are good for getting your code to work, but they don't explain why you get the error you're receiving. The reason why that error was shown is that '' is not valid syntax, since there is no such thing as an "empty character". All characters have value, but Strings can be empty. Remember that type String = [Char], and it's very clear that there can be such a thing as an empty list, but characters always have a value. It's comparable to saying you can have an empty list of Ints, namely [], but you can't have an "empty int", whatever that would mean. A: You can use a Maybe: before :: Char -> [Char] -> Maybe Char before x str = initialise x str initialise x (y:xs) | x == y = Nothing | otherwise = trackelement x y xs trackelement :: Char -> Char -> [Char] -> Maybe Char trackelement x y [] = Nothing trackelement x y (z:zs) | x == z = Just y | otherwise = trackelement x z zs To take care of the corner case before 'l' "luis", we have to add a new initialiser function. It basically checks if the first character matches the searched one. If it does, we return Nothing, because we checked the first character which obviously does not have a preceding one. Else we just call trackelement and use it's result. As Zeta mentioned, you can combine the functions, which simplifies everything and takes care of the corner case you are currently experiencing. before _ [x] = Nothing before a (x:y:xs) | a == y = Just x | otherwise = before a (y:xs) Just using this function, you noticed you have problems when encountering a word containing more than one letter which is also searched for (before 'a' "amalia" -> Just 'm'). Currently the best solution I know of is again splitting this up into more than one function, which brings us back to the solution at the top. A: Match the first two elements instead just head and tail. That way you don't even need trackelement: before :: Eq a => a -> [a] -> Maybe a before x (a:b:rest) | a == x = Nothing | b == x = Just a | otherwise = before x (b:rest) before _ _ = Nothing
{ "pile_set_name": "StackExchange" }
Q: Twisted server-client data sharing I slightly modified a server-client Twisted program on this site, which provided a program that could act as a server and a client (http://stackoverflow.com/questions/3275004/how-to-write-a-twisted-server-that-is-also-a-client). I am able to connect the server-client to an external client on one side and an external server on the other. I want to transfer data from the external client to the external server via the server-client program. The problem I am having is getting the line received in the ServerProtocol class (in the server-client program) into the ClientProtocol class (in the server-client program). I have tried a number of ways of doing this, including trying to use the factory reference, as you can see from the def init but I cannot get it to work. (at the moment I am just sending literals back and forth to the external server and client) Here is the server-client code: from twisted.internet import protocol, reactor from twisted.protocols import basic class ServerProtocol(basic.LineReceiver): def lineReceived(self, line): print "line recveived on server-client",line self.sendLine("Back at you from server-client") factory = protocol.ClientFactory() factory.protocol = ClientProtocol reactor.connectTCP('localhost', 1234, factory) class ClientProtocol(basic.LineReceiver): def __init__(self, factory): self.factory = factory def connectionMade(self): self.sendLine("Hello from server-client!") #self.transport.loseConnection() def lineReceived(self, line): print "line recveived on server-client1.py",line #self.transport.loseConnection() def main(): import sys from twisted.python import log log.startLogging(sys.stdout) factory = protocol.ServerFactory() factory.protocol = ServerProtocol reactor.listenTCP(4321, factory) reactor.run() if __name__ == '__main__': main() I should mention that I am able to connect to the server-client program with the external server and external client on ports 4321 and 1234 respectively and they just echo back. Also, I have not shown my many attempts to use the self.factory reference. Any advice or suggestions will be much appreciated. A: This question is very similar to a popular one from the Twisted FAQ: How do I make input on one connection result in output on another? It doesn't make any significant difference that the FAQ item is talking about many client connections to one server, as opposed to your question about one incoming client connection and one outgoing client connection. The way you share data between different connections is the same. The essential take-away from that FAQ item is that basically anything you want to do involves a method call of some sort, and method calls in Twisted are the same as method calls in any other Python program. All you need is to have a reference to the right object to call the method on. So, for example, adapting your code: from twisted.internet import protocol, reactor from twisted.protocols import basic class ServerProtocol(basic.LineReceiver): def lineReceived(self, line): self._received = line factory = protocol.ClientFactory() factory.protocol = ClientProtocol factory.originator = self reactor.connectTCP('localhost', 1234, factory) def forwardLine(self, recipient): recipient.sendLine(self._received) class ClientProtocol(basic.LineReceiver): def connectionMade(self): self.factory.originator.forwardLine(self) self.transport.loseConnection() def main(): import sys from twisted.python import log log.startLogging(sys.stdout) factory = protocol.ServerFactory() factory.protocol = ServerProtocol reactor.listenTCP(4321, factory) reactor.run() if __name__ == '__main__': main() Notice how: I got rid of the __init__ method on ClientProtocol. ClientFactory calls its protocol with no arguments. An __init__ that requires an argument will result in a TypeError being raised. Additionally, ClientFactory already sets itself as the factory attribute of protocols it creates. I gave ClientProtocol a reference to the ServerProtocol instance by setting the ServerProtocol instance as the originator attribute on the client factory. Since the ClientProtocol instance has a reference to the ClientFactory instance, that means it has a reference to the ServerProtocol instance. I added the forwardLine method which ClientProtocol can use to direct ServerProtocol to do whatever your application logic is, once the ClientProtocol connection is established. Notice that because of the previous point, ClientProtocol has no problem calling this method.
{ "pile_set_name": "StackExchange" }
Q: desktopCapture in Chrome - cancelChooseDesktopMedia results in Crash I'm playing around with Screensharing in Webrtc and ran into the following issue: I want to hide the media picker dialog (see below) when clicking a button (screenshot Cancel text). According to the documentation: cancelChooseDesktopMedia(integer desktopMediaRequestId) Hides (the) desktop media picker dialog shown by chooseDesktopMedia(). Id returned by chooseDesktopMedia() sounds exactly like what I want in my background.js (I'm writing an extension to avoid setting the allow capture flag in chrome://flags by hand) I get the desktopMediaRequestId like this: var desktopMediaRequestId = ''; desktopMediaRequestId = chrome.desktopCapture.chooseDesktopMedia(data_sources, port.sender.tab, function(streamId){ ... }); and call cancelChooseDesktopMedia it like that: if (desktopMediaRequestId) chrome.desktopCapture.cancelChooseDesktopMedia(desktopMediaRequestId); However, Chrome (Version 34.0.1847.131) and Canary (Version 36.0.1964.2 canary) freeze and crash with the Dialog still open after cancelChooseDesktopMedia is called. I posted the most relevant stuff for now. Just scream and I will provide more information :). Thanks A: There are open chrome bugs about crashing or the desktop picker simply not closing on macs
{ "pile_set_name": "StackExchange" }
Q: How do I make one word in a text box end a program? So one of the forms I have to create is where you enter a first and last name and then it splits the two names and puts them next to the appropriate labels, form design: https://gyazo.com/9b34dca0c1cd464fd865830390fcb743 but when the word stop is entered in any way e.g. Stop, StOp, sToP etc. it needs to end. private void btnSeparate_Click(object sender, EventArgs e) { string strfullname, strgivenname, strfamilyname, strfirstname; int int_space_location_one, int_space_location_two; strfullname = txtFullName.Text; int_space_location_one = strfullname.IndexOf(" "); strgivenname = strfullname.Substring(0, int_space_location_one); lblGivenEntered.Text = strgivenname; strfirstname = strfullname.Remove(0, int_space_location_one + 1); int_space_location_two = strfirstname.IndexOf(" "); strfamilyname = strfirstname.Substring(int_space_location_two + 1); lblFamilyEntered.Text = strfamilyname; } This is my current code, I have tried many different ways to get the word stop to end it but it wont work so that's why there is currently no code trying to stop the program, the main problem I get is because it is searching for a space between the first and last name and it obviously doesn't have one for one word it just crashes. Any help with this would be amazing, thanks in advance. A: Just hook up the TextChanged event and go like this: private void TextChanged(Object sender, EventArgs e) { // If text, converted to lower-characters contains "stop" -> Exit if(txtFullName.Text.ToLower().Contains("stop")) { // What I understand as "stopping it". Application.Exit(); } } IF with "stop it" you mean to cancle the operation: private void btnSeparate_Click(object sender, EventArgs e) { // If text, converted to lower-characters contains "stop" -> Exit if (txtFullName.Text.ToLower().Contains("stop")) { // What I understand as "stopping it". Application.Exit(); } else { // Your code inside the else block } } Short version of everything: Also covering no spaces problem private void btnSeparate_Click(object sender, EventArgs e) { // Save how many words are inside int wordsInText = txtFullName.Text.Split(' ').Length; // Save if "stop" was typed into the textbox bool stopExisting = !txtFullName.Text.ToLower().Contains("stop"); // If text has exactly 3 words and "stop" is NOT existing if (wordsInText == 3 && !stopExisting) { // Save array of splitted parts string[] nameParts = txtFullName.Text.Split(' '); // This is never used?? string strfirstname = nameParts[1]; // Set name-parts to labels lblGivenEntered.Text = nameParts[0]; lblFamilyEntered.Text = nameParts[2]; } // If text has NOT exactly 3 words and "stop" is NOT existing else if(wordsInText != 3 && !stopExisting) { // If there are no 3 words, handle it here - MessageBox? } // If "stop" IS existing else if(stopExisting) { // If text contains "stop" handle it here // Application.Exit(); <-- if you really want to exit } }
{ "pile_set_name": "StackExchange" }
Q: How to subtract one year from DateTime I want a button in windows forms application(C#) to display a exactly 1 year past time date and hour("specially hour")... Example: if the date time now is 20 Aug 2013 2:15 pm so when I click on the button, it will show me 20 Aug 2012 2:15 pm... and opposite in 2nd button i.e from previous to current date time hour Code I am using is just for yesterdays date string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd"); A: DateTime.Today.AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss")
{ "pile_set_name": "StackExchange" }
Q: Create ActiveX.exe using .Net 4 and VS2010 My application is vb6 application which refer to delphi active.exe file. I need to replace this file with C# one. How can I create activeX exe with VS 2010 and C#? (needless to say I cannot work with files other then activeX exe) A: There is a tutorial by Microsoft about migrating VB6 ActiveX EXEs to .NET. It specifically states: the Visual Basic 2005 upgrade wizard does not support upgrading Visual Basic 6 ActiveX EXEs Therefore the Microsoft tools, at least, do not support producing an ActiveX EXE from .NET based on original VB6 code. (That does not mean that another route might not be possible.) An alternative approach could be to convert it to a regular .NET COM Interop DLL which is a lot easier, but you may require it to run out-of-process which a DLL cannot do.
{ "pile_set_name": "StackExchange" }
Q: Arduino and ball position I'm looking for some way to detect a position of the ball on 2D surface. On this video it's doing by web-camera, but is there any other way to detect ball position? http://youtu.be/0DqcnHE6r9M A: You can detect the positions of things in numerous ways on a 2D surface. Generally this is done using a camera, as it is very easy to detect the position of objects in an image. Although the other ways of doing it are very diverse and creative, and I cannot possibly list them all here, a couple that come to mind: You can use a laser range-finder to get a 2D distance measurement from some point in 180 degrees on the side of the 2D plane, which can be used to determine the position of the ball. You can use some sort of pressure sensor underneath the board - perhaps a sensitive grid of sensors - to get the approximate location.
{ "pile_set_name": "StackExchange" }
Q: Matching Regular Expression for URLS in JavaScript Produces null I have the following regular expression which I have validated: "(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?" I have the following Javascript code to find regular expressions: var cTextVal = "This URL should match http://google.com"; var regEx = "(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?" var matches = cTextVal.match(regEx); alert(matches); // This produces null How do I find the string that matches this regular expression in JavaScript? Update Based on Comments: This crashes my code: var regEx = /(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/g This produces null: var regEx = "/(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/g" A: Escape forward slashes before second capture group var regEx = /(http|ftp|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?/; var cTextVal = "This URL should match http://google.com"; var matches = cTextVal.match(regEx).shift(); console.log(matches);
{ "pile_set_name": "StackExchange" }
Q: What is that on Athena's chest? In this statue there is something what looks like a face on Athena's chest. I have seen it on some other statues of Athena. What is it? Is there a myth behind it? A: It's not clear from your picture, but the face is most probably a Gorgoneion, a recurring element of Athena's iconography: In Ancient Greece, the Gorgoneion (Greek: Γοργόνειον) was a special apotropaic amulet showing the Gorgon head, used most famously by the Olympian deities Athena and Zeus: both are said to have worn the gorgoneion as a protective pendant. It was assumed, among other godlike attributes, as a royal aegis to imply divine birth or protection, by rulers of the Hellenistic age, as shown, for instance, on the Alexander Mosaic and the Gonzaga Cameo. Source: Wikipedia contributors. (2018, June 16). Gorgoneion. In Wikipedia, The Free Encyclopedia. Retrieved 21:22, February 5, 2019, from https://en.wikipedia.org/w/index.php?title=Gorgoneion&oldid=846161112 The ever-so-helpful theoi.com has tons of information on the mythology of the Gorgons, if you wish to know more about them. We also happen to host some very interesting questions about Medusa and her sisters on this site.
{ "pile_set_name": "StackExchange" }
Q: How do i get good result useing foreach in row result output In mysqli database i have mobi2, mobi7,run2,run3 as item_name with book 1905515 for all example id | book | item_name 1 | 1905515 | mobi2 2 | 1905515 | mobi7 3 | 1905515 | run2 4 | 1905515 | run3 my problem is how do i get each item_name in one loop useing foreach statement i have tried: require("init.php"); $result = mysqli_query($conn, "SELECT item_name FROM books WHERE book = 1905515"); while($row = mysqli_fetch_array($result)) { foreach($row as $each); $display=$each["item_name"]; echo ', '$display; } i get m,m,r,r as result instead of mobi2,mobi7,run2,run3 thanks your time and impact in my solutions A: You alredy do foreach inside while and use mysqli_fetch_assoc for correct keys: require("init.php"); $result=mysqli_query($conn, "SELECT `item_name` FROM `books` WHERE `book`='1905515'"); while($row=mysqli_fetch_assoc($result)){ $display=$row["item_name"]; echo ', '$display; }
{ "pile_set_name": "StackExchange" }
Q: Are Doflamingo's Fakes waterproof? What would happen if Doflamingo's Fakes touches water? Are they proofed against water? In the Chapter 752, Doflamingo appears as a "Fake" Doflamingo Would Doflamingo lose his power? Would the fake Doflamingo lose his power or is he immune against water? A: At least for Paramacia the sea only affects the user and not the effects of the fruit. Example: Luffy's neck was still stretchable after being submerged in water during the Arlong Arc, while Luffy himself was not able to move. Vander Decken IX's tracking ability worked even while it went underwater, as well as Whitebeard's earthquake fruit got transmuted through the sea to the ocean floor. So as long as Doflamingo's not in the water himself his powers or extension thereof shouldnt be affected. @Rajven What is the basis for this? His clone could have ended due to the attack it sustained from the other revolters.
{ "pile_set_name": "StackExchange" }
Q: Clearing RAM tables of eosio.token contract What I am trying to do is clear the RAM table completely. This question is not a duplicate since it is asking for a full and a working solution. The contract that I was executing filling the RAM table (method = transfer) is: https://github.com/EOSIO/eos/blob/master/contracts/eosio.token/eosio.token.cpp Abi is the same as in the eosio.token directory. RAM table was filled sending a generated token. What I am trying to accomplish is something that would work like this, repeated as many times as needed to clear the whole RAM tables (accounts and currency_stats): for(auto itr = _ramTable.begin(); itr != _ramTable.end() && count!=100;) { // delete element and update iterator reference itr = _ramTable.erase(itr); count++; } The lack of knowledge I have concerns not knowing what to put into hpp file, or how to declare _ramTable. I can cut/paste the snippets of other code, but then I frequently run into errors that usually don't happen with Java's syntax. Please provide the full code (meaning, cpp, hpp and abi) that works. A: UPDATE: Updated the code to compile with eosio.cdt version 1.6.1. I finally got it working nicely! Parsing the token symbol in the action parameters was especially complicated. The other solution posted has a couple of issues that will prevent you from clearing all the RAM properly: It doesn't delete the stat table, leaving there some info about the created token using up some memory. You're supposed to hand it an arbitrary amount in the action parameters, which has to match the same exact decimal precision used when creating the token, instead of just specifying the symbol of the token you want to delete. My final solution is thoroughly tested by creating and issuing various tokens using the standard eosio.token contract, then replacing it by this one, and using the new actions to destroy the database records. I checked every step by inspecting the tables associated to the contract account using cleos get table <CONTRACT_ACCOUNT> <TOKEN_NAME> stat and cleos get table <CONTRACT_ACCOUNT> <AIRDROPPED_ACCOUNT> accounts and everything was neatly cleared at the end. You will need the list of accounts that you airdropped to, but you won't need the exact amounts that they are currently holding. The code goes like this: token_ram_recovery.cpp #include <eosio/asset.hpp> #include <eosio/eosio.hpp> #include <string> using namespace eosio; using std::string; class[[eosio::contract]] token : public contract { private: struct [[eosio::table]] account { asset balance; uint64_t primary_key() const { return balance.symbol.code().raw(); } }; struct [[eosio::table]] currency_stats { asset supply; asset max_supply; name issuer; uint64_t primary_key() const { return supply.symbol.code().raw(); } }; typedef eosio::multi_index<name("accounts"), account> accounts; typedef eosio::multi_index<name("stat"), currency_stats> stats; public: using contract::contract; [[eosio::action]] void destroytoken(string symbol) { require_auth(_self); symbol_code sym(symbol); stats stats_table(_self, sym.raw()); auto existing = stats_table.find(sym.raw()); check(existing != stats_table.end(), "Token with symbol does not exist"); stats_table.erase(existing); }; [[eosio::action]] void destroyacc(string symbol, name account) { require_auth(_self); symbol_code sym(symbol); accounts accounts_table(_self, account.value); const auto &row = accounts_table.get(sym.raw(), "No balance object found for provided account and symbol"); accounts_table.erase(row); }; }; EOSIO_DISPATCH(token, (destroytoken)(destroyacc)) The code is well annotated so you can generate the .abi automatically when compiling the code using eosio-cpp -abigen -contract token token_ram_recovery.cpp -o token_ram_recovery.wasm. Then just deploy this new contract to the same account that had the previous one, and proceed with the deletion of the token and the accounts: Destroy the token from the stat table: cleos push action <CONTRACT_ACCOUNT> destroytoken '["<TOKEN_SYMBOL>"]' -p <CONTRACT_ACCOUNT>@active Destroy each account that holds any of the token: cleos push action <CONTRACT_ACCOUNT> destroyacc '["<TOKEN_SYMBOL>", "<AIRDROPPED_ACCOUNT>"]' -p <CONTRACT_ACCOUNT>@active Let me know if you need any more assistance. I hope everything goes well!
{ "pile_set_name": "StackExchange" }
Q: How to set a folder destination for a zip-file on python? I'm using zipfile to compress a folder that contains different files. It works well. My only problem is that it creates the zipped file into the root folder where I'm executing the code. How can I tell the folder destination where I want the zipped file? My code example is this one: # Zips an entire directory using zipfile ---------------------------- def make_zipfile(_path): import zipfile if os.path.isdir(_path): inName = os.path.basename(_path) + '.zip' #head, tail = os.path.split(os.path.split(_path)[0]) print "saving: " + inName def zipdir(_path, zip_handle): for root, dirs, files in os.walk(_path): for file in files: print os.path.join(root, file) zip_handle.write(os.path.join(root, file), file) with zipfile.ZipFile(inName, 'w', compression=zipfile.ZIP_DEFLATED, allowZip64=True) as z: zipdir(_path, z) print "zip file created" return inName A: Use a complete path in inName: inName = os.path.join('/tmp', os.path.basename(_path) + '.zip')
{ "pile_set_name": "StackExchange" }
Q: Equivalent of .Net Data Repeater in Cocoa I'm a total noob to Xcode and Interface builder. I'm on version 3.2.3 and OSX 10.6.4. What I'd like to know, and haven't been able to find out, is how to display a list of n items. Using .Net, I'd probably use a Data Repeater control and then use that to repeatedly populate the controls I'd like to display. Is there an equivalent or am I going about things in the wrong way? I don't see anything in the IB controls library that is quite what I'm looking for. Any help is much appreciated, even a direction to a relevant tutorial or something. Regards, Iain A: I guess you are looking for NSTableView with it's DataSource (ArrayController or equivalent) and it's delegate (for defining N items)?
{ "pile_set_name": "StackExchange" }
Q: Using Geofence with google api v2 in android I am trying to create the Geofence in google location api-V2 But class LocationClient is not found in the latest version of google location library. Is there any way to use Geofence with google api-V2 A: Can't you just use the GeoFence api? https://developer.android.com/reference/com/google/android/gms/location/Geofence.html, https://developer.android.com/reference/com/google/android/gms/location/GeofencingApi.html Otherwise here's a thread on the deprecation of LocationClient: Android LocationClient class is deprecated but used in documentation
{ "pile_set_name": "StackExchange" }
Q: How to link to forked package in distutils, without breaking pip freeze? Preface The official python package python-openid (as distributed through pypi.org) does not work with Google Apps. Somebody wrote a fix to this and uploaded the patched source to github. Now I want to create a package which should link to this forked package. Now when installing this package, everything is well. The forked package is installed and everything is fine. However, when doing a pip freeze, there is no mentioning of where the package came from. As the forked package should be used, including the official package breaks deployments. How can I link to a forked package in my own package and also list the forked package in pip freeze? Update Ok, so I created the tag 2.2.5-bouke0, created a distribution and uploaded it to github. My setup.py of the referencing package now looks like this: dependency_links=[ 'http://github.com/Bouke/python-openid/downloads', ], install_requires=[ 'python-openid == 2.2.5-bouke0', ], When building and installing this package everything is fine. The referenced package is downloaded from github and installed correctly. However, pip freeze does not show where the package came from: django-federated-login==0.1.3 python-openid==2.2.5-bouke0 As the version 2.2.5-bouke0 cannot be found on pypi, the deployment of such a requirements.txt will fail. How can I instruct pip freeze to reference the alternative source from where to get the package? A: Make a tag 2.2.5 in the repository. Put -f https://github.com/adieu/python-openid/downloads into the requirements.txt file. To be sure, change version number to something like 2.2.5-bouke1. Read semver.org for details.
{ "pile_set_name": "StackExchange" }
Q: Sobolev Space basic calculation I'm new to Sobolev Space I'm not quite understanding the following: Proposition: If $s$ and $s' \in \mathbb{R}, s < s'$ then we have $H^{s'}(\mathbb{R}^{n}) \subset H^{s}(\mathbb{R}^{n})$ where the inclusion is strict and where we denote the Sobolev space of order $s$ on $\mathbb{R}^{n}$ by $$ H^{s}(\mathbb{R}^{n}):= \{u \in \mathcal{S}'(\mathbb{R}^{n}): (1+|\xi|^{2})^{\frac{s}{2}}\hat{u} \in L^{2}(\mathbb{R}^{n})\}$$ To show the inclusion is strict we use consider $u \in \mathcal{S}'(\mathbb{R}^{n})$ such that $ \hat{u}(\xi) = <\xi>^{-s-\frac{n}{2}- \epsilon}, \epsilon \in (0, s'-s)$ where $ <\xi>:=(1+|\xi|^{2})^{\frac{1}{2}}$ I don't understand how applying the above we obtain the following $$ <\xi>^{s}\hat{u} \in L^{2}, <\xi>^{s'}\hat{u} \notin L^{2}$$ A: With this choice of $u$ you have: $$\langle \xi \rangle^t \hat{u}= \langle \xi\rangle^{t-s-\frac{n}{2}-\epsilon}$$ so as by definition $\langle \xi\rangle^2=(1+|\xi|^2)$: $$\int_{\mathbb{R}^d}|\langle \xi \rangle^t \hat{u}(\xi)|^2 d \xi=\int_{\mathbb{R}^d}(1+|\xi|^2)^{t-s-\frac{n}{2}-\epsilon} d\xi$$ using polar coordinate, with $C_n$ the surface of the unit ball of dimension $n$ you obtain: $$\int_{r \in (0,+\infty)}(1+r^2)^{t-s-\frac{n}{2}-\epsilon} C_n r^{n-1}dr$$ as the integrand is continuous in $[0,+\infty)$ and: $$(1+r^2)^{t-s-\frac{n}{2}-\epsilon} r^{n-1} \sim_{r \to \infty} r^{2(t-s)-n-2\epsilon+n-1}=r^{2(t-s)-2\epsilon-1}$$ we obtain: if $2(t-s)-2\epsilon-1<-1$ then integral is finite if $2(t-s)-2\epsilon-1\geq-1$ then integral is infinite and in your case: $2(s-s)-2\epsilon-1<-1$ $2(s'-s)-2\epsilon-1=2((s'-s)-\epsilon)-1 <-1$
{ "pile_set_name": "StackExchange" }
Q: Who does what in a Single Page Application? My development background is in ASP .NET webforms. I've been reading various SPA tutorials but they always get into the weeds about specific javascript libraries. I'm just trying to understand what happens in an SPA with a .NET middle tier. Specifically: Does the domain model exist both in .NET and javascript? Is the javascript model more of a view model than a complete domain model? Does this eliminate the need for views in the context of ASP MVC? ie. Does making an SPA basically turn ASP MVC into ASP MC? Does the .NET layer only send data (JSON/XML) to the client? No markup? Does all the ASP MVC routing configuration become largely irrelevant? Is all the routing handled client side? A: So, I'm more experienced in PHP and Python but my answers should be valid for ASP .NET too, seen that your questions are more about the MVC structure rather than the language / framework itself. First of all, the choice of the javascript library may be crucial to answer your questions. For instance, if you choose the full MeteorJS stack (where models are shared between the server and the client) or just a front-end library like Angular or React (or a combination of both). Does the domain model exist both in .NET and javascript? It might: depends on the library. The data is normally received as a JSON object via an XMLHttp call (or websocket, for a Meteor App) or directly accessed from the local storage. Implementing a model could be useful to keep your code clean (in Typescript you could use an interface) but for handling CRUD operations it really depends on the JS library of your choice. Is the javascript model more of a view model than a complete domain model? In a SPA you normally have Controllers (or "components", or "directives"), not view models. Again, it really depends on the JS framework / library. In the latest Angular 2.0 iteration the component is both a view and a controller. For more infos: https://www.youtube.com/watch?v=g9GgByAy80s Does this eliminate the need for views in the context of ASP MVC? ie. Does making an SPA basically turn ASP MVC into ASP MC? Yes, if you plan to use ASP as a RESTful API endpoint you still need controllers for routing and Models for CRUD: ideally, the "View" is just a JSON document. Does the .NET layer only send data (JSON/XML) to the client? Yes, but it should also be able to handle requests for CRUD operations (GET, POST, UPDATE, DELETE for REST, others for the DDP protocol) No markup? What kind of markup do you want to send? Does all the ASP MVC routing configuration become largely irrelevant? Is all the routing handled client side? As stated before, you'll still need routing to handle REST / DDP business logic. Everything else (like URL routing that the user can interact with in the browser bar) is managed by the SPA (and of course, the usage varies depending on your library choice)
{ "pile_set_name": "StackExchange" }
Q: JPos - ISO8583 Messages TLV Fields I'm constructing a simple e-purchase financial message using jpos library, i'm using a generic packager to pack my message fields, the problem occurs at field 48 which is a TLV Field. here are the packaging parameters for field 48. <isofieldpackager id="48" name="Additional Private Data" length="999" class="org.jpos.iso.IFB_LLLBINARY" emitBitmap="false" tagMapper="org.jpos.iso.packager.TTTDecimalTagMapper" packager="org.jpos.iso.packager.GenericTaggedFieldsPackager"> <!-- --> <isofield id="1" length="8" name="PSP Identifier" class="ma.XXY.net.merkit.utils.IFA_TTLLBINARY2"/> <!-- --> <isofield id="2" length="8" name="Ecommerce Acquirer Identifier" class="ma.XXY.net.merkit.utils.IFA_TTLLBINARY2"/> <!-- --> <isofield id="3" length="3" name="Buyer Country Code" class="ma.XXY.net.merkit.utils.IFA_TTLLBINARY2" /> <!-- --> <isofield id="4" length="20" name="Buyer Card Brand" class="ma.XXY.net.merkit.utils.IFA_TTLLBINARY2" /> <!-- --> <isofield id="5" length="24" name="Buyer IP Address" class="ma.XXY.net.merkit.utils.IFA_TTLLBINARY2" /> <!-- --> <isofield id="6" length="30" name="Buyer email Address" class="ma.XXY.net.merkit.utils.IFA_TTLLBINARY2" /> <!-- --> <isofield id="7" length="14" name="Buyer Phone Number" class="ma.XXY.net.merkit.utils.IFA_TTLLBINARY2" /> <isofield id="8" length="6" name="Merchant Operation Reference" class="org.jpos.iso.IF_CHAR" /> <isofield id="9" length="3" name="One Click Indicator" class="org.jpos.iso.IF_CHAR"/> <isofield id="10" length="12" name="ISC INTERNET PIN" class="org.jpos.iso.IF_CHAR"/> <isofield id="11" length="3" name="One Click Indicator" class="org.jpos.iso.IF_CHAR"/> <isofield id="12" length="12" name="ISC INTERNET PIN" class="org.jpos.iso.IF_CHAR"/> <!-- --> <isofield id="13" length="12" name="One Click Indicator" class="ma.XXY.net.merkit.utils.IFA_TTLLBINARY2"/> <!-- --> <isofield id="14" length="1" name="ISC INTERNET PIN" class="ma.XXY.net.merkit.utils.IFA_TTLLBINARY2"/> </isofieldpackager> IFA_TTLLBINARY2.java public class IFA_TTLLBINARY2 extends ISOTagBinaryFieldPackager { public IFA_TTLLBINARY2() { super(0,null, BcdPrefixer.LLL, NullPadder.INSTANCE, LiteralBinaryInterpreter.INSTANCE, BcdPrefixer.LL); } public IFA_TTLLBINARY2 (int len, String description) { super(len, description, BcdPrefixer.LLL, NullPadder.INSTANCE, LiteralBinaryInterpreter.INSTANCE, BcdPrefixer.LL); } } main.java ISOMsg authISOMsg = new ISOMsg(); ISOMsg authISOMsgResp; QMUX qMux; IServicesUtils service = new ServiceUtilsImpl(); logger.info("Initiating Authorization Request for Simple ePurchase Transaction : 11001122222"); // To be used in header String stan = service.generateSTAN(); // HEADER String acquirerTimeOut = service .getValuesFromPropertiesFile(new String[] { IConstants.ACQUIRER_MSG_TIMEOUT }, "parameters.properties") .get(IConstants.ACQUIRER_MSG_TIMEOUT).toString(); String issuerTimeOut = service .getValuesFromPropertiesFile(new String[] { IConstants.ISSUER_MSG_TIMEOUT }, "parameters.properties") .get(IConstants.ISSUER_MSG_TIMEOUT).toString(); authISOMsg.setHeader(("001" + issuerTimeOut + DateUtils.getHeaderFieldIso(new Date(), stan)).getBytes()); try { // MTI authISOMsg.setMTI(IsoConstants.ISO_AUTH_REQUEST_MSG_MTI); authISOMsg.set(14, "0819"); // Merchant Type - not existing in mpi response authISOMsg.set(18, "3306"); // POS Entry Mode authISOMsg.set(22, IsoConstants.ISO_AUTH_REQUEST_POS_ENTRY_MODE); // POS Condition code authISOMsg.set(25,IsoConstants.ISO_AUTH_REQUEST_POS_CONDITION_CODE); // Card Acceptor Terminal Identification authISOMsg.set(41,"BX023350"); // Merchant ID authISOMsg.set(42, service.reduceMerchantIDLength("*****")); // authISOMsg.set("48.1","PSP_001"); authISOMsg.set("48.2","ACQ_002"); authISOMsg.set("48.3","MAR"); authISOMsg.set("48.4","VISA INTERNATIONAL"); authISOMsg.set("48.5","10.0.0.136"); authISOMsg.set("48.6","*****"); authISOMsg.set("48.7","******"); // Currency authISOMsg.set(49,"840"); Q2 scanner = new Q2(); scanner.start(); qMux = (QMUX) QMUX.getMUX("clientmux"); authISOMsgResp = qMux.request(authISOMsg, Integer.parseInt(acquirerTimeOut)); if (authISOMsgResp != null) { System.out.println(authISOMsgResp.getString(2)); } The main code above represents a Financial msg containing some fields, the problem that i have occurs at field 48. The error below throws the following exception. Nested:org.jpos.iso.ISOException: Error reading deploy\packager\basic-packager.xml (org.xml.sax.SAXParseException; systemId: file:basic-packager.xml; lineNumber: 114; columnNumber: 64; Attribute "tagMapper" must be declared for element type "isofieldpackager"). A: It seems you need to use the generic-subtag-packager.dtd to validate your xml packager definition. You can copy that file in the same directory as your xml and substitute the doctype definition for this one: <!DOCTYPE isopackager SYSTEM "generic-subtag-packager.dtd"> I Hope this solve your problem.
{ "pile_set_name": "StackExchange" }
Q: Activity Indicator not showing up I have two issues with activity indicator: 1. Activity Indicator not showing up on UIViewController I have activity indicator added in .xib file. On button click it should start animating. and when response from server is received, before going to next page it should stop animating. I am doing it as follows: activityIndicator.hidden = NO; [activityIndicator performSelector:@selector(startAnimating) withObject:nil afterDelay:0.1]; [self.view bringSubviewToFront:activityIndicator]; ....rest of code here.... activityIndicator.hidden = YES; [activityIndicator stopAnimating]; Activity Indicator not showing up on UITableView For table view I am doing it same way but on didselectrowatindexpath... For tableview I also tried adding activity view to cell accessory, but still not showing up In both cases activity Indicator is not showing up. Please help Thanks A: If all this code is in one method or in response to one event, then none of the changes to the views are going be visible until you return to the event loop. You set the activityIndicator.hidden to NO and then set it again to YES before the UI has an opportunity to even refresh. You also apparently stop the animation before you start it. What you need to do is make the activity indicator visible here and start its animation. Then schedule the work to be done (start an asynchronous network connection, or put some work into a queue, or whatever it is you need to get done) and return from this method so that the UI can refresh, the indicator can be drawn, and the animation can actually start. Then later at some point after the work is complete, you can hide the indicator and stop the animation. But you can't do all of that on the main thread within one single turn of the event loop. None of your changes will be visible because no drawing at all will happen here while this method is executing (assuming this is on the main thread) I hope that makes sense?
{ "pile_set_name": "StackExchange" }
Q: CSRF Protection with Firebase Email/Password Authentication I am working on deploying my Node.js app into production. We had been running into some CSRF issues but after looking deeper into the problem and learning more about CSRF attacks, I'm wondering if we even need to perform these checks. Our API is whitelisted from our CSRF checks so our mobile apps that rely on the API can run properly (we're working on securing that currently). On the web frontend, we allow our users to register/log in and create/edit their data. We use Firebase's email/password authentication system to perform authentication (https://firebase.google.com/docs/auth/web/password-auth). As I understand it, this means we don't have to worry about CSRF attacks on registering and logging in because Firebase handles that. My question is: if we make sure our users are authenticated with Firebase on each Post route in our app, does that mean we don't have to worry about CSRF attacks? A: CSRF becomes an issue when you are saving a session cookie. Firebase Auth currently persists the Auth State in web storage (localStorage/indexedDB) and are not transmitted along the requests. You are expected to run client side code to get the Firebase ID token and pass it along the request via header, or POST body, etc. On your backend, you would verify the ID token before serving restricted content or processing authenticated requests. This is why in its current form, CSRF is not a problem since Javascript is needed to get the ID token from local storage and local storage is single host origin making it not accessible from different origins. If you plan to save the ID token in a cookie or set your own session cookie after Firebase Authentication, you should then look into guarding against CSRF attacks.
{ "pile_set_name": "StackExchange" }
Q: Should I .gitignore Application/build/ folder in AndroidStudio? I know that I have to .gitignore the /build folder in project root. But there is also Application/build/ folder. Do i need to track it? Update: I see there is another similar question but more general. But I don't see anyone there talking about issue like I have. It looks like if you put slash at the end it makes the difference: build/ And it looks like nobody talks there about Application/build folder. This must be new project structure because some people use /builder and it works for them. That's because they don't have Application/builder folder. I think. A: A typical AndroidStudio gitignore file does include the gitignore rule build/ That would ignore any build folder, recursively from the top folder of the repository. Including Application/build.
{ "pile_set_name": "StackExchange" }
Q: Front-end registration form with password field I'm trying to create a front-end registration form for my Wordpress website. The registration form is in the header, so any plugins I've seen don't work as they use shortcodes. Look at my website for a better explanation. I want the registration form to work in the dropdown box at the top of the page. A: If you were to use a plugin that uses shortcode you can call it in your template by using this in your template: <?php echo do_shortcode ('[your-shortcode]'); ?> You can also do something similar to this form / code below for a front end login: <form method="post" action="<?php bloginfo('url') ?>/wp-login.php" class="wp-user-form"> <div class="username"> <label for="user_login"><?php _e('Username'); ?>: </label> <input type="text" name="log" value="<?php echo esc_attr(stripslashes($user_login)); ?>" size="20" id="user_login" tabindex="11" /> </div> <div class="password"> <label for="user_pass"><?php _e('Password'); ?>: </label> <input type="password" name="pwd" value="" size="20" id="user_pass" tabindex="12" /> </div> <div class="login_fields"> <div class="rememberme"> <label for="rememberme"> <input type="checkbox" name="rememberme" value="forever" checked="checked" id="rememberme" tabindex="13" /> Remember me </label> </div> <?php do_action('login_form'); ?> <input type="submit" name="user-submit" value="<?php _e('Login'); ?>" tabindex="14" class="user-submit" /> <input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>" /> <input type="hidden" name="user-cookie" value="1" /> </div> </form>
{ "pile_set_name": "StackExchange" }
Q: How to simulate keystrokes in a browser to control cross-domain iframe using javascript? I am particularly interested in simulating arrow keys. Although there are many ways to simulate keys, like in this Keydown Simulation in Chrome fires normally but not the correct key It doesnt work if it is on a iframe A: Imagine the following scenario. Bob is surfing the internet and goes to your site. Eve's site opens an iframe with content from http://bobsbank.com Eve's site stars injecting keystrokes and clicks to that site, sending all of Bob's money to Eve's account This sort of scenario is why what you're trying to do is impossible. The same origin policy will prevent it.
{ "pile_set_name": "StackExchange" }
Q: TFS2015 build agent cannot sync repository I am trying to set up build automation (it will be for CI in the future, but at the moment I'm queuing builds manually) on a TFS 2015 server, using the newer method, not the old XAML method. I have a build agent installed and registered (which seems to have gone okay), but every time I try and queue a build, it will fail when syncing the repository with the message "Unable to read data from the transport connection: The connection was closed." The user that the build agent service is running as has access to the TFS repository. As far as I know, there is no proxy between the build agent and the server. The server is within the same network as the build agent; it is not Team Services. The agent version is 1.83.2 What should I be looking for to fix this? The log is below: 2017-06-28T15:14:02.4032890Z Starting: Get sources 2017-06-28T15:14:02.4188890Z Entering TfvcSourceProvider.PrepareRepositoryAsync 2017-06-28T15:14:02.4188890Z localPath=C:\TFSBuildAgent\WorkFolder\ff694322\SCR 2017-06-28T15:14:02.4188890Z clean=False 2017-06-28T15:14:02.4188890Z sourceVersion=C13590 2017-06-28T15:14:02.4188890Z mappingJson={"mappings":[{"serverPath":"$/SCR","mappingType":"map"},{"serverPath":"$/SCR/Drops","mappingType":"cloak"}]} 2017-06-28T15:14:02.4188890Z Syncing repository: SCR (TFVC) 2017-06-28T15:14:02.4188890Z workspaceName=ws_ff694322_3 2017-06-28T15:14:03.5264910Z Workspace Name: ws_ff694322_3;Build\a2dd1d8a-5146-47c6-bda1-6f761cddeecd 2017-06-28T15:14:13.0113076Z ##[error]Unable to read data from the transport connection: The connection was closed. 2017-06-28T15:14:13.0425077Z ##[error]Unable to read data from the transport connection: The connection was closed. A: You could try below ways to narrow down the issue: Please check your TFS version, the agent version 1.83.2 is for TFS 2015 RTM. if your TFS is not 2015 RTM , suggest you update the agent to the specific version. Check the event viewer on the TFS server if there are some related error info. Try to set other accounts which can get the sources as the agent service account. Try to deploy a new agent to check this issue again. If you are using Window Server 2008R2, just try to apply the HotFix and try the workaround.
{ "pile_set_name": "StackExchange" }
Q: Are there examples of stone age cultures living in proximity close to iron age cultures without adapting to metal use? BACKGROUND I was reading about the technological diffusion of metallurgy, and started to wonder if there were good historical examples of stone age peoples living near to or having extensive contact with iron age or even early medieval cultures, but without either adapting to metal use or quickly being eradicated or absorbed. (In this case quickly might be 100-200 years.) In other words, I'm looking for examples of technological diffusion failing where intuitively one might think it would succeed. My hope is that I can find enough examples to do some reading and identify common themes. I'd prefer to focus on the Old World, unless there are a dearth of good examples there, as I'm much more interested in why cultures might develop differently in close proximity than to the reactions of Amerindian and Mesoamerican cultures to a foreign transplant. (Still, if someone with good knowledge of New World cultures thinks they have something to say here then I'm always happy to learn.) QUESTION Are there examples of stone age cultures that had lived close to or had contact with iron age or medieval cultures, but did not adapt to metal technology? EDIT: The current answer by LangLangC is excellent, but I'd like to gather a few more examples, so I'm offering this bounty to whoever can provide the most new ones. Thanks! A: If we look at sub-saharan Africa then the times for categorising these "ages" are a bit shifted and stretched compared with Asia, Europe and North-Africa. Metal-using Africa Farming societies in Africa developed after the origins and spread of livestock pastoralism throughout the continent. Likewise, the early use of metallurgy by farming communities was not developed independently in Africa until around 3000 BCE. Pockets of iron usage appeared in subsequent millennia but metal did not supplant stone in the south of the continent until around 500 BCE, when both iron and copper spread southwards through the continent, reaching the Cape around 200 CE. Although some details regarding the Bantu expansion are still controversial amongst archaeologists, linguists, and historians, the widespread use of iron does seem to have played a major role in the spread of Bantu farming communities throughout sub-Saharan Africa. Contact and interaction between hunter/gatherer, pastoralist, and incoming farming communities remains an important topic of interest in African archaeology today. One example that fits the question and might almost be described as still "living in that old way" are the San in South Africa. They didn't adapt to metallurgy and even rejected sedentary life: The San, the first people in South Africa: The ability of Later Stone Age hunter-gatherers to sustain themselves was seriously challenged at least three times in the past 2 000 years. Firstly, this occurred with the southward migration of the Khoikhoi herders into the western half of the country. Although they appear to have developed a symbiotic relationship with the hunter-gatherers, they converted individuals to herding, and therefore weakened hunter-gatherer social cohesion. Secondly, hunter-gatherers were challenged in the north and east of South Africa, as Iron Age farmers (Nguni and later Sotho nations) had settled in the summer rainfall regions within the last 1 800 years to grow crops and tend their stock. They also lived alongside hunter-gatherers, particularly in the Drakensberg region, and developed a working relationship with them. However, they became more and more powerful in terms of population size and land ownership. Finally, the death knell came with the arrival of European colonists whose commandos with guns and horses decimated the hunter-gatherers within two centuries. Some of this history is reflected in the rock art of the later Stone Age. Also in Africa you have the well studied and famous Hadza people: Since the 18th century, the Hadza have come into increasing contact with farming and herding people entering Hadzaland and its vicinity; the interactions often were hostile and caused population decline in the late 19th century. The first European contact and written accounts of the Hadza are from the late 19th century. Since then, there have been many attempts by successive colonial administrations, the independent Tanzanian government, and foreign missionaries to settle the Hadza, by introducing farming and Christianity. These efforts have largely failed, and many Hadza still pursue virtually the same way of life as their ancestors are described as having in early 20th-century accounts. In recent years, they have been under pressure from neighbouring groups encroaching on their land, and also have been affected by tourism and safari hunting. In Brazil there are perhaps a number of peoples fitting the search criteria. Although most of these are simply not really known to the Western mind. One tribe still living as hunter-gatherers with known contact, and rejecting it, are the Pirahã, description has that they even reject using stones: The Pirahã are supremely gifted in all the ways necessary to ensure their continued survival in the jungle: they know the usefulness and location of all important plants in their area; they understand the behavior of local animals and how to catch and avoid them; and they can walk into the jungle naked, with no tools or weapons, and walk out three days later with baskets of fruit, nuts, and small game.
{ "pile_set_name": "StackExchange" }
Q: What are the pros/cons of choosing between static and instance data access classes in a web app? I've read several other questions on this topic (here, here, and here), but have yet to see a great answer. I've developed my fair share of data access layers before and personally prefer to use instance classes instead of static classes. However, it is more of a personal preference (I like to test my business objects, and this approach makes mocking out the DAL easier). I have used static classes to access the database before, but I've always felt a little insecure in the appropriateness of such a design (especially in an ASP.NET environment). Can anyone provide some good pros/cons with regards to these two approaches to developing data access classes with ADO.NET providers (no ORM), in an ASP.NET application in particular. Feel free to chime in if you have some more general static vs. instance class tips as well. In particular, the issues I'm concerned about are: Threading & concurrency Scalability Performance Any other unknowns Thanks! A: Static based approaches really typically have one, and only one, main advantage: they're easy to implement. Instance based approaches win for: Threading and Concurrency - You don't need any/as much synchronization, so you get better throughput Scalability - Same issues as above Perf. - Same issues as above Testability - This is much easier to test, since mocking out an instance is easy, and testing static classes is troublesome Static approaches can win on: Memory - You only have one instance, so lower footprint Consistency/Sharing - It's easy to keep a single instance consistent with itself. In general, I feel that instance-based approaches are superior. This becomes more important if you're going to scale up beyond a single server, too, since the static approach will "break" as soon as you start instancing it on multiple machines... A: My general feeling is: Why instantiate if you don't have to? I use static classes when there wont be any use for multiple instances and there isn't a need for instance members. As for the DAL, the point is that there is only one. Why instantiate it if there is no value in it? Look at this link, which shows that static method calls are faster than instance class method calls. This link shows that an advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. This link shows that a static class can be used as a convenient container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields. For a DAL, this is exactly what you have. There is no reason to create any internal instance fields, and therefore, no reason to instantiate.
{ "pile_set_name": "StackExchange" }
Q: Custom code snippet type in Slack There is a possibility to post code snippets in many programming languages in Slack: We have a domain-specific language in our platform and it would be great to have a code snippet type in Slack with the custom code coloring scheme. Is there any possibility to achieve this? A: No, it is not possible to define a custom syntax highlighting scheme. You might be better off experimenting with the ones already defined to see whether they provide any accidental pleasant highlighting of your custom DSL.
{ "pile_set_name": "StackExchange" }
Q: UITapGestureRecognizer with couple of views I am using : UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleViewClicked:)]; [tmp addGestureRecognizer:gestureRecognizer]; [gestureRecognizer release]; to get notification when a view(bigview for our example) i clicked(I have a lot of view), and in the front there is a UIView (a blank one) the he is in the front of the view (there is a reason why this view is in the front before al the views). there is now a problem to get notification when tmp is tapped because the bigview is in the front. there is any solution for something like this? EDIT In the bigview i have UISwipeGestureRecognizer: UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeRight:)]; [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)]; [itemsView addGestureRecognizer:recognizer]; [recognizer release]; and if i make userInteractionEnabled in the bigview to NO he don't get notification on swipe A: Two options: A. Set userInteractionEnabled to NO on that big/blank view. B. Implement pointInside:withEvent: on that big/blank view - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event { // UIView will be "transparent" for touch events if we return NO return NO; } (as taken from allowing-interaction-with-a-uiview-under-another-uiview)
{ "pile_set_name": "StackExchange" }
Q: CSS - how to set some divs inline Hi im trying to set some divs inline and i dont know what else to do. .menuboton{ display:inline; padding:0.7em; border-radius: 4px; background-color: #093; } .menu{ display:inline; margin-right:4em; } There are two classes, first are 4 divs and the another is one div with an <img> inside. Those divs are inside another div: #elmenu{ margin:auto; margin-bottom:10px; width:100%; border-top:1px solid black; border-bottom:1px solid black; } This is my problem: the 4 divs always are slightly below the one with the <img> inside and cross over the container div (elmenu). For fix that I tried setting it display:inline-block and fix the problem of exceds the container limit but still below the one with <img> inside. Here the html code: <div id="elmenu"> <div class="menu" id="logo"><img id="imglogo" src="psds/logo.png" /></div> <div class="menuboton"><a href="index.php">Inicio</a></div> <div class="menuboton"><a href="Posts.php">Posts</a></div> <div class="menuboton"><a href="login.php">Login</a></div> <div class="menuboton"><a href="usuarios/actividadUsuario.php">Usuario</a></div> </div> Pics: Using display:inline; Using display:inline-block; I want all divs stay at the same level! Some guess? A: Place the Knowit image in left and the menu in right and edit widths accordingly. HTML: <div class='container'> <div class='left'></div> <div class='right'></div> </div> CSS: .container { overflow: hidden; margin:0; padding:0; } .left{ float: left; width: 150px; } .right { float: right; width: 150px; text-align:left; } Edit on OP request: To center object within div class use: text-align:center; to center align the div container use: margin: 0 auto; All this information can be found at http://w3schools.com/
{ "pile_set_name": "StackExchange" }
Q: Windows: Will compressing the hard drive partition speed up disk access? Possible Duplicate: How does NTFS compression affect performance? In theory, on a reasonably fast PC, the processor is mostly idle during hard drive access. A compressed file takes up less physical space, so the hard drive (being the slowest part in the system) has to read less physical data. One could argue that the small additional amount of work for the processor to uncompress the data on the fly will not result in slowdown of the read operation, so hence my question: If I activate drive compression on a Windows machine, can I positively affect data throughput at the expense of a somewhat higher CPU usage? A: Some discussion on the subject here http://ask.metafilter.com/51652/Could-turning-on-disk-compression-actually-speed-up-disk-access and here http://arstechnica.com/civis/viewtopic.php?f=17&t=801882 too many variables for a direct answer.
{ "pile_set_name": "StackExchange" }
Q: IntelliJ mvn project test classes not functioning In my maven project for some reason, even though the class and the test class are located in the same package, when I did Ctrl+Shift+T it says "No Test Class Found". More importantly, when I right click on the test file, it only gives me the option to compile test, but not run test. I'm able to run the tests successfully if I just do mvn clean install in command line. Any idea? A: You need to mark the test files/directories as "Test Sources" in Project Settings -> Modules?
{ "pile_set_name": "StackExchange" }
Q: Use awk or sed to eliminate repeat entries in text file I have a text file like this... apples berries berries cherries and I want it to look like this... apples berries cherries That's it. I just want to eliminate doubled entries. I would prefer for this to be an awk or sed "one-liner" but if there's some other common bash tool that I have overlooked that would be fine. A: sort -u file if in case you are not worried about the order of the output. Remove duplicates by retaining the order: awk '!a[$1]++' file
{ "pile_set_name": "StackExchange" }
Q: How to add qwidget to qlist I have several widgets, like QLineEdit m_namePoiFilter; QLineEdit m_ID_MSSIPoiFilter; I would like to add them to a list of qwidgets, then set all of them visible. I have made QList<QWidget> m_PoiFilterWidgets; but I can not add an item to it like m_PoiFilterWidgets.push_back(m_namePoiFilter); A: You need to hold these via a pointer, and you should use a lower-overhead container like std::array. E.g.: class Foo { QLineEdit m_namePoiFilter; QLineEdit m_ID_MSSIPoiFilter; std::array<QLineEdit*, 2> const m_edits = {&m_namePoiFilter, &m_ID_MSSIPoiFilter}; }; This code is safe from dangling pointers by construction: m_edits will be constructed after the widgets are constructed, and will be destroyed before the widgets are destroyed: thus its contents are always valid. I'd avoid QList/QVector as these allocate on the heap - unnecessarily in your case.
{ "pile_set_name": "StackExchange" }
Q: How to display private properties of a class (PHP OOP) I've read that it's better to have properties of a class be private, and use get/set methods to access/change them. So I set up a class that way, but I want to be able to display the properties in an html table and I was going to use a separate htmlTable display class to do it. I thought of 4 possibilities. Feel free to skip them if you already know the ideal way to do this. Thank you. Possibilities: I can get the class fields using: $class_Vars = get_class_vars($object_class); $fields = $class_vars['fields']; // But as far as iterating through each object, this doesn't work: foreach($object_array as $current_object) { foreach($current_object as $value) { $html = '<td>' . $value . '</td>'; } } The values are private and inaccessible. A possible solution that looks very clumsy and would probably be a debugging nightmare is: foreach($fields as $value) { $get_func = 'get' . ucwords($value); // e.g. $get_func = 'getId' $current_value = $current_object->$get_func(); } I think it would work but it doesn't sit right with me. Interface. Another possibility is to write in an htmlTable function into every class I want to do it. But that is a lot of code reuse. Interface. Or I could write in an export() function into every class that just outputs an array with property names and values. Then my htmlTable class can just handle those outputs. A: Either make them public or make get/set methods. You could also make a getAll() method that returns an associative array with all of your private variables.
{ "pile_set_name": "StackExchange" }
Q: How to return the total count of a database entity when one of its rows matches a condition I have a list of numbers which I’m looping through to identify if an entity in a database table matches at least one of these numbers, if so, I want to count how many times these entities appear in that table and return the entities along with the number of time they a in the table. As the entities may match one or more numbers, I can just the duplicate data by using pythons set(), unless obviously there’s are better way to do it. So for example List = [a, b, c, d] # Unknown number of entries Column 1 Column 2 column3 etc Blue a Blue - Blue a Green - Red a Red b Red c Red c Red - Red - So im trying to return: Blue, 3 Red, 6 The closest I've been able to get is below, but is not yielding the desired resutls. for letter in list: c.execute('SELECT colour, COUNT(*) FROM table GROUP BY colour HAVING letter=?', [(letter)]) I'm not sure how to proceed with this, any advice would be very much be appreciated. In responce to @CL. This was the kind of data that it was returning. The later nest in the list contains the correct values, but then the first nest contains “random” values. I can’t understand how these are formed so I’m unsure how to remove them. [[(red, 1), (anotherColour, 1)], [(red, 6), (blue, 3), (anotherColour, 5) ]] A: First, get the entities that you want to count: SELECT DISTINCT colour FROM MyTable WHERE letter IN ('a', 'b', 'c', 'd') Then, use that to filter the entities before counting: SELECT colour, COUNT(*) FROM MyTable WHERE colour IN (SELECT colour FROM MyTable WHERE letter IN ('a', 'b', 'c', 'd')) GROUP BY colour When you have an unknown number of entries, you have to construct the parameter list dynamically: list = ['a', 'b', 'c', 'd'] params = ','.join('?' for _ in list) c.execute("""SELECT colour, COUNT(*) FROM MyTable WHERE colour IN (SELECT colour FROM MyTable WHERE letter IN (""" + params + """)) GROUP BY colour""", list)
{ "pile_set_name": "StackExchange" }
Q: How to make browser request new js and css files I want to show some important information to the users (via banner). So, I want to set new cookies through js. I need users browsers to request new js files and not take them from cache. And this should work in mostly all browsers. How can it be done? A: Send the browser an HTML document with different URLs in the src attributes of the <script> elements. You could add a query string if you don't want to rename a static file.
{ "pile_set_name": "StackExchange" }
Q: How to include 3rd party libraries in CodeIgniter? I'm trying to get Google Plus Authentication into CodeIgniter using the following: https://code.google.com/p/google-api-php-client/ I have put these files in third_party/google-api-php-client/src If I was doing this without CI, I would simply use: require_once 'google-api-php-client/src/Google_Client.php'; require_once 'google-api-php-client/src/contrib/Google_PlusService.php'; What would be the CI equivalent way to "require" these files? I have tried doing require APPPATH .'third_party/google-api-php-client/src/Google_Client.php'; However get issued the following message: Message: require(application/third_party/google-api-php-client/src/Google_Client.php): failed to open stream: Permission denied A: download the third party library and put it inside your library or third party folder and the same you load your other libraries you can load this as will, check out this way i hope it will work $this->load->library('phpword'); for third parties. for google api check read out this i hope this will solve your problem https://github.com/joeauty/Google-API-Client-CodeIgniter-Spark
{ "pile_set_name": "StackExchange" }
Q: ¿Como desactivo todos los elementos de un jpanel? en java Lo intento de la siguiente manera: jPanel.setEnabled(false); Pero no funciona. ¿Hay otra opción? A: Con tu código lo que haces es "desactivar" el JPanel en sí (lo cual realmente no hace gran cosa). Si quieres desactivar los elementos contenidos en el JPanel, tendrás que obtener la lista de estos elementos y recorrerla, desactivando cada elemento por separado. for (Component component : jPanel.getComponents()) { component.setEnabled(false); } A: Deberías de forma básica obtener todos los componentes y desactivarlos, tal como se ve a continuación: public void enableComponents(Container container, boolean enable) { Component[] components = container.getComponents(); for (Component component : components) { component.setEnabled(enable); if (component instanceof Container) { enableComponents((Container)component, enable); } } } En el ejemplo se puede ver el atributo Container que sería tu JPanel ya que este extiende del primero como se ve en la documentación de Container en la documentación de AWT. El ejemplo completo lo puedes revisar en StackOverflow en Inglés.
{ "pile_set_name": "StackExchange" }
Q: Derivative of $H(x)=[f(x)]^{x^2+1}-[\cos(2x)]^{g(x)}$ for differentiable, positive $f(x), g(x)$ I found this question in the review of a chapter that covered derivatives, implicit differentiation, related rates, inverse functions, one-to-one functions, derivatives of higher order. Let $f,g: \mathbb{R}\rightarrow(0,\infty)$ be differentiable functions. Find the derivative of $$H(x)=[f(x)]^{x^2+1}-[\cos(2x)]^{g(x)} .$$ I derived it as follows: $$(x^2+1)[f(x)]^{x^{2}}+2\sin(2x)g(x)[\cos(2x)]^{g(x)-1}$$ I strongly believe that there is something else required to differentiate this function but I am not sure what I should be looking for. I thought about isolating $f(x)$ and $g(x)$ and representing each in terms of $x$ and then substituting into $h(x)$ before differentiating but I'm not sure if this is required and how to accomplish this. A: Hint For differentiable, positive functions $a, b : \Bbb R \to (0, \infty)$, we can write $$a(x)^{b(x)} = \exp [b(x) \log a(x)] .$$ Then, we can apply the chain rule, the product rule, and the rule $\frac{d}{du} \log u = \frac{1}{u}$. Alternatively, we can take the logarithm of both sides of $y(x) := a(x)^{b(x)}$, implicitly differentiate to get an equation $\frac{y'(x)}{y(x)} = \cdots$, solve for $y'(x)$, and substitute for $y(x)$ to write $y'(x)$ in terms of $a(x)$, $b(x)$, and their derivatives.
{ "pile_set_name": "StackExchange" }
Q: Can I use @Profile Tags on Components without creating an @Configuration class in Spring Boot or a Web.xml I've managed to avoid developing any xml files so far for my Spring Boot Maven project (apart from the pom) with them all being generated on compile and I was hoping to keep this way by defining my profiles within the run commands as specified here. By simply using @ComponentScan my main class to enable the scanning of components and tagging my DAO as @Repository I have successfully managed to autowire my UserDAOmySQLImpl class (which inherits UserDAO). @Autowired private UserDAO userDAO; Then looking forward to add a second DAO for when in Live where we use a db8 implementation I need the application to figure out which UserDAO implementation needs to be used. Profiles seemed to be the answer. After some reading, it seemed that mostly I need to add in some sort of configuration classes and external xml to manage these profiles and components, though this seems messy and I am hoping unnecessary. I have tagged by two implementations as so: @Repository @Profile("dev") public class UserDAOmySQLImpl implements UserDAO {... - @Repository @Profile("dev") public class UserDAOdb8Impl implements UserDAO {... And then set the active profile through the Maven goals as specified here in hope that this would be a nice clean solution so I could specify the active profile within the goal for our dev and live build scripts respectively. My current goal for testing is: spring-boot:run -Drun.profiles=dev However, when building I receive an error that both beans are being picked up. *No qualifying bean of type [com.***.studyplanner.integration.UserDAO] is defined: expected single matching bean but found 2: userDAOdb8Impl,userDAOmySQLImpl* Questions Is the profile set in the Maven Goal the one being checked against when using the @Profile tag? Why is Spring picking up both implementations, when if the profile isn't being set properly surely neither implementation should be selected? Any suggestions on a nice clean way to achieve what I'm looking for? Bonus I would really like to set the profile within the app, as it would be easy to simply check whether an environment file exists to decide which profile to use, though I'm struggling to replicate this (found within Spring Profiles Examples public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); //Enable a "live" profile context.getEnvironment().setActiveProfiles("live"); context.register(AppConfig.class); context.refresh(); ((ConfigurableApplicationContext) context).close(); } in to the unusual main class in the application I am working on which I am hesitant to play around with. public class StudyPlannerApplication { ... public static void main(String[] args) { SpringApplication.run(StudyPlannerApplication.class, args); } ... } Any help would much appreciated. Cheers, Scott. A: Silly me, proof reading the question I noticed that a bad copy & paste job meant that both DAO implementations had the @profile set to "Dev". After changing the db8 DAO to @Profile("live") the above works fine. So to choose your repository based on profile is actually quite easy when using maven and spring boot. 1) Ensure your main class has the @ComponentScan annotation @ComponentScan public class StudyPlannerApplication { 2) Tag your components with the @Profile tags according to which profile you would like them sectected for @Repository @Profile("dev") public class UserDAOdb8Impl implements UserDAO {... - @Repository @Profile("live") public class UserDAOdb8Impl implements UserDAO {... 3) Send your profile in with your maven goal spring-boot:run -Drun.profiles=dev Hopefully this will help others, as I haven't seen a full example of using the autowiring profiles as I have done elsewhere on the web
{ "pile_set_name": "StackExchange" }
Q: XSLT-Create elements dynamically with java I have a method that should create and then append a xsl:template tag into the xml file given below. Java: ... tF = TransformerFactory.newInstance(); DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); fact.setNamespaceAware(true); DocumentBuilder builder2 = fact.newDocumentBuilder(); id = builder2.parse(ctx.getRealPath("/WEB-INF/identity.xsl")); ... attributes_only(id); StreamSource xmlSource = new StreamSource(ctx.getResourceAsStream("/WEB-INF/input.xml")); response.setContentType("text/html"); DOMSource ds_id = new DOMSource(id); Transformer mine = tF.newTransformer(ds_id); DOMResult output = new DOMResult(); mine.transform(xmlSource, output); ... private void attributes_only(Document d) { Element root = d.getDocumentElement(); Element e = d.createElement("xsl:template"); e.setAttribute("match","a|b|c"); root.appendChild(e); } ... XML: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <!-- This is what I want to achieve <xsl:template match="a|b|c"> </xsl:template> --> </xsl:stylesheet> I am using org.w3c.dom and everything runs fine except for this method. The error message (from tomcat) is something like "xsl:template is not allowed in this position in the stylesheet" and an empty xml is produced. Does anyone have an idea about what's wrong? Thank you in advance A: To create elements and attributes in a namespace-aware DOM tree you need to use the DOM level 2 *NS versions of the methods, rather than the (ancient) DOM level 1 methods that pre-date namespaces. Element e = d.createElementNS("http://www.w3.org/1999/XSL/Transform", "xsl:template"); e.setAttributeNS(null, "match","a|b|c");
{ "pile_set_name": "StackExchange" }
Q: bootstrap navbar collapse not fuctioning and the answers on other questions didn't work I am trying to make a collapsable navbar with bootstrap, the nav does collapse but when I click on it it does not dropdown here is all the code I have in my index html page <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Honk</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="public/stylesheets/styles.css"> <script src="//code.jquery.com/jquery-1.11.2.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"> <link rel="stylesheet" href="public/stylesheets/custom.css"> </head> <body> <nav class="navbar navbar-fixed-top navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <img class="logo" src="public/images/honklogoo.png" alt=""> </div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav navbar-right"> <li><a class="discrip" href="#">About</a></li> <li><a href="#">Commuters</a></li> <li><a href="#">Travelers</a></li> <li><a href="#">On Demand</a></li> <li><a href="#">Safety</a></li> <li><a href="#">Download</a></li> </ul> </div> </div> </nav> </body> </html> A: you dont have the the bootstrap js script in your html (you just have the css) <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script> its working here: http://jsfiddle.net/swm53ran/26/ btw, make sure you put it after your jquery script since bootstrap is dependent on jquery
{ "pile_set_name": "StackExchange" }
Q: If an integer $n$ is such that $7n$ is the form $a^2 + 3b^2$, prove that $n$ is also of that form. If an integer $n$ is such that $7n$ is the form $a^2 + 3b^2$, prove that $n$ is also of that form. I thought that looking at quad residues mod $7$ might??? help. But that didn't take me anywhere so apart from that I'm at a loss. I would appreciate any help. Thanks in advance. A: $\text{Make use of the identity }$$$\color{red}{(x^2+3y^2)(u^2+3v^2) = \underbrace{(xu\pm3yv)^2 + 3(xv\mp yu)^2}_{a^2 + 3b^2}}$$ $\text{Now we have}$ $$7 = 2^2 + 3 \times 1^2$$ $\text{i.e., }x=2 \text{ and }y=1$. $\text{Use this to obtain $u$ and $v$.}$ $\textbf{EDIT}$: $\text{Here is the full solution. The main claim is that if $7 \vert (a^2+3b^2)$, then}$ Either $7 \vert (a+2b)$ and $7 \vert (2a-3b)$ Or $7 \vert (a-2b)$ and $7 \vert (2a+3b)$ This can be checked by listing out the different possibilities for $a$ and $b$. If $7 \vert (a+2b)$ and $7 \vert (2a-3b)$, then set $u = \dfrac{2a-3b}7$ and $v = \dfrac{a+2b}7$. Else, if $7 \vert (a-2b)$ and $7 \vert (2a+3b)$, then set $u = \dfrac{3b-2a}7$ and $v = \dfrac{a+2b}7$. This guarantess that $u$ and $v$ are integers. Hence, $\text{$n$ can be written as $u^2+3v^2$.}$
{ "pile_set_name": "StackExchange" }
Q: how to get specific fields by id in Netsuite using RESTlet I could get all the standard and system fields with values of specific record by id in netsuite using below function. var response = record.load({ type: resourceType, id: recordId }); But I want to get specific fields using above function like below var response = record.load({ type: resourceType, id: recordId, fields: ["id","name"] }); I could get specific fields by search. But search will take time compare than load(). A: You can also use search.lookupFields() which is usually faster that a record.load() or search.create(). It works like this: var customer = search.lookupFields({ type: 'customer', id: 968, columns: ['internalid', 'companyname', 'daysoverdue'] }); log.debug(customer.internalid[0].value); log.debug(customer.companyname); log.debug(customer.daysoverdue); log.debug(JSON.stringify(customer)); The response you get back from search.lookupFields() looks like this: { "internalid": [{ "value": "968", "text": "968" }], "companyname": "DataTek Systems, Inc.", "daysoverdue": "0" }
{ "pile_set_name": "StackExchange" }
Q: Selecting specific tags with BeautifulSoup I am fetching some html table rows with BeautifulSoup with this piece of code: from bs4 import BeautifulSoup import urllib2 import re page = urllib2.urlopen('www.something.bla') soup = BeautifulSoup(page) rows = soup.findAll('tr', attrs={'class': re.compile('class1.*')}) This is what I get as a result: <tr class="class1 class2 class3">...</tr> <tr class="class1 class2 class3">...</tr> <tr class="class1 class5">...</tr> <tr class="class1_a class5_a">...</tr> <tr class="class1 class5">...</tr> <tr class="class1_a class5_a">...</tr> <!-- etc. --> However, I'd like to exclude (or not select them in the first place) those rows which have class1 class2 class3 as an attribute. How can I do that? Thanks for help! A: Perhaps it's easier without regex. This works with BeautifulSoup 3: from BeautifulSoup import BeautifulSoup page = """ <tr class="class1 class2 class3">1</tr> <tr class="class1 class2 class3">2</tr> <tr class="class1 class5">3</tr> <tr class="class1_a class5_a">4</tr> <tr class="class1 class5">5</tr> <tr class="class1_a class5_a">6</tr> <tr>7</tr>""" def cond(x): if x: return x.startswith("class1") and not "class2 class3" in x else: return False soup = BeautifulSoup(page) rows = soup.findAll('tr', {'class': cond}) for row in rows: print row => <tr class="class1 class5">3</tr> <tr class="class1_a class5_a">4</tr> <tr class="class1 class5">5</tr> <tr class="class1_a class5_a">6</tr> With BeautifulSoup 4, I was able to make it work as follows: import re from bs4 import BeautifulSoup page = """ <tr class="class1 class2 class3">1</tr> <tr class="class1 class2 class3">2</tr> <tr class="class1 class5">3</tr> <tr class="class1_a class5_a">4</tr> <tr class="class1 class5">5</tr> <tr class="class1_a class5_a">6</tr> <tr>7</tr>""" soup = BeautifulSoup(page) rows = soup.find_all('tr', {'class': re.compile('class1.*')}) for row in rows: cls = row.attrs.get("class") if not ("class2" in cls or "class3" in cls): print row => <tr class="class1 class5">3</tr> <tr class="class1_a class5_a">4</tr> <tr class="class1 class5">5</tr> <tr class="class1_a class5_a">6</tr> In BS4, multi-valued attributes like class have lists of strings as their values, not strings. See http://www.crummy.com/software/BeautifulSoup/bs4/doc/#id12.
{ "pile_set_name": "StackExchange" }
Q: Prototype.js Upload and Browse not working v1.9.2.1 The buttons are there, but as with 8788v2 patch they are showing on the left hand side, not the right, they are also not working. Checking in the console: prototype.js:828 Uncaught ReferenceError: Uploader is not defined at eval (eval at <anonymous> (http://defibshop.yoma-cloud.co.uk/js/prototype/prototype.js:612:64), <anonymous>:3:24) at eval (eval at <anonymous> (http://defibshop.yoma-cloud.co.uk/js/prototype/prototype.js:612:64), <anonymous>:8:7) at http://defibshop.yoma-cloud.co.uk/js/prototype/prototype.js:612:64 at http://defibshop.yoma-cloud.co.uk/js/prototype/prototype.js:865:29 at http://defibshop.yoma-cloud.co.uk/js/prototype/prototype.js:825:18 at Array.forEach (native) at Array.each (http://defibshop.yoma-cloud.co.uk/js/prototype/prototype.js:824:12) at Array.collect (http://defibshop.yoma-cloud.co.uk/js/prototype/prototype.js:864:10) at String.evalScripts (http://defibshop.yoma-cloud.co.uk/js/prototype/prototype.js:612:34) at Function.<anonymous> (http://defibshop.yoma-cloud.co.uk/js/prototype/prototype.js:391:23) However I have copied the original file from the Magento version and replaced it, still not working. I have cleared the cache, reindexed and also tried a number of different browsers. Any ideas what it could be? 8788 patch has been applied. In the console: When loading the page, checking the console: (index):1829 Uncaught ReferenceError: Uploader is not defined(anonymous function) @ (index):1829(anonymous function) @ (index):1834 (index):1846 Uncaught SyntaxError: Unexpected token , A: I had to add this into Main.xml <action method="addJs"><file>lib/uploader/flow.min.js</file></action> <action method="addJs"><file>lib/uploader/fusty-flow.js</file></action> <action method="addJs"><file>lib/uploader/fusty-flow-factory.js</file></action> <action method="addJs"><file>mage/adminhtml/uploader/instance.js</file></action>
{ "pile_set_name": "StackExchange" }
Q: C# extension to resolve cross thread exception Is there any extension method available for resolving cross thread exception in windows forms like the one which is there for wpf forms.or any general pattern.. http://www.codeproject.com/Articles/37314/Useful-WPF-Threading-Extension-Method.aspx A: Invoke already does some things to short-circuit here, but it would be trivial to make it complete: public static class SyncExtensions { public static void InvokeIfRequired(this ISynchronizeInvoke ctrl, MethodInvoker method) { if(ctrl.InvokeRequired) ctrl.Invoke(method, null); else method(); } } The choice of MethodInvoker is since this has specific handling inside Invoke to avoid having to use DynamicInvoke (reflection).
{ "pile_set_name": "StackExchange" }
Q: Lining up link buttons to be centered in between the links above them I have a total of five link buttons three on top and two underneath. I am trying to get them to line up by having the bottom two links centered inbetween the ones on top. Currently there is a big gap inbetween them. Can someone help me adjust the css to line up directly inbetween the ones above them? .content-sm { padding-top: 60px; padding-bottom: 60px; } @media (min-width: 1200px) .container { width: 1170px; } @media (min-width: 992px) .container { width: 970px; } @media (min-width: 768px) .container { width: 750px; } .container { padding-right: 15px; padding-left: 15px; margin-right: auto; margin-left: auto; } * { border-radius: 0; } /*Business Posts Section ------------------------------------*/ .business-post-section { position: relative; background: #f7f7f7; } /*Business Posts Links/Buttons ------------------------------------*/ .business-post-link { padding-top: 25px; text-align: center; } .business-post-link i { color: #fff; width: 90px; height: 90px; padding: 30px; font-size: 30px; line-height: 30px; position: relative; text-align: center; background: #00539c; margin-bottom: 25px; display: inline-block; } .business-post-link i:after { top: -8px; left: -8px; right: -8px; bottom: -8px; content: " "; position: absolute; border: 1px solid #dedede; border-radius: 50% !important; } .business-post-link:hover i, .business-post-link:hover i:after { transition: all 0.3s ease-in-out; } .business-post-link:hover i { background: #db9e33; } .business-post-link:hover i:after { border-color: #db9e33; } .rounded-x { border-radius: 50% !important; } .business-post-title { font-size: 20px; line-height: 24px; color: #555; } @media (min-width: 768px) .col-sm-4 { width: 33.33333333%; } @media (min-width: 768px) .col-sm-6 { width: 50%; } @media (min-width: 768px) .col-sm-1, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9 { float: left; } .col-lg-1, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-md-1, .col-md-10, .col-md-11, .col-md-12, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-sm-1, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-xs-1, .col-xs-10, .col-xs-11, .col-xs-12, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9 { position: relative; min-height: 1px; padding-right: 15px; padding-left: 15px; } <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <link href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.css" rel="stylesheet"/> <div class="wrapper"> <!--=== Business Block ===--> <div class="business-post-section"> <div class="container content-sm"> <div class="row "> <a href="http://www.test.com"> <div class="col-md-4 business-post-link"> <i class="rounded-x icon-drawer"></i> <h2 class="business-post-title">Tax Collection Solutions</h2> </div> </a> <a href="http://www.test.com"> <div class="col-md-4 business-post-link"> <i class="rounded-x icon-flag"></i> <h2 class="business-post-title">Auction Solutions</h2> </div> </a> <a href="http://www.test.com"> <div class="col-md-4 business-post-link"> <i class="rounded-x icon-wallet"></i> <h2 class="business-post-title">Payment Solutions</h2> </div> </a> </div><!--/row--> </div><!--/container--> </div> <!--=== Contact Us Block ===--> <div class="business-post-section"> <div class="container content-sm"> <div class="row "> <a href="http://www.test.com"> <div class="col-md-6 business-post-link"> <i class="rounded-x icon-screen-desktop"></i> <h2 class="business-post-title">Request a Demo</h2> </div> </a> <a href="http://www.test.com"> <div class="col-md-6 business-post-link"> <i class="rounded-x icon-call-in"></i> <h2 class="business-post-title">Contact Us</h2> </div> </a> </div><!--/row--> </div><!--/container--> </div> </div> A: Maybe try putting some col-md-2 place holder divs on either side? The first row of three buttons, since all three divs are col-md-4 in a 12 column system, the top row of buttons end up centered between columns 2 & 3, between 6 & 7, and between 10 & 11. The ideal place to center the two buttons for the second row would be between columns 4 & 5 and between columns 8 & 9. But if you do two big col-md-3 columns, they end up getting centered between columns 3 & 4 and between columns 9 & 10. .content-sm { padding-top: 60px; padding-bottom: 60px; } @media (min-width: 1200px) .container { width: 1170px; } @media (min-width: 992px) .container { width: 970px; } @media (min-width: 768px) .container { width: 750px; } .container { padding-right: 15px; padding-left: 15px; margin-right: auto; margin-left: auto; } * { border-radius: 0; } /*Business Posts Section ------------------------------------*/ .business-post-section { position: relative; background: #f7f7f7; } /*Business Posts Links/Buttons ------------------------------------*/ .business-post-link { padding-top: 25px; text-align: center; } .business-post-link i { color: #fff; width: 90px; height: 90px; padding: 30px; font-size: 30px; line-height: 30px; position: relative; text-align: center; background: #00539c; margin-bottom: 25px; display: inline-block; } .business-post-link i:after { top: -8px; left: -8px; right: -8px; bottom: -8px; content: " "; position: absolute; border: 1px solid #dedede; border-radius: 50% !important; } .business-post-link:hover i, .business-post-link:hover i:after { transition: all 0.3s ease-in-out; } .business-post-link:hover i { background: #db9e33; } .business-post-link:hover i:after { border-color: #db9e33; } .rounded-x { border-radius: 50% !important; } .business-post-title { font-size: 20px; line-height: 24px; color: #555; } @media (min-width: 768px) .col-sm-4 { width: 33.33333333%; } @media (min-width: 768px) .col-sm-6 { width: 50%; } @media (min-width: 768px) .col-sm-1, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9 { float: left; } .col-lg-1, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-md-1, .col-md-10, .col-md-11, .col-md-12, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-sm-1, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-xs-1, .col-xs-10, .col-xs-11, .col-xs-12, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9 { position: relative; min-height: 1px; padding-right: 15px; padding-left: 15px; } <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <link href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.css" rel="stylesheet"/> <div class="wrapper"> <!--=== Business Block ===--> <div class="business-post-section"> <div class="container content-sm"> <div class="row "> <a href="http://www.test.com"> <div class="col-md-4 business-post-link"> <i class="rounded-x icon-drawer"></i> <h2 class="business-post-title">Tax Collection Solutions</h2> </div> </a> <a href="http://www.test.com"> <div class="col-md-4 business-post-link"> <i class="rounded-x icon-flag"></i> <h2 class="business-post-title">Auction Solutions</h2> </div> </a> <a href="http://www.test.com"> <div class="col-md-4 business-post-link"> <i class="rounded-x icon-wallet"></i> <h2 class="business-post-title">Payment Solutions</h2> </div> </a> </div><!--/row--> </div><!--/container--> </div> <!--=== Contact Us Block ===--> <div class="business-post-section"> <div class="container content-sm"> <div class="row "> <div class="col-md-2"></div> <a href="http://www.test.com"> <div class="col-md-4 business-post-link"> <i class="rounded-x icon-screen-desktop"></i> <h2 class="business-post-title">Request a Demo</h2> </div> </a> <a href="http://www.test.com"> <div class="col-md-4 business-post-link"> <i class="rounded-x icon-call-in"></i> <h2 class="business-post-title">Contact Us</h2> </div> </a> <div class="col-md-2"></div> </div><!--/row--> </div><!--/container--> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: Apache 2.4 redirecting local virtual host to https instead http I'm using MAC os and apache 2.4. I have created a virtual host for my local development. This virtual host is redirecting to https instead of simple http (I need it to work in http). I have tried it on chrome and safari. It's a laravel project. Here is the content of httpd-vhosts.conf # ServerAlias www.dummy-host.example.com # ErrorLog "/private/var/log/apache2/dummy-host.example.com-error_log" # CustomLog "/private/var/log/apache2/dummy-host.example.com-access_log" common #</VirtualHost> #<VirtualHost *:80> # ServerAdmin [email protected] # DocumentRoot "/usr/docs/dummy-host2.example.com" # ServerName dummy-host2.example.com # ErrorLog "/private/var/log/apache2/dummy-host2.example.com-error_log" # CustomLog "/private/var/log/apache2/dummy-host2.example.com-access_log" common #</VirtualHost> <VirtualHost *:80> DocumentRoot "/Library/WebServer/Documents/onboardera/public" ServerName onboardera.dev ServerAlias onboardera.dev </VirtualHost> <VirtualHost *:80> DocumentRoot "/Library/WebServer/Documents/multi-site/public" ServerName multi-site.dev ServerAlias multi-site.dev </VirtualHost> Following is the content of hosts file. ## # Host Database # # localhost is used to configure the loopback interface # when the system is booting. Do not change this entry. ## 127.0.0.1 localhost 127.0.0.1 multi-site.dev 127.0.0.1 khan.multi-site.dev 127.0.0.1 onboardera.dev 255.255.255.255 broadcasthost ::1 localhost Screenshot is also attached A: .dev domains belongs to google and Google Chrome is rolled out v63 that now forces all .dev domains to use HTTPS. So either You can try some other browser or use .local or .test Viable option is to switch to Firefox as your development browser. It’s fast, has comfortable dev tools, and has really made a ton of improvements over the past few years.
{ "pile_set_name": "StackExchange" }
Q: Como enviar um e-mail após haver um novo cadastro no mysql Olá, Tenho uma tabela no mysql basicamente neste formato. id transaction_id name buyer_email transaction_date paymentstatus 1 989Y8DT8S65DS Test [email protected] 17/02/2016 Completed Minha intenção seria que ao haver um novo dado inserido no mysql, seria enviado um e-mail automaticamente para o e-mail da tabela buyer_email A: Tu tens que pegar o script que faz a inserção e ao fim dela verificar. Faz um if pra confirmar que o registro foi inserido corretamente. Se sim, entra o script de email, usando o próprio e-mail que veio no cadastro. Exemplo (sem código, só lógica): envia.php - Contém os dados a serem inseridos com um POST para a página recebe.php recebe.php - Pega os dados, insere no banco e se a inserção foi feita faz o envio do e-mail. Exemplo: $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL); $sql = mysqli_query("INSERT INTO tabela VALUES ('', '$email', ...)"); if($sql){ //envia o email; } else { //retorna para outra página } Verifica a função mail para enviar.
{ "pile_set_name": "StackExchange" }
Q: Writing low-level program like PartitionManager I would like to learn how to write programs which may run without booting the operating system, like Norton Ghost or Paragon programs. I would like to be able to run the program from a CD or a USB stick. Could you give me some pointers, please? A: Basically - unless you use an existing one - you have to write your own operating system - it could be small, but it is an OS. Writing it is a bit different from writing applications, because you have to interface with hardware directly (or through the BIOS). It requires a good knowledge of low-level programming, hardware devices specifications and processor architecture, especially if you need memory and have to switch a x86 processor to protected mode ("unreal mode" could be used, though) which uses a fairly complex mechanism. Some parts may need to be written in assembler to access the special "privileged" instructions used by "kernels" running at the most privileged level ("ring 0") in protected mode, and to handle interrupts. You could start here http://wiki.osdev.org/Main_Page.
{ "pile_set_name": "StackExchange" }
Q: imported createStackNavigator undefined I have a problem with importing my stack navigator in a react-native project. I am using the JSX syntax. Below I have posted information about the project that I hope is relevant to find a solution to this issue. The following code does the import. It lies in a file called App.js import { AppNavigator } from '../navigation' console.log(AppNavigator) // prints undefined AppNavigator.js looks like the following: import { createStackNavigator } from 'react-navigation' import StartScreen from '../screen/start-screen' const AppNavigator = createStackNavigator({ Start: { screen: StartScreen } }, { initialRouteName: 'Start', navigationOptions: { header: null } }) export default AppNavigator I have simplified the router configuration (AppNavigator is a bit more complicated) to try and isolate the issue and I don't believe StartScreen is mucking things up. StartScreen.js has never failed before, but the "undefined issue" happened after I attempted to integrate redux with react navigation has described in: https://reactnavigation.org/docs/en/redux-integration.html Here is the project's package.json: { "name": "App", "version": "0.0.1", "private": true, "scripts": { "start": "node node_modules/react-native/local-cli/cli.js start", "test": "jest", "clean": "watchman watch-del-all && rm -rf node_modules/ && rm -rf ios/build/ && rm -rf android/build/ && rm -rf $TMPDIR/react-* rm package-lock.json && npm install && react-native link && npm start", "ios": "react-native run-ios" }, "dependencies": { "debounce": "^1.1.0", "deep-freeze": "0.0.1", "es6-promise": "^4.2.4", "event-emitter": "^0.3.5", "isomorphic-fetch": "^2.2.1", "moment": "^2.22.1", "react": "16.3.1", "react-datepicker": "^1.5.0", "react-dom": "^16.4.1", "react-native": "^0.55.4", "react-native-calendar": "^0.13.1", "react-native-calendars": "^1.19.3", "react-native-collapsible": "^0.12.0", "react-native-elements": "^0.19.1", "react-native-form": "^2.1.2", "react-native-modal": "^6.1.0", "react-native-vector-icons": "^4.6.0", "react-navigation": "^2.5.5", "react-navigation-redux-helpers": "^2.0.2", "react-redux": "^5.0.7", "redux": "^4.0.0", "redux-form": "^7.4.2", "redux-logger": "^3.0.6", "redux-thunk": "^2.2.0" }, "devDependencies": { "babel-jest": "22.4.3", "babel-preset-react-native": "4.0.0", "eslint": "^4.19.1", "eslint-plugin-react": "^7.10.0", "jest": "22.4.3", "react-test-renderer": "16.3.1", "standard": "^11.0.1" }, "jest": { "preset": "react-native" } } I am running the project with Xcode 9.2 on a MacBook Mini (macOS Sierra 10.12.6) My question is: What reasons could result in an import yielding undefined when the import "should work". I believe my syntax is correct . Is the reasons related to the build or linking. I have rebuilt the project several times, removed the App on the IOS simulator, and reinstalled it with Xcode. I have also run the following command: "watchman watch-del-all && rm -rf node_modules/ && rm -rf ios/build/ && rm -rf android/build/ && rm -rf $TMPDIR/react-* rm package-lock.json && npm install && react-native link" A: StartScreen.js contained an incorrect import , which caused the import of StartScreen in AppNavigator.js to become undefined.
{ "pile_set_name": "StackExchange" }
Q: Random demodulator in matrix form I went through a paper in random demodulator. It states that If the sampling rate is $R$ ($R$ is less then $W$, $W=$band limit of a signal in Hz), and assume that $W$ is divided by $R$. Then each sample is the sum of $W/R$ consecutive entries of the demodulated signal. Does it mean that the signal is compressed by taking $W/R$ samples at a time? A: The random demodulator (in this definition) compresses the signal by taking samples that are each linear combinations of W/R Nyquist rate samples. So it does not take W/R samples at a time; it takes one sample at a time, each of which contain information corresponding to several (W/R) Nyquist rate samples. It is then up to a reconstruction algorithm to subsequently "disentangle" these into the original signal (approximately) at Nyquist rate. The random demodulator works by "smearing" the content of the input signal all over the spectrum (by multiplication with the spreading sequence). Provided that the input signal is sufficiently sparse, we can now reconstruct it from just a small portion of the resulting spectrum (selected by the low-pass filter).
{ "pile_set_name": "StackExchange" }
Q: Reasons to use a sharepoint calendar over outlook I am trying to sell using SharePoint calanders to the business. How would you go about using SharePoint calnders over Outlook. What advantages does it bring over creating outlook events? A: SharePoint calendars doesn't replace the outlook calendars. It's for a different use, especially for Sharing a calendar among several users just with the browser. There are some advantages for the SharePoint, because the calendar is based on a SharePoint list, you can enjoy from all the list capabilities such as the ability to add fields, views, manage permissions, exposure in SharePoint search results, ranking and more.
{ "pile_set_name": "StackExchange" }
Q: Android In-app Billing Issues I am using this tutorial: http://mcondev.wordpress.com/2011/06/26/integrate-in-app-billing-just-3-lines-of-code-in-your-app/. When I get to the last step: checkout.sendCheckoutRequest(purchaseUri.toString(),null); it crashes. What is the purchaseUri for? Thanks A: This purchaseUri is the “In-app Product ID” of your resource on the “market.android.com/publish->Create New In-App Product” options. This string should be set as the “in app product” id. That’s why the “id” is most important. The “In-App Product ID” is how you refer to that particular product. Also, in Security.java dont forget to add your “public key” from your market place account “edit profile” page.
{ "pile_set_name": "StackExchange" }
Q: Show ActionBar in Android PhoneGap project I'm working on an Android PhoneGap solution where I want to use the Native ActionBar to show a few menu options, but somehow the actionbar is not showing. I'm thinking that PhoneGap is hiding it somewhere, but I can't find the solution to unhide it again. I found some posts where they said that in the OnCreate method I have to set the ShowTitle property to true before the super.OnCreate method is called. Tried it like below: super.setBooleanProperty("ShowTitle", true); But above method is deprecated. Also tried it in the config.xml file like below: <preference name="ShowTitle" value="true"/> No luck so far. Also tried it with requestWindowFeature: this.requestWindowFeature(Window.FEATURE_ACTION_BAR); I'm kind of out of options to think how to get this ActionBar visible. I'm using PhoneGap version 3.3.0 And testing it on the emulator with Android 4.0 API level 14 based on the Nexus 4 A: Ok, found it. In my manifest the Activity has the theme set to android:theme="@android:style/Theme.Black.NoTitleBar" removed the theme and the action bar is there.
{ "pile_set_name": "StackExchange" }
Q: How can I scroll to the top/bottom of web page with a three finger gesture? I'd like to use a three finger swipe to scroll to the top or bottom of a web page. Is there a way to make that work? A: BetterTouchTool (free)
{ "pile_set_name": "StackExchange" }
Q: No Online Account in Freya 0.3.2 There is an answered question at Where is the option to add online accounts listed? It certainly isn't under settings in my system! but I don't think the answer is correct. When Elementary Freya was finally released, many tech sites published "what's news" topics on Freya, which mentioned Online Account. So how can I get Online Account working? Thanks. A: This isn't a feature that got into Freya. However looking at a couple of bugreports that target loki(the next version) it seems that it will be available in the next version.
{ "pile_set_name": "StackExchange" }
Q: How do I use PHPMailer? I can't find a simple decent tutorial online I'm trying to send out a Plain/HTML multipart email out and I'm currently using PHP's mail() function. Many people have recommended PHPMailer so I thought I'd give it a go. However, as everything seems to be nowadays, it appears very complicated. I downloaded it and it talks about installing it and configuring MySQL connections and SMTP connections!? All I want to do is use a nice class that will build the MIME emails for me and send them! I understand the SMTP possibilities but it all seems so complex! Is there some way of simply just using it, for example, include a php file (no server installation or re-compiling PHP!) and then just using the class to build and send the email? I'd be very grateful if someone could explain things simply! I'm sure it's possible and I can't believe after my hours of searching there's no really good, simple article about it online. Everything's TOO complicated when I know it doesn't need to be! A: Pretty way (from this link), first extend PHPMailer and set the defaults for your site : require("class.phpmailer.php"); class my_phpmailer extends phpmailer { // Set default variables for all new objects var $From = "[email protected]"; var $FromName = "Mailer"; var $Host = "smtp1.example.com;smtp2.example.com"; var $Mailer = "smtp"; // Alternative to IsSMTP() var $WordWrap = 75; // Replace the default error_handler function error_handler($msg) { print("My Site Error"); print("Description:"); printf("%s", $msg); exit; } // Create an additional function function do_something($something) { // Place your new code here } } Then include the above script where needed (in this example it is named mail.inc.php) and use your newly created my_phpmailer class somewhere on your site: require("mail.inc.php");//or the name of the first script // Instantiate your new class $mail = new my_phpmailer; // Now you only need to add the necessary stuff $mail->AddAddress("[email protected]", "Josh Adams"); $mail->Subject = "Here is the subject"; $mail->Body = "This is the message body"; $mail->AddAttachment("c:/temp/11-10-00.zip", "new_name.zip"); // optional name if(!$mail->Send()) { echo "There was an error sending the message"; exit; } echo "Message was sent successfully"; A: I don't know anything about PHPMailer, but I recommend using Zend_Mail. Here's a simple example with an attachment: $mail = new Zend_Mail(); $mail->setBodyText('This is the text of the mail.'); $mail->createAttachment($myImage, 'image/gif', Zend_Mime::DISPOSITION_INLINE, Zend_Mime::ENCODING_8BIT); $mail->setFrom('[email protected]', 'Some Sender'); $mail->addTo('[email protected]', 'Some Recipient'); $mail->setSubject('TestSubject'); $mail->send(); It probably does everything you want (Attachments, HTML, SMTP-Configuration, ...). By default it uses sendmail, like the mail() function, so you don't have to configure anything like SMTP if you don't need it. It also has very good documentation, so you won't have trouble finding examples. A: Try SwiftMailer instead.
{ "pile_set_name": "StackExchange" }
Q: Does the partition key also have to be part of the primary key? I am partitioning a table based on a column that is not a primary key? I've read some conflicting information today on whether the partition column must be a part of the primary key. My gut says no, but I am not 100% sure. So questions... Must the partition column be part of the primary? Is it recommended one way or the other? Do I have to create an index for the partition key, or does the DBMS do it automatically on its own? A: Not at all. One of the most common scenarios for partitioning is to use a date field, which is totally unrelated to your PK. For instance, if you have a table Orders with the field OrderDate you would most likely partition based on the month and year of OrderDate. When records age out and are no longer relevant you can move those partitions off to an archive table or database so they are no longer processed. Partitioning will work with pretty much any field, but in order for it to work WELL the field(s) you partition on should be used in most, if not all, of your queries. If you don't include your partition keys then you will get essentially an expensive table scan that goes across multiple tables (partitions). EDIT For part 2, I think the answer is no as well. The partition key is used to determine which partition to put the row in, but I don't think an index is maintained. There may be stats in the back end on it though. A: In addition to JNK's answer, you probably should read this article which discusses aligning table partitions and index partitions. There are many types of scenarios where partitioning scheme does exactly follows the primary key's first column - for instance in a data warehouse scenario where the snapshot date of a fact table is usually the partition column as well as the first column in the primary key. But equally, in OLTP environments where the PK is an IDENTITY or other surrogate key, it makes little sense to use this for the partition, since partitioning on arbitrary numbers is not normally terribly useful. In OLTP systems, you also tend to partition by date the most (probably not in the PK), but potentially also regionally or by some kind of organizational division (maybe in the PK if you aren't using a surrogate). But it's not a requirement.
{ "pile_set_name": "StackExchange" }
Q: what is the mel scale? I am not sure I understand what the Mel Scale is. Googling doesn't give me various answers. I seem to be getting the same response again and again. Which would be something like: "The mel scale reflects how people hear musical tone" First of all, does the concert pitch has a specific frequency? So why do we even have a scale stating how do people hear it? I am currently trying to understand how MFCC uses them, and it seems like it maps the frequency to the Mel scale, or there are some filter banks which are applied on the given frames A: To stand on @hotpaw2's answers, think of Mel as one kind of pyscho-acoustic scale, derived from a set of experiments on human subjects, others are Bark & ERB Why have such a scale? Imagine a 100 Hz sine wave playing in your head, .... wait for it to stick ...okay... Good. Imagine now, a 200 Hz sine wave playing ... marinate in it. Good work. Now compare the two, they have some "perceptual distance". Perceptual only because we're using your soft-grey matter as a measuring instrument. Finally, if you were you repeat this experiment with 1100 Hz & 1200 Hz, and again with 10,100Hz and 10,200Hz, your opinion of this percpetual distance might diminish, i.e. 100 & 200 Hz can sound "farther apart" than do 10,100 & 10,200Hz, even though in all cases the differences are equivalent to 100Hz. These pyschoacoustic scales try to capture these distances from low (20Hz) to high frequency (20kHz).
{ "pile_set_name": "StackExchange" }
Q: When given a choice between octane 89 and 93, which should I choose? I just recently got a 2005 Volvo S40 with a turbo engine; I want to take good care of it, so naturally, when the instruction manual recommends 91 octane fuel but says it takes a minimum of 87, I have no problem with buying 91, knowing (or at least believing) that it's better for my engine and improves performance and fuel efficiency compared to just shoving regular unleaded into its tank. I checked online, read a bit about engine knocking and whatnot, and was determined that's what I'd do, and the previous seller also filled it with premium gas so it has been well taken care of thus far. This morning I stopped at a local gas station to refill it for the first time. My fuel octane choices were 87, 89, or 93. Oh no! I probably should have hopped back in my car and went looking for a "normal" gas station, with premium at 91 octane... But instead I just choice 89 and made a mental note to ask this question. Should I have chosen 93? Or would that have been "too much"? Is it better to choose a bit higher or a bit lower? Could one be more harmful than the other to my engine? I'm in the USA if it matters. A: Being in the midst of summer, I may have erred on the side of caution and gone with the 93 but I'm sure the 89 hasn't been harmful to your vehicle if the manual states you can put 87 into it. Since you mentioned knocking, it sounds like you have already done some research. Still, to cover it, the higher rated octane fuel is essentially "harder" to ignite and so is called for in either high compression engines or when using forced induction (turbocharger or supercharger). A lower octane fuel can have the tendency to ignite prematurely which is called knocking or detonation. This can cause many different issues as your pistons and valves will not be at the right positions for the proper engine rotation. Since your car's manual says it will take 87 but recommends 91, most likely it has a knock sensor that when it detects early detonation it changes characteristics of the engine's operation to prevent further knocking. This will prevent damage to the engine, but at the cost of performance and possibly fuel efficiency. The reason I said erring on the side of caution with the 93 for summer is that depending on where your engine really falls in its need for 91 for optimal performance, 89 may or may not trip the knock sensor and cause that degraded state. One factor that will impact it on a turbocharged engine is the charged air temperature, which in the summer is already starting at a higher temperature. A: Just to add to what ManiacZX covered in his answer: On modern turbocharged cars, the ignition computer will prevent knocking, which will prevent damage. You will end up with a bit less power, and a bit less fuel mileage. I have never heard of a car being damaged by using a higher octane fuel than needed - in fact, many gas companies try temp people to do just that with their advertizing when it's not needed. Next time you need 91 octane, but only have a choice between 89 and 93, fill it with 1/2 of each - this will give you what's needed.
{ "pile_set_name": "StackExchange" }
Q: Redirect www to https after messing up config files I got an SSL certificate from Let's Encrypt and after messing up the installation with bad selections at the installation process, I believe I got some broken code in the 000-default.conf file, because currently only if I type example.com it redirects me to https://example.com/, but when I type www.example.com it leaves me at www.example.com without HTTPS. this is how 000-default.conf currently looks like: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For example the # following line enables the CGI configuration for this host only # after it has been globally disabled with "a2disconf". #Include conf-available/serve-cgi-bin.conf RewriteEngine on RewriteCond %{SERVER_NAME} =example.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> # vim: syntax=apache ts=4 sw=4 sts=4 sr noet Edit: Let's Encrypt created more files inside sites-available, alongside 000-default.conf, so I assume you need all them to work together, such as the following file: 000-default-le-ssl.conf: <IfModule mod_ssl.c> <VirtualHost *:443> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For example the # following line enables the CGI configuration for this host only # after it has been globally disabled with "a2disconf". #Include conf-available/serve-cgi-bin.conf ServerName example.com Include /etc/letsencrypt/options-ssl-apache.conf ServerAlias www.example.com SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem </VirtualHost> </IfModule> I have certificate for both www.example.com and example.com. What do I need to edit to prevent www.example.com access to regular HTTP and redirect it to HTTPS? I can't find out Thanks A: You'll want to include the server name and alias to your virtual host <VirtualHost *:80> ServerAdmin webmaster@localhost ServerName website.com ServerAlias www.website.com RewriteEngine On RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,QSA,R=permanent] </VirtualHost> This will force both urls to be redirected. Note that your rule used to be limited to non-www url.
{ "pile_set_name": "StackExchange" }
Q: What size expansion gap should I leave between my wall a hardwood floating floor? How much space to leave between wall and hardwood floating floor? This is a unique floor. Each board is solid bamboo (never thought I'd say that) but they snap together the same way that an engineered wood floor does. This is still a floating floor though, each piece is just much heavier since it's solid. I'm wondering how much of an expansion gap I should leave between my wall? I've read anywhere from a 1/4" (on each side for a total of 1/2") or 1/2" (on each side for a total of 1"). As part of that, should the moisture barrier go all the way to the wall or should I keep that the same distance from the wall as the wood/bamboo? A: Your vapor barrier needs to extend beyond the edges of the floor to prevent moisture from getting to the floor. Install in accordance to manufacturer's recommendations. The expansion gap needed also depends on the manufacturer's recommendations - different materials expand at different degrees. The point of the gap is to give it room so it doesn't end up buckling. If you can't find a solid recommendation then use 1/2" for the maximum protection - and if the trim you install doesn't cover the gap, use quarter round.
{ "pile_set_name": "StackExchange" }
Q: How can I make a list horizontally scrollable without items going to the second line? I have a list of items: <div class="dates-bar"> <ul> <li>1</li> <li>...</li> <li>30</li> </ul> </div> I need this bar to be in a single line. I don't know how to achieve that. I have tried the following: .dates-bar { width: 100%; overflow-x: scroll; } .dates-bar ul { width: 500%; } .dates-bar li { display: inline-block; margin: 0 10px; } The problem here is that, if the numbers items cross get to the end of the bar, it will wrap the items to the second line and if the number of items is small, there will be a huge gap at the end of this bar. With some tweaking I can fix the latter one. However, I don't know what to do, so that the items don't go over the second line. A: .dates-bar{ width:auto; max-width:100% overflow-x: atuo; } .dates-bar ul{ white-space: nowrap; } The whitespace property is the missing ingredient.
{ "pile_set_name": "StackExchange" }
Q: jquery ui datepicker allows past dates? How can I allow past dates as deep as possible in jquery ui datepicker? $( ".date-picker" ).datepicker({ dateFormat: "yy-mm-dd" }); these answers I found seem that you have to set a date in the past to start. But what if I want to allow the dates which were very very far in the past, such as in 1800s? $('.date-picker').datePicker({startDate:'01/01/2000'}); $('.date-picker').datePicker({startDate: (new Date()).addYears(-1).asString()}); Is it possible? A: Set the changeYear parameter to true to display the year drop-down; this make the year selection easier. Also set the yearRange parameter to specify the range of years; default is current year +/- 10 years: $("#datepicker1").datepicker({ changeMonth: true, changeYear: true, yearRange: "1:c+10" // 1AD to 2013AD + 10 }); Demo here
{ "pile_set_name": "StackExchange" }
Q: Python: get the most maximum values from dictionary I have a dictionary {u'__': 2, u'\u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0430': 1, u'\u041f\u043e\u0447\u0435\u043c\u0443': 1, u'\u041d\u0430\u043c': 1, u'\u043e\u0434\u0438\u043d': 1, u'\u0441\u043e\u0432\u0435\u0442\u0430\u043c\u0438': 1, u'\u041f\u0440\u043e\u0438\u0437\u043d\u0435\u0441\u0442\u0438': 1, u'\u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e,': 1, u'\u0432\u044b\u0445\u043e\u0434\u044f\u0449\u0435\u043c\u0443': 1, u'\u043d\u0430\u0448\u0435\u0439': 2, u'\u0441\u0438\u0441\u0442\u0435\u043c\u0443': 1, u'\u0441\u0431\u043e\u0440\u0430': 1, u'\u0434\u0430\u043b\u044c\u043d\u0435\u0439\u0448\u0435\u043c.': 1, u'[![\u042f\u043d\u0434\u0435\u043a\u0441](//yastatic.net/lego/_/la6qi18z8lwgnzdsar1qy1gwcwo.gif)](//www.yandex.ru)': 1, u'\u0412\u0430\u043c': 1, u'\u0430': 102, u'\u0432\u0438\u0440\u0443\u0441\u043e\u0432,': 1, u'\u043e\u0447\u0435\u043d\u044c': 1, u'\u0438': 90, u'\u0440\u0430\u0437.': 1, u'[cureit](http://www.freedrweb.com/?lng=ru)': 1, u'\u043d\u0435': 9, u'\u0438\u043b\u0438': 2, u'\u0441\u043f\u0435\u0446\u0438\u0430\u043b\u044c\u043d\u043e': 1, u'\u043d\u0430': 11, u'\u043d\u043e': 17, u'\u0443\u0441\u0442\u0430\u043d\u043e\u0432\u043b\u0435\u043d\u044b': 1, u'\u041c\u043e\u0436\u0435\u0442': 1, u'\u0432\u0430\u0448': 5, u'\u0445\u043e\u0442\u0438\u0442\u0435': 1, u'[\u0444\u043e\u0440\u043c\u043e\u0439': 1, u'\u0432\u044b': 5, u'\u0446\u0435\u043b\u0435\u0439': 1, u'\u0441\u0438\u043c\u0432\u043e\u043b\u044b': 3, u'\u0415\u0441\u043b\u0438': 2, u'\u0422\u0430\u043a\u0436\u0435': 1, u'\u0432\u043e\u0437\u043d\u0438\u043a\u043b\u0438': 1, u'\u0434\u0430\u043d\u043d\u043e\u0433\u043e': 1, u'**\u0412': 1, u'\u0437\u0430\u043f\u0440\u043e\u0441\u044b),': 1, u'\u041f\u043e\u043c\u043e\u0449\u0438](//help.yandex.ru/common/?id=1111120).': 1, u'\u042f\u043d\u0434\u0435\u043a\u0441\u0443': 1, u'\u0431\u0440\u0430\u0443\u0437\u0435\u0440\u0435': 2, u'\u0432': 69, u'\u0441\u0435\u0440\u0432\u0438\u0441\u043e\u043c': 1, u'\u043f\u043e\u043f\u0440\u043e\u0431\u0443\u0439\u0442\u0435': 1, u'\u0443\u0442\u0438\u043b\u0438\u0442\u043e\u0439': 1, u'\u0430\u0432\u0442\u043e\u043c\u0430\u0442\u0438\u0447\u0435\u0441\u043a\u0438\u0435': 4, u'\u0432\u043e\u043f\u0440\u043e\u0441': 1, u'\u0430\u0432\u0442\u043e\u043c\u0430\u0442\u0438\u0447\u0435\u0441\u043a\u0438\u0435.': 1, u'\u043f\u043e': 24, u'##': 1, u'\u0434\u043e\u0441\u0442\u0443\u043f': 1, u'\u0443': 37, u'(\u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440,': 1, u'\u0437\u0430\u043f\u043e\u043c\u043d\u0438\u0442\u044c': 1, u'\u2192': 1, u'\u042f\u043d\u0434\u0435\u043a\u0441': 4, u'\u0441\u043b\u0443\u0447\u0430\u0435': 2, u'\u043f\u043e\u0445\u043e\u0436\u0438': 1, u'\u043a\u0430\u043f\u0447\u0435\u0439': 1, u'\xab\u041e\u0442\u043f\u0440\u0430\u0432\u0438\u0442\u044c\xbb.': 1, u'#': 3, u'cookies**.': 1, u'\u0431\u0443\u0434\u0435\u0442': 1, u'\u0427\u0442\u043e\u0431\u044b': 2, u'\u0441\u0432\u044f\u0437\u0438](//feedback2.yandex.ru/captcha/).': 1, u'\u043f\u0440\u043e\u0432\u0435\u0440\u0438\u0442\u044c': 1, u'\u0434\u0440\u0443\u0433\u043e\u043c\u0443': 1, u'\u043f\u0440\u043e\u0431\u043b\u0435\u043c\u044b': 1, u'\u0432\u0430\u043c,': 1, u'\u0441\u043b\u0435\u0432\u0430![](//yastatic.net/lego/_/la6qi18z8lwgnzdsar1qy1gwcwo.gif)\u041e\u0442\u043f\u0440\u0430\u0432\u0438\u0442\u044c': 1, u'\u043c\u043e\u0433\u0443\u0442': 1, u'\u0432\u044b\u0445\u043e\u0434\u044f\u0449\u0438\u0445': 1, u'\u0432\u0440\u0435\u043c\u0435\u043d\u043d\u043e': 1, u'\u0441\u043b\u0443\u0436\u0431\u0435': 1, u'ip-\u0430\u0434\u0440\u0435\u0441\u0430,': 1, u'\u043f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430,': 2, u'\u0430\u043d\u0442\u0438\u0432\u0438\u0440\u0443\u0441\u043d\u043e\u0439': 1, u'\u0432\u0430\u043c\u0438': 1, u'\u0435\u0433\u043e': 4, u'\u0437\u0430\u0434\u0430\u0442\u044c': 1, u'\u0442\u0430\u043a': 1, u'\u0440\u0430\u0437': 3, u'\u0441\u0435\u0442\u044c': 1, u'\u0441\u0442\u043e\u0438\u0442': 1, u'cookies,': 1, u'ip-\u0430\u0434\u0440\u0435\u0441\u0430.': 1, u'\u0437\u0430\u0440\u0430\u0436\u0435\u043d': 1, u'\u043d\u0430\u0436\u043c\u0438\u0442\u0435': 1, u'\u0437\u0430\u0431\u043b\u043e\u043a\u0438\u0440\u043e\u0432\u0430\u0442\u044c': 1, u'\u0434\u043b\u044f': 2, u'\u043e\u0439...': 1, u'[\u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0435': 1, u'\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u044e,': 1, u'\u0438\u0445.': 1, u'\u044d\u0442\u0438\u0445': 1, u'\u043f\u0440\u043e\u0434\u043e\u043b\u0436\u0438\u0442\u044c': 1, u'\u043e\u0431': 9, u'\u043f\u043e\u0438\u0441\u043a,': 1, u'\u0440\u043e\u0434\u0443': 1, u'\u0434\u043e\u0432\u043e\u043b\u044c\u043d\u043e': 1, u'\u0412': 6, u'\u0441\u043b\u0443\u0447\u0438\u043b\u043e\u0441\u044c?': 1, u'\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u0435\u0439,': 1, u'\u0432\u044b\u043d\u0443\u0436\u0434\u0435\u043d\u044b': 1, u'\u043f\u043e\u043b\u0435': 1, u'\u043f\u043e\u0441\u0442\u0443\u043f\u0438\u0432\u0448\u0438\u0435': 1, u'\u043a\u0430\u0440\u0442\u0438\u043d\u043a\u0438': 1, u'\u043a': 30, u'\u0438\u0434\u0435\u043d\u0442\u0438\u0444\u0438\u0446\u0438\u0440\u043e\u0432\u0430\u0442\u044c': 1, u'\u0438\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u044e\u0449\u0435\u0439': 1, u'\u041d\u0435\u0432\u0435\u0440\u043d\u043e,': 1, u'ip.': 1, u'\u0434\u0440\u0443\u0433\u0438\u0445': 1, u'\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0442\u0435\u043b\u044c\u043d\u043e': 1, u'\u043e\u0442\u043a\u043b\u044e\u0447\u0435\u043d\u044b': 1, u'\u0440\u0430\u0437\u0440\u0430\u0431\u043e\u0442\u0430\u043d\u043d\u044b\u043c': 1, u'\u043d\u0430\u043b\u0438\u0447\u0438\u0435': 1, u'\u0432\u0432\u0435\u0434\u0438\u0442\u0435': 1, u'\u0434\u043e\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u044f,': 1, u'\u043f\u043e\u0441\u043b\u0435': 1, u'\u0432\u0430\u0448\u0435\u0433\u043e': 2, u'\u043f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u043e': 1, u'![](//mc.yandex.ru/watch/10630330?ut=noindex)': 1, u'\u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440\u0430,': 1, u'\u0440\u0435\u043a\u043e\u043c\u0435\u043d\u0434\u0443\u0435\u043c': 2, u'\u0436\u0430\u043b\u044c,': 1, u'\u0432\u0432\u043e\u0434\u0430': 1, u'\u043e\u0442\u043a\u043b\u044e\u0447\u0438\u0442\u044c': 1, u'\u043e\u0442': 9, u'\u0437\u0430\u0434\u0430\u0432\u0430\u0442\u044c': 1, u'\u0447\u0435\u0433\u043e': 1, u'\u043d\u0430\u043f\u0440\u0438\u043c\u0435\u0440,': 2, u'\u0437\u0430\u043f\u0440\u043e\u0441\u044b,': 1, u'\u044d\u0442\u043e\u043c': 3, u'\u0437\u043d\u0430\u0435\u0442\u0435': 1, u'\u044d\u0442\u043e\u0439': 1, u'\u0435\u0449\u0451': 1, u'\u0444\u0430\u0439\u043b\u044b': 1, u'\u043a\u043e\u0442\u043e\u0440\u044b\u0435': 1, u'\u0441\u043c\u043e\u0436\u0435\u0442': 1, u'\u0434\u043e\u043b\u0433\u043e.': 1, u'\u043d\u0435\u043e\u0431\u0445\u043e\u0434\u0438\u043c\u043e': 2, u'\u041f\u043e': 3, u'\u0434\u0435\u044f\u0442\u0435\u043b\u044c\u043d\u043e\u0441\u0442\u0438': 1, u'\u043e\u0442\u043b\u0438\u0447\u0430\u0442\u044c': 1, u'\u0432\u0430\u0448\u0435\u043c': 2, u'\u043e\u0442\u043f\u0440\u0430\u0432\u043b\u044f\u0442\u044c': 1, u'\u0432\u0432\u0435\u0441\u0442\u0438': 1, u'\u0437\u0430\u043f\u043e\u043c\u043d\u0438\u043c': 1, u'\u0432\u0430\u0441': 4, u'![](https://www.yandex.ru/captchaimg?ahr0chm6ly9zlmnhchrjageuewfuzgv4lm5ldc9pbwfnzt9rzxk9zdm5y2x2ukryv3ryogdaclb0bkjvevbntxjlq2dnrey,_0/1476178373/d4dbeb7c6b14f42a9352a0c4a457922c_1d31938b6816fc51509079a461b5ae7a)': 1, u'\u0432\u0438\u0440\u0443\u0441\u043d\u043e\u0439': 2, u'\u0412\u043e\u0437\u043c\u043e\u0436\u043d\u043e,': 2, u'\u043f\u043e\u0434\u0434\u0435\u0440\u0436\u043a\u0438,': 1, u'\u0437\u0430\u043f\u0440\u043e\u0441\u044b': 5, u'\u043e\u0431\u0440\u0430\u0442\u043d\u043e\u0439': 1, u'\u0441': 77, u'\u0444\u043e\u0440\u043c\u0443,': 1, u'\u043a\u043e\u043c\u043f\u044c\u044e\u0442\u0435\u0440': 2, u'\u043f\u043e\u0441\u0442\u0443\u043f\u0430\u044e\u0442': 1, u'\u0432\u0430\u043c': 5, u'\u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u043e\u0439,': 1, u'\u0447\u0442\u043e': 1, u'\u0432\u043e\u0441\u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u044c\u0441\u044f': 1, u'\u043f\u043e\u0438\u0441\u043a\u0443.': 2, u'\u0431\u044b\u0442\u044c,': 1, u'\u0441\u043c\u043e\u0436\u0435\u043c': 1, u'\u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435': 1, u'\u0432\u043e\u0441\u043f\u043e\u043b\u044c\u0437\u0443\u0439\u0442\u0435\u0441\u044c': 2, u'\xabdr.web\xbb.': 1, u'\u0432\u043a\u043b\u044e\u0447\u0438\u0442\u044c': 1, u'[\u042f\u043d\u0434\u0435\u043a\u0441.xml](//xml.yandex.ru).': 1, u'\u0438\u043d\u0444\u043e\u0440\u043c\u0430\u0446\u0438\u0438.': 1, u'\u043f\u0440\u0438\u0447\u0438\u043d\u0435': 1, u'\u0431\u0435\u0441\u043f\u043e\u043a\u043e\u0438\u0442\u044c': 1, u'\u043c\u044b': 3, u'\u043e\u0434\u043d\u043e\u0433\u043e': 1, u'\u043f\u0440\u0438\u043d\u0430\u0434\u043b\u0435\u0436\u0430\u0442': 1} I need to convert it encoding and get dictionary with 10 the biggest values. I try to use print max(dict.iteritems(), key=operator.itemgetter(10))[0] But it returns me nothing. But how convert this string I don't know. I didn't find the way to do it. A: max() can only ever return a single value. Use a Counter: from collections import Counter counter = Counter(yourdictionary) print(counter.most_common(10))
{ "pile_set_name": "StackExchange" }
Q: How to mirror a reddit moderator page with python I'm trying to create a mirror of specific moderator pages (i.e. restricted) of a subreddit on my own server, for transparency purposes. Unfortunately my python-fu is weak and after struggling a bit with the reddit API, its python wrapper and even some answers in here, I'm no closer to having a working solution. So what I need to do is login to reddit with a specific user, access a moderator only page and copy its html to a file on my own server for others to access The problem I'm running into is that the API and its wrapper is not very well documented so I haven't found if there's a way to retrieve a reddit page after logging in. If I can do that, then I could theoretically copy the result to a simple html page on my server. When trying to do it outside the python API, I can't figure out how to use the built-in modules of python to login and then read a restricted page. Any help appreciated. A: I don't use PRAW so I'm not sure about that, but if I were to do what you wanted to do, I'd do something like: login, save the modhash, grab the HTML from the url of the place you want to go: It also looks like it's missing some CSS or something when I save it, but it's recognizable enough as it is. You'll need the requests module, along with pprint and json import requests, json from pprint import pprint as pp2 #---------------------------------------------------------------------- def login(username, password): """logs into reddit, saves cookie""" print 'begin log in' #username and password UP = {'user': username, 'passwd': password, 'api_type': 'json',} headers = {'user-agent': '/u/STACKOVERFLOW\'s API python bot', } #POST with user/pwd client = requests.session() r = client.post('http://www.reddit.com/api/login', data=UP) #if you want to see what you've got so far #print r.text #print r.cookies #gets and saves the modhash j = json.loads(r.text) client.modhash = j['json']['data']['modhash'] print '{USER}\'s modhash is: {mh}'.format(USER=username, mh=client.modhash) #pp2(j) return client client = login(USER, PASSWORD) #mod mail url url = r'http://www.reddit.com/r/mod/about/message/inbox/' r = client.get(url) #here's the HTML of the page pp2(r.text)
{ "pile_set_name": "StackExchange" }
Q: Mapbox JS Marker Creation On Click I am currently using mapbox js in conjunction with a satellite imagery API and I am wondering how to display a very simple marker of the last click (from the user) on the map. Ideally when the user clicks in the map it would be display a small semi-transparent square which would correspond to the zoomed in area being displayed by the satellite API. There's a ton of information about interacting with current markers that were created beforehand, but I want to dynamically create a marker on click that only lives until the next click. It would be something like below, only with a smaller radius. A: If you are just looking to add the circle and remove it on the next mouseclick, something like this would work: L.mapbox.accessToken = 'pk.eyJ1IjoiY2NhbnRleSIsImEiOiJjaWVsdDNubmEwMGU3czNtNDRyNjRpdTVqIn0.yFaW4Ty6VE3GHkrDvdbW6g'; var map = L.mapbox.map('map', 'mapbox.streets').setView([38.91338, -77.03236], 16); streetsBasemap = L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiY2NhbnRleSIsImEiOiJjaWVsdDNubmEwMGU3czNtNDRyNjRpdTVqIn0.yFaW4Ty6VE3GHkrDvdbW6g', { maxZoom: 18, minZoom: 6, zIndex: 1, id: 'mapbox.streets' }).addTo(map); map.on('click', addMarker); function addMarker(e){ if (typeof circleMarker !== "undefined" ){ map.removeLayer(circleMarker); } //add marker circleMarker = new L.circle(e.latlng, 200, { color: 'red', fillColor: '#f03', fillOpacity: 0.5 }).addTo(map); } body { margin:0; padding:0; } #map { position:absolute; top:0; bottom:0; width:100%; } <!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>Single marker</title> <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' /> <script src='https://api.mapbox.com/mapbox.js/v2.4.0/mapbox.js'></script> <link href='https://api.mapbox.com/mapbox.js/v2.4.0/mapbox.css' rel='stylesheet' /> <style> </style> </head> <body> <div id='map'></div> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: Defaulting a date field in ColdFusion I want to default a date input control to today <cfoutput> <input type="date" class="form-control" name="dtStart" value="#LSDateFormat(now(), 'mm/dd/yyyy')#" required /> <br /> My Date: #LSDateFormat(now(), 'mm/dd/yyyy')# </cfoutput> All I get out of this is Is there a way to get it to default to today? A: You can use code like below ( Set mask as 'yyyy-mm-dd' ) , It will show default value as the current date for your input date field. <cfoutput> <input type="date" class="form-control" name="dtStart" value="#LSDateFormat(now(),'yyyy-mm-dd')#" required /> <br /> My Date: #LSDateFormat(now(), 'mm/dd/yyyy')# </cfoutput> Code result as screenshot
{ "pile_set_name": "StackExchange" }
Q: Cakephp switch database connection in controller for CakePHP 2.2.5 I am trying to get data from two different databases in a controller app/Controller/UsersController.php my db connections are declared in the database.php $default = array( ... 'database' => 'test' ... ); $test = array( ... 'database' => 'test1' ... ); and in my display() action: public function display() { $this->set('defaultUsers', $this->User->find('all')); $this->User->schemaName = 'test1'; $this->User->cacheQueries = false; $this->set('testUsers', $this->User->find('all')); } This would allow me to grab data from two different sources successfully, however problem is that these two databases have to have the same password otherwise it wouldn't work. I've tried other solutions found here and other sites. like: changing $this->User->useDbConfig = 'test' and $this->User->cacheQueries = false would still give me the same dataset; using ConnectionManager::getDataSource() and setConfig(), create(), drop(), setDataSource(), etc. None of those worked and some don't even exist any more. Any help would be greatly appreciated! As I need to the same codebase for two similar applications a.k.a two databases. Thanks! A: You probably need to use 'setDataSource()' to switch the datasource/connection as this will reset the 'cached' schema etc on the Model; public function display() { $this->set('defaultUsers', $this->User->find('all')); $this->User->setDataSource('test1'); $this->set('testUsers', $this->User->find('all')); } If you need to access data from both databases throughout your application, another option is to create two User models, one with 'test' as datasource, and another that uses 'test1' as datasource. This way you don't have to switch the data-source all the time Example: class TestUser extends AppModel { public $useTable = 'users'; // name of the database table public $useDbConfig = 'test1'; // name of the database configuration in database.php } On a further note: The '$test' database-config is pre-configured database-connection that is used for running CakePHP Unit-tests. You might consider creating your own database-connection name
{ "pile_set_name": "StackExchange" }
Q: Java: Help with a RegEx So, I want to replace all & in the following string with a single &. These & can be separated by one or more spaces. I have a sample input string and a code snippet of what I have. Input string: a& & &&& & b Here is what I have so far: String foo = "a& & &&& & b".replaceAll("(\\s*&+\\s*&\\s*)", "&"); System.out.println(foo); // prints: "a&&b" // expected: "a&b" I'm not sure why two & are ending up in the result. Any hlep would be appreciated. Thanks! A: why make it more complicated than it needs to be "(\\s*&)+\\s*" one or more (sequences of & preceded by zero or more whitespace) followed by zero or more whitespace A: Try:String foo = "a& & &&& & b".replaceAll("(\\s*&[\\s&]*)", "&");
{ "pile_set_name": "StackExchange" }
Q: DNS query using Google App Engine socket I'm trying to use the new socket support for Google App Engine in order to perform some DNS queries. I'm using dnspython to perform the query, and the code works fine outside GAE. The code is the following: class DnsQuery(webapp2.RequestHandler): def get(self): domain = self.request.get('domain') logging.info("Test Query for "+domain) answers = dns.resolver.query(domain, 'TXT', tcp=True) logging.info("DNS OK") for rdata in answers: rc = str(rdata.exchange).lower() logging.info("Record "+rc) When I run in GAE I get the following error: File "/base/data/home/apps/s~/one.366576281491296772/main.py", line 37, in post return self.get() File "/base/data/home/apps/s~/one.366576281491296772/main.py", line 41, in get answers = dns.resolver.query(domain, 'TXT', tcp=True) File "/base/data/home/apps/s~/one.366576281491296772/dns/resolver.py", line 976, in query raise_on_no_answer, source_port) File "/base/data/home/apps/s~/one.366576281491296772/dns/resolver.py", line 821, in query timeout = self._compute_timeout(start) File "/base/data/home/apps/s~/one.366576281491296772/dns/resolver.py", line 735, in _compute_timeout raise Timeout Which is raised by dnspython when no answer is returned within the time limit. I've raised the timelimit to 60 seconds, and DnsQuery is a task, but still getting the same error. Is there any limitation in Google App Engine socket implementation, which prevents the execution of DNS requests ? A: This is a bug and will be fixed ASAP. As a workaround, pass in the source='' argument to dns.resolver.query. tcp=True is not necessary.
{ "pile_set_name": "StackExchange" }
Q: Resizeing a crystal report I have one crystal report. In this report I have 10 sections in report footer. report footer1 .... report footer10; Every section contains data. I have suppress formula at each section base on data. Ex. this formula is for one of my section " {#RTotal8} = 0 " So until here every thing is ok. If I don't have data in each section, that section does not appear it hides. But if every 10 sections hide or most of them, I have white space. I want for each section that hide, my report resize. (I want default size with consider of all section, and if all section appear so we have no white space, but if each section hide i want my report resize too) A: You can suppress the blank section In section expert there is option to suppress blank section of the report
{ "pile_set_name": "StackExchange" }
Q: jQuery/CSS script change button color based on time of day I have a a href button that I need to hide depending on the time of day or changed the background color like this: <a class="button not-active " href="updateScheduleRequest.php?slotid=4&amp;timeremain=120&amp;current_date=2015-08-28&amp;empnum=107">Assign Slot 4</a> My CSS is configured as: .button { } /* daytime */ .day { background-color:#e0d0b7 !important; } /* Sunset */ .sunset { background-color:#887f70 !important; } /* Nightime */ .night { display:hidden !important; } And then my jQuery is broken out to handle the time of day like this but it is not making any changes to the button at all? What am I missing? // Change background depending on user's time function applyclass() { var d = new Date(); var n = d.getHours(); if (n > 19) // If time is 7PM or later apply night theme to 'body' $('button').addClass('night'); else if (n > 16 && n < 19) // If time is between 4PM – 7PM sunset theme to 'body' $('button').addClass('sunset'); else // Else use 'day' theme $('button').addClass('day'); } window.onload = applyclass; A: You may consider using a switch statement instead of if/else if/else. It tidies up the code a bit: function applyclass() { var d = new Date(); var n = d.getHours(); switch(true) { case (n > 19) : buttonClass = 'night'; break; case (n > 16 && n < 19) : buttonClass = 'sunset'; break; default: buttonClass = 'day'; } $('.button').addClass(buttonClass); } Also, consider styling the .button element with default styles (like those in the 'day' class) and then only apply an additional class when necessary to override those styles. It's simpler than relying on a modifier class for each and every case. Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: Can I use a plural noun before "on of the"? Is it correct to use a plural noun before "one of the" and in the following sentence should I use "are" or "would be"? if the sentence is incorrect please let me know the correct version. Participating in extracurricular activities such as sport events and being a proactive student to promote my university in terms of attending conferences and meetings to talk about the features of my university are(or would be) one of my favorite activities. A: No, you should not use plurals with "one of". Instead you could say: A and B are two of my favorite things. A and B are some of my favorite things. There can be exceptions to the above rule when two or more things are treated collectively as one group. For example: Fish and chips is one of my favorite foods. As for "are" vs "would be", that depends on your intended meaning. "Are" is the present tense, while "would be" is a conditional. If you do not need to indicate any uncertainty or hypothetical context, then simply use "are".
{ "pile_set_name": "StackExchange" }
Q: Sagemaker Hyperparameter Optimization XGBoost I am trying to build a hyperparameter optimization job in Amazon Sagemaker, in python, but something is not working. Here is what I have: sess = sagemaker.Session() xgb = sagemaker.estimator.Estimator(containers[boto3.Session().region_name], role, train_instance_count=1, train_instance_type='ml.m4.4xlarge', output_path=output_path_1, base_job_name='HPO-xgb', sagemaker_session=sess) from sagemaker.tuner import HyperparameterTuner, IntegerParameter, CategoricalParameter, ContinuousParameter hyperparameter_ranges = {'eta': ContinuousParameter(0.01, 0.2), 'num_rounds': ContinuousParameter(100, 500), 'num_class': 4, 'max_depth': IntegerParameter(3, 9), 'gamma': IntegerParameter(0, 5), 'min_child_weight': IntegerParameter(2, 6), 'subsample': ContinuousParameter(0.5, 0.9), 'colsample_bytree': ContinuousParameter(0.5, 0.9)} objective_metric_name = 'validation:mlogloss' objective_type='minimize' metric_definitions = [{'Name': 'validation-mlogloss', 'Regex': 'validation-mlogloss=([0-9\\.]+)'}] tuner = HyperparameterTuner(xgb, objective_metric_name, objective_type, hyperparameter_ranges, metric_definitions, max_jobs=9, max_parallel_jobs=3) tuner.fit({'train': s3_input_train, 'validation': s3_input_validation}) And the error I get is: AttributeError: 'str' object has no attribute 'keys' The error seems to come from the tuner.py file: ----> 1 tuner.fit({'train': s3_input_train, 'validation': s3_input_validation}) ~/anaconda3/envs/python3/lib/python3.6/site-packages/sagemaker/tuner.py in fit(self, inputs, job_name, **kwargs) 144 self.estimator._prepare_for_training(job_name) 145 --> 146 self._prepare_for_training(job_name=job_name) 147 self.latest_tuning_job = _TuningJob.start_new(self, inputs) 148 ~/anaconda3/envs/python3/lib/python3.6/site-packages/sagemaker/tuner.py in _prepare_for_training(self, job_name) 120 121 self.static_hyperparameters = {to_str(k): to_str(v) for (k, v) in self.estimator.hyperparameters().items()} --> 122 for hyperparameter_name in self._hyperparameter_ranges.keys(): 123 self.static_hyperparameters.pop(hyperparameter_name, None) 124 AttributeError: 'list' object has no attribute 'keys' A: Your arguments when initializing the HyperparameterTuner object are in the wrong order. The constructor has the following signature: HyperparameterTuner(estimator, objective_metric_name, hyperparameter_ranges, metric_definitions=None, strategy='Bayesian', objective_type='Maximize', max_jobs=1, max_parallel_jobs=1, tags=None, base_tuning_job_name=None) so in this case, your objective_type is in the wrong position. See the docs for more details.
{ "pile_set_name": "StackExchange" }
Q: How closely grounded is Suhrawardis Illuminationism in the Qur'an? Suhrawardi developed a metaphysics of light - illuminationism - one aspect of which is to privilege the intuition over the intellect (reason) in understanding. Light being the condition by which we see without intellectual effort; it is the orientation of the visible. Genesis, in the Bible opens with the command 'let there be light; and the Injil is a prophetic book in the tradition of Islam, but generally seen to be corrupted. Is there a similar commandment in the Qur'an? A: Suhrewardi's Metaphysics of Lights was an important stride in development of Islamic philosophical legacy. His both ontological and epistemological innovations -- accordingly explanation of existence by a substantial analogy with workings and characteristics of light, and the idea of superiority of intuitive knowledge over reason -- were later adopted by Mulla Sadra who in turn made a greater stride by reconciling Suhrewardian Illuminationism with Peripatetism to form his synthetic school of Transcendent Philosophy. Mulla Sadra paid equal regard to reason and intuition and considered them two irreplaceable and inseparable means of obtaining knowledge. But as for your question, drawing analogy between existence/knowledge and light does find a lot of references in the Quran and Hadith; most notable and impressive is the verse 35 of Surat un-Nur (a Sura which actually means Light) that exhibits an expressive Illuminationist theme: God is the Light of the heavens and the earth. The allegory of His light is that of a pillar on which is a lamp. The lamp is within a glass. The glass is like a brilliant planet, fueled by a blessed tree, an olive tree, neither eastern nor western. Its oil would almost illuminate, even if no fire has touched it. Light upon Light. God guides to His light whomever He wills. God thus cites the parables for the people. God is cognizant of everything. (24:35) Another example is found in Surat ul-An'am: Is he who was dead, then We gave him life, and made for him a light by which he walks among the people, like he who is in total darkness, and cannot get out of it? Thus the doings of disbelievers are made to appear good to them. (6:122) Another interesting example can be seen in Surat ul-Baqara God is the Lord of those who believe; He brings them out of darkness and into light. As for those who disbelieve, their lords are the evil ones; they bring them out of light and into darkness; these are the inmates of the Fire, in which they will abide forever. (2:257) Among the hadiths, I can now only think of a famous one by the Holy Prophet which I think appears only in Shiite sources but I'm not sure. It reads: Knowledge is a light that is granted by Allah to whoever He desires. To summarize, the concept of light in Islamic sources similar to Suhrawardi's application is associated with concepts of perfection such as Allah, faith, guidance and goodness; while darkness is associated with their opposites such as Satan, disbelief, mislead and evil.
{ "pile_set_name": "StackExchange" }
Q: MySQL YEAR Comparison Years ago, I wrote a query and now while going back through some of this old code I'm trying to figure out why I did it the way it had been done. The intent, as far as I can tell, was to simply extract the year from a UNIX timestamp. Can anyone tell me what the benefit might have been to use: YEAR(DATE_ADD(DATE_SUB(DATE_ADD(FROM_UNIXTIME( 0 ), INTERVAL FullDate SECOND), INTERVAL @@session.time_zone HOUR_MINUTE), INTERVAL '08:00' HOUR_MINUTE)) Instead of simply: DATE_FORMAT(FROM_UNIXTIME(FullDate), '%Y') A: It looks like you were trying to compensate for whatever the current time zone was and then output the (year of the) current time in the timezone UTC+8:00 (countries this applies to from Wikipedia). So DATE_ADD(FROM_UNIXTIME( 0 ), INTERVAL FullDate SECOND) gives you the current time, in the current time zone; the DATE_SUB(..., INTERVAL @@session.time_zone HOUR_MINUTE) converts that to UTC, and DATE_ADD(..., INTERVAL '08:00' HOUR_MINUTE) then converts the time to UTC+8:00. If you didn't want to make that timezone conversion, then DATE_FORMAT(FROM_UNIXTIME(FullDate), '%Y') will do the job, as in fact would FROM_UNIXTIME(FullDate, '%Y') or YEAR(FROM_UNIXTIME(FullDate))
{ "pile_set_name": "StackExchange" }
Q: Ionic 3 - Scroll issue I am doing an Ionic 3 app and on some pages there is no scroll, like this page : History.html <ion-card *ngFor="let h of History; let i=index" text-wrap (click)="toggleGroup(i)" [ngClass]="{active: isGroupShown(i)}" class="HistoryPage"> <ion-card-header> <span class="title">{{h.nom_commun}}</span> <span class="date">{{h.date_signalement}}</span> <button (click)="openPage()" class="edit"> <ion-icon large name="create" color="mainColor" class="edit"></ion-icon> </button> </ion-card-header> <ion-card-content> <ion-icon color="success" item-right [name]="isGroupShown(i) ? 'arrow-dropdown-circle' : 'arrow-dropright-circle'" color="mainColor"></ion-icon> <br /> <div *ngIf="isGroupShown(i)"> <div class="up"> <ion-slides class="Pictures" slidesPerView="3"> <ion-slide> <img src="{{h.image}}" /> </ion-slide> <ion-slide> <img src="../assets/img/rossignol3.jpg" /> </ion-slide> <ion-slide> <img src="../assets/img/rossignol4.jpg" /> </ion-slide> <ion-slide> <img src="{{h.pictures}}" /> </ion-slide> </ion-slides> <ion-list> <p><strong>Nom codifié :</strong> {{h.nom_codifie}}</p> <p><strong>Etat actuel :</strong> {{h.etat_actuel}}</p> <p><strong>Date de réception :</strong> {{h.date_reception}}</p> <p *ngIf="h.date_renvoi"><strong>Date de renvoi en liberté :</strong> {{h.date_renvoi}}</p> <p><strong>Pays :</strong> {{h.pays}}</p> <p><strong>Lieu de signalement :</strong> {{h.lieu_signalement}}</p> <p><strong>Condition du signalement :</strong> {{h.condition_signalement}}</p> <p><strong>Numéro d'immatriculation :</strong> {{h.immatriculation}}</p> </ion-list> </div> </div> </ion-card-content> </ion-card> History.ts : import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import { EditBirdPage } from '../EditBird/EditBird'; import { BirdService } from '../../providers/bird-service'; import { jQuery } from 'jquery'; @Component({ selector: 'page-History', templateUrl: 'History.html' }) export class HistoryPage { History:any =[]; constructor(public navCtrl: NavController, public serviceOne: BirdService) { this.serviceOne.getData().subscribe( data => this.History = data ); } openPage() { this.navCtrl.push(EditBirdPage); } shownGroup = null; toggleGroup(group) { if (this.isGroupShown(group)) { this.shownGroup = null; } else { this.shownGroup = group; } }; isGroupShown(group) { return this.shownGroup === group; }; } The scroll work only on page with basic text but with content which is generate or open manually ( like an accordion ) it's not working. Thanks for your help ! A: If you want your content to be scrolled, you need to wrap it inside ion-content like this, <ion-content> --your scrolling content goes here-- </ion-content> in your case if you want History.html contents to be scrolled, then wrap it inside ion-content like this, <ion-content> <ion-card *ngFor="let h of History; let i=index" text-wrap (click)="toggleGroup(i)" [ngClass]="{active: isGroupShown(i)}" class="HistoryPage"> <ion-card-header> <span class="title">{{h.nom_commun}}</span> <span class="date">{{h.date_signalement}}</span> <button (click)="openPage()" class="edit"> <ion-icon large name="create" color="mainColor" class="edit"></ion-icon> </button> </ion-card-header> <ion-card-content> <ion-icon color="success" item-right [name]="isGroupShown(i) ? 'arrow-dropdown-circle' : 'arrow-dropright-circle'" color="mainColor"></ion-icon> <br /> <div *ngIf="isGroupShown(i)"> <div class="up"> <ion-slides class="Pictures" slidesPerView="3"> <ion-slide> <img src="{{h.image}}" /> </ion-slide> <ion-slide> <img src="../assets/img/rossignol3.jpg" /> </ion-slide> <ion-slide> <img src="../assets/img/rossignol4.jpg" /> </ion-slide> <ion-slide> <img src="{{h.pictures}}" /> </ion-slide> </ion-slides> <ion-list> <p><strong>Nom codifié :</strong> {{h.nom_codifie}}</p> <p><strong>Etat actuel :</strong> {{h.etat_actuel}}</p> <p><strong>Date de réception :</strong> {{h.date_reception}}</p> <p *ngIf="h.date_renvoi"><strong>Date de renvoi en liberté :</strong> {{h.date_renvoi}}</p> <p><strong>Pays :</strong> {{h.pays}}</p> <p><strong>Lieu de signalement :</strong> {{h.lieu_signalement}}</p> <p><strong>Condition du signalement :</strong> {{h.condition_signalement}}</p> <p><strong>Numéro d'immatriculation :</strong> {{h.immatriculation}}</p> </ion-list> </div> </div> </ion-card-content> </ion-card> </ion-content>
{ "pile_set_name": "StackExchange" }
Q: Adding submit button value to submit() I am using the Jquery UI dialog box to act as a confirmation when deleting a record. What I'm trying to achieve is that when you click on a submit button with the value "delete" it will open the dialog window and confirm your choice. If you choose yes it will submit the form with the value of the submit button. I understand that it won't work at the moment because submit() has no way of knowing which button was clicked but I'm not sure how to go about it? Many thanks in advance. <script type="text/javascript"> $(document).ready(function(){ $("#dialog").dialog({ modal: true, bgiframe: true, width: 500, height: 200, autoOpen: false }); $("#rusure").click(function(e) { e.preventDefault(); $("#dialog").dialog('option', 'buttons', { "Confirm" : function() { $("#tasks").submit(); }, "Cancel" : function() { $(this).dialog("close"); } }); $("#dialog").dialog("open"); }); }); </script> <input type="submit" name="action" value="Delete" id="rusure"/> The form is called "tasks" and the hidden div containing the dialog content is called "dialog". At the moment everything is working fine apart from the form being submitted with the value of the submit button. There are also 2 submit buttons in the form. A: Give this a try: $("#rusure").click(function(e) { e.preventDefault(); // Create hidden input from button and append to form var input = $('<input name="confirm_delete" value="yesplz" type="hidden" />').appendTo('#tasks'); $("#dialog").dialog('option', 'buttons', { "Confirm" : function() { $("#tasks").submit(); }, "Cancel" : function() { $(this).dialog("close"); $(input).remove();// Remove hidden input } }); $("#dialog").dialog("open"); }); Demo here: http://jsfiddle.net/Madmartigan/ZGLNc/1/
{ "pile_set_name": "StackExchange" }
Q: Why don't fluorescent lights produce shadows? I have watched light sources such as incandescent lamps and other lamp sources; they have always made shadows. But a fluorescent lamp doesn't make any shadow. What is the reason behind the non-appearance of prominent shadow? A: To complement Floris's answer, here's a quick animation showing how the shadow changes with the size of the light source. In this animation, I've forced the intensity of the light to vary inversely with the surface area, so the total power output is constant ($P \approx 62.83 \, \mathrm{W}$). This is why the object (Suzanne) doesn't appear to get any brighter or darker, but the shadow sharpness does change: In this scene, the spherical lamp is the only light source, except for the dim ambient lighting. This makes the shadows very easily visible. In a real-world scenario with other light sources (windows, for example), the effect would be less pronounced because the shadows would be more washed out. The following animation shows the scenario Floris described, with a rotating long object: A: It does have a shadow - but it is very faint. When you have a point source of light, it casts a strong shadow (which is really an image of the object casting the shadow). As the source of light becomes larger ("extended" is the word) then you end up with a shadow that is made up of "lots of overlapping shadows" - which makes the edges seem blurry. If you have a fluorescent tube, you can see that by holding a wide stick (maybe a cricket bat) parallel to the tube and close to the floor: now you will see a shadow as the tube is narrower in one direction. When you turn the bat 90°, so it is perpendicular to the tube, the shadow will be much less strong. This picture shows how a small source makes a shadow - when you make the source larger, the edge will get "softer" until the shadow seems to disappear. Incidentally this is why you have frosted bulbs, lamp shades and reflectors: it is usually better for shadows to be softer (so you see everywhere and not just in the direct light).
{ "pile_set_name": "StackExchange" }
Q: Building Customer Service Applications I read manual "Chapter 11: Building Customer Service Applications for the Right Situations (Real World SharePoint 2010)". Build and install example code on test farm. But the service only run on one server. Advise idea how to run CacheService on second server? A: I solve my problem by writing PowerShell Comand: [Cmdlet(VerbsCommon.Add, "CalcServiceInstance", SupportsShouldProcess = true)] public class AddCaclServiceInstance : SPCmdlet { private SPServer _server; [Parameter()] public SPServer Server{ get{return _server;} set{_server = value;} } protected override bool RequireUserFarmAdmin() { return true; } protected override void InternalProcessRecord() { if (_server == null) { _server = SPServer.Local; } if ((SPPersistedObject)null == (SPPersistedObject)_server) { this.WriteError((Exception)new InvalidOperationException("Server not found."), ErrorCategory.ObjectNotFound, (object)this); this.SkipProcessCurrentRecord(); } CalcService service = SPFarm.Local.Services.GetValue<CalcService>(); if ((SPPersistedObject)null == (SPPersistedObject)service) { service = new CalcService(SPFarm.Local); service.Update(true); service.Provision(); } if ((SPPersistedObject)null != (SPPersistedObject)_server.ServiceInstances.GetValue<CalcServiceInstance>(string.Empty)) this.SkipProcessCurrentRecord(); CalcServiceInstance calcServiceInstance = new CalcServiceInstance(_server, service); _server.ServiceInstances.Ensure((SPServiceInstance)calcServiceInstance); calcServiceInstance.Provision(); calcServiceInstance.Update(); } } And using on SharePoint server: $server = Get-SPServer "APP-02" Add-CalcServiceInstance -Server $server
{ "pile_set_name": "StackExchange" }
Q: Add new distribution to JAGS or OpenBUGS? I would like model some variables using a distribution that is not neither JAGS' nor OpenBUGS core distributions. Do you know how can I implement it? Thanks. A: You can use the 'zeros trick'.
{ "pile_set_name": "StackExchange" }
Q: Unindo arrays onde os mesmos tiverem um certo campo igual Como faço para unir vários arrays em um array quando os mesmos tiverem os campos iguais? Eu tenho esse seguinte array sendo retornado, eu gostaria de agrupá-los em um único array onde eles tiverem o mesmo valor pro id_pergunta, por exemplo: nos 3 primeiros array que tem o id_pergunta = 1, os mesmos entrar em um array só, ficando, array = [ [array1], [array2], [array3] ] P.S: Todos esses arrays estão dentro dentro de outro que está contido na variável $retorno o SQL é esse: SELECT * FROM respostas INNER JOIN perguntas ON respostas.id_pergunta = perguntas.id_pergunta WHERE perguntas.id_questionario = $id_questionario A: Se colocar, exemplo: while($result = $acesso->result->fetch(PDO::FETCH_ASSOC)) { $retorno[$result['id_pergunta']][] = $result; } vai agrupar pela chave id_pergunta, isso acontece porque a chave é a mesma para aquele determinado item do array, e o agrupamento acontece naturalmente. Referencia: Arrays
{ "pile_set_name": "StackExchange" }
Q: Qt Designer vs Qt Quick Designer vs Qt Creator? I have seen references to all three of these applications on various parts of the Qt website but am completely unclear as to the exact differences between them and whether they are actually separate things or just different names for the same thing, or the name changed over time? Or is one no longer supported? What's the deal with these? A: Qt Creator is Qt's IDE. You don't have to use it, but it greatly simplifies Qt development. Qt Designer is a graphical tool that lets you build QWidget GUIs. Qt Quick Designer is similar, but for building QML GUIs. Both are built in to Qt Creator. This is explained in a little more detail over at Wikipedia. A: I will explain to you the difference between these tools by the approach for what they are used: Qt Designer: Sub tool used to create/edit widget files (.ui). You can use it to create the graphical layouts (.ui files only). The most use is to design the graphical stuff in PyQt apps. It is installed always when you install Qt, for example it is in the path: Qt5.13.1\5.13.1\mingw73_64\bin\designer.exe. It also be used to edit any .ui file of a Qt C++ application, however it is very limited since only allows to edit the graphical stuff (not C++ logic). Qt Quick Designer (it refers to Qt Creator): It does not exist, it is integrated in Qt Creator (see below). Is normal to say that Qt Quick Designer allows to edit QML files (.qml), however it is integrated in Qt Creator now. Qt Creator: This is the so defacto and most powerfull IDE to create QT applications natively (C++ with Qt engine). It allows you to create, edit source code, debug applications, etc. In addition to that, yo can open a .ui file or a .qml file in Qt Creator and it will open and allow you to edit. For example if you open an .ui file it will show you the Qt Designer app embedded in the full integrated Qt Creator IDE. In summary, you can use Qt Creator to open/edit any .ui or .qml file and create Qt/C++ applications. Of course, if the file is .ui then Qt Creator will show you the Qt Designer tool, if it is .qml then it will allow you to edit the QML.
{ "pile_set_name": "StackExchange" }
Q: Convert yyMdd into normal date in java (hexadecimal month number) I have a date formatted as 'yyMdd', where 'M' is a hexadecimal encoding of the month number (1 is January, C is December). How can I parse it to a java.util.Date? This is the same format as here, but a Java solution is required. Sure I can write a simple function for it myself but are there any existing parsers that handles this format? A: With the class SimpleDateFormat you are forced to do some text preprocessing. String input = "12B17T"; // according to the other SO-post String month = input.substring(2, 3); if (month.equals("A")) { month = "10"; } else if (month.equals("B")) { month = "11"; } else if (month.equals("C")) { month = "12"; } else { month = "0" + month; } String date = input.substring(0, 2) + month + input.substring(3, 5); SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd"); Date d = sdf.parse(date); Another solution using Joda-Time might look like: String input = "12B17T"; // according to the other SO-post int pivotYear = 2032; DateTimeParser monthParser = new DateTimeParser() { @Override public int estimateParsedLength() { return 1; } @Override public int parseInto(DateTimeParserBucket bucket, String text, int position) { DateTimeField field = ISOChronology.getInstance().monthOfYear(); char c = text.charAt(position); if (c >= '1' && c <= '9') { int value = c - '0'; bucket.saveField(field, value); return position + 1; } switch (c) { case 'A' : bucket.saveField(field, 10); break; case 'B' : bucket.saveField(field, 11); break; case 'C' : bucket.saveField(field, 12); break; default : return ~position; } return position + 1; } }; DateTimeFormatter f = new DateTimeFormatterBuilder().appendTwoDigitYear(pivotYear - 50).append(monthParser) .appendDayOfMonth(2).appendLiteral('T').toFormatter(); LocalDate date = f.parseLocalDate(input); System.out.println(date); // output: 2012-11-17 Surely this approach is not shorter or easier, but offers the advantage of immutability and hence thread-safety. Of course the same scheme can also be applied on other time libraries based on immutable types.
{ "pile_set_name": "StackExchange" }
Q: How do I calculate the total XP to reach a particular level, when each level takes 10% more? How do I calculate the amount of XP for a level where the first level is 110, and each level after is 10% more than the last. Preferably to do without a loop because the levels will have to be infinite and will need to be quickly calculated. in js using a loop: var xptest=110; var lastLevel = 110; for (var level = 2; xptest <= Number.MAX_SAFE_INTEGER || level < 100; level++) { lastLevel*=1.1; lastLevel = Math.round(lastLevel *1.1) xptest+= lastLevel; console.log('LEVEL',level,'('+lastLevel+' / '+xptest+')'); } A: Let's work through some cases, given \$baseXP = 110\$ and \$increase = 1.1\$: $$\begin{align} targetXP(1) &= baseXP\\ targetXP(2) &= baseXP + baseXP \cdot increase\\ targetXP(3) &= baseXP + baseXP \cdot increase + baseXP\cdot increase^2\\ ...\\ targetXP(n) &= baseXP + baseXP \cdot increase + ... + baseXP \cdot increase ^ {n-1}\\ \end{align}$$ If we multiply \$targetXP(n)\$ by \$increase\$, we find that all it does is shift the terms down one: $$\begin{align}targetXP(n)&\cdot increase\\ &= baseXP \cdot increase + baseXP \cdot increase^2 + ...+ baseXP \cdot increase^n\end{align}$$ So if we subtract the original from this shifted version, all the terms except the first and last will cancel out, and we get... $$\begin{align} targetXP(n) \cdot increase - targetXP(n) &= baseXP \cdot increase^n - baseXP\\ targetXP(n) \cdot (increase - 1) &= baseXP \cdot (increase^n - 1)\\ targetXP(n) &= baseXP \cdot \frac {1 - increase^n} {1 - increase}\end{align}$$ This is what's called a Geometric Series - you can read more about the math behind this here.
{ "pile_set_name": "StackExchange" }
Q: AppBarLayout with FrameLayout container as scrolling content doesn't work I'm trying to use the newest design library to make my toolbar hide/show on scroll. My issue is the scrolling content I have is in the fragment, I'm just injecting it into the FrameLayout container and it doesn't work. Here's my activity: <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.design.widget.CoordinatorLayout android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <include layout="@layout/layout_toolbar" /> </android.support.design.widget.AppBarLayout> <FrameLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> </android.support.design.widget.CoordinatorLayout> <FrameLayout android:id="@+id/navigation_drawer_container" android:layout_width="@dimen/navigation_drawer_width" android:layout_height="match_parent" android:layout_gravity="start" tools:layout="@layout/fragment_nav_drawer_anon" /> and my fragment: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.v4.widget.SwipeRefreshLayout android:id="@+id/pull_to_refresh" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="match_parent"/> </android.support.v4.widget.SwipeRefreshLayout> <TextView android:id="@android:id/empty" android:layout_width="match_parent" android:layout_height="match_parent" android:textSize="18sp" android:fontFamily="sans-serif" android:color="@color/dark_grey" android:padding="60dp"/> and toolbar: <android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorPrimary" android:minHeight="?attr/actionBarSize" app:layout_scrollFlags="scroll|enterAlways" style="@style/Widget.MyApp.ActionBar" /> I'm following official doc and this demo, and still can't figure out how to make it work. A: Replace your FrameLayout with android.support.v4.widget.NestedScrollView NestedScrollView is just like ScrollView, but it supports acting as both a nested scrolling parent and child on both new and old versions of Android. Nested scrolling is enabled by default. Link to doc A: The reason for that behaviour is that the Framelayout doesn't specify a Behaviour. The CoordinatorLayout relies on the child view to handle the Behaviour. You can read at the bottom here http://android-developers.blogspot.in/2015/05/android-design-support-library.html It states that CoordinatorLayout and custom views One thing that is important to note is that CoordinatorLayout doesn’t have any innate understanding of a FloatingActionButton or AppBarLayout work - it just provides an additional API in the form of a Coordinator.Behavior, which allows child views to better control touch events and gestures as well as declare dependencies between each other and receive callbacks via onDependentViewChanged(). Views can declare a default Behavior by using the CoordinatorLayout.DefaultBehavior(YourView.Behavior.class) annotation,or set it in your layout files by with the app:layout_behavior="com.example.app.YourView$Behavior" attribute. This framework makes it possible for any view to integrate with CoordinatorLayout. Edit: Although FrameLayout is not a custom view, it doesnt specify a behaviour which CoordinateLayout seeks. A: Using FrameLayout as child of CoordinatorLayout works quite well. The toolbar is collapsing like it's supposed to. I had a problem in the beginning, when I used outdated libraries. Here are the gradle dependencies I'm using right now: compile 'com.android.support:appcompat-v7:22.2.1' compile 'com.android.support:cardview-v7:22.2.0' compile 'com.android.support:recyclerview-v7:22.2.0' compile 'com.android.support:design:22.2.0' I'm using FrameLayout with the attribute app:layout_behavior="@string/appbar_scrolling_view_behavior" as a child of CoordinatorLayout in an activity's layout. The FrameLayout serves as container for fragments. My fragment layouts' root elements are either a RecyclerView or a NestedScrollView. Here is the layout of the activity: <android.support.design.widget.CoordinatorLayout android:layout_width="match_parent" android:layout_height="match_parent" > <FrameLayout android:id="@+id/..." android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> <android.support.design.widget.AppBarLayout android:layout_height="192dp" android:layout_width="match_parent" > <android.support.design.widget.CollapsingToolbarLayout android:layout_width="match_parent" android:layout_height="match_parent" app:layout_scrollFlags="scroll|exitUntilCollapsed" > <ImageView android:id="@+id/.." android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" android:scaleType="centerCrop" android:src="@drawable/..." app:layout_collapseMode="parallax"/> <android.support.v7.widget.Toolbar android:id="@+id/toolbar_sessions" android:layout_height="?attr/actionBarSize" android:layout_width="match_parent" app:layout_collapseMode="pin" /> </android.support.design.widget.CollapsingToolbarLayout> </android.support.design.widget.AppBarLayout> </android.support.design.widget.CoordinatorLayout> My first fragment's layout looks like this: <android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:scrollbars="vertical" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="..." /> My second fragment's layout looks like this: <android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="..." android:layout_width="match_parent" android:layout_height="match_parent" tools:context="..." > ... </android.support.v4.widget.NestedScrollView>
{ "pile_set_name": "StackExchange" }
Q: align the background-image of :after to its parent container I want to get a transparent background-image within my content div. In order to do this without effecting the child elements of the .content I defined a background-image of .content:after and wanted to set its position to the position of my .content. The problem is: in this code the background-image starts at top: 0, left: 0, right: 0, bottom: 0 of the body. How can I get this to start at my .content? Another problem with that is that I actually have a header too which has a flexible height. So don't know the absolute top-position of the .content. .content { width: 200px; margin: 10px auto; } .content:after { content: ""; background-image url("http://works.mihaimoga.com/stackoverflow_logo.jpg"); position: absolute; top: 0; bottom: 0; left: 0; right: 0; opacity: 0.7; } A: Instead of using :after pseudo class, you can use background value as rgba. which will not effect transparency to child elements. .content { width: 200px; margin: 10px auto; background-image url("http://works.mihaimoga.com/stackoverflow_logo.jpg"); background-color: rgba(255, 255, 255, 0.7); /* added */ }
{ "pile_set_name": "StackExchange" }
Q: How do I get an int from a string in C with no whitespace? So I have a string like this: "MULTR12" I want to get '1' and '2' as two seperate integers. How do I go about doing that? Before, I had it simply as: char *string = "MULTR12"; val = string[5]; But I get a really weird value for val instead of 1, like I want. Can anyone help? Thanks! A: This is how you convert a char to int .. int x = string[5] - '0'; Here's some explanation.. Every character is represented as an ASCII character in memory, A will be 65 and simliar. This also applies to numbers, so 0 in ASCII is 48, 1 is 49 etc. Now, when we subtract 0 from any number's ASCII representation. Let's say the number is 5, this is what we are actually doing.. int x = 53 - 48 which gives us 5 as an integer. In other words, we are calculating the displacement of that numbers ASCII representation from 0's ASCII representation.
{ "pile_set_name": "StackExchange" }
Q: Multiple where conditions in Laravel 5.1 i have a problem in my multiple filters implementation. I have some checkboxes that pass to AJAX some params that can have multiple values. In my controller i have written this to handle this params: function getCategoria(Request $request) { $path_info = Request::getPathInfo(); $path = substr($path_info, 1); $links = explode('/', $path); $categorie = \App\Models\Categorie::where('primaria',1)->get(); $categoria = \App\Models\Categorie::where('link_statico', $path)->first(); $categoriaz = \App\Models\Categorie::where('link_statico', $path)->first(); $id = ucfirst($links[0]); $prodottip = \App\Models\Prdotticategorie::where('prodotti2categorie.id_categoria', $categoriaz->id)->join('prodotti', 'prodotti.id', '=', 'prodotti2categorie.id_prodotto')->query(); $brands = Input::get('brands'); $genere = Input::get('genere'); $stagione = Input::get('stagione'); $this->data['links'] = $links; $this->data['categorie'] = $categorie; $this->data['categoria'] = $categoria; $this->data['categoriaz'] = $categoriaz; $this->data['id'] = $id; $this->data['pages'] = 'categorie.frontend'; if(count($brands) > 0 && count($genere) > 0 && count($stagione) > 0) { if(count($brands) > 0) { $brands_array = []; if(is_array($brands) || is_object($brands)) { foreach ($brands as $brand) { $brands_array[] = $brand; } $rst = $prodottip->whereIn('prodotti.id_produttore', $brands_array); } } if(count($genere) > 0) { $genere_array = []; if(is_array($genere) || is_object($genere)) { foreach ($genere as $gen) { $genere_array[] = $gen; } $rst = $prodottip->whereIn('prodotti.genere', $genere_array); } } if (count($stagione) > 0) { $stagione_array = []; if(is_array($stagione) || is_object($stagione)) { foreach ($stagione as $stag) { $stagione_array[] = $gen; } $rst = $prodottip->whereIn('prodotti.stagione', $stagione_array); } } $prodottix = $rst->paginate(18); } else { $prodottix = $prodottip->paginate(18); } $this->data['prodottix'] = $prodottix; if (Request::ajax()) { $page = 'layouts.'.CNF_THEME.'.categorie_ajax'; $view = view($page, $this->data)->render(); return response()->json(['html'=>$view]); } $page = 'layouts.'.CNF_THEME.'.categorie'; return view($page, $this->data); } The problem is that AJAX reload correctly but the results remaining the same. I can bring it working only if i an elseif with different scenarios like this: if(count($brands) > 0 && count($genere) > 0 && count($stagione) > 0) //query with 3 where elseif(count($brands) > 0 && count($genere) == 0 && count($stagione) == 0) // query with 1 where Hi have read something on DynamicScopes in Laravel, but i need more help thks A: function getCategoria(Request $request) { $path_info = Request::getPathInfo(); $path = substr($path_info, 1); $links = explode('/', $path); $categorie = \App\Models\Categorie::where('primaria', 1)->get(); $categoria = \App\Models\Categorie::where('link_statico', $path)->first(); $categoriaz = \App\Models\Categorie::where('link_statico', $path)->first(); $id = ucfirst($links[0]); $prodottip = \App\Models\Prdotticategorie::where('prodotti2categorie.id_categoria', $categoriaz->id)->join('prodotti', 'prodotti.id', '=', 'prodotti2categorie.id_prodotto')->query(); $brands = Input::get('brands'); $genere = Input::get('genere'); $stagione = Input::get('stagione'); $this->data['links'] = $links; $this->data['categorie'] = $categorie; $this->data['categoria'] = $categoria; $this->data['categoriaz'] = $categoriaz; $this->data['id'] = $id; $this->data['pages'] = 'categorie.frontend'; $rst = null; if (count($brands) > 0) { $brands = is_object($brands) ? array($brands) : $brands; $rst = $prodottip->whereIn('prodotti.id_produttore', $brands); } if (count($brands) > 0) { $genere = is_object($genere) ? array($genere) : $genere; $rst = $prodottip->whereIn('prodotti.genere', $genere); } if (count($stagione) > 0) { $stagione = is_object($stagione) ? array($stagione) : $stagione; $rst = $prodottip->whereIn('prodotti.stagione', $stagione); } if(null !== $rst) { $prodottix = $rst->paginate(18); } else { $prodottix = $prodottip->paginate(18); } $this->data['prodottix'] = $prodottix; if (Request::ajax()) { $page = 'layouts.' . CNF_THEME . '.categorie_ajax'; $view = view($page, $this->data)->render(); return response()->json(['html' => $view]); } $page = 'layouts.' . CNF_THEME . '.categorie'; return view($page, $this->data); } Considering $brands,$genere,$stagione are array by default. If it is object then then type casting to array and using in the query. Removed first if condition which is checking count of all 3 arrays and then trying to build up a query. Created new variable $rst which is having default value as null. In any condition is satisfied then it will assign the query object to $rst. At last checking is $rst not equal to null and calling its paginate method. Hope this will clears to you and solve your problem. If not,at least you will get an idea how you can re-factor your code :)
{ "pile_set_name": "StackExchange" }
Q: Display data from database(Entity framwork) into _Layout.cshtml I'm developping a web site on MVC3 asp.net and I use entities framwork for data base: I want to display the logo from database on _Layout.cshtml, and I want to display the texte from database into My home page. this is my model public class Theme { [Required(ErrorMessage = "ID is required.")] public string ThemeID { get; set; } public string path { get; set; } [AllowHtml] [Required(ErrorMessage = "Text is required.")] public string texte { get; set; } } I put in the _Layout.cshtml @Html.Partial("~/Views/Shared/_Header.cshtml") this is my ThemeController.cs [ChildActionOnly] public ActionResult Header(string id) { var model = db.Themes.ToList(); return View("~/Views/Shared/_Header.cshtml", model); } this is the _Header.cshtml @model ICollection<DSClient.Models.Theme> @{ <img src="@Href( @Model.ElementAt(@Model-1).path )" /> } When I type the url of Theme/index It's OK, BUT the problem is when I load an other page, I have this exception Object reference not set to an instance of an object. Please Ineed your help. A: Html.Partial is used to include a partial view. Therefore, when you include _Header.cshtml and the Model is not a ICollection<DSClient.Models.Theme>, you're in trouble. Since you made a method with a Childaction attribute, I assume you may want to use Html.Action instead of Html.Partial. This would execute the child action of the controller which outputs the _Header.cshtml with the appropriate data. Remove the string argument in the Header action (it's not used) and in _Layout.cshtml, you may call it like this: @Html.Action("Header", "Theme")
{ "pile_set_name": "StackExchange" }
Q: Spotfire - Is there a way to 'drill up' instead of drill-down? Spotfire has the ability to drill down via 'create details visualization' that allows you to click on an element in a graph and view just that data inside another graph. My question is about doing the opposite. I have a scatter plot where each dot is an individual row of data (with name, dollar amount, etc columns). I want to click on a dot (which is an individual row of data), and in a second visualization see every row of data that shares the name value with that individual row of data. Essentially this is a 'drill-up' from one row of data. Any ideas on how to do this? A: That's not so easy like details visualization, but surely you can do that. Best way I could think of: As you've already created your scatter plot, let's build on that: duplicate your data table: add data tables - add - from current visualization - select your original table link the two tables on [name] column: edit - data table - relations - manage relations - new - select original and copied data tables and [name column for both] create your "drill up" visualization based on the copied table open properties of this new visualization and go to "data" and in "limit data using markings" check the colour you use in your original visualization I know it sounds complicated, but in practice it's easier and works:)
{ "pile_set_name": "StackExchange" }
Q: R: Getting all dates a unique row occured and storing it in a variable I am pulling data in a spark table and want to know the dates when a unique row occurred, and then storing these dates in a new variable. For example, if the data is: ID amt status date A 1000 A 2019-01-01 A 1000 A 2019-02-01 B 1000 I 2019-01-01 B 3000 A 2019-02-01 B 3000 A 2019-03-01 I would like to see: ID amt status var A 1000 A 2019-01-01|2019-02-01 B 1000 I 2019-01-01 B 3000 A 2019-02-01|2019-03-01 Thanks and appreciate your help A: You can group_by(ID, amt, status) and then mutate date to contain all dates separated by |. library(tidyverse) df %>% group_by(ID, amt, status) %>% mutate(date = paste(date, collapse = "|")) %>% distinct() Output ID amt status date <fct> <int> <fct> <chr> 1 A 1000 A 2019-01-01|2019-02-01 2 B 1000 I 2019-01-01 3 B 3000 A 2019-02-01|2019-03-01 Or base R option: aggregate(date ~ ID + amt + status, df, paste, collapse = "|") Or data.table: data.table(df)[,lapply(.SD, paste, collapse = "|"), .(ID, amt, status)]
{ "pile_set_name": "StackExchange" }
Q: Just beginning new internship and another company wants to interview I am beginning a busy-season internship at an accounting firm, January-March. My first day is January 3rd, and I am training at my local office January 3rd-9th and then going to Chicago to train Jan 10th-12th. I assume it is going to be a lot of information to soak up and remember, considering I am a very young, new hire. Being that this internship is only for the spring, I am still actively looking for a summer internship. A company that I had applied for a summer internship emailed me today and told me that I could choose a time slot and come in to interview on the 4th of January (my second day of training at my new internship, assumedly something that is way too important to skip out on, even for a couple hours). What is my best course of action here? I will not be done training with my new internship until the 12th, but this other company wants to interview the 4th. Should I request a later date? Request a phone or video interview? A: If it's possible for you to make it, then make it. If you absolutely cannot miss the training, then ask if you can reschedule for after the 12th. The hiring manager should understand that you have an obligation. It seems unlikely that they wouldn't be willing to wait a week but if the answer is no, you'll have to decide for yourself which is more important. You could certainly ask to do it over Skype, though I find that it's usually a poor substitute for meeting face to face. There are certain elements of a person's character that can only be learned through face-to-face interaction.
{ "pile_set_name": "StackExchange" }
Q: How is type_info implemented Most c++ STL classes have easy to understand implementation. However, the type_info class is confusing. How does some code know the info of a class? Theory 1: My first theory is that the type_info class gets the information from the compiler (which means that the STL has some integration with the compiler). Theory 2: It could also be some obscure c++ syntax that I don’t know of, but am not too sure about this theory. A: type_info is just a standard library class that provides type information. Objects of this class are returned by the typeid operator. Of greatest interest is not the class itself, but the RTTI (Run-Time Type Identification) implementation. This is a purely compiler dependent feature, part of the ABI (Application Binary Interface). In brief, the compiler stores type information for each polymorphic type along with its vtable or VMT (Virtual Method Table). This information is per-type, not per-object and used by typeid and by dynamic_cast. The type_info class is just an interface provided to the end user, it has an internal implementation depending on the compiler. Different compilers implement different ABIs. Modern gcc and clang compilers implement Itanium C++ ABI, which describes all the details of RTTI and the rest. Microsoft Visual C++ ABI is undocumented. A good article that describes C++ vtables and covers RTTI: Shahar Mike - C++ vtables.
{ "pile_set_name": "StackExchange" }