text
stringlengths
64
89.7k
meta
dict
Q: How to clear the username and password in login form when they are wrong I have a question When an user type a wrong username and/or password and joomla display a message about this error and I would like to clean both fields, how can I do that ? thank you for you help A: Go to your Joomla root folder, from there: go to: /templates/[your template]/html/mod_login Backup default.php: cp default.php default.php.org Edit default.php: vi default.php And here's the tricky part, the thing you have to changes is different for each template, for example, in atomic template you should look for the line: So the id of this field in this case is: "modlgn_username". Now you can use jQuery / Javascript and "clean" the value.
{ "pile_set_name": "StackExchange" }
Q: How to update contact owner value I have this SOQL: SELECT Id, mudouProprietario__c,(SELECT Id, AccountId, OwnerId FROM Contacts) FROM Account I need get value of owner account and set the value at the contact owner I created a for passing the list that returns the select Task[] listaTarefaUpdate = new Task[] {}; Opportunity[] listaOportunidadeUpdate = new Opportunity[] {}; Contact[] listaContatosUpdate = new Contact[] {}; Account[] listaContas = (Account[]) scope; for( Account contas : listaContas){ for(Task task: contas.Tasks){ task.OwnerId = contas.OwnerId; listaTarefaUpdate.add(task); } for(Opportunity oportunidade : contas.Opportunities){ oportunidade.OwnerId = contas.OwnerId; listaOportunidadeUpdate.add(oportunidade); } for(Contact contato : contas.Contacts){ contato.OwnerId = contas.OwnerId; listaContatosUpdate.add(contato); } contas.mudouProprietario__c = false; } Database.SaveResult[] srListOpt = Database.update(listaOportunidadeUpdate, false); Database.SaveResult[] srListCont = Database.update(listaContatosUpdate, false); Database.SaveResult[] srListTar = Database.update(listaTarefaUpdate, false); It would be like this? A: It would be far simpler to approach this from the opposite direction; query the contacts and the account owner in a child-parent relationship instead of a parent-child relationship: Contact[] records = [SELECT Account.OwnerId FROM Contact WHERE AccountId <> NULL]; for(Contact record: records) { record.OwnerId = record.Account.OwnerId; } update records; For many different children, then you might do something like this: Account[] records = [SELECT OwnerId, (SELECT Id FROM Contacts), (SELECT Id FROM Opportunities WHERE IsClosed = false) FROM Account]; sObject[] updates = new sObject[0]; for(Account record: records) { for(Contact contactRecord: record.Contacts) { updates.add(new Contact(Id=contactRecord.Id, OwnerId=record.Id)); } } update updates; updates.clear(); for(Account record: records) { for(Opportunity opportunityRecord: record.Opportunities) { updates.add(new Opportunity(Id=opportunityRecord.Id, OwnerId=record.Id)); } } update updates; ... This isn't the only way to do so, but one of several different possibilities.
{ "pile_set_name": "StackExchange" }
Q: seq(as.Date("2016/3/31"),as.Date("2016/6/30"),by = "month") The following R code is not working properly: seq(as.Date("2016/3/31"),as.Date("2016/6/30"),by = "month") The output is: "2016-03-31" "2016-05-01" "2016-05-31" But the expected output is: "2016-03-31" "2016-04-30" "2016-05-31""2016-06-30" A: I think this is a duplicate of Generate a sequence of the last day of the month over two years and they suggested to do the following ymd("2010-02-01")+ months(0:23)-days(1) Simply specify the first day of the next month and generate a sequence from that but subtract 1 days from it to get the last day of the preceding month.
{ "pile_set_name": "StackExchange" }
Q: caching Type.GetXYZ In a specific piece of code i cal Type.GetFields() many times. One call can call it 5 times or more. Also a piece of code could iterate thousands of times. ATM i dont need to optimize but i am asking so if i need to i know how. How could i cache this? I am hoping i can do something like obj.GetType().Tag["myCacheId"] and pull out cached data. But i doubt i can do this. Can i attach data to a type somehow? i really hope i dont resort to a singleton. How might i cache data relating to Type's? A: The CLR already caches metadata. Very slow on the first call when it is dug out of the assembly, fast afterward. Caching yourself isn't going to make any difference.
{ "pile_set_name": "StackExchange" }
Q: Checking a fuction for monotony I have a question about checking for monotony in functions and later proving them mathematically. $$f_1:\mathbb {R}^+→\mathbb {R},x \to \frac{1+6x+2x^2}{(x+3)x} $$ By plugging in values 0, 1 and 2 I get the following results: 1, 2.25 and 2.05. I see this is no monotony so I don't have to explain my solution. (Or I am incorrect?) $$f_1:\mathbb {R}→\mathbb {R},x \to \ln(x) $$ I plugged values 3,5 and 7 here, resulting in 1.09, 1.60 and 1.94, thus making this a monotonically increasing function. My question is how can I prove this mathematically? I already know to confirm this is as a monotonically increasing function, the following statements have to be correct: when for $x_1<x_2$ applies $f(x_1)<f(x_2)$. I just don't understand which values I use to prove this. A: You say that $f: D \to \mathbb{R}$ is (strictly) increasing if and only if for all $x_1,x_2 \in D$ you have that $x_1 < x_2 \Rightarrow f(x_1)<f(x_2)$. So, if you want to prove that $f$ is not increasing, you just need to find a counterexample (if it was increasing, the implication should hold for every $x_1,x_2$. However, if you want to prove that the function is increasing, an example is not enough... because you must show that the implication holds for all $x_1,x_2$. You cannot prove that all dogs are brown just by giving an example of a brown dog, but you can show that not all dogs are brown by finding a black dog. For instance, regarding the logarithm, taking $0 < x_1< x_2$, you can note that $$ f(x_1)-f(x_2) = \ln x_1-\ln x_2 = \ln \frac{x_1}{x_2} < 0 \Rightarrow f(x_1) < f(x_2). $$ The inequality $\ln \frac{x_1}{x_2}< 0$ is obtained because $0 < x_1/x_2 < 1$ and so its logarithm is negative. Of course, from the previous is equivalent to $f(x_1)- f(x_2)$.
{ "pile_set_name": "StackExchange" }
Q: Issue in Changing WooCommerce Currency Symbol I wrote a code to change WooCommerce currency symbol based on the Country selection from the Checkout page. Below is the code: add_filter('woocommerce_currency_symbol', 'change_existing_currency_symbol', 10, 2); function change_existing_currency_symbol( $currency_symbol, $currency ) { global $post, $woocommerce; $my_country = WC()->customer->get_shipping_country(); /*echo $my_country; echo "<br>"; echo $country;*/ switch( $my_country ) { case 'GB': $currency_symbol = '£'; break; case 'NZ': $currency_symbol = '$'; break; case 'IE': $currency_symbol = '€'; break; default: $currency_symbol = '$'; } return $currency_symbol; } The code is working fine and when Country is select from the Checkout page, the Symbol appeared well. However, we see that we can't access the admin section as it says: This page isn’t working www.XXXXXX-XX.com is currently unable to handle this request. HTTP ERROR 500 When I removed the code: $my_country = WC()->customer->get_shipping_country(); , the admin panel opens but Symbol did not appear. Seeking your help. A: Use a conditional check so that it only runs the code on the checkout page. add_filter('woocommerce_currency_symbol', 'change_existing_currency_symbol', 10, 2); function change_existing_currency_symbol( $currency_symbol, $currency ) { if ( is_checkout() ) { $my_country = WC()->customer->get_shipping_country(); switch( $my_country ) { case 'GB': $currency_symbol = '£'; break; case 'NZ': $currency_symbol = '$'; break; case 'IE': $currency_symbol = '€'; break; default: $currency_symbol = '$'; } } return $currency_symbol; }
{ "pile_set_name": "StackExchange" }
Q: Erlang trouble using otp logging I currently trying to setup otp logging in my app as documentation recommends to use it. I have following startup line: erl -pa ebin edit deps/*/ebin -boot start_sasl \ -detached \ -sasl sasl_error_logger "{file, \"priv/log/app.log\"}" \ -sasl errlog_type all \ -sname $APP_NAME \ -s $APP_NAME But when i say in my app something like error_logger:error_report("!!!!") or error_logger:error_msg("!!!!"), then nothing is printed in log file, what i'm doing wrong ? A: The problem is very simple. SASL only logs PROGRESS, CRASH and SUPERVISOR reports (or so the documentation says). You are sending something which is an ERROR report which it doesn't log. If you create some crash in a process that is SASL-enabled, say proc_lib:spawn(fun() -> exit(argh) end). Then that report should come up in your log. I think the mf logger takes everything but I might be wrong. It also requires the rb tool to read the log files in question. A good alternative for a real application is to use the lager application written by the fine guys at Basho technologies. It provides a more syslog-like interface and it also handles SASL error log types too. In addition it won't destroy your server if you try to log a very large process state - which the default SASL loggers will.
{ "pile_set_name": "StackExchange" }
Q: (Visual C++ v141) Bitwise function compiling incorrectly Using Visual Studio Enterprise 2017 version 15.1 (26403.7) on toolset v141. The following code seems to compile incorrectly. #define GMASK(rangeStart, rangeEnd) ((1 << (rangeEnd - rangeStart + 1)) - 1) uint32_t _gmask(uint32_t rangeStart, uint32_t rangeEnd) { return ((1 << (rangeEnd - rangeStart + 1)) - 1); } int main() { cout << bitset<32>(GMASK(0, 31)) << endl; cout << bitset<32>(_gmask(0, 31)) << endl; return 0; } In Visual Studio the output is 11111111111111111111111111111111 00000000000000000000000000000000 However in gcc the output is 11111111111111111111111111111111 11111111111111111111111111111111 Why is there a difference in the output when it's the same code? A: It's undefined behavior. In your code, when computing _gmask(0, 31), the value 232 is used. That's already outside the range of uint32_t, which could range from 0 to 232 - 1. From C++14 5.8 Shift operators: The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned type, the value of the result is E1 × 2E2, reduced modulo one more than the maximum value representable in the result type. Otherwise, if E1 has a signed type and non-negative value, and E1×2E2 is representable in the corresponding unsigned type of the result type, then that value, converted to the result type, is the resulting value; otherwise, the behavior is undefined.
{ "pile_set_name": "StackExchange" }
Q: What is the mathematical mystery here? I know that, $$\sqrt{25}=5≠-5$$ But, in quadratic equation we write $$(2ax+b)^2=b^2-4ac$$ $$(2ax+b)=±\sqrt{b^2-4ac}$$ Why?? We must write $±$, and What is the mathematical mystery here? A: In $\mathbb{R}$ there are two numbers $x$ such that $x^2=a$ (for $a>0$), and these two numbers have opposite sign, but, by definition, the symbol $\sqrt{a}$ indicates only the positive one of such two numbers, so, if we want indicate expliciltly all the two we must write $ x= \pm \sqrt{a}$.
{ "pile_set_name": "StackExchange" }
Q: Install PHP MSSQL Driver on Windows 2008 64bit IIS 7 - Unable to load dynamic library maybe somebody is able to help with the following problem: I have to install PHP 5.2 on Windows 2008 IIS with MSSQL Support but I'm unable to get MSSQL to work. Current situation Windows 2008 Server 64bit IIS7 PHP 5.2.17 installed with PHP Manager PHP works fine php_mssql doesn't (logs errors) When I add the php_mssql.dll it won't work and it logs this error: PHP Warning: PHP Startup: Unable to load dynamic library 'C:\PHP\PHP5.2\ext\php_mssql.dll' - The specified module could not be found. in Unknown on line 0. I know there is a problem with the ntwdblib.dll which is loaded internally from php_mssql.dll, but the file is in the PHP directory and I copied it everywhere: system32, php\ext etc but nothing works. That helps in previous installations every time in this case, but this is my first Windows 2008 64bit Installation, maybe there is a 64bit problem? And I know I should use the Microsoft Drivers for PHP for SQL Server but that would lead me to other function calls (sqlsrv_connect instead of mssql_connect) and I have to run an old application which contains mssql_ function calls on this server. A: I Argue with Whoru, Our company Web system of 6 servers all run php with the MSSQL driver on IIS and its far more stable then LAMP in terms of hacking the server NTLM on a Domain Server is almost unbreakable unlike SSH witch will let you retry to no end, But you must use sqlsrv_connect as the php mssql_connect driver is dead wont work on SQL 2k5 or 2k8 We had to make the change on all of our servers sorry i could not give you better news
{ "pile_set_name": "StackExchange" }
Q: Does anyone know of a good Arduino library for the Linksprite CC3000? I bought this Linksprite CC3000 WiFi Shield for Arduino from Amazon: The company website is http://www.linksprite.com/ The product page for it is http://linksprite.com/wiki/index.php5?title=CC3000_WiFi_Shield_for_Arduino On the product page there is a link for the Library & Test code which I've downloaded and placed into the library folder of my Arduino version 1.0.3 (because I read that the CC3000 doesn't work with the latest version of Arduino). The sample/test scripts state "This is an example for the Tinysine CC3000 Wifi Shield" and when I attempt to run them I either get the error "Wifi shield not present" or it attempts to connect to my network and eventually times out over and over. I've searched everywhere to try and find code that will work for this shield and I'm worried that I made a bad purchase. Has anyone had experience with this shield or knowledge of how I can get it to work? EDIT 11/13/2015 - I've been told through Amazon that the Tinysine code does work for this shield but I have yet to get it to work properly. A: I found that the Adafruit CC3000 library works perfectly for this shield. https://learn.adafruit.com/adafruit-cc3000-wifi/cc3000-library-software
{ "pile_set_name": "StackExchange" }
Q: How to calculate pairwise distances of nominal variable? I have the following data frame where I need to calculate pairwise differences between all rows(names here). names<- c("t1","t2","t3","t4","t5","t6","t7","t8") v1 <- c(2,3,4,2,2,4,7,12) v2 <- c(15,12,2,2,3,1,7,12) v3<- c(2,3,2,16,14,11,2,7) v4<- c(12,3,4,5,9,1,12,13) mydf<- data.frame(names,v1,v2,v3,v4) So the expected output needs to be something similar to what dist(mydf[-1]) gives but those numbers are nominal characters and the order of values also matter. e.g: "t1 and "t2" are 4/4 different while "t1" & "t3" difference is 3/4. Thanks A: What about: ans <- expand.grid(first=1:nrow(mydf), second=1:nrow(mydf)) ans$diff <- apply(ans, 1, function(x) { ncols <- ncol(mydf)-1 sum(mydf[x[1],-1] != mydf[x[2],-1]) / ncols }) m <- matrix(ans$diff, nrow = nrow(mydf)) colnames(m) <- rownames(m) <- names m
{ "pile_set_name": "StackExchange" }
Q: Is keeping all my game art in a static class wasting memory? When I make games, I generally create a static class called Art that has static fields to track all content in the game. For example public static class Art { public static SpriteFont defaultFont; public static Texture2D playerSprite; public static void LoadContent(ContentManager content) { defaultFont = content.Load<SpriteFont>("Fonts/DefaultFont"); playerSprite = content.Load<PlayerSprite>("Sprites/PlayerSprite"); } } My question is do these objects in my art class take up memory for the duration of the games lifetime? The point of this class is to only have to load my art once in the game and have easy access to the assets anywhere in my project, but at what cost? A: When LoadContent works as advertised, then it seems to load all resources from disk into memory. The result will be a longer load-time at the beginning of the game, but far shorter load-times during playing. Whether or not this is a good tradeoff depends on how the players play your game. When it's a game you play for hours in one session, players would certainly prefer shorter ingame loading times. When it's a game you just play for a few minutes, players whould rather prefer a fast startup. Having everything in memory at once could cause you to run out of RAM. Whether or not this will happen depends on how large your assets are (note that filesize does not necessarily correspond with memory requirement after loading) and how much RAM your target platform usually has. An alternative would be "lazy loading". Instead of loading all assets at startup, you load resources when they are first requested. You would usually do that by calling a function to obtain an asset. This could look something like this: public static class Art { private static HashMap<String, Sprite> spriteCache = new HashMap<String, Sprite>(); public static Sprite getSprite(filename) { // look in sprite cache if sprite was already loaded before Sprite sprite = spriteCache[filename]; if (sprite == null) { // sprite wasn't found. load it now. sprite = content.Load(filename); spriteCache[filename] = sprite; } return sprite; } } Warning: This implementation is not thread-safe. It will load the same resource multiple times in parallel when requested by multiple threads at once The upside is that you won't have any loading screens at all, because nothing gets preloaded. The downside is that the game will start to lag whenever a lot of unloaded stuff appears in the game for the first time. When your game needs almost all assets on startup, then you will end up with the same loading time as before. You will also end up with the same memory usage as before when the player plays for a long time and sees every art asset you have. To prevent this "memory leak" effect your Art class could keep track of the time each asset was requested last and automatically unload those which were not requested for a while. When you go down that route, make sure that every use of an asset goes through your Art class and no other class keeps own references to assets. Otherwise the Art class could think an asset is no longer used even though something uses it all the time but does so through a reference it owns itself.
{ "pile_set_name": "StackExchange" }
Q: Visual C++: Linking a DLL from another DLL using a relative path I have the following file structure C:\Application\application.exe C:\Application\plugins\myplugin\myplugin.dll C:\Application\plugins\myplugin\libs\utils.dll Here application.exe loads myplugin.dll dynamically via LoadLibrary. Note that I have no control over application.exe as I am developing the plugin only. What I want is to make myplugin.dll load libs\utils.dll via a relative path (ideally using static linking). That is, I don't want to be dependent on the location of application.exe. I currently add C:\Application\plugins\myplugin\libs to the PATH environment variable when installing myplugin, but environment variables are not an ideal solution and I want to avoid doing that. I was hoping I could use assemblies and config files to specify the relative path libs\utils.dll in myplugin.dll. And I tried this, but to no avail. I then saw someone mentioning here on StackOverflow that config files only work for applications (i.e. executables). But as I said above, I have no control over application.exe. Is there a solution to this seemingly simple problem which I believe on Unix systems can be solved via rpaths? A: You cannot statically link to a DLL path at all, relative or absolute. The PE imports table only contains filenames. That is why a DLL search path exists to locate DLLs. If you want to control where utils.dll is loaded from, you have to load it dynamically. myplugin.dll can retrieve its own path using GetModuleFileName(), using the module handle that is passed in to its DllMain() entry point. It can then remove the filename from the path, append the relative path to the path, and then load the DLL when needed (not inside of DllMain() itself, or else a deadlock/crash may occur). There are two ways you can handle this: load everything dynamically yourself: #include <windows.h> #include <shlwapi.h> #pragma comment(lib, "shlwapi.lib") HINSTANCE hThisDLL = NULL; HMODULE hUtils = NULL; typedef ReturnType __CallingConv (*DllFuncType)(Params); DllFuncType DllFunc = NULL; BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { if (fdwReason == DLL_PROCESS_ATTACH) { hThisDLL = hinstDLL; ... } return TRUE; } ... ReturnType CallDllFunc(Params) { if (!hUtils) { TCHAR szUtilsFileName[MAX_PATH] = {0}; GetModuleFileName(hThisDLL, szUtilsFileName, MAX_PATH); if (!PathRemoveFileSpec(szUtilsFileName)) { // do something... return ...; } if (!PathAppend(szUtilsFileName, TEXT("libs\\utils.dll"))) { // do something... return ...; } hUtils = LoadLibrary(szUtilsFileName); if (!hUtils) { // do something... return ...; } } if (!DllFunc) { DllFunc = (DllFuncType) GetProcAddress(hUtils, "DllFuncName"); if (!DllFunc) { // do something... return ...; } } return DllFunc(Params); } static link to everything like you normally would, but then utilize your compiler's delay load feature (if supported) so you can specify the DLL's filename dynamically at runtime, but still statically link to the DLL function itself (the delay-load mechanism will call GetProcAddress() for you). #include <windows.h> #include <shlwapi.h> #include <delayimp.h> #pragma comment(lib, "Delayimp.lib") #pragma comment(lib, "shlwapi.lib") HINSTANCE hThisDLL = NULL; FARPROC WINAPI DelayLoadHook(unsigned dliNotify, PDelayLoadInfo pdli) { if ((dliNotify == dliNotePreLoadLibrary) && (strcmpi(pdli->szDll, "utils.dll") == 0)) { TCHAR szUtilsFileName[MAX_PATH] = {0}; GetModuleFileName(hThisDLL, szUtilsFileName, MAX_PATH); if (!PathRemoveFileSpec(szUtilsFileName)) { // do something... return NULL; } if (!PathAppend(szUtilsFileName, TEXT("libs\\utils.dll"))) { // do something... return NULL; } HMODULE hUtils = LoadLibrary(szUtilsFileName); return reinterpret_cast<FARPROC>(hUtils); } return NULL; } PfnDliHook __pfnDliNotifyHook2 = DelayLoadHook; BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { if (fdwReason == DLL_PROCESS_ATTACH) { hThisDLL = hinstDLL; ... } return TRUE; } ... ReturnType CallDllFunc(Params) { return DllFuncName(Params); }
{ "pile_set_name": "StackExchange" }
Q: Remote Xdebug with PhpStorm On my remote server I have xdebug installed and I am doing a port forward from my server to my local machine in order to debug. The issue is that the request is coming in and the mapping for files is prompted but when I choose the corresponding file PHPStorm show me the /var/www/html/index.php like on the server. Does anyone have any idea how to fix this? I can complete my question with tech details if needed. Update 1 https://imagebin.ca/v/3I2XzlNC7J8C A: Take a look at this a little old, but still valid blog post. In short, you need to define an environment variable PHP_IDE_CONFIG that will tell PhpStorm to use a specific mapping config. For example, in Ubuntu you can do the following: $ export PHP_IDE_CONFIG="serverName=yourServerName" Instead of yourServerName you need to put the name of the server configuration that you defined in PhpStorm Servers Settings.
{ "pile_set_name": "StackExchange" }
Q: Creating a file under nested folder in Sharepoint What's the best way to create a file under a nested folder in Sharepoint ? My current method public string CreateSPFile(string spServerURL, string spDocumentLibraryURL, string folder, string fileName, Stream fileStream, bool overwrite) { if (SPSite.Exists(new Uri(spServerURL))) { SPSite site = new SPSite(spServerURL); SPWeb oWebsite = site.OpenWeb(); oWebsite.AllowUnsafeUpdates = true; SPFolder spFolder = oWebsite.Folders[spDocumentLibraryURL]; if (!string.IsNullOrEmpty(folder)) { spFolder.SubFolders[folder].Files.Add(fileName, fileStream, overwrite); } else { SPFileCollection files = spFolder.Files; spFolder.Files.Add(fileName, fileStream, overwrite); } oWebsite.AllowUnsafeUpdates = false; site.Close(); } } As you can see, if I want to create a file under nested folder, i need to modified my codes. What will be better way to handle this kind of saving nested folder situation? According to my project structure, the file can be like /DocumentLibrary/Folder1/Folder2/Folder3/File.txt. A: You can load a folder by its server relative URL: SPFolder folder = web.GetFolder("/DocumentLibrary/Folder1/Folder2/Folder3/"); With this approach you do not have to load folder by folder and your code works with n folder levels. I've updated your code sample and added some comments regarding SharePoint best practices: public string CreateSPFile(string spServerURL, string spDocumenttargetUrl, string folder, string fileName, Stream fileStream, bool overwrite) { // I suggest skip this pre check since it internally opens a new site object // If you have to silenlty ignore non-existant SPSite you should catch a FileNotFoundException. if (SPSite.Exists(new Uri(spServerURL))) { // use the using construct to safely dispose the opened SPSite object using (SPSite site = new SPSite(spServerURL)) { // SPWeb object opened with SPSite.OpenWeb() have to be disposed as well using (SPWeb web = site.OpenWeb()) { web.AllowUnsafeUpdates = true; string targetUrl = SPUrlUtility.CombineUrl(web.ServerRelativeUrl, spDocumenttargetUrl); if (!String.IsNullOrEmpty(folder)) { targetUrl = SPUrlUtility.CombineUrl(targetUrl, folder); } SPFolder target = web.GetFolder(target); SPFileCollection files = target.Files; target.Files.Add(fileName, fileStream, overwrite); // no need to revert AllowUnsafeUpdates for newly opened webs // web.AllowUnsafeUpdates = false; } } } } A: For uploading a file into a nested folder you could consider the following approach: ensure the target folder exist using the method EnsureFolder provided below upload a file using SPFileCollection.Add method How to ensure a nested Folder exist using SharePoint SSOM internal static class SPWebExtensions { /// <summary> /// Ensure SPFolder /// </summary> /// <param name="web"></param> /// <param name="listTitle"></param> /// <param name="folderUrl"></param> /// <returns></returns> public static SPFolder EnsureFolder(this SPWeb web, string listTitle, string folderUrl) { if (string.IsNullOrEmpty(folderUrl)) throw new ArgumentNullException("folderUrl"); var list = web.Lists.TryGetList(listTitle); return CreateFolderInternal(list, list.RootFolder, folderUrl); } private static SPFolder CreateFolderInternal(SPList list, SPFolder parentFolder, string folderUrl) { var folderNames = folderUrl.Split(new char[] {'/'}, StringSplitOptions.RemoveEmptyEntries); var folderName = folderNames[0]; var curFolder = parentFolder.SubFolders.Cast<SPFolder>().FirstOrDefault( f => System.String.Compare(f.Name, folderName, System.StringComparison.OrdinalIgnoreCase) == 0); if (curFolder == null) { var folderItem = list.Items.Add(parentFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, folderName); folderItem.SystemUpdate(); curFolder = folderItem.Folder; } if (folderNames.Length > 1) { var subFolderUrl = string.Join("/", folderNames, 1, folderNames.Length - 1); return CreateFolderInternal(list, curFolder, subFolderUrl); } return curFolder; } } Gist: EnsureFolder.cs The following example demonstrates how to ensure the following folder structure exist under Documents library and upload a file into it: Orders | A -- | A1 Example: var targetFolder = web.EnsureFolder("Documents", "Orders3/A/A1"); var fileContent = System.IO.File.ReadAllBytes(fileName); var fileUrl = Path.GetFileName(fileName); targetFolder.Files.Add(fileUrl, fileContent);
{ "pile_set_name": "StackExchange" }
Q: How to check if an object can be instantiated using PHP I can't do this but wondering what would work: is_object(new Memcache){ //assign memcache object $memcache = new Memcache; $memcache->connect('localhost', 11211); $memcache->get('myVar'); } else{ //do database query to generate myVar variable } A: You can use class_exists() to check if a class exists, but it will not return if you can instantiate that class! One of the reasons you can't, might be that it is an abstract class. To check for that you should do something like this after you check for class_exists(). This might be impossible (having an abstract class, not checking for it) for above example, but in other situations might be giving you headaches :) //first check if exists, if (class_exists('Memcache')){ //there is a class. but can we instantiate it? $class = new ReflectionClass('Memcache') if( ! $class->isAbstract()){ //dingdingding, we have a winner! } } A: See class_exists if (class_exists('Memcache')){ //assign memcache object $memcache = new Memcache; $memcache->connect('localhost', 11211); $memcache->get('myVar'); } else{ //do database query to generate myVar variable }
{ "pile_set_name": "StackExchange" }
Q: SmartOS reboots spontaneously I run a SmartOS system on a Hetzner EX4S (Intel Core i7-2600, 32G RAM, 2x3Tb SATA HDD). There are six virtual machines on the host: [root@10-bf-48-7f-e7-03 ~]# vmadm list UUID TYPE RAM STATE ALIAS d2223467-bbe5-4b81-a9d1-439e9a66d43f KVM 512 running xxxx1 5f36358f-68fa-4351-b66f-830484b9a6ee KVM 1024 running xxxx2 d570e9ac-9eac-4e4f-8fda-2b1d721c8358 OS 1024 running xxxx3 ef88979e-fb7f-460c-bf56-905755e0a399 KVM 1024 running xxxx4 d8e06def-c9c9-4d17-b975-47dd4836f962 KVM 4096 running xxxx5 4b06fe88-db6e-4cf3-aadd-e1006ada7188 KVM 9216 running xxxx5 [root@10-bf-48-7f-e7-03 ~]# The host reboots several times a week with no crash dump in /var/crash and no messages in the /var/adm/messages log. Basically /var/adm/messages looks like there was a hard reset: 2012-11-23T08:54:43.210625+00:00 10-bf-48-7f-e7-03 rsyslogd: -- MARK -- 2012-11-23T09:14:43.187589+00:00 10-bf-48-7f-e7-03 rsyslogd: -- MARK -- 2012-11-23T09:34:43.165100+00:00 10-bf-48-7f-e7-03 rsyslogd: -- MARK -- 2012-11-23T09:54:43.142065+00:00 10-bf-48-7f-e7-03 rsyslogd: -- MARK -- 2012-11-23T10:14:43.119365+00:00 10-bf-48-7f-e7-03 rsyslogd: -- MARK -- 2012-11-23T10:34:43.096351+00:00 10-bf-48-7f-e7-03 rsyslogd: -- MARK -- 2012-11-23T10:54:43.073821+00:00 10-bf-48-7f-e7-03 rsyslogd: -- MARK -- 2012-11-23T10:57:55.610954+00:00 10-bf-48-7f-e7-03 genunix: [ID 540533 kern.notice] #015SunOS Release 5.11 Version joyent_20121018T224723Z 64-bit 2012-11-23T10:57:55.610962+00:00 10-bf-48-7f-e7-03 genunix: [ID 299592 kern.notice] Copyright (c) 2010-2012, Joyent Inc. All rights reserved. 2012-11-23T10:57:55.610967+00:00 10-bf-48-7f-e7-03 unix: [ID 223955 kern.info] x86_feature: lgpg 2012-11-23T10:57:55.610971+00:00 10-bf-48-7f-e7-03 unix: [ID 223955 kern.info] x86_feature: tsc 2012-11-23T10:57:55.610974+00:00 10-bf-48-7f-e7-03 unix: [ID 223955 kern.info] x86_feature: msr 2012-11-23T10:57:55.610978+00:00 10-bf-48-7f-e7-03 unix: [ID 223955 kern.info] x86_feature: mtrr 2012-11-23T10:57:55.610981+00:00 10-bf-48-7f-e7-03 unix: [ID 223955 kern.info] x86_feature: pge 2012-11-23T10:57:55.610984+00:00 10-bf-48-7f-e7-03 unix: [ID 223955 kern.info] x86_feature: de 2012-11-23T10:57:55.610987+00:00 10-bf-48-7f-e7-03 unix: [ID 223955 kern.info] x86_feature: cmov 2012-11-23T10:57:55.610995+00:00 10-bf-48-7f-e7-03 unix: [ID 223955 kern.info] x86_feature: mmx 2012-11-23T10:57:55.611000+00:00 10-bf-48-7f-e7-03 unix: [ID 223955 kern.info] x86_feature: mca 2012-11-23T10:57:55.611004+00:00 10-bf-48-7f-e7-03 unix: [ID 223955 kern.info] x86_feature: pae 2012-11-23T10:57:55.611008+00:00 10-bf-48-7f-e7-03 unix: [ID 223955 kern.info] x86_feature: cv8 The problem is that sometimes the host loses the network interface on reboot so we need to perform a manual hardware reset to bring it back. We do not have physical or virtual access to the server console - no KVM, no iLO or anything like this. So, the only way to debug is to analyze crash dumps/log files. I am not a SmartOS/Solaris expert so I am not sure how to proceed. Is there any equivalent of Linux netconsole for SmartOS? Can I just redirect the console output to the network port somehow? Maybe I am missing something obvious and crash information is located somewhere else. A: Run the command dumpadm to check crash dumps are enabled, and on what device. If it is enabled and you find no crash dumps, then suspect a hardware fault and ask your hosting company to move you to a different physical server. (They will also be able to check hardware logs and fault lights and call the vendor and so on.)
{ "pile_set_name": "StackExchange" }
Q: Firefox absolute positioning failure My website http://cynthiawoodyardlandscapedesign.com/ has a couple of issues that are only present in Firefox. When an image on the home page is clicked on, the arrows that appear on either side to allow the user to change the picture are way at the top of the page. The div that holds the arrows should have a height of 100%, I even added !important to the CSS. Only Firefox doesn't show this correctly. My css (http://cynthiawoodyardlandscapedesign.com/css/main.css): #sheet { width: 100%; height: 100%; position: fixed; overflow: hidden; top: 0; left: 0; background-color: rgba(0,0,0,0.8); display: table; z-index: 150; } #popover { margin: auto; background: rgba(0,0,0,0); text-align: center; padding: 10px; border: 1px solid black; position: relative; display: table-cell; vertical-align: middle; } #popover-image { height: 70%; border: 10px solid white; } #exit { position: absolute; top: 50px; color: white; font-size: 20px; font-weight: bold; width: 100%; text-align: center; z-index: 300; font-family: sans-serif; } #next-image, #previous-image { cursor: pointer; background: transparent; } #next-image::-moz-selection, #previous-image::-moz-selection, #next-image::selection, #previous-image::selection { background: rgba(0,0,0,0); } #leftArrow, #rightArrow { width: 20%; height: 100% !important; position: absolute; z-index: 200; display: table; background: transparent; top: 0; } #leftArrow { left: 0; } #rightArrow { right: 0; } #next-image { display: table-cell !important; vertical-align: middle; margin: 0 auto; text-align: center; line-height: 50px; font-size: 50px; -webkit-text-stroke: 1px black; -moz-text-stroke: 1px black; height: 50px; width: 50px; color: white; } #previous-image { display: table-cell !important; vertical-align: middle; margin: 0 auto; text-align: center; line-height: 50px; font-size: 50px; -webkit-text-stroke: 1px black; -moz-text-stroke: 1px black; height: 50px; width: 50px; color: white; } My HTML (http://cynthiawoodyardlandscapedesign.com/default.php): <div id="sheet"> <div id="exit">Exit</div> <div id="popover"> <div id="leftArrow"><div id="previous-image" onclick="previous()">&laquo;</div></div> <img src="watermark.php?src=images/main1.jpg&x=0&y=420&opactity=50" id="popover-image" onclick="close()" /> <div id="rightArrow"><div id="next-image" onclick="next()">&raquo;</div></div> </div> </div> Every other browser that I've tried (except IE; I am on a Mac) displays the page correctly. EDIT: I am having more Firefox issues. The page at http://cynthiawoodyardlandscapedesign.com/photography.php shows many pictures that are in <td> tags and after the img but before the </td> there is a span that has an absolute position, top: 10px; On every browser (even IE8!!) it doesn't work correctly. My HTML page: <table id="photos"> <tr> <td><img src="images/photo-thumbs/garden.jpg" /><span>Gardens</span></td><td><img src="images/photo-thumbs/trees.jpg" /><span>Trees</span></td><td><img src="images/photo-thumbs/shrubs.jpg" /><span>Shrubs</span></td><td><img src="images/photo-thumbs/perennials.jpg" /><span>Perennials</span></td> </tr> <tr> <td><img src="images/photo-thumbs/annuals.jpg" /><span>Annuals</span></td><td><img src="images/photo-thumbs/tropicals.jpg" /><span>Tropicals</span></td><td><img src="images/photo-thumbs/bulb.jpg" /><span>Bulbs</span></td><td><img src="images/photo-thumbs/containers.jpg" /><span>Containers</span></td> </tr> <tr> <td><img src="images/photo-thumbs/fruit.jpg" /><span>Fruit</span></td><td><img src="images/photo-thumbs/animals.jpg" /><span>Creatures</span></td><td><img src="images/photo-thumbs/people.jpg" /><span>People</span></td><td><img src="images/photo-thumbs/travel.jpg" /><span>Travel</span></td> </tr> </table> #photos td { width: 192px; height: auto; position: relative; border-right: 5px solid transparent; } #photos td img { width: 100%; border: 1px solid gold; } #photos td span { position: absolute; top: 10px; left: 0; width: 100%; text-align: center; background: rgba(0,0,0,0.4); padding-top: 2px; padding-bottom: 2px; color: #f0f0f0; font-weight: bold; font-family: "Source Sans Pro", sans-serif; display: none; } A: Here is the answer of your second part: Hover issue with span position. It is working fine see the below changes i have done in html, css and jquery code. please let me know if i am missing something. Code: http://jsfiddle.net/brNdq/1/ Working Demo: http://jsfiddle.net/brNdq/1/embedded/result/ HTML: <table id="photos"> <tr> <td><div class="img_container"><img src="http://cynthiawoodyardlandscapedesign.com/images/photo-thumbs/garden.jpg" /><span>Gardens</span></div></td> <td><div class="img_container"><img src="http://cynthiawoodyardlandscapedesign.com/images/photo-thumbs/trees.jpg" /><span>Trees</span></div></td> <td><div class="img_container"><img src="http://cynthiawoodyardlandscapedesign.com/images/photo-thumbs/shrubs.jpg" /><span>Shrubs</span></div></td> <td><div class="img_container"><img src="http://cynthiawoodyardlandscapedesign.com/images/photo-thumbs/perennials.jpg" /><span>Perennials</span></div></td> </tr> <tr> <td><div class="img_container"><img src="http://cynthiawoodyardlandscapedesign.com/images/photo-thumbs/annuals.jpg" /><span>Annuals</span></div></td> <td><div class="img_container"><img src="http://cynthiawoodyardlandscapedesign.com/images/photo-thumbs/tropicals.jpg" /><span>Tropicals</span></div></td> <td><div class="img_container"><img src="http://cynthiawoodyardlandscapedesign.com/images/photo-thumbs/bulb.jpg" /><span>Bulbs</span></div></td> <td><div class="img_container"><img src="http://cynthiawoodyardlandscapedesign.com/images/photo-thumbs/containers.jpg" /><span>Containers</span></div></td> </tr> </table> CSS: .img_container { position:relative; } Jquery: Remove hover from TD and put it on class .img_container <script type="text/javascript"> $(document).ready(function () { $(".img_container").hover(function() { $(this).children('span').fadeIn('medium'); }, function () { $(this).children('span').fadeOut('fast'); }); }); </script>
{ "pile_set_name": "StackExchange" }
Q: Is it possible to Redirect an HTTPPost in ASP.NET MVC? In my MVC application I have a View that collects user input in a basic Form. When the user hits submit it Posts to my MVC Application where I perform a database operation but then need to redirect the values from the Form to an external URL via another HTTP Post. The real scenario is as follows. 1. I display a Shopping Cart Page. The View contains an Html Form which contains financial details (ie. items, unit price, quanitities and a total). As well it collects billing and shipping information. 2. When the user hit the submit the Form values are included in a Post to my MVC Application. At this point I need to record that a payment is about to be collected so I write an entry to my database. Then I need to redirect to a third party site that will do the credit card processing. This redirect must be an HTTP Post that includes the same Form Values from my original Form. 3. The user will be presented with the third party credit card processing page. It handles the redirect to me. Thanks. A: You could make an Ajax call when the user first submits the form. The call would write to your database, return data (if needed) to the page, then the callback would post the page to the third party.
{ "pile_set_name": "StackExchange" }
Q: Want to extract pinned messages from the groups/channels on Telegram i am part of using Telethon I'm using Telethon API Want to extract pinned messages of all the channels i am member. Please guide me with the procedure. Thank you. A: use can use GetFullChannelRequest and GetHistoryRequest methods to extract pinned message from one channel from telethon import TelegramClient from telethon.tl.functions.channels import GetFullChannelRequest from telethon.tl.functions.messages import GetHistoryRequest from telethon.tl.types import PeerChannel api_id = XXXXX api_hash = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' phone_number = '+98XXXXXXXX' ################################################ client = TelegramClient('session_name', api_id, api_hash ) assert client.connect() if not client.is_user_authorized(): client.send_code_request(phone_number) me = client.sign_in(phone_number, input('Enter code: ')) channel_entity = client.get_entity(PeerChannel(channel_id)) channel_info = client(GetFullChannelRequest(channel_entity)) pinned_msg_id = channel_info.full_chat.pinned_msg_id if pinned_msg_id is not None: posts = client(GetHistoryRequest( channel_entity, limit=1, offset_date=None, offset_id=pinned_msg_id + 1, max_id=0, min_id=0, add_offset=0, hash=0 )) print(posts.messages[0].to_dict()) I used Telethon V0.19, but the previous versions are pretty much the same
{ "pile_set_name": "StackExchange" }
Q: Python from matrix to simple text file I would like to ask you how to change file looks like this: 123 111 1 146 204 2 178 398 1 ... ... First column is x, second is y and the third mean the number in each square. My matrix is 400x400 dimension. I would like to change it to the simple file M file doesn't posses every square (for example 0 0 doesn't exist which mean that in output file i would like to have 0 in first row in first place. My output file should look like this 0 0 1 0 0 0 1 0 7 9 3 0 2 0 ... 8 0 0 1 0 0 0 0 0 0 0 0 0 0 ... 7 8 9 0 7 5 0 0 3 2 4 5 5 7 ... ... ... How can I change my file? From first file i would like to reah second file. Like text file with 400lines each 400 characters splited by " " (blankspace). A: Just initialize your matrix as as a list of list of zeros, and then iterate the lines in the file and set the values in the matrix accordingly. Cells that are not in the file will remain unchanged. matrix = [[0 for i in range(400)] for k in range(400)] with open("filename") as data: for row in data: (x, y, n) = map(int, row.split()) matrix[x][y] = n Finally, write that matrix to another file: with open("outfile", "w") as outfile: for row in matrix: outfile.write(" ".join(map(str, row)) + "\n") You could also use numpy: matrix = numpy.zeros((4,4), dtype=numpy.int8)
{ "pile_set_name": "StackExchange" }
Q: inserting batch update no error but number of rows effected -2 Java + Spring + JPA + Hibernate + oracle I am using following code to batch inserts when i execute the following code i get response -2 and no record insert into the table. any help ? Example code.java List<ReportItem> reportItems = new ArrayList<ReportItem>(); ReportItem reportItem = new ReportItem(); reportItems.add(reportItem); reportItem.setReportId(new Long(61)); reportItem.setLicenseWindowEnd("LICENSE_WINDOW_END"); reportItem.setLicenseWindowStart("LICENSE_WINDOW_START"); reportItem.setPackageAssetID("PACKAGE_ASSET_ID"); reportItem.setPackageAssetName("PACKAGE_ASSET_NAME"); reportItem.setPackageProvider("PACKAGE_PROVIDER"); reportItem.setPackageProviderID("PACKAGE_PROVIDER_ID"); reportItem.setPackageUpdateNum("PACKAGE_UPDATE_NUM"); reportItem.setTitle("TITLE"); reportItem.setTitleAssetID("TITLE_ASSET_ID"); reportItem.setTitleBrief("TITLE_BRIEF"); reportItem.setTitleProviderID("TITLE_PROVIDER_ID"); reportItem.setTitleUpdateNum("TITLE_UPDATE_NUM"); reportItem.setTargetPitchDate("TARGET_PITCH_DATE"); reportItem.setAssetCdnStatus("ASSET_CDN_STATUS"); reportItem.setAssetReceived("ASSET_RECEIVED"); reportItem.setAssetReceived("ASSET_AVAILABLE"); int[] counts = reportDAO.insertBatchReportItems(reportItems); // response return counts[0] is -2 Dao.java @Override public int[] insertBatchReportItems(final List<ReportItem> reportItems) { int[] counts = getJdbcTemplate().batchUpdate(sql, new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int i) throws SQLException { ReportItem reportItem = reportItems.get(i); ps.setLong(1, reportItem.getReportId()); ps.setString(2, reportItem.getLicenseWindowEnd()); ps.setString(3, reportItem.getLicenseWindowStart()); ps.setString(4, reportItem.getPackageAssetID()); ps.setString(5, reportItem.getPackageAssetName()); ps.setString(6, reportItem.getPackageProvider()); ps.setString(7, reportItem.getPackageProviderID()); ps.setString(8, reportItem.getPackageUpdateNum()); ps.setString(9, reportItem.getTitle()); ps.setString(10, reportItem.getTitleAssetID()); ps.setString(11, reportItem.getTitleBrief()); ps.setString(12, reportItem.getTitleProviderID()); ps.setString(13, reportItem.getTitleUpdateNum()); ps.setString(14, reportItem.getTargetPitchDate()); ps.setString(15, reportItem.getAssetCdnStatus()); ps.setString(16, reportItem.getAssetReceived()); ps.setString(17, reportItem.getAssetAvailable()); } @Override public int getBatchSize() { return reportItems.size(); } }); return counts; } A: According to jdbc Statement.SUCCESS_NO_INFO — the command was processed successfully, but the number of rows affected is unknown Statement.SUCCESS_NO_INFO is defined as being -2, so your result says everything worked fine, but you won't get information on the number of updated columns. As per oracle docs For a prepared statement batch, it is not possible to know the number of rows affected in the database by each individual statement in the batch. Therefore, all array elements have a value of -2. According to the JDBC 2.0 specification, a value of -2 indicates that the operation was successful but the number of rows affected is unknown.
{ "pile_set_name": "StackExchange" }
Q: DateTimeParseException while using java.time.temporal.ChronoUnit I am new to both stack overflow and programming. I am trying to use Java 8's to find the time difference between a TimeStamp value and Current Time Stamp Value. Following is my code snippet of my Scala code: println(ChronoUnit.MILLIS.between(Instant.parse("1534274986"), Instant.now())) It works fine until I have a test case where the epoch to Human DateTime comes down to 08/14/18 19:06:17. In that case, I get an error as: Execution exception[[DateTimeParseException: Text '08/14/18 19:06:17' could not be parsed at index 0]] Please help me understand why I am getting such an error. Thank you. A: The .parse() method of LocalDateTime is rather limited by default. That's why you run into that error posted above. But you can solve this problem by designing and applying your own particular formatter using a FormatterBuilder in between: import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.temporal.ChronoField; import java.time.temporal.ChronoUnit; DateTimeFormatter formatter = new DateTimeFormatterBuilder() .appendPattern("MM/dd/yy[ HH:mm:ss]") .parseDefaulting(ChronoField.HOUR_OF_DAY, 0) .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0) .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0) .toFormatter(); LocalDateTime localDateTime1 = LocalDateTime.parse("08/14/18 19:06:17", formatter); LocalDateTime localDateTime2 = LocalDateTime.parse("08/14/18 19:08:19", formatter); System.out.println(ChronoUnit.MILLIS.between(localDateTime1, localDateTime2)); // Result: 122000 ms You can compare the formatted time to the current local time as well: LocalDateTime currentDateTime = LocalDateTime.now(); System.out.println(ChronoUnit.MILLIS.between(localDateTime1, currentDateTime)); And if you prefer to work with Instant you can easily create your own out of the LocalDateTime instances you parsed above: import java.time.*; LocalDateTime currentDateTime = LocalDateTime.now(); ZoneId zoneId = ZoneId.of("US/Eastern"); ZonedDateTime zonedDateTime = ZonedDateTime.of(currentDateTime, zoneId); Instant instant = zonedDateTime.toInstant();
{ "pile_set_name": "StackExchange" }
Q: Placing Multilple Google Charts on webpage from MYSQL Data I have been able to show a google chart from mysql data, but when I add the second chart I am only able to see the data from the 2nd array(for 2nd chart) I used json_encode on in my php script. If I change the order of the array encoding so that the 2nd chart's array is now encoded first I no longer see it, but now the first chart is visible. Can anyone see the issue? Maybe I should use column charts instead of material charts?? here is my javascript: <script type="text/javascript"> google.setOnLoadCallback(drawCharts); function drawCharts() { drawChartA(); drawChartB(); } function drawChartB(){ var data = new google.visualization.DataTable(<?=$jsonTable?>); var options = { chart: { title: 'Calls for <?php echo $cLabel;?>', subtitle: 'Something to put Here', }, annotations:{ textStyle:{ fontName: 'Times-Roman', fontSize: 12, bold: true, italic: false } }, width: 1200, height: 600, }; var chart = new google.charts.Bar(document.getElementById('chart_div')); chart.draw(data, google.charts.Bar.convertOptions(options)); } function drawChartA(){ var data = new google.visualization.DataTable(<?=$jsonTable_ct?>); var options = { chart: { title: 'Calls for <?php echo $cLabel;?>', subtitle: 'Something to put Here', }, annotations:{ textStyle:{ fontName: 'Times-Roman', fontSize: 12, bold: true, italic: false } }, width: 1200, height: 600, isStacked: 'true', }; var chart = new google.charts.Bar(document.getElementById('chart_div_ct')); chart.draw(data, google.charts.Bar.convertOptions(options)); } </script> my json_encoded files are: {"cols":[{"label":"Time Interval","type":"string"},{"label":"Calls - All Offices","type":"number"}],"rows":[{"c":[{"v":"05:00"},{"v":1}]},{"c":[{"v":"06:00"},{"v":3}]},{"c":[{"v":"07:00"},{"v":9}]},{"c":[{"v":"07:30"},{"v":22}]},{"c":[{"v":"08:00"},{"v":82}]},{"c":[{"v":"08:30"},{"v":68}]},{"c":[{"v":"09:00"},{"v":97}]},{"c":[{"v":"09:30"},{"v":48}]},{"c":[{"v":"10:00"},{"v":56}]},{"c":[{"v":"10:30"},{"v":70}]},{"c":[{"v":"11:00"},{"v":75}]},{"c":[{"v":"11:30"},{"v":53}]},{"c":[{"v":"12:00"},{"v":56}]},{"c":[{"v":"12:30"},{"v":48}]},{"c":[{"v":"13:00"},{"v":22}]},{"c":[{"v":"13:30"},{"v":42}]},{"c":[{"v":"14:00"},{"v":40}]},{"c":[{"v":"14:30"},{"v":60}]},{"c":[{"v":"15:00"},{"v":69}]},{"c":[{"v":"15:30"},{"v":65}]},{"c":[{"v":"16:00"},{"v":73}]},{"c":[{"v":"16:30"},{"v":37}]},{"c":[{"v":"17:00"},{"v":20}]},{"c":[{"v":"17:30"},{"v":10}]},{"c":[{"v":"18:00"},{"v":10}]},{"c":[{"v":"18:30"},{"v":2}]},{"c":[{"v":"19:00"},{"v":1}]},{"c":[{"v":"19:30"},{"v":2}]},{"c":[{"v":"20:00"},{"v":1}]},{"c":[{"v":"20:30"},{"v":1}]}]} and the other is here: (they both work so reviewing this may not be necessary) {"cols":[{"label":"Time Interval","type":"string"},{"label":"NP Calls","type":"number"},{"label":"DR Calls","type":"number"},{"label":"RE Today Calls","type":"number"},{"label":"RE Future","type":"number"},{"label":"ACCT","type":"number"},{"label":"EMER","type":"number"},{"label":"Other Calls","type":"number"}],"rows":[{"c":[{"v":"05:00"},{"v":0},{"v":0},{"v":0},{"v":0},{"v":0},{"v":0},{"v":1}]},{"c":[{"v":"06:00"},{"v":0},{"v":0},{"v":1},{"v":0},{"v":0},{"v":0},{"v":0}]},{"c":[{"v":"07:00"},{"v":0},{"v":0},{"v":0},{"v":0},{"v":0},{"v":0},{"v":2}]},{"c":[{"v":"07:30"},{"v":2},{"v":0},{"v":3},{"v":0},{"v":0},{"v":1},{"v":2}]},{"c":[{"v":"08:00"},{"v":9},{"v":3},{"v":11},{"v":5},{"v":0},{"v":4},{"v":23}]},{"c":[{"v":"08:30"},{"v":1},{"v":2},{"v":13},{"v":7},{"v":2},{"v":4},{"v":14}]},{"c":[{"v":"09:00"},{"v":3},{"v":1},{"v":15},{"v":11},{"v":6},{"v":3},{"v":23}]},{"c":[{"v":"09:30"},{"v":0},{"v":0},{"v":4},{"v":6},{"v":5},{"v":0},{"v":16}]},{"c":[{"v":"10:00"},{"v":1},{"v":3},{"v":2},{"v":10},{"v":2},{"v":0},{"v":17}]},{"c":[{"v":"10:30"},{"v":5},{"v":1},{"v":1},{"v":10},{"v":2},{"v":3},{"v":23}]},{"c":[{"v":"11:00"},{"v":5},{"v":3},{"v":7},{"v":11},{"v":10},{"v":1},{"v":23}]},{"c":[{"v":"11:30"},{"v":4},{"v":1},{"v":2},{"v":6},{"v":2},{"v":0},{"v":18}]},{"c":[{"v":"12:00"},{"v":3},{"v":0},{"v":5},{"v":11},{"v":2},{"v":0},{"v":21}]},{"c":[{"v":"12:30"},{"v":5},{"v":1},{"v":4},{"v":4},{"v":4},{"v":1},{"v":5}]},{"c":[{"v":"13:00"},{"v":2},{"v":1},{"v":3},{"v":2},{"v":2},{"v":0},{"v":6}]},{"c":[{"v":"13:30"},{"v":2},{"v":0},{"v":1},{"v":3},{"v":1},{"v":0},{"v":15}]},{"c":[{"v":"14:00"},{"v":5},{"v":3},{"v":1},{"v":5},{"v":3},{"v":1},{"v":4}]},{"c":[{"v":"14:30"},{"v":3},{"v":1},{"v":5},{"v":6},{"v":6},{"v":0},{"v":19}]},{"c":[{"v":"15:00"},{"v":3},{"v":1},{"v":4},{"v":8},{"v":4},{"v":1},{"v":22}]},{"c":[{"v":"15:30"},{"v":8},{"v":1},{"v":0},{"v":10},{"v":4},{"v":0},{"v":22}]},{"c":[{"v":"16:00"},{"v":6},{"v":5},{"v":1},{"v":12},{"v":3},{"v":2},{"v":20}]},{"c":[{"v":"16:30"},{"v":3},{"v":4},{"v":3},{"v":7},{"v":3},{"v":1},{"v":7}]},{"c":[{"v":"17:00"},{"v":1},{"v":0},{"v":0},{"v":4},{"v":1},{"v":0},{"v":5}]},{"c":[{"v":"17:30"},{"v":0},{"v":1},{"v":0},{"v":1},{"v":1},{"v":0},{"v":1}]},{"c":[{"v":"18:00"},{"v":1},{"v":0},{"v":1},{"v":0},{"v":0},{"v":0},{"v":2}]},{"c":[{"v":"18:30"},{"v":0},{"v":0},{"v":0},{"v":1},{"v":0},{"v":0},{"v":0}]}]}Can A: It's most likely the same issue that was reported in google-visualization-issues repository. There are at least two solution available at the moment: Option 1. Render charts synchronously The general idea is to render chart synchronously. Since draw function is asyncronous, we utilize ready event handler for that purpose. Place ready event handler in every function before draw function invocation: if (typeof ready != "undefined") google.visualization.events.addOneTimeListener(chart, 'ready', ready); and change drawChartN() function signature to drawChartN(ready) Then replace: function drawCharts() { drawChartA(); drawChartB(); } with: function drawCharts() { drawChartA(function(){ drawChartB(); }); } PhpFiddle Option 2. Using the frozen version loader. Since The rollout of the v43 candidate release that would fix this problem switch to using the frozen version loader. Steps: 1)Add a reference to loader: <script src="//www.gstatic.com/charts/loader.js"></script> 2)Then load a 43 version of library: google.charts.load("43",{packages:["corechart","bar"]}); 3)Replace: function drawCharts() { drawChartA(); drawChartB(); } with google.charts.setOnLoadCallback(drawChartA); google.charts.setOnLoadCallback(drawChartB);
{ "pile_set_name": "StackExchange" }
Q: SQL Server 2016: How to read different substrings from a text with special characters I have a string with the value 'Initiator;[email protected]'. I would like to read these two fields in two separate queries. ';' would be the delimiter always. I used the below query and it works for fetching the email. However it looks overcomplicated to me. select SUBSTRING(NOTES (CHARINDEX(';',NOTES,1)+1),LEN(NOTES)) from DOCUMENT where DOC_ID = '12345' Can someone please help in simplifying it and reading both the values. Thanks in advance. A: First, your query looks fine for email but it has incorrect syntax, second just use left() with charindex() to get the first part : select left(notes, charindex(';', notes)-1), substring(notes, charindex(';', notes)+1, len(notes)) from document where doc_id = 12345;
{ "pile_set_name": "StackExchange" }
Q: How do I add typeahead.js (Bloodhound) to jQuery dynamically-created fields? I can load Twitter typeahead just fine on a static form. However, in this situation, I would like to apply it to a dynamically-generated field. Even though my duplication script adds the required ".typeahead" class to the new input, it never seems to work. Indeed, the static form is surrounded by several additional classes, which are not generated for the dynamic fields. I feel like there is something more I need to do in order for the dynamic fields to function like the static field, but I am not sure. The Javascript: <!-- Dataset: First Names --> var firstnames = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'), queryTokenizer: Bloodhound.tokenizers.whitespace, limit: 5, prefetch: { url: './datasets/firstnames.json', filter: function(list) { return $.map(list, function(firstname) { return { name: firstname }; }); } } }); firstnames.initialize(); $('.typeahead').typeahead(null, { name: 'firstnames', displayKey: 'name', source: firstnames.ttAdapter() }); <!-- Dataset: First Names (End) --> <!-- Dynamic Fields --> var count=2; $("#add").click(function(){ var html="<div id='div"+count+"'><input id='firstname"+count+"' type='text' class='typeahead' placeholder='Additional First Name'></input><button type='button' onclick=remover('"+count+"')>Remove</button></div>"; $("#additionalnames").append(html); count++; }); function remover(which){ $("#div"+which).remove(); } <!-- Dynamic Fields End --> The HTML: <p>Standard field works fine (type a letter from a to g):</p> <input type="text" id="firstname" name="firstname" class="typeahead" placeholder="First Name"> <br /><br /><br /><br /><br /><br /> <p>Dynamic field does not:</p> <div id="additionalnames"></div> <button id="add" type="button">Add Another</button> I don't think JSFiddle can handle my json file, so a live implementation is here: http://drjoeseriani.com/firstnames A downloadable version of this resides here: http://drjoeseriani.com/firstnames.zip Thanks for any help. A: Creating elements using javascript instead of appending raw markup can be useful. Why ? Because if you create an element using javascript (or jQuery), you can attach an event/plugins to it and in this case it can be a typeahead plugin. Like this var input = $('<input>').attr('id', 'firstname' + count).addClass('typeahead').prop('placeholder', 'Additional First Name'); Now that you have an input element you can attach .typehead({ ... }) to it. So your click event should be something like this. $("#add").click(function() { // creating a new <div id=count></div> var div = $('<div>').attr('id', count); // creating a new <input id=count class="typeahead" placeholder=".."></input> var input = $('<input>').attr('id', 'firstname' + count) .addClass('typeahead') .prop('placeholder', 'Additional First Name'); // creating a new <button>Remove</button> (with a click event) var button = $('<button>').text('Remove') .on('click', function() { $(this).closest('div').remove(); }); div.append(input); // appending the input to the div div.append(button); // appending the button to div // attaching typeahead to the newly creating input input.typeahead(null, { name: 'firstnames', displayKey: 'name', source: firstnames.ttAdapter() }); // appending our newly creating div with all the element inside to #additionalnames $("#additionalnames").append(div); // incrementing count count++; }); Also, I changed the took the liberty of removing the remover script all together. You can attach a click event to the button and look for the parent div and remove it using .closest() Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: Pandas - Return last/first day of the month in a custom Datetime Index I'm using a multi index columns dataframe with custom dates (specific holidays,weekdays..). DatetimeIndex(['1989-01-31', '1989-02-01', '1989-02-02', '1989-02-03', '1989-02-06', '1989-02-07', '1989-02-08', '1989-02-09', '1989-02-10', '1989-02-13', ... '2019-02-25', '2019-02-26', '2019-02-27', '2019-02-28', '2019-03-01', '2019-03-04', '2019-03-05', '2019-03-06', '2019-03-07', '2019-03-08'], dtype='datetime64[ns]', length=7585, freq=None) I need to slice it for first or last day of the month from the index. Due to holidays,... some first/last day of the month of the index would not match with freq = 'BM'. No need to mention i cannot use resample(),... Here an example: import pandas as pd import numpy as np idx = pd.DatetimeIndex(['1989-01-31', '1989-02-01', '1989-02-02', '1989-02-03','1989-02-06', '1989-02-07', '1989-02-08', '1989-02-09','1989-02-10', '1989-02-13', '2019-02-25', '2019-02-26', '2019-02-27', '2019-02-28','2019-03-01', '2019-03-04', '2019-03-05', '2019-03-06','2019-03-07', '2019-03-08'], dtype='datetime64[ns]') numbers = [0, 1, 2] colors = [u'green', u'purple'] col = pd.MultiIndex.from_product([numbers, colors],names=['number', 'color']) df = pd.DataFrame(np.random.rand(len(idx),len(col)),index =idx,columns=col) number 0 1 2 color green purple green purple green purple 2018-06-05 0.64943 0.64943 0.64943 0.64943 0.64943 0.64943 etc... Expected Output: 2018-06-29 0.64943 0.64943 0.64943 0.64943 0.64943 0.64943 How could i do this please ? thanks A: You need to use a Grouper on your DataFrame. Using the mcve in the above question: # Month End df.groupby(pd.Grouper(freq='M')).last() # Month Start df.groupby(pd.Grouper(freq='MS')).first() Note: Grouping in this manner groups by the DateTimeIndex month, whose group min and max months are calendrical and not necessarily in the index. So we can go after a grouping of our own, requiring attention to months repeating over the years. grpr = df.groupby([df.index.year, df.index.month]) data = [] for g, gdf in grpr: data.append(gdf.loc[gdf.index.min()]) data.append(gdf.loc[gdf.index.max()]) new_df = pd.DataFrame(data) new_df number 0 1 2 color green purple green purple green purple 1989-01-31 0.246601 0.915123 0.105688 0.645864 0.845655 0.339800 1989-01-31 0.246601 0.915123 0.105688 0.645864 0.845655 0.339800 1989-02-01 0.694509 0.665852 0.593890 0.715831 0.474022 0.011742 1989-02-13 0.770202 0.452575 0.935573 0.554261 0.235477 0.475279 2019-02-25 0.626251 0.826958 0.617132 0.118507 0.079782 0.183616 2019-02-28 0.740565 0.131821 0.968403 0.981093 0.211755 0.806868 2019-03-01 0.812805 0.379727 0.758403 0.345361 0.908825 0.166638 2019-03-08 0.238481 0.045592 0.740523 0.201989 0.432714 0.672510 It is correct to see duplication because gdf.index.min() may equal gdf.index.max(). A check would eliminate duplication when iterating over the groups.
{ "pile_set_name": "StackExchange" }
Q: JPA switching from "drop-and-create-table" to "none" results in massive Bugs My team and me are currently working at a project using Hibernate-Validation and JPA. Problem: we decided to use "drop-and-create-table" during the development-phase. everything worked just fine and as everything was implemented we changed the generation-mode to "none" (with a stable database running). What it was doing before: We drop the table, create the table from our entities with specific attributes and fill the table with some datasets. What it is doing now: We work on the existing, previously working, table (already filled with some data); but now some relations seem to be missing. Now we have encountered a number of Exceptions during runtime and we can't locate them. It seems, that some attribute-relationships were deleted or something, because there are Exceptions (e.g. NullPointerExceptions) thrown, that were not thrown before. Is there anything else we have to change in the persistence.xml, except the generation-mode? here's the code for the persistance.xml: <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="ticketline" transaction-type="RESOURCE_LOCAL"> <class>at.ticketline.entity.Veranstaltung</class> <class>at.ticketline.entity.Saal</class> <class>at.ticketline.entity.Reihe</class> <class>at.ticketline.entity.Platz</class> <class>at.ticketline.entity.Person</class> <class>at.ticketline.entity.Ort</class> <class>at.ticketline.entity.News</class> <class>at.ticketline.entity.Kunde</class> <class>at.ticketline.entity.Kuenstler</class> <class>at.ticketline.entity.Kategorie</class> <class>at.ticketline.entity.Bestellung</class> <class>at.ticketline.entity.BestellPosition</class> <class>at.ticketline.entity.BaseEntity</class> <class>at.ticketline.entity.Auffuehrung</class> <class>at.ticketline.entity.Artikel</class> <class>at.ticketline.entity.Adresse</class> <class>at.ticketline.entity.Benutzer</class> <class>at.ticketline.entity.Ticket</class> <class>at.ticketline.entity.compositekeys.PlatzPK</class> <class>at.ticketline.entity.compositekeys.ReihePK</class> <class>at.ticketline.entity.compositekeys.SaalPK</class> <class>at.ticketline.entity.compositekeys.AuffuehrungPK</class> <properties> <property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver" /> <property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:hsql://localhost/ticketline" /> <property name="javax.persistence.jdbc.user" value="sa" /> <property name="javax.persistence.jdbc.password" value="" /> <property name="eclipselink.ddl-generation" value="none" /> </properties> </persistence-unit> </persistence> Stack-Trace: !STACK 0 java.lang.NullPointerException at at.ticketline.kassa.ui.editor.TicketSuchergebnisEditor$11.getText(TicketSuchergebnisEditor.java:253) at org.eclipse.jface.viewers.ColumnLabelProvider.update(ColumnLabelProvider.java:36) at org.eclipse.jface.viewers.ViewerColumn.refresh(ViewerColumn.java:152) at org.eclipse.jface.viewers.AbstractTableViewer.doUpdateItem(AbstractTableViewer.java:399) at org.eclipse.jface.viewers.StructuredViewer$UpdateItemSafeRunnable.run(StructuredViewer.java:485) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:49) at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:175) at org.eclipse.jface.viewers.StructuredViewer.updateItem(StructuredViewer.java:2167) at org.eclipse.jface.viewers.AbstractTableViewer.createItem(AbstractTableViewer.java:277) at org.eclipse.jface.viewers.AbstractTableViewer.internalRefreshAll(AbstractTableViewer.java:757) at org.eclipse.jface.viewers.AbstractTableViewer.internalRefresh(AbstractTableViewer.java:649) at org.eclipse.jface.viewers.AbstractTableViewer.internalRefresh(AbstractTableViewer.java:636) at org.eclipse.jface.viewers.AbstractTableViewer$2.run(AbstractTableViewer.java:592) at org.eclipse.jface.viewers.StructuredViewer.preservingSelection(StructuredViewer.java:1443) at org.eclipse.jface.viewers.StructuredViewer.preservingSelection(StructuredViewer.java:1404) at org.eclipse.jface.viewers.AbstractTableViewer.inputChanged(AbstractTableViewer.java:590) at org.eclipse.jface.viewers.ContentViewer.setInput(ContentViewer.java:280) at org.eclipse.jface.viewers.StructuredViewer.setInput(StructuredViewer.java:1690) at at.ticketline.kassa.ui.editor.TicketSuchergebnisEditor.createPartControl(TicketSuchergebnisEditor.java:67) at org.eclipse.ui.internal.EditorReference.createPartHelper(EditorReference.java:670) at org.eclipse.ui.internal.EditorReference.createPart(EditorReference.java:465) at org.eclipse.ui.internal.WorkbenchPartReference.getPart(WorkbenchPartReference.java:595) at org.eclipse.ui.internal.PartPane.setVisible(PartPane.java:313) at org.eclipse.ui.internal.presentations.PresentablePart.setVisible(PresentablePart.java:180) at org.eclipse.ui.internal.presentations.util.PresentablePartFolder.select(PresentablePartFolder.java:270) at org.eclipse.ui.internal.presentations.util.LeftToRightTabOrder.select(LeftToRightTabOrder.java:65) at org.eclipse.ui.internal.presentations.util.TabbedStackPresentation.selectPart(TabbedStackPresentation.java:473) at org.eclipse.ui.internal.PartStack.refreshPresentationSelection(PartStack.java:1245) at org.eclipse.ui.internal.PartStack.setSelection(PartStack.java:1198) at org.eclipse.ui.internal.PartStack.showPart(PartStack.java:1597) at org.eclipse.ui.internal.PartStack.add(PartStack.java:493) at org.eclipse.ui.internal.EditorStack.add(EditorStack.java:103) at org.eclipse.ui.internal.PartStack.add(PartStack.java:479) at org.eclipse.ui.internal.EditorStack.add(EditorStack.java:112) at org.eclipse.ui.internal.EditorSashContainer.addEditor(EditorSashContainer.java:63) at org.eclipse.ui.internal.EditorAreaHelper.addToLayout(EditorAreaHelper.java:225) at org.eclipse.ui.internal.EditorAreaHelper.addEditor(EditorAreaHelper.java:213) at org.eclipse.ui.internal.EditorManager.createEditorTab(EditorManager.java:808) at org.eclipse.ui.internal.EditorManager.openEditorFromDescriptor(EditorManager.java:707) at org.eclipse.ui.internal.EditorManager.openEditor(EditorManager.java:666) at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditorBatched(WorkbenchPage.java:2942) at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditor(WorkbenchPage.java:2850) at org.eclipse.ui.internal.WorkbenchPage.access$11(WorkbenchPage.java:2842) at org.eclipse.ui.internal.WorkbenchPage$10.run(WorkbenchPage.java:2793) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:2789) at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:2773) at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:2756) at at.ticketline.kassa.ui.command.TicketSucheResultsCommandHandler.execute(TicketSucheResultsCommandHandler.java:28) at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:293) at org.eclipse.core.commands.Command.executeWithChecks(Command.java:476) at org.eclipse.ui.internal.handlers.HandlerService.executeCommand(HandlerService.java:178) at org.eclipse.ui.internal.handlers.SlaveHandlerService.executeCommand(SlaveHandlerService.java:247) at org.eclipse.ui.internal.handlers.SlaveHandlerService.executeCommand(SlaveHandlerService.java:247) at at.ticketline.kassa.ui.view.TicketSucheView.openEditor(TicketSucheView.java:246) at at.ticketline.kassa.ui.view.TicketSucheView$1.widgetSelected(TicketSucheView.java:194) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:240) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4165) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3754) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2701) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2665) at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2499) at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:679) at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:668) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149) at at.ticketline.kassa.TicketlineApplication.start(TicketlineApplication.java:21) at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:344) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:622) at org.eclipse.equinox.launcher.Main.basicRun(Main.java:577) at org.eclipse.equinox.launcher.Main.run(Main.java:1410) at org.eclipse.equinox.launcher.Main.main(Main.java:1386) A: My guess is that your database is missing some data. When you run your populate in memory, you are populating the shared cache and the database. However you are most likely no building your objects correctly. Maybe you have transient fields that you set in memory, but when you read from the database, these transient fields are null. Maybe you have bi-directional relationships and are not setting both sides of the relationships, so are not populating the database correctly. Maybe you have not mapped some attributes correctly, so the data in the database is not correct. My guess is that if you disabled the shared cache, you would have the same errors.
{ "pile_set_name": "StackExchange" }
Q: Writing to hardware register using void * I'm writing an application on top of an Altera soft processor. The API provides access to registers, defined in VHDL, as shown below. #define __IO_CALC_ADDRESS_DYNAMIC(BASE, OFFSET) \ ((void *)(((alt_u8*)BASE) + (OFFSET))) #define IOWR_32DIRECT(BASE, OFFSET, DATA) \ __builtin_stwio (__IO_CALC_ADDRESS_DYNAMIC ((BASE), (OFFSET)), (DATA)) Based on everything I've learned about writing code that interfaces with hardware or registers directly, I've written my code like this, typedef uint8_t volatile reg; /* special type to access registers */ typedef struct reg_one /* access to base and offsets */ { reg data_0; /* first 8 bits */ reg data_1; /* second 8 bits */ . . } reg_one; static reg_one *const reg_ptr = (reg_one *)SOME_BASE_ADDRESS; uint32_t data; data = 0; __builtin_stwio(&(reg_ptr->data_0), data); However, the address is cast to a void * and the volatile and const qualifiers are immediately discarded. Is there a work around for this, or am I just missing something simple? I understand that using a macro to define a pointer is an option, #define reg_ptr ((reg_one *)SOME_ADDRESS) but I'd prefer to use a constant object for scope and type. Thank you for any help in advance! A: I would think that a more appropriate way to use a struct to define one's device register interface would be to declare the struct with normal types, but then to qualify the struct's type with the keyword volatile when defining the pointer to the registers' base address, thus: typedef struct reg_one /* access to base and offsets */ { uint8_t data_0; /* first 8 bits */ uint8_t data_1; /* second 8 bits */ /* ... */ } reg_one; /* key addition: volatile applied to the struct's type, reg_one */ static volatile reg_one* const reg_ptr = (reg_one*)SOME_BASE_ADDRESS; This will mark all accesses made through the pointer reg_ptr to the members of that struct as volatile. This is useful for ensuring that such statements as reg_ptr->data_0 = (uint8_t)data; /* reg_ptr has type volatile reg_one*, so reg_ptr->data_0 has type volatile uint8_t */ won't be deleted or reordered by an optimizing compiler. But it appears you are not accessing these members through C-language assignments, inc/decrements or what not. Instead you use what looks like a GCC builtin, __builtin_stwio. According to http://www.johnloomis.org/altera/nios2/gnutools/binutils/gcc/Altera-Nios-II-Built-in-Functions.html, the builtin __builtin_stwio is defined as void __builtin_stwio (volatile void *, int) When you become involved with compiler builtins, all bets are off as to their true behaviour, because a compiler give them any special treatment it wants. That said, I'd say it's a safe bet that your GCC variant will honor what the prototype appears to suggest. In all likelyhood your compiler will neither delete nor reorder calls to this builtin, and thus its use will obey volatile semantics.
{ "pile_set_name": "StackExchange" }
Q: Mixture of Poisson Additive Regression Model This is for a personal project (Just learnt EM algorithm and GAM model; and thinking about combine them together) Believing that these data belongs to different clusters (where the labels are missing), and I want to do regression on them. Similar to mixture of expert that each regression take up its own data space Now, consider we have a much more complicated nonlinear data, instead of doing mix of simple linear regression, I'm thinking doing mix of Poisson regression with additive model So I'm thinking about mixture of regression using EM.The latent variable is the missing labels. So if I choose Poisson Regression with monomial basis functions Latent variable is Z, poisson counts is Y, input data is X, d is dimension of each data. So the likelihood would be $P(x) = \sum_k \alpha_k Poi(\lambda_k)$ where $\alpha_k$ is the weight for k-th cluster density ==============Updated================ Initialization: uniform outer weight $\alpha_k$ for each of GAM; naive guess for each GAM coefficient $\beta$; where $GAM_k = \alpha_k(\beta_0 + \sum_{d=1}^D \beta_d \times f_{d,k}(x)$) Repeat: (1) for each data point, I compute the posterior of responsibility $p(Z=z|X) = \frac{\alpha_z Poi(\lambda_z)}{\sum_k \alpha_k Poi(\lambda_k)}$ (2) update outer weight $\alpha_z = \frac{\sum_x P(Z=z|x)}{N}$ (3) for each GAM: backfitting algorithm update coefficient to get a new $GAM_k'$. Then $GAM_k \leftarrow P(Z=z|x) \times GAM_k'$ ======================================== Is this the approach you suggested? Any suggestions A: First, there should be a separate GAM for each Poisson mean. You can then fit each GAM using the latent probabilities as weights, or simply fit the GAM on the subset of the data $$S=\{x\in X: \mathop{\mathrm{argmax}}_i P(Z=i|X=x)=z\}$$ Rinse and repeat.
{ "pile_set_name": "StackExchange" }
Q: How do I find death details for an individual where no current online record exists? I am looking for the death details of a grandmother for a child in care. I have: the first and married name of the deceased the name of her surviving husband the approximate year of death (2009 - 2010) the region of death (Illawarra NSW) I do not know: the town she died in if she was cremated or buried. It is not possible to obtain further details from relatives or friends. I have searched any possible cemetery sites within the region, but there are not many indexed. I have not been able to find any Obituary or Funeral notice online in the local newspapers. A: If there was a newspaper notice of the death, it was probably in the Illawarra Mercury (incidentally, one of Australia's oldest newspapers). The site only displays classified notices from the last week but a Google search {site:illawarramercury.com.au archive 2010} generates plenty of hits indicating an extensive back catalogue. Unfortunately, they all lead to 404 (Page not found) apparently as a result of building a "new" website. The Ryerson Index_ is a community-generated index to death notices appearing in current Australian newspapers. It also includes some funeral notices, probate notices and obituaries. The website allows you to check the extent of coverage of each newspaper. Although the Mercury is incorrectly placed in some alphabetic lists as WOLLONGONG ILLAWARRA MERCURY, the coverage is excellent. RANGE OF NOTICES INDEXED Death Notices..... From January 1st, 1997 to November 10th, 2012 (40999) Funeral Notices.. From January 1st, 1997 to November 3rd, 2012 (2197) Use the surname and the presumed timespan to launch your search. With a little luck, you will locate a notice that refers to the deceased as "beloved sister of ..." or something similar that will open up new lines of research.
{ "pile_set_name": "StackExchange" }
Q: How to compute orthonormal basis for rank deficient rectangular matrix I'm doing a project which needs to compute the orthonormal basis of a rectangular matrix and this matrix may or may not be rank deficient. In matlab, we can just call function orth() which is based on svd to handle this problem, but I need to implement it in C. I tried to use Gram-Schmidt and it works well when the matrix is full-rank. Is there any library in C which can solve this problem? Or some hints on implementing it in C? Thanks a lot. A: When a matrix is rank-deficient by k (for instance, if a 4x3 matrix is of rank 2, then k=1), then you need to generate k random vectors and then subtract the components of other orthonormalized vectors previously generated by Gram-Schmidt from the random vectors. It is necessary to generate vectors yourself as you can see the following example: A 2x2 matrix 1 1 0 0 By Gram-Schmidt, you will get 1 0 0 0 It is because the original column space only contains a single direction. When you detect such a case (norm(v2) < eps, where eps is a sufficiently small floating-point number, like 1e-10), generate a random vector for the second vector v2, say 1 0.2 0 -0.3 subtract the component of v1 1 0 0 -0.3 and normalize the current v2 1 0 0 1 In such a way, you can construct the directions that don't exist in the original column space. Note that if computational speed is of your concern, at this point or at your production code, SVD should be avoided when possible. Although SVD and matrix-matrix product are both of O(N^3) complexity, SVD usually has a factor which is larger than 10 times slower compared to matrix-matrix product. In fact, in such a problem, SVD can be useful in your investigation, but a better tool should be QR decomposition, which is essentially Gram-Schidt but in different order of operations to have better numerical stability.
{ "pile_set_name": "StackExchange" }
Q: How to get   to behave properly using HTML Purifier? I am using HTML Purifier in my PHP project and am having trouble getting it to work properly with user input. I am having users enter in HTML using a WYSIWYG editor (TinyMCE), but whenever a user enters in the HTML entity &nbsp; (non-breaking space) it gets saved into the database as this weird foreign character (Â). However, the thing is, when I edit the saved entry using the WYSIWYG editor it gets displayed properly as &nbsp;. It also functions properly when displayed, only that in the source code it appears as a real space, but not the non-breaking space character. Also, in the MySQL database it displays as the weird foreign character. I read the doc about Unicode and HTML Purifier and changed my database and web page encoding to be UTF-8, but I am still having problems with the non-breaking space character not being mangled. The other HTML entities, such as &lt; and &gt;, get saved as < and >, but why not &nbsp;? A: The non-breaking space isn't being saved in your database as one weird foreign character, it's being saved as two characters. The Unicode non-breaking space character is encoded in UTF-8 as 0xC2 0xA0, which in ISO-8859-1 looks like " " (i.e. a weird foreign character followed by a non-breaking space). You're probably forgetting to do SET NAMES 'utf8' on your database connection, which causes PHP to send its data to MySQL as ISO-8859-1 (the default). Have a look at "UTF-8 all the way through…" to see how to properly set up UTF-8 when using PHP and MySQL.
{ "pile_set_name": "StackExchange" }
Q: Finding the range and domain of $f(x)=\tan (x)$ I am attempting to find the range and domain of $f(x)=\tan(x)$ and show why this is the case. I can seem to find the domain relatively well, however I run into problems with the range. Here's what I have done so far. Finding the domain of $f(x)=\tan(x)$ Consider $f(x)=\tan(x)$ is defined as $f(x)=\tan(x)=\frac{\sin(x)}{\cos(x)}$, it is clear the domain of $f(x)$ is undefined when $\cos(x)=0$. $\cos(x)=0$ whenever $x=\frac{\pi}{2}+\pi k$ for integers $k$, so the domain of $f(x) =\tan (x)$ can be stated as $x\in\mathbb{R}, x \ne \frac{\pi}{2}+\pi k\text{ for integers k}$ Finding the range of $f(x)=\tan(x)$ To find the range of $f(x)=\tan(x)$ we must refer to the definition of $f(x)=\tan(x)=\frac{\sin(x)}{\cos(x)}$. From this we can see that $f(x)$ is undefined when $\cos(x)=0$, as the interval of $\cos(x)$ is $[-1,1]$ we will now need to split this into two cases: $-1\leqslant\cos(x)<0$ and $0<\cos(x)\leqslant1$. Considering the first interval; $-1\leqslant\cos(x)<0$, as $\cos(x)\to0^-$: $\sin(x)\to1$ and $\tan(x)=\frac{\sin(x)}{\cos(x)}\approx\frac{1}{\text{very small(negative)}}\approx\text{very big(negative)}$. In other words as $\cos(x)\to0^-$, $\tan(x)\to-\infty$ Considering the second interval; $0<\cos(x)\leqslant1$, as $\cos(x)\to0^+$: $\sin(x)\to1$ and $\tan(x)=\frac{\sin(x)}{\cos(x)}\approx\frac{1}{\text{very small(positive)}}\approx\text{very big(positive)}$. In other words as $\cos(x)\to0^+$, $\tan(x)\to+\infty$. This is where I am up to. What I want to know is how I can show definitively that $tan(x)$ can take all the values within the interval $[-\infty,\infty]$. Some people would call it a day here, and say that this shows that the range of $f(x)$ is $-\infty<\tan(x)<\infty$. However I nearly ran into a similar error when I was finding the range of $\sec(x)$, only to discover that although it does tend to positive and negative infinity it doesnt take any values in the interval $(-1,1)$. Where do I proceed from here? EDIT: I am not looking for answers that use differentiation. Answers should be pre-calculus level. A: Firstly, I'd like to applaud you on your persistence in trying to get to a rigorous solution. I'll give you a hint for a geometric solution: if you use the triangle definition of a tangent, can you think of a way of constructing a triangle giving any desired value of tangent? Edit: some more detail Lets say I want to find a value of $x$ such that $\tan(x) = y$ for some $y$. Then I can construct a right angled triangle with sides of lengths $1, y$ and $\sqrt{1+y^2}$. Then if $x$ is the appropriate angle, then $\tan(x) = y$ A: This really is up to how rigourous you want to be. Your ideas on showing that $\tan(x)$ diverging to when $\cos(x)$ tends to 0 is fine, but rigourous proof would start from definition of 'tending to infinity' and manipulate limit definitions to show that these imply that $\tan(x)$ does tend to infinity according to definition. Also, it is benefitial to just consider the interval $(-\frac{\pi}{2},\frac{\pi}{2})$ since by periodicity of $\tan(x)$ any result on this interval would transport to whole interval immediately. Once you prove that $\tan(x) \rightarrow \pm\infty$ now you want to show that $\tan(x)$ is continuous on the interval $(-\frac{\pi}{2},\frac{\pi}{2})$. This can be done by showing that both $\sin(x)$ and $\cos(x)$ are continous on the interval (easy to show from definition), and appeal to algebra of limits version of continuity: since both are continous, $\tan(x)=\frac{\sin(x)}{\cos(x)}$ is continous. Once you have shown this, then you need to use Intermediate value Theorem. Since $\tan(x)$ goes to $\pm\infty$, we can always find, for any $y\in\mathbb{R}$ you can find $x_1,x_2\in(-\frac{\pi}{2},\frac{\pi}{2})$ such that $y$ lies strictly between $\tan(x_1)$ and $\tan(x_2)$ and apply IVT to $\tan(x)$ on $[x_1,x_2]$ (or $[x_2,x_1]$ as it may be) to find that there exists $z\in(-\frac{\pi}{2},\frac{\pi}{2})$ such that $\tan(z)=y$. edit: Okay, juding from your response, I highly doubt if you have ever come across rigourous definitions of limits and continuity of functions, so I guess giving you a bunch of $\epsilon - \delta$ arguments would be inappropriate ( try googling them to see what I mean by epsilon delta definition). I would start form 'definition' of $\sin(x)$ and $\cos(x)$. I reckon you most likely have met these definitions in terms of ratio between length of sides of triangle, and this definition does not make any sense, for instance, negative values of the fuctions: how would you have length being negative, and furthermore, how do you define the 'length?. Thus one way of defining $\sin(x)$ $\cos(x)$ is to do the following: define $\sin(x)$=$\sum\limits_{k=0}^\infty(-1)^k\frac{x^{2k+1}}{(2k+1)!}$ $\cos(x)$=$\sum\limits_{k=0}^\infty(-1)^k\frac{x^{2k}}{(2k)!}$ This definition coincides with Talyor series of sin and cos function, in case you would wonder why anyone would define them in this way. Now I am pretty sure you are happy with me saying functions like $f(x)=x$ are continuous. There is a theorem saying that: if $f,g$ are continous functions, then i) $\lambda fg$ and ii) $\lambda f+\mu g$ are also continous functions for any $\lambda, \mu \in\mathbb{R}$. Moreover, given $g\neq0$ the fuction iii) $\lambda \frac{f}{g}$ is also continous on the same domain. This is really intuitive, I hope, and you can accept this for now. Then you can see that both $\sin(x)$ and $\cos(x)$, as defined above are continous on the domain $(-\frac{\pi}{2},\frac{\pi}{2})$ (but justifying this requires the fact that both infinite series above are uniformly convergent on whole interval. But you can accept this now and, it must make intuitive sense to you: as you said, both $\sin(x)$ and $\cos(x)$ are real numberas and their quotient must exist continously). For instance, $x^{2k+1}$ is continuous for any k, by i) repeatedly applied to $f(x)=x$ Then since $\cos(x) \neq 0$ on the given domain, by third result $\frac{\sin(x)}{\cos(x)}=\tan(x)$ is continuous. I think all you need really is to know what it means(by definition, that is) a function to be continuous on a given domain, and use of some power series (but not one bit of calculus). Do not worry too much even if you cant fully understand why tan is onto $(-\infty,\infty)$. Once you have right techniques it must not be really difficult. I guess this one helps more: Consider a unit circle on x-y plane(radius=1). Consider a point P on the circumference, and let $\theta$ be angle measured from positive x axis in anticlockwise orientation. So a point (0,1) will have angle $\frac{\pi}{2}$. Define, for any point $P=(x,y)$ on circumference, $\sin(\theta)=y$ $\cos(\theta)=x$ $\tan(\theta)=\frac{\sin(\theta)}{\cos(\theta)}$ Then observe how tan is onto $(-\infty,\infty)$ as $\theta$ varies on $(-\frac{\pi}{2},\frac{\pi}{2})$
{ "pile_set_name": "StackExchange" }
Q: Moving Local PostgreSQL 8.4.20 Database to Amazon EC2 or RDS I'm running PostgresSQL 8.4.20 on a local server and plan to migrate the data to either Amazon EC2 or RDS. I have working knowledge of databases and need advice from experts. I've been researching this topic and I've come across some helpful and similar answers like this and this already. I'm leaning towards Amazon RDS because of automatic backups and less maintenance. But will I be able to install v8.4 on RDS? Or do I need to upgrade to v9.3+? Will moving data from v8.4 to v9.3 cause any issues? If so, maybe it is best to install v8.4 on EC2? A: Amazon's RDS only offers PostgreSQL versions 9.3.x, and it seems unlikely that they'll ever offer to host older versions of Postgres. So by jumping from a local 8.4 install directly to RDS, you would in effect be making two significant changes at once (jumping up several Postgres versions, as well as switching to managed hosting). That may be alright or not -- it all depends on what features you're using and depending on. You should do some reading on RDS's limitations (no external hot standby, limited extensions, no shell access to the database instance, etc.) and benefits (hopefully much less maintenance work) and decide whether it's right for you. Also, I suggest you walk through the steps of dumping and restoring your data into RDS and ensure your application works OK, as well as reading through the Postgres major-version release notes for 9.0, 9.1, 9.2, and 9.3, paying particular note to the incompatibilities listed to see if any of them would affect you.
{ "pile_set_name": "StackExchange" }
Q: In XNA, is there an issue with copying/pasting the using statements to each .cs file? When I'm working on a project in XNA I copy the using statements from file to file. However, on tutorials I've seen for various games, they show files that only have specific using statements used. Do the other statements cause problems in the event the program doesn't need it? I want to avoid any future problems. A: Extra using statements will very rarely cause problems, and when they do they will be because you have introduced an ambiguous name into the scope (for example, using two namespaces with both define a Vector type, and then trying to write Vector myVector = new Vector() will be ambiguous). The compiler will tell you of these name clashes, and fail to compile your code. If you run afoul of this, you can either fully-qualify the name reference (MyNamespace.Vector verus SomeOtherNamespace.Vector) or remove the unused using directives. Note that if you are using Visual Studio, there is an option in the right-click menu while in the text editor for a source file to "remove unused usings." You can also have them sorted via a similar menu command.
{ "pile_set_name": "StackExchange" }
Q: How does GL_ARB_shader_group_vote influence shader performance? The OpenGL extension GL_ARB_shader_group_vote provides a mechanism to group different shader invocations with the same value for a user-defined boolean condition, such that all invocations inside that group only need to evaluate one - the same - branch of a conditional statement. For example: if (anyInvocationARB(condition)) { result = do_fast_path(); } else { result = do_general_path(); } So there is a potential performance gain here, because the invocations can be grouped beforehand such that all do_fast_path-candidates can be executed faster than the rest. However, I could not find any information to when this mechanism is actually useful and whether it could even be harmful. Consider a shader with a dynamically uniform expression: uniform int magicNumber; void main() { if (magicNumber == 1337) { magicStuff(); } else { return; } } In this case, does it make sense to replace the condition by anyInvocationARB(magicNumber == 1337)? Since the flow is uniform, it could already be detected that only one of the two branches will ever need to be evaluated across all shader invocations. Or is this an assumption the SIMD processor must not make for any reason? I am using a lot of branching based on uniform values in my shaders and it would be interesting to know whether I could actually benefit from this extension or whether it could even decrease the performance because I inhibit uniform flow optimizations. I have not profiled this myself (yet), so it would be good to know beforehand what experiences others have made, this could spare me some troubles. A: No, there's no point. Read the description of the extension again: Compute shaders operate on an explicitly specified group of threads (a local work group), but many implementations of OpenGL 4.3 will even group non-compute shader invocations and execute them in a SIMD fashion. When executing code like if (condition) { result = do_fast_path(); } else { result = do_general_path(); } where diverges between invocations, a SIMD implementation might first call do_fast_path() for the invocations where is true and leave the other invocations dormant. Once do_fast_path() returns, it might call do_general_path() for invocations where is false and leave the other invocations dormant. In this case, the shader executes both the fast and the general path and might be better off just using the general path for all invocations. So modern GPU's don't necessarily jump; they may instead execute both sides of the if expression, enabling or disabling writes on the tasks that pass or fail the condition, except if all of the tasks chose one side of the branch. This implies two things: Using the *Invocations functions on dynamically uniform expressions is useless, since they evaluate to the same value on every task. You should probably be using allInvocationsARB for the fast path condition, as one of the tasks may need to go through the general path.
{ "pile_set_name": "StackExchange" }
Q: How to pass a value to a anonym method in Task.Factory I'm using a construct like that: string myurl = "http://google.de"; Task.Factory.StartNew(() => { MessageBox.Show(url); }); How to pass myurl to the anonym function? A: Just use it directly: string myurl = "http://google.de"; Task.Factory.StartNew(() => { MessageBox.Show(myurl); }); This is called a "closure". If you don't want to do that then you can pass the url in as another parameter to StartNew: string myurl = "http://google.de"; Task.Factory.StartNew(url => { MessageBox.Show((string)url); }, myurl); This second version is a tad more code, it limits you to only one parameter (so if you have several you need to either use a closure or put all of your parameters into some container object) and also types the parameter to object, thus forcing you to cast it to what it really is in the method body. The advantage, on the other hand, is that there is a small overhead associated with closing over variables that you can potentially avoid using this method. Note that in most situations this isn't going to be an important performance issue, so you should go with what is most convenient unless you have a reason to do otherwise.
{ "pile_set_name": "StackExchange" }
Q: code refactoring using pathname and writing to a file I am using ruby on rails. Below given code works. However I was wondering if it can be written better. # Usage: write 'hello world' to tmp/hello.txt file # Util.write_to_file('hello world', 'a+', 'tmp', 'hello.txt') def self.write_to_file(data, mode, *args) input = args filename = input.pop dir = Rails.root.join(*input).cleanpath.to_s FileUtils.mkdir_p(dir) file = File.join(dir, filename) File.open(file, mode) {|f| f.puts(data) } end A: How often are you going to be changing the mode? If not very often, I'd put it directly in the method, and do the rest like so: def self.write_to_file(data, *args) file = Rails.root.join(*args) FileUtils.mkdir_p(file.dirname) File.open(file, "a+") { |f| f.puts(data) } end
{ "pile_set_name": "StackExchange" }
Q: How to navigate to indendation levels in vim I have the following code (line numbers included): 1 def test(): 2 a = 1 3 b = 1 4 c = 1 5 d = 1 6 if a == 1: 7 print('This is a sample program.') And the cursor is on line 7, the last line. Is there a fast, and ideally one key, way to navigate up to line 6, which is one indentation level up, and then, on the next key press, to line 1, one indentation level up again? Conversely, is there a matching method to "drill down" that way? A: There is a plugin for that: https://github.com/jeetsukumaran/vim-indentwise The mappings it provides that match what you are looking for are: [- : Move to previous line of lesser indent than the current line. [+ : Move to previous line of greater indent than the current line. ]- : Move to next line of lesser indent than the current line. ]+ : Move to next line of greater indent than the current line. Then, if you really wanted to do what you asked for in a single keypress, you can remap them like so, for example: nmap - [- nmap + ]+
{ "pile_set_name": "StackExchange" }
Q: How do I test connectivity to an unknown web service in C#? I'm busy writing a class that monitors the status of RAS connections. I need to test to make sure that the connection is not only connected, but also that it can communicate with my web service. Since this class will be used in many future projects, I'd like a way to test the connection to the webservice without knowing anything about it. I was thinking of passing the URL to the class so that it at least knows where to find it. Pinging the server is not a sufficient test. It is possible for the server to be available, but the service to be offline. How can I effectively test that I'm able to get a response from the web service? A: You could try the following which tests the web site's existence: public static bool ServiceExists( string url, bool throwExceptions, out string errorMessage) { try { errorMessage = string.Empty; // try accessing the web service directly via it's URL HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Timeout = 30000; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) throw new Exception("Error locating web service"); } // try getting the WSDL? // asmx lets you put "?wsdl" to make sure the URL is a web service // could parse and validate WSDL here } catch (WebException ex) { // decompose 400- codes here if you like errorMessage = string.Format("Error testing connection to web service at" + " \"{0}\":\r\n{1}", url, ex); Trace.TraceError(errorMessage); if (throwExceptions) throw new Exception(errorMessage, ex); } catch (Exception ex) { errorMessage = string.Format("Error testing connection to web service at " + "\"{0}\":\r\n{1}", url, ex); Trace.TraceError(errorMessage); if (throwExceptions) throw new Exception(errorMessage, ex); return false; } return true; } A: You are right that pinging the server isn't sufficient. The server can be up, but the web service unavailable due to a number of reasons. To monitor our web service connections, I created a IMonitoredService interface that has a method CheckService(). The wrapper class for each web service implements this method to call an innocuous method on the web service and reports if the service is up or not. This allows any number of services to be monitored with out the code responsible for the monitoring knowing the details of the service. If you know a bit about what the web service will return from accessing the URL directly, you could try just using the URL. For example, Microsoft's asmx file returns a summary of the web service. Other implementations may behave differently though.
{ "pile_set_name": "StackExchange" }
Q: Wordpress: How to add element to Woocommerce order page I have a woocommerce shop, and I want to be able show orders where a custom field has a value of today. I realized that it can be done by going to a certain url, since updating the HTTP query string will get the job done. I'm thinking of something likes this: 'domain.com/wp-admin/edit.php?order_by=abc&date=DATE_HERE&somethingelse' So how can I put an html <a>-element on the woocommerce orders page, and how can I update the href automatically using javascript? Which php action hooks should I use? A: The following code will add a custom button, based on your attached image. Why should the href update be done via javascript and not with php? // Add action button function my_manage_posts_extra_tablenav( $which ) { global $pagenow, $typenow; if ( $typenow === 'shop_order' && $pagenow === 'edit.php' && $which === 'top' ) { ?> <div class="alignleft actions custom"> <button type="submit" name="custom" style="height:32px;" class="button" value=""> <?php echo __( 'Custom', 'woocommerce' ); ?> </button> </div> <?php } } add_action( 'manage_posts_extra_tablenav', 'my_manage_posts_extra_tablenav', 20, 1 );
{ "pile_set_name": "StackExchange" }
Q: Will Specific Operators give me different results? I'm working in my Sam's teach yourself work book, in lesson 5 the workshop asks to show the results of 32/7 and 32.0/7. Will the use of different operators such as float or int give me different results. I attempted in my code, but it resulted in an error. Could you point me in the right direction?? #include <iostream> #include "stdafx.h" using namespace std; int main() { int num1 = 32, num2 = 32.0, num3 = 7; int result = num1/num3; float result2 = num2/num3; cout << result << endl; cout << result2 << endl; return 0; } A: You have declared all the three numbers num1, num2 and num3 as int, so they will behave as integers. You may probably want num2 to be declared as a float for result2 to store a float value. When two ints are divided, they will result in an int, and after that if you store the result in a float, it will only result in a floating point representation of the integer result. Eg : for result2, num2/num3 will be 32/7 which will be equal to 4 as an integer. Now, since it has to be stored in a float (reading the expression from right to left), it will be typecasted as 4.000000.
{ "pile_set_name": "StackExchange" }
Q: Refrigerator ice maker not working known/unknowns Whirlpool refrigerator with ice maker and door dispenser. The refrigerator makes ice, but the dispenser is not working. I took the front assembly off and confirmed that the switch is good with a multimeter. This leaves me with: The motor is bad or the circuit board is bad Is there any other mechanism that could be involved that I am not aware of? A: I don't think there's anything else it you could check. But, if it's a slide-out unit you can jiggle, push, pull & twist it to see if it just came a little loose & has a bad connection. Ice overflows or overfills can jockey them around to inoperability. Also, check the manual of course. If you can uninstall & reinstall, you may find unplugging (turning off the circuit breaker, if known) the fridge for this operation & then plugging it back it clears any fault & gets it working again. In that case it may be a temporary fault or a first fault in the motor going bad & drawing too much power or not working at all. If the "reset" works, then you'll have to wait for it to fail again & it may not.
{ "pile_set_name": "StackExchange" }
Q: How to relate an Entity to another one that can (but not always) belong to I want to store information about houses. Those houses can be independent or belong to buildings. I want to store information about those buildings as well. So, a building can contain one or more houses and a house can be contained in zero or one building. The question is how to relate in a mysql database those two entities. The solucion I'm considering is adding to the house table an id_building that can be null but I'm not sure this is a good idea provided that it'd be a foreign key. Thank you very much in advance! A: Your idea is the correct way to implement this relationship. It is a 0/1-->n relationship. You capture the "0" relationship with a NULL value for building_id. You capture the "1" relationship with a valid value for building_id.
{ "pile_set_name": "StackExchange" }
Q: How to set encoding parameter for SQL Server Bulk statement? I wrote this SQL Server Bulk script: BULK INSERT dbo.test FROM 'd:\1.csv' WITH( FIELDTERMINATOR =',' ); But my CSV file should be encode with this encoding system: Encoding.GetEncoding(1256) How can I apply up code to that Bulk script? A: CodePage is what you're looking for. You might also need a RowTerminator value set. BULK INSERT dbo.test FROM 'd:\1.csv' WITH( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n', CODEPAGE = '1256' );
{ "pile_set_name": "StackExchange" }
Q: Direction with Multiple Stops - Google Map v3 Assume that we understand how directionservice on Google Map v3 works and I got it populated on google map. Let's say I have: Start: Chicago Waypoints: 1. LAX, 2. California, 3. New York End: Michigan If you plot this using the direction service and waypts, it won't plot it in the order above. It'll plot: 1. Chicago 2. California 3. LAX 4. New York 5. Michigan I think it somehow calculates the closest route basic on Start and End. Is there a way that I can go about plotting in the order searched? A: I believe its just a case of setting optimizeWaypoints:false in the request object See the docs -> https://developers.google.com/maps/documentation/javascript/reference#DirectionsRequest If set to true, the DirectionService will attempt to re-order the supplied intermediate waypoints to minimize overall cost of the route. If waypoints are optimized, inspect DirectionsRoute.waypoint_order in the response to determine the new ordering.
{ "pile_set_name": "StackExchange" }
Q: How to understand the loss function in scikit-learn logestic regression code? The code for the loss function in scikit-learn logestic regression is: # Logistic loss is the negative of the log of the logistic function. out = -np.sum(sample_weight * log_logistic(yz)) + .5 * alpha * np.dot(w, w) However, it seems to be different from common form of the logarithmic loss function, which reads: -y(log(p)+(1-y)log(1-p)) (please see http://wiki.fast.ai/index.php/Log_Loss) Could anyone tell me how to understand to code for loss function in scikit-learn logestic regression and what is the relation between it and the general form of the logarithmic loss function? Thank you in advance. A: First you should note that 0.5 * alpha * np.dot(w, w) is just a normalization. So, sklearn logistic regression reduces to the following -np.sum(sample_weight * log_logistic(yz)) Also, the np.sum is due to the fact it consider multiple samples, so it again reduces to sample_weight * log_logistic(yz) Finally if you read HERE, you note that sample_weight is an optional array of weights that are assigned to individual samples. If not provided, then each sample is given unit weight. So, it should be equal to one (as in the original definition of cross entropy loss we do not consider unequal weight for different samples), hence the loss reduces to: - log_logistic(yz) which is equivalent to - log_logistic(y * np.dot(X, w)). Now, why it looks different (in essence it is the same) from the cross entropy loss function, i. e.: - [y log(p) + (1-y) log(1-p))]. The reason is, we can use either of two different labeling conventions for binary classification, either using {0, 1} or {-1, 1}, which results in the two different representations. But they are the same! More details (on why they are the same) can be found HERE. Note that you should read the response by Manuel Morales.
{ "pile_set_name": "StackExchange" }
Q: Migrating Gitlab from CE 7.14 to 8.17.8 causes unicorn to be unable to start and 502 error After migrating from 7.1 to 7.14 successfully, I tried migrating to version 8.17.8. Unfortunately it didn't work, as now I'm getting the following error: ==> /var/log/gitlab/unicorn/unicorn_stderr.log <== NameError: uninitialized constant UsersGroup::Notifiable /opt/gitlab/embedded/service/gitlab-rails/app/models/users_group.rb:15:in `<class:UsersGroup>' ==> /var/log/gitlab/sidekiq/current <== 2018-05-25_06:21:50.98012 uninitialized constant UsersGroup::Notifiable I tried running reconfigure, restart, even rebooting the server, but nothing works. A: If sudo gitlab-ctl reconfigure is not enough to fix the issue, then you might consider doing the same migration again, but this time minor version by minor version. That is: follow the "Upgrade recommendations" (which you did): We recommend that you first upgrade to the latest available minor version within your major version. By doing this, you can address any deprecation messages that could possibly change behaviour in the next major release. But this time, try first 7.14 to 8.0.x, then 8.17.8, meaning one intermediate steps in the lower version of 8.x
{ "pile_set_name": "StackExchange" }
Q: Changing the initial value of an exposed view filter I'm trying to programmatically set the starting value of an exposed view filter (so that it initially loads the view with data matching that value). I've managed to change the filter field value with this code in a views_pre_build hook (doesn't work in pre_execute or pre_render): $view->display[$view->current_display]->handler->handlers['filter']['field_year_value']->value['value'] = $year; But the view still loads with the value from the view filter's config value. How can I get my change reflected in the view when it loads? A: For some reason a site I was adding a feature to had a years taxonomy vocabulary, with a number of terms, one for each year in a range. So I wanted to auto set the exposed filter to the current year, but to do so needed to set the filter value with the tid of the right term. I implement hook_views_query_alter(). check if the view is the right name and if the view doesn't have any user selected input (this view only had one filter). You have to alter the value for the filter's query value You have to unset the exposed filter area markup and regenerate it. function mymodule_views_query_alter(&$view, &$query) { if($view->name == 'executive_committee' && empty($view->exposed_input)) { $current_year = date('Y'); // find year term id $term_query = new EntityFieldQuery(); $tids = $term_query->entityCondition('entity_type', 'taxonomy_term') ->propertyCondition('name', $current_year) ->propertyCondition('vid', 3) ->execute(); if(!empty($tids['taxonomy_term'])) { $tids = array_keys($tids['taxonomy_term']); $current_year_tid = reset($tids); // set values to the views object and query objet $view->exposed_data['field_year_tid'] = $current_year_tid; unset($view->exposed_widgets); $view->exposed_raw_input['field_year_tid'] = $current_year_tid; $query->where[1]['conditions'][2]['value'] = $current_year_tid; // rebuild the exposed form $form_state = array( 'view' => $view, 'display' => $view->display_handler->display, 'exposed_form_plugin' => $view->display_handler->get_plugin('exposed_form'), 'method' => 'get', 'rerender' => TRUE, 'no_redirect' => TRUE, 'always_process' => TRUE, // This is important for handle the form status. ); $form = drupal_build_form('views_exposed_form', $form_state); $form['field_year_tid']['#value'] = $current_year_tid; $view->exposed_widgets = drupal_render($form); } } }
{ "pile_set_name": "StackExchange" }
Q: Get browser to redirect window from modalized content I have content in a modalized window, and when a user clicks a link, I'd like to have the entire browser redirect, not just the modal window. This doesn't work, unfortunately. Code I currently have: <a onclick="window.location.href = 'http://insert/url/here'">morestuff!</a> This only loads the url in the modal window. What can I do to get the whole window to load said url? A: Something like this should work: <a onclick="window.parent.location.href='http://insert/url/here'">morestuff!</a>
{ "pile_set_name": "StackExchange" }
Q: Conditional independence of random variables Let $(X_t),$ $(Y_t)$ be independent bounded martingales (for filtration $ \{ \mathcal{F}_t \}$ )which converge to $X_\infty$ and $Y_\infty$ respectively, by the martingale convergence theorem. Let $\{ \mathcal{F}^{X,Y}_t \}$ denote the filtration generated by processes $X$ and $Y$. Then the book claims that $$ \mathbb{E} [X_\infty Y_\infty | \mathcal{F}^{X,Y}_t ] = \mathbb{E} [X_\infty | \mathcal{F}^{X,Y}_t ] \mathbb{E} [Y_\infty | \mathcal{F}^{X,Y}_t ] = X_t Y_t \quad \text{ a.s..}$$ Can anyone explain to me why $ \mathbb{E} [X_\infty Y_\infty | \mathcal{F}^{X,Y}_t ] = \mathbb{E} [X_\infty | \mathcal{F}^{X,Y}_t ] \mathbb{E} [Y_\infty | \mathcal{F}^{X,Y}_t ] $ ? Does this conditional independence property follow from the independence of the stochastic processes $X$ and $Y$? A: The answer is quite nontrivial and requires $X,Y$ to be continuous independent martingales. See http://mech.math.msu.su/~cherny/pmt.pdf where it is laid out in full detail. I will present an an easy version in which $X,Y$ are bounded. Theorem: If $X,Y$ are continuous bounded $\mathscr{F}_t$-martingales, then $XY$ is a continuous $\mathscr{F}_t$- martingale. Proof: It suffices to show $\langle X,Y\rangle = 0$. Since $X,Y$ are continuous, $\langle X,Y \rangle_t$ is the limit in probability of sums like $ \sum (X_{t_{i+1}}-X_{t_i})(Y_{t_{i+1}}-Y_{t_i}) $ as the partition size $\Delta$ tends to $0$. We'll show these sums converge in $L^2$ to $0$. $$ E\left(\sum (X_{t_{i+1}}-X_{t_i})(Y_{t_{i+1}}-Y_{t_i})\right)^2 =\sum E(X_{t_{i+1}}-X_{t_i})^2E(Y_{t_{i+1}}-Y_{t_i})^2 $$ $$ \leq \max_i E(X_{t_i+1}^2-X_{t_i}^2) \cdot \sum E(Y_{t_{i+1}}^2-Y_{t_i}^2) = \max_i E(X_{t_i+1}^2-X_{t_i}^2) E(Y_t^2 - Y_0^2). $$ The max term tends to $0$ as $\Delta\to 0$ since $EX_t^2$ is continuous in $t$ (monotone/dominated convergence). Thus $\langle X,Y\rangle_t =0$. If you wanted to extend this to continuous local martingales (showing $XY$ is a local marginale), you would then take a reducing sequence of stopping times where the local martingales are bounded (hence true martingales) and approximate. To then extend to continuous martingales, stop the martingale at times which it is bounded and apply the result for local martingales. Then use standard estimates to get $L^1$ convergence and show $XY$ is a martingale.
{ "pile_set_name": "StackExchange" }
Q: Can i define methods in exception classes other than __init__ in Python? As the question already asks, I'm aware of building a custom exception class like this: class MyException(Exception) : def __init__(self, message='My error message') : self.message = message super(MyException, self).__init__(message) which will build a custom Exception class object with a predefined overwritable message. I wanted to know if it's possible to define more methods in it, other than __init__, and what would the effects of that be. Thanks A: Yes, you can. It won't have any effect other than having those other methods on it.
{ "pile_set_name": "StackExchange" }
Q: Ellipsoid but not quite I have an ellipsoid centered at the origin. Assume $a,b,c$ are expressed in millimeters. Say I want to cover it with a uniform coat/layer that is $d$ millimeters thick (uniformly). I just realized that in the general case, the new body/solid is not an ellipsoid. I wonder: How can I calculate the volume of the new body? What is the equation of its surface? I guess it's something that can be calculated via integrals but how exactly, I don't know. Also, I am thinking that this operation can be applied to any other well-known solid (adding a uniform coat/layer around it). Is there a general approach for finding the volume of the new body (the one that is formed after adding the layer)? A: Let $\mathcal{E} = \{ (x,y,z) \mid \frac{x^2}{a^2} + \frac{y^2}{b^2} + \frac{z^2}{c^2} \le 1 \}$ be the ellipsoid at hand. The new body $\mathcal{E}_d$ is the Minkowski sum of $\mathcal{E}$ and $\bar{B}(d)$, the closed ball of radius $d$. ie., $$\mathcal{E}_d = \{ p + q : p \in \mathcal{E}, q \in \bar{B}(d) \}$$ Since $\mathcal{E}$ is a convex body, the volume of $\mathcal{E}_d$ has a very simple dependence on $d$. It has the form: $$\verb/Vol/(\mathcal{E}_d) = V + A d + 2\pi \ell d^2 + \frac{4\pi}{3}d^3\tag{*1}$$ where $V$, $A$ and $\ell$ is the volume, surface area and something known as mean width for $\mathcal{E}$. The problem is for an ellipsoid, the expression for $A$ and $\ell$ are very complicated integrals. If I didn't make any mistake, they are: $$\begin{align} A &= abc\int_0^{2\pi} \int_0^{\pi} \sqrt{(a^{-2}\cos^2\phi + b^{-2}\sin^2\phi)\sin^2\theta + c^{-2}\cos^2\theta} \sin\theta d\theta d\phi\\ \ell &= \frac{1}{2\pi} \int_0^{2\pi}\int_0^{\pi}\sqrt{(a^2\cos^2\phi + b^2\sin^2\phi)\sin^2\theta + c^2\cos^2\theta} \sin\theta d\theta d\phi \end{align}\tag{*2}$$ Good luck for actually computing the integral. Update When $a = b$, the integral simplify to something elementary. For the special case $a = b \ge 1, c = 1$, by a change of variable $t = \cos\theta$, we have: $$\begin{align} A &= 4\pi a\int_0^1\sqrt{(1 + (a^2 - 1)t^2}dt\\ &= \frac{2\pi a}{a^2-1}\left(\sqrt{a^2-1}\sinh^{-1}(\sqrt{a^2-1}) + a(a^2-1)\right) \\ \ell &= 2\int_0^1 \sqrt{a^2 + (1-a^2)t^2}dt = \frac{a^2}{\sqrt{a^2-1}}\sin^{-1}\left(\frac{\sqrt{a^2-1}}{a}\right) + 1 \end{align} $$ For a test case, when $a = b = 2, c = d = 1$, we find $$\begin{align} \verb/Vol/(\mathcal{E}_1) - V &= A + 2\pi \ell + \frac{4\pi}{3} = \frac{\pi}{3\sqrt{3}}\left( 12 \sinh^{-1}(\sqrt{3}) +8 \pi +34\sqrt{3}\right)\\ &\approx 60.35475634605034 \end{align} $$ Matching the number on Euler project 449 that motivates this question. IMHO, I don't think Euler project expect one to know the volume formula $(*1)$. or how to compute the integrals in $(*2)$. There should be a more elementary way to derive the same result for the special case $a = b$. That part will probably stamp on the foot of Euler project. I better stop here. A: If $d$ << any of ( a,b,c ) you need to just find the surface area (using the elliptic integrals in Wikipedia) and multiply by $d$. The loss of accuracy using a paint layer thickness between the ellipsoid and Huygen's wavelet sort of body is of no avail or worth in practical engineering work. It is just like: For a thin tube of radii $ b-a =t$ we take cross section area to be $2 \pi a t$ or $2 \pi b t$ or $ \pi (a+b) t$ but do not care for the second order differences or inaccuracies that are lost when not considering a more correct: $$ \pi ( b^2-a^2). $$ EDIT 1: If I am tasked to compute spray paint volume etc., I would settle for an approximation like: $$ A \approx \frac{12 \pi a b c }{(a+b+c)} $$ EDIT 2: If d is not negligibly small, the outside anyhow being not an ellipsoid and we may take average of semi-axes and the approximation may be: $$ Vol. \approx \frac{12 \pi \bar a \bar b \bar c d }{(\bar a+\bar b+ \bar c)} $$ For a = b =2, c=d=1 it gives V = 54.3737. Since it is a harmonic mean it would be a lower bound. A: Let $(x,y,z)=(a\sin u \cos v, b\sin u \sin v,c\cos u)$ on the ellipse $\displaystyle \frac{x^2}{a^2}+\frac{y^2}{b^2}+\frac{z^2}{c^2}=1$, then the unit normal vector is $$\mathbf{n}= \frac{\displaystyle \left(\frac{x}{a^2},\frac{y}{b^2},\frac{z}{c^2} \right)} {\displaystyle \sqrt{\frac{x^2}{a^4}+\frac{y^2}{b^4}+\frac{z^2}{c^4}}}$$ Then new surface will have coordinates of $$(x',y',z')=(x,y,z)+d\mathbf{n}$$ which no longer to be a quadric anymore. In particular, if $d <-\frac{1}{\kappa} <0$ where $\kappa$ is one of the principal curvatures, then the inner surface will have self-intersection. If we try reducing the dimension from three (ellipsoid) to two (ellipse) and setting $a=1.5,b=1$, the unit normal vectors (inward) won't pointing on the straight line (i.e. the degenerate ellipse $\displaystyle \frac{x^{2}}{0.5^{2}}+\frac{y^{2}}{0^{2}}=1$). And also the discrepancy of another case
{ "pile_set_name": "StackExchange" }
Q: how to make a library jar in maven How to make an executable jar file which prints something on command prompt? Can some one tell me steps to make the jar file executable? I have made a small command prompt program that prints "Hello World" on console. I've exported that jar file in eclipse, but it's not working. A: As for starters, Oracle Java Tutorials. You can learn basic of Java programming there.
{ "pile_set_name": "StackExchange" }
Q: MC Music gone crazy! When I play minecraft in singular player my music goes crazy: for instance 1 song would start playing, but after a while another song starts at the SAME TIME! It very annoying. when I turn my music to off in the music & sound area it doesn't turn off! So I end up having to turn off my master volume. I cant stand the silence. plz help me A: If you are playing in minecraft 1.7.2, there is a bug where multiple songs can load at once, this was fixed in 1.7.3/1.7.4 update.
{ "pile_set_name": "StackExchange" }
Q: Is __all__ in __init__.py, needed when accessing class or method? Googling around, I read many answers explaining that __all__ is for 'from some.package.name import *' , restricting importable modules to only ones inside it. I'm absolutely sure it's true, if I want to import all the modules using wildcard from packages. But my question is about when I want to import some lower level objects like class, functions than modules, from package directly, the __all__ seems useless because to directly access the class from packages, it's the only way to import class from modules under the package into the __init__ file. Here's example While doing some Django jobs, I recognized that Django-contributors really enjoy using __all__in the __init__.py files. For example, in the basic Django package, models, __init__ files go like this. django.db.model.__init__.py ---skipped--- from django.db.models.base import DEFERRED, Model # ---skipped--- __all__ = aggregates_all + constraints_all + fields_all + indexes_all __all__ += [ '---skipped---' 'Prefetch', 'Q', 'QuerySet', 'prefetch_related_objects', 'DEFERRED', 'Model', ] You can see that here, 'Model' is definitely included __all__ ,but problem here is it's already imported upper lines, so if you don't include 'Model' in __all__, you can import it with from statement from django.db.models import *. So I concluded that, in this case __all__ is redundant or needless, and that the purpose of writing 'Model' despite its redundancy is that for readability. Do you think it's the right conclusion? A: The tutorial about modules explains that __all__ is actually used to restrict what is imported when you use import *. If __all__ is defined then when you import * from your package, only the names defined in __all__ are imported in the current namespace. So it can be redundant, but only if you put in __all__ everything you import and define in your package. Minimal working example: testing/__init__.py: from .moda import A from .modb import B __all__ = ['A'] testing/moda.py: class A: pass testing/modb.py: class B: pass Then when I import * from testing, I've got only A imported in current namespace, not B: >>> from testing import * >>> dir() ['A', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__'] >>> 'B' in dir() False >>> 'A' in dir() True
{ "pile_set_name": "StackExchange" }
Q: insert a word document into sql server database? I feel quite overwhelmed with the variety on technologies I would need to use for the above task. I've searched the stack overflow stocks but couldn't pinpoint a solid check list of steps to do this. I would like to get an overview of the steps/tools that need to be used when inserting a word document into a database. I thought about: reading the word file as a FileStream. deserializing it into an xml object (word ml). somehow (not sure how) insert the word ml into a xml column in sql server. is it possible to read word ml using the XMLSerializer object ? how would I then insert it to the database ? Edit: I actually need to perform operations on the stored data like finding nodes using xpath, hence my need to store it as xml... A: You should either go with FileStream or ordinary BLOB-storage. FileStream does require a little more initial work, and I have had problems upgrading certain already installed databases to use this. Depending on your ability/willingness to reinstall servers to get this to work, you should certainly do a proof-of-concept before going too far. Technically, I've never had problems with using BLOBs Some research has been done as to which should be preferred depending on your usage pattern. Ie. if your files are greater than 1Mb on average and you need fast read access, you might be better off using FileStream. I've only rarely seen the performance difference myself, but I do prefer FileStream from a design viewpoint. Take a look at: http://technet.microsoft.com/en-us/library/bb933993.aspx http://www.mssqltips.com/sqlservertip/1489/using-filestream-to-store-blobs-in-the-ntfs-file-system-in-sql-server-2008/
{ "pile_set_name": "StackExchange" }
Q: Number of ways of spelling Abracadabra in this grid This is embarrasingly, the first problem in notes on introductory combinatorics by Polya and Tarjan. (Solved, but I havent looked). Problem statement: Find the number of ways of spelling "abracadabra" always going from one letter to the adjacent. $$A$$ $$B \quad B$$ $$R \quad R \quad R $$ $$A\quad A \quad A \quad A $$ $$C\quad C\quad C\quad C\quad C$$ $$A\quad A \quad A \quad A \quad A\quad A$$ $$D\quad D\quad D\quad D\quad D$$ $$A\quad A \quad A \quad A $$ $$B \quad B \quad B $$ $$R \quad R$$ $$A$$ I got a very improbable answer of $2^{25}$ so I tried a simpler case to understand it. Starting at the northmost A there are two routes. At each of the two B's on the second row there are $2$ routes, so uptil this point $$A$$ $$B \quad B$$ $$R \quad R \quad R $$ there should be $2^3$ ways to get the three letter word "ABR" but on manually counting the number of ways is just 4 (LL, LR, RR, RL where R=right/L=left). What is wrong with my approach? More precisely, where have I overcounted? Edit: I understood my problem. I used the product rule instead of the sum rule. I think I will stop paying attention to these "rules" as they are hindering my problem solving anyway. (I have asked a previous questions on the subject) A: This is essentially the same as this problem. Start by rewriting your array as a square, with the top now at the bottom left, and the bottom now at the top right: $$\begin{array}{cccccc} A & D & A & B & R & A\\ C & A & D & A & B & R\\ A & C & A & D & A & B\\ R & A & C & A & D & A\\ B & R & A & C & A & D\\ A & B & R & A & C & A \end{array}$$ You want to get from the bottom left to the top right, using only moves right or up. A simple thing is to note that there is only one way to get to the bottom left, and at any point, the number of ways to get to a point is the sum of the number of ways to get to the point directly below and the number of ways to get to the point directly left. This gives: $$\begin{array}{cccccc} 1 & 6 & 21 & 56 & 126 & 252\\ 1 & 5 & 15 & 35 & 70 & 126\\ 1 & 4 & 10 & 20 & 35 & 56\\ 1 & 3 & 6 & 10 & 15 & 21\\ 1 & 2 & 3 & 4 & 5 & 6\\ 1 & 1 & 1 & 1 & 1 & 1 \end{array}$$ giving $252$ ways. Alternatively, in the end, you must make five moves right and five moves up. Your only decisions to make is when you make the moves up. You have six locations (before all the moves right, between any two moves right, and after all moves right), and you have to choose them, allowing repetitions and without caring about the order. That is, you want to count combinations with repetitions, selecting six from seven possibililties. The way to make $r$ choices from $n$ possibilities, allowing repetitions and where order does not matter, is $\binom{n+r-1}{r}$, so in this case we have $$\binom{6+5-1}{5} = \binom{10}{5} = \frac{10!}{5!5!} = 252.$$
{ "pile_set_name": "StackExchange" }
Q: Determining $A,B,C$ in terms of $X,Y,Z$ given a linear equation for each I have a set of equations representing a linear transformation from the variables $A, B, C$ to $X, Y, Z$. I know that this can be solved by substitution, but I can't figure out how to carry out that substitution. How can this be done? Here are my equations: $A = \frac{1}{4}X + \frac{1}{2}Y + \frac{1}{4}Z$ $B = X - Y$ $C = Z - Y$ Now I want to retrieve the opposite transformation. Given $A, B, C$, what are the values for $X, Y, Z$? This can be solved by inverting a matrix about them, but I am hoping for a simple approach by substitution. For full disclosure, this is exam review for me. I know the question and answer, but how the substitution is carried out doesn't make sense to me :) A: From the second and third equation, you get $X = B + Y$ and $Z = C + Y$. Substitute in (four times) the first to get $4A = (B + Y) + 2Y + (C + Y) = B + C + 4Y$. So $Y = (4A - B - C)/4$ and so on ($X = (4A + 3B - C)/4$ and $Z = (4A - B + 3C)/4$).
{ "pile_set_name": "StackExchange" }
Q: (java)If enum is static - how is it that another instance is created in my code (using DB40) ? In my code I have the following enum public ennum BuySell { buy('B', true, RoundingMode.DOWN, 1), sell('S', false, RoundingMode.UP, -1 buy); BuySell(char c, boolean isBuy, RoundingMode roundingMode, int mult) { this.aChar = c; this.isBuy = isBuy; this.isSell = !isBuy; this.roundingMode = roundingMode; this.mult = mult; } BuySell(char c, boolean isBuy, RoundingMode roundingMode, int mult, BuySell oppositeAction) { this(c, isBuy, roundingMode, mult); this.opposite = oppositeAction; oppositeAction.opposite = this; } } I save objects containing this enum through DB40 and when my system loads it loads those objects. what I see is that the loaded objects contain ButSell with different object id . Here you go : you can see that one selling = 9570 and the other is 9576 My quoestion is - how does another instance of this enum is created ? isnt it static ? How can I avoid it? Thanks. A: You can get multiple instances if You have multiple class loaders. You use Unsafe to create an instance of an Enum class. Further investigation would be required to determine how to avoid this. e.g. Are you setting the class loader. Is the ClassLoader for the two object different? Does the library use Unsafe.allocateInstance ? BTW: I would use BUY and SELL rather than buy and sell for enum constants.
{ "pile_set_name": "StackExchange" }
Q: Display current section number using fullpage.js I have seen this question asked here BEFORE and the answer helped... kind of. I am using fullPage.js, I have a side bar and I have a div inside this sidebar which will display a number depending on which slide is active I have a div <div id="num" class="slideNumber"></div> and I have this snippit var slideNumber = $('.fp-section.active').find('.fp-slide.active').index() + 1; //do whatever here $('#num').text(slideNumber); The number inside the div is displaying 0, then on scroll it refreshes that div to say 0 again each time a section is passed. I want this to instead change the number depending on which section its on. Edit: I fixed it. Solution below: var slideNumber = $('.fp-section.active').index() + 1; //This will change the input of NUM to current section number $('#num').html(slideNumber); A: var slideNumber = $('.fp-section.active').index() + 1; //This will change the input of NUM to current section number $('#num').html(slideNumber); I removed .find('.fp-slide.active') and replaced $('#num').text(slideNumber); with $('#num').html(slideNumber); and it started outputting correctly inside the #num div
{ "pile_set_name": "StackExchange" }
Q: Regex to parse out multiline strings Thought I'd give credit where it was due since my previous post was answered but I have more to ask. So here is a sample of what I have after using BareGrep. I need to parse out the question, and possible answers but drop the explanations. The txt doc has about 1000 questions I've created over the years. I've removed the exact answers but I need a tool and syntax to remove the explanations. I use Mac OS 10 and Windows 7/XP. QUESTION 19: Why must you blah and blah? A. So you can blah. B. So you can blah. C. So you can blah. D. So you can blah. The reason the answer is blah is blah. QUESTION 20: When should you blah blah? A. When you can blah. B. Where you can blah. C. Blah you can blah. D. All of the blah. The reason the answer is not blah is blah. A: Assuming it's exactly in that format, I think you can use this regex or something similar: "QUESTION \d+:(\n.+){5}"
{ "pile_set_name": "StackExchange" }
Q: How can I retrieve all the text nodes of a HTMLDocument in the fastest way in C#? I need to perform some logic on all the text nodes of a HTMLDocument. This is how I currently do this: HTMLDocument pageContent = (HTMLDocument)_webBrowser2.Document; IHTMLElementCollection myCol = pageContent.all; foreach (IHTMLDOMNode myElement in myCol) { foreach (IHTMLDOMNode child in (IHTMLDOMChildrenCollection)myElement.childNodes) { if (child.nodeType == 3) { //Do something with textnode! } } } Since some of the elements in myCol also have children, which themselves are in myCol, I visit some nodes more than once! There must be some better way to do this? A: It might be best to iterate over the childNodes (direct descendants) within a recursive function, starting at the top-level, something like: HtmlElementCollection collection = pageContent.GetElementsByTagName("HTML"); IHTMLDOMNode htmlNode = (IHTMLDOMNode)collection[0]; ProcessChildNodes(htmlNode); private void ProcessChildNodes(IHTMLDOMNode node) { foreach (IHTMLDOMNode childNode in node.childNodes) { if (childNode.nodeType == 3) { // ... } ProcessChildNodes(childNode); } }
{ "pile_set_name": "StackExchange" }
Q: At what point in the process do you create the visual design? I like to do a wireframe before I start coding and work from there. But when should I start worrying about the visual design? When should I consider the colours, the font, whether corners should be round or sharp, icon design, etc? Is that the last thing to do before launch? Or is there any reason to work on it while you're still in the coding phase, or testing and debugging phase? A: I'd like to say that as a programmer you shouldn't be creating the visual design at all, instead handing that off to UI and graphic designers, but unfortunately I know all too well that most companies aren't willing to invest any money in that unless it's going to directly generate revenue. So the next best thing is to wait as long as possible before getting into that. You can hash out most of what the UI is going to do with tools like Balsamiq or the free Pencil, and if you're using a good presentation architecture (MVC, MVP, MVVM, etc.) then you should have no trouble at all testing the UI functions without an actual UI. The more complete your GUI design is, the more everybody else who sees it is going to think that you're "almost done". You don't want this. Back when I did mostly Winforms development, I tended to start with the UI first, but I've since learned my lesson, and now it's always the last thing I do, after the controller or view-model unit tests. The other issue is that it's simply a distraction and requires you to approach the problem from a completely different perspective. If you spend too much time working on the GUI when the library/model/business/domain code's not done, you're going to hurt your own productivity from the constant context-switching. People aren't very good at multitasking; don't do it if you can avoid it.
{ "pile_set_name": "StackExchange" }
Q: Undefined offset on array - Get they key of each arrays This is my existing code: foreach($masterData as $data) { ?> <tr> <td><?=$data[0]?></td> //error line here </tr> <? echo '<pre>',print_r($data),'</pre>'; }?> Result when try printing the $data: Array ( [payment] => Array ( [name] => name [email] => address [depositdate] => 3-mar-16 [depositamount] => 200 ) ) 1 Array ( [payment] => Array ( [name] => John [email] => [email protected] [depositdate] => 29-Apr-16 [depositamount] => 5000.70 ) ) 1 But echoing the $data[0], [1], [2].. PHP give me notice: Notice: Undefined offset: 0 Possible cause of this error? Anything wrong with my code and how to fix it? A: Try this to get key of all index in array: <?php foreach($masterData as $key=>$data) { // you can get key of array in $key ?> <tr> <td><?=$key?></td> <!-- you can get $key here --> </tr> <?php echo '<pre>',print_r($data),'</pre>'; } ?>
{ "pile_set_name": "StackExchange" }
Q: imgkit get height of image what I'd like to do is very simple. I have a code which uses a imgkit library to load some webpage image and then stores it. It looks like that: kit = IMGKit.new(site, :quality => 5, :width => 1024) img = kit.to_img(:png) file = kit.to_file("#{Rails.root}/public/images/#{s2}.png") I need to know the image height after loading in order to stretch canvas element behind it. Is there a way I can get the height ? Or if not, how could I achieve this without knowing the image height before loading, javascript ? A: Ok, I've figured it out. Mini_magick gem was a fine way how to do this.
{ "pile_set_name": "StackExchange" }
Q: check for child element, hide parent if child exists I have tried this: <script> $(document).ready(function() { $('#title_article:not(:has(>hr:first-child))').hide(); }); </script> But never shows.. <div id="title_article"> <span style="padding-left:121px;">Article | </span> <span class="entry-date"><?php echo get_the_date(); ?></span> </div> Seeking to check for child element of <hr> if <hr> exists hide parent or #title_article <hr> would not be within <div id="title_article"></div> but below: <!-- page content --> <div id="title_article></div> <hr> <!-- page content --> A: $(document).ready(function() { if($("#title_article").next("hr").length==0) $("#title_article").hide() }); http://fiddle.jshell.net/prollygeek/57gcx6or/3/ Edit: Use .siblings() A: You are looking for .next() Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector. You have to do something like: if ($('#title_article').next('hr').length) $('#title_article').hide(); In your example, <hr> is not a child element of #title_article, but a sibling.
{ "pile_set_name": "StackExchange" }
Q: Exception Handling in Spring boot I have a spring-boot application which has the following end point: @RequestMapping("/my-end-point") public MyCustomObject handleProduct( @RequestParam(name = "productId") String productId, @RequestParam(name = "maxVersions", defaultValue = "1") int maxVersions, ){ // my code } This should handle requests of the form /my-end-point?productId=xyz123&maxVersions=4 However, when I specify maxVersions=3.5, this throws NumberFormatException (for obvious reason). How can I gracefully handle this NumberFormatException and return an error message? A: You can define an ExceptionHandler in the same controller or in a ControllerAdvice that handles the MethodArgumentTypeMismatchException exception: @ExceptionHandler(MethodArgumentTypeMismatchException.class) public void handleTypeMismatch(MethodArgumentTypeMismatchException ex) { String name = ex.getName(); String type = ex.getRequiredType().getSimpleName(); Object value = ex.getValue(); String message = String.format("'%s' should be a valid '%s' and '%s' isn't", name, type, value); System.out.println(message); // Do the graceful handling } If during controller method argument resolution, Spring detects a type mismatch between the method argument type and actual value type, it would raise an MethodArgumentTypeMismatchException. For more details on how to define an ExceptionHandler, you can consult the documentation.
{ "pile_set_name": "StackExchange" }
Q: Comparing two ArrayLists I have two arrayList of the same Type and I want to compare the two based on a particular attribute in the ValueList. ValueList ValueList A contains 1,10,5, 2,20,3 3,40,5, 4,60,8 ValueList B contains 2,20,3 3,40,5 I want to compare both the list based on line_num and create another arraylist Result and if the line_num is present in ValueList A but not in ValueList B, then the value field in the Result has to have a -1. Result should be like; Result 10,-1 20,3 40,5, 60,-1 I am not able to write the 'Not Found' Condition. Could someone please help me? My code List<Result> result= new ArrayList<Result>(); for(ValueList data1: valueListA) { for (ValueList data2: valueListB) { Result inter = new Result(); if(data1.getLine_num==data2.getLine_num) { inter.setKey(data1.getKey()); inter.setValue(data1.getValue()); result.add(inter); } } } Updated Code which works: public static List<Result> result;= new ArrayList<Result>(); .... int i1 = 0,int i2 = 0; Result inter = new Result(); while (i1 < valueListA.size() && i2 < valueListB.size()) { ValueList data1 = valueListA.get(i1); ValueList data2 = valueListB.get(i2); if (data1.getLine_num == data2.getLine_num) { // Add the result. result= new ArrayList<Result>(); inter.setValue(data1.getValue()); inter.setKey(data1-getKey()) result.add(inter); i1++; i2++; } else if (data1.getLine_num < data2.getLine_num) { result= new ArrayList<Result>(); // Add -1 because the data was not in valueListB. inter.setValue(data1.getValue()); inter.setKey(-1); result.add(inter); i1++; } else { i2++; } } A: From an algorithm point of view: Add a boolean variable found that equals to false before the start of the inner loop. Then when you found one, you set it to true. After the loop, you test the variable found and if it's false, you add -1. List<Result> result= new ArrayList<Result>(); for(ValueList data1: valueListA){ boolean found = false; for (ValueList data2: valueListB){ Result inter= new Result(); if(data1.getLine_num==data2.getLine_num){ inter.setKey(data1.getKey()); inter.setValue(data1.getValue()); result.add(inter); found = true; break; } } if (!found) { result.add(...) } } However, Java allows better solutions, see the other answers for that. But, if the lists are sorted like in your example, you have better algorithms. You can use a single while loop and 2 indexes (one per list). The complexity will drop from O(N*M) to O(N+M). int i1 = 0; int i2 = 0; while (i1 < valueListA.size() && i2 < valueListB.size()) { ValueList data1 = valueListA[i1]; ValueList data2 = valueListB[i2]; if (data1.getLine_num == data2.getLine_num) { // Add the result. i1++; i2++; } else if (data1.getLine_num < data2.getLine_num) { // Add -1 because the data was not in valueListB. i1++; } else { i2++; } }
{ "pile_set_name": "StackExchange" }
Q: Rails / RSpec factory girl testing with invalid model produces strange behaviour I am testing my rails controller with rspec and factory_girl My actions returns error messages in json format with 412 status in case of invalid attributes format.json{render json: user.errors.messages, status: 412} like this When I am trying to test the functionality let(:invalid_attributes){ FactoryGirl.attributes_for(:user,password: "password") } it "returns error if invalid attributes" do post :create,{user: invalid_attributes},valid_session expect(response).to have_status(412) end I get this error Failure/Error: expect(response).to have_status(412) expected #<ActionController::TestResponse:0x00000006f4cc10> to respond to `has_status?` If i try to test like this it "returns error if invalid attributes" do user = FactoryGirl.build(:user,invalid_attributes) post :create,{user: invalid_attributes},valid_session expect(response.body).to eq(user.errors.messages.to_json) end I get this error Failure/Error: expect(response.body).to eq(user.errors.messages.to_json) expected: "{}" got: "{\"password_confirmation\":[\"doesn't match Password\",\"doesn't match Password\"],\"password\":[\"Password must contain 1 Uppercase alphabet 1 lowercase alphabet 1 digit and minimum 8 charecters\"]}" What is the problem?Thank you in advance A: You can test the response status like this: expect(response.status).to eq(412) And the JSON response with: expect(response.body).to eq "{\"password_confirmation\":[\"doesn't match Password\",\"doesn't match Password\"],\"password\":[\"Password must contain 1 Uppercase alphabet 1 lowercase alphabet 1 digit and minimum 8 charecters\"]}"
{ "pile_set_name": "StackExchange" }
Q: BigQuery COALESCE/IFNULL type mismatch with literals In SQL I usually use COALESCE and IFNULL to ensure that I get numbers and not NULL when my queries contain aggregate functions like COUNT and SUM, for example: SELECT IFNULL(COUNT(foo), 0) AS foo_count FROM … However, in BigQuery I run into an error: Argument type mismatch in function IFNULL: 'f0_' is type uint64, '0' is type int32. Is there a way to make BigQuery understand that a literal 0 should be interpreted as a unit64 in this context? I've tried using CAST, but there's no unit64 type I can cast to, so I try INTEGER: SELECT IFNULL(COUNT(foo), CAST(0 AS INTEGER)) AS foo_count FROM … That gives me basically the same error, but at least I've successfully gotten a 64-bit zero instead of a 32-bit: Argument type mismatch in function IFNULL: 'f0_' is type uint64, '0' is type int64. The same happens if I use INTEGER(0). I can get it to work if I cast both arguments to INTEGER: SELECT IFNULL(INTEGER(COUNT(foo)), INTEGER(0)) AS foo_count FROM … But now it starts to be verbose. Is this really how you're supposed to do it in BigQuery? A: This is a bug in BigQuery which has been around for quite some time. For the time being you need to force the conversion of the COUNT, but you shouldn't need to do it for your "0". The following should work: SELECT IFNULL(INTEGER(COUNT(foo)), 0) AS foo_count FROM Thanks @Kinaan Khan Sherwani for the link to the official bug report.
{ "pile_set_name": "StackExchange" }
Q: How to access c# visual studio project from different location I moved my visual studio project (Visual STudio 2010 > Projects > Project file) file to a different location (desktop). Then I tried to access the project but when I go to the form file, nothing loads except the form in visual studio. No design view, and I can't even compile it. How can I open the application like I normally did when it was in its original location? A: Why don't you move it back and then copy the whole folder it is in (project folder) to the desktop? Your other options are to edit the project file itself and change the paths to the project files or copy everything from the original folder to your desktop. I would go with my first recommendation.
{ "pile_set_name": "StackExchange" }
Q: How to specify the icons theme in qooxdoo? I want to have an icon in my DateField in the Qooxdoo framework. How do I specify the icon set to use? This is my config file. As you can see I want to use the default theme. "let" : { "APPLICATION" : "myapp02", "QOOXDOO_PATH" : "../qooxdoo-2.1.1-sdk", "QXTHEME" : "qx.theme.Modern", "API_EXCLUDE" : ["qx.test.*", "${APPLICATION}.theme.*", "${APPLICATION}.test.*", "${APPLICATION}.simulation.*"], "LOCALES" : [ "en" ], "CACHE" : "${TMPDIR}/qx${QOOXDOO_VERSION}/cache", "ROOT" : "." }, But it doesn't use any icons in the DateField. Instead it simply display the date and the right part of the DateField (where you're suppose to click to get the full calendar) is empty. I also tried to use: "QXTHEME" : "myapp02.theme.Theme", And this is my Theme.js file: qx.Theme.define("myapp02.theme.Theme", { meta : { color : myapp02.theme.Color, decoration : myapp02.theme.Decoration, font : myapp02.theme.Font, icon : qx.theme.icon.Tango, appearance : myapp02.theme.Appearance } }); But to no avail. (still no icons in the DateField) I placed a similar question here: https://stackoverflow.com/questions/16310728/how-do-i-place-a-label-on-the-datefield. So to reiterate, how do I use an icon set Tango or Oxygen to place an icon in my DateField like in this tutorial: http://demo.qooxdoo.org/2.1.1/demobrowser/#widget~DateField.html? Thanks A: you need to install the icon set (Tango icon set for example) before using the createapplication.py script.
{ "pile_set_name": "StackExchange" }
Q: External USB 2.0 drive formatted as ext4 periodically "freezes" if files are not read or written I have an external USB 2.0 harddisk (Seagate 9SD2A2-500) that periodically "freezes" when files on the drive are not written to or read within approximately five minutes. The drive is formatted as ext4, and I am running Ubuntu 10.04 LTS 64-bit. If I am editing a file that is stored on this drive, and I do not save the file every five minutes, an open application (such as gedit) will become unresponsive. I must wait for at least a minute before the external drive becomes responsive again and the file can be saved. I've also noticed this behavior when trying to access a file in Nautilus. It appears that the drive is "falling asleep" and then "wakes up" after a certain time. What is happening here, and is it possible to change this behavior? I have another USB 2.0 harddisk attached to the computer. The harddisk is formatted as FAT32, and does not show this behavior. A: This is a "feature" rather than a bug related to power management of your external hard drive unrelated to formatting. Things you could try to do: Disable harddisk power management from your BIOS. Ask Seagate on how to disable power management on their external USB drives. This is entirely not an Ubuntu issue.
{ "pile_set_name": "StackExchange" }
Q: Laravel : how to pass parameters to my view and display them in Form::text and Form::date? I'm trying to make a view for editing fields. In fact I have two problems : 1) I get my data from my db with my controller, that's work, and I try to pass it to my view, that doesn't work... 2) I want to display these data in Form::text and Form::date, that doesn't work... What I've in my controller : public function edit($id) { $data = DB::connection('my-db') ->table('my-table') ->where('id', '=', $id) ->select('field1', 'field2') ->first(); return view('my-view', compact('field1', 'field2')); } I don't even know if compact in return view works like this What I've in my view : <div class="col-md-6"> {!! Form::text(field1, "", ['id'=> 'idField', 'class' => 'form-control', 'placeholder' => 'Modify field']) !!} </div> <div class="col-md-2"> {!! Form::date(field2, "", ['id'=> 'datetimepicker', 'class' => 'form-control']) !!} </div> I hope it's understandable, and thanks for your future answers :) A: public function edit($id) { $data = DB::connection('my-db') ->table('my-table') ->where('id', '=', $id) ->select('field1', 'field2') ->first(); $field1 = $data->field1; // intialize the $field1 variable $field2 = $data->field2; // intialize the $field2 varialbe return view('my-view', compact('field1', 'field2')); } You were missing the $ sign before the variable name Change field1 to $field1 <div class="col-md-6"> {!! Form::text('field1', $field1, ['id'=> 'idField', 'class' => 'form-control', 'placeholder' => 'Modify field']) !!} </div> <div class="col-md-2"> {!! Form::date('field2', $field2, ['id'=> 'datetimepicker', 'class' => 'form-control']) !!} </div> For more information, you can visit Laravel Form Collective Documentation
{ "pile_set_name": "StackExchange" }
Q: Парсинг всех страниц на сайте Увидел код (за это спасибо JackWolf) вот код: import requests from bs4 import BeautifulSoup r = requests.get('https://3dtoday.ru/3d-models?page=1') soup = BeautifulSoup(r.text, 'html.parser') element = soup.find_all('div', class_='threedmodels_models_list__elem__str') for index in range(18): elem_soup = BeautifulSoup(str(element[index]), 'html.parser') title = elem_soup.find_all('a')[2].text print(' '.join(title.split())) на каждой странице в каталоге примерно 18 элементов так вод страниц там больше чем 900 страниц. Так вот каким образом парсить за один запуск программы весь каталог и записывать его в CSV файл? A: import requests from bs4 import BeautifulSoup num_of_page = 10 for i in range(num_of_page): url = 'https://3dtoday.ru/3d-models?page=' + str(i + 1) response = requests.get(url, verify=False) soup = BeautifulSoup(response.text, 'html.parser') items = soup.findAll('div', class_='threedmodels_models_list__elem__title') for item in items: title = item.find('a').get_text(strip=True) print(title) Вместо num_of_page поставь кол-во страниц.
{ "pile_set_name": "StackExchange" }
Q: DBにレコードが追加されたか確認する手段はありますか?(PDO,MySql) 下記コードを書いたphp.pdoというファイルを作り、localhost/php.pdoでアクセスすると「接続しました」とだけ表示されます。phpmyadminのデータベース‘personal’のテーブル‘friend’にデータを挿入したいのですが、DBにレコードが追加されたか確認する手段はありますか? ご回答のほど宜しくお願います。 <?php define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASSWORD', 'root'); define('DB_NAME', 'personal'); // エラー表示設定:通知系以外全て表示 error_reporting(E_ALL & ~E_NOTICE); try { $dbh = new PDO('mysql:'.DB_NAME.';'.DB_HOST, DB_USER, DB_PASSWORD); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); print('接続しました。'); //SQL文を作る(新規レコード追加) $db -> exec("insert into friend (name, price, place) values ('フライドチキン',100,'渋谷')"); //プリペアドステートメントを作る $stm = $dbh->prepare($sql); //SQL文を実行 $stm->execute(); } catch(PDOException $e){ print('ERROR:'.$e->getMessage()); exit; } ?> A: DBにレコードが追加されたか確認する手段はありますか? insert文の実行結果は、 '$dbh -> exec'の返り値(失敗: FALSE を返します。)を見て追加されたか判断するすると良いでしょう。 以下 単純な動作サンプルです。 $dbh = new PDO('mysql:host=localhost;dbname=personal', 'root', 'root'); $ret = $dbh -> exec("insert into friend (name, price, place) values ('フライドチキン',100,'渋谷')");
{ "pile_set_name": "StackExchange" }
Q: Create a database stored procedure from .NET? I would like to create a stored procedure in my database from within C# code. How can I do this? FOR INSTANCE: Using Microsoft SQL Server, I just want to create a stored procedure sp_GetUsers in the database that takes an int parameter userid and a simple statement such as SELECT * FROM Users WHERE ID = @userid This would be great because I could check the DB for the existence of that stored procedure, and if it doesn't, I just create from within code. A: You can run arbitrary DDL statements: new SqlCommand(@"CREATE PROCEDURE ...").ExecuteNonQuery();
{ "pile_set_name": "StackExchange" }
Q: Is dynamic memory destroyed when static object is destroyed? Taking a look to the following code snippet: //A.h class A { void f(); }; //A.cpp #include "A.h" void A:f() { map<string, string> *ThisMap = new map<string, string>; //more code (a delete will not appear) } //main.cpp #include "A.h" int main( int argc, char **argv ) { A object; object.f(); //more code (a delete will not appear) return 0; } When main() ends it execution, object will be destroyed. Would be destroyed dinamic allocated memory asigned to ThisMap too? A: Would be destroyed dinamic allocated memory asigned to ThisMap too? No! You have a memory leak, since object gets destroyed, its destructor gets called, but no delete is called for your map. Pro-tip: delete whatever you new'ed, when you are done with it. PS: I highly doubt it that you need to dynamic allocate a standard container (like std::map), but if you really are sure that you need to use, then consider using std::unique_ptr.
{ "pile_set_name": "StackExchange" }
Q: .NET to .NetCore/.netstandard I am upgrading my application from .Net to .Netstandard(Which is Core compliant) Now, I came across a lot of articles but none of them specifically answers my questions. I have following questions: Most of the articles refer to Project.json. Well, we are VS2017 .NEtStandard1.6 and Microssoft has already got rid of that file. Is there a good article on handling this migration? This is a console application, should I create a new solution and copy each file one by one or is there a short-cut to -re-tatget my framework from .NET 4.6 to .netstandard1.6 if re-targetting in the same solution works then I am not seeing netstandard1.6 as a target option to upgrade What is the best way to address this situation? A: The new csproj format works with all files in the folder by default. Your best course of action is to create a new .net core console application project and any files you put in its directory will become part of the project. You state that this is a console application, but talk about targeting .Net Standard. For the application itself, you need to target a framework (.Net 4.6, .Net Core, Mono), not a standard. Any libraries you have, can target a .Net standard level, but the executables should be targeting frameworks.
{ "pile_set_name": "StackExchange" }
Q: Duplicate Entire MySQL Database Is it posible to duplicate an entire MySQL database on a linux server? I know I can use export and import but the original database is >25MB so that's not ideal. Is it possible using mysqldump or by directly duplicates the database files? A: First create the duplicate database: CREATE DATABASE duplicateddb; Make sure the user and permissions are all in place and: mysqldump -u admin -p originaldb | mysql -u backup -pPassword duplicateddb; A: To remote server mysqldump mydbname | ssh host2 "mysql mydbcopy" To local server mysqldump mydbname | mysql mydbcopy A: I sometimes do a mysqldump and pipe the output into another mysql command to import it into a different database. mysqldump --add-drop-table -u wordpress -p wordpress | mysql -u wordpress -p wordpress_backup
{ "pile_set_name": "StackExchange" }
Q: background-image and sites.php I have a multisite configuration with Drupal7, my prod site is mysite.example.mydomain.com and dev is mysitedev.example.mydomain.com I have set in sites/sites.php : $sites = array('mysite.example.mydomain.com' => 'mysitedev.example.mydomain.com', ); so searching for sites/mysite.example.mydomain.com would result as sites/mysite.dev. example mydomain.com, but I have a background Image Url: background: url("/sites/mysite.example.mydomain.com/files/myimage.jpg"); if the Url is /sites/mysitedev.example.mydomain.com/files it works, otherwise with /sites/mysite.example.mydomain.com/files it don't! What am I missing??? Thanks. A: It sounds like you're confusing hostnames with file system paths. The array mapping in sites.php is: Hostname => Instance Folder So taking your example, requests for http://mysite.example.mydomain.com will use the folder /sites/mysitedev.example.mydomain.com. In that scenario, the path /sites/mysite.example.mydomain.com/files doesn't exist, so requests for files under it will return a 404. That's to be expected. You can always add an alias/redirect via your server config, but it might be best to just use the system as it was intended.
{ "pile_set_name": "StackExchange" }
Q: Javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: Failure in SSL library, usually a protocol error I am trying to run the following code in android URLConnection l_connection = null; // Create connection uzip=new UnZipData(mContext); l_url = new URL(serverurl); if ("https".equals(l_url.getProtocol())) { System.out.println("<<<<<<<<<<<<< Before TLS >>>>>>>>>>>>"); sslcontext = SSLContext.getInstance("TLS"); System.out.println("<<<<<<<<<<<<< After TLS >>>>>>>>>>>>"); sslcontext.init(null, new TrustManager[] { new CustomTrustManager()}, new java.security.SecureRandom()); HttpsURLConnection .setDefaultHostnameVerifier(new CustomHostnameVerifier()); HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext .getSocketFactory()); l_connection = (HttpsURLConnection) l_url.openConnection(); ((HttpsURLConnection) l_connection).setRequestMethod("POST"); } else { l_connection = (HttpURLConnection) l_url.openConnection(); ((HttpURLConnection) l_connection).setRequestMethod("POST"); } /*System.setProperty("http.agent", "Android_Phone");*/ l_connection.setConnectTimeout(10000); l_connection.setRequestProperty("Content-Language", "en-US"); l_connection.setUseCaches(false); l_connection.setDoInput(true); l_connection.setDoOutput(true); System.out.println("<<<<<<<<<<<<< Before Connection >>>>>>>>>>>>"); l_connection.connect(); On l_connection.connect() , it is giving this SSLhandshakeException. Sometimes it works, but most of the time it gives the exception. It is only happening on Android 4.0 emulator. I tested it on Android 4.4 and 5.0, it works fine. What could be the cause of this ? Please help STACKTRACE 04-28 15:51:13.143: W/System.err(2915): javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x870c918: Failure in SSL library, usually a protocol error 04-28 15:51:13.143: W/System.err(2915): error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:658 0xb7c393a1:0x00000000) 04-28 15:51:13.143: W/System.err(2915): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:460) 04-28 15:51:13.143: W/System.err(2915): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:257) 04-28 15:51:13.143: W/System.err(2915): at libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:210) 04-28 15:51:13.143: W/System.err(2915): at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:477) 04-28 15:51:13.153: W/System.err(2915): at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:441) 04-28 15:51:13.153: W/System.err(2915): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282) 04-28 15:51:13.153: W/System.err(2915): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232) 04-28 15:51:13.153: W/System.err(2915): at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80) 04-28 15:51:13.153: W/System.err(2915): at libcore.net.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:164) 04-28 15:51:13.153: W/System.err(2915): at com.ofss.fcdb.mobile.android.rms.helpers.NetworkConnector.getConnection(NetworkConnector.java:170) 04-28 15:51:13.153: W/System.err(2915): at com.ofss.fcdb.mobile.android.rms.util.InitiateRMS$2.run(InitiateRMS.java:221) 04-28 15:51:13.153: W/System.err(2915): at java.lang.Thread.run(Thread.java:856) 04-28 15:51:13.153: W/System.err(2915): Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x870c918: Failure in SSL library, usually a protocol error 04-28 15:51:13.153: W/System.err(2915): error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:658 0xb7c393a1:0x00000000) 04-28 15:51:13.153: W/System.err(2915): at org.apache.harmony.xnet.provider.jsse.NativeCrypto.SSL_do_handshake(Native Method) 04-28 15:51:13.153: W/System.err(2915): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:410) 04-28 15:51:13.153: W/System.err(2915): ... 11 more 04-28 16:42:44.139: W/ResourceType(3140): No package identifier when getting value for resource number 0x00000000 A: I found the solution for it by analyzing the data packets using wireshark. What I found is that while making a secure connection, android was falling back to SSLv3 from TLSv1 . It is a bug in android versions < 4.4 , and it can be solved by removing the SSLv3 protocol from Enabled Protocols list. I made a custom socketFactory class called NoSSLv3SocketFactory.java. Use this to make a socketfactory. /*Copyright 2015 Bhavit Singh Sengar Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.*/ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketException; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.net.ssl.HandshakeCompletedListener; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; public class NoSSLv3SocketFactory extends SSLSocketFactory{ private final SSLSocketFactory delegate; public NoSSLv3SocketFactory() { this.delegate = HttpsURLConnection.getDefaultSSLSocketFactory(); } public NoSSLv3SocketFactory(SSLSocketFactory delegate) { this.delegate = delegate; } @Override public String[] getDefaultCipherSuites() { return delegate.getDefaultCipherSuites(); } @Override public String[] getSupportedCipherSuites() { return delegate.getSupportedCipherSuites(); } private Socket makeSocketSafe(Socket socket) { if (socket instanceof SSLSocket) { socket = new NoSSLv3SSLSocket((SSLSocket) socket); } return socket; } @Override public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException { return makeSocketSafe(delegate.createSocket(s, host, port, autoClose)); } @Override public Socket createSocket(String host, int port) throws IOException { return makeSocketSafe(delegate.createSocket(host, port)); } @Override public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException { return makeSocketSafe(delegate.createSocket(host, port, localHost, localPort)); } @Override public Socket createSocket(InetAddress host, int port) throws IOException { return makeSocketSafe(delegate.createSocket(host, port)); } @Override public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { return makeSocketSafe(delegate.createSocket(address, port, localAddress, localPort)); } private class NoSSLv3SSLSocket extends DelegateSSLSocket { private NoSSLv3SSLSocket(SSLSocket delegate) { super(delegate); } @Override public void setEnabledProtocols(String[] protocols) { if (protocols != null && protocols.length == 1 && "SSLv3".equals(protocols[0])) { List<String> enabledProtocols = new ArrayList<String>(Arrays.asList(delegate.getEnabledProtocols())); if (enabledProtocols.size() > 1) { enabledProtocols.remove("SSLv3"); System.out.println("Removed SSLv3 from enabled protocols"); } else { System.out.println("SSL stuck with protocol available for " + String.valueOf(enabledProtocols)); } protocols = enabledProtocols.toArray(new String[enabledProtocols.size()]); } super.setEnabledProtocols(protocols); } } public class DelegateSSLSocket extends SSLSocket { protected final SSLSocket delegate; DelegateSSLSocket(SSLSocket delegate) { this.delegate = delegate; } @Override public String[] getSupportedCipherSuites() { return delegate.getSupportedCipherSuites(); } @Override public String[] getEnabledCipherSuites() { return delegate.getEnabledCipherSuites(); } @Override public void setEnabledCipherSuites(String[] suites) { delegate.setEnabledCipherSuites(suites); } @Override public String[] getSupportedProtocols() { return delegate.getSupportedProtocols(); } @Override public String[] getEnabledProtocols() { return delegate.getEnabledProtocols(); } @Override public void setEnabledProtocols(String[] protocols) { delegate.setEnabledProtocols(protocols); } @Override public SSLSession getSession() { return delegate.getSession(); } @Override public void addHandshakeCompletedListener(HandshakeCompletedListener listener) { delegate.addHandshakeCompletedListener(listener); } @Override public void removeHandshakeCompletedListener(HandshakeCompletedListener listener) { delegate.removeHandshakeCompletedListener(listener); } @Override public void startHandshake() throws IOException { delegate.startHandshake(); } @Override public void setUseClientMode(boolean mode) { delegate.setUseClientMode(mode); } @Override public boolean getUseClientMode() { return delegate.getUseClientMode(); } @Override public void setNeedClientAuth(boolean need) { delegate.setNeedClientAuth(need); } @Override public void setWantClientAuth(boolean want) { delegate.setWantClientAuth(want); } @Override public boolean getNeedClientAuth() { return delegate.getNeedClientAuth(); } @Override public boolean getWantClientAuth() { return delegate.getWantClientAuth(); } @Override public void setEnableSessionCreation(boolean flag) { delegate.setEnableSessionCreation(flag); } @Override public boolean getEnableSessionCreation() { return delegate.getEnableSessionCreation(); } @Override public void bind(SocketAddress localAddr) throws IOException { delegate.bind(localAddr); } @Override public synchronized void close() throws IOException { delegate.close(); } @Override public void connect(SocketAddress remoteAddr) throws IOException { delegate.connect(remoteAddr); } @Override public void connect(SocketAddress remoteAddr, int timeout) throws IOException { delegate.connect(remoteAddr, timeout); } @Override public SocketChannel getChannel() { return delegate.getChannel(); } @Override public InetAddress getInetAddress() { return delegate.getInetAddress(); } @Override public InputStream getInputStream() throws IOException { return delegate.getInputStream(); } @Override public boolean getKeepAlive() throws SocketException { return delegate.getKeepAlive(); } @Override public InetAddress getLocalAddress() { return delegate.getLocalAddress(); } @Override public int getLocalPort() { return delegate.getLocalPort(); } @Override public SocketAddress getLocalSocketAddress() { return delegate.getLocalSocketAddress(); } @Override public boolean getOOBInline() throws SocketException { return delegate.getOOBInline(); } @Override public OutputStream getOutputStream() throws IOException { return delegate.getOutputStream(); } @Override public int getPort() { return delegate.getPort(); } @Override public synchronized int getReceiveBufferSize() throws SocketException { return delegate.getReceiveBufferSize(); } @Override public SocketAddress getRemoteSocketAddress() { return delegate.getRemoteSocketAddress(); } @Override public boolean getReuseAddress() throws SocketException { return delegate.getReuseAddress(); } @Override public synchronized int getSendBufferSize() throws SocketException { return delegate.getSendBufferSize(); } @Override public int getSoLinger() throws SocketException { return delegate.getSoLinger(); } @Override public synchronized int getSoTimeout() throws SocketException { return delegate.getSoTimeout(); } @Override public boolean getTcpNoDelay() throws SocketException { return delegate.getTcpNoDelay(); } @Override public int getTrafficClass() throws SocketException { return delegate.getTrafficClass(); } @Override public boolean isBound() { return delegate.isBound(); } @Override public boolean isClosed() { return delegate.isClosed(); } @Override public boolean isConnected() { return delegate.isConnected(); } @Override public boolean isInputShutdown() { return delegate.isInputShutdown(); } @Override public boolean isOutputShutdown() { return delegate.isOutputShutdown(); } @Override public void sendUrgentData(int value) throws IOException { delegate.sendUrgentData(value); } @Override public void setKeepAlive(boolean keepAlive) throws SocketException { delegate.setKeepAlive(keepAlive); } @Override public void setOOBInline(boolean oobinline) throws SocketException { delegate.setOOBInline(oobinline); } @Override public void setPerformancePreferences(int connectionTime, int latency, int bandwidth) { delegate.setPerformancePreferences(connectionTime, latency, bandwidth); } @Override public synchronized void setReceiveBufferSize(int size) throws SocketException { delegate.setReceiveBufferSize(size); } @Override public void setReuseAddress(boolean reuse) throws SocketException { delegate.setReuseAddress(reuse); } @Override public synchronized void setSendBufferSize(int size) throws SocketException { delegate.setSendBufferSize(size); } @Override public void setSoLinger(boolean on, int timeout) throws SocketException { delegate.setSoLinger(on, timeout); } @Override public synchronized void setSoTimeout(int timeout) throws SocketException { delegate.setSoTimeout(timeout); } @Override public void setTcpNoDelay(boolean on) throws SocketException { delegate.setTcpNoDelay(on); } @Override public void setTrafficClass(int value) throws SocketException { delegate.setTrafficClass(value); } @Override public void shutdownInput() throws IOException { delegate.shutdownInput(); } @Override public void shutdownOutput() throws IOException { delegate.shutdownOutput(); } @Override public String toString() { return delegate.toString(); } @Override public boolean equals(Object o) { return delegate.equals(o); } } } Use this class like this while connecting : SSLContext sslcontext = SSLContext.getInstance("TLSv1"); sslcontext.init(null, null, null); SSLSocketFactory NoSSLv3Factory = new NoSSLv3SocketFactory(sslcontext.getSocketFactory()); HttpsURLConnection.setDefaultSSLSocketFactory(NoSSLv3Factory); l_connection = (HttpsURLConnection) l_url.openConnection(); l_connection.connect(); UPDATE : Now, correct solution would be to install a newer security provider using Google Play Services: ProviderInstaller.installIfNeeded(getApplicationContext()); This effectively gives your app access to a newer version of OpenSSL and Java Security Provider, which includes support for TLSv1.2 in SSLEngine. Once the new provider is installed, you can create an SSLEngine which supports SSLv3, TLSv1, TLSv1.1 and TLSv1.2 the usual way: SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, null, null); SSLEngine engine = sslContext.createSSLEngine(); Or you can restrict the enabled protocols using engine.setEnabledProtocols. Don't forget to add the following dependency (check the latest version here): implementation 'com.google.android.gms:play-services-auth:17.0.0' For more info, checkout this link. A: Scenario I was getting SSLHandshake exceptions on devices running versions of Android earlier than Android 5.0. In my use case I also wanted to create a TrustManager to trust my client certificate. I implemented NoSSLv3SocketFactory and NoSSLv3Factory to remove SSLv3 from my client's list of supported protocols but I could get neither of these solutions to work. Some things I learned: On devices older than Android 5.0 TLSv1.1 and TLSv1.2 protocols are not enabled by default. SSLv3 protocol is not disabled by default on devices older than Android 5.0. SSLv3 is not a secure protocol and it is therefore desirable to remove it from our client's list of supported protocols before a connection is made. What worked for me Allow Android's security Provider to update when starting your app. The default Provider before 5.0+ does not disable SSLv3. Provided you have access to Google Play services it is relatively straightforward to patch Android's security Provider from your app. private void updateAndroidSecurityProvider(Activity callingActivity) { try { ProviderInstaller.installIfNeeded(this); } catch (GooglePlayServicesRepairableException e) { // Thrown when Google Play Services is not installed, up-to-date, or enabled // Show dialog to allow users to install, update, or otherwise enable Google Play services. GooglePlayServicesUtil.getErrorDialog(e.getConnectionStatusCode(), callingActivity, 0); } catch (GooglePlayServicesNotAvailableException e) { Log.e("SecurityException", "Google Play Services not available."); } } If you now create your OkHttpClient or HttpURLConnection TLSv1.1 and TLSv1.2 should be available as protocols and SSLv3 should be removed. If the client/connection (or more specifically it's SSLContext) was initialised before calling ProviderInstaller.installIfNeeded(...) then it will need to be recreated. Don't forget to add the following dependency (latest version found here): compile 'com.google.android.gms:play-services-auth:16.0.1' Sources: Patching the Security Provider with ProviderInstaller Provider Making SSLEngine use TLSv1.2 on Android (4.4.2) Aside I didn't need to explicitly set which cipher algorithms my client should use but I found a SO post recommending those considered most secure at the time of writing: Which Cipher Suites to enable for SSL Socket? A: Also you should know that you can force TLS v1.2 for Android 4.0 devices that don't have it enabled by default: Put this code in onCreate() of your Application file: try { ProviderInstaller.installIfNeeded(getApplicationContext()); SSLContext sslContext; sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, null, null); sslContext.createSSLEngine(); } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException | NoSuchAlgorithmException | KeyManagementException e) { e.printStackTrace(); }
{ "pile_set_name": "StackExchange" }
Q: updating ssl cert for gitlab using certbot & lets encrypt I am running gitlab on ubuntu 14. The previously configured cert has expired (no cron entry was setup for renewal). I am trying to setup certbot (with let's encrypt) to renew the cert and then setup the crontab entry for auto renewals. When I run certbot, I get a message copied below (is there a location where I can grab a more detailed error message): command being run: ./certbot-auto certonly --webroot -w /opt/gitlab/ssl -d git.xyz.com git.xyz.com is a valid domain (I replaced the actual domain with xyz). The directory /opt/gitlab/ssl exists and the user being used to run the command has read/write privileges on that directory and its contents. Error Failed authorization procedure. git.xyz.com (http-01): urn:acme:error:connection :: The server could not connect to the client to verify the domain :: Could not connect to git.xyz.com IMPORTANT NOTES: - The following errors were reported by the server: Domain: git.xyz.com Type: connection Detail: Could not connect to git.xyz.com To fix these errors, please make sure that your domain name was entered correctly and the DNS A record(s) for that domain contain(s) the right IP address. Additionally, please check that your computer has a publicly routable IP address and that no firewalls are preventing the server from communicating with the client. If you're using the webroot plugin, you should also verify that you are serving files from the webroot path you provided. Any thoughts on how I can debug this issue better? forgot to mention: I can access the URL from an external network (the domain name is correct) and currently no firewall was configured to stop traffic on port 80/443 (I even shut off the firewall to test as well). A: I'm not sure if this is of any help, but at least I could imagine that this is the problem: You're redirecting automatically to https if connecting via http. This redirect applies to Let's Encrypt as well, so they'll get your invalid, due to the date, cert. At this point the connection won't be successful, leading to the error shown to you. Also, you're making use of HSTS. I'm not sure if Let's Encrypt does respect this header, if they've once seen it. So, what to do? I'm not sure as well, but here are some hints: Disable the http to https redirect, and try again. If HSTS is respected: Set the HSTS header to something really short, like one second, put this config in place, run the Let's Encrypt client again, so they're getting the new header, disable the redirect, wait some time, and run the client again. If this doesn't work: Get a different cert, which is valid, for example issued by StartSSL, install it and try again. For the future: Set up automatic cert renewal and, additionally, put monitoring in place which at least will warn you if something like this might happen again, before it's happening. Do something good: Create a ticket or write a post into their forum / an email explaining what happened and asking if they could check for these errors, and give the people a hint (aka a better error message). (Minor: If you don't want to make your domain public, you should remove it out of your post.)
{ "pile_set_name": "StackExchange" }
Q: join tables with using max mysql I have two tables with one to one relationship, the first is "book" and the second is "payment", I want to get the (cus_id) from "book"with the highest (price) from payment using join, which means i have to use max, but i can not get the right syntax for this book has these columns (cus_id, inv_id as FK,....) and payment has (inv_id as PK, price,...) I tried this syntax select b.cus_id, p.price from customer b, payment p where b.inv_id=p.inv_id; but this syntax absolutely won't give me the max price, and here i need the help. A: Select a.cus_id,max(price) from book a,payment where a.inv_id = (Select b.inv_id from payment b where price = (select max(price) from payment))
{ "pile_set_name": "StackExchange" }
Q: Dense subset of irrational have same measure If A is subset of E. Where E is fix subset of irrational number. Suppose A is dense in E . Can we say that both A and E have same Lebesgue measure ? ( Assume both set measurable). I guess that it is true but i don't know how to proceed. A: No. The set of irrational algebraic numbers is countable, so it has Lebesgue measure $0$. This set is dense in $\Bbb R$. It is easy to prove (and a bit tedious, if you ask me) that in every open interval $(a,b)$ there is some irrational $\sqrt r$ for rational $r$.
{ "pile_set_name": "StackExchange" }
Q: chromeのテキストボックスに入力した全角英数字をjavascriptでリアルタイムに半角へ変換したい いくつか参考サイトを探し、 http://qiita.com/yoya_k/items/4bce6201fde9ee3a9561 こちらを参考にさせていただきながら、なんとか近い形にはできたのですが 気になったのはそもそも情報が少ないということは、別の方法があるからなのか? 予想ではもっとこの問題で悩んでいる方がいるかと思っておりましたので意外でした。 ime-modeが使えない場合の基本的なやり方が分かればと思います。 入力モードが全角になっていても半角の数値のみが入力(即時変換?)可能にしたいです。 実現可能であれば、jqueryやangularjs等も利用したいと思っています。 何卒どうぞよろしくお願いいたします。 A: リアルタイムで…というのは、IMEの挙動も制御したいということですよね? その前提で話をしますが。 私が思うに、そもそも情報が少ないのは、そのような制御が好ましくないからです。 (うろ覚えですがime-modeすら廃止の勧告を受けた記憶があります) 例えばあるユーザーは「郵便番号辞書」を使いたくても入力できなくなります。 さらに「あれ?なんで勝手に入力確定しているんだ!?」と大変驚くことでしょう。 ユーザービリティの観点からすべきではありません。 普通に、pattern属性なり$watchなりで入力確定したものを検証すべきです。
{ "pile_set_name": "StackExchange" }
Q: SMS online sending service I'm looking for an online sms sending service, that I can use within my iOS-App. My aim is to send a verification code to the phone number, the user provided. In Android its not too big of a deal, since I can send sms programmatically, but in iOS I can't. Any suggestions? A: In our app we use http://www.twilio.com/ to send SMS through a service on the iPhone, its pretty great. For sending SMSs you don't even need to download their SDK and put it into your project. It basically comes down to a HTTP POST command in which you provide the phone number to SMS, the message body, and your API key+secret. Here is an example for your convenience on sending an SMS through Twillio: - (void)twilloSendSMS:(NSString *)message withQueue:(NSOperationQueue *)queue andSID:(NSString *)SID andSecret:(NSString *)secret andFromNumber:(NSString *)from andToNumber:(NSString *)to { NSLog(@"Sending request."); // Build request NSString *urlString = [NSString stringWithFormat:@"https://%@:%@@api.twilio.com/2010-04-01/Accounts/%@/SMS/Messages", SID, secret, SID]; NSURL *url = [NSURL URLWithString:urlString]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:url]; [request setHTTPMethod:@"POST"]; // Set up the body NSString *bodyString = [NSString stringWithFormat:@"From=%@&To=%@&Body=%@", from, to, message]; NSData *data = [bodyString dataUsingEncoding:NSUTF8StringEncoding]; [request setHTTPBody:data]; [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; if ([data length] >0 && error == nil && ([httpResponse statusCode] == 200 || [httpResponse statusCode] == 201)) { NSString *receivedString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"Request sent. %@", receivedString); } else { NSString *receivedString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"Request sent. %@", receivedString); NSLog(@"Error: %@", error); } }]; }
{ "pile_set_name": "StackExchange" }
Q: The height of the menu is not correct CSS I'm working in a home page, it's working correctly, but the menu on the left sidebar, it's not making and overflow correctly. I need the scrollbars on the menu, 'cause I don't want it on the page. I think the issue it's with the height, but I need the 100% of the height not in pixels, somebody can help me? Here you are de JsBin: http://jsbin.com/ceyij A: I've got the best result with the following thanks to jQuery $(document).ready(function() { // Handler for .ready() called. var alt = $(".wrapper").height(); $(".left-side").height(alt); $(".sidebar").height(alt - 153); var altHeader = $("header.header").height(); $(".sidebar-menu").height(alt - 153); });
{ "pile_set_name": "StackExchange" }
Q: How can I get mod_wsgi working on Mac? I have been trying to install the latest version of mod_wsgi (3.3) since hours on my Mac. I'm on Snow Leopard and I have the versions of Apache (Apache/2.2.15) and Python 2.6.1 (r261:67515) that come with the system. I downloaded mod_wsgi-3.3.tar.gz from http://code.google.com/p/modwsgi/downloads/detail?name=mod_wsgi-3.3.tar.gz Extracted the file and executed the following through terminal: ./configure make sudo make install I added LoadModule wsgi_module modules/mod_wsgi.so to my httpd.conf. Restarted Apache by disabling and enabling Web Sharing from the control panel. localhost stops working until I remove the line I added httpd.conf :( Please help. Thanks in advance. A: I use the homebrew installed version of mod_wsgi. That gives me a universal version of mod_wsgi that works with the vanilla apache. ➔ file `brew list mod_wsgi` /usr/local/Cellar/mod_wsgi/3.2/libexec/mod_wsgi.so: Mach-O universal binary with 2 architectures /usr/local/Cellar/mod_wsgi/3.2/libexec/mod_wsgi.so (for architecture x86_64): Mach-O 64-bit bundle x86_64 /usr/local/Cellar/mod_wsgi/3.2/libexec/mod_wsgi.so (for architecture i386): Mach-O bundle i386 A: The problem you had was the path to mod_wsgi.so. On OS X the appropriate line is LoadModule wsgi_module libexec/apache2/mod_wsgi.so A: I had to first run the below command to get mod_wsgi installed brew tap homebrew/apache And then run brew install mod_wsgi
{ "pile_set_name": "StackExchange" }
Q: Allow Vue2 Select Component to take in any array for select options I'm trying to create a reusable Select component that will work with any Array passed to it as options. I have it working if the Object properties in the array share the same names bound in the component, but if you pass an array of objects that have different property/attribute names, as expected, the options will not render. How can I assign on the component which object property I want as the option value and which I want as the option label/name? FormSelect.vue / Component <template> <select :id="id" v-model="selected"> <option v-if="options.length > 0" value="">Please Select</option> <option v-if="options.length > 0" v-for="(option, index) in options" :key="index" :selected="selected" :value="option.value" v-text="option.name" /> </select> </template> <script> props: { value: { type: [Array, String, Number, Object], default: null }, options: { type: Array, default: () => [] } }, computed: { selected: { get() { return this.value ? this.value : ""; }, set(v) { this.$emit("input", v); } } } </script> Parent.vue / Parent <form-select id="gender" label="Gender" :options="genderOptions" @input="handleEdit(deep(profile))" v-model="user.gender" /> This works: genderOptions: [ { name: "Male", value: "MALE" }, { name: "Female", value: "FEMALE" } ], This would not (notice obj key names): genderOptions: [ { id: "Male", gender: "MALE" }, { id: "Female", gender: "FEMALE" } ], So I'm thinking there needs to be a way to tell the component which properties I want to use as the option value and label. Something like this, but then it would also need to be handles on the component side: <form-select id="gender" label="Gender" :options="genderOptions" optionVal="gender" optionName="id" @input="handleEdit(deep(profile))" v-model="user.gender" /> A: You're missing to add optionVal and optionName props to your component and to work with them, i suggest the following solution <script> props: { value: { type: [Array, String, Number, Object], default: null }, options: { type: Array, default: () => [] }, optionVal:{ type:String, default: 'value' }, optionName:{ type:String, default: 'name' } }, computed: { selected: { get() { return this.value ? this.value : ""; }, set(v) { this.$emit("input", v); } } } </script> <select :id="id" v-model="selected"> <option v-if="options.length > 0" value="">Please Select</option> <option v-if="options.length > 0" v-for="(option, index) in options" :key="index" :selected="selected" :value="option[optionVal]" v-text="option[optionName]" /> </select>
{ "pile_set_name": "StackExchange" }
Q: Should an App Service and it's corresponding Web API use the same Application Insights? I have an architecture where I have a thin ASP.NET Core MVC website that connects to an ASP.NET Web API which handles all of the logic. What is the best practice for setting up Application Insights for the 2 apps? Should they use the same AI instance or independent? How can you track calls from the MVC site to the API so that I can see the corresponding telemetry data for the request? A: The previous guideline was to use a different Application Insights resource per app. Now we're transitioning to natively supporting all telemetry reported single instrumentation key. The end goal is that Application Insights work the same (from UX, alerting, etc.) perspective whether each app instrumented with its own ikey or all apps report telemetry to the same ikey. This future might take time to materialize =)
{ "pile_set_name": "StackExchange" }
Q: Is the time complexity/Big O of this function a constant? is the time complexity of this program O(1)? f1(int n){ int temp = n; while (temp /= 2)) { len++; result+=m; } } and if we change int temp to double temp, does the time complexity change as well, or it will remain constant? f2(int n){ double temp = (double)n; while (temp /= 2)) { len++; result+=m; } } A: The answer for the integer part is O(log n) because the value is halved each time. The double version starts the same way, except that when the value reaches 1 or close to 1, it doesn't stop and divides until underflow makes it 0. At this point, the number of divisions is fixed. I've made a small empirically calibrated program which tries to predict the number of loops: #include <stdio.h> #include <math.h> void f2(int n){ int len=0; double temp = (double)n; while (temp /= 2) { len++; } // 1.53 is an empiric constant, maybe it could be theorically computed // it was just to make the numbers match printf("%d %lf\n",len,log(n)*1.53+1074); } int main() { f2(100000000); f2(10000000); f2(1000000); f2(10000); f2(100); f2(1); } I get: 1101 1102.183642 1097 1098.660686 1094 1095.137731 1087 1088.091821 1081 1081.045910 1074 1074.000000 So the complexity is O(log n) plus an incompressible number of iterations, depending on the machine. (my apologies for the empiric aspect of my answer, I'm not a floating point expert)
{ "pile_set_name": "StackExchange" }
Q: Mathcad simplifies results using $\textrm{csgn}$ instead of $1$ How can I prevent Mathcad from adding $\textrm{csgn}$ to my simplification? Sample: (x-1)/((x-1)^2)1/2 simplify -> csgn(x-1) Image from Mathcad A: Mathcad is not wrong. Plug in $x=-2$ and see what you get. To expand upon this. The top can be either positive or negative (large negative $x$ means the top is negative and a large positive $x$ means the top is positive). However, the function $\sqrt{x}$, by convention, is always positive. Which is why, if we want both the positive or the negative root, we use $\pm\sqrt{x}$. Therefore our answer can be either positive or negative and not just 1.
{ "pile_set_name": "StackExchange" }
Q: Curve Text In UILabel Programmatically Around UIButton I have created a circular UIButton by setting the cornerRadius property to half of the width and height values of the UIButton. btn.layer.cornerRadius = 75.f; That works fine but I would like to also create a label for the UIButton where the label text curves around the edge of the UIButton. If this is even possible could somebody post a snippet of code as to how this curved text around the button edge could be accomplished? A: You might have a look at this question: Curve text on existing circle It's not actually a UIButton, but you will certainly get an idea of how to draw text on a curve. There's especially talk of the sample project CoreTextArcCocoa from Apple. It's for OS X instead for iOS, but you might want to check this out.
{ "pile_set_name": "StackExchange" }
Q: How to efficiently save data to a remote server database (python) Currently in my code, there are a few client machines doing processing and one server machine with a database. After an individual client machine finishes processing some data, it saves the data to a .txt file and sftp's it over to the server. The server has a job that just waits for these txt files and stores the data into a database. I wanted to know of any other efficient processes for this, kinda a python beginner. Is there a way to remotely save data into the database of the server? How to do so securely, etc? To be more specific, this project is a webapp hosted in django. I know how to use django's standalone scripts to save data into a db, just preferably need to know how to do so remotely. Thank you. A: Django databases can be remote - there is no requirement they be on the same host at the django server. Just set an appropriate HOST and PORT. See: https://docs.djangoproject.com/en/dev/ref/databases/#id10 Update: Based on your comment, I understand that you want to write python/django code that will run in the browser, and connect to a remote database. There is no practical way of doing this. Have the data sent back to your server, and forward it on from there. Update 2: If you are able to distribute software outside of the browser, you could have a small django deployment on each client computer, which the user connects to through their browser, which could connect directly to the database. Obviously, security considerations apply.
{ "pile_set_name": "StackExchange" }
Q: kies stuck on "connecting" on mac+galaxy s2 i have the latest version of kies,os x, and a galaxy s2 with cm10 on it. it is set to MTP with usb debugging off (if it's on usb storage rather than mtp, kies crashes). i tried playing with many parameters but none of them seem to work - when i plug in my galaxy kies shows "connecting" and nothing happens.. (the program itself is not stuck). someone suggested launching phoneutil (7284) and changing the pda/modem stuff, but it doesn't launch on my phone, i guess it's because of my cm10. what else can i do? thanks in advance. p.s tried rebooting the phone\mac several times. A: You can't use Kies with custom ROMs (like CM), only with Samsung ROMs.
{ "pile_set_name": "StackExchange" }
Q: Google Analytics Event Tracking - Minimal Interval between the events I want to track multiple events using GA _trackEvent method across multiple domains. Because of the nature of the report I want to generate, I must do something like this: for (var i=0; var < books.length; i++) { //showing values for current books[i] _gaq.push(['_trackEvent', 'Books Displayed', 'Fantasy', 'Lord of The Rings']); } So, when my books list is populated I want to send appropriate GA event. It is important that I send each item separately so I can drill-down on Event Dashboard to preview all items in 'Fantasy' category and so on. Note, books list is never longer than about 10 items. The problem I'm experiencing at the moment is that for no good reason Google code is ignoring some of my requests. The way how Google event tracking works, is that with every call to _trackEvent, Google is dropping gif on the page: http://www.google-analytics.com/__utm.gif that has loads of parameters, and one of them - utme contains my data: __utm.gif?utmt=event&utme=5(Books%20Displayed*Fantasy*Lord%20of%20The%20Rings) Using Fiddler (or Firebug Net tab) I can check if this request is really coming out from the browser. Unfortunately, it seems like every time about half of my requests are completely ignored by google and _trackEvent is not translated to __utm.gif call. I have a feeling it has something to do with the frequency of the _trackEvent call. Because I am using them inside a for loop, all events are spawned with minimal interval between. It seems like Google doesn't like it, and ignores my calls. I did test it, adding 2 seconds interval between each call and it worked. But this solution is unacceptable - I can't make user wait for 20 seconds to send all events. Unfortunately this flaw makes GA Event Tracking completely useless - I can't just "hope" GA code will correctly record my event because the report won't be precise. The worst thing about it is that there is no proper documentation on Google saying what is the maximum allowed number of requests per second (they only state that max request per session is 500 what is a lot more than what I generate anyway). My question is - did you experience similar problems with Google Event tracking before and how did you manage to fix it? Or does it mean I must completely abandon GA Tracking because it will never be precise enough? A: First off, I want to point out that the 500 limit per session is for all requests to Google, not just for events. So that includes any other custom tracking you are doing, and that also includes normal page view hits. This to me sounds more like a general js issue than a GA issue. Something along the lines of you pushing code for GA to process faster than it can process so some are falling through the cracks. I don't think there really is anything you can do about that except for delay each push as you have done...though I think you could probably lower that interval from 2s to maybe as low as 500ms...but still, that would at best drop you down to a 5 second wait, which IMO is a lot better than 20s but still too long. One solution that might work would be for you to skip using _gaq.push() and output an image tag with the URL and params directly for each one. This is sort of the same principle as the "traditional" GA code that came before the async version, and is what most other analytics tools still do today. If you want my honest opinion though...in my experience with web analytics, I think the most likely thing here is that you need to re-evaluate what you are tracking in the first place. Judging by the context of your values, (and this is just a guess) it looks to me like you have for instance a page where a user can see a list of books, like a search results page or maybe a general "featured books" page or something similar, and you are wanting to track all the books a user sees on that page. Based on my experience with web analytics, you are being way too granular about the data you collect. My advice to you is to sit down and ask yourself "How actionable is this data?" That is, after all, the point of web analytics - to help make actionable decisions. All day long I see clients fall into the trap of wanting to know absolutely every minute detail about stuff because they think it will help them answer something or make some kind of decision, and 99% of the time, it doesn't. It is one thing to track as an event individual books a user views, like an individual product details page, where you'd be tracking a single event. Or for search results page...track it as a "search" event, popping stuff like what the term searched was, how many results given, etc.. but not details about what was actually returned. I guess if I knew more details about your site and what this tracking is for, I could maybe give you more solid advice :/
{ "pile_set_name": "StackExchange" }