texts
sequence | tags
sequence |
---|---|
[
"Check if two pyspark Rows are equal",
"I am writing unit tests for a Spark job, and some of the outputs are named tuples: pyspark.sql.Row\n\nHow can I assert their equality?\n\nactual = get_data(df)\nexpected = Row(total=4, unique_ids=2)\nself.assertEqual(actual, expected)\n\n\nWhen I do this, the values are rearranged in an order I can not determine."
] | [
"python",
"python-2.7",
"unit-testing",
"pyspark",
"pyspark-sql"
] |
[
"Repeating an alarm to fire exact at specific time not work correctly",
"I am trying to set an alarm to fire everyday at specific time ex: 8:00am\nbut alarm manager not fire at exact time sometime after 2 minute of specific time and sometime more than that .\n\nMy code \n\nclass AlarmReceiver : BroadcastReceiver() {\n\noverride fun onReceive(context: Context, intent: Intent) {\n\n val builder = NotificationCompat.Builder(context)\n .setSmallIcon(R.drawable.ic_stat_name)\n .setContentTitle(\"notification title\")\n .setContentInfo(\"info\")\n .setDefaults(NotificationCompat.DEFAULT_SOUND)\n\n\n val notifManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager\n\n notifManager.notify(0, builder.build())\n}\n\ncompanion object {\n\n fun startAlarmManager(context: Context, hour: Int, minute: Int = 0) {\n // set time for alarm manager\n val calendar = Calendar.getInstance()\n calendar.timeInMillis = System.currentTimeMillis()\n calendar.set(Calendar.HOUR_OF_DAY, hour)\n calendar.set(Calendar.MINUTE, minute)\n calendar.set(Calendar.SECOND, 0)\n calendar.set(Calendar.MILLISECOND, 0)\n\n if (calendar.timeInMillis < System.currentTimeMillis())\n calendar.timeInMillis += 1000 * 60 * 60 * 24\n\n // set up alarm manager\n val alarmReceiver = Intent(context, AlarmReceiver::class.java)\n val pendingIntent = PendingIntent.getBroadcast(context, 0, alarmReceiver, PendingIntent.FLAG_UPDATE_CURRENT)\n val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager\n alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, AlarmManager.INTERVAL_DAY,\n pendingIntent)\n\n context.toast(\"started\")\n }\n\n fun stopAlarmManager(context: Context) {\n // set up alarm manager\n val alarmReceiver = Intent(context, AlarmReceiver::class.java)\n val pendingIntent = PendingIntent.getBroadcast(context, 0, alarmReceiver, 0)\n val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager\n alarmManager.cancel(pendingIntent)\n\n }\n\n\n}\n\n\n}\n\nwhen i use \n\nalarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.timeInMillis,pendingIntent)\n\n\nIt work fine and notification send exact at specific time \nOne more thing, I have already read this question but not solve my problem .\n\nUsing Alarmmanager to start a service at specific time\n\nAlarm Manager not working at specific given time interval\n\nand also\n\nScheduling Repeating Alarms"
] | [
"android",
"kotlin",
"alarmmanager"
] |
[
"iOS Convert TouchBegan coordinates to OpenGL ES Coordinates",
"New to OpenGL ES here. \nI'm using the following code to detect where I tapped in a GLKView (OpenGL ES 2.0). I would like to know if I touched my OpenGL drawn objects. It's all 2D. \nHow do I convert the coordinates I am getting to OpenGL ES 2.0 coordinates, which are seemingly -1.0 to 1.0 based? Are there already built in functions to do so? \n\nThanks. \n\n- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event\n{\n CGRect bounds = [self.view bounds];\n\n UITouch* touch = [[event touchesForView:self.view] anyObject];\n\n CGPoint location = [touch locationInView:self.view];\n\n NSLog(@\"x: %f y: %f\", location.x, location.y);\n\n}"
] | [
"ios",
"opengl-es",
"opengl-es-2.0"
] |
[
"Using javascript global window variables and integration testing",
"There's this nifty stackoverflow post on passing variables to Javascript. It echos this railscast episode. The technique works like a charm for configuring a jquery datepicker, but cause all my javascript integration tests to fail.\n\nHere is the code in application.html.erb\n\n<script type=\"text/javascript\">\n<%-# commented line -%>\n window.sDateFormatLocal = \"<%= t 'date.formats.js_date' %>\"\n</script>\n\n\nThis is a datepicker initialization that uses it\n\n $(\"input.datepicker\").datepicker({\n dateFormat: sDateFormatLocal,\n onClose: function(value, ui) {\n console.log(\"regular old datepicker\");\n }\n }\n\n\nIt appears to work very well. The only problem, all my integration tests with 'js: true' now fail. Here are the errors I get.\n\n\n Capybara::Poltergeist::JavascriptError:\n One or more errors were raised in the Javascript code on the page:\n\n ReferenceError: Can't find variable: sDateFormatLocal\n\n\n\nWhen I run in browser (Chrome, Firefox) there are no errors or warnings in the console.\n\nFor completeness, a typical spec looks like this:\n\n describe \"The root\" do\n it \"should load the page and have js working.\", :js => true do\n visit root_path\n page.should have_content \"Hello world\"\n end\n end\n\n\nIs there a setting I am missing to allow variables like this in poltergeist?"
] | [
"ruby-on-rails",
"capybara",
"phantomjs",
"poltergeist"
] |
[
"Split a list of tuples into sub-lists of the same tuple field",
"I have a huge list of tuples in this format. The second field of the each tuple is the category field.\n\n [(1, 'A', 'foo'),\n (2, 'A', 'bar'),\n (100, 'A', 'foo-bar'),\n\n ('xx', 'B', 'foobar'),\n ('yy', 'B', 'foo'),\n\n (1000, 'C', 'py'),\n (200, 'C', 'foo'),\n ..]\n\n\nWhat is the most efficient way to break it down into sub-lists of the same category ( A, B, C .,etc)?"
] | [
"python",
"list",
"sorting",
"grouping"
] |
[
"How to get vim to indent tcl properly?",
"I have the following sample tcl:\n\n#!/usr/bin/env tclsh\n\nproc main {} {\n foreach v $::argv {\n puts $v\n}\n}\n\nmain\n\n\nWhen I get vim to indent this code (ggVG=), it indents exactly as above, which is obviously wrong as the braces do not match up. \n\nHowever, I'm pretty sure my vim is set up properly:\n\n:set\n--- Options ---\n autoindent backspace=2 expandtab hlsearch scroll=22 syntax=tcl wildmenu\n autoread comments=:# filetype=tcl incsearch shiftround ttyfast window=0\n background=dark commentstring=#%s helplang=en modelines=0 shiftwidth=4 ttymouse=xterm2 nowrap\n fileencoding=utf-8\n fileencodings=ucs-bom,utf-8,default,latin1\n formatoptions=tcroql\n indentexpr=GetTclIndent()\n indentkeys=0{,0},!^F,o,O,0]\n\n\nand\n\n:scriptnames\n...\n 52: /usr/share/vim/vim80/ftplugin/tcl.vim\n 53: /usr/share/vim/vim80/indent/tcl.vim\n 54: /usr/share/vim/vim80/syntax/tcl.vim\n...\n\n\nIs this just how vim indents tcl, or am I doing something wrong?"
] | [
"vim",
"tcl",
"indentation"
] |
[
"What's the difference between RECTL and RECT?",
"According to MSDN, RECT and RECTL are identical structures. Is there any difference between them at all and if not whats the point of having both of them instead of just one?"
] | [
"winapi"
] |
[
"Blender animated character exported to THREE.js not animating properly",
"I am trying to export animated character from Blender to THREE.js JSON using official THREE.js blender exporter. I have tried a few models from the internet and also a model included in THREE.js: https://github.com/mrdoob/three.js/blob/dev/examples/models/skinned/marine/marine_anims_core.blend\n\nExported JSONs are tested in this example: https://github.com/mrdoob/three.js/blob/dev/examples/webgl_animation_skinning_blending.html \n\nImported models are animating badly + model has a wrong x rotation (-90deg). The rotation can be repaired by rotating imported object in THREE.js. However it rotates the bones too and so not fix the problem. I think the problem is bad rotation of skeleton in relation to the model. \n\nHow should I export the model from blender correctly? Or is there a way to fix this later in javascript? \n\nBlender: 2.73, 2.79, THREE.js: r77, r88, Chrome\n\nExample: Wrong animation video"
] | [
"animation",
"three.js",
"blender"
] |
[
"To stop button pass to another page JavaScript",
"Before clicking the button to execute, I want to verify whether the filled content meets the requirements. If there is any error message, the page cannot be redirected.\nI used .preventDefault(), but it didn't work. Even error, the page was still redirected.\n\r\n\r\nlet btnAjtBtlCellier = document.getElementById('ajouterBouteilleCellier');\nlet fAjtBtlCellier = document.getElementById('form-ajouter-btl');\nlet inputEles = document.querySelectorAll('#form-ajouter-btl input');\nlet erreurAjtBtl = false;\ninputEles.forEach(function(element) {\n //Verify all required inputs\n element.addEventListener('change', (evt) => {\n quantiteValideAjt();\n date_achatValideAjt();\n prixValideAjt();\n })\n});\n\nbtnAjtBtlCellier.addEventListener('click', (evt) => {\n erreurAjtBtl = false;\n if (erreurAjtBtl) evt.preventDefault();\n})\r\n<div class=\"form-ajouter\" id=\"form-ajouter-btl\">\n <p>Nom : <span data-id=\"\" class=\"nom_bouteille\"></span></p>\n <span id=\"errNom_ajouter\"></span>\n <label for=\"millesime_ajouter\">Millesime : </label>\n <input type=\"text\" name=\"millesime\" id=\"millesime_ajouter\" value=\"2020\">\n <label for=\"quantite_ajouter\">Quantite : </label>\n <input type=\"text\" name=\"quantite\" value=\"1\" id=\"quantite_ajouter\">\n <span id=\"errQuantite_ajouter\"></span>\n <label for=\"date_achat_ajouter\">Date achat : </label>\n <input type=\"date\" name=\"date_achat\" id=\"date_achat_ajouter\" value=\"\">\n <span id=\"errAchat_ajouter\"></span>\n <label for=\"prix_ajouter\">Prix : </label>\n <input type=\"text\" name=\"prix\" id=\"prix_ajouter\" value=\"\">\n <span id=\"errPrix_ajouter\"></span>\n <label for=\"garde_jusqua_ajouter\">Garde : </label>\n <input type=\"text\" name=\"garde_jusqua\" id=\"garde_jusqua_ajouter\">\n <label for=\"notes_ajouter\">Notes</label>\n <input type=\"text\" id=\"notes_ajouter\" name=\"notes\">\n <!-- input caché avec id usager -->\n <input type=\"hidden\" name=\"courriel_usager\" value=\"<?= $_SESSION[\" courriel \"] ?>\">\n</div>\n<button name=\"ajouterBouteilleCellier\" id=\"ajouterBouteilleCellier\">AJOUTER LA BOUTEILLE</button>"
] | [
"javascript"
] |
[
"Interlocked used to increment/mimick a boolean, is this safe?",
"I'm just wondering whether this code that a fellow developer (who has since left) is OK, I think he wanted to avoid putting a lock. Is there a performance difference between this and just using a straight forward lock?\n\n private long m_LayoutSuspended = 0;\n public void SuspendLayout()\n {\n Interlocked.Exchange(ref m_LayoutSuspended, 1);\n }\n\n public void ResumeLayout()\n {\n Interlocked.Exchange(ref m_LayoutSuspended, 0);\n }\n\n public bool IsLayoutSuspended\n {\n get { return Interlocked.Read(ref m_LayoutSuspended) != 1; }\n }\n\n\nI was thinking that something like that would be easier with a lock? It will indeed be used by multiple threads, hence why the use of locking/interlocked was decided."
] | [
"c#",
"multithreading",
"interlocked"
] |
[
"MS Excel Vba Arabic unicode",
"I have a text file and a macro enabled excel file. the excel file gets (using vba) the string (arabic text) from the text file per line then put it on the sheet1 cells. The problem is the string is not properly displayed. It is displayed in random Japanese characters. (My windows locale is Japan). \n\nHere is my code:\n\nOpen FilePath For Inputs As #1\n\nDo Until EOF(1)\n\nLine Input #1, textline\nActiveWorkbook.sheets(1).Cell(1,1).Value = textline\n 'MsgBox(textline)\n\nLoop\n\nClose#1\n\n\nQuestion: How can I get the string(arabic text) to be still arabic when pasted in the excel file?"
] | [
"excel",
"vba",
"unicode",
"locale",
"arabic"
] |
[
"How to reconnect a client automatically on ratchetphp?",
"I'm using rachetphp to create a client for an api server.\nBut i have a problem, when my connection close, whatever the reason, i can't reconnect automatically.\n\nhere the lib i use : https://github.com/ratchetphp/Pawl\n\n<?php\n\nrequire __DIR__ . '/vendor/autoload.php';\n\n$loop = React\\EventLoop\\Factory::create();\n$connector = new Ratchet\\Client\\Connector($loop);\n\n$connector('ws://127.0.0.1:9000', ['protocol1', 'subprotocol2'], ['Origin' => 'http://localhost'])\n->then(function(Ratchet\\Client\\WebSocket $conn) {\n $conn->on('message', function(\\Ratchet\\RFC6455\\Messaging\\MessageInterface $msg) use ($conn) {\n echo \"Received: {$msg}\\n\";\n $conn->close();\n });\n\n $conn->on('close', function($code = null, $reason = null) {\n echo \"Connection closed ({$code} - {$reason})\\n\";\n });\n\n $conn->send('Hello World!');\n}, function(\\Exception $e) use ($loop) {\n echo \"Could not connect: {$e->getMessage()}\\n\";\n $loop->stop();\n});\n\n$loop->run();\n\n\nI would like to try a reconnect every Seconds after a connection close.\nAny ideas?"
] | [
"php",
"sockets",
"client",
"wss",
"reactphp"
] |
[
"AES-128 CBC decryption",
"I have written this code in java in order to decrypt a ciphertext. I have the key. Everything seems correct to me but I have the problem that I'm gonna explain.\nHere is my code:\n\nimport javax.crypto.Cipher;\nimport javax.crypto.spec.IvParameterSpec;\nimport javax.crypto.spec.SecretKeySpec;\n\npublic class AES_CBC {\n\n public static void main(String[] args) throws Exception {\n\n byte[] keyBytes = new byte[] { 14, (byte) 0x0b, (byte) 0x41,\n (byte) 0xb2, (byte) 0x2a, (byte) 0x29, (byte) 0xbe,\n (byte) 0xb4, (byte) 0x06, (byte) 0x1b, (byte) 0xda,\n (byte) 0x66, (byte) 0xb6, (byte) 0x74, (byte) 0x7e, (byte) 0x14 };\n\n byte[] ivBytes = new byte[] { (byte) 0x4c, (byte) 0xa0, (byte) 0x0f,\n (byte) 0xf4, (byte) 0xc8, (byte) 0x98, (byte) 0xd6,\n (byte) 0x1e, (byte) 0x1e, (byte) 0xdb, (byte) 0xf1,\n (byte) 0x80, (byte) 0x06, (byte) 0x18, (byte) 0xfb, (byte) 0x28 };\n\n SecretKeySpec key = new SecretKeySpec(keyBytes, \"AES\");\n IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);\n\n Cipher cipher = Cipher.getInstance(\"AES/CBC/PKCS5Padding\");\n\n byte[] cipherText = new byte[] { (byte) 0x28, (byte) 0xa2, (byte) 0x26,\n (byte) 0xd1, (byte) 0x60, (byte) 0xda, (byte) 0xd0,\n (byte) 0x78, (byte) 0x83, (byte) 0xd0, (byte) 0x4e,\n (byte) 0x00, (byte) 0x8a, (byte) 0x78, (byte) 0x97,\n (byte) 0xee, (byte) 0x2e, (byte) 0x4b, (byte) 0x74,\n (byte) 0x65, (byte) 0xd5, (byte) 0x29, (byte) 0x0d,\n (byte) 0x0c, (byte) 0x0e, (byte) 0x6c, (byte) 0x68,\n (byte) 0x22, (byte) 0x23, (byte) 0x6e, (byte) 0x1d,\n (byte) 0xaa, (byte) 0xfb, (byte) 0x94, (byte) 0xff,\n (byte) 0xe0, (byte) 0xc5, (byte) 0xda, (byte) 0x05,\n (byte) 0xd9, (byte) 0x47, (byte) 0x6b, (byte) 0xe0,\n (byte) 0x28, (byte) 0xad, (byte) 0x7c, (byte) 0x1d, (byte) 0x81 };\n\n cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);\n byte[] original = cipher.doFinal(cipherText);\n String plaintext = new String(original);\n System.out.println(plaintext);\n}\n}\n\n\nI get the error below:\n\n Exception in thread \"main\" javax.crypto.BadPaddingException: Given final block not properly padded\n at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:969)\n at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:831)\n at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:436)\n at javax.crypto.Cipher.doFinal(Cipher.java:2097)\n at AES_CTR.main(AES_CBC.java:39)\n\n\nWhat is going wrong?\nI know the problem is somehow related to the padding but I don't the exact solution. I just have one ciphertext, IV, and the key."
] | [
"java",
"cryptography",
"block-cipher"
] |
[
"How to allow addons on firefox private browsing?",
"I have developed a firefox add-on. It is running fine in normal mode, but it is not running while in private browsing. \n\nDoes Firefox support addons in private browsing-mode? If yes, then how can i allow it to work in private-browsing mode?"
] | [
"firefox",
"firefox-addon"
] |
[
"Rails - insert many random items on create with has_many_through relation",
"I want to create a random pack of 15 cards which should be invoked in the cardpacks_controller on create. I have the following models:\n\nCard:\n\nclass Card < ActiveRecord::Base\n # relations\n has_many :cardpacks, through: :cardpackcards\n belongs_to :cardset\nend\n\n\nCardpack:\n\nclass Cardpack < ActiveRecord::Base\n #relations\n has_many :cards, through: :cardpackcards\n belongs_to :cardset\n\n # accept attributes\n accepts_nested_attributes_for :cards\nend\n\n\nCardpackcards:\n\nclass Cardpackcard < ActiveRecord::Base\n #relations\n belongs_to :card\n belongs_to :cardpack\nend\n\n\nCardsets:\n\nclass Cardset < ActiveRecord::Base\n #relations\n has_many :cards\n has_many :cardsets\nend\n\n\nHow can I create 15 Cardpackcards records with random card_id values and with the same cardpack_id (so they belong to the same pack)\n\nI have watched the complex form series tutorial but it gives me no comprehension as how to tackle this problem.\n\nI hope anyone can help me solve this problem and give me more insight in the rails language.\n\nThanks,\nErik"
] | [
"ruby-on-rails",
"has-many-through"
] |
[
"Rest POST API working with POSTMAN but not working Xamarin.Forms",
"Heres the code to my HttpPost request\n\nasync void ContinueBtn_Clicked(object sender, EventArgs e)\n{\n if (!CheckValidation())\n {\n LoginBLL cust = new LoginBLL();\n EncryptPassword encrypt = new EncryptPassword();\n\n cust.name = txtFieldName.Text;\n cust.email = txtFieldEmail.Text;\n cust.Password = encrypt.HashPassword(txtFieldPass.Text);\n cust.profession = txtFieldJob.Text;\n cust.company = txtFieldCompany.Text;\n cust.subId = 1320;\n\n HttpClient client = new HttpClient();\n string url = \"https://www.example.com/api/customer/\";\n var uri = new Uri(url);\n client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/json\"));\n HttpResponseMessage response;\n var json = JsonConvert.SerializeObject(cust);\n var content = new StringContent(json, Encoding.UTF8, \"application/json\");\n response = await client.PostAsync(uri, content);\n\n\n if (response.StatusCode == System.Net.HttpStatusCode.Accepted)\n {\n validationName.Text = await response.Content.ReadAsStringAsync();\n }\n else\n {\n validationName.Text = await response.Content.ReadAsStringAsync();\n }\n\n }\n\n\nAnd I am getting this error when I am executing the above function\n\n\n No HTTP resource was found that matches the request URI 'https://www.example.com/api/customer/'.\n\n\nBut it is working fine in Postman with same variables.\n\nI even verified the JSON generated in POSTMAN with the JSON being generated in the Visual Studio it is identical.\n\nI am running this on iphone 8 iOS 12.0"
] | [
"c#",
"rest",
"api",
"post",
"xamarin.forms"
] |
[
"How can I create a standard DLL in VB6?",
"TL:DR; How can I compile a VB6 module file into a standard DLL which I can use across multiple VB6 applications?\n\nI am tasked with the support of multiple legacy applications written in VB6.\n\nAll of these applications make use of piece of hardware constructed by my employer. Before I came on to work for my employer, he had outsourced the work of developing a DLL for the project to a company that is no longer capable of supporting it since the individual working for THEM recently quit and no one else is capable of figuring it out.\n\nMy employer has recently upgraded our hardware, so even worse - the DLL that Company furnished us with is no longer useful either.\n\nFurther exacerbated by the fact that the company who released to us the NEW hardware did not release to us a DLL file which is capable of running in VB6.\n\nIt now falls to me to create a DLL file ( NOT a device driver ) which is capable of facilitating communications between the new ( and hopefully the old ) devices and VB6 applications.\n\nMy knowledge of VB6 is... limited, at best. I am mostly familiar with .Net and have had much success in creating DLLs in .Net, but when it comes to VB6, I know enough to get by. I'm entering into uncharted territory here.\n\nI'm well acquainted with the HID.dll and the SetupAPI.dll P/Invokes and structs necessary to make this work, and I was even fortunate enough to stumble upon this, which had a working bit of VB6 code which facilitates read/writing to/from HIDs connected to the system. I tested this and ( with a bit of fidgeting ) it worked for our device out of the box. But that doesn't help me because I can't compile the module into a DLL file ( let alone figuring out events in VB6 and a truck load of other things, but I'm getting ahead of myself ).\n\nI've read and tried a few different methods and while they proved promising, they didn't work.\n\nGoogle has also inundated me with a lot of red herrings and been in general not very helpful.\n\nIf necessary, I would even write it in C/C++ ( though I'd rather not if there is some other way ).\n\nSo is what I am trying to do possible? Can someone direct me to some step-by-step for this sort of thing?\n\nEDIT 1 :\n\nTo expound a bit, when I say that \"they didn't work\", what I mean is that in the case of the first link, the program still failed to find the function ( with an error message like \"Function entry point not found\" ) and in the second case I consistently and repeatedly received a memory write error when trying to call the function ( not fun )."
] | [
"dll",
"vb6"
] |
[
"objective-c: help me understand views and modal transition",
"I'm lacking a serious understanding of how modal transitions work, so please do not leave the simplest answer out of this.\n\nI have two views with their own view controllers set up in storyboard. A button on the main-menu leads to other-view. I set up this transition purely via ctrl-click and selecting the modal transition. I also have a button leading from the other-view back to the main-menu, set up similarly.\n\nTo further my understanding of these transitions I decided that I want the main menu to play a sound when it loads up, but only the first time i hit run, and not again when i go hit the button the other-view to go back to menu-view.\n\nin my menu-view I have a private property BOOL\n\n@interface MainMenuViewController ()\n@property BOOL menuSoundPlayed;\n@end\n\n\nand my viewDidLoad...\n\n- (void)viewDidLoad\n{\n [super viewDidLoad];\n if (!self.menuSoundPlayed){\n //sound setup code omitted for clarity\n AudioServicesPlaySystemSound(mySound);\n self.menuSoundPlayed = YES;\n }\n}\n\n\ncan someone help me understand why the menu sound plays every time main-menu view loads? I do acknowledge that the menuSoundPlayed is never really initialized, but I dont know where I would even do that.\n\nside-note: I love that apple gives us all these conveniences like story-board, but I almost wish it was easier to see all the code behind these things, so i could actually understand what was going on when i 'segue' between views.\n\nAnyways, thank you!"
] | [
"iphone",
"objective-c",
"storyboard",
"modal-dialog",
"segue"
] |
[
"RibbonCommand was not found",
"I see the majority of WPF Ribbon examples out there use some code like \n\nxmlns:r=\"clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary\"\n\n\n\n\nI'm getting this error...\"The type 'r:RibbonCommand' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built.\"\n\nUsing VS 2010, .NET 4.0.\n\nI'm trying to figure out how to add a button to the ribbon and execute code/command when it's clicked.\n\nThanks."
] | [
"wpf",
"ribbon",
"ribboncontrolslibrary"
] |
[
"when I download mp3 error when I download song",
"When I open this link\n\ndownload.php?dir=files\\Special-Download&file=maid-with-the-flaxen-hair.mp3\n\nerror occure like\n\nWarning: Cannot modify header information - headers already sent by (\n\nthis is my php code\n\n$files = new filemanager;\n$dir = $files->get_absolute_path($_GET['dir']);\n$filemg=explode('.',$_GET['file']);\n$dwfile=$files->seo_friendly_url($filemg[0]).'.'.$filemg[1];\nif (isset($_GET['file'])) \n{\n $file=$dir.DIRECTORY_SEPARATOR.$dwfile;\n $files->downloadFile($file);\n}\n\n\ni use this class\n\nfunction downloadFile($dwf) {\n $file=str_replace('-',' ',$dwf);\n $ar_ext = explode('.',$file);\n $ext = strtolower(end($ar_ext));\n $extensions = array(\n 'mp3' =>'audio/mp3'\n );\n $ctype = isset($extensions[$ext]) ? $extensions[$ext] : 'application/force-download';\n header('Content-Description: File Transfer');\n header('Content-Type: application/octet-stream');\n header('Content-Disposition: attachment; filename=\"'.basename($file).'\"');\n header('Expires: 0');\n header('Cache-Control: must-revalidate');\n header('Pragma: public');\n readfile($file);\n}"
] | [
"php",
"download"
] |
[
"need help about process",
"when i start process like process= Runtime.getRuntime().exec(\"gnome-terminal\");, it start shell execution, i want to stop shell execution and want to redirect I/O from process, can anybody tell how i can do this?\n\nmy code is: \n\npublic void start_process()\n{\n try\n {\n process= Runtime.getRuntime().exec(\"bash\");\n pw= new PrintWriter(process.getOutputStream(),true);\n br=new BufferedReader(new InputStreamReader(process.getInputStream()));\n err=new BufferedReader(new InputStreamReader(process.getErrorStream()));\n\n }\n catch (Exception ioe)\n {\n System.out.println(\"IO Exception-> \" + ioe);\n }\n\n\n}\n\npublic void execution_command()\n{\n\n if(check==2)\n {\n try\n {\n boolean flag=thread.isAlive();\n if(flag==true)\n thread.stop();\n\n Thread.sleep(30);\n thread = new MyReader(br,tbOutput,err,check);\n thread.start();\n\n }catch(Exception ex){\n JOptionPane.showMessageDialog(null, ex.getMessage()+\"1\");\n }\n }\n else\n {\n try\n {\n Thread.sleep(30);\n thread = new MyReader(br,tbOutput,err,check);\n thread.start();\n check=2;\n\n }catch(Exception ex){\n JOptionPane.showMessageDialog(null, ex.getMessage()+\"1\");\n }\n\n }\n}\n\nprivate void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { \n // TODO add your handling code here:\n command=tfCmd.getText().toString().trim();\n\n pw.println(command);\n\n execution_command();\n\n} \n\n\nwhen i enter some command in textfield and press execute button, nothing displayed on my output textarea, how i can stop shellexecution and can redirect Input and output?"
] | [
"java"
] |
[
"Unable to configure AspNet.Identity using PostgreSQL",
"I have a web project that was setup using SQL Server, and that now has to be migrated to PostgreSQL. I'm using Entity Framework version 6.0 with the latest version of Microsoft.AspNet.Identity to manage user credentials. I'm using VS2015 and .NET Framework 452.\n\nThe project works fine with the PostgreSQL server for everything except AspNet.Identity. When I try to register a new user or do a login I get the same error message described in this question. Same error, same line but the question is 2 years old and the solution given doesn't work for me (I have tried Add-Migration and Update-Database multiple times).\n\nEverything else works, I have checked and my postgreSQL database does NOT contain any tables related to AspNet.Identity even though they were created automatically when the project was using SQL Server. Other model related tables are present and working.\n\nThank you."
] | [
"c#",
".net",
"postgresql",
"entity-framework",
"asp.net-identity"
] |
[
"Plugin works in local server but doesn't work in production server",
"I've a created a plugin with a button which does some task when clicking it. I've put this plugin in my local Jenkins (/jenkins/plugins) location and then restarted server. \n\nThe button appears on every job page, but When I put the same plugin in production server and restart it, the button doesn't appear.\n\nBoth my local Jenkins and production Jenkins have same version (2.7.1)\nI put plugin.jar and plugin.hpi files in /jenkins/plugins location\nCan anyone have idea whats the problem. How can I debug it?"
] | [
"jenkins",
"jenkins-plugins"
] |
[
"Taskbar Issue for My App",
"When I click on my Winforms app then its forms are opened in separate section in Taskbar with default C# icon. How can I solve this issue?\n\n\n\nUpdate:\n\nAt first I open my login form as bellow:\n\nApplication.Run(new frmLogin());\n\n\nThen I open my main form from the login form as bellow:\n\nthis.Hide();\nfrmMain frmMain = new frmMain();\nfrmMain.Show();"
] | [
"c#",
"winforms",
"taskbar"
] |
[
"Adding line breaks in a csv file",
"I got a coma separated string. I need to convert this to an array and be able to save it as a csv file.\n\n$fp = fopen(\"abc.csv\", \"w\");\n$str = \"FRUIT, STOCKS, TYPE\\n lychee, instocks, B-type\\n strawberry, N/A,A-type\\n\";\n\n$data = str_getcsv($str);\nfputcsv($fp, $data);\nfclose($fp);\n\n\nCurrently it outputs the entire string as a single line.\n\nExpected csv output:\n\nFRUIT, STOCKS, TYPE\nlychee, instocks, B-type\nstrawberry, N/A, A-type"
] | [
"php"
] |
[
"Incomplete filling when upsampling with `agg` for multiple columns (pandas resample)",
"I found this behavior of resample to be confusing after working on a related question. Here are some time series data at 5 minute intervals but with missing rows (code to construct at end):\n user value total\n2020-01-01 09:00:00 fred 1 1\n2020-01-01 09:05:00 fred 13 1\n2020-01-01 09:15:00 fred 27 3\n2020-01-01 09:30:00 fred 40 12\n2020-01-01 09:35:00 fred 15 12\n2020-01-01 10:00:00 fred 19 16\n\nI want to fill in the missing times using different methods for each column to fill missing data. For user and total, I want to to a forward fill, while for value I want to fill in with zeroes.\nOne approach I found was to resample, and then fill in the missing data after the fact:\nresampled = df.resample('5T').asfreq()\nresampled['user'].ffill(inplace=True)\nresampled['total'].ffill(inplace=True)\nresampled['value'].fillna(0, inplace=True)\n\nWhich gives correct expected output:\n user value total\n2020-01-01 09:00:00 fred 1.0 1.0\n2020-01-01 09:05:00 fred 13.0 1.0\n2020-01-01 09:10:00 fred 0.0 1.0\n2020-01-01 09:15:00 fred 27.0 3.0\n2020-01-01 09:20:00 fred 0.0 3.0\n2020-01-01 09:25:00 fred 0.0 3.0\n2020-01-01 09:30:00 fred 40.0 12.0\n2020-01-01 09:35:00 fred 15.0 12.0\n2020-01-01 09:40:00 fred 0.0 12.0\n2020-01-01 09:45:00 fred 0.0 12.0\n2020-01-01 09:50:00 fred 0.0 12.0\n2020-01-01 09:55:00 fred 0.0 12.0\n2020-01-01 10:00:00 fred 19.0 16.0\n\nI thought one would be able to use agg to specify what to do by column. I try to do the following:\nresampled = df.resample('5T').agg({'user':'ffill',\n 'value':'sum',\n 'total':'ffill'})\n\nI find this to be more clear and simpler, but it doesn't give the expected output. The sum works, but the forward fill does not:\n user value total\n2020-01-01 09:00:00 fred 1 1.0\n2020-01-01 09:05:00 fred 13 1.0\n2020-01-01 09:10:00 NaN 0 NaN\n2020-01-01 09:15:00 fred 27 3.0\n2020-01-01 09:20:00 NaN 0 NaN\n2020-01-01 09:25:00 NaN 0 NaN\n2020-01-01 09:30:00 fred 40 12.0\n2020-01-01 09:35:00 fred 15 12.0\n2020-01-01 09:40:00 NaN 0 NaN\n2020-01-01 09:45:00 NaN 0 NaN\n2020-01-01 09:50:00 NaN 0 NaN\n2020-01-01 09:55:00 NaN 0 NaN\n2020-01-01 10:00:00 fred 19 16.0\n\nCan someone explain this output, and if there is a way to achieve the expected output using agg? It seems odd that the forward fill doesn't work here, but if I were to just do resampled = df.resample('5T').ffill(), that would work for every column (but is undesired here as it would do so for the value column as well). The closest I have come is to individually run resampling for each column and apply the function I want:\nresampled = pd.DataFrame()\n\nd = {'user':'ffill',\n 'value':'sum',\n 'total':'ffill'}\n\nfor k, v in d.items():\n resampled[k] = df[k].resample('5T').apply(v)\n\nThis works, but feels silly given that it adds extra iteration and uses the dictionary I am trying to pass to agg! I have looked a few posts on agg and apply but can't seem to explain what is happening here:\n\nLosing String column when using resample and aggregation with pandas\n\nresample multiple columns with pandas\npandas groupby with agg not working on multiple columns\n\nPandas named aggregation not working with resample agg\n\n\nI have also tried using groupby with a pd.Grouper and using the pd.NamedAgg class, with no luck.\n\nExample data:\nimport pandas as pd\n\ndates = ['01-01-2020 9:00', '01-01-2020 9:05', '01-01-2020 9:15',\n '01-01-2020 9:30', '01-01-2020 9:35', '01-01-2020 10:00']\ndates = pd.to_datetime(dates)\n\ndf = pd.DataFrame({'user':['fred']*len(dates),\n 'value':[1,13,27,40,15,19],\n 'total':[1,1,3,12,12,16]},\n index=dates)"
] | [
"python",
"pandas",
"dataframe",
"fillna",
"pandas-resample"
] |
[
"Matrix column comparison",
"I have to compare matrix columns.\n\nI tried many variations, but as far as I got, is when I compare \"next to each other\" columns.\n\n// N rows\n// M columns\n\n#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n ios_base::sync_with_stdio(false);\n\n int N, M, ok = 1;\n const int maxn = 1000;\n const int maxm = 1000;\n short H[maxn][maxm];\n\n cin >> N >> M;\n\n for (int i=0; i<N; i++){\n for (int j=0; j<M; j++){\n cin >> H[i][j];\n }\n }\n\n for (int j = 1; j < M; ++j)\n {\n ok = 1;\n for (int i = 0; i < N; ++i)\n {\n if (H[i][j-1] >= H[i][j])\n {\n ok = 0;\n }\n }\n if (ok)\n {\n cout << j+1 << endl;\n return 0;\n }\n }\n cout << -1 << endl;\n return 0;\n}\n\n\nI have to give back the index of the first column where is true, that the column's every element is greater than ANY OTHER column's elements. (Not summarized.) \n\nFor example:\n\n10 10 12 15 10\n11 11 11 13 20\n12 16 16 16 20\n\n\nIt returns with 4, because the 4th column's every element is greater, than the 1st column's elements.\nIf there are none, it has to return with -1."
] | [
"c++",
"algorithm",
"matrix"
] |
[
"Why this error appear? \"Invalid XAML\"",
"<toolkit:GestureListener DragDelta=\"taskitem_DragDelta\" DragCompleted=\"taskitem_DragCompleted\"/>\n\n\nThe code above always shows an error in Blend4, \"Invalid XAML\"\nbut never shows an error in VS2010 for WP.\nand the app can run like a charm.\n\nWhy does this error happen and how I can solve it? is it just a bug?"
] | [
"windows-phone-7",
"xaml",
"expression-blend"
] |
[
"State Management and Instances",
"Here is how I'm changing the UI depending on provider value:\nclass Decider extends StatelessWidget {\n @override\n Widget build(BuildContext context) =>\n Consumer<ConnectionStateUpdate>(\n builder: (_, connectionStateUpdate, __) {\n bool _bleDeviceConnected() =>\n connectionStateUpdate.connectionState ==\n DeviceConnectionState.connected;\n if (_bleDeviceConnected()) return DeviceUI(); //stateful widget which contains device UI and funcs\n else return DeviceConnectChecks(); //stateful widget allowing searching/connecting to device\n }\n );\n}\n\nDoes this mean that every time the bool value for bleDeviceConnected changes, a new instance of the same class is created and the previous one is kept in memory? After repeatedly disconnecting/connecting the device (around 6-7 times in the same instance of the app ie. without restarting it), the UI and animations start appearing janky."
] | [
"flutter",
"flutter-provider"
] |
[
"NameError: global name is not defined",
"Hello\nMy error is produced in generating a zip file. Can you inform what I should do?\n\nmain.py\", line 2289, in get\n buf=zipf.read(2048)\nNameError: global name 'zipf' is not defined\n\n\nThe complete code is as follows:\n\n def addFile(self,zipstream,url,fname):\n # get the contents \n result = urlfetch.fetch(url)\n\n # store the contents in a stream\n f=StringIO.StringIO(result.content)\n length = result.headers['Content-Length']\n f.seek(0)\n\n # write the contents to the zip file\n while True:\n buff = f.read(int(length))\n if buff==\"\":break\n zipstream.writestr(fname,buff)\n return zipstream\n\n def get(self): \n self.response.headers[\"Cache-Control\"] = \"public,max-age=%s\" % 86400\n start=datetime.datetime.now()-timedelta(days=20)\n count = int(self.request.get('count')) if not self.request.get('count')=='' else 1000 \n from google.appengine.api import memcache\n memcache_key = \"ads\"\n data = memcache.get(memcache_key)\n if data is None:\n a= Ad.all().filter(\"modified >\", start).filter(\"url IN\", ['www.koolbusiness.com']).filter(\"published =\", True).order(\"-modified\").fetch(count)\n memcache.set(\"ads\", a) \n else:\n a = data\n dispatch='templates/kml.html'\n template_values = {'a': a , 'request':self.request,}\n path = os.path.join(os.path.dirname(__file__), dispatch)\n output = template.render(path, template_values) \n self.response.headers['Content-Length'] = len(output) \n zipstream=StringIO.StringIO()\n file = zipfile.ZipFile(zipstream,\"w\")\n url = 'http://www.koolbusiness.com/list.kml'\n # repeat this for every URL that should be added to the zipfile\n file =self.addFile(file,url,\"list.kml\")\n # we have finished with the zip so package it up and write the directory\n file.close()\n zipstream.seek(0)\n # create and return the output stream\n self.response.headers['Content-Type'] ='application/zip'\n self.response.headers['Content-Disposition'] = 'attachment; filename=\"list.kmz\"' \n while True:\n buf=zipf.read(2048)\n if buf==\"\": break\n self.response.out.write(buf)"
] | [
"python",
"django",
"google-app-engine",
"zip",
"kmz"
] |
[
"How to get results from a query which is inside of a function",
"I'm trying to make an \"AdminCheck\" system which will check if the user is admin and return user's admin level based on information gathered from database\n\nI've did some research and realized my problem is with query being asynchronous, but I couldn't find more\n\nfunction isAdmin(varr){\n let queryCheck = \"SELECT AdminLVL FROM accounts WHERE username = ?\"\n pool.query(queryCheck, [varr], (err,results) => {\n console.log(results[0].AdminLVL) // This gives me results\n if(err){\n console.log(err)\n }\n else {\n return results[0].AdminLVL\n }\n })\n}\n\n\nright where I commented \"This gives me results\" everything works fine, but I wanna be able to use the result, which let's think its \"300\", somewhere else."
] | [
"mysql",
"node.js"
] |
[
"Debugging React using Visual Studio Code",
"I'm trying to debug a React application I'm creating using Visual Studio code. I'm trying to debug it after creating a launch configuration for debug.\nMy Issues:\n\nSometimes when I try to step into a code in another file, I jump to that file, but the rows where the code iterator is are not highlighted and I can't see the values of the variables. The only thing which is a little different is a little almost transparent box telling me what line is executed right now. It's like there's another file which is actually being debugged? Not happens everywhere.. in a constructor I'm trying to debug for example.\n\nMy desired behavior: I want a clear debugging like you have in other IDEs like VS where the entire line is marked and I can view variable's state by hovering their name in the code.\n\nWhen I set a breakpoint at a line it's being set, but when I run the code for debug it's being grayed out and I need to set it again.\n\nMy desired behavior: Keep the breakpoint on\nPlease note that I don't want to change the code with adding debugger every time I need to debug something..\nHow can I solve these issues?"
] | [
"debugging",
"visual-studio-code"
] |
[
"Implementing SHORTCUT",
"i want to implement SHORTCUT as we see in android emulator. i want to know how to get the long clicked grid item on homeScreen with same position/co-ordinates as that of menuScreen. atleast provide me some ideas. Thanks in advance"
] | [
"android",
"android-widget",
"shortcut",
"homescreen"
] |
[
"Javascript animating CSS opacity, stuck",
"I am trying to animate a single elements opacity when I hover over it by using the same class and accessing it via $this.\n\nI know I could solve this problem by adding different named classes for each item, but as my application grows that will not be a viable solution, below is my code, it currently animates all three image opacitys to 1.\n\n<script>\n$(document).ready(function(){\n $(\".videos\").hover(function(){\n var $this = $(this),\n $focus = $this.find('.video');\n $focus.stop().animate({opacity: 1.0 }, 500);\n }, function(){\n $(\".video\").stop().animate({opacity: 0.6 }, 500);\n });\n});\n</script>\n\n\nAnd here is the html :\n\n<div class=\"videos\">\n <div class=\"row-fluid\">\n <div class=\"span12\">\n <h3>LATEST VIDEOS</h3>\n <div class=\"row-fluid\">\n <div class=\"span4 video1\">\n <a href=\"#\"><img class=\"video\" src=\"images/media/vid1.jpg\"/></a>\n <p>A description of the video will go here for the user to see,\n once a user clicks a video the player will be enlarged and the other\n videos shall be forced underneath</p>\n </div>\n <div class=\"span4 video2\">\n <a href=\"#\"><img class=\"video\" src=\"images/media/vid2.jpg\"/></a>\n <p>A description of the video will go here for the user to see,\n once a user clicks a video the player will be enlarged and the other\n videos shall be forced underneath</p>\n </div>\n <div class=\"span4 video3\">\n <a href=\"#\"><img class=\"video\" src=\"images/media/vid3.jpg\"/></a>\n <p>A description of the video will go here for the user to see,\n once a user clicks a video the player will be enlarged and the other\n videos shall be forced underneath</p>\n </div>\n </div>\n </div>\n </div>\n </div>\n\n\nI have tried browsing other web sources but I have not yet found a solution, I'm sure I have made a silly mistake somewhere.\n\nAny pointer would be greatly appreciated."
] | [
"javascript",
"jquery",
"html"
] |
[
"Get an element from server in asc order based on the particular id",
"I get a certain response from the server which looks like so...\n\n[\n {\n \"theCode\": A12345,\n \"id\": 2980,\n \"name\": “HELLO”\n },\n {\n \"theCode\": A12345,\n \"id\": 2986,\n \"name\": \"HELLO THERE”\n },\n {\n \"theCode\": A12345,\n \"id\": 2987,\n \"name\": \"HOW ARE YOU”\n }\n]\n\n\nOnce the api is called, I store the above data in an array. It is given like so...\n\nif let myArray = (sdfg[\"entries\"] as? NSMutableArray) {\n print(myArray) \n\n} \n\n\nI would like the name in the above response to be sorted in ascending order based on the id. How can this be achieved...?"
] | [
"ios",
"swift"
] |
[
"Sampling from an array",
"I have a float array containing 1M floats\n\nI want to do sampling: for each 4 floats I want to take only 1. So i am doing this :\n\nfor(int i = 0; i< floatArray.Length; i++) {\n if(i % 4 == 0) {\n resultFloat.Add(floatArray[i])\n }\n}\n\n\nThis works fine, but it takes much time to run through all the elements , is there any other methods to make it with better results (if there are any)"
] | [
"c#"
] |
[
"chunked encoding and connection:close together",
"I'm a bit confused about what to do with the \"Connection\" header when using chunked-encoding. Shall the \"Connection\" header not be added (or set to keep-alive, which is the same as we're talking about HTTP 1.1) or is this authorized to set it to Connection:close\nSending an empty chunk, means the end of the transfer, but does it mean the end of the connection? I thought that I would need to add Connection:close when my intention is to close the connection after an empty chunk has been sent where if I don't add the Connection header, it would remain open\n\nThanks"
] | [
"http",
"chunked-encoding"
] |
[
"Extend interface object",
"I've had a problem I couldn't solve in a 'pleaserable manner', so I'm wondering if some people here would know how to do it.\nSay I have an interface with a specific property :\ninterface a{\n x: {\n property: string;\n }\n}\n\nIf I have a second interface, that extends the first, and want to add properties to 'x', the compiler will throw an error, unless I add the previous property to b :\ninterface b extends a{ //Will give 'interface b incorectly extends interface a'\n x: {\n otherProperty: number; \n }\n}\n\ninterface b extends a{ //Will work\n x: {\n property: string;\n otherProperty: number; \n }\n}\n\nNow, i'm wondering if there is a way to say to the compiler that the x property of b is equal to a's, something similar to :\ninterface b extends a{\n x extends a.x{\n otherProperty: number;\n }\n}\n\nThank you for taking the time to read."
] | [
"typescript",
"interface"
] |
[
"BusinessProcessManagement with BonitaSoft Engine",
"I am very much new to BPM (Business Process Management), I was asked to go through the Bonitasoft BPM and got an idea of it. I have created a sample Business Process in the Bonita Studio, after that what should I do with this process I created? I mean how will I use this in my application?\n\nThanks"
] | [
"business-process-management"
] |
[
"ReflectionTypeLoadException and COM-Interop",
"I have a .Net4 assembly which exposes an abstract, base class. In that same assembly, I have some code which reflects over all the files in a folder to build up a list of classes inheriting that base class. Here's the salient routine \n\nprivate JsonTextWriter GetAvailableServices(JsonTextWriter writer, string path)\n{\n try\n { \n writer.WriteStartArray();\n writer = new DirectoryInfo(path).GetFiles(FileFilter)\n .Where(f => IsAssembly(f.FullName))\n .Select(f => Assembly.LoadFile(Path.Combine(path, f.Name)))\n .SelectMany(a => GetLoadableTypes(a))\n .Where(p => typeof(ServiceProxy).IsAssignableFrom(p) && !p.IsAbstract)\n .Select(a0 => new { Instance = Activator.CreateInstance(a0), ClassName = a0.ToString() })\n .Aggregate(writer, (s, v) =>\n {\n s.WriteStartObject();\n s.WritePropertyName(ClassnameLabel);\n s.WriteValue(v.ClassName);\n s.WritePropertyName(DescriptionLabel);\n s.WriteValue(((ServiceProxy)v.Instance).Description);\n s.WriteEndObject();\n return s;\n }); \n }\n catch { Exception ex; }\n finally\n {\n writer.WriteEndArray(); \n }\n\n return writer;\n}\n\nprivate IEnumerable<Type> GetLoadableTypes(Assembly assembly)\n{ \n try\n {\n return assembly.GetTypes();\n }\n catch (ReflectionTypeLoadException e)\n {\n return e.Types.Where(t => t != null);\n }\n}\n\n\nI have a unit test which runs this code, targeting a specific folder, and it all works fine returning a list of classes inheriting the base class as JSON.\n\nThe above code sits in an assembly which is to be invoked from a COM (VB6) component. If I now invoke this same code from COM, targetting the same folder which the unit test targets, I get the reflection error and the loader info reports that it can't load the assembly which contains the above code. This only occurs in the GetLoadableTypes routine on the GetTypes() call when I am reflecting over an assembly which contains classes which do inherit the base class.\n\nIt sounds almost like a re-entrancy issue which only arises when COM is involved. I guess I could put the abstract base class into another assembly but wondered if there was something else going on.\n\nAny explanation or pointers obviously gratefully received\n\nError Message:\n\n\n ReflectionTypeLoadException \"Unable to load one or more of the\n requested types. Retrieve the LoaderExceptions property for more\n information.\"\n\n\nand in the LoaderExceptions:\n\n\n \"Could not load file or assembly 'IfxGenDocService, Version=1.0.0.0,\n Culture=neutral, PublicKeyToken=null' or one of its dependencies. The\n system cannot find the file specified.\":\"IfxGenDocService,\n Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\"\n\n\nEDIT1: I changed things around a bit to extract the base class into its own assembly and am still getting the same error. Perhaps relevant, is that I have atest assembly which contains 3 classes inheriting the base class. I get 3 LoaderExceptions (all the same as reported above. I assume 1 for each class."
] | [
"c#",
"reflection",
"com-interop"
] |
[
"\"Pinch to Zoom\" using AutoLayout",
"I have followed many \"Pinch to Zoom\" tutorials I found online, and have done reading on AutoLayout, but I can't get it to work in my project. \n\nMy whole project uses AutoLayout, so I don't want to turn it off. \nI am loading a huge UIImage (EG: 5000px on long edge) into a UIImageView, and i'd like to be able to pinch to zoom and move around the zoomed in image. \n\nI've tried using UIImageView inside a UISrollView, but I couldn't get it to work properly. The closest I could get was some random \"glitching\" where the image moved erratically when pinched. \n\nHas anybody got 'Pinch to Zoom' to work using Autolayout in iOS 6? I don't care if it uses UIScrollView or something else, I'd just love to get it to work. \n\nThanks,\n\nIsaac"
] | [
"uiscrollview",
"uiimageview",
"zooming",
"autolayout",
"pinch"
] |
[
"Howto load a smaller version of UImage directly from a file in ios?",
"When I open large images in an UIImageView (above 2000x3000), my app crashes because of memory consumption, so the idea is to scale the image. So far I have only seen code to load the large image, then draw it in a smaller context, which still needs the memory for the large file.\n\nIs there some way to draw into the context directly from a file or to create an UIImage from file that has the right dimensions?\n\nWhat I want is to show the content of lets say a jpeg-file with 2000x3000 pixels in lets say a UIImageView with 500x750 pixels. And that without using up too much memory because there are multiple images to be shown.\n\nAny help/ideas are welcome!"
] | [
"ios",
"uiimage"
] |
[
"Refering to dynamically selected keys in XML Schemas",
"If I have an XML document that goes something like this:\n\n<Choices name=\"Numbers\">\n <Choice>1</Choice>\n <Choice>2</Choice>\n <Choice>3</Choice>\n</Choices>\n<Choices name=\"Letters\">\n <Choice>A</Choice>\n <Choice>B</Choice>\n <Choice>C</Choice>\n</Choices>\n<Selected>\n <Selection category=\"Letters\">B</Selection>\n</Selected>\n\n\nI would like to describe a constrain in an XSD that makes sure that the selection tags data only refers to choices in the category \"Letters\". Is this something that is doable? It is fairly easy to do it with keys as long as you are OK with it having any choice in any category as it's data, but I'm stumped on how to limit which categories choices it can refer to."
] | [
"xml",
"xsd"
] |
[
"Are Using Remote Url or local path same performance wise when copying?",
"Question is self-explanatory.\nI have a file /var/www/example/filez/file1.exe\n\nIt can also be accessed via https://www.abc.xyz/filez/file1.exe.\n\nNow my question is if I have a script\n/var/www/example/script.php\n\nIs Trying \ncopy('/var/www/example/filez/file1.exe',$target_location) \n\nless expensive than\n\ncopy('https://www.abc.xyz/filez/file1.exe',$target_location) ?\n\nOr it does it not matter?"
] | [
"php",
"linux",
"ubuntu",
"https",
"copy"
] |
[
"Couldn't find Workout without an ID Error With Nested Routes",
"I have a set of nested routes that look like this:\n\n resources :workouts do\n resources :exercises do\n resources :reports, shallow: true\n end\n end\n\n\nI tried to make them as shallow as possible, but not nesting them simply generated too many errors.\n\nRight now they're working fine except when I try to access the exercises#index page for a specific workout. I'm linking the page like this:\n\n<%= link_to 'Add/Edit Exercises', workout_exercises_path(@workout, exercise), method: :index %>\n\n\nAnd when I click that link I get:\n\nActiveRecord::RecordNotFound at /workouts/3/exercises\nCouldn't find Workout without an ID\n\n\nThe error is called on my exercises_controller on the indicated line:\n\nclass ExercisesController < ApplicationController\n before_action :authenticate_user!\n\n def index\n @workout = Workout.friendly.find(params[:id]) <<<<<THIS LINE\n @exercise = Exercise.new\n @exercises = Exercise.all\n end\n\n def new\n @exercise = Exercise.new\n end\n\n def create\n @workout = Workout.friendly.find(params[:id])\n exercise = @workout.exercises.new(exercise_params)\n exercise.user = current_user\n\n if exercise.save\n flash[:notice] = \"Results saved successfully.\"\n redirect_to [@workout]\n else\n flash[:alert] = \"Results failed to save.\"\n redirect_to [@workout]\n end\n end\n\n def destroy\n @workout = Workout.friendly.find(params[:workout_id])\n exercise = @workout.exercises.find(params[:id])\n\n if exercise.destroy\n flash[:notice] = \"Exercise was deleted successfully.\"\n redirect_to [@workout]\n else\n flash[:alert] = \"Exercise couldn't be deleted. Try again.\"\n redirect_to [@workout]\n end\n end\n\n private\n\n def exercise_params\n params.require(:exercise).permit(:name, :needs_seconds, :needs_weight, :needs_reps, :workout_id)\n end\n\n def authorize_user\n exercise = Exercise.find(params[:id])\n unless current_user == current_user.admin?\n flash[:alert] = \"You do not have permission to create or delete an exercise.\"\n redirect_to [exercise.workout]\n end\n end\nend\n\n\nThe friendly.find is because I am using the friendly_id gem, which generates slugs instead of ids in the url. I use it in the same manner in other working models, so I do not believe this is causing the current problem.\n\nCan anyone see why I'm getting this error? I have typed @workout into the live shell of my error and it says that @workout is nil, which means it isn't getting the value somehow. I know this is important information, but don't know how to fix it."
] | [
"ruby-on-rails",
"nested-routes"
] |
[
"Swift 3 Presenting View Controller",
"I am having a perplexing problem in Swift 3. I'm presenting a ViewController and, for some reason, the parent ViewController gets loaded again thus causing an error. My code for loading my ViewController is:\n\nlet vc = self.storyboard?.instantiateViewController(withIdentifier: \"jobcodes\") as! JobCodesViewController\nvc.badge=self.badgeNum\nvc.jobnumber=self.keysPressed\nvc.show=result as! String\nself.present(vc, animated: true, completion: nil)\n\n\nI made sure the identifier wasn't tied to the wrong view and it is not."
] | [
"swift3",
"viewcontroller"
] |
[
"Can I use if/then to enforce property constraints contradicting those previously given?",
"I'm working with a multi-part JSON schema (but am new to JSON schemas).\nThe schema places constraints on a profile, which contains resource templates, each of which contains property templates.\nI'm attempting to change the way that constraints are enforced on the properties within any given property template.\n\nIn the schema module for property templates, constraints are placed on the properties \"mandatory\", \"repeatable\", and \"type\" as follows:\n\n\"mandatory\": {\n \"type\": [\"boolean\", \"string\"],\n \"enum\": [\"true\", \"false\"],\n \"title\": \"Mandatory\",\n \"description\": \"Indication that a value for the property is required. If unspecified, defaults to false.\",\n \"default\": false\n},\n\n\n[...]\n\n\"repeatable\": {\n \"type\": [\"boolean\",\"string\"],\n \"enum\": [\"true\", \"false\"],\n \"title\": \"Repeatable\",\n \"description\": \"Indication that the property is repeatable. If unspecified, defaults to true.\",\n \"default\": true\n},\n\n\n[...]\n\n\"type\": {\n \"type\": \"string\",\n \"enum\": [\"literal\", \"lookup\", \"resource\"],\n \"title\": \"Type\",\n \"description\": \"Type of value (literal / resource / lookup) that is allowed by this property.\"\n},\n\n\nI'd like to use an if then statement to indicate that if the value of another property is -1 (an indicator that the property template has been added to the profile but not yet filled in with values), it needn't conform to the rules above. In fact, I'd like to make sure that the values for the properties above are empty strings in this case. \n\nI tried to do this in the following way:\n\n\"allOf\": [\n\n\n(some other if-thens here)\n\n {\n \"if\": {\n \"properties\": {\n \"uwFormOrder\": {\n \"const\": -1\n }\n }\n },\n \"then\": {\n \"$ref\": \"#/definitions/empty-PTs\"\n }\n }\n ],\n \"definitions\": {\n\n\n(some other definitions here)\n\n\"empty-PTs\": {\n \"properties\": {\n \"mandatory\": {\n \"const\": \"\"\n },\n \"repeatable\": {\n \"const\": \"\"\n },\n \"type\": {\n \"const\": \"\"\n }\n }\n }\n\n\nIs this approach* fundamentally wrong? \n\n*This approach = adding an additional if/then inside the existing \"allOf\", adding an additional definition insde the existing \"definitions\".\n\nOne final note: I'm modifying a schema published openly here--the original work is not my own, I'm just attempting to build a bit on it."
] | [
"json",
"jsonschema"
] |
[
"How to display the nth child of a Model?",
"How should i display my model correctly on my page? I have this model Process that hasOne Person and a person hasMany Training, so in my ProcessController@show i have this: \n\n$process = Process::where('id', $process->id)->with(['person'])->firstOrFail();\ndd($process->person->trainings);\n\n\non that die&dump it output all Training data that belongs to that particular person but my problem is on this page(show.blade.php of my process), it doesn't show my data:\n\n<table class=\"table4 display compact\">\n <tr style=\"line-height: 5px;\">\n <th style=\"display: none;\">Id</th>\n <th>Training</th>\n <th>Description</th>\n <th width=\"30px;\"></th>\n </tr>\n @if ($process->person && count($process->person->trainings) > 0)\n @foreach ($process->person->trainings as $training)\n <tr class=\"hide\" style=\"line-height: 5px;\">\n <td style=\"display: none;\">{{ $training->id }}</td>\n <td contenteditable=\"false\">{{ $training->training_name }}</td>\n <td contenteditable=\"false\">{{ $training->description }}</td>\n <td>\n <!--span class=\"table-remove4 glyphicon glyphicon-remove\"><i class=\"fas fa-minus-circle\"></i></span-->\n </td>\n </tr>\n @endforeach\n @else\n <tr class=\"hide\" style=\"line-height: 10px;\">\n <td style=\"display: none;\"></td>\n <td contenteditable=\"true\"></td>\n <td contenteditable=\"true\"></td>\n <td>\n <span class=\"table-remove4 glyphicon glyphicon-remove\"><i class=\"fas fa-minus-circle\"></i></span>\n </td>\n </tr>\n @endif\n</table>"
] | [
"html",
"laravel",
"laravel-blade"
] |
[
"Specify the length of the one-hot encoder in scikt",
"In this case, the output of \n\nfrom sklearn.preprocessing import OneHotEncoder\ndata = [[1], [3], [5]]\nencoder = OneHotEncoder(sparse=False)\nencoder.fit(data)\nprint(encoder.fit_transform(data))\n\n\nis\n\n[[1. 0. 0.]\n [0. 1. 0.]\n [0. 0. 1.]]\n\nIs it possible to get the output?\n\n[[1. 0. 0. 0. 0.]\n [0. 0. 1. 0. 0.]\n [0. 0. 0. 0. 1.]]"
] | [
"python",
"scikit-learn"
] |
[
"Why is VBA not able to locate an Excel file in a particular path, unless the file is re-saved with same name?",
"I have a VBA macro to open three workbooks (call them \"file0.xlsm\", \"file1.xlsm\", and \"file2.xlsm\") for reading and editing.\n\nThe problem is with opening the first of these files. Whenever I start Excel and attempt to run the macro, VBA shows the error: \n\n\n \"Runtime Error 1004:\n Sorry we couldn't find 'file0.xlsm'. Is it possible it was moved, renamed, or deleted?\"\n\n\nThe file is in the directory and does have the correct name. (All three files are in the same directory as the workbook where the code lives.) Moreover: if I open the workbook \"file0.xlsm\", hit \"Save As\", save it with the same name, close it, and then run the VBA code, the error no longer appears.\n\nThe error appears regardless of (1) Whether the file is saved as .xlsx or .xlsm format, (2) Whether the file name is hard-coded or user-specified in a spreadsheet, and (3) the order in which I open the files.\n\nI tried moving the data from file0 to a new workbook (by copying worksheets from file0 to the new book one at a time), and then referencing opening the new book instead of file0 in my code. The error persists. \n\nI also checked for leading/trailing spaces in my file names, and followed the procedure on this page: https://github.com/OfficeDev/VBA-content/issues/637.\n\nCode for opening the books:\n\nIf Not IsWorkBookOpen(book1) Then\n Workbooks.Open Filename:=\"file0.xlsm\", UpdateLinks:=0, ReadOnly:=False, ignorereadonlyrecommended:=0, notify:=False, addtomru:=True\nEnd If\nIf Not IsWorkBookOpen(book2) Then\n Workbooks.Open Filename:=\"file1.xlsm\", UpdateLinks:=0, ReadOnly:=False, ignorereadonlyrecommended:=0, notify:=False, addtomru:=True\nEnd If\nIf Not IsWorkBookOpen(book3) Then\n Workbooks.Open Filename:=\"file2.xlsm\", UpdateLinks:=0, ReadOnly:=False, ignorereadonlyrecommended:=0, notify:=False, addtomru:=True\nEnd If\n\n\nNote: IsWorkBookOpen() is a function that checks if a book is already open.\n\nCode for IsWorkBookOpen():\n\nFunction IsWorkBookOpen(Name As String) As Boolean\n Dim xWb As Workbook\n On Error Resume Next\n Set xWb = Application.Workbooks.Item(Name)\n IsWorkBookOpen = (Not xWb Is Nothing)\nEnd Function"
] | [
"excel",
"vba"
] |
[
"if statements may seems to be flipped",
"I have an if statement where the app will put a modal view controller called LoginViewController on the condition that dataCenter.usernameData returns (null), otherwise, it will continue running code. I've set it up to where it does return (null). However, it seems that the statements have been flipped to where if dataCenter.usernameData is returned as (null), then it will not add LoginViewController and instead continue running the code from the Parent View Controller.\n\nHere is the code:\n\nAppDelegate *dataCenter = (AppDelegate *) [[UIApplication sharedApplication] delegate];\n\n if ([dataCenter.usernameData isEqual: @\"(null)\"]) {\n\n ViewController *viewControl = [self.storyboard instantiateViewControllerWithIdentifier:@\"LoginControllerNav\"];\n\n [[NSNotificationCenter defaultCenter] addObserver:self\n selector:@selector(didDismissSecondViewController)\n name:@\"SecondViewControllerDismissed\"\n object:nil];\n\n [self presentViewController:viewControl animated:NO completion:nil];\n\n NSLog(@\"No username.\");\n } else {\n\n NSLog(@\"Username; continue running code.\");\n }\n\n\nIs this supposed to happen? Or am I doing something wrong? A side question: say I release it in this format in the App Store. Will it flip back to the correct way or will it just stay like this? Any help is appreciated. Thank you."
] | [
"objective-c",
"if-statement"
] |
[
"_frontendCSRF cookie appears to be vulnerable to SQL injection attacks",
"I got this testing issue from my testing company that _frontendCSRF cookie can cause sql injection. They provide it for login page. My application is build over yii2. Here is the details information.\n\n\n The _frontendCSRF cookie appears to be vulnerable to SQL injection\n attacks. The payload ')and%20benchmark(20000000%2csha1(1))--%20 was\n submitted in the _frontendCSRF cookie. The application took 11004\n milliseconds to respond to the request, compared with 1681\n milliseconds for the original request, indicating that the injected\n SQL command caused a time delay.\n\n\nCookie: PHPFRONTSESSID=62ca0ebed7ad7d7c5e15a8c267f77551; current_shop=2; site_url=http%3A%2F%2F52.6.251.159%2F%7Edemoecom%2Fbuyold%2Ffrontend%2Fweb; blog_url=http%3A%2F%2F52.6.251.159%2F%7Edemoecom%2Fbuyold%2Fblog; is_buyold_login=0; _language=ba7c0570c541af8890cb020f80553258ee37070af083c555286d73a4165020c5a%3A2%3A%7Bi%3A0%3Bs%3A9%3A%22_language%22%3Bi%3A1%3Bs%3A2%3A%22au%22%3B%7D; _frontendCSRF=ae5e122353d27ce1288157fc2b42e65dacf96d5fc4c5d0d7f883c19215138691a%3A2%3A%7Bi%3A0%3Bs%3A13%3A%22_frontendCSRF%22%3Bi%3A1%3Bs%3A32%3A%22S8P_oYh_fNd-eODMV4NMrUqkebCWEKsL%22%3B%7D')and%20benchmark(20000000%2csha1(1))--%20; __atuvc=6%7C31; __atuvs=57a03a16ead33d80005\nConnection: keep-alive\nContent-Type: application/x-www-form-urlencoded\nContent-Length: 153\n\n\nRight now my project is in beta mode so it is in http. What would be the solution for it?\nCan i use _frontendCSRF in session or https will solve it ? Any help would be appreciated."
] | [
"php",
"mysql",
"cookies",
"yii2"
] |
[
"Else Statement in PHP",
"I'm learning PHP and wrote a simple translator. \n\n\r\n\r\n<!DOCTYPE html>\r\n<html lang=\"en\">\r\n<head>\r\n <meta charset=\"UTF-8\">\r\n <title>Translator</title>\r\n</head>\r\n<body>\r\n\r\n<form method=\"post\" action=\"\">\r\n<input type=\"string\" name=\"word\">\r\n<input type=\"submit\"> \r\n</form>\r\n\r\n<?php \r\n\r\nif (isset($_POST[\"word\"])) {\r\n $word = $_POST[\"word\"];\r\n echo $word . \" -> \";\r\n\r\nfunction translate($word){\r\n$dict = array('hello' => 'sawadee khap','thanks' => 'kap khum khap','sorry' => 'mai pen rai');\r\n foreach ($dict as $en => $th) {\r\n if ($word == $en) {\r\n echo $th;\r\n break;\r\n }\r\n }\r\n} \r\n\r\ntranslate($word);\r\n\r\n} else {\r\n echo \"enter a word\";\r\n}\r\n\r\n?>\r\n</body>\r\n</html>\r\n\r\n\r\n\n\nHow can I display the string 'not in dictionary' when I enter a word that isn't in the array? I'd also appreciate any feedback or suggestions on improving the code."
] | [
"php"
] |
[
"Laravel 5 is there a minimum/recommended php memory size, Required?",
"developing with Laravel 5 some times I encountered errors like \nAllowed memory size of .... bytes exhausted ... trying to allocate ...\n\nUsually I faced this kind of error along with long resultsets using Eloquent / Models or using Flysystem to upload large files\n(sometimes chunking is not enough to have it solved, Lrvl's components bug w/ memory leaks?)\n\nSometimes I solved it by performing the same actions but with a \"lower level\" functionalities. (i.e. avoid using Builder/Eloquent in favour of raw queries)\n\nBut definitely I end up solving it, by increasing php allowed memory limit.\n\nI'd like to know If there's a minimum suggested PHP config for memory_limit\n(default set is 128MB) in order to have enough room to use hi-level Laravel5 functionalities."
] | [
"php",
"laravel",
"memory-leaks",
"out-of-memory"
] |
[
"Can't send a message in chat app with Sockets?",
"i'm trying to send a message through my app, but i always get this error in heroku. Here's the error:\n\n\n\nand here is the api code: https://github.com/devslopes-learn/mac-chat-api\n\nthe snippet of the api code: \n\n client.on('newMessage', function(messageBody, userId, channelId, userName, userAvatar, userAvatarColor) {\n //Create message\n\n console.log(messageBody);\n\n let newMessage = new Message({\n messageBody: messageBody,\n userId: userId,\n channelId: channelId,\n userName: userName,\n userAvatar: userAvatar,\n userAvatarColor: userAvatarColor\n });\n //Save it to database\n newMessage.save(function(msg){\n //Send message to those connected in the room\n console.log('new message sent');\n\n io.emit(\"messageCreated\", newMessage.messageBody, newMessage.userId, newMessage.channelId, newMessage.userName, newMessage.userAvatar, newMessage.userAvatarColor, newMessage.id, newMessage.timeStamp);\n });\n });"
] | [
"javascript",
"node.js",
"sockets",
"websocket"
] |
[
"\\n or \\n in php echo not print",
"Possible Duplicate:\n Print newline in PHP in single quotes\n Difference between single quote and double quote string in php \n\n\n\n\n$unit1 = 'paragrahp1';\n$unit2 = 'paragrahp2';\necho '<p>' . $unit1 . '</p>\\n';\necho '<p>' . $unit2 . '</p>';\n\n\nThis is displaying (on view source):\n\n<p>paragraph1</p>\\n<p>paragraph2</p>\n\n\nbut isnt what I’m expecting, not printing the new line, what can be?"
] | [
"php",
"string"
] |
[
"top X results per day with sql in access",
"I am trying to get the top 2 results per day, where the \"top\" results are the rows with the highest \"MPR\". My table looks like this:\n\ndate symbol MPR\n8/7/2008 AA 0.98\n8/7/2008 AB 0.97\n8/7/2008 AC 0.96\n...\n8/7/2008 AZ 0.50\n8/8/2008 AA 0.88\n8/8/2008 AB 0.87\n8/8/2008 AC 0.86\n...\n8/8/2008 AZ 0.40\n...\nmany other days\n\n\nI would like the result set to be:\n\ndate symbol MPR\n8/7/2008 AA 0.98\n8/7/2008 AB 0.97\n8/8/2008 AA 0.88\n8/8/2008 AB 0.87\n\n\nI have tried using the TOP keyword, but this only gives me the top 2 rows, and I'm trying to do the top 2 rows per date.\n\nI am using Microsoft Access. I'd appreciate any help! :-)"
] | [
"sql",
"ms-access"
] |
[
"Optimal Database setup for online game",
"I'm a noob database / game dev (actually this will be my first game) i've been interested in making games for a while and so i decided to make a start on my strongest language, which is PHP.\n\nMy work with databases are very limited (basically down to search engine and some statistics collection), so i'm not entirely sure about the best way to setup such a database for my game.\n\nI was thinking along the lines of\n\ntable: users\n user_id, int, 10, auto_increment, null, primary\n username, text, 30, not null\n password, text, 128, not null (i plan to use my own encryption methods but open to suggestions)\n E-mail, text, 50, not null\n last_login, text, 30, not null (this could probably be date, not sure how to handle it yet)\n last_ip, text, 15, not null (tracking last logins for user)\n\n\nThen there will be another table holding game details of their accounts, I plan to have passive income streams and area ownerships and maybe even guilds and groups of players together and further along the lines with chat rooms and such but that's a different thread. There will also be unit construction timers and an open player markets.\n\nfor now i just want to get the basics out of the way \n\ntable: game_data (i know horrible i'll think of a better name later)\n user_id, primary, not null? (dunno about this)\n capital, int, 15\n income, int, 15\n\n\nas an example. How would you handle unit data would you put that into an separate table linking to the user_id?\n\nanyway any thoughts on this layout?\n\nEDIT: (extra game details for reference)\n\nThe game idea is similar to an eve online / dark throne cross, where you can own planets and entire solar systems which you draw income from and fight against other players for ownership of these systems / planets. you'll have a large range of ships that you can build entirely your self or you can buy / sell from an player run market as well as allowing real time pvp (as in players can jump to a solar system with their units and move them around in that solar system and sending them to fight. think of a RTS game such as red alert here).\n\ni got much more details on the game but i think you get the general idea. :)"
] | [
"php",
"mysql",
"multiplayer"
] |
[
"How to generate click event of anchor tag on enter key press in textbox",
"I am developing a JSP page where I have many anchor tags. So I have put a text box where I can search all the anchor tags on my page. I am using Javascript.\nNow what I need is when I text an anchor tag name in the text box and press Enter Key it should work as onclick of that particular anchor tag .\nI have tried the below code but it did not work for me:\n<script>\nfunction searchkeypress(e)\n{\nif(typeof e=='undefined'&& window.event){e=window.event;}\nif(e.keycode==13)\ndocument.getElementById("search").click();\n}\n</script>\n\n<input type="text" id="text1" onkeypress="searchkeypress(event)"/>\n<a id="search" href="#Ajax" onclick="index.jsp"/>"
] | [
"javascript",
"jsp",
"dom-events"
] |
[
"Using Google Sign-In on my website, how can I sign the user out?",
"I seem to have a working solution, but it's unbelievably complicated!\n\nFirst, I need to download some code: \n\n<script src=\"https://apis.google.com/js/platform.js\"></script>\n\n\nSecond and third, I need to download the auth2 module.\nAfter that I need to provide client_app_id to asynchronously get an auth object instance:\n\n gapi.load('auth2', function () {\n gapi.auth2.init({\n client_id: '__________.apps.googleusercontent.com'\n });\n });\n\n\nFourth, fuh, I can finally log out:\n\n gapi.auth2.getAuthInstance().signOut().then(function () {\n ...\n });\n\n\nAm I doing something wrong? Can this be done easier? I have found some docs here and here"
] | [
"oauth-2.0",
"google-signin",
"google-oauth",
"google-openid"
] |
[
"How to implements a method of a generic interface?",
"I have this interface:\n\npublic interface ParsableDTO<T> {\n public <T> T parse(ResultSet rs) throws SQLException;\n}\n\n\nImplemented in some kind of dto classes and this method in another class:\n\npublic <T extends ParsableDTO<T>> List<T> getParsableDTOs(String table, \n Class<T> dto_class) {\n List<T> rtn_lst = new ArrayList<T>();\n ResultSet rs = doQueryWithReturn(StringQueryComposer\n .createLikeSelectQuery(table, null, null, null, true));\n\n try {\n while(rs.next()) {\n rtn_lst.add(T.parse(rs)); //WRONG, CAN'T ACCESS TO parse(...) OF ParsableDTO<T>\n }\n rs.close();\n } catch (SQLException e) {\n System.err.println(\"Can't parse DTO from \" \n + table + \" at \" + dateformat.format(new Date()));\n System.err.println(\"\\nError on \" + e.getClass().getName() \n + \": \" + e.getMessage());\n e.printStackTrace();\n }\n\n return rtn_lst;\n}\n\n\nHow can I access the method parse(ResultSet rs) of the interface that can parse a specific T? Is there a working, different and/or better method to do that?"
] | [
"java",
"generics",
"methods",
"interface",
"implements"
] |
[
"How do I make my program wait if it returns overflow error?",
"So I'm trying to get data from an API which has a max call limit of 60/min. If I go over this it will return a response [429] too many requests.\n\nI thought maybe a better way was to keep requesting the API until I get a response [200] but I am unsure how to do this.\n\nimport requests\n\nr = requests.get(\"https://api.steampowered.com/IDOTA2Match_570/GetTopLiveGame/v1/?key=\" + key + \"&partner=0\")\n\nlivematches = json.loads(r.text)['game_list']\n\n\nSo usually it runs but if it returns anything other than a response [200], my program will fail and anyone who uses the website won't see anything."
] | [
"python",
"get",
"python-requests"
] |
[
"How can I cast or initialize ImageInputStream with InputStream?",
"I am developing an image scraping application. I am getting URL \n\nURL imageUrl = new URL(imageSource);\n\n\nThen I'm creating an InputStream with this URL:\n\nInputStream is = new URL(imageUrl.toString()).openStream();\n\n\nAfter this I wanna create an ImageInputStream to determine ImageIO readers. \n\nImageInputStream iis = ??????\n\n\nBut I couldn't initialize this. Can I implement URL or InputStream for ImageInputStream?"
] | [
"java",
"image",
"inputstream"
] |
[
"http to https AND //domain.com to www.domain.com AND subdomain.domain.com to subdomain.domain.com through htaccess",
"I'm hoping someone can help me, as for years I've always tried different approaches to redirecting and came across an interesting one on a project I'm working on.\nI need HTTP to redirect to HTTPS\nAND\nI need non-www to redirect to www but only if //domain.com without any subdomains\nAND\nI need subdomain.domain.com to still work so do not redirect the subdomain, i'm using wildcard (*) in apache to handle any subdomain as these will be detected in php with $_SERVER and handled for specific tasks.\nThis is what I have so far however the non-www (//domain.com) ends up in an endless redirect\nRewriteEngine On\nOptions -Indexes\n\nRewriteCond %{HTTPS} off [OR]\n# add www if not subdomain\nRewriteCond %{HTTP_HOST} ^[^.]+\\.[^.]+$\nRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n \nRewriteCond %{HTTPS} off [OR]\n# remove www if subdomain\nRewriteCond %{HTTP_HOST} ^www\\.([^.]+\\.[^.]+\\.[^.]+)$ [NC]\nRewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]\n\nApache virtual hosts two different files one for non SSL and one for SSL using lets encrypt\n<VirtualHost *:80>\n DocumentRoot /var/www/html/www.domain.com\n ServerName domain.com\n RewriteEngine on\n RewriteCond %{SERVER_NAME} =domain.com\n RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]\n</VirtualHost>\n\n<VirtualHost *:80>\n DocumentRoot /var/www/html/www.domain.com\n ServerName www.domain.com\n ServerAlias *.domain.com\n RewriteEngine on\n RewriteCond %{SERVER_NAME} =www.domain.com\n RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]\n</VirtualHost>\n\n<VirtualHost *:443>\n ServerName www.domain.com\n ServerAlias *.domain.com\n DocumentRoot /var/www/html/www.domain.com\n RewriteEngine on\n RewriteCond %{SERVER_NAME} =domain.com\n RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]\n\n Include /etc/letsencrypt/options-ssl-apache.conf\n SSLCertificateFile /etc/letsencrypt/live/domain.com/fullchain.pem\n SSLCertificateKeyFile /etc/letsencrypt/live/domain.com/privkey.pem\n</VirtualHost>\n\n<VirtualHost *:443>\n ServerName domain.com\n DocumentRoot /var/www/html/www.domain.com\n Include /etc/letsencrypt/options-ssl-apache.conf\n SSLCertificateFile /etc/letsencrypt/live/domain.com-0001/fullchain.pem\n SSLCertificateKeyFile /etc/letsencrypt/live/domain.com-0001/privkey.pem\n</VirtualHost>\n\nAll your help greatly appreciated!"
] | [
"php",
"regex",
"apache",
".htaccess",
"mod-rewrite"
] |
[
"How to get Kth largest element of a DoubleStream in java",
"What's the best way of getting the Kth largest element in a DoubleStream in java?\n\nI know we can do .max().getDouble() to get the largest element."
] | [
"java",
"java-8",
"java-stream"
] |
[
"Can not hide with JQuery \"View All Site Content\" for NT AUTHORITY\\authenticated visitors in SharePoint 2010",
"My option is to use JQuery to hide the \"View All Site Content\" link.\n\nThe result when I use this code is that the link will be hidden for Administrators but not hidden for visitors with NT AUTHORITY\\authenticated rights. How can I hide \"View All Site Content\" also for NT AUTHORITY\\authenticated users?\n\n$('#ctl00_PlaceHolderLeftNavBar_PlaceHolderQuickLaunchBottom_PlaceHolderQuickLaunchBottomV4_idNavLinkViewAllV4').hide();"
] | [
"jquery",
"sharepoint-2010"
] |
[
"D3js Tooltip not generating correctly",
"My bar chart is coming together pretty well. But there are still a couple of tweaks. I'm having issues getting the bar labels aligned correctly & still remain responsive for when extra data is added, etc.\n\nSo I decided that I'd get rid of those labels and do a Tooltip on mouse-over instead. But I'm finding that it's not populating the correct data. It only populates it for the Green bars (global). When I mouseover the blue (local) bar, I get the same tooltip, with the value from global. \n\nSeems that it's generating the tooltip for the entire set, rather than an individual bar.\n\nIssue #1 How do I get it to generate the correct data for individual bar, rather than the entire set?\n\nIssue #2 How do I have multiple values in the tooltip. You'll see from my Fiddle, that it is currently only specifying the CPC, and not generating data for the Search Volume. Can the tooltips only pull one piece of dynamic data? That doesn't seem right.\n\nJSFiddle is Here\n\nsets.append(\"rect\")\n .attr(\"class\",\"local\")\n.attr(\"width\", xScale.rangeBand()/2)\n.attr(\"y\", function(d) {\n return yScale(d.local);\n })\n .attr(\"x\", xScale.rangeBand()/2)\n .attr(\"height\", function(d){\n return h - yScale(d.local);\n })\n.attr(\"fill\", colors[0][1])\n.on(\"mouseover\", function(d,i) {\n //Get this bar's x/y values, then augment for the tooltip\n var xPosition = parseFloat(xScale(i) + xScale.rangeBand() );\n var yPosition = h / 2;\n //Update Tooltip Position & value\n d3.select(\"#tooltip\")\n .style(\"left\", xPosition + \"px\")\n .style(\"top\", yPosition + \"px\")\n .select(\"#cpcVal\")\n .text(d.cpc)\n .select(\"#volVal\")\n .text(d.local);\n d3.select(\"#tooltip\").classed(\"hidden\", false);\n})\n.on(\"mouseout\", function() {\n //Remove the tooltip\n d3.select(\"#tooltip\").classed(\"hidden\", true);\n})\n;\n\nsets.append(\"rect\")\n .attr(\"class\",\"global\")\n.attr(\"width\", xScale.rangeBand()/2)\n.attr(\"y\", function(d) {\n return yScale(d.global);\n})\n .attr(\"height\", function(d){\n return h - yScale(d.global);\n })\n.attr(\"fill\", colors[1][1])\n.on(\"mouseover\", function(d,i) {\n //Get this bar's x/y values, then augment for the tooltip\n var xPosition = parseFloat(xScale(i) + xScale.rangeBand() );\n var yPosition = h / 2;\n //Update Tooltip Position & value\n d3.select(\"#tooltip\")\n .style(\"left\", xPosition + \"px\")\n .style(\"top\", yPosition + \"px\")\n .select(\"#cpcVal\")\n .text(d.cpc)\n .select(\"#volVal\")\n .text(d.global);\n d3.select(\"#tooltip\").classed(\"hidden\", false);\n})\n.on(\"mouseout\", function() {\n //Remove the tooltip\n d3.select(\"#tooltip\").classed(\"hidden\", true);\n})\n;"
] | [
"javascript",
"d3.js",
"tooltip"
] |
[
"Calculate APR (annual percentage rate) Programmatically",
"I am trying to find a way to programmatically calculate APR based on\n\n\nTotal Loan Amount\nPayment Amount\nNumber of payments\nRepayment frequency\n\n\nThere is no need to take any fees into account. \n\nIt's ok to assume a fixed interest rate, and any remaining amounts can be rolled into the last payment.\n\nThe formula below is based on a credit agreement for a total amount of credit of €6000 repayable in 24 equal monthly instalments of €274.11. \n\n\n\n(The APR for the above example is 9.4%)\n\nI am looking for an algorithm in any programming language that I can adapt to C."
] | [
"objective-c",
"algorithm"
] |
[
"3D Basemap Adding 3D bars",
"Hi everyone I wanted to create one of the examples of Basemap in 3D in here, which its for 3d bars on geographical maps and their sample code is this:\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.basemap import Basemap\nfrom matplotlib.collections import PolyCollection\nimport numpy as np\n\nmap = Basemap(llcrnrlon=-20,llcrnrlat=0,urcrnrlon=15,urcrnrlat=50,)\n\nfig = plt.figure()\nax = Axes3D(fig)\n\nax.set_axis_off()\nax.azim = 270\nax.dist = 7\n\npolys = []\nfor polygon in map.landpolygons:\n polys.append(polygon.get_coords())\n\n\nlc = PolyCollection(polys, edgecolor='black',\n facecolor='#DDDDDD', closed=False)\n\nax.add_collection3d(lc)\nax.add_collection3d(map.drawcoastlines(linewidth=0.25))\nax.add_collection3d(map.drawcountries(linewidth=0.35))\n\nlons = np.array([-13.7, -10.8, -13.2, -96.8, -7.99, 7.5, -17.3, -3.7])\nlats = np.array([9.6, 6.3, 8.5, 32.7, 12.5, 8.9, 14.7, 40.39])\ncases = np.array([1971, 7069, 6073, 4, 6, 20, 1, 1])\ndeaths = np.array([1192, 2964, 1250, 1, 5, 8, 0, 0])\nplaces = np.array(['Guinea', 'Liberia', 'Sierra Leone','United States', 'Mali', 'Nigeria', 'Senegal', 'Spain'])\n\nx, y = map(lons, lats)\n\nax.bar3d(x, y, np.zeros(len(x)), 2, 2, deaths, color= 'r', alpha=0.8)\n\nplt.show()\n\nBut after I run that code I get this error:\nAttributeError: 'LineCollection' object has no attribute 'do_3d_projection'\nDoes anybody know what's the problem?"
] | [
"python",
"matplotlib-basemap"
] |
[
"Regex to discard an entire capture if it's immediately preceded by a specific character",
"Given the following text: \n\nsomerandomtext06251/750/somerandomtext/21399/10 79/20 8301\n\n\nhow do I extract 06251/750, 79/20, 8301 and ignore 21399/10 ?\n\nThe general rules:\n\n\nin a random string match every group of at least 2 digits followed by optional / and followed by another at least 2 digits; be greedy about the digits (take as much as possible)\nignore the complete match if it is immediately preceded by /\n\n\nI started with the following match pattern:\n\n (?<invnr>\\d{2,}/?\\d{2,})\n\n\nIn general, it works, but it has just one problem: it takes also 21399/10. So, I added a negative lookbehind:\n\n (?<!/)(?<invnr>\\d{2,}/?\\d{2,})\n\n\nNow it ignores the first digit of 21399/10 (because it is preceded by /), but still it captures all the following characters, that is 1399/10. But I need to skip 21399/10 entirely.\n\nHow do I make the lookbehind to make dropping entire match and skipping to the next one instead of skipping just one digit?"
] | [
".net",
"regex",
"regex-group",
"negative-lookbehind"
] |
[
"Determine whether a date falls on weekend in Angular/Javascript",
"Given a date in yyyy-mm-dd format, how can I determine whether a date falls in the weekend in Angular/Javascript?\n\n$scope.isWeekend= function(){ \n $scope.date = '2018-05-13'; \n /* if (day(date)=='saturday' || day(date)=='sunday') { */\n alert(\"\");\n /* } */\n}"
] | [
"javascript",
"angularjs",
"scope",
"momentjs",
"weekend"
] |
[
"file input does not update except in Chrome",
"I have a local program which writes a JSON object to a file so that a JavaScript can pick up its data and process it. The file is selected using an <input> object:\n\n<form id = \"getfiles\">\n <input type = \"file\" multiple id = \"files\" />\n</form>\n\n\nwith the following JS function setInterval to repeat every 300ms. However, when the file changes, only Google Chrome reloads the file and processes the new content; I have to manually reselect the file on the page in IE 10 and Firefox 20.\n\nfunction speakText() \n{\n var thefile = document.getElementById('files').files[0];\n var lastChanged = thefile.lastModifiedDate;\n var reader = new FileReader(); \n\n reader.onload = function(event)\n {\n var lcd = document.getElementById(\"last_change_date\");\n if (!lcd)\n {\n var spanLastChanged = document.createElement(\"span\");\n spanLastChanged.id = \"last_change_date\";\n spanLastChanged.innerText = lastChanged;\n console.log(lastChanged);\n document.body.appendChild(spanLastChanged);\n }\n else\n {\n // compare lastChanged with last_change_date\n var last_known_change = Date.parse(lcd.innerText);\n // var last_known_change = Date.parse(thefile.lastModifiedDate);\n if (last_known_change !== Date.parse(lastChanged))\n {\n console.log(\"Something is new since \" + lcd.innerText);\n var fileContent = event.target.result;\n var commands = JSON.parse(fileContent);\n handleJSON(fileContent);\n lcd.innerText = lastChanged;\n }\n }\n }\n reader.readAsText(thefile, \"UTF-8\"); \n}"
] | [
"javascript",
"google-chrome",
"firefox",
"setinterval"
] |
[
"getElementById problem",
"I call the following function with a mouseover event but it's not working. My id's are all correct & I have properly linked all my external scripts.\n\nfunction new2() {\nvar prevWin = document.GetElementById(\"recentlyaddedtip\");\nprevWin.style.visibility = \"visible\";\n}\n\n\nrecentlyaddedtip is set as hidden in the stylesheet (and it properly changes to visible when I change it manually.)"
] | [
"javascript"
] |
[
"Pandas apply method on a column only when conditions are met",
"I want to use df.apply to a DataFrame column.\nThe df represents hierarchical biological classifications.\nDataframe for biological data\nI want to show the relevant classification depending on if the data exists within the column.\nI have written a function that should do this:\ndef condition(data):\n for i in range(len(data)):\n if data.G[i] and data.Taxonomy[i]:\n return(data.G[i] + " " +data.Taxonomy[i])\n elif data.G[i] and not data.Taxonomy[i]:\n return(data.G[i])\n elif not data.G[i] and not data.Taxonomy[i]:\n return(data.F[i])\n elif data.O[i] and not data.G[i] and not data.Taxonomy[i]:\n return(data.O[i])\n elif data.C[i] and not data.O[i] and not data.G[i] and not data.Taxonomy[i]:\n return(data.C[i])\n elif data.P[i] and not data.O[i] and not data.G[i] and not data.Taxonomy[i]:\n return(data.P[i])\n elif data.k[i] and not data.P[i] and not data.O[i] and not data.G[i] and not data.Taxonomy[i]:\n return(data.k[i]) \n\nI have attempted to apply this function to the dataframe to output an additional column which shows the data after it has gone through condition():\ndata['name']=data.apply(lambda x: condition(data), axis = 1)\n\nI receive the output of\nOutput after df.apply\nWhere the outcome repeats itself instead of applying the function per row.\nHow can I apply this function so it gives the desired output?"
] | [
"python",
"pandas",
"dataframe"
] |
[
"Allocating memory for a char pointer that is part of a struct",
"im trying to read in a word from a user, then dynamically allocate memory for the word and store it in a struct array that contains a char *. i keep getting a implicit declaration of function âstrlenâ so i know im going wrong somewhere.\n\nstruct unit\n{\n char class_code[4];\n char *name;\n};\n\nchar buffer[101];\nstruct unit units[1000];\n\nscanf(\"%s\", buffer);\n\nunits[0].name = (char *) malloc(strlen(buffer)+1);\nstrcpy(units[0].name, buffer);"
] | [
"c",
"memory-management"
] |
[
"Getting difference in mouse movement using JavaScript",
"I'm wondering if there's a simple way to get the difference in mouse movement using JavaScript. \nWhat I mean by this is, if the user moves the cursor 5px to the right, a variable's value would be set to 5, and if the user moves the mouse to the starting location, the variable would be zero. This would also mean that if the user moved the cursor to the left of the starting position, it would result in a negative value. It would also be great to make another variable for the cursor's Y position. This would be done with event.clientX and event.clientY;\nThanks for any help :)"
] | [
"javascript",
"html"
] |
[
"ExtJS Form within a CardLayout",
"Whenever I add a form to a card layout, all the form items seem to disappear. I tested my layout here:\nhttp://tof2k.com/ext/formbuilder/\nwith this code and got the same result, (use show/edit JSON to try it or build one yourself)\nHow can I make the for fields visible?\n\n{\nxtype:\"panel\",\ntitle:\"Panel\",\nitems:[{\n layout:\"card\",\n title:\"CardLayout Container\",\n activeItem:\"0\",\n items:[{\n xtype:\"form\",\n title:\"Form\",\n items:[{\n xtype:\"textfield\",\n fieldLabel:\"Text\",\n name:\"textvalue\"\n },{\n xtype:\"textfield\",\n fieldLabel:\"Text\",\n name:\"textvalue\"\n }]\n }]\n }]\n}"
] | [
"extjs",
"extjs3"
] |
[
"jQuery nth element with custom markup",
"As shown here: http://jsfiddle.net/3sNbV/\n\n$('.box:nth-child(5n)').addClass('edge');\n\n\n.. the nth element is incorrect if you have any other html elements in there besides the one its looking for, although I've specifically given a classname.\n\nIs there a way to avoid this behaviour without changing the markup?\n\nThanks"
] | [
"jquery",
"css-selectors"
] |
[
"Subset a list of data.frames and return list of data.frames",
"I realise this question is quite similar to this one (amongst others) however I cannot seem to modify the solution(s) to fit my problem. Please mark as a duplicate or link to the existing answer if needed. Here is some example data modified slightly from the aforementioned question:\n\na=c(1,2,3,4,5,6)\nb=c(4,5,6,5,5,5)\nc=c(3,4,5,6,7,8)\nA=data.frame(a=a,b=b,c=c)\nB=data.frame(a=c,b=b,c=a)\nC=data.frame(a=b,b=c,c=a)\nl <- list(A, B, C)\n\n\nI would like to generate a list of dataframes that is a subset of the original dataframes (in l) that match a condition. For example I might like to return all values greater than or equal to 4 with lower values replaced by NA's so that my new list, subsetl looks as follows. (I don't care about keeping the NA's in the correct place in the dataframe.)\n\n> subsetl\n[[1]]\na b c\n1 NA 4 NA\n2 NA 5 4\n3 NA 6 5\n4 4 5 6\n5 5 5 7\n6 6 5 8\n\n[[2]]\na b c\n1 NA 4 NA\n2 4 5 NA\n3 5 6 NA\n4 6 5 4\n5 7 5 5\n6 8 5 6\n\n[[3]]\na b c\n1 4 NA NA\n2 5 4 NA\n6 5 NA\n4 5 6 4\n5 5 7 5\n6 5 8 6\n\n\nI hope my example is clear enough to understand but let me know if not. This is no doubt simple using lapply, sapply or the like but I cant get the syntax right when using lists and especially when a list of dataframes is the desired outcome."
] | [
"r",
"dataframe",
"subset"
] |
[
"Eden Php - Smtp, Custom Header - How to change 'From'-Field to custom Sender-Email-Address",
"This is about http://eden.openovate.com/api/eden/mail/smtp.php \n\npublic function send(array $headers = array())\n\nSends an email\n\nArguments\n\narray custom headers\n\nReturns array headers\n\n\nI understand that i have to provide an array of headers with this method to overwrite the default from header (equals by default to smtp server account address) to the \"real sender\" address (provided by the user filling the mail form)\n\nThe problem is: I cant find any documentation how to use it.\n\nThe question is: What is the correct way to provide this header. \n\n(Please provide a \"working code sample\" of send-method call with parameter)\n\nThank you ;-)"
] | [
"smtp",
"email-headers",
"eden"
] |
[
"How to access table created by join in JPA",
"I am creating an app where there are two entities\n\nusers\n\nchatrooms\n\n\nThere is a many to many relationship between users and chatrooms.\nI created a many to many relationship with a join table named users_chatrooms. The values are getting populated in the join table correctly when I wrote code for a user to join a chatroom.\nMy issue is that, I need an endpoint that can fetch all the users of a given chatroom. For this, I need the table created by the join (users_chatrooms) as part of Jpa. How to accomplish this in JPA ?\nUser class\npackage com.example.chat.models;\n\nimport javax.persistence.*;\nimport java.util.List;\n\n@Entity\n@Table(name="USERS")\npublic class User {\n @Id\n @Column(name="userid")\n private String username;\n\n @Column(name="pass")\n private String password;\n\n\n @ManyToMany(mappedBy = "users",fetch=FetchType.EAGER,cascade = CascadeType.ALL)\n List<Chatroom>rooms;\n\n public List<Chatroom> getRooms() {\n return rooms;\n }\n\n public void setRooms(List<Chatroom> rooms) {\n this.rooms = rooms;\n }\n\n\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getUsername() {\n return username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n}\n\nChatroom class\npackage com.example.chat.models;\n\nimport javax.persistence.*;\nimport java.util.List;\n@Entity\n@Table(name="Chatrooms")\npublic class Chatroom {\n @Id\n @Column(name="chatroomId")\n private String id;\n @Column(name="chatRoomName")\n private String name;\n @Column(name="chatroomDesc")\n private String description;\n\n @ManyToMany(fetch=FetchType.EAGER,cascade = CascadeType.ALL)\n @JoinTable(\n name = "users_chatrooms",\n joinColumns = @JoinColumn(name = "chatroomId"),\n inverseJoinColumns = @JoinColumn(name = "userid"))\n private List<User>users;\n\n public List<User> getUsers() {\n return users;\n }\n\n public void setUsers(List<User> users) {\n this.users = users;\n }\n\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n}"
] | [
"java",
"spring",
"spring-boot",
"jpa",
"spring-data-jpa"
] |
[
"Combining String and Integers in a single variable",
"I'm trying to combine them in PHP. But I get an integer output everytime.\n\nExample\nExpected Output:\nInput:\naabbbc\n\nOutput:\n2a3bc\n\nReality:\nOutput: 14\n\nThis is my code:\n\n $string = str_split($s);\n\n for($i=0;$i<count($string);$i++){\n $counter = substr_count($s,$string[$i]);\n $stringConverted += $counter . \"\" . $string[$i];\n }\n return $stringConverted;\n}"
] | [
"php"
] |
[
"How to return new records using JQuery Ajax",
"I'm creating a website element where users can contribute to a discussion. In doing so, the latest contributions need to appear at the top of the list at a regular short interval, using Ajax.\n\nWhile I know how to return the initial results, I'm not sure how to go about adding only the latest updates to the current list of items.\n\nHelp, anyone?\n\nthanks,\nGeoff"
] | [
"jquery",
"ajax"
] |
[
"badimageformatexception - Which assembly is problematic",
"I'm fighting with a BadImageFormatException:\n\nSystem.BadImageFormatException : Could not load file or assembly 'Bla.Bla.Bla, Version=0.0.0.18329, Culture=neutral, PublicKeyToken=null' or one of its dependencies.\n\n\nI'm fairly sure that the Bla.Bla.Bla assembly is correct (set as AnyCpu). It's dependancies are also correct (only Castle.Core, Castle.Windsor and Castle.WcfIntegration). However, when I run the NUnit tests for this project, I get the BadImageFormatException.\n\nIs there a way to find out what assembly is responsible for this exception?"
] | [
".net",
"nunit"
] |
[
"the form which remains null symfony",
"I set up a search form with a handmade Entity but the form does not transmit the info to the entity ... you have an idea to solve this problem?\n\nAlso it's symfony 4.4 and I've already checked the findWeeklyPlanningRs query in the repository and it works fine. \n\nthis is the entity:\n\n\n<?php\n\nnamespace App\\Entity ;\n\nclass FilterWeek\n{\n\n private $nbWeek ;\n\n\n public function getNbWeek(): ?int\n {\n return $this-> nbWeek;\n }\n\n public function setNbWeek(int $nbWeek): self\n {\n $this->$nbWeek = $nbWeek;\n\n return $this;\n }\n\n}\n\n\nthe Controller\n\n /**\n * @Route(\"/{id}/week\" , name=\"week\")\n */\n\n public function weeklyPlanning(Request $request , $id ) : Response\n {\n\n $em = $this->getDoctrine()->getManager();\n\n $week = new FilterWeek();\n\n $form = $this -> createForm(FilterWeekType::class , $week ) ;\n $form->handleRequest($request);\n\n\n\n\n\n $planning = $em -> getRepository(Chargement::class) -> findWeeklyPlanningRs($id , $week-> getNbWeek() ) ;\n\n $responsableSecteur = $em ->getRepository(ResponsableSecteur::class)->find($id) ;\n\n\n\n return $this -> render('Planing/ResponsableSecteurWeek.html.twig' , [\n 'responsable_secteur' => $responsableSecteur,\n 'chargements' => $planning ,\n 'form' => $form -> createView()\n ] );\n\n }\n\n\n\nthe form :\n\n\n<?php\n\nnamespace App\\Form;\n\nuse App\\Entity\\FilterWeek;\nuse Symfony\\Component\\Form\\AbstractType;\nuse Symfony\\Component\\Form\\FormBuilderInterface;\nuse Symfony\\Component\\OptionsResolver\\OptionsResolver;\nuse Symfony\\Component\\Form\\Extension\\Core\\Type\\IntegerType;\n\nclass FilterWeekType extends AbstractType\n{\n public function buildForm(FormBuilderInterface $builder, array $options)\n {\n $builder\n ->add('nbWeek' , IntegerType::class , [\n\n 'label' => 'numéro de la semaine' ,\n 'required' => false\n ])\n ;\n }\n\n public function configureOptions(OptionsResolver $resolver)\n {\n $resolver->setDefaults([\n 'data_class' => FilterWeek::class,\n 'method' => 'get',\n 'csrf_protection' => false,\n ]);\n }\n\n public function getBlockPrefix(){\n\n return '';\n }\n}\n\n\n\nthe view :\n\n{% extends 'base.html.twig' %}\n\n{% block body %}\n\n <div class=\"container\">\n\n <h3>Planning des chargements par Semaine</h3>\n\n <br><br>\n\n <div class=\"form-row\" >\n <div class=\"col-4\">\n {{ form_start(form) }}\n {{ form_row(form.nbWeek) }}\n <button class=\"btn color-br\" style=\"top : 5em;\" >Rechercher</button>\n\n {{ form_end(form) }}\n </div>"
] | [
"php",
"forms",
"symfony",
"symfony4",
"php-7"
] |
[
"UITableView-didSelectRowAtIndexPath Problems when call didSelectRowAtIndexPath",
"I have a UITableView with CustomCell, in my CustomCell I added UIImage,UILabel...\nBut, when I selected cell in row 1 and remove UIImage on it : [[cell.contentView viewWithTag:TAG_FOR_TOPIMAG]removeFromSuperview]; However, cell at index 7 was changed same cell 1."
] | [
"iphone",
"uitableview"
] |
[
"Mysql connection with python",
"this code runs without error but no records are added to the database\n\nmydb=sql.connect(host=\"localhost\",user=\"root\",passwd=\"\")\ncmd=mydb.cursor()\ncmd.execute(\"create database if not exists library\")\ncmd.execute(\"use library\")\ncmd.execute(\"create table if not exists class_12 (roll_no int(2) not null,name varchar(30) not null,book_issued varchar(50),book_no int(6) not null)\")\nc=input(\"do u want to edd entries in the book record? y/n : \")\nwhile c==\"y\":\n print(\"please supply the following details \")\n r=int(input(\"roll number of the student\"))\n n=str(input(\"enter the name of the student\"))\n bn=str(input(\"enter the book name\"))\n BN=int(input(\"Enter BOOK number : \"))\n inp=(\"insert into class_12(roll_no,name,book_issued,book_no) values(%s,%s,%s,%s)\")\n val=(r,n,bn,BN)\n cmd.execute(inp,val)\n cmd.execute(\"commit\")\n c=input(\"do u want to edd entries in the book record? y/n : \")```"
] | [
"mysql",
"python-3.x",
"mysql-connect"
] |
[
"Storyboard doesn't accept some sizes for UIView",
"I have made a view like this:\n\n\n\nTo make the divider lines, I am using UIViews with small heights.\n\nNow , the problem is that the storyboard doesn't accept some heights for my dividers. For instance, when I try to set the height to 0.8, it changes it to 0.67. or when I try to set it to 1.5, it changes it to 1.67 and so on. \n\nI have tried to set height constraints and also removing all of the constraints from the whole container but nothing changed.\n\nDoes anyone know what is the reason for this?"
] | [
"ios",
"swift",
"uiview",
"storyboard",
"size"
] |
[
"Array truncation with splice method",
"I need to delete occurrences of an element if it occurs more than n times.\n\nFor example, there is this array:\n\n[20,37,20,21]\n\n\nAnd the output should be:\n\n[20,37,21]\n\n\nI thought one way of solving this could be with the splice method\n\nFirst I sort the array it order to make it like this:\n\n[20,20,37,21]\n\n\nThen I check if the current element is not equal to the next and split the array into chunks, so it should look like:\n\n[20, 20],[37],[21]\n\n\nLater I can edit the chunk longer than 1 and join it all again. \n\nThis is what the code looks like in my head but didn't work in real life\n\nvar array = [20, 37, 20, 21];\nvar chunk = [];\nfor(i = 0; i < array.length; i++) {\n if(array[i] !== array[i + 1]) {\n var index = array.indexOf(array[i]);\n chunk.push = array.splice(0, index) // cut from zero to last duplicate element\n } else\n var index2 = a.indexOf(a[i]);\n chunk.push(a.splice(0, index));\n}\n\n\nwith this code the output is \n\n[[], [20, 20]]\n\n\nI think It's something in the 'else' but can't figure it out what to fix."
] | [
"javascript",
"arrays"
] |
[
"List of numbers into dimensional Array",
"I have the following problem:\nI have a .txt file form my professor, which contains different numbers.Every number is in another line. There is nothing else in this file.\nThose numbers represent coordinates, eg. first line = first x coord., second line = first y coord. and so on. We may not use LINQ.\n\nSo my question is: How can I transfer these numbers into an 2d-array like the following?\n\ncoordArray[0,0] = line1 of textfile (x1)\ncoordArray[0,1] = line2 (y1)\ncoordArray[1,0] = line3 (x2)\n\n\nI already tried the following without success:\n\n string path = @\"C:\\coords.txt\";\n int lines = (File.ReadAllLines(path).Count())/2;\n\n List<double> xy = new List<double>();\n using (StreamReader r = new StreamReader(path))\n {\n string coord;\n while ((coord = r.ReadLine()) != null)\n {\n xy.Add(double.Parse(coord));\n }\n }\n\n double[,] coordArray = new double[lines, 2];\n for(int i = 0; i<lines; i+=2)\n {\n for(int j = 0; j<lines; j++)\n {\n coordArray[j, 0] = xy[i];\n coordArray[j, 1] = xy[i + 1];\n }\n }"
] | [
"c#",
"arrays"
] |
[
"anti-forgery form field __RequestVerificationToken is not present after post",
"I've got my logoff link:\n\n<a id=\"lnkLogoff\" href=\"javascript:document.getElementById('logoutForm').submit()\"><i class=\"fa fa-lock\"></i> @Resources.LogOff</a>\n\n\nWhen link is pressed it submits my logoff form:\n\n<form method=\"post\" action=\"@Url.Action(\"Logoff\", \"Account\")\" id=\"logoutForm\">\n @Html.AntiForgeryToken()\n</form>\n\n\nThis works great 99.9% of the time. But I ran into an issue when I submit a form, it goes in to the controller and it returns the model back to the view displaying toaster messages on the result. Once it's returned there, all of my AntiFOrgeryTokens seem to be missing or invalid, or something.\n\n[HttpPost]\n [ValidateAntiForgeryToken]\n public PartialViewResult PersonUserOpen(UserPageModel model)\n {\n model.Function = DataFactory.SystemAccess.GetFunction(model.Function.Id);\n\n if (ModelState.IsValid && model.Roles.Any(a => a.IsGranted))\n {\n //This is valid, do stuff and add success message\n }\n else{\n //add Error messages to be displayed\n }\n\n return PartialView(model);\n}\n\n\nAfter displaying the view again with its messages, all of the form's anti forgery tokens are either missing or invalid, not sure. So when I post this view's form or click logoff to post the logoff form they don't work because it's missing the anti-forgery token.. What's up with this? This page is for updating user's passwords stored in UserManager, could this be related to the problem? In the HttpGet method of the controller I add the user being changed to the model:\n\nvar user = UserManager.FindById(person.ApplicationUserId);\n\n model.MembershipRoles = DataFactory.SystemAccess.GetMembershipRoles(user.Id);\n\n model.User = new UserViewModel\n {\n Id = user.Id,\n Email = user.Email,\n Username = user.UserName,\n Active = user.Active\n };"
] | [
"asp.net-mvc",
"antiforgerytoken"
] |
[
"XNA / Monogame Texture2D to to string",
"I want to store a small png image in a XML file and Load it back to Texture2D.\n\nThis is what I'm doing\n\nCode for saving\n\nI'm writing the data of the Texture2D with the BinaryWriter to a MemoryStream,\n\nthen converting the MemoryStream to an Array. I have to Convert the array to a Base64String because you can't save all characters\n\nin a XML file.\n\nThe string is saved in my XML file.\n\n public static string SaveTextureData(this Texture2D texture)\n {\n int width = texture.Width;\n int height = texture.Height;\n Color[] data = new Color[width * height];\n texture.GetData<Color>(data, 0, data.Length);\n\n MemoryStream streamOut = new MemoryStream();\n\n BinaryWriter writer = new BinaryWriter(streamOut);\n\n writer.Write(width);\n writer.Write(height);\n writer.Write(data.Length);\n\n for (int i = 0; i < data.Length; i++)\n {\n writer.Write(data[i].R);\n writer.Write(data[i].G);\n writer.Write(data[i].B);\n writer.Write(data[i].A);\n } \n\n return Convert.ToBase64String(streamOut.ToArray());\n }\n\n\nCode for Loading\n\nSame here.. I'm converting the Base64Str to an array and trying to read it.\n\nBut I cant read it back.\n\n public static Texture2D LoadTextureData(this string gfxdata, GraphicsDevice gfxdev)\n {\n byte[] arr = Convert.FromBase64String(gfxdata);\n\n MemoryStream input = new MemoryStream();\n\n BinaryWriter bw = new BinaryWriter(input);\n bw.Write(arr);\n\n using (BinaryReader reader = new BinaryReader(input))\n {\n var width = reader.ReadInt32();\n var height = reader.ReadInt32();\n var length = reader.ReadInt32();\n var data = new Color[length];\n\n for (int i = 0; i < data.Length; i++)\n {\n var r = reader.ReadByte();\n var g = reader.ReadByte();\n var b = reader.ReadByte();\n var a = reader.ReadByte();\n data[i] = new Color(r, g, b, a);\n }\n\n var texture = new Texture2D(gfxdev, width, height);\n texture.SetData<Color>(data, 0, data.Length);\n return texture;\n }\n }\n\n\nCould need some help here.\n\nGetting an exception in the reading method that the value couldnt read.\nin line \n\nvar width = reader.ReadInt32();"
] | [
"c#",
"xml",
"xna",
"monogame",
"texture2d"
] |
[
"Triggering Background task in UWP",
"I have set the ToastNotificationHistoryChangedTrigger for triggering background task, for monitoring the changes in the action centre. But it will trigger the back ground task if we remove the notifications in the action centre, but it will not triggering when we add a notifications in the action centre.\n\nIs there any way to monitor the notifications that are added to action centre ?"
] | [
"windows-store-apps",
"win-universal-app"
] |
[
"Writable .config file for all users in application directory?",
"I need to have a common application settings file and i need it to be editable by the application at runtime. \n\nI don't want to use the build in settings operation by putting \"User\" in settings scope because it gets saved in users local directory.\n\nOn the other hand i cant use the .config with \"Application\" as i cannot save into this file from within the application.\n\nOne might say \"Create your own save settings XML file its easy\"..Yes probably it is but i wonder what is the solution for a common writable config file with MS build in classes?"
] | [
"c#",
".net",
"app-config",
"configuration-files"
] |
[
"How to prevent ffmpeg transcode from low quality to high quality?",
"I use nginx to build livestream server and use exec command to run ffmpeg for transcode but I don't want transcode with input stream have quality like 640x360 and output stream transcode have quality 1280x720.\n\nThis is the command I use to transcode :\n\nexec /usr/bin/ffmpeg -i rtmp://localhost:1935/$app/$name -c:a aac -b:a 96k -c:v libx264 -vf \"scale='if(gte(iw,ih),-2,360)':'if(gte(iw,ih),360,-2)'\" -f flv rtmp://localhost:1935/360p/$name;\n\n\nThe result I want is if input stream have quality 1280x720 or 640x360 then transcode go normal but if input stream have quality 160x120 then don't transcode\n\nThanks in advance."
] | [
"nginx",
"ffmpeg"
] |
[
"Test Web application on iOS Simulator",
"I am trying to optimize my website for iPad. Could you please guide me on the best approach:\n\n\nIn terms of whether I should separate desktop/ipad just by CSS or redirect to an entirely different domain (e.g. mysite.com/ipad)\nHow do I test on iPad simulator? Should I use XCode for development?\n\n\nPlease help me with some good online tutorials. Thank you."
] | [
"javascript",
"html",
"ios",
"ipad"
] |
[
"Why pointers can't be used to index arrays?",
"I am trying to change value of character array components using a pointer. But I am not able to do so. Is there a fundamental difference between declaring arrays using the two different methods i.e. char A[] and char *A?\n\nI tried accessing arrays using A[0] and it worked. But I am not able to change values of the array components.\n\n{\n char *A = \"ab\";\n printf(\"%c\\n\", A[0]); //Works. I am able to access A[0]\n A[0] = 'c'; //Segmentation fault. I am not able to edit A[0]\n printf(\"%c\\n\", A[0]);\n}\n\n\nExpected output: \n\na\nc\n\n\nActual output:\n\na\nSegmentation fault"
] | [
"c",
"arrays",
"pointers"
] |
[
"Robot Frameworks - Click Element step passes, does not trigger action",
"I am having an issue, where I need to click on an element that opens up a menu. The click element step is successful; however the expected action is not triggered. I have added a Sleep statement, Wait Until Element Is Visible, and Set Selenium Speed to 1s. On the Log.html page I see the screen capture where the element I attempt to click is visible. The menu that I am trying to open is inside an iframe.\nAny help would be greatly appreciated.\n\n`\n*** Test Cases ***\nAccess Page\n Set Selenium Timeout 60\n Check Web Tier Enabled\n Sleep 30\n Capture Page Screenshot\n\nOpen Widget\n Click Element ${App_Components}\n Click Element ${Widget_List}\n Sleep 2\n Select Frame ${iFrame}\n Sleep 5\n Capture Page Screenshot\n\nOpen Menu\n Wait Until Element Is Visible ${Menu}\n Focus ${Menu}\n Mouse Over ${Menu}\n Sleep 5\n Click Element ${Menu} <--- this step is successful, but does not triger action\n Sleep 5\n Capture Page Screenshot\n`"
] | [
"frameworks",
"selenium2library"
] |
[
"How to convert obfuscated jar file into respective Windows / Linux / Mac native code?",
"I know a good hacker can obtain the source code of my Java files but I want to at least make it difficult for any one else to do so.\n\nI can use ProGuard to obfuscate my jar file and the next step is to convert the jar file into Windows exe, Ubuntu bin?, Mac Os ...\n\nWhat are the free software to do so?"
] | [
"java",
"jar",
"executable-jar"
] |
[
"Make new object with reflection?",
"I'm not sure if this is possible and after lengthy research I haven't found something conclusive. \n\nI am trying to dynamically create a new object (itself a new Type) from a dictionary. So say I have key and value that key and value will become a property that returns the value. Something that I can use like this:\n\nSample code\n\npublic T getObject(Dictionary<string, string> myDict)\n{\n // make a new object type with the keys and values of the dictionary. \n // sample values in dictionary:\n // id : 112345\n // name: \"greg\"\n // gender: \"m\"\n // Eventually also make the interface?\n}\n\n// Somewhere else:\nvar myNewObject = helper.getObject();\n// what is expected here is that when I type myNewObject. \n// I get id, name, gender as suggestions\nint id = myNewObject.Id;\n\n\nWhat is important for me is to get intellisense out of it. So I can type object. and suggestions with all the keys will come out. This way I don't need to know the dictionary in advance in order to access the values (or else I would simply use the dictionary).\n\nI have looked into Clay but it isn't clear to me how to use it to get intellisense as I want it. I also found this post about it.\n\nAdditionally I checked ImpromptuInterface but for both the documentation is poor or I can't figure it out. \n\nIf this is possible with Clay (it sure seems like it) how could I do it so It can work as a library on other projects that won't reference Clay?\n\nIf something is unclear or this is a duplicate don't hesitate to comment."
] | [
"c#",
"dynamic",
"intellisense",
"impromptu-interface",
"clay"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.