id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23536700
The most primitive way would be to create the repositories in these helper methods, then destroy them (using clauses), and there are obvious downsides to that, and it's against DRY. I also see examples of people registering these repositories as services, and use them that way. Please take thread safety into consideration. What are the expert opinions on this? Any example would be much appreciated. PS. I'm a senior level Java guy but almost entry level on C#, so any java-related comparison would be great too. A: The 'correct' way to register and retrieve Repositories is with a DI Container (I recommend Autofac builder.RegisterType<MyRepository>().AsImplementedInterfaces().InstancePerLifetimeScope(); InstancePerLifeTimeScope means it's thread scoped so only one instance per thread. Every object needing the repository will have the repository interface as the constructor dependency. For some services, the repository can be a method argument. The repository will use a (micro)ORM to 'talk' with the database. There are some cases where you need data or even some objects which can be retrieved directly from the db. In that case you have a service and not a repository, although both implementations (not interfaces) belong in the DAL. I'm assuming that all the services and repositories are passed as abstractions, so every object needing a service or repository will know only about a IService or IRepository. The DI Container will inject the concrete types, the client objects don't need to know about those.
doc_23536701
Div looks like that: 1) <div>Text text text text <input> text text <input> text</div> 2) <div>text Text <input> text <input> text text Text</div> Is it possible to get whole text including input values from a div (with id 'body' in my case)? jQuery code: var body = data.body.replace(/\.\.\./g, "<input class='bodyy' type='text' size='2' />"); $("#body").html(body); Fiddle: https://jsfiddle.net/uepf87fc/ A: You can parse it yourself with a function, here's an example: function getTextWithInputValues(id) { var element = document.getElementById(id); if (!element) { return null; } var elementText = element.innerHTML; // Get the entire text from your element var elementInputs = element.getElementsByTagName('input'); // fetch all inputs from your element // replace all input fields with their respective values Object.getOwnPropertyNames(elementInputs).forEach( (input) => { var inputText = elementInputs[input].outerHTML; if (elementText.search(inputText) > 0) { elementText = elementText.replace(inputText, elementInputs[input].value); } } ); return elementText; } You can test it right here by opening a console, paste this code in, then type in something in the search box on the top of the page (don't click search, just type in something), then when you call the function in the console like getTextWithInputValues('search') it will output something like <svg ......</svg> your-text-here <button .....</button> Hope this helps. A: Even though you asked for REGEX, I don't believe it is by any means needed. This will return the data in an array. With the first index being the body text, and each input field value thereafter. var values = []; values.push($('#body').text()); var inputs = $('#body input'); for(var i = 0; i < $(inputs).length; i++) { var currentElement = $(inputs)[i]; values.push($(currentElement).val()); } console.log(values);
doc_23536702
The response is mapped to an object like this (simplified): public readonly Stream Response; public readonly string Etag; private MyObject(Stream response, string etag) { this.Response = response; this.Etag = etag; } Since the object also contains the response stream I face the same issue here. How do I cache this? A: A Stream is a pipe, not a bucket. If you need to store it, you must first get the actual contents. For example, you could read it all into a byte[]. For example: using(var ms = new MemoryStream()) { response.CopyTo(ms); byte[] payload = ms.ToArray(); } You can store the byte[] trivially. Then if you want a Stream later, you can use new MemoryStream(payload). A: Can you create a custom class that contains a byte array for storing the data and another field with HttpWebRequest.Headers for the headers? Then cache that.
doc_23536703
/** * @SWG\Get(path="/articles", * tags={"Article"}, * summary="Get all Articles", * description="Show list of Articles", * operationId="all", * produces={"application/json"}, * @SWG\Parameter( * name="columns", * in="query", * description="get specific columns", * required=false, * type="array", * collectionFormat="multi", * @SWG\Items( * type="string", * @SWG\Property(property="name", type="string"), * @SWG\Property(property="description", type="string"), * @SWG\Property(property="author", type="string"), * @SWG\Property(property="created_at", type="string"), * @SWG\Property(property="updated_at)", type="string") * ) * ), * @SWG\Response(response="200"), * @SWG\Response(response=500) * ), * ) */
doc_23536704
function begin() { mysql_query("BEGIN"); } function commit() { mysql_query("COMMIT"); } function rollback() { mysql_query("ROLLBACK"); } begin(); mysql_query("TRUNCATE TABLE table_name"); if(mysql_query("Any bad insert query")) { commit(); } else { rollback(); } A: TRUNCATE TABLE causes implicit commit (i.e. it can't be rolled back). Use DELETE instead.
doc_23536705
On a windows phone it does nothing, and on android it gets caught in what seems like a loop as just alerts all the time. is there a better way to do this? Maybe with jquery (best option), if not better javascript solution? function doOnOrientationChange () { switch (window.orientation) { case -90: case 90: alert('landscape'); break; default: alert('portrait'); break; } } window.addEventListener('orientationchange', doOnOrientationChange); A: Orientation is subject to support and device type. Here is a very simple crude method you could experiment with that would be widely supported: function doOnOrientationChange () { let landscape = ( document.body.clientWidth > document.body.clientHeight ); alert( landscape ? 'landscape' : 'portrait' ) } window.addEventListener('resize', doOnOrientationChange); You could add an offset value to change the orientation result to your liking, for example you might want to clamp landscape view on certain screen resolutions that are more square.
doc_23536706
I know i need the quanitity too, but i dont know exactly the code. With this code it doesnt work. $array = unserialize($_SESSION['__vm']['vmcart']); //read the cart session $products = $array->products; //list the products if (array_key_exists('53', $products)) { //if productID 53 then $cart = VirtueMartCart::getCart(); $quantityPost= 1; //set quantity on 1 $virtuemart_product_id = 1; //set product id on 1 $cart->add(array(1)); //add into cart product with id 1 //$tmpProduct = $this->getProduct((int) $virtuemart_product_id,$quantityPost); //? echo "Article added!"; } //echo Message else { echo "Nothing added!"; } //echo Message A: The exact way of adding item to the Cart is like follows its an ajax call function . var data = "quantity[]="+qty+"&virtuemart_product_id[]="+pid //data = encodeURIComponent(data); jQuery.ajax({ type: "GET", dataType: 'json', url: "index.php?option=com_virtuemart&nosef=1&view=cart&task=addJS", data: data, success: function(data) { alert(data); } }); If you want to do it from php section go to the cart controller file and check function addJS then pass the corresponding param to that function. Hope this may help you.. A: Please use the VirtueMart API for correct cart handling. http://forum.virtuemart.net/index.php?topic=125870.msg431290#msg431290 In short, VirtueMart uses by default a call done with jQuery.getJSON which is a shorthand for an Ajax function. So all this above is not necessary. In doubt it is also unsecure. You should use the VM API to retrieve and store the cart object.
doc_23536707
type Obj = Readonly<{ x: string, y: number }> const obj = { x: 'abc', y: 123 } type TypeOfX = Obj['x']; // this works fine and returns string type TypeOfY = Obj['y']; // this works fine and returns number type Property = keyof Obj; const property: Property = 'x'; // error here type TypeOfObjProperty = Obj[property]; The errors are: Type 'any' cannot be used as an index type.(2538) 'property' refers to a value, but is being used as a type here. Did you mean 'typeof property'?(2749) Exported type alias 'TypeOfObjProperty' has or is using private name 'property'.(4081) A: While Obj[property] only works as a type when property is a type, you can use generics and extends to simulate this, at least on the function level: type Obj = Readonly<{ x: string, y: number }> function f<Property extends keyof Obj, TypeOfObjProperty extends Obj[Property]> (prop: Property, value: TypeOfObjProperty) { // TypeOfObjProperty is the type Obj[prop] } Playground link Depending on what you're doing, this may give you the type TypeOfObjProperty that you need.
doc_23536708
I have tried: *var textConvert = $('#editor').html($('textarea').html().replace(/\n/g, "<br />")); However, this solution does not work. It created an object, but it was a huge mess. The Javascript loads the HTML file into the div fine as text. However, I want to be able to retrieve the html after the user edits the contents of the div. Code: <div class="center">          <div id="editor" contenteditable></div>          <textarea name="ticketDesc" id="editorCopy" required="required" style="display:none;"></textarea> </div> <script type="text/javascript">         $('#select_section').change(function() {             var $option = $(this).find('option:selected');             var value = $option.val();             var text = $option.text();             if(value == 1){                 $("#editor").load("1.html");             }             if(value == 2){                 $("#editor").load("2.html");             }             if(value == 3){                 $("#editor").load("3.html");             }             if(value == 4){                 $("#editor").load("4.html");             }                                }); </script> A: I 'm a little confused about the purpose of the textarea in the context of your question. If you load the HTML into the contenteditable div, you can edit the contents there and then just save down the innerHTML of that same div. const d = document d.querySelector('button').onclick = e => { const storedHTML = d.getElementById('t').innerHTML console.log(storedHTML) } <div id="t" contenteditable> <h1>This is a header</h1> <p>This is paragraph copy</p> </div> <button>Export</button>
doc_23536709
orders=# \dS customer Table "public.customer" Column | Type | Modifiers ---------------+-------------------+-------------------------------------------------- id | integer | not null default nextval('cst_id_seq'::regclass) name | character varying | not null (...) Should I directly query some metadata / catalogue table instead to obtain that bit of information? A: Answering my own question ... Yeap, just like millimoose suggested, it can't be done with DdlUtils and you have to query the information_schema.columns table: public String getPostgreSQLSequenceForColumn(String database, String table, String column) { try { Statement stmt = connection.createStatement(); String sql="select column_default from information_schema.columns where "+ "table_catalog='"+database+"' and " + "table_schema='public' and " + "table_name='"+table+"' and " + "column_name='"+column+"'"; ResultSet rs = stmt.executeQuery(sql); rs.next(); String sequenceName = rs.getString(1); panicIf(rs.next()); return sequenceName; } catch (Exception e) { throw new ExceptionAdapter(e); } }
doc_23536710
I am instantiating a number of global objects (classes) in Workbook_Open() and trying to write wrapper functions for these classes to be called as UDFs in the various worksheets. If any of these functions fail with an un-trapped error all of these global objects are set to nothing. Why is this happening, as I would have thought maybe only the global object I was manipulating would be affected not all of them, and is there any other solution other than closing the workbook and reopening to re-establish them for further debugging? The instantiation is simply Private Sub Workbook_Open() Dim i as Integer For i = 0 to nStreams Set gStream(i) = New CStream Next i End Sub A: You can split your "set globals" code out from the Workbook_Open event: Private Sub Workbook_Open() SetGlobals End Sub 'in a regular module Public Sub SetGlobals() Dim i as Integer For i = 0 to nStreams Set gStream(i) = New CStream Next i End sub
doc_23536711
Here is my Controller. using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using quotingDojo.Models; namespace quotingDojo.Controllers { public class HomeController : Controller { // GET: /Home/ [HttpGet] [Route("")] public IActionResult Index() { return View(); } [HttpPost] [Route("quotes")] public IActionResult Quotes(Home model) { if(!ModelState.IsValid) { return View(); } //continue your code to save return RedirectToAction("Index"); } } } Here is my Index.cshtml @model quotingDojo.Models.Home <h1>Welcome to the Quoting Dojo</h1> @using(Html.BeginForm("Quotes","Home")) { <p>@Html.ValidationSummary()</p> <p> <label>Your Name</label> @Html.TextBoxFor(s=>s.Name) @Html.ValidationMessageFor(s => s.Name) </p> <p> <label>Your Quote</label> @Html.TextAreaFor(d=>d.Quote) </p> <input type="submit" name="submit" value="Add my quote!"/> } <form action="quotes" method="get"> <input type="submit" name="submit" value="Skip to quotes!"/> </form> Here is my Quotes.cshtml where the error messages currently show up. <h1>Test</h1> <p>@Html.ValidationSummary()</p> Here is my models page using System.ComponentModel.DataAnnotations; namespace quotingDojo.Models { public class Home { [Required(ErrorMessage ="Please enter your name")] [DataType(DataType.Text)] [MinLength(3)] public string Name {get; set;} [Required] [MinLength(5)] public string Quote{get; set;} } } A: Your issue is here: return View(); That will return a view named "Quotes" since your action method is named Quotes (this is MVC convention). You also do not pass a model to it so even if the view existed, it will not know of the errors. Two ways to fix your issue: 1. You have to pass the model to your Index view so you need to explicitly return the Index view. if(!ModelState.IsValid) { return View("Index", model); } 2. I personally prefer this method. Name your first action which serves the original form the same as the one your are posting to and then you can do this (note: you will also need to rename the view): // GET: /Home/ [HttpGet] [Route( "" )] public IActionResult Quotes() { return View(); } [HttpPost] [Route( "quotes" )] public IActionResult Quotes(Home model) { if( !ModelState.IsValid ) { return View(model); } //continue your code to save return RedirectToAction( "Index" ); } This way both of them return the view named Quotes so you do not have to explicitly mention it. A: The standard practice is, If model state is not valid, you return the same view (which user submitted) where you will show the validation error messages. You just need to change your Quotes action method to Index action method. [HttpPost] [Route("quotes")] public IActionResult Index(Home model) { if (!ModelState.IsValid) return View(); // to do :continue saving } Make sure to update your form to post to this action. Not sure why you want to redirect to another page where you want to show the errros. If you absolutely want to show the error messages in another view which was loaded via RedirectToAction method call (hence a totally new GET call), You need to use TempData to transfer the errors. public ActionResult Quotes(Home model) { if (!ModelState.IsValid) { List<string> errors = new List<string>(); foreach (var modelStateVal in ViewData.ModelState.Values) { foreach (var error in modelStateVal.Errors) { errors.Add(error.ErrorMessage); } } TempData["errors"] = errors; return RedirectToAction("Index"); } //continue your code to save } And in your index view, @if (TempData["errors"] != null) { var errors = (List<string>) TempData["errors"]; foreach (var error in errors) { <span class="alert warning">@error</span> } }
doc_23536712
yearly_avg=df2.groupby(years).mean() yearly_sum=df2.groupby(years).sum() yearly_MAX=df2.groupby(years).max() yearly_MIN=df2.groupby(years).min() I need to calculate averages, max and min numbers based on the water year where October 1st is the first day of a year. As an explanation of "water year": https://en.wikipedia.org/wiki/Water_year Here is my sample file stored here: https://drive.google.com/file/d/1AYi9vp3_DPXHoCPB_YkMQp68FvC_INrV/view?usp=sharing How can I do that? Thanks. A: Just set the year to start on October instead of January. I am just happy your columns were already datetime types, this made it easier! df = pd.read_excel('sample_water_year.xlsx') df['# YEAR'] = df.Dates.dt.to_period('A-Sep') #year ends on sep Note that you will have to subtract 1 as it does not change the initial year value set. df['# YEAR'] = df['# YEAR'] - 1 Then simply find the summary statistics: yearly_avg = df.groupby('# YEAR').mean() yearly_sum = df.groupby('# YEAR').sum() yearly_MAX = df.groupby('# YEAR').max() yearly_MIN = df.groupby('# YEAR').min() Hopefully this helps!
doc_23536713
A: Because Reference Transactions effectively tokenize the credit card data for storage and later use it is considered a PCI compliant solution. A: Yes, you are liable to PCI compliance. See the PCI FAQ for details: Q: To whom does PCI apply? A: PCI applies to ALL organizations or merchants, regardless of size or number of transactions, that accepts, transmits or stores any cardholder data. Said another way, if any customer of that organization ever pays the merchant directly using a credit card or debit card, then the PCI DSS requirements apply. Q: What is defined as ‘cardholder data’? A: Cardholder data is any personally identifiable data associated with a cardholder. This could be an account number, expiration date, name, address, social security number, etc. All personally identifiable information associated with the cardholder that is stored, processed, or transmitted is also considered cardholder data. Your site accepts credit card data that is transmitted to PayPal. You can read about how to be PCI compliant here: https://www.paypal.com/pcicompliance
doc_23536714
The template: <template name="home"> {{> quickForm collection="Posts" id="insertPostForm" type="insert"}} </template> The Route (iron:router) : Router.route('/', { name: "home", data: function () { return { posts: Posts.find(); }; }, waitOn: function () { return Meteor.subscribe("allPostHeaders"); } }); And I published the "allPostHeaders" : Meteor.publish("allPostHeaders", function(){ return Posts.find({}, { fields: {content: 0} }); }); So in Meteor I installed iron:router, aldeed:collection2 and aldeed:autoform and also install with npm simpl-schema. So when I launch my app the following exception appear.. Exception in template helper: quickFormContext@http://localhost:3000/packages/aldeed_autoform.js I found that post but I don't forget my quote.. so someone could help me to find what I missed? A: I solved it. The problem was due to the installation. With the autoform 6+ (the recent version of autoform) we couldn't install aldeed:collection2 but aldeed:collection2-core for installing separately simple-schema.
doc_23536715
According to show processlist; 99% of the time is spent on Creating sort index. If I greatly increase the number of ids in the menu_id in (...) list, the query takes 10-30 minutes. Unfortunately, I cannot copy/paste text from the database server to this terminal, so tabular output below is abbreviated. Query info: SELECT COUNT(DISTINCT user_id) AS count_user_id, org, category FROM menu_views WHERE menu_id in ( ...about 1300 ids... ) GROUP BY org, category; explain; | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | 1 | SIMPLE | menu_views | range | i_menu_view_menu_id,tyler_group,tyler_user_group,tyler_user_menu_group,tyler_menu_group | i_menu_views_menu_id | 5 | NULL | 7914 | Using index condition; Using filesort | Output: | count_user_id | org | category | |--------------------------------| | 13000 | foo | pizza | | 1 | bar | candy | | 90 | baz | cheese | | 80 | gaz | soda | | 150 | urk | pizza | | ... etc (86 rows) ... | |--------------------------------| Background info: describe menu_views; | Field | Type | Null | Key | Default | |------------------------------------------------| | id | int(11) | NO | PRI | NULL | | menu_id | int(11) | YES | MUL | NULL | | user_id | int(11) | YES | MUL | NULL | | category | varchar(255) | NO | | UNKNOWN | | org | varchar(255) | NO | MUL | UNKNOWN | |------------------------------------------------| show index from menu_views; | Key_name | Seq_in_index | Column_name | |-----------------------------------------------------| | PRIMARY | 1 | id | | i_menu_views_menu_id | 1 | menu_id | | tyler_group | 1 | org | | tyler_group | 2 | category | | tyler_user_group | 1 | user_id | | tyler_user_group | 2 | org | | tyler_user_group | 3 | category | | tyler_user_menu_group | 1 | user_id | | tyler_user_menu_group | 2 | menu_id | | tyler_user_menu_group | 3 | org | | tyler_user_menu_group | 4 | category | | tyler_menu_group | 1 | menu_id | | tyler_menu_group | 2 | org | | tyler_menu_group | 3 | category | |-----------------------------------------------------| There are other indexes on the table, but these are the ones that appear via EXPLAIN. I added the tyler_* ones to try to force a loose index scan, but it's not helping. The org and category fields properly belong on users, but I denormalized them in hopes that a non-JOIN query would be faster. However, I haven't seen any performance improvement. Full disclosure: I am using several variants of this query, all of which are slow. This is the simplest variant. Others include a WHERE created_at BETWEEN ('X' and 'Y') and GROUP BY year/month/week/day(created_at), category. A: I seem to finally be on the right track, after staring at lots of other people's code and blog posts. I realized that I am never going to achieve a loose index scan because of my use of COUNT and a GROUP BY. It turned out that the truly slow part is the COUNT(DISTINCT user_id). I can run the exact same query with COUNT(user_id) and receive results in two seconds. Much faster, but the wrong data for my purposes. My current optimized version, using a subquery, is: SELECT COUNT(user_id) AS count_user_id, org, category FROM ( SELECT user_id, org, category FROM menu_views WHERE menu_id IN ( ... lots of ids ... ) GROUP BY user_id, org, category ) AS groupings GROUP BY org, category; I think I still need to play with indexes and the like, but this runs in 20% of the time of the original query. A: Give these a try: INDEX(user_id, org, category) -- covering index for either of your queries. INDEX(created_at, category) -- for the additional example The output implies that it had to touch over 13K rows. With the above index, it can do all the work in the index, without having to reach over to the data. (Please provide SHOW CREATE TABLE, it is more descriptive than DESCRIBE.) With 47M rows, you should consider 'normalizing' org and category -- I assume there are a lot of repeats in those fields? I can't tell whether our queries are I/O-bound, but this would decrease the likelihood of such.
doc_23536716
c_id (int) name (varchar) table2 - account_data a_id (int) c_id (int) -> use customer_data.c_id plan_id (int) table3 - game_data g_id (int) sort (int) a_id (int) -> use account_data.a_id game_name (var) I using sub-query to select the game_data from account_data. like that: SELECT `a_id`,`c_id`,`plan_id`, (SELECT `game_name` FROM `game_data` WHERE `a_id` = a.`a_id` ORDER BY `sort` ASC LIMIT 1) as main_game FROM `accoubt_data` AS a WHERE `a_id` > 0 ORDER BY `id` DESC this sql is work for select game_data from account_data But I can't using it to select game_data from customer_data How can I do something? customer_data +----------------------+ | c_id | name | +----------------------+ | 1001 | Joe | | 1002 | John | | 1003 | David | +----------------------+ account_data +-------------------------------------+ | a_id | cid | plan_id | +-------------------------------------+ | 6015 | 1002 | 34 | | 6028 | 1003 | 1 | | 6088 | 1001 | 9 | +-------------------------------------+ game_data +--------------------------------------+ | g_id | game_name | a_id | +--------------------------------------+ | 8011 | GTA5 | 6015 | | 8023 | WWE2016 | 6028 | | 8088 | FIFA16 | 6088 | | 8095 | FIFA17 | 6088 | | 8086 | FIFA15 | 6088 | +--------------------------------------+ this is base select I need get this data from customer_data.c_id +--------------------------------------+ | c_id | name | frist_game | +--------------------------------------+ | 1001 | Joe | FIFA15 | | 1002 | John | GTA5 | | 1003 | David | WWE2016 | +--------------------------------------+ c_id > a_id > g_id ORDER BY sort ASC A: Try with join: SELECT c.`c_id`,c.name, (SELECT `game_name` FROM `game_data` WHERE `a_id` = a.`a_id` ORDER BY `sort` ASC LIMIT 1) as first_game FROM `accoubt_data` a JOIN customer_data c ON(a.c_id = c.c_id) WHERE a.`a_id` > 0 ORDER BY a.`id` DESC A: try this SELECT cd.c_id,cd.name, first_game FROM account_data ad inner join game_data gd ON ad.a_id = gd.a_id order by gd.g_id,ad.a_id as games inner join customer_data cd on games.c_id = cd.c_id order by cd.c_id Hope this works.
doc_23536717
Each picture has a value and when the image is clicked it adds to an overall total. I can't get this total to persist if the page is refreshed or closed and reopened. My javascript for calculating the total and storing the checkboxes is below. $('.dp-spotter-switch input[type="checkbox"]').click(function () { if (!$(this).is(':checked')) { $(this).parent('.dp-spotter-switch').removeClass('spotter-scale'); } else { $(this).parent('.dp-spotter-switch').addClass('spotter-scale'); } }); function showDiv() { document.getElementById('getScoreLabel').style.display = "block"; } // Total values function totalIt() { var input = document.getElementsByName("product"); var total = 0; for (var i = 0; i < input.length; i++) { if (input[i].checked) { total += parseFloat(input[i].value); } } document.getElementById("total").value = "" + total.toFixed(0); } // Store checkbox state (function () { var boxes = document.querySelectorAll("input[type='checkbox']"); for (var i = 0; i < boxes.length; i++) { var box = boxes[i]; if (box.hasAttribute("store")) { setupBox(box); } } function setupBox(box) { var storageId = box.getAttribute("store"); var oldVal = localStorage.getItem(storageId); console.log(oldVal); box.checked = oldVal === "true" ? true : false; box.addEventListener("change", function () { localStorage.setItem(storageId, this.checked); }); } })(); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="dp-spotter-container"> <div class="dp-top-paragraph"> <p>Some text</p> <p>Click on the photos once you have spotted, and at the end click on <strong>Get Your Score</strong> to see how you've done</p> <div id="getScoreLabel" style="display:none; text-align: center;"> <div class="dp-your-score-text" id="getScore">Your Score</div> <input value="0" readonly="readonly" type="text" id="total" class="dp-scores dp-floating"/> </div> </div> <br/> <br/> <!-- Spotter 1 --> <div class="dp-switch-container"> <label class="dp-spotter-switch"> <img class="dp-spotter-img" src="image.jpg"> <input type="checkbox" name="product" value="3" id="cb1" class="spotter-check" onclick="totalIt()" store="checkbox1"> <span class="dp-spotter-slider"></span> <span class="dp-spotter-text-label">Item 1- 3 Points</span> </label> </div> <!-- Spotter 2 --> <div class="dp-switch-container"> <label class="dp-spotter-switch"> <img class="dp-spotter-img" src="image.jpg"> <input type="checkbox" name="product" value="3" id="cb2" class="spotter-check" onclick="totalIt()" store="checkbox2"> <span class="dp-spotter-slider"></span> <p class="dp-spotter-text-label">Item 2 - 3 Points</p> </label> </div> <!-- Spotter 3 --> <div class="dp-switch-container"> <label class="dp-spotter-switch"> <img class="dp-spotter-img" src="image.jpg"> <input type="checkbox" name="product" value="5" id="cb3" class="spotter-check" onclick="totalIt()" store="checkbox3"> <span class="dp-spotter-slider"></span> <p class="dp-spotter-text-label">ITem 3 - 5 Points</p> </label> </div> <!-- Spotter 4 --> <div class="dp-switch-container"> <label class="dp-spotter-switch"> <img class="dp-spotter-img" src="image.jpg"> <input type="checkbox" name="product" value="10" id="cb4ß" class="spotter-check" onclick="totalIt()" store="checkbox4"> <span class="dp-spotter-slider"></span> <p class="dp-spotter-text-label">Item 4 - 10 Points</p> </label> </div> <a href="#getScore" class="dp-getScore" onclick="showDiv()">Get Your Score</a> </div> I'm looking for a way to add to the existing function for the checkboxes if possible. A: Unfortunately we can't use local storage in StackOverflow runnable code snippets, so you'll have to head over to my repl.it to see this working in action. Since you're using jQuery, I've gone ahead and provided a jQuery solution: * *Used .attr() to set the checkbox based on local storage *Called totalIt when showing showDiv If you want to use your existing code, just change box.checked = oldVal === "true" ? true : false; to box.setAttribute('checked', oldVal === "true" ? true : false) and add totalIt to your showDiv function Demo https://repl.it/@AnonymousSB/SO53500148 Solution function showDiv() { totalIt(); document.getElementById('getScoreLabel').style.display = "block"; } // Total values function totalIt() { var input = document.getElementsByName("product"); var total = 0; for (var i = 0; i < input.length; i++) { if (input[i].checked) { total += parseFloat(input[i].value); } } document.getElementById("total").value = "" + total.toFixed(0); } // Store checkbox state function setupBox(box) { var storageId = box.attr("store"); var oldVal = localStorage.getItem(storageId); box.attr('checked', oldVal === "true" ? true : false) box.change(function() { localStorage.setItem(storageId, this.checked); }); } $(document).ready(function () { $( "input[type='checkbox'][store]" ).each(function( index ) { setupBox($( this )); }); }) You can open Chrome Dev Tools, go to Application, and see your local storage
doc_23536718
I saw that there are a lot of similar problem, but every problem has a different solution. Tnx a lot! LogCat 12-24 18:11:37.923: I/ActivityThread(1385): Pub com.bogdanskoric.recnik.DictionaryProvider: com.bogdanskoric.recnik.DictionaryProvider 12-24 18:11:38.464: D/dalvikvm(1385): GC_FOR_ALLOC freed 121K, 3% free 8263K/8455K, paused 125ms, total 129ms 12-24 18:11:38.486: I/dalvikvm-heap(1385): Grow heap (frag case) to 9.582MB for 1536016-byte allocation 12-24 18:11:38.594: D/dalvikvm(1385): GC_CONCURRENT freed 2K, 3% free 9761K/9991K, paused 27ms+6ms, total 110ms 12-24 18:11:39.524: I/Choreographer(1385): Skipped 49 frames! The application may be doing too much work on its main thread. 12-24 18:11:39.723: D/gralloc_goldfish(1385): Emulator without GPU emulation detected. 12-24 18:11:41.454: I/Choreographer(1385): Skipped 348 frames! The application may be doing too much work on its main thread. 12-24 18:11:44.463: I/Choreographer(1385): Skipped 59 frames! The application may be doing too much work on its main thread. 12-24 18:11:46.124: I/Choreographer(1385): Skipped 36 frames! The application may be doing too much work on its main thread. SearchableDictionary.java package com.bogdanskoric.recnik; handleIntent(intent); } private void handleIntent(Intent intent) { if (Intent.ACTION_VIEW.equals(intent.getAction())) { // handles a click on a search suggestion; launches activity to show word Intent wordIntent = new Intent(this, WordActivity.class); wordIntent.setData(intent.getData()); startActivity(wordIntent); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.searchable_dictionary, menu); MenuItem item = menu.findItem(R.id.search); final SearchView searchView = (SearchView)MenuItemCompat.getActionView(item); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchableInfo info = searchManager.getSearchableInfo(getComponentName()); searchView.setSearchableInfo(info); searchView.setIconified(true); int searchDeleteImgId = getResources().getIdentifier("android:id/search_close_btn", null, null); ImageView searchDeleteImg = (ImageView) searchView.findViewById(searchDeleteImgId); searchDeleteImg.setImageResource(R.drawable.ic_action_discard); int searchSrcTextId = getResources().getIdentifier( "android:id/search_src_text", null, null); EditText searchEditText = (EditText) searchView.findViewById(searchSrcTextId); searchEditText.setTextColor(Color.WHITE); searchEditText.setHintTextColor(Color.WHITE); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String s) { return true; } @Override public boolean onQueryTextChange(String s) { return false; } }); return true; } WordActivity.java public class WordActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.word); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){ ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); } Uri uri = getIntent().getData(); Cursor cursor = managedQuery(uri, null, null, null, null); if (cursor == null) { finish(); } else { cursor.moveToFirst(); TextView word = (TextView) findViewById(R.id.word); TextView definition = (TextView) findViewById(R.id.definition); int wIndex = cursor.getColumnIndexOrThrow(DictionaryDatabase.KEY_WORD); int dIndex = cursor.getColumnIndexOrThrow(DictionaryDatabase.KEY_DEFINITION); word.setText(cursor.getString(wIndex)); definition.setText(cursor.getString(dIndex)); } } DictionaryProvider.java public class DictionaryProvider extends ContentProvider { String TAG = "DictionaryProvider"; public static String AUTHORITY = "com.bogdanskoric.recnik.DictionaryProvider"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/dictionary"); public static final String WORDS_MIME_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.bogdanskoric.recnik"; public static final String DEFINITION_MIME_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.bogdanskoric.recnik"; private DictionaryDatabase mDictionary; // UriMatcher stuff private static final int SEARCH_WORDS = 0; private static final int GET_WORD = 1; private static final int SEARCH_SUGGEST = 2; private static final int REFRESH_SHORTCUT = 3; private static final UriMatcher sURIMatcher = buildUriMatcher(); private static UriMatcher buildUriMatcher() { UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); // to get definitions... matcher.addURI(AUTHORITY, "dictionary", SEARCH_WORDS); matcher.addURI(AUTHORITY, "dictionary/#", GET_WORD); // to get suggestions... matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGEST); matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGEST); matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT, REFRESH_SHORTCUT); matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*", REFRESH_SHORTCUT); return matcher; } @Override public boolean onCreate() { mDictionary = new DictionaryDatabase(getContext()); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // Use the UriMatcher to see what kind of query we have and format the db query accordingly switch (sURIMatcher.match(uri)) { case SEARCH_SUGGEST: if (selectionArgs == null) { throw new IllegalArgumentException( "selectionArgs must be provided for the Uri: " + uri); } return getSuggestions(selectionArgs[0]); case SEARCH_WORDS: if (selectionArgs == null) { throw new IllegalArgumentException( "selectionArgs must be provided for the Uri: " + uri); } return search(selectionArgs[0]); case GET_WORD: return getWord(uri); case REFRESH_SHORTCUT: return refreshShortcut(uri); default: throw new IllegalArgumentException("Unknown Uri: " + uri); } } private Cursor getSuggestions(String query) { query = query.toLowerCase(); String[] columns = new String[] { BaseColumns._ID, DictionaryDatabase.KEY_WORD, /* SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, (only if you want to refresh shortcuts) */ SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID}; return mDictionary.getWordMatches(query, columns); } private Cursor search(String query) { query = query.toLowerCase(); String[] columns = new String[] { BaseColumns._ID, DictionaryDatabase.KEY_WORD, DictionaryDatabase.KEY_DEFINITION}; return mDictionary.getWordMatches(query, columns); } private Cursor getWord(Uri uri) { String rowId = uri.getLastPathSegment(); String[] columns = new String[] { DictionaryDatabase.KEY_WORD, DictionaryDatabase.KEY_DEFINITION}; return mDictionary.getWord(rowId, columns); } private Cursor refreshShortcut(Uri uri) { String rowId = uri.getLastPathSegment(); String[] columns = new String[] { BaseColumns._ID, DictionaryDatabase.KEY_WORD, DictionaryDatabase.KEY_DEFINITION, SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID}; return mDictionary.getWord(rowId, columns); } @Override public String getType(Uri uri) { switch (sURIMatcher.match(uri)) { case SEARCH_WORDS: return WORDS_MIME_TYPE; case GET_WORD: return DEFINITION_MIME_TYPE; case SEARCH_SUGGEST: return SearchManager.SUGGEST_MIME_TYPE; case REFRESH_SHORTCUT: return SearchManager.SHORTCUT_MIME_TYPE; default: throw new IllegalArgumentException("Unknown URL " + uri); } } A: For anyone looking for an answer to this question, it's documented well here: The application may be doing too much work on its main thread.
doc_23536719
function user_apps() { $this->db->select('*'); $this->db->from('apps'); $this->db->join('members', 'members.user_ID = apps.user_ID'); $query = $this->db->get(); return $query; } Here is an image of the DB tables, and goal is to basically get the urls from the apps table of each user, http://cl.ly/516bd1e8aae62bd11773 A: You haven't specified a WHERE clause in your query. At the moment it is returning everything because you only have two users and they both have entries in the 'apps' table. If you add: $this->db->where('members.first_name', $first_name); And pass a first name as a parameter to the function then it will only return results for that user. function user_apps($first_name) { $this->db->select('*'); $this->db->from('apps'); $this->db->join('members', 'members.user_ID = apps.user_ID'); $this->db->where('members.first_name', $first_name); $query = $this->db->get(); return $query; }
doc_23536720
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <script type="text/javascript" src="js/jquery.js"></script> <title>Some title</title> </head> <body> <div id="mostRecent"> Most Recent Time: <span id="mTime"></span><br> </div> <input id="butt" type="button" value="refresh" /> <script type="text/javascript"> $(document).ready(function(){ count = 0; $('#butt').click(function(){ $('#mTime').text(" <%= new java.util.Date() %> "); count += 1; }); }); </script> </body> </html> When I click the refresh button the current date is written in the span as expected, but only the first time it is called ie. New more current date strings are not added, making me think that the method is being called (successfully) only once. Is there any way around this? Or even better, is there a problem in my general technique (ie. should I be making a request to a servlet for the time as to not add too much view logic). If that is the case then a description as to how I could load a servlet response into only a small part of the page (rather than printing the response to a new page) would be appreciated. Many thanks. A: Well your example don't work because the page is interpreted only once, i.e. the jsp page is interpreted when the it is requested. To solve your problem you can create a JSP page with the code: <%= new java.util.Date() %> You can try something like this: $('#butt').click(function(){ $.get("get_current_date.jsp", function(response) { $('#mTime').text(response); count += 1; }); });
doc_23536721
And directory structure would be: /Acme /Module1 /src /Module1 /Class.php And a valid way to instantiate the class is : new Acme\Module1\Class(); Are my assumptions correct? If so, what's the benefit of using the src folder? A: Convention usually. If you're using composer and you want to autoload your classes, it looks like you're trying to do PSR-0 autoloading. So if you have "Acme": "src/" Then in the same directory as your composer.json file would be a src folder, and in the src folder would be a Acme folder. All files in that folder would be namespace Acme; and all files in subdirectories of that folder would be namespace Acme\Subdirectory;. In the console you need to type composer dump-autoload every time you make changes to the autoloading part of your composer.json file. (or for classmap autoloading, every time you add new files to directories being autoloaded.) This causes the files generated by composer to be updated. (you can find these files in the vendor/composer directory). So if there was a src/Acme/Subdirectory/ClassName.php with a class in it named ClassName then to instantiate that class you could type new \Acme\Subdirectory\ClassName(); edit: so if this is your composer.json file { "autoload": { "psr-0": { "Acme": "src/" } } } then your directory structure would be something like this /ProjectRoot composer.json /src /Acme /Module1 Class.php And you would create a new instance of your class by typing new \Acme\Module1\Class();
doc_23536722
http://localhost:8080/context/login/{user}/{password} and example of this request is http://localhost:8080/context/login/admin/admin i have configured an AbstractPhaseInterceptor in the applicationContext.xml of my spring application. And the interceptor class is public class TokenInInterceptor extends AbstractPhaseInterceptor { public TokenInInterceptor() { super(Phase.READ); } public void handleMessage(Message message) { } } i would like to retrieve the parameters user and password form the object message in the handleMessage method, but i can`t found where it is. Anyone know how can i retrieve that parameters? thanks A: You can do something like: UriInfo uriInfo = new UriInfoImpl(message); MetadataMap<String, String> metadataMap = (MetadataMap<String, String>) uriInfo.getPathParameters(); User user = metadataMap.getFirst("user"); String password = metadataMap.getFirst("password");
doc_23536723
I expected that the following code both 1) redirects to the designated path and 2) updates state, however, it only executes 1). What is wrong with my codes? What I intend to do with this method is to change the current state of pages that highlight the menu color. This happens when the page on the menu is selected or link function in a page triggered. Class App extends .. { constructor(props) { super(props); this.state = { state: null }; } handleState = index => e => { this.setState({ state: index }); }; render() { return ( <Switch> <Route path="/SampleA"> <SampleA handleState={this.handleState}> </Route> <Route path="/SampleB"> <SampleB> </Route> </Switch> ); } } Const SampleA = props => { const handlClick = () => { props.handleState(0); props.history.push({ pathname: `/SampleB` }); } return( <Button onClick={handleClick}>Go to B!</Button> ); } A: This might be the issue: handleState = index => e => { this.setState({ state: index }); }; should be handleState = index => { this.setState({ state: index }); }; because previously handleState is a function that takes index as an argument and returns another function that expects another argument e. Now it just takes index and updates the state. update this is how your function should be: Const SampleA = props => { const handlClick = (e) => { props.handleState(e, 0); props.history.push({ pathname: `/SampleB` }); } return( <Button onClick={handleClick}>Go to B!</Button> ); } Now the event and index are passed to the handleState function so you can use them as: handleState = (event, index) => { console.log(event, index); this.setState({ state: index }); };
doc_23536724
//Service async createOrderProposal(createOrderProposalDto: CreateOrderProposalDto) { const { startDate, categories, paymentMethodId, address } = createOrderProposalDto; let freelancers; categories.forEach(async category => { freelancers.push(await this.freelancerRepository.getFreelancersByCategoryId(category.categoryId)); }) console.log(freelancers); // gives [] } Then the repository function looks something like: async getFreelancersByCategoryId(categoryId: string){ await this.createQueryBuilder('freelancers') .innerJoinAndSelect('freelancers.user','user') .innerJoinAndSelect('user.freelancerCategories', 'categories') .select('freelancers') .where('categories.category_id = :categoryId', {categoryId}) .getMany() } Logging this repository function gives me the correct entities but i am unable to store it in a variable in service. What am i doing wrong??
doc_23536725
Her is a snip of the features which I could select in the installation:
doc_23536726
I have an API I'm pulling info from and serving it on the DOM. I only need a list of one of the values. The problem I'm having is that I can't seem to target the value correctly because it is several layers deep in the JSON. Ideally I'll have this replace and append an existing list on the page by targeting the ID. I can get that to work, but in this code example I can only get all 81 indexes. If I add [0] to the onetObj then I get a list of the names in that index. What I want is the value of one of those names only, for all of the indexes, in a list. Specifically the Alternate Titles in each index. The way they have auth setup you won't be able to run my code directly without a CORS violation. So I'm including the code I'm using as well as a copy of the array I'm working with. I hope that helps. EDIT There was a question about my end goal here. Hopefully this will help! I am building a career matching site using a CMS of info from my client and pulling in extra data from a Department of Labor API. There are over 1100 careers in their database and 37 databases of additional information for us to pick and choose from. In this specific example I have a page that has the main title of the career and a writeup on it from the client's CMS. I'm trying to add a list of Alternate Titles for that career. The Alternate Titles come from the API. All I can seem to get to show on the DOM is a list of the Row numbers when the only thing I need is a list of the Alternate Titles (alternate_title) from each row. My script: <script> var myHeaders = new Headers(); myHeaders.append("Accept", "application/json"); var requestOptions = { method: 'GET', headers: myHeaders, redirect: 'follow' }; async function start(){ const response = await fetch("https://services.onetcenter.org/v1.9/ws/database/rows/alternate_titles?filter=onetsoc_code.eq.17-2051.00&end=9999&client=careerpuppy", requestOptions) const data = await response.json() console.log(data) createOnetObj(data.row) } start() function createOnetObj(onetObj) { document.getElementById("alttitlelist").innerHTML = ` ${Object.keys(onetObj).map(function (altTitle) { return `<li>${altTitle}</li>` }).join('')} ` } </script> Here's two indexes from the 81 in the JSON I'm getting with this request: end: 81 filter: ["onetsoc_code.eq.17-2051.00"] info: "https://services.onetcenter.org/v1.9/ws/database/info/alternate_titles" row: Array(81) 0: {onetsoc_code: "17-2051.00", title: "Civil Engineers", alternate_title: "Airport Engineer", short_title: null, sources: "08"} 1: {onetsoc_code: "17-2051.00", title: "Civil Engineers", alternate_title: "Architectural Engineer", short_title: null, sources: "08"} A: Your objectives are unclear to me but Object.keys is not what you need. You work with data.row, that's an Array. If you want to iterate over values, use something like: data.row.forEach( (value, index) => { console.log(index, ':', value.alternate_title); }); const alternateTitles = data.row.map( value => value.alternate_title); If you need unicity, the solution is here Edition Just put things together, something like <script> async function updateListItems(){ const url = "https://services.onetcenter.org/v1.9/ws/database/rows/alternate_titles?filter=onetsoc_code.eq.17-2051.00&end=9999&client=careerpuppy"; const response = await fetch(url, { method: 'GET', headers: { "Accept" : "application/json"}, redirect: 'follow' }); const data = await response.json(); const list = document.getElementById("alttitlelist"); const listItems = data.row.map( value => `<li>${value.alternate_title}</li>`).join(''); list.innerHTML = listItems; } updateListItems(); </script> And unicity is just what it means, removing duplicate items.
doc_23536727
Steps I have used to attempt to diagnose/resolve: * *Closed out document and reopened- still has the problem *Tried shortcut in consul and different document- still inserts = not <- *Closed out of RStudio and reopened- no change *Reset all keyboard shortcuts- no change Additional information: * *Rstudio version: Version 1.0.136 *OS: Windows 10 *Have posted on Rstudio *Googled- only can find how to use that shortcut but not how to change the operator
doc_23536728
I have this error when I do a POST to http://myServer/api/Codes: An error occurred when trying to create a controller of type 'CodesController'. Make sure that the controller has a parameterless public constructor. I have this packages installed: <?xml version="1.0" encoding="utf-8"?> <packages> <package id="Antlr" version="3.5.0.2" targetFramework="net451" /> <package id="bootstrap" version="3.3.2" targetFramework="net451" /> <package id="DotNetZip" version="1.9.3" targetFramework="net451" /> <package id="EntityFramework" version="6.1.2" targetFramework="net451" /> <package id="jQuery" version="2.1.3" targetFramework="net451" /> <package id="jQuery.Validation" version="1.13.1" targetFramework="net451" /> <package id="log4net" version="2.0.3" targetFramework="net451" /> <package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net451" /> <package id="Microsoft.AspNet.Razor" version="3.2.3" targetFramework="net451" /> <package id="Microsoft.AspNet.Web.Optimization" version="1.1.3" targetFramework="net451" /> <package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net451" /> <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net451" /> <package id="Microsoft.AspNet.WebApi.Client.es" version="5.2.3" targetFramework="net451" /> <package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net451" /> <package id="Microsoft.AspNet.WebApi.Core.es" version="5.2.3" targetFramework="net451" /> <package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net451" /> <package id="Microsoft.AspNet.WebApi.WebHost.es" version="5.2.3" targetFramework="net451" /> <package id="Microsoft.AspNet.WebPages" version="3.2.3" targetFramework="net451" /> <package id="Microsoft.jQuery.Unobtrusive.Ajax" version="3.2.3" targetFramework="net451" /> <package id="Microsoft.jQuery.Unobtrusive.Validation" version="3.2.3" targetFramework="net451" /> <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net451" /> <package id="Modernizr" version="2.8.3" targetFramework="net451" /> <package id="Newtonsoft.Json" version="6.0.8" targetFramework="net451" /> <package id="Ninject" version="3.2.2.0" targetFramework="net451" /> <package id="Ninject.MVC5" version="3.2.1.0" targetFramework="net451" /> <package id="Ninject.Web.Common" version="3.2.3.0" targetFramework="net451" /> <package id="Ninject.Web.Common.WebHost" version="3.2.3.0" targetFramework="net451" /> <package id="Ninject.Web.WebApi" version="3.2.4.0" targetFramework="net451" /> <package id="WebActivatorEx" version="2.0.6" targetFramework="net451" /> <package id="WebGrease" version="1.6.0" targetFramework="net451" /> </packages> But the strange thing is I have an ApiController that works perfectly, and two ApiControllers that doesn't work. Working ApiController constructor: public ExternalCodesController( IGenericRepository<EXTERNAL_CODES> genericRepositoryECodes, IGenericRepository<CHINA_CODES_HEADER> genericRepositoryHeader, IGenericRepository<BATCHES> genericRepositoryBatches, IGenericRepository<LINES> genericRepositoryLine, IExternalCodesMapper externalCodesMapper, IExceptionLogHelper exceptionLogger) { m_GenericRepositoryECodes = genericRepositoryECodes; m_GenericRepositoryHeader = genericRepositoryHeader; m_ExceptionLogger = exceptionLogger; m_GenericRepositoryBatches = genericRepositoryBatches; m_GenericRepositoryLine = genericRepositoryLine; m_ExternalCodesMapper = externalCodesMapper; } Not working ApiController constructor: public AggregationsController( IGenericRepository<Data.AGGREGATIONS> repositoryAggs, IGenericRepository<Data.AGGREGATION_CHILDS> repositoryAggChilds, IGenericRepository<Data.CODES> repositoryCodes, IAggregationsMapper aggregationMapper, IAggregationChildsMapper aggChildsMapper, IExceptionLogHelper exceptionLogger) { m_RepositoryAggs = repositoryAggs; m_RepositoryAggChilds = repositoryAggChilds; m_RepositoryCodes = repositoryCodes; m_AggregationMapper = aggregationMapper; m_AggChildsMapper = aggChildsMapper; m_ExceptionLogger = exceptionLogger; } public CodesController( IGenericRepository<CODES> repositoryCodes, ICodesMapper codesMapper, IExceptionLogHelper exceptionLogger) { m_RepositoryCodes = repositoryCodes; m_CodesMapper = codesMapper; m_ExceptionLogger = exceptionLogger; } Any idea about this Poltergeist? If you need something else, please tell me. A: You're missing a required dependency (not registered) and ninject is cascading to a parameterless constructor which does not exist. One way to determine which dependency is missing is to remove parameters from the constructor until you don't get this error.
doc_23536729
I'm using Screen Recording by https://github.com/alskipp/ASScreenRecorder. Code for playing mp4 video through AVPlayer: let fileURL = Bundle.main.url(forResource:"file_example_MP4_480_1_5MG", withExtension: "mp4") let player = AVPlayer(url: fileURL!) let playerLayer = AVPlayerLayer(player: player) playerLayer.frame = viewToRecord.frame viewToRecord.layer.addSublayer(playerLayer) player.play() In above code viewToRecord is the UIView which I need to record with mp4 video in Screen Recording. Looking for best possible solutions!!!
doc_23536730
Account Table Zone ACC_NUM Profile Status INT 123456 11 Active DOM 246810 12 Active INT 135791 12 Inactive Meter Table Acc_Num Meter 123456 156894 135791 NULL Expected Result Zone ACC_NUM Profile Status Meter INT 123456 11 Active 156894 DOM 246810 12 Active NULL INT 135791 12 Inactive NULL I have written the following query, but I see some duplicates like the results that followed the below query Select a.Zone, a.Acc_Num, a.Status, m.Meter From Account a left join Meter m on m.Acc_Num=a.Acc_Num I got the following results which are not desirable Zone ACC_NUM Profile Status Meter INT 123456 11 Active NULL INT 123456 11 Active 156894 DOM 246810 12 Active NULL INT 135791 12 Inactive NULL From above results, I found that when there is match between both the tables and meter is not null it returned duplicate row, one with NULL meter and other with actual value and seems like it's good when there is no match or when there is match but meter is NULL. May I know a better way to get the expected results? A: Your code is perfectly valid: CREATE TABLE #Account( Zone VARCHAR(30) NOT NULL ,ACC_NUM INTEGER NOT NULL ,Profile INTEGER NOT NULL ,Status VARCHAR(80) NOT NULL ); INSERT INTO #Account(Zone,ACC_NUM,Profile,Status) VALUES ('INT',123456,11,'Active'); INSERT INTO #Account(Zone,ACC_NUM,Profile,Status) VALUES ('DOM',246810,12,'Active'); INSERT INTO #Account(Zone,ACC_NUM,Profile,Status) VALUES ('INT',135791,12,'Inactive'); CREATE TABLE #Meter( Acc_Num INTEGER NOT NULL ,Meter VARCHAR(60) ); INSERT INTO #Meter(Acc_Num,Meter) VALUES (123456,'156894'); INSERT INTO #Meter(Acc_Num,Meter) VALUES (135791,NULL); Select a.Zone, a.Acc_Num, a.Status, m.Meter From #Account a left join #Meter m on m.Acc_Num=a.Acc_Num; LiveDemo The problem is probably your data in Meter table. I guess you have additional row with 123456 NULL value. If you want only one value per group you can use: Select a.Zone, a.Acc_Num, a.Status, m.Meter From #Account a left join (SELECT Acc_Num, MIN(Meter) AS Meter FROM #Meter GROUP BY Acc_Num) AS m on m.Acc_Num=a.Acc_Num LiveDemo2 A: Your query is about the best way to do it. However, to answer your question how do I handle if just in case there is a NULL to get the expected results?, just add a NULL check to your join condition: Select a.Zone, a.Acc_Num, a.Status, m.Meter From #Account a left join #Meter m on NOT m.Meter IS NULL AND m.Acc_Num = a.Acc_Num; Here is a fiddle.
doc_23536731
A: Actually ES does not use random decision it takes into account a lot of factors: * *MaxRetryAllocationDecider - prevents shards from being allocated on any node if the shards allocation has been retried N times without success *NodeVersionAllocationDecider - prevents relocation or allocation from nodes that might not be version compatible. *SameShardAllocationDecider - prevents multiple instances of the same shard to be allocated on the same node. *DiskThresholdDecider - checks that the node a shard is potentially being allocated to has enough disk space. *ShardsLimitAllocationDecider - limits the number of shards per node on a per index or node-wide basis. *AwarenessAllocationDecider - controls shard allocation based on awareness key-value pairs defined in the node configuration. As you can see there are a lot of factors and there is no low disc space checkers. So the only solution is to write your own plugin which extends org.elasticsearch.plugins.ClusterPlugin which will provide your decider. But I think this is not a good idea because it contradicts the main design/idea of ES allocation decider pattern: * *any decider can veto decisions of all previous deciders *any positive solution has no influence on the subsequent decision *most of the deciders use local node data This strategy allows you to prohibit and is designed to maximize the freedom to choose within a cluster. That's why from the outside it looks like a randomly moving. This is a great strategy for large and long-lived clusters. The introduction of any kind of biasing may leads to catastrophic problems in production. Let's imagine you have disc space based decider and one server has incredibly large HDD - after a while all shards will be allocated on this machine. To solve this problem, it is necessary to take into account more significant resources like CPU, Memory, Network, amount of shards etc. Moreover, we need to come up with a metric and weights for each factor.
doc_23536732
I.e., it seems to be only practical for the tenants, which are narrowly specialised in handling certain mail, and does not contain any regular individual's mail. The question: is there, perhaps, any way to run a daemon with only delegated permissions configured for the app? That would seem to solve the predicament. A: One way is to limit the daemon app's permissions in Exchange Online with an application access policy: https://learn.microsoft.com/en-us/graph/auth-limit-mailbox-access. The other more complicated way is to use delegated permissions through refresh tokens. The process for that looks like this: * *User who wants to give the app access to send emails from their mailbox signs in to the app (you need some kind of front-end) *The app receives an ID token, an access token, and a refresh token *ID token tells the app who the user is, so they can get for example the user's unique immutable id from there (the oid claim) in order to identify the user who gave access *The access token isn't really necessary here, so the app can throw that away *The refresh token on the other hand is stored in a secret store *Daemon app wants to send an email, so it gets the refresh token from secret store *A new access token and refresh token are acquired from Azure AD using the refresh token *The new refresh token is stored in the secret store to replace the existing one *The daemon app uses the access token to send the email as the user The daemon app needs to be ready for the inevitable situation where the refresh token doesn't work though. It could have expired for various reasons. In that situation the first steps need to be repeated for that user. The refresh token can also expire if not used, though this may have changed in recent times. In the past we made a process that would ensure that each refresh token got at least used to acquire new tokens once a week to keep them fresh. So you can see that the daemon app approach with application permissions is a lot simpler and more robust (just have to make sure the secret/certificate doesn't expire). On the other hand the approach with delegated permissions is fundamentally more secure as you can't gain more access than what the user has. Individual users can also revoke consent. A: If you are just trying to read one particular AD user's mailbox, you may be able to use the Integrated Windows provider, which uses delegated permissions. While this is meant more for desktop/mobile apps, it can be used in daemon apps as well. The nice thing about it is it allows you to get a token silently, with no user interaction required. There are a few caveats, however, which admittedly limits its scope: * *The app must be running as the user whose mailbox you are trying to access. *The user cannot have MFA enabled (since that requires user interaction--may not be an issue for a service account user). *You would need to enable the "Allow public client flows" app setting in the Azure portal. The code would then look something like below. More info here and here. AuthenticationConfig config = AuthenticationConfig.ReadFromJsonFile("appsettings.json"); IPublicClientApplication app = PublicClientApplicationBuilder .Create(config.ClientId) .WithTenantId(config.Tenant) .Build(); string[] scopes = new string[] { $"{config.ApiUrl}.default" }; var authProvider = new Microsoft.Graph.DelegateAuthenticationProvider(async (request) => { var result = await app.AcquireTokenByIntegratedWindowsAuth(scopes).ExecuteAsync(); request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken); }); var graphClient = new Microsoft.Graph.GraphServiceClient(authProvider); var messages = await graphClient.Users["TheUser@YourDomain.com"].Messages.Request() .Select("sender,subject").GetAsync(); // substitute your user
doc_23536733
What I want to know is what steps do you recommend I take to diagnose the cause of this condition? It is not possible to upgrade this site to a newer version of JBoss nor java (currently 1.5.0.7). It is running on 32-bit CentOS 5.3 Linux on 3 xen-based virtual servers in a load balanced configuration. The code is common to all three servers via an nfs share. This same issue was seen, however, when the 3 servers were physical and the code was local to each server. The servers are each 2 cpu, 4GB RAM servers. Also as an FYI, the wars that deploy in this instance of JBoss are actually exploded wars contained in directories within the deploy directory. A: Chances are, jBoss is unpacking the war file to the tmp directory. This will take a while on a machine with a slow disk or if the war is large. Try explodig it in the deploy directory. Here's a wiki on the topic, but the short version is create a directory with the name of the war, including the .war at the end, and unzip the contents into that. It'll be something like %JBOSS_HOME%\server\<instance>\deploy\<war_file>.war. A: What I want to know is what steps do you recommend I take to diagnose the cause of this condition? First of all 15 minutes are a typical timeout delay, maybe trying to access a network resource. * *1st strace -p pid to find out what the server is doing (system calls) *2nd create a few thread dumps during idle time to find out where it gets stuck. *3rd check $JBOSS_HOME/bin/run.conf for JAVA_OPTS for weird changes.
doc_23536734
Is there any way to show the search in Youtube of the string given when i start the Webview activity? Thanks A: Yes you can search & play video in webview public class UniversalWebViewFragment extends Fragment { private static final String GOOGLE_SERACH_URL = "https://www.google.com/search?q="; private static final String YOUTUBE_SERACH_URL = "https://www.youtube.com/results?search_query=android"; private WebView webView; private FrameLayout customViewContainer; private WebChromeClient.CustomViewCallback customViewCallback; private View mCustomView; private myWebChromeClient mWebChromeClient; private myWebViewClient mWebViewClient; public static UniversalWebViewFragment newInstance() { return new UniversalWebViewFragment(); } public void searchOnGoogle(String key) { webView.loadUrl(GOOGLE_SERACH_URL + key); } public void searchOnYoutube(String key) { webView.loadUrl(YOUTUBE_SERACH_URL + key); } /** * Called when the activity is first created. */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.universal_web_view, container, false); customViewContainer = (FrameLayout) rootView .findViewById(R.id.customViewContainer); webView = (WebView) rootView.findViewById(R.id.webView); mWebViewClient = new myWebViewClient(); webView.setWebViewClient(mWebViewClient); mWebChromeClient = new myWebChromeClient(); webView.setWebChromeClient(mWebChromeClient); webView.getSettings().setJavaScriptEnabled(true); // Important for PayUMoney webView.getSettings().setDomStorageEnabled(true); webView.getSettings().setAppCacheEnabled(true); webView.getSettings().setBuiltInZoomControls(true); webView.getSettings().setSaveFormData(true); webView.loadUrl(GOOGLE_SERACH_URL); // webView.requestFocus(); // Handle Back keyPress rootView.setFocusableInTouchMode(true); rootView.requestFocus(); rootView.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { return true; } // return super.onKeyDown(keyCode, event); return true; } }); return rootView; } public boolean inCustomView() { return (mCustomView != null); } public void hideCustomView() { mWebChromeClient.onHideCustomView(); } @Override public void onPause() { super.onPause(); // To change body of overridden methods use File | // Settings | File Templates. webView.onPause(); } @Override public void onResume() { super.onResume(); // To change body of overridden methods use File | // Settings | File Templates. webView.onResume(); } @Override public void onStop() { super.onStop(); // To change body of overridden methods use File | // Settings | File Templates. if (inCustomView()) { hideCustomView(); } } class myWebChromeClient extends WebChromeClient { private View mVideoProgressView; @Override public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) { onShowCustomView(view, callback); // To change body of overridden // methods use File | Settings | // File Templates. } @Override public void onShowCustomView(View view, CustomViewCallback callback) { // if a view already exists then immediately terminate the new one if (mCustomView != null) { callback.onCustomViewHidden(); return; } mCustomView = view; webView.setVisibility(View.GONE); customViewContainer.setVisibility(View.VISIBLE); customViewContainer.addView(view); customViewCallback = callback; } @Override public View getVideoLoadingProgressView() { if (mVideoProgressView == null) { LayoutInflater inflater = LayoutInflater.from(getActivity()); mVideoProgressView = inflater.inflate(R.layout.video_progress, null); } return mVideoProgressView; } @Override public void onHideCustomView() { super.onHideCustomView(); // To change body of overridden methods // use File | Settings | File Templates. if (mCustomView == null) return; webView.setVisibility(View.VISIBLE); customViewContainer.setVisibility(View.GONE); // Hide the custom view. mCustomView.setVisibility(View.GONE); // Remove the custom view from its container. customViewContainer.removeView(mCustomView); customViewCallback.onCustomViewHidden(); mCustomView = null; } } class myWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { return super.shouldOverrideUrlLoading(view, url); } private int webViewPreviousState; private final int PAGE_STARTED = 0x1; private final int PAGE_REDIRECTED = 0x2; Dialog dialog = new Dialog(getActivity()); /* * (non-Javadoc) * * /* (non-Javadoc) * * @see * android.webkit.WebViewClient#onPageStarted(android.webkit.WebView, * java.lang.String, android.graphics.Bitmap) */ @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); webViewPreviousState = PAGE_STARTED; if (dialog == null || !dialog.isShowing()) dialog = ProgressDialog.show(getActivity(), "", "Loading Please Wait", true, true, new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { // do something } }); } @Override public void onPageFinished(WebView view, String url) { if (webViewPreviousState == PAGE_STARTED) { if (null != dialog) dialog.dismiss(); dialog = null; } } } } Here is layout for youtube <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <WebView android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/webView" android:layout_gravity="center" /> <FrameLayout android:id="@+id/customViewContainer" android:layout_width="fill_parent" android:layout_height="fill_parent" android:visibility="gone" /> </LinearLayout> Layout for youtube progress <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/progress_indicator" android:orientation="vertical" android:layout_centerInParent="true" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ProgressBar android:id="@android:id/progress" style="?android:attr/progressBarStyleLarge" android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:paddingTop="5dip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="loading" android:textSize="14sp" android:textColor="?android:attr/textColorPrimary"/> </LinearLayout> Use it like this universalWebViewFragment = UniversalWebViewFragment.newInstance(); getFragmentManager().beginTransaction() .add(R.id.frame_root, universalWebViewFragment).commit(); Search Videos like this universalWebViewFragment.searchOnYoutube(searchView .getText().toString()); dont forgot to add permission <uses-permission android:name="android.permission.INTERNET" /> Find full project here https://github.com/hiteshsahu/UniversalWebPageLoader
doc_23536735
I tried to go through the solutions that already exist but could not get information on the range based delineation for multiple columns The data looks like: Column1 -------------------------------------------------------- 00000000000102019000000000000000000049491000000000004CAD    00000000000102019000000000000000000049491000000000005CAP     00000000000102019000000000000000000049491000000000023GSP   00000000000102019000000000000000000049491000000000030MUD The field range is defined as: Field Name | Start | End -------------------------- COL1 | 1 | 2 COL2 | 13 | 17 COL3 | 18 | 12 .... I have about 200,000 rows with having 55 columns each based on the range described above. I am not sure how input multiple ranges to create a new dataframe with all the 55 columns split based on the start and end values. Could anyone please assist me with this? A: try the following code. Note that I made the code according with the data that you mention. example <- c("00000000000102019000000000000000000049491000000000004CAD","00000000000102019000000000000000000049491000000000004CAD") name <- c("COL1","COL2","COL3") start <- c(1,13,18) end <- c(2,17,22) # save the second file for reference range_df <- data.frame(Field_name=name,Start=start,End=end) # Make a function that splits according the second file split_cols <- function(string){ # Get the `n` rows of the second file for iteration n <- nrow(range_df) # Declare an empty `data.frame` for save the splitted data cols <- data.frame(matrix(NA,1,n)) for(i in 1:n){ # Get the range of characters with `substr` function # The start and end range is defined in the `range_df` # column 2 is the `start` character and columns 3 the `end` cols[,i] <- substr(string,range_df[i,2],range_df[i,3]) # save it in each column of the new data frame named `cols` } # Return the values of the `splitted` string as data.frame return(cols) } # In order to apply the function above for each row you can either # use `for` loop or apply function. In this case I used `lapply` all_data <- lapply(example,split_cols) # `lapply` makes the job done, however is in a `list` form. Yo can # structure the data with do.call function final_df <- do.call("rbind",all_data) # Finally add the columns names from the secondary df names(final_df) <- as.character(range_df[,1]) Of course this code can be improved considerably but this can get the job done. Hope this can help A: Here's how you could try: Given: 1) raw_data is your text file 2) mapping is your column width table Apply a function to mapping row-wise that extracts the corresponding column from raw_data. Output from all rows of mapping correspond to each column that you need. raw_data <- data.frame(str_data = c('00000000000102019000000000000000000049491000000000004CAD', '00000000000102019000000000000000000049491000000000005CAP', '00000000000102019000000000000000000049491000000000023GSP', '00000000000102019000000000000000000049491000000000030MUD')) mapping = data.frame('columns' = c('COL1', 'COL2', 'COL3'), 'start' = c(1,13,18), 'end' = c(2,17,22)) # Funtion that returns column within start and end indexes columns = function(x, str_table) { col = substr(str_table[,1], x['start'], x['end']) return(col) } # Apply the function columns to rows in mapping tab = data.frame(apply(mapping, MARGIN = 1,columns, raw_data)) colnames(tab) <- mapping$columns Here's the output: COL1 COL2 COL3 1 00 02019 00000 2 00 02019 00000 3 00 02019 00000 4 00 02019 00000
doc_23536736
http://ipgames.wordpress.com/tutorials/writeread-data-to-plist-file/ If I want to use a plist to hold my tile map objects game data, do I have to create a plist with xcode first? and then update that? or do I not need to do that and I can just create it from scratch with code when the game runs? If I don't have to create one with xcode first, what would be the benefit of doing that? A: The code from your link is useful if you want some default data in the property list when the application is started for the first time. If you don't need default data, don't have to create a property list in Xcode and include it in your application. NSString *path = ... // path to plist file in Documents directory NSMutableDictionary *plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path]; if (plistDict == nil) { // No plist present (or invalid contents), start with empty dictionary: plistDict = [[NSMutableDictionary alloc] init]; } Now you can add/modify/remove items in plistDict and save it later.
doc_23536737
Account#: 1 Data1 Data2 Data3 Account#: 1 Data4 Data5 Data6 Account#: 1 Data7 Data8 Data9 Account#: 2 Data10 Data11 Data12 Account#: 2 Data13 Data14 Data15 Account#: 3 Data16 Data17 Data18 Account#: 3 Data19 Data20 Data21 The result should be in my first index it will composed of Account#: 1 with Data1-9, then in my second index Account#: 2 with Data 10-15 and so on.. ("Data" here is composed of new lines and etc) I'm thinking to use the split(regex) but, how can i regex the range of account#? is there any chance that regex can match unique values? Thanks for the response. A: Using a regular expression will still require the file to be read / scanned. A reg exp is simply a way of efficiently scanning the data, once read from the file. Why not implement something simple to read the file once, line-by-line. As you are reading it and encounter each Account #, write the data that follows to a unique file for that account #, or alternatively to an in-memory data structure, such as a java.util.Map keyed by the Account # (if the data will fit in-memory). If you write this efficiently, with data going to an output file per account #, you will only need to read the input file once (which a regular expression approach would need to do anyway), and could write out to each account file as you detect which account # the data is for. If the file is not sorted by account #, you could keep up to a certain number of file output streams open at once, closing them only when you reach the end of the file, or when there are too many open. If you need to further append to a file for an account #, just re-open in append mode. The input file could be any size, with time taken to process it will be directly proportional to its size. Regular expressions are for finding definable patterns in data, not for spotting unique values.
doc_23536738
So I think to do it with matInput and matMenu. but it don't come out as I expected. * *The div is closing the I click on it. *Not open below the textbox (it open under the input), doesn't keep the width of input. How do I fix with angular material? <mat-form-field class="example-form-field"> <mat-label>Search</mat-label> <input matInput type="text" [(ngModel)]="value"> <button [matMenuTriggerFor]="menu" mat-button *ngIf="value" matSuffix mat-icon-button aria-label="Clear"> <mat-icon>keyboard_arrow_down</mat-icon> </button> </mat-form-field> <mat-menu #menu="matMenu" > <form class="example-form"> <mat-form-field class="example-full-width"> <mat-label>Company (disabled)</mat-label> <input matInput disabled value="Google"> </mat-form-field> <table class="example-full-width" cellspacing="0"><tr> <td><mat-form-field class="example-full-width"> <mat-label>First name</mat-label> <input matInput> </mat-form-field></td> <td><mat-form-field class="example-full-width"> <mat-label>Long Last Name That Will Be Truncated</mat-label> <input matInput> </mat-form-field></td> </tr></table> <p> <mat-form-field class="example-full-width"> <mat-label>Address</mat-label> <textarea matInput placeholder="Ex. 100 Main St">1600 Amphitheatre Pkwy</textarea> </mat-form-field> <mat-form-field class="example-full-width"> <mat-label>Address 2</mat-label> <textarea matInput></textarea> </mat-form-field> </p> </form> </mat-menu>
doc_23536739
library(shiny) ui <- fluidPage( sidebarLayout( sidebarPanel("Inputs", numericInput(inputId = "media", label = "Mean:", value = 0, min = 0), numericInput(inputId = "desv_pad", label = "Standard Deviation:", value = 1, min = 0), numericInput(inputId = "delta", label = "Mean Shift:", value = 0.5, min = 0, max = 2, step = 0.25), numericInput(inputId = "n", label = "Size of Samples:", value = 5, min = 0, max = 10, step = 1), numericInput(inputId = "alfa", label = "% alpha", value = 0.27, min = 0, step = 0.1), numericInput(inputId = "beta", label = "% beta:", value = 97, min = 0, step = 0.1), numericInput(inputId = "xb_teo", label = "%X max:", value = 10, min = 0), actionButton("rodar", "Run") ), mainPanel( tags$h4( tableOutput('saida')), tags$br(), tags$br(), tags$br(), tags$br(), tags$br(), tags$br(), actionButton("reset", "Reset") ) ) ) server <- function(input, output) { v <- reactiveValues(data = NULL) observeEvent(input$rodar,{ output$saida <- renderTable({ #resultado, passo_n <- 0 #Recebendo os inputs: n <-input$n Xb_teo <- input$xb_teo# input Xbarra percentual teorico definido pelo usuario med<- input$media #input da media desv_pad <- input$desv_pad #input do desvio padrao alfa <- input$alfa #% determinado pelo usuario beta <- input$beta #% determinado pelo usuario delta <- input$delta v$data <- c(n, Xb_teo,med, desv_pad, alfa, beta, delta) }) }) observeEvent(input$reset, { v$data <- NULL }) output$saida <- renderTable({ if(is.null(v$data)) return() v$data }) } shinyApp(ui = ui, server = server) A: There are lot of undefined variables in your code. I have replaced them with constants for now. Put output$saida outside observeEvent. Try this app : library(shiny) ui <- fluidPage( sidebarLayout( sidebarPanel("Inputs", numericInput(inputId = "media", label = "Mean:", value = 0, min = 0), numericInput(inputId = "desv_pad", label = "Standard Deviation:", value = 1, min = 0), numericInput(inputId = "delta", label = "Mean Shift:", value = 0.5, min = 0, max = 2, step = 0.25), numericInput(inputId = "n", label = "Size of Samples:", value = 5, min = 0, max = 10, step = 1), numericInput(inputId = "alfa", label = "% alpha", value = 0.27, min = 0, step = 0.1), numericInput(inputId = "beta", label = "% beta:", value = 97, min = 0, step = 0.1), numericInput(inputId = "xb_teo", label = "%X max:", value = 10, min = 0), actionButton("rodar", "Run") ), mainPanel( tags$h4( tableOutput('saida')), tags$br(), tags$br(), tags$br(), tags$br(), tags$br(), tags$br(), actionButton("reset", "Reset") ) ) ) server <- function(input, output) { v <- reactiveValues(data = NULL) observeEvent(input$rodar,{ passo_n <- 0 #Recebendo os inputs: n <-input$n Xb_teo <- input$xb_teo# input Xbarra percentual teorico definido pelo usuario med<- input$media #input da media desv_pad <- input$desv_pad #input do desvio padrao alfa <- input$alfa #% determinado pelo usuario beta <- input$beta #% determinado pelo usuario delta <- input$delta v$data <- c(n, Xb_teo,med, desv_pad, alfa, beta, delta) }) observeEvent(input$reset, { v$data <- NULL }) output$saida <- renderTable({ v$data }) } shinyApp(ui = ui, server = server)
doc_23536740
As said in the docs: The notification parameter with predefined options indicates that GCM will display the message on the client app’s behalf if the client app implements GCMListenerService on Android However I have trouble getting that to work even though the GCMListenerService is implemented. AndroidManifest.xml <receiver android:name="com.google.android.gms.gcm.GcmReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND" > <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> <category android:name="cz.kubaspatny.pushservertest" /> </intent-filter> </receiver> <service android:name="cz.kubaspatny.pushservertest.gcm.CustomGcmListenerService" android:exported="false" > <intent-filter> <action android:name="com.google.android.c2dm.intent.RECEIVE" /> </intent-filter> </service> CustomGcmListenerService.java public class CustomGcmListenerService extends GcmListenerService { @Override public void onMessageReceived(String from, Bundle extras) { super.onMessageReceived(from, extras); Log.d("GcmListenerService", "Received gcm from " + from + " with bundle " + extras.toString()); } } The notification from server is logged but not shown by GCM. Received gcm from 333813590000 with bundle Bundle[{notification={"icon":"ic_launcher.png","body":"great match!","title":"Portugal vs. Denmark"}, collapse_key=do_not_collapse}] The message sent from server: { "registration_ids":[...], "data": { "notification" : { "body" : "great match!", "icon" : "ic_launcher.png", "title" : "Portugal vs. Denmark" } } } Is there anything else needed to be done to allow the automatic display? A: Try making the notification field a sibling of the data field. The data field is passed to onMessageReceived and the notification field is used to automatically generate the notification. { "registration_ids":[...], "notification" : { "body" : "great match!", "icon" : "ic_launcher.png", "title" : "Portugal vs. Denmark" } }
doc_23536741
What I tried / found: 1.) I already read some of the linked answer to this response, but it seems everytime a quite unique solution to a general problem. 2.) It is surely no problem of '~' & lm-/glm-function. 3.) I tried other summary functions offered by qwraps2 and searched for typos or misleading signs (to exclude kind of problems like in 2.)..) This is my code: #### begin # created combined variable tbl4 <- tbl4 %>% mutate(perc_total = (tbl4$image == 1 | tbl4$image == 2)) # table input img_type <- list("Title" = list((tbl4$house)), "Title 01" = list("CT, n (%)" = ~ perc_n(image == "1"), "MR, n (%)" = ~ perc_n(image == "2")), "Title 02" = list("% of total" = ~ perc_n(perc_total), "%CT" = ~ perc_n(ct == "1"), "%MR" = ~ perc_n(mr == "1")) ) table_img_type <- summary_table(tbl4, img_type) #### end Note: all variables are factors & all NA are excluded. As I am an absolute beginner & as I am sitting here since a while, I'll be very thankful for any sort of help... Thanks in advance! A: The issue is with the "Title" element of img_type. list((tbl4$house)) is not a function and thus the error. My guess at what you are looking for is to label columns. If that is the case then try this: img_type <- list( "Title 01" = list("CT, n (%)" = ~ perc_n(image == "1"), "MR, n (%)" = ~ perc_n(image == "2")), "Title 02" = list("% of total" = ~ perc_n(perc_total), "%CT" = ~ perc_n(ct == "1"), "%MR" = ~ perc_n(mr == "1")) ) summary_table(tbl4, img_type, by = "house")
doc_23536742
(The script reads a list list ob subfolders in a directory and checks if any of the subfolders appear in a file.) Here is my script: set searchFile to "/tmp/output.txt" set theCommand to "/usr/local/bin/pdftotext -enc UTF-8 some.pdf" & space & searchFile do shell script theCommand tell application "Finder" set companies to get name of folders of folder ("/path/" as POSIX file) end tell repeat with company in companies set theCommand to "grep -c " & quoted form of company & space & quoted form of searchFile try do shell script theCommand set CompanyName to company as string return CompanyName on error end try end repeat return false The problem is e.g. with strings with umlauts. "theCommand" is somehow differently encoded that when I do it on the CLI directly. $ grep -c 'Württemberg' '/tmp/output.txt' --> typed on command line 3 $ grep -c 'Württemberg' '/tmp/output.txt' --> copy & pasted from AppleScript 0 $ grep -c 'rttemberg' '/tmp/output.txt' --> no umlauts, no problems 3 The "ü" from the first and the second line are different; a echo 'Württemberg' | openssl base64 shows this. I tried several encoding tricks at different places, basically everything I could find or think of. Does anyone have any idea? How can I check which encoding a string has? Thanks in advance! Sebastian A: Overview This can work by escaping each character that has an accent in each company name before they are used in the grep command. So, you'll need to escape each one of those characters (i.e. those which have an accent) with double backslashes (i.e. \\). For example: * *The ü in Württemberg will need to become \\ü *The ö in Königsberg will need to become \\ö *The ß in Einbahnstraße will need to become \\ß Why is this necessary: These accented characters, such as a u with diaeresis, are certainly getting encoded differently. Which type of encoding they receive is difficult to ascertain. My assumption is that the encoding pattern used begins with a backslash - hence why escaping those characters with backslashes fixes the issue. Consider the u with diaeresis in the previous link, it shows that for the C/C++ language the ü is encoded as \u00FC. Solution In the complete script below you'll notice the following: * *set accentedChars to {"ü", "ö", "ß", "á", "ė"} has been added to hold a list of all characters that will need to be escaped. You'll need to explicitly state each one as there doesn't seem to be a way to infer whether the character has an accent. *Before assigning the grepcommand to theCommand variable we firstly escape the necessary characters via the line reading: set company to escapeChars(company, accentedChars) As you can see here we are passing two arguments to the escapeChars sub-routine, (i.e. the non-escaped company variable and the list of accented characters). *In the escapeChars sub-routine we iterate over each char in the accentedChars list and invoke the findAndReplace sub-routine. This will escape any instances of those characters with backslashes found in the company variable. Complete script: set searchFile to "/tmp/output.txt" set accentedChars to {"ü", "ö", "ß", "á", "ė"} set theCommand to "/usr/local/bin/pdftotext -enc UTF-8 some.pdf" & ¬ space & searchFile do shell script theCommand tell application "Finder" set companies to get name of folders of folder ("/path/" as POSIX file) end tell repeat with company in companies set company to escapeChars(company, accentedChars) set theCommand to "grep -c " & quoted form of company & ¬ space & quoted form of searchFile try do shell script theCommand set CompanyName to company as string return CompanyName on error end try end repeat return false (** * Checks each character of a given word. If any characters of the word * match a character in the given list of characters they will be escapd. * * @param {text} searchWord - The word to check the characters of. * @param {text} charactersList - List of characters to be escaped. * @returns {text} The new text with the item(s) replaced. *) on escapeChars(searchWord, charactersList) repeat with char in charactersList set searchWord to findAndReplace(char, ("\\" & char), searchWord) end repeat return searchWord end escapeChars (** * Replaces all occurances of findString with replaceString * * @param {text} findString - The text string to find. * @param {text} replaceString - The replacement text string. * @param {text} searchInString - Text string to search. * @returns {text} The new text with the item(s) replaced. *) on findAndReplace(findString, replaceString, searchInString) set oldTIDs to text item delimiters of AppleScript set text item delimiters of AppleScript to findString set searchInString to text items of searchInString set text item delimiters of AppleScript to replaceString set searchInString to "" & searchInString set text item delimiters of AppleScript to oldTIDs return searchInString end findAndReplace Note about current counts: Currently your grep pattern only reports the number of lines that the word was found on. Not how many instances of the word were found. If you want the actual number of instances of the word then use the -o option with grep to output each occurrence. Then pipe that to wc with the -l option to count the number of lines. For example: grep -o 'Württemberg' /tmp/output.txt | wc -l and in your AppleScript that would be: set theCommand to "grep -o " & quoted form of company & space & ¬ quoted form of searchFile & "| wc -l" Tip: If your want to remove the leading spaces in the count/number that gets logged then pipe it to sed to strip the spaces: For example via your script: set theCommand to "grep -o " & quoted form of company & space & ¬ quoted form of searchFile & "| wc -l | sed -e 's/ //g'" and the equivalent via the command line: grep -o 'Württemberg' /tmp/output.txt | wc -l | sed -e 's/ //g'
doc_23536743
https://fullcalendar.io/js/fullcalendar-3.6.2/demos/external-dragging.html Is there a way to get it to work? I tried adding the jQueryUI Touch Punch library, which made it work in some mobile browsers but not all of them.
doc_23536744
Getting title and meta tags from external website A: Personally, I would choose to tackle this with the very nice Requests, BeautifulSoup, and LXML libraries. Assuming we have the following model in models.py, we could override the save() method to populate the title, description, and keywords attributes: from bs4 import BeautifulSoup import requests from django.db import models class Link(models.Model): url = models.URLField(blank=True) title = models.CharField(max_length=20, blank=True) description = models.TextField(blank=True) keywords = models.TextField(blank=True) def save(self, *args, **kwargs): if self.url and not (self.title or self.keywords or self.description): # optionally, use 'html' instead of 'lxml' if you don't have lxml installed soup = BeatifulSoup(requests.get(self.url).content, "lxml") self.title = soup.title.string meta = soup.find_all('meta') for tag in meta: if 'name' in tag.attrs and tag.attrs['name'].lower() in ['description', 'keywords']: setattr(self, tag.attrs['name'].lower(), tag.attrs['content']) super(Link, self).save(*args, **kwargs) The logic from the overridden save() method could very well live in a view or utility function or even in another method on the Link model that could be called conditionally. The above works with Django 1.4. No guarantees, but it should work on earlier versions as well. Edit: Fix syntax error and mention alternative parser, thanks @jinesh and @stonefury. A: The answer by jnovinger basically works for me in Django 1.5, but I had to make a few adjustments. First, there seems to be a typo in the code itself. The line soup = BeatifulSoup(requests.get(self.url).contents, "lxml") raised AttributeError: 'Response' object has no attribute 'contents'. Based on the Requests documentation, I believe the correct attribute is requests.get(self.url).content, although requests.get().text also seems to work. I tried implementing this in a simple script first before putting it in my Django project, and in this case I also obtained the following error: requests.exceptions.MissingSchema: Invalid URL u'www.example.com/': No schema supplied This was due to naively not including http:// before the url. In Django this is done automatically, but I mention this in case another beginner makes the same mistake and doesn't understand what is meant by 'missing schema.' The final problem I encountered was due to lack of validation of content length. When the inspected link yielded title, keyword or details fields that were longer than the limits of the Field objects in the model (the max_length argument), this caused DatabaseErrors when trying to save new Links. DatabaseError: value too long for type character varying(20) Here is my rough fix; there may be better approaches but this seems to work. from bs4 import BeautifulSoup import requests from django.db import models class Link(models.Model): url = models.URLField(blank=True) title = models.CharField(max_length=100, blank=True) description = models.TextField(blank=True) keywords = models.TextField(blank=True) def save(self, *args, **kwargs): if self.url and not (self.title or self.keywords or self.description): soup = BeautifulSoup(requests.get(self.url).content, "lxml") limit = self._meta.get_field('title').max_length # check field max_length self.title = soup.title.string[:limit] # limit title to max_length meta = soup.find_all('meta') for tag in meta: if 'name' in tag.attrs and tag.attrs['name'].lower() in ['description', 'keywords']: field = tag.attrs['name'].lower() # check whether description or keywords limit = self._meta.get_field(field).max_length # check field max_length content = tag.attrs['content'][:limit] # limit field to max_length setattr(self, tag.attrs['name'].lower(), content) super(Link, self).save(*args, **kwargs) Note that this will simply cut off titles, descriptions, and keyword lists mid-word rather than stopping at the last completed word, so you may end up with nonsensical word fragments.
doc_23536745
NimMessage receiveMessage(Clientconnection client) throws NimServerException { NimMessage request = null; while (request == null){ request = (NimMessage) client1.toserver.pollLast(); //read from queue } //log("\n" + request.toString()); return request; } I enter the methodd with this NimMessage request = receiveMessage(client1); But when i want the second client to read the second queue with request = receiveMessage(client2); The receiveMessage method just reads from the client1 queue. I cant figure out how to add the second queue in the receiveMessage method.
doc_23536746
Define structs with tags named env: type Env struct { Port string `env:"PORT"` } Call some function which will get the environment variable names using os.Getenv and put set it in the struct. Right now, I have this: package main import ( "fmt" "os" "reflect" ) func ParseEnv(t interface{}, v interface{}) { it := reflect.TypeOf(t) for i := 0; i < it.NumField(); i++ { field := it.Field(i) value := os.Getenv(field.Tag.Get("env")) if value == "" { continue } reflect.ValueOf(v).Elem().FieldByName(field.Name).SetString(value) } } type Env struct { Port string `env:"PORT"` DatabaseURL string `env:"DATABASE_URL"` } func main() { os.Setenv("PORT", "8080") os.Setenv("DATABASE_URL", "postgres://user:pass@host:5432/my-db") env := Env{} ParseEnv(env, &env) fmt.Println(env) } http://play.golang.org/p/b8uPPVo4aV But, as you can see, I have to pass both the reference and the pointer to my function. While this works, it is very ugly (at least I think it is). If I try to pass the pointer only, I can't get the type right (because it will be an *interface{}) and, if I pass only the reference, I can't set the values using reflect (even if I could, it would not work). Is there a sane way of doing this? A: Below is a "saner" way of doing what you want. You will notice that, instead of passing in two copies of the struct, we only need a pointer to the struct. func ParseEnv(val interface{}) { ptrRef := reflect.ValueOf(val) if ptrRef.Kind() != reflect.Ptr { panic("pointer to struct expected") } ref := ptrRef.Elem() if ref.Kind() != reflect.Struct { panic("pointer to struct expected") } refType := ref.Type() for i := 0; i < refType.NumField(); i++ { field := refType.Field(i) value := os.Getenv(field.Tag.Get("env")) if value == "" { continue } ref.Field(i).SetString(value) } } The above function should be invoked in the following way: ParseEnv(&env) Example: https://play.golang.org/p/_BwWz2oUql
doc_23536747
The problem is that When i go to the console I only see an empty array. But the weird part is that in the html file, the data is loaded in from the "empty" array.Only in the .html file the array is filled in but not in the .ts one. So in the .ts file the array is empty, but in the .html file there is data in the array. The image of the console and the filled in For loop are down below, the first log is the empty array, the second output is the one from the subscribe method. Kind regards Brian Console empty array through getter component.ts: import {Component, OnInit} from '@angular/core'; import {IStageopdracht} from '../../shared/stageopdracht'; import {StagevoorstellenService} from './coordinatorStagevoorstellen.service'; @Component({ selector: 'coordinator-stagevoorstellen', moduleId: module.id, templateUrl: 'coordinatorStagevoorstellen.component.html', styleUrls: ['../../assets/css/in/content.css'] }) /* tslint:disable */ export class CoordinatorStagevoorstellenComponent implements OnInit{ listRichtingFilter: String = 'AON';//TEST listStatusFilter: String = 'NogTeKeuren';//TEST stagevoorstellen: IStageopdracht[] = []; errorMessage: String; constructor(private _stagevoorstellenService: StagevoorstellenService){ } ngOnInit(): void { this._stagevoorstellenService.getStagevoorstellen() .subscribe(stagevoorstellen => this.stagevoorstellen = <IStageopdracht[]>stagevoorstellen, error => this.errorMessage = <any>error); } getStagevoorstellen(): IStageopdracht[]{ return this.stagevoorstellen; } component.html: <div id="title"> <span>Stagevoorstellen</span> </div> <div style="display: table-row" id="stagevoorstelDropdown"> <div style="display: table-cell"> <b>Voorkeur afstudeerrichting</b> <select #selectedStatus (change)="checkStatus(selectedStatus.value)"> <option value= "NogTeKeuren">Nog te keuren</option> <option value= "Afgekeurd" >Afgekeurd</option> </select> </div> <div style="display: table-cell"> <b>Afstudeerrichting</b> <select #selectedRichting (change)="checkRichting(selectedRichting.value)"> <option value= "AON">Applicatieontwikkeling</option> <option value= "SWM">Softwaremanagement</option> <option value= "SNB">System and networks</option> </select> </div> </div> <div id="content"> <table> <thead> <tr > <th>Naam Bedrijf</th> <th>Gemeente</th> <th>Opdracht</th> <th>Omgeving</th> <th>Meer</th> </tr> </thead> <tbody> <tr *ngFor="let voorstel of stagevoorstellen | stagevoorstellenRichtingFilter : listRichtingFilter | stagevoorstellenStatusFilter : listStatusFilter"> <td>{{ voorstel.Omschrijving }}</td> <td>{{ voorstel.Gemeente }}</td> <button>Info opdracht</button> <td> <ul> <li>{{ voorstel.Onderzoeksthema }}</li> </ul> </td> <a class="btn btn-default" [routerLink]="['/voorstel',voorstel.StageopdrachtId]"> <i class="glyphicon glyphicon-chevron"></i>Meer </a> </tr> </tbody> </table> </div> .ts file where I use the get method import { ActivatedRoute, Router} from '@angular/router'; import {Component, OnInit} from '@angular/core'; import {IStageopdracht} from '../../shared/stageopdracht'; import {CoordinatorStagevoorstellenComponent} from './coordinatorStagevoorstellen.component'; @Component({ selector: 'coordinator-stagevoorstellenDetail', moduleId: module.id, templateUrl: 'coordinatorStagevoorstellenDetail.component.html', styleUrls: ['../../assets/css/in/content.css'] }) export class CoordinatorStagevoorstellenDetailComponent implements OnInit{ pageTitle: String = 'Stagevoorstel details:'; voorstellen: IStageopdracht[] = []; voorstel: IStageopdracht; constructor(private _route: ActivatedRoute, private _router: Router, private _stageV: CoordinatorStagevoorstellenComponent){ } ngOnInit(): void { console.log(+this._route.snapshot.params['id']); let id = +this._route.snapshot.params['id']; this.pageTitle += " " + id; this.voorstellen = this._stageV.getStagevoorstellen(); // This is where it returns an empty array console.log(this._stageV.getStagevoorstellen()); //This is the console this.findVoorstel(id); } findVoorstel(id: number): void { this.voorstel = this.voorstellen[id - 1]; }
doc_23536748
I tried a few things but nothing is working quite the way I want it to... in some cases, a sentence or the article may begin with "Lake" so there is no text before it. In some cases, the proper name may be 3 words (Lake St. Clair or Red Hawk Lake). Example code to work with: text <- paste("Lake Erie is located on the border of the United States and Canada.", "It is located nearby to Lake St. Clair and Lake Michigan.", "All three lakes have a history of high levels of Phosphorus.", "One lake that has not yet been impacted is Lake Ontario.") This was maybe the closest I got-- pulling from another stack overflow but it's still not working out. context <- function(text){splittedText <-strsplit(text,'',T) print(splitted Text) data.frame(before = head(c('',splittedText),-1),words=splittedText,after=tail(c(splittedText,''),-1))} info <- context(text) print(subset(info, words == 'Lake') I would like to get either: 1) the proper lakes names extracted ("Lake Erie", "Lake St. Clair", etc.) OR 2) a dataframe with the words before and after "Lake". Ideally the first but I'm flexible at this point. before <- c("","nearby to", "Clair and","impacted is") Lake <- c("Lake","Lake","Lake","Lake") after <- c("Erie is","St. Clair", "Michigan ","Ontario ") output <- data.frame(cbind(before,Lake,after)); print(output) Thanks in advance for the help! A: You need to define some rules to extract words based on the data you have. Here I get the first word after the word "Lake". stringr::str_extract_all(text, "Lake \\w+")[[1]] #[1] "Lake Erie" "Lake St" "Lake Michigan" "Lake Ontario" Or similarly in base R regmatches(text, gregexpr("Lake \\w+", text))[[1]] For the given text this almost works except for "Lake St. Clair" where it misses "Clair" part. To handle this we could have defined another rule where in case there is a dot after the next word of "Lake", we extract two words but this would fail for "Lake Michigan" and "Lake Ontario" since they have full-stop following the word. A: With stringi, we can use library(stringi) stri_extract_all_regex(text, "Lake\\s+\\w+")[[1]] #[1] "Lake Erie" "Lake St" "Lake Michigan" "Lake Ontario" Or using str_match_all library(stringr) str_match_all(text, "Lake\\s+\\w+")[[1]][,1]
doc_23536749
I created a series of Fragments within a single main Activity. In each Fragment is either a form for data collection, or a ListView for displaying the colelcted data. The data manipulation is controlled by the listener methods of several widgets and the data model behind the scenes. Basically I am using the data collection Fragment to store data in an SQLite database, which is then queried upon travel to a display fragment. The display fragments have buttons for returning to the collection fragments to add, edit, or delete a selected item. In the case of an add/edit button press I would in certain states send a bundle which could be filled differently based on the needs of the user. Typically a bundle contains information sent from a parent context to a child context upon which the child unpacks the bundle and places data in text fields and/or sets spinners containing static data. I tried using an over complicated approach where I created a new Bundle directly inside whatever widget listener was being used. But I found that it was creating unnecessary complexity in the following Fragment where I would need to test for keys contained within the Bundles from several different possible origins. The thought was that inside the beginning of any Fragment I would call Bundle bundle = this.getArguments() Which would set bundle to whichever Bundle was passed in: fragment.setArguments(*bundle based on conditions*) so from this flow I had to create an incredibly long and hard to read succession of if-conditionals looking for specific keys based on bundle.isEmpty() which of course throws a NullPointerException if you're arriving at that Fragment for the first time and no bundle has been sent yet. Then to compound the nightmare I threw all of this in a try-catch to handle the bundle.isEmpty() null pointer, which, I tried to use as an indicator of current state (/sigh... I know). What I would like to do is use Bundle savedInstanceState for any traffic of info/state to a new Fragment. So ideally I would only ever have to access one Bundle and test for containing keys. Then it seems that I would be able to test for whether or not savedInstanceState is null and set it somehow. The problem is that I have these widgets in my Fragments which I am using to interact with my model and possibly navigate to the next necessary Fragment. If I use savedInstanceState within an onClick listener method of one of the widgets, I am forced to make it final which promptly removes my ability to use savedInstanceStatein any other scope but the initial usage of it or at least that is my understanding. This causes NullPointerException errors when I try to access savedInstanceStateoutside of the first scope. If I remove final the IDE tells me (correctly so) that I cannot access savedInstanceState from within an inner class, which in my case is several widgets to which I have attached listener methods. I have read: Are the bundles in android permanent in saving activity states ? How to use the anonymous inner class? How to use Outer Method's input in Anonymous Inner Class? Here is a code example of two Fragments reliant upon sending Bundles to each other; The display and select class: public class Row_main extends Fragment { Spinner location_spinner; Button add_row_btn,edit_row_button,delete_row_btn; ListView row_list_holder; StorageHandler sh; List<Row> row_list; ArrayAdapter<CharSequence> ls_adapter; String [] location_test_values = {"test_location"}; boolean has_items; public Row_main() { //default constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) { if(savedInstanceState == null) { //this will satisfy if arriving here from navigation menu. //I would like to set savedInstanceState here if null. savedInstanceState = new Bundle(); //but I get error: 'cannot assign a value to final variable' } getActionBar().setTitle("Row"); //Create view final View v = inflater.inflate(R.layout.row_main_layout, container, false); add_row_btn = (Button) v.findViewById(R.id.add_row_btn); edit_row_button = (Button) v.findViewById(R.id.edit_row_btn); delete_row_btn = (Button) v.findViewById(R.id.delete_row_btn); add_row_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addRow fragment = new addRow(); FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); fragment.setArguments(savedInstanceState); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, fragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); getActionBar().setTitle("Add Row"); } }); edit_row_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for(int i=0; i<row_list.size(); i++) { if(row_list.get(i).isSelected()) { row_list.get(i).setEdited(true); addRow fragment = new addRow(); savedInstanceState.putStringArrayList("current_row",row_list.get(i).getList()); fragment.setArguments(savedInstanceState); FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, fragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); getActionBar().setTitle("Add Row"); } } } }); return v; } private ActionBar getActionBar() { return ((AppCompatActivity) getActivity()).getSupportActionBar(); } and here is the data collect form class: public class addRow extends Fragment { IdGenerator generator; String new_id; AlertDialog.Builder alertDialogBuilder, fmdDialogBuilder; EditText row_name, rack_name, tile_location, tile_name, separation, bf_offset; Spinner object_type, direction, rotation; ArrayAdapter<CharSequence> objType_adapter, direction_adapter, rotation_adapter; String[] objtype_values = {"Rack","FMD"}; String[] direction_values = {"Right","Left"}; String[] rotation_values = {"0","90","180","270"}; int RACK = 0,FMD = 1,RIGHT = 0,LEFT = 1; Row current_row; ArrayList<String> list_to_unpack; Button save_row_btn, add_btn, cancel_btn; public addRow() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) { // Inflate the layout for this fragment View v = inflater.inflate(R.layout.add_row_layout, container, false); generator = new IdGenerator(); new_id = generator.randomString(5); if(savedInstanceState != null) { //Bundle passed, edit button was used, unpack if (savedInstanceState.containsKey("current_row")) { Log.d("BUNDLE-CONTENTS", "" + savedInstanceState.size()); list_to_unpack = savedInstanceState.getStringArrayList("current_row"); current_row.setId(list_to_unpack.get(0)); current_row.setRow_name(list_to_unpack.get(1)); current_row.setObject_type(list_to_unpack.get(2)); current_row.setRack_name(list_to_unpack.get(3)); current_row.setTile_location(list_to_unpack.get(4)); current_row.setTile_name(list_to_unpack.get(5)); current_row.setDirection(list_to_unpack.get(6)); current_row.setRotation(list_to_unpack.get(7)); current_row.setSeparation(list_to_unpack.get(8)); current_row.setBf_offset(list_to_unpack.get(9)); current_row.setEdited(true); row_name.setText(current_row.getRow_name()); if (current_row.getObject_type().equalsIgnoreCase("Rack")) { object_type.setSelection(RACK); } else { object_type.setSelection(FMD); } rack_name.setText(current_row.getRack_name()); tile_location.setText(current_row.getTile_location()); tile_name.setText(current_row.getTile_name()); if (current_row.getDirection().equalsIgnoreCase("Right")) { direction.setSelection(RIGHT); } else { direction.setSelection(LEFT); } switch(current_row.getRotation()) { case "0": rotation.setSelection(0); break; case "90": rotation.setSelection(1); break; case "180": rotation.setSelection(2); break; case "270": rotation.setSelection(3); break; } separation.setText(current_row.getSeparation()); bf_offset.setText(current_row.getBf_offset()); } } row_name = (EditText) v.findViewById(R.id.rowName_value); rack_name = (EditText) v.findViewById(R.id.rackName_value); tile_location = (EditText) v.findViewById(R.id.tileLoc_value); tile_name = (EditText) v.findViewById(R.id.tileName_value); separation = (EditText) v.findViewById(R.id.separation_value); bf_offset = (EditText) v.findViewById(R.id.bfOffset_value); object_type = (Spinner) v.findViewById(R.id.obj_type); direction = (Spinner) v.findViewById(R.id.direction); rotation = (Spinner) v.findViewById(R.id.rotation_spinner); objType_adapter = new ArrayAdapter<CharSequence>(this.getActivity(), android.R.layout.simple_spinner_dropdown_item, objtype_values); direction_adapter = new ArrayAdapter<CharSequence>(this.getActivity(), android.R.layout.simple_spinner_dropdown_item, direction_values); rotation_adapter = new ArrayAdapter<CharSequence>(this.getActivity(), android.R.layout.simple_spinner_dropdown_item, rotation_values); object_type.setAdapter(objType_adapter); direction.setAdapter(direction_adapter); rotation.setAdapter(rotation_adapter); save_row_btn = (Button) v.findViewById(R.id.save_row_btn); add_btn = (Button) v.findViewById(R.id.add_btn); cancel_btn = (Button) v.findViewById(R.id.cancel_btn); alertDialogBuilder = new AlertDialog.Builder(getActivity()); fmdDialogBuilder = new AlertDialog.Builder(getActivity()); alertDialogBuilder.setMessage("Add Rack or FMD:"); fmdDialogBuilder.setMessage("Add Power Providing or Power Consuming FMD:"); alertDialogBuilder.setNegativeButton("Rack", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //if user selects power providing fmd //send id with it //StorageHandler sh = new StorageHandler(getActivity()); Row row = new Row( new_id, row_name.getText().toString(), object_type.getSelectedItem().toString(), rack_name.getText().toString(), tile_location.getText().toString(), tile_name.getText().toString(), direction.getSelectedItem().toString(), rotation.getSelectedItem().toString(), separation.getText().toString(), bf_offset.getText().toString()); ArrayList<String> rowList = row.getList(); for(String i : rowList) { Log.d("ADD ROW BTN","rowList[i]=" + i); } savedInstanceState.putStringArrayList("current_row", rowList); addRack fragment = new addRack(); fragment.setArguments(savedInstanceState); FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, fragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); getActionBar().setTitle("Add Rack to: " + row.getRow_name()); } }); alertDialogBuilder.setPositiveButton("FMD", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //todo choice between consuming and providing fmdDialogBuilder.show(); } }); fmdDialogBuilder.setPositiveButton("Providing", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Row row = new Row( new_id, row_name.getText().toString(), object_type.getSelectedItem().toString(), rack_name.getText().toString(), tile_location.getText().toString(), tile_name.getText().toString(), direction.getSelectedItem().toString(), rotation.getSelectedItem().toString(), separation.getText().toString(), bf_offset.getText().toString()); ArrayList<String> obj_as_list = row.getList(); Log.d("newId", obj_as_list.get(0)); Log.d("row_name", obj_as_list.get(1)); Log.d("object_type", obj_as_list.get(2)); Log.d("rack_name", obj_as_list.get(3)); Log.d("objaslistsize", ""+obj_as_list.size()); savedInstanceState.putStringArrayList("current_row", obj_as_list); addPowerProvidingFMD fragment = new addPowerProvidingFMD(); fragment.setArguments(savedInstanceState); FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, fragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); getActionBar().setTitle("add FMD to: " + row_name.getText().toString()); } }); fmdDialogBuilder.setNegativeButton("Consuming", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Row row = new Row( new_id, row_name.getText().toString(), object_type.getSelectedItem().toString(), rack_name.getText().toString(), tile_location.getText().toString(), tile_name.getText().toString(), direction.getSelectedItem().toString(), rotation.getSelectedItem().toString(), separation.getText().toString(), bf_offset.getText().toString()); ArrayList<String> obj_as_list = row.getList(); savedInstanceState.putStringArrayList("current_row", obj_as_list); addPowerConsumingFMD fragment = new addPowerConsumingFMD(); fragment.setArguments(savedInstanceState); FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, fragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); getActionBar().setTitle("add FMD to: " + row_name.getText().toString()); } }); save_row_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //save row info to database StorageHandler sh = new StorageHandler(getActivity()); if(current_row.isEdited()) { //update row String current_id = current_row.getId(); Log.d("*update row*", "id=" + current_id); //get updated values from fields, send to database Row row = new Row(current_id, row_name.getText().toString(), object_type.getSelectedItem().toString(), rack_name.getText().toString(), tile_location.getText().toString(), tile_name.getText().toString(), direction.getSelectedItem().toString(), rotation.getSelectedItem().toString(), separation.getText().toString(), bf_offset.getText().toString()); sh.updateRow(row); sh.close(); } else { //save new row Log.d("*save row*", "id=" + new_id); //save row to database sh.addRow(new Row(new_id, row_name.getText().toString(), object_type.getSelectedItem().toString(), rack_name.getText().toString(), tile_location.getText().toString(), tile_name.getText().toString(), direction.getSelectedItem().toString(), rotation.getSelectedItem().toString(), separation.getText().toString(), bf_offset.getText().toString())); sh.close(); } Row_main fragment = new Row_main(); FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, fragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); getActionBar().setTitle("Row"); } }); add_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialogBuilder.show(); } }); cancel_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Row_main fragment = new Row_main(); FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, fragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); getActionBar().setTitle("Row"); } }); return v; } private ActionBar getActionBar() { return ((AppCompatActivity) getActivity()).getSupportActionBar(); } I would like to use Bundles here since it is not important to restore anything from a Bundle if the user leaves the app or presses the back Button. Am I going about this right? what should I do about the final Bundle situation in onClickListener methods? I absolutely need to pass Bundles from them the way I have things setup now and I would like to use the same Bundle if I can. I have a deadline to consider so a complete overhaul might be out of the question. Any input is greatly appreciated. A: I think it'll be easier to isolate your data-passing problems once you refactor some code. 1. Replace these similar blocks with a method. You seem to have copied this same chuck of code about five times. Make it a method! Call it getRow(), give it a parameter, if you have to, like for the int id. // int id = <some_value>; return new Row(id, row_name.getText().toString(), object_type.getSelectedItem().toString(), rack_name.getText().toString(), tile_location.getText().toString(), tile_name.getText().toString(), direction.getSelectedItem().toString(), rotation.getSelectedItem().toString(), separation.getText().toString(), bf_offset.getText().toString()); 2. Now, it seems you are passing around this Row class, so suggested to make that implement Parcelable so you can more easily pass that between Bundles when the need arises. 3. Next, you should let the Fragment interactions happen across the Activity boundary, not from within each Fragment. So, you add interfaces, for example. You can split this into many interfaces, if you do not need all this functionality. public interface OnRowInteractionListener { public void onRowAdded(Row row); public void onRowEdited(Row row); public void onRowRemoved(Row row); public void onRowActionCancel(); } 3a. Implement onAttach of the Fragment class(es) to set these interfaces. private OnRowInteractionListener mListener; @Override public void onAttach(Context context) { super.onAttach(context); final String contextName = context.class.getSimpleName(); try { mListener = (OnRowInteractionListener) context; } catch (ClassCastException e) { throw new ClassCastException(contextName + " must implement OnRowInteractionListener"); } } 3b. Now, clean up the Fragment buttons add_row_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Row added = getRow(); // remember about that parameter value if (mListener != null) mListener.onRowAdded(added); } }); 3c. In the Activity, you need to implement those interfaces after you make the class implements OnRowInteractionListener. @Override public void onRowAdded(Row row) { getActionBar().setTitle("Add Row"); // This acts like your 'constructor' AddRowFragment fragment = AddRowFragment.newInstance(row); // fragment.setArguments(savedInstanceState); getSupportFragmentManager() .beginTransaction() .replace(R.id.fragment_container, fragment) .addToBackStack(null) .commit(); } (similar for onRowEdited) 4. I also see this Fragment replacement block of code repeated for cancel and save buttons, so make that a method as well. Row_main fragment = new Row_main(); FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, fragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); getActionBar().setTitle("Row"); I would really suggest you make one really generic method in the Activity to handle all Fragment transitions. public void transitionFragment(Fragment fragment, Bundle arguments, String title) { getSupportActionBar().setTitle(title); if (arguments != null) fragment.setArguments(arguments); getSupportFragmentManager() .beginTransaction() .replace(R.id.fragment_container, fragment) .addToBackStack(null) .commit(); } Then, just pass in the respective newInstance()'d Fragment to that method whenever you need it. Optionally pass extra arguments, else, just null. So, then, you now can use that method for the previous block of code, for example, in the cancel action of the interface implementation. @Override public void onRowActionCancel() { Fragment fragment = RowMainFragment.newInstance(); transitionFragment(fragment, null, "Add Row"); } As far as the SQLite processing goes, maybe look into RealmDB, SugarORM, or really any ORM library. The findViewById code could be simplified with Butterknife. Also, the Android Data Binding library in case you are frequently mapping data to the View objects from a Java object.
doc_23536750
I need to produce a map for every day of the project in order to send the maps to people who don't have Tableau. I intend to make a slideshow with the maps displaying the change in the map over the two months. The problem is that this means creating about 60 maps. My question is: Is there a way to automate this process and automatically produce a jpg file in the map tab of my Tableau worksheet for all days in the data set? A: Can you make an animation? You can put your date element in the pages shelf and animate. From there you can create a screen capture of the animation and create a movie. If you want it to be an image, you could turn that movie into an animated gif or extract all the frames (search for ImageMagick for more on this). Here's an example of an animated map. http://apandre.wordpress.com/2014/01/12/motion-map-chart/
doc_23536751
There's Number.MIN_VALUE, but, as the name implies, that's for Number, not for int. A: Apparently, that's int.MIN_VALUE -.-
doc_23536752
doc_23536753
"Condition": { "ForAllValues:StringEquals": { "dynamodb:LeadingKeys": [ "${cognito-identity.amazonaws.com:sub}" ] } } I am designing my data structure and need to know how DynamoDB applies this scoping in the context of Scan operations. When doing a Scan, will DynamoDB apply the user scope to the table first (so the only documents scanned will be the user's documents) or will the Scan consume the whole table and then apply the policy to scope the records? The implication of this question is how efficient a scan is - if the whole table is to be scanned then the operation will be very expensive, but if only the user's own records (a small fraction of the table) are being scanned then Scans might be acceptably efficient. A: Its best practice to design your application to use Query instead of Scans. Scans are expensive and scan the entire table by definition. Per the Dynamodb Scan and Query Best Practice documentation: If possible, you should avoid using a Scan operation on a large table or index with a filter that removes many results What you are proposing is exactly this scenario. Please consider a redesign to avoid this. The IAM security piece will do the job of preventing editing of other user data, but for a single user, the scan will need to remove other users files from the scan and will be expensive.
doc_23536754
df_train[LABEL_COLUMN] = (df_train["label"].apply(lambda x: '>50K' in x)).astype(int) df_test[LABEL_COLUMN] = (df_test["label"].apply(lambda x: '>50K' in x)).astype(int) change the label column from string to int. However, it seems that this kind of operation only works well on two-classes classification data sets, i.e, yes or no, 1 or 0 problems. Now I hope to apply the wide and deep model on more classes, especially numerical data than string data. But I got TypeError: argument of type 'float' is not iterable I have also tried to delete the codes transforming label columns to int, which shown above, and I got tensorflow.contrib.learn.python.learn.monitors.NanLossDuringTrainingError: NaN loss during training. So how can I solve those problems? Can't the wide_n_deep model make use for multi-classification? A: The wide&deep estimators do support multiclass classification if you produce labels in a larger range than 0 or 1. A: You can do it on a float column : df_train[LABEL_COLUMN] = df_train["float_column"].astype(float) But I have 0.0 accuracy ... maybe this not the right answer but it shows no errors. A: If you are still looking to solve this. tf r1.1 has an argument n_classes estimator = DNNLinearCombinedClassifier( # common settings n_classes=n_classes, weight_column_name=weight_column_name, # wide settings linear_feature_columns=[sparse_feature_a_x_sparse_feature_b], linear_optimizer=tf.train.FtrlOptimizer(...), # deep settings dnn_feature_columns=[sparse_feature_a_emb, sparse_feature_b_emb], dnn_hidden_units=[1000, 500, 100], dnn_optimizer=tf.train.AdagradOptimizer(...)) n_classes: number of label classes. Default is binary classification. Note that class labels are integers representing the class index (i.e. values from 0 to n_classes-1). For arbitrary label values (e.g. string labels), convert to class indices first. Link to doc's
doc_23536755
A ListView that show list of friends. After onClick() of an item in the friend list, it will go to Activity 2 which is ProfileActivity showing the details of such friend. Activity 2 (ProfileActivity): And there is a Button, after onClick(), will go to Activity 3 (NearByActivity) which shows list of twenty nearby friends within 10km. Activity 3 (NearByActivity): After onClick() of an item, it will go to Activity 2 (ProfileActivity). The story is that from Activity 2 to Activity3, I don't want to finish() Activity 2 before start Activity because user may want to go back. So, the question is: How to finish the Activity2 if user click any item in Activity 3 so that preventing Activity 2 -> Activity 3 -> Activity 2 -> Activity 3... Although Activity 2 will call many times, the profile details is depending on which user is clicked. Or any other suggestion?? A: You can override onActivityResult() in Activity2. When you finish Activity3 just pass result to Activity2 . for Example //In Activity2 onActivityResult(ReqCode , ResultCode, Intent) { if(ResultCode == FINISH){ finish(); } else if(ResulCode == DO_SOMETHING_ELSE){ // Do Somthing } } //Activity 3 onClick1(){ setResult(FINISH); finish(); } onClick2(){ setResult(DO_SOMETHING_ELSE); finish(); } See onActivityResult here A: Use FLAG_ACTIVITY_CLEAR_TOP. If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent. A: when a button click from activity 3. just send a broadcast message (you can also use localbroadcas). and in activity 2 there will be a broadcastreceiver so if it get broadcast message containing exit command then it will finish()
doc_23536756
See the example below: $50,000 Climax Show, The Or also how do you remove the , A? Bug's Life, A A: Find & Select, Replace..., Find what: , *, Replace All. A: =IF(RIGHT(UPPER(A1),5) = ", THE",LEFT(A1,LEN(A1)-5),IF(RIGHT(UPPER(A1),3) = ", A",LEFT(A1,LEN(A1)-3),A1))
doc_23536757
code, Is this true? A: It is not true. The Import command is for the compiler only. It does not impact the compiler output in any way.
doc_23536758
async { do! port.AsyncWriteLineAsByte messange let! response = port.AsyncReadLineAsByte() return response } Where response is byte[] and method is simple as that: member this.AsyncReadLineAsByte() : Async<byte[]> = async { let buffer_ref = ref (Array.zeroCreate<byte> this.ReadBufferSize) let buffer = !buffer_ref let! read_bytes = this.BaseStream.AsyncRead(buffer, 0, this.ReadBufferSize) return buffer } And well it works, it sends and recives messages, there is one but in all this. Reading responses shold be on event of some sort. I am new to F# but i tried something like: async { let data_recived_event = port.AsyncReadLineAsByte() do! port.AsyncWriteLineAsByte messange port.DataReceived.AddHandler(data_recived_event) // it says SerialDataReciveHandler is what he expects let! response = ??? return response } But no luck, documentation is rather, for f# it just specify prototype and method construction not a practical usage. I need a event and a way to return that value , is there a way? EDIT: Ive been able to add event as serial port namespace has DataReceived.AddHandler event subscription. So now it looks: async { let data_recived() = async{ let! buffer = port.AsyncReadLineAsByte() printfn "Response from event %A" buffer // return buffer } |> fun response -> Async.RunSynchronously(response) port.DataReceived.AddHandler(fun _ _ -> data_recived()) do! port.AsyncWriteLineAsByte messange let! response = port.AsyncReadLineAsByte() return response } And it works, problem is still how to return such a value from event, if I do something like: let data_recived() = async{ let! buffer = port.AsyncReadLineAsByte() printfn "Response from event %A" buffer return buffer } |> fun response -> Async.RunSynchronously(response) port.DataReceived.AddHandler(fun _ _ -> response = data_recived()) Is says it expects uint and get bool A: I'm not an expert on how serial ports work, but you can wait for an event inside async workflow using the Async.AwaitEvent operation. So, you could write something like this: let writeAndRead () = async { let port = new SerialPort("COM1") port.Write("TEST") let mutable finished = false while not finished do let! e = port.DataReceived |> Async.AwaitEvent let data = port.ReadExisting() printfn "GOT: %A" data finished <- data.Contains("EOF") } The only caveat here is that the DataReceived event might be triggered concurrently, while you are processing the received data in the body of the loop - and then you will miss the event. I'm not sure how serial ports work and whether this can actually happen, but it could lead to problems. To address that, you could use the BlockingQueueAgent type from F# Async Extras. This would let you implement a queue of notifications - so the DataReceived handler would add notifications to the queue and you would then read them from the queue in the loop. I have not actually tested this, but I think something like this should work: let writeAndRead () = async { let queue = BlockingQueueAgent<_>(Int32.MaxValue) let port = new SerialPort("COM1") port.DataReceived.Add(fun e -> queue.Add(e)) port.Write("TEST") let mutable finished = false while not finished do let! e = queue.AsyncGet() let data = port.ReadExisting() finished <- data.Contains("EOF") } EDIT: Moved the queue event handler setup before writing any data to the port.
doc_23536759
Is it a good approach to simply use things like List<myobject> data and do something like this: data.Where((s => s.text.Substring(0,3) == expected));? Are there anything I can do regarding database optimization (like indexing) when I use this method? A: TL;DR I suggest evaluating your requirements. If using a simple List<> meets your requirements and you are happy with performance results of profiling your application then use it. If not consider using an in-memory database. One of the main reason database are fast enough to retrieve data is Index. When you use common C# data structures you miss this feature. I think if you are tackling with small number of records then you would not face performance problem but if you have many records then you should consider using in memory databases. Keep in mind that the chosen database may not support the way you want to index data or you have complex queries which indexing does not improve their performance. If you just have keys and corresponding values then take a look at Redis and StackExchange.Redis. Another thing to consider is concurrency! Databases usually support accessing data from multiple threads and handle multiple reader or writer on same data. You can use thread-safe collections in .NET but you have to do a lot to get features which are built in databases. A: If you are only doing prefix searches (as in the question) you can probably get away with using a list, as long as you keep it sorted and do a binary search instead of a linear one (which is what where will do). A dictionary, while much faster if you are doing exact matches, isn't the right tool here because you want to do searches which will still be O(N). If you want to use LINQ you are probably better off just using EF and SQL Server CE. This is a pretty painless option, though you are obviously adding some significant dependencies. If you want to roll your own solution in C# that will work pretty much the same way a database would the datastructure you are looking for is called a Trie[1] This still won't give you LINQ (unless you write a bunch more code) but will give you good search performance. [1]https://en.wikipedia.org/wiki/Trie A: If you are using data structure so it is better that you will use data structure with complexity of o(1) like dictionary and hash table and not list that had more slower complexity. Be aware that list is taking you some of your free memory. A: Check this test: using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace CSharpConsoleApplication.Tests { class JustATest { public static void Run() { var list = new List<Test>(); for (int i = 0; i < 1000000; i++) list.Add(new Test() { Text = "a" + i.ToString().PadLeft(6, '0') }); string input = "a011"; List<Test> found = null; // Get the results with LinQ var w = new Stopwatch(); w.Start(); found = list.Where(t => t.Text.Substring(0, 4) == input).ToList(); w.Stop(); Console.WriteLine("Search list with linq. Results count = {0}", found.Count); Console.WriteLine(w.Elapsed); Console.ReadLine(); // Store data in dictionary if no refresh needed // Populate the dictionary var objectsDictionary = new Dictionary<string, List<Test>>(); w.Restart(); PopulateDictionary(objectsDictionary, list, input.Length); w.Stop(); Console.WriteLine("Populate dictionary"); Console.WriteLine(w.Elapsed); Console.ReadLine(); // Search in dictionary w.Restart(); if (objectsDictionary.ContainsKey(input)) found = objectsDictionary[input]; //objectsDictionary[input].ForEach(t => Console.WriteLine(t.Text)); w.Stop(); Console.WriteLine("Search in dictionary. Results count = {0}", found.Count); Console.WriteLine(w.Elapsed); Console.ReadLine(); } static void PopulateDictionary(Dictionary<string, List<Test>> dictionary, List<Test> list, int textLength) { foreach (var t in list) { string text = t.Text.Substring(0, textLength); if (dictionary.ContainsKey(text)) dictionary[text].Add(t); else dictionary.Add(text, new List<Test>() { t }); } } class Test { public string Text { get; set; } } } }
doc_23536760
I want to allow user(kind of participant) to create an asset, but do it only in transaction, whereas outside of this transaction I want deny all user rights to create assets. I tried to solve it using condition in rule .acl file using function: rule UserCanCreateAssetOnlyInTransaction { description: "Deny all participants create access to all userWallets if not in transaction" participant(p): "com.example.User" operation: CREATE resource(r): "com.example.UserAsset" condition:(isInTransactionF()) action: ALLOW } Then in transaction I create variable as var isInTransaction = true;, and in logic.js file I added: /** @returns {boolean} boolean true/false */ function isInTransactionF(){ if(isInTransaction){ return true; }else{ return false; } } It doesn't work, when I call the only transaction in which create access should work, it says that the user do not have create access to submit this transaction. I guess I'm doing something wrong, is there any way to solve this problem? A: to achieve what you want in your function - you would say : /** @returns {boolean} boolean true/false */ function isInTransactionF() { var isInTransaction = true ; // Boolean if(isInTransaction) { // if( Boolean(isInTransaction)) { // alternative return true; } else{ return false; } } Your current ACL would then work. I can call console.log to see the returned result console.log("The return result is " + isInTransactionF() );` // true To restrict a participant to create an asset ONLY through a certain transaction class - the rule would look something like (ie the asset can only be created through this class - implicitly it should be denied elsewhere assuming there are no other Asset Create rules): rule CreateAssetThruTxn { description: "sample"" participant(p): "com.example.User" operation: CREATE resource(r): "com.example.UserAsset" transaction(tx): "com.example.AssetCreate" condition:(true) action: ALLOW } If your ACL is failing, then you need to see what other ACL rules could be ALLOWING the creation of this asset through another means but the rule I provided would be the usual means to control that (based on the info you provided in the question)
doc_23536761
Like detect if this link: https://github.com/jasmine/jasmine/issues is correct github issue link. Like detect if this link: https://github.com/jasmine/jasmine/pull/1801 is correct github Pull request link. Found similar question: Regular expression to match github profile urls : Regex: /^(?:http(s)?://)?[\w.-]+(?:.[\w.-]+)+[\w-._~:/?#[]@!$&'()+,;=.]+$/ A: If you want to be specific, you might use jasmine in the url followed by matching either issues or pull/ followed by 1+ digits using an alternation (?:issues|pull\/\d+) Pattern https?:\/\/github\.com\/jasmine\/jasmine\/(?:issues|pull\/\d+) Regex demo A more broad match might be repeating 1+ more times matching any char except a / or a whitspace (?:[^\/\s]+\/)+ Pattern https?:\/\/github\.com\/(?:[^\/\s]+\/)+(?:issues|pull\/\d+) Regex demo
doc_23536762
Any chance to use this type of message box from within my JS desktop app? Any code snippets available? Or can I use it from within a dos batch file? Thanks in advance
doc_23536763
controller: @GetMapping("tesget") @ResponseStatus(HttpStatus.OK) public List getTes2() throws Exception { return userService.getTes2(); } servlet: public class Servlet extends HttpServlet { public void init() throws ServletException { // Do required initialization } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>Servlet Testing</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("Welcome to the Servlet Testing Center"); out.println("</BODY>"); out.println("</HTML>"); } public void destroy() { // do nothing. } } web.xml: <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <servlet> <servlet-name>Servlet</servlet-name> <servlet-class>com.project.maven.config.Servlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Servlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> Before I created servlet and war, I running usually and when I go to localhost:8080/SpringNew/tesget, the result is true, list JSON from database, but when I create servlet, the url localhost:8080/SpringNew/tesget is wrong. the result is: Welcome to the Servlet Testing Center how to fix this problem? Thanks. Bobby A: AppInitializer.java public class AppInitializer implements WebApplicationInitializer { public void onStartup(ServletContext container) throws ServletException { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(AppConfig.class); ctx.setServletContext(container); ServletRegistration.Dynamic servlet = container.addServlet( "dispatcher", new DispatcherServlet(ctx)); servlet.setLoadOnStartup(1); servlet.addMapping("/"); } } HibernateConfiguration.java @Configuration @EnableTransactionManagement @ComponentScan({ "com.project.maven." }) @PropertySource(value = { "classpath:application.properties" }) public class HibernateConfiguration { @Autowired private Environment environment; @Bean public LocalSessionFactoryBean sessionFactory() { LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(dataSource()); sessionFactory.setPackagesToScan(new String[] { "com.project.maven.entity" }); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; } @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName")); dataSource.setUrl(environment.getRequiredProperty("jdbc.url")); return dataSource; } private Properties hibernateProperties() { Properties properties = new Properties(); properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect")); properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql")); properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql")); return properties; } @Bean @Autowired public HibernateTransactionManager transactionManager(SessionFactory s) { HibernateTransactionManager txManager = new HibernateTransactionManager(); txManager.setSessionFactory(s); return txManager; } } AppConfig.java @Configuration @EnableWebMvc @ComponentScan(basePackages = "com.project.maven") public class AppConfig extends WebMvcConfigurerAdapter { @Bean public ViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/"); viewResolver.setSuffix(".jsp"); return viewResolver; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("/static/"); registry.addResourceHandler("**/**") .addResourceLocations("classpath:/META-INF/resources/"); // harus ada folder resources di webapp/WEB-INF/ } @Bean public MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); return messageSource; } A: * *what about your other config ! *send your controller class code *if you are sure about your config try with @GetMapping("/tesget")
doc_23536764
The docs show this API request in curl curl -X POST https://sandbox.plaid.com/link/token/create -H 'Content-Type: application/json' -d '{ "client_id": "CLIENT_ID", "secret": "SECRET", "user": { "client_user_id": "unique-per-user", }, "client_name": "Plaid App", "products": ["auth"], "country_codes": ["GB"], "language": "en", "webhook": "https://sample-web-hook.com", "account_filters": { "depository": { "account_subtypes": ["checking"] } } }' How would I translate this curl request to swift - specifically in swiftUI. Thanks A: That’s a pretty specific question, and to some degree no one can answer it for you. You’ll have to write the code yourself to be able to understand and debug it when things go wrong. That being said, here’s a pretty good tutorial on how to make http post requests: https://www.appsdeveloperblog.com/http-post-request-example-in-swift/ The relevant section starts like: // Prepare URL let url = URL(string: "https://jsonplaceholder.typicode.com/todos") guard let requestUrl = url else { fatalError() } // Prepare URL Request Object var request = URLRequest(url: requestUrl) request.httpMethod = "POST" // HTTP Request Parameters which will be sent in HTTP Request Body let postString = "userId=300&title=My urgent task&completed=false"; Obviously you’ll want to use the plaid variables instead of the example. But that should get you started.
doc_23536765
private void ClientMqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e) { var msg = Encoding.UTF8.GetString(e.Message); Trace.WriteLine($"client_MqttMsgPublishReceived topic: {e.Topic} {msg}"); TaskCompletionSourceResponse.TrySetResult(msg); } The issue is the following call: Trace.WriteLine($"client_MqttMsgPublishReceived topic: {e.Topic} {msg}"); e.Message is a JSON object encoded as a byte array containing 2,669,000 bytes. It gets converted to a string msg of the same number of characters. Next, Trace.WriteLine() is called with an interpolated string as its argument, which contains the string msg. This call to Trace.WriteLine() causes Visual Studio 2019 to freeze for about a minute, making it completely unresponsive: The simplest solution seems to be to simply delete the call to Trace.WriteLine(). However, I am still interested in knowing why Visual Studio stops responding? And if there's another way to mitigate this issue? Can't Trace.WriteLine() handle too long strings?
doc_23536766
It's an app where users can make a post and comment with a notification system. Getting Resource is not in the state stackUpdateComplete error message on amplify push type User @model { id: ID! following: [User] follower: [User] post: [Post] @connection(name: "UserPost") comment: [Comment] @connection(name: "UserComment") notification: [Notification] @connection(name: "UserNotification") } type Post @model { id: ID! user: User! @connection(name: "UserPost") privacy: String! content: String! loved: [User] comment: [Comment] @connection(name: "PostComment") } type Comment @model { id: ID! user: User! @connection(name: "UserComment") content: String! loved: [User] post: Post @connection(name: "PostComment") } type Notification @model { id: ID! content: String! link: String! category: String! user: User! @connection(name: "UserNotification") } Can anyone see anything wrong on my schema file and know how to debug the error in the best way on Appsync? A: This is known to happen when there are changes to connection directives wich triggers updates DynamoDB GSI. Cloudformation has update limits for DynamoDB GSIs. Amplify team is actively working on @key directive which will replace the @connection directive. In the time being follow these steps if you're making changes to @connection directive * *Make only one change in @connection directive per push. If you want to rename a connection, first remove the connection and do a push and then add it with the new name *If a push results in failure and subsequent pushes may result in Resolver not found. This is caused by the Cloudformation implementation where a rollback removed the resolvers but did not create the original resolver. You could overcome this issue by adding missing resolvers in AppSync console. Ref: https://github.com/aws-amplify/amplify-cli/issues/1406#issuecomment-494533788
doc_23536767
Here is how my code looks like now: (I've shortened it) I have a datatable to fill in and then use it for visualization on website written in Javascript DataTable usd_table = DataTableBuilder .create("usd_final_sum") .withColumn(String.class, "Line", new ArrayList<>()) .withColumn(String.class, "Date1", new ArrayList<>()) .withColumn(String.class, "Date2", new ArrayList<>()) ... (95 rows more) .withColumn(String.class, "Date97", new ArrayList<>()) .build().get(); Then I fill it in: usd_table = usd_table.rows().addValues(cum_cash_list.get(0), cum_cash_list.get(1), ....... (95 rows more), cum_cash_list.get(98)).get(); There are 98 rows when creating and 98 rows when filling in.. Terrible.. So it works, but it is so long code. How can I shorten it? cum_cash_list consists of String values May be some List iterator or while loop, I don't know.. A: Use a for-loop: var builder = DataTableBuilder .create("usd_final_sum") .withColumn(String.class, "Line", new ArrayList<>()) //Here numRows is 98 or however many rows you have for (int i = 1; i <= numRows; i ++) { builder = builder.withColumn(String.class, "Date" + i, new ArrayList<>()); } At the end of the loop, builder will have the columns you need. Then you can say DataTable usd_table = builder.build().get(); EDIT: To fill in the database, you can just use a for-loop again. I assume that the addValues method uses varargs, so you can pass in an array: //I don't know the return type of cum_cash_list.get(int), so I'm naming it Value Value[] values = new Value[98/*or number of rows*/]; for (int i = 0; i < values.length; i ++) values[i] = cum_cash_list.get(i); usd_table = usd_table.rows().addValues(values).get(); EDIT: That var isn't a JS var, I just wasn't sure whether the type of builder would be DataTableBuilder or something else.
doc_23536768
A = 4*pi*r^2 AFt = A / 12 V = 4/3 * pi * r^3 VFt = V / 1728 Gallons of water = VFt * 7.48 The test width value is 400. This should give me the output of A = 502,400.00 AFt = 41,866.67 V = 33,493,333.33 VFt = 2,791,111.11 Gallons of Water = 20,877,511.11 Here is my code so far. The first two calculations are correct but I am having trouble correctly calculating the Volume, volume in feet, and gallons of water. Any help is much appreciated. import java.util.Scanner; public class WaterTowerCalculator { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scan = new Scanner(System.in); System.out.println("Enter the width of the sphere"); int width = scan.nextInt(); final double PI = 3.14; final double C_VARIABLE = 7.48; double w = width; double r = w/2; double A = 4*PI*r*r; double AFt = (double) A/12; double V = (4/3)*PI*(r*r*r); double VFt = (double) V/1728; double gallons = (double) VFt * C_VARIABLE; System.out.printf("Area in inches " +"%,.2f\n", A); System.out.printf("Area in feet " + "%,.2f\n", AFt); System.out.printf("Volume in inches " + "%,.2f\n", V); System.out.printf("Volume in feet " + "%,.2f\n", VFt); System.out.printf("Gallons of water " + "%,.2f\n", gallons); } } A: It looks like you're using integer division when you want floating point division. Replace e.g. 4/3 with 4.0 / 3.0.
doc_23536769
Order::with(['products'=>function($q){ $q->select('name', 'price', 'quantity')->orderBy('name','asc'); }])->paginate($length); returns all orders with their respective product data, but Order::with(['products'=>function($q){ $q->select('name', 'price', 'quantity')->orderBy('name','asc'); }])->select('pickup_date', 'pickup_time', 'remark')->paginate($length); gives me all order data I want, but an empty products array? I want to select some specific columns from the order table with some specific columns from the products table. How can I do this? FYI: Orders-products have a many-to-many relationship with models: Order Model: public function products() { return $this->belongsToMany('App\Models\Product')->withTimestamps(); } Product Model: public function orders() { return $this->belongsToMany('App\Models\Order')->withTimestamps(); } A: You need to select like this way : Order::with(['products'=>function($q){ $q->orderBy('name','asc'); }])->select('products.name as name','products.price as price','products.quantity as quantity','orders.pickup_date as pickup_date', 'orders.pickup_time as pickup_time', 'orders.remark as remark')->paginate($length); Or without sub query : Order::with('products') ->select('products.name as name','products.price as price','products.quantity as quantity','orders.pickup_date as pickup_date', 'orders.pickup_time as pickup_time', 'orders.remark as remark') ->orderBy('name','asc'); ->paginate($length); A: You are missing one thing,you should add product id in outer select. Order::with(['products'=>function($q){ $q->select('name', 'price', 'quantity')->orderBy('name','asc'); }])->select('product_id','pickup_date', 'pickup_time', 'remark')->paginate($length); I hope it would be helpful A: Try: Order::query() ->select(['pickup_date', 'pickup_time', 'remark']) ->with(['products:name,price,quantity']) ->paginate($length);
doc_23536770
Is it possible to join tables in SQL in a way that you can ORDER BY columns with the same name, such that x rows are returned, where x = the sum of rows in table 1 and table 2. To hopefully clarify what I mean, here's an example query: SELECT * FROM (combined Real and Placeholder items) ORDER BY StartDate, OnDayIndex and here's what results might look like: ID OnDayIndex StartDate ItemType Name TemplatePointer 12308 2 1996-09-18 Real Actual Name Null 10309 11 1996-09-19 Placeholder Null 123 30310 5 1996-09-20 Real Actual Name Null 30410 6 1996-09-20 Placeholder Null 456 My use case is a calendar application with recurring events. To save space, it doesn't make sense to store every recurrence of an event. If it weren't for the particulars of my use case I'd just store a template with a rule and recurring events would be generated when viewed, except for one-off events. The problem is the calendar app I'm working on allows you to move items around in the day they're and saves way you order the items. I'm already using a ranked model gem (link here: https://github.com/mixonic/ranked-model) to cut down on the number of writes needed to update the "onDayIndex". The template approach on its own turns into a bit of a nightmare when "onDayIndex" is factored in... (I could say more...) So I'd like to store slimmed down 'Placeholder' items that store the items' position and a pointer to template, perhaps in a separate table if possible. If this isn't possible, an alternative approach I've considered for conserving space is moving most columns from the Items table to an ItemData table, and storing an ItemDataID on Items. But I'd really like to know if it is possible, as I'm pretty junior in SQL, as well as any other vital information I may be missing. I'm using Rails with a Postgres database. A: Are you talking about using UNION / UNION ALL to stack result sets on top of each other, but where the sources have different columns? If so, you need to fill in the 'missing' columns (you can only UNION two sets if their signatures match, or can be coerced to match). For example... SELECT col1, col2, NULL as col3 FROM tbl1 UNION ALL SELECT col1, NULL AS col2, col3 FROM tbl2 Note: UNION expends additional resources to remove duplicates from the results. Use UNION ALL if such effort is wasted.
doc_23536771
Sub cItems_ItemChange(ByVal Item As Object) [enter image description here][1] ' Change the following line to your new Message Class NewMC = "IPM.Appointment.NewForm" If Item.Class = olAppointment Then If Item.MessageClass <> NewMC Then Item.MessageClass = NewMC Item.Save End If End Sub This works on appointments I create: https://i.stack.imgur.com/B4pUL.png
doc_23536772
I downloaded these files and I moved the dwx mq5 file into the Expert/Advisor folder in metatrader5 as expected, yet...I can't see the EA after refreshing I use a Mac, and I was thinking if it makes any difference. Although I had tried using the mq4 for metatrader4, it worked successfully but the mq5 file wouldn't work on metatrader5 Also, does anyone know which folders the remaining 3 "mqh" files should be moved to? I'm stuck, would really appreciate any help Thanks in advance. A: After many trials, I got a hang of it The tested server codes are here for both mt4 and mt5 https://github.com/darwinex/dwxconnect
doc_23536773
I have an Enumerated field on my entity bean: @Column(name="APPROVAL_BY") @Enumerated(EnumType.STRING) private ApprovalTypeEnum approvedBy; And I'm using it to filter my result set within a querydsl BooleanBuilder: builder.and(qPositionToIndividualRelationship.approvedBy.stringValue().in(filter.getSelectedApprovalTypeList())); Which then results in the following clause in the executed SQL: str(positionto1_.APPROVAL_BY) in ('Value1' , 'Value2') When there are no results to return this is fine and no error is encountered, however when there are results I get the following: [SqlExceptionHelper.logExceptions] SQL Error: 8114, SQLState: S0005 [SqlExceptionHelper.logExceptions] Error converting data type varchar to float. If I manually execute the query without the parse using str() the query works fine and returns the results I expect. Does anyone know: * *Why the SqlServer dialect decides to parse using str()? *Is there a way to prevent this? Cheers A: So, my understanding of whats happening here is that calling .stringValue() is inserting the STR() in the query, not getting the string value of the enum like perhaps you are intending. not really sure if there is a way of doing that since it is dealing with a 'Path' type object. I think queryDSL really intends for you to compare enums with enums, or objects with objects. it will then handle the conversion so you dont need to worry about it. ie. builder.and(qPositionToIndividualRelationship.approvedBy.in(filter.getSelectedApprovalTypeList())); where filter.getSelectedApprovalTypeList() returns a list of your ApprovalTypeEnum
doc_23536774
TEMPTABLENAME is a temp table with an id column (and all the other columns). I am thinking some kind of while loop using the id as a counter. The real problem with the merge statement is that it locks the entire table for an extended amount of time when processing 200K+ records. I want to loop every 100 rows so I can release the lock and let the other applications access the table. This table has millions of rows and also fires off an audit every time data is updated. This causes 160K records to take around 20 to 30 mins in the merge below. The merge code below is a sample of the code. There is probably about 25 columns that get updated/inserted. I would be open to finding another way other than the merge to insert the data. I just can not change the audit system or amount of records in the table. merge Employee as Target using TEMPTABLENAME as Source on (Target.ClientId = Source.ClientId and Target.EmployeeReferenceId = Source.EmployeeReferenceId) when matched then update set Target.FirstName = Source.FirstName, Target.MiddleName = Source.MiddleName, Target.LastName = Source.LastName, Target.BirthDate = Source.BirthDate when not matched then INSERT ([FirstName], [MiddleName], [LastName], [BirthDate]) VALUES (Source.FirstName, Source.MiddleName, Source.LastName, Source.BirthDate) OUTPUT $action INTO @SummaryOfChanges; SELECT Change, COUNT(*) AS CountPerChange FROM @SummaryOfChanges GROUP BY Change;
doc_23536775
* *Survey respondents can view/edit/delete only their own responses *A SharePoint group (composed of teams lead/managers) can view all responses but cannot edit/delete (unless their own survey response) *A SharePoint group (composed of team leads) can view/edit all responses to add notes to the response. The group members could intersect with group #2 members. I have configured 1 above through a survey advanced settings. But I'm not sure if 2 and 3 are possible. I have tried the following: * *Created a new permission level that allows editing/viewing of list item. *Create a new group and assign #1 permission level Above doesn't seem to work. The survey response permission is getting overwritten by the survey setting allow users to view/edit/delete their own responses only. Any advice? Thanks.
doc_23536776
Here's my left join query and it's result: SELECT a.id AS cat_id, b.id AS subcat_id, a.name AS cat_name, b.name AS sub_cat_name, CONCAT_WS(' / ', a.name, b.name) AS full_name FROM taxonomies as a LEFT JOIN taxonomies AS b ON a.id = b.parent_taxonomy_id WHERE (a.name LIKE 'Se%' OR b.name LIKE 'Se%') ORDER BY full_name DESC; +--------+-----------+----------+--------------+--------------------+ | cat_id | subcat_id | cat_name | sub_cat_name | full_name | +--------+-----------+----------+--------------+--------------------+ | 84 | 85 | Season | Winter | Season / Winter | | 84 | 91 | Season | Summer | Season / Summer | | 84 | 90 | Season | Spring | Season / Spring | | 84 | 128 | Season | Fall | Season / Fall | | 84 | 129 | Season | Christmas | Season / Christmas | +--------+-----------+----------+--------------+--------------------+ 5 rows in set (0.00 sec) ``` Here's my right join query and it's result: SELECT a.id AS cat_id, b.id AS subcat_id, a.name AS cat_name, b.name AS sub_cat_name, CONCAT_WS(' / ', a.name, b.name) AS full_name FROM taxonomies as a RIGHT JOIN taxonomies AS b ON a.id = b.parent_taxonomy_id WHERE (a.name LIKE 'Se%' OR b.name LIKE 'Se%') ORDER BY full_name DESC; +--------+-----------+----------+--------------+--------------------+ | cat_id | subcat_id | cat_name | sub_cat_name | full_name | +--------+-----------+----------+--------------+--------------------+ | 84 | 85 | Season | Winter | Season / Winter | | 84 | 91 | Season | Summer | Season / Summer | | 84 | 90 | Season | Spring | Season / Spring | | 84 | 128 | Season | Fall | Season / Fall | | 84 | 129 | Season | Christmas | Season / Christmas | | NULL | 84 | NULL | Season | Season | +--------+-----------+----------+--------------+--------------------+ 6 rows in set (0.00 sec) Here's the data in taxonomies table: mysql> select * from taxonomies; +-----+-----------------------+-----------------------+--------+----------------+--------------------+---------+---------------------+---------------------+ | id | name | machine_name | app_id | is_subcategory | parent_taxonomy_id | user_id | created_at | updated_at | +-----+-----------------------+-----------------------+--------+----------------+--------------------+---------+---------------------+---------------------+ | 84 | Season | season | mw | 0 | NULL | 94711 | 2015-04-10 12:00:00 | 2015-04-10 12:00:00 | | 85 | Winter | winter | mw | 1 | 84 | 94711 | 2015-04-10 12:00:00 | 2015-04-10 12:00:00 | | 90 | Spring | spring | mw | 1 | 84 | 94711 | 2015-04-10 12:00:00 | 2015-04-10 12:00:00 | | 91 | Summer | summer | mw | 1 | 84 | 94711 | 2015-04-10 12:00:00 | 2015-04-10 12:00:00 | | 128 | Fall | fall | mw | 1 | 84 | 94711 | 2015-07-09 13:18:03 | 2015-07-09 13:18:03 | | 129 | Christmas | christmas | mw | 1 | 84 | 94711 | 2015-07-09 13:18:11 | 2015-07-09 13:18:11 | | 130 | Content Type | content-type | mw | 0 | NULL | 94711 | 2015-07-09 13:18:47 | 2015-07-09 13:18:47 | | 131 | Trend Watch | trend-watch | mw | 1 | 130 | 94711 | 2015-07-09 13:19:10 | 2015-07-09 13:19:10 | | 132 | Charm Unit | charm-unit | mw | 1 | 130 | 94711 | 2015-07-09 13:19:17 | 2015-07-09 13:19:17 | | 133 | Infographic | infographic | mw | 1 | 130 | 94711 | 2015-07-09 13:19:23 | 2015-07-09 13:19:23 | | 134 | Word Art | word-art | mw | 1 | 130 | 94711 | 2015-07-09 13:19:29 | 2015-07-09 13:19:29 | | 135 | Storify | storify | mw | 1 | 130 | 94711 | 2015-07-09 13:19:35 | 2015-07-09 13:19:35 | | 136 | Content Label | content-label | mw | 0 | NULL | 94711 | 2015-07-09 13:19:59 | 2015-07-09 13:19:59 | | 137 | Usage | usage | mw | 1 | 136 | 94711 | 2015-07-09 13:20:04 | 2015-07-09 13:20:04 | | 138 | Word History | word-history | mw | 1 | 136 | 94711 | 2015-07-09 13:20:10 | 2015-07-09 13:20:10 | | 139 | Spelling Bee | spelling-bee | mw | 1 | 136 | 94711 | 2015-07-09 13:20:16 | 2015-07-09 13:20:16 | | 140 | Obscure Words | obscure-words | mw | 1 | 136 | 94711 | 2015-07-09 13:20:22 | 2015-07-09 13:20:22 | | 141 | Words We're Watching | words-were-watching | mw | 1 | 136 | 94711 | 2015-07-09 13:20:29 | 2015-07-09 13:20:29 | | 142 | Word Lists | word-lists | mw | 1 | 136 | 94711 | 2015-07-09 13:20:34 | 2015-07-09 13:20:34 | | 143 | Language Acquisition | language-acquisition | mw | 1 | 136 | 94711 | 2015-07-09 13:20:41 | 2015-07-09 13:20:41 | | 144 | Trending | trending | mw | 1 | 136 | 94711 | 2015-07-09 13:20:45 | 2015-07-09 13:20:45 | | 145 | Best Of | best-of | mw | 1 | 136 | 94711 | 2015-07-09 13:20:50 | 2015-07-09 13:20:50 | | 146 | Pop Culture | pop-culture | mw | 1 | 136 | 94711 | 2015-07-09 13:20:55 | 2015-07-09 13:20:55 | | 147 | Politics | politics | mw | 1 | 136 | 94711 | 2015-07-09 13:21:01 | 2015-07-09 13:21:01 | | 148 | Science | science | mw | 1 | 136 | 94711 | 2015-07-09 13:21:06 | 2015-07-09 13:21:06 | | 149 | Grammar | grammar | mw | 1 | 136 | 94711 | 2015-07-09 13:21:10 | 2015-07-09 13:21:10 | | 150 | Travel | travel | mw | 1 | 136 | 94711 | 2015-07-09 13:21:14 | 2015-07-09 13:21:14 | | 151 | History | history | mw | 1 | 136 | 94711 | 2015-07-09 13:21:20 | 2015-07-09 13:21:20 | | 152 | Sports | sports | mw | 1 | 136 | 94711 | 2015-07-09 13:21:25 | 2015-07-09 13:21:25 | | 153 | Lexicography | lexicography | mw | 1 | 136 | 94711 | 2015-07-09 13:21:35 | 2015-07-09 13:21:35 | | 154 | Quotable Quotes | quotable-quotes | mw | 1 | 136 | 94711 | 2015-07-09 13:21:48 | 2015-07-09 13:21:48 | | 155 | Book Excerpts | book-excerpts | mw | 1 | 136 | 94711 | 2015-07-09 13:21:54 | 2015-07-09 13:21:54 | | 156 | Religion | religion | mw | 1 | 136 | 94711 | 2015-07-09 13:22:04 | 2015-07-09 13:22:04 | | 157 | Lifestyle | lifestyle | mw | 1 | 136 | 94711 | 2015-07-09 13:22:10 | 2015-07-09 13:22:10 | | 158 | Literature | literature | mw | 1 | 136 | 94711 | 2015-07-09 13:22:15 | 2015-07-09 13:22:15 | | 159 | Online Culture | online-culture | mw | 1 | 136 | 94711 | 2015-07-09 13:22:21 | 2015-07-09 13:22:21 | | 160 | Topic | topic | mw | 0 | NULL | 94711 | 2015-07-09 13:22:35 | 2015-07-09 13:22:35 | | 161 | Arts & Entertainment | arts--entertainment | mw | 1 | 160 | 94711 | 2015-07-09 13:22:43 | 2015-07-09 13:22:43 | | 162 | Science & Technology | science--technology | mw | 1 | 160 | 94711 | 2015-07-09 13:25:46 | 2015-07-09 13:25:46 | | 163 | Home & Garden | home--garden | mw | 1 | 160 | 94711 | 2015-07-09 13:25:52 | 2015-07-09 13:25:52 | | 164 | Business | business | mw | 1 | 160 | 94711 | 2015-07-09 13:25:57 | 2015-07-09 13:25:57 | | 165 | Education & Research | education--research | mw | 1 | 160 | 94711 | 2015-07-09 13:26:04 | 2015-07-09 13:26:04 | | 166 | Sports & Recreation | sports--recreation | mw | 1 | 160 | 94711 | 2015-07-09 13:26:11 | 2015-07-09 13:26:11 | | 167 | Health & Fitness | health--fitness | mw | 1 | 160 | 94711 | 2015-07-09 13:26:17 | 2015-07-09 13:26:17 | | 168 | History & Literature | history--literature | mw | 1 | 160 | 94711 | 2015-07-09 13:26:26 | 2015-07-09 13:26:26 | | 169 | Medical | medical | mw | 1 | 160 | 94711 | 2015-07-09 13:26:31 | 2015-07-09 13:26:31 | | 170 | Government | government | mw | 1 | 160 | 94711 | 2015-07-09 13:26:36 | 2015-07-09 13:26:36 | | 171 | Word of the Year | word-of-the-year | mw | 0 | NULL | 94711 | 2015-07-09 13:26:45 | 2015-07-09 13:26:45 | | 172 | Word of the Year 2013 | word-of-the-year-2013 | mw | 1 | 171 | 94711 | 2015-07-09 13:26:50 | 2015-07-09 13:26:50 | | 173 | Word of the Year 2014 | word-of-the-year-2014 | mw | 1 | 171 | 94711 | 2015-07-09 13:26:57 | 2015-07-09 13:26:57 | | 174 | Word of the Year 2015 | word-of-the-year-2015 | mw | 1 | 171 | 94711 | 2015-07-09 13:27:03 | 2015-07-09 13:27:03 | | 176 | Travel | travel | mw | 1 | 160 | 94711 | 2015-07-10 13:31:05 | 2015-07-10 13:31:05 | | 177 | Test | test | mw | 0 | 0 | 94706 | 2015-07-16 20:03:19 | 2015-07-16 20:03:19 | +-----+-----------------------+-----------------------+--------+----------------+--------------------+---------+---------------------+---------------------+ 53 rows in set (0.00 sec) ^ if I join a table on itself - why in the world would I get different results? A: To expand on @MatRichardson said above; basically * *the first query is getting all nodes with any parents if they have them *the second is getting all nodes with any children if they have them A: The reason is that a LEFT JOIN selects all rows from the "left" of the join statement and any rows from the right statement that satisfies the join condition (ON clause), and RIGHT JOIN does the exact opposite -> it selects all rows from the right and any rows from the left that satisfies the condition. In your case, on the second example your selecting the first row (id=84) in the "b" alias, and then since no "a" row matches it, all "a" columns are NULL. In your first example, that row (where b.id=84) is omitted because it doesn't satisfy the condition of a.id=b.parent_taxonomy_id for any "a" row
doc_23536777
The source code I am trying to compile is LibLinkTest.cpp: #include <boost/filesystem.hpp> #include <fstream> #include <iostream> #include <string> #include <assert.h> using namespace boost::filesystem; int main(int argc, char* argv[]) { std::string str{"test passed"}; std::cout << str << std::endl; boost::filesystem::path p{argv[1]}; try { std::cout << p.string() << std::endl; if (exists(p)) { if (is_regular_file(p)) { std::ifstream file{p.c_str()}; std::string line; if (file.good() && file.is_open()) { while (file >> line) { std::cout << line << std::endl; } } file.close(); } else if (is_directory(p)) { std::cout << p.string() << " is a directory " << std::endl; // path stream inserter } else std::cout << p.string() << " exists, but is neither a regular file nor a directory" << std::endl; } else { std::cout << p.string() << " does not exist" << std::endl; } } catch (const filesystem_error& ex) { std::cout << ex.what() << std::endl; } } Running: c++ -std=c++11 -I /usr/boost_1_54_0/boost/ LibLinkTest.cpp -o LibTest -L /usr/boost_1_54_0/lib/ -lboost_filesystem -lboost_system compiles it just fine and the code runs (with a seg fault, but I'll address that separately). However, I want to use CMake with my other projects. Trying to compile LibLinkTest.cpp with the following CMakeLists.txt causes linking errors. CMAKE_MINIMUM_REQUIRED (VERSION 2.6) PROJECT(BoostTest CXX) SET(CMAKE_CXX_FLAGS "-std=c++11 -stdlib=libc++") FIND_PACKAGE(Boost 1.54.0 COMPONENTS filesystem system REQUIRED) INCLUDE_DIRECTORIES( ${Boost_INCLUDE_DIR} /usr/include/ /usr/include/c++/4.2.1/ ) ADD_EXECUTABLE( LibTest LibLinkTest.cpp ) TARGET_LINK_LIBRARIES(LibTest boost_filesystem boost_system) The output from running cmake ../ is: -- The CXX compiler identification is Clang 5.0.0 -- Check for working CXX compiler: /usr/bin/c++ -- Check for working CXX compiler: /usr/bin/c++ -- works -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Boost version: 1.54.0 -- Found the following Boost libraries: -- filesystem -- system -- Configuring done -- Generating done And finally running make gives the error: Scanning dependencies of target LibTest [100%] Building CXX object CMakeFiles/LibTest.dir/LibLinkTest.cpp.o Linking CXX executable LibTest Undefined symbols for architecture x86_64: "std::string::c_str() const", referenced from: boost::system::system_error::what() const in LibLinkTest.cpp.o boost::filesystem::path::c_str() const in LibLinkTest.cpp.o "std::string::empty() const", referenced from: boost::system::system_error::what() const in LibLinkTest.cpp.o "std::basic_ios<char, std::char_traits<char> >::good() const", referenced from: _main in LibLinkTest.cpp.o It seems like a setting in CMake is not correct, perhaps something that points to the std c++ lib. Does anyone know how I can configure CMake correctly? A: I have solved this by changing the line: SET(CMAKE_CXX_FLAGS "-std=c++11 -stdlib=libc++") to SET(CMAKE_CXX_FLAGS "-std=c++11 -stdlib=libstdc++") It seems like I had just made a typo in the CMakeLists.txt. On a side note, does anyone know why I need to set this flag? Is it a C++11 thing? It also seems to have solved my issues with the seg fault that I was getting when compiling from the command line. A: You should change the line TARGET_LINK_LIBRARIES(LibTest boost_filesystem boost_system) to TARGET_LINK_LIBRARIES(LibTest ${Boost_LIBRARIES}) The FIND_PACKAGE command sets the Boost_LIBRARIES variable to what you need to link with. A: If you see these two lines from the output -- Check for working CXX compiler: /usr/bin/c++ -- Check for working CXX compiler: /usr/bin/c++ -- works It tells you that it might not be clang that is used to compile the source. To see if it is, to e.g. $ c++ --version to see what compiler it actually is. If it doesn't say clearly you may want to do e.g. $ ls -l /usr/bin/c++ and if it's a symbolic link then check the link (and so on). On my system (Ubuntu 13.10) the file /usr/bin/c++ is a symbolic link to /etc/alternatives/c++ which is a symbolic link to /usr/bin/g++, meaning that on my system the command c++ is actually the GCC C++ compiler. To make sure you use clang, then redo the cmake command (from a clean folder, that you haven't run cmake in before) with the environment variable CXX set to clang++, like $ CXX=clang++ cmake path/to/folder/with/CMakeLists.txt Pro-tip: Make a separate folder for building, and run cmake from it. Then you can easily clean it up by just removing it if needed.
doc_23536778
public List<Messages> GetAllItemsByWebContentId(string webContentId) { lock (locker) { return database.Table<Messages>().Where(o => o.webContentDefinitionId == webContentId).ToList(); } } Messages is my model class. public class Messages { public Messages() { } [PrimaryKey, AutoIncrement] public int ID { get; set; } public int tweetId { get; set; } public string profileImage { get; set; } public string name { get; set; } public long createdTime { get; set; } public string tweetData { get; set; } public string mediaUrl { get; set; } public string webContentDefinitionId { get; set; } } Now I need to sort this list in the order of createdTime. My createdTime is a 13 digit java timestamp. One example created time is 1543608245696, which means 01/12/2018 01:34. Without sorting, the latest messages are coming on the last of the local database. So inside of GetAllItemsByWebContentId() how can I add created time sorting? A: Very easy! change your code to: return database.Table<Messages>() .Where(o => o.webContentDefinitionId == webContentId) .OrderByDescending(x => x.CreatedTime) .ToList();
doc_23536779
In Firefox you can highlight text, click inside and it totally deselects. In Chrome/Chromium if you click inside highlighted text that's still counted as selected until one more click (even though the visual highlight is gone). How do we work around this? JS / Jquery Code: function getSelected() { var return_text; if (window.getSelection) { return_text = window.getSelection(); } else if (document.getSelection) { return_text = document.getSelection(); } return return_text; } $(document).on('click', "div", function(e) { var selection = getSelected(); var selectedText = selection.toString(); console.log(selectedText); }); HTML for testing: <div> This is some text. Open your F12 console and select some text to test me<br /> <br /> In Chromium, the selected text stays until you click twice even though it is visually unselected on the first click. In Firefox, it clears properly on one click.<br /> <br /> Why is Chromium doing this? It's causing really annoying behaviour. </div> Example: https://jsfiddle.net/7sf35c4j/ From what I can see, this makes it basically impossible in Chrome/Chromium to accurately know when something is deselected???
doc_23536780
Jan 05, 2015 12:06:16 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1ab930d: startup date [Mon Jan 05 12:06:16 IST 2015]; root of context hierarchy Jan 05, 2015 12:06:16 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [applicationContext.xml] Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:217) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:188) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:252) at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:127) at org.springframework.context.support.AbstractXmlApplicationContext.loadBeanDefinitions(AbstractXmlApplicationContext.java:93) at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129) at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:537) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:452) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83) at com.javatpoint.Test.main(Test.java:14) Caused by: java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:330) ... 13 more A: This message is pretty clear. You need a file named applicationContext.xml with the required spring configuration. For an example look here A: This error may arise when the setter and getter methods are not properly defined in the bean class. So make sure you have proper getter and setter methods in the bean class.
doc_23536781
HTML <button class="k-button" id="ResultButton" style="display: none;"></button> This is where I am creating my button in my "index.cshtml file. Javascipt var csvData = data.result; var buffer = csvData; var uri = "data:text/csv;charset=utf8," + encodeURIComponent(buffer); var fileName = "resultCSV.csv"; var link = document.createElement("a"); if (link.download !== undefined) { // feature detection // Browsers that support HTML5 download attribute link.setAttribute("href", uri); link.setAttribute("download", fileName); } else if (navigator.msSaveBlob) { // IE 10+ link.addEventListener("click", function (event) { var blob = new Blob([buffer], { "type": "text/csv;charset=utf-8;" }); navigator.msSaveBlob(blob, fileName); }, false); } link.innerHTML = "Export to CSV"; // I think I may be doing this incorrect document.getElementById("ResultButton") .appendChild(link); $("#ResultButton").show(); } else { alert("Your Search Cameback Empty Please Check Your Selections And Retry"); } I think I may doing this incorrect. Seems when I am trying to bind this link to my button it overrides the link. Because when I document.body.appendChild(link); it gives me the link properly, but when I bind it to the button it just refreshes the web page. A: I think its because you are appending link as child of the button, then clicking button wont initiate click of link.So instead of document.getElementById("ResultButton") .appendChild(link); $("#ResultButton").show(); this you sholud give $("#ResultButton").click(function(){ link.click(); }); A: This will make it look like a button. > var myATag = '<a href="somelink" type="button" class="k-button" > id="ResultButton"/>'; Remove the button code. Create a div and at the end of your function do. $("#mydiv").html(myATag);
doc_23536782
My import in angular 4 is import Blockly from 'node-blockly/browser';. That works. Looking at the browser.js file, I can see that it includes ./lib/blocks_compressed_browser.js and this file seems not to be regenerated. I would be very happy if someone could provide some tips on how to generate custom blocks in node-blockly. Many thanks. A: It will be regenerated when you run npm run prepublish, to which pre-requisite is that you run npm install. You will then see all re-generated changes in lib folder
doc_23536783
Here is the code I am using to compile it... from cx_Freeze import setup, Executable import sys import numpy.core._methods import numpy.lib.format from xlwt import ExcelFormulaParser additional_mods = ['numpy.core._methods', 'numpy.lib.format'] setup(name='ReconApp', version='0.1', description='xyz.script', options = {'build_exe': {'includes': additional_mods}}, executables = [Executable("reconciliation_application.py")]) The code compiles enter image description herewith no errors. When I go to run the .exe the program launches and closes with this error. I notice that it does not like something inside xlwt module ExcelFormulaParser By I do not know what the error is. any suggestions? A: Try to add xlwt library to setup options, i.e. import sys, os from cx_Freeze import setup, Executable build_exe_options = {"packages": ["numpy", "matplotlib", "xlwt"]} setup( name = "App", version = "1.0", description = "App ...", options = {"build_exe": build_exe_options}, executables = [Executable("App.py", base = "Win32GUI")])
doc_23536784
angular.module('ngS3upload.directives', []). directive('s3Upload', ['$parse', 'S3Uploader', 'ngS3Config', function ($parse, S3Uploader, ngS3Config) { return { restrict: 'AC', require: '?ngModel', replace: true, transclude: true, scope: true, controller: ['$scope', '$element', '$attrs', '$transclude', function ($scope, $element, $attrs, $transclude) { $scope.emptyfile=function() { alert("hello"); $scope.$apply(); }; }], compile: function (element, attr, linker) { return { pre: function ($scope, $element, $attr) { if (angular.isUndefined($attr.bucket)) { throw Error('bucket is a mandatory attribute'); } }, post: function (scope, element, attrs, ngModel) { // Build the opts array var opts = angular.extend({}, scope.$eval(attrs.s3UploadOptions || attrs.options)); opts = angular.extend({ submitOnChange: true, getOptionsUri: '/s3options', acl: 'public-read', uploadingKey: 'uploading', folder: '', enableValidation: true, targetFilename: null }, opts); {{ some code here}} } }; }, templateUrl: function(elm, attrs) { var theme = attrs.theme || ngS3Config.theme; return 'theme/' + theme + '.html'; } }; }]); angular.module('ngS3upload').run(['$templateCache', function($templateCache) { 'use strict'; $templateCache.put('theme/bootstrap2.html', "<div class=\"upload-wrap\">\n" + " <button class=\"btn btn-primary\" type=\"button\" ng-hide=\"filename\"><span ng-if=\"!filename\">Choose file</span></button>\n" +"<div id=\"imgdiv\" class=\"pindiv\" style=\"position: relative\" ng-if=\"filename\"><audio controls><source src=\"{{filename}}\" type=\"audio/ogg\"><source src=\"{{filename}}\" type=\"audio/mpeg\"></audio><a href=\"\" value=\"change\" ng-click=\"emptyfile()\">Change</a></div>"+ "<p></p><div class=\"progress\" ng-show=\"uploading\">\n"+"<div class=\"progress-bar\" role=\"progressbar\" aria-valuenow=\"{{progress}}\" aria-valuemin=\"2\" aria-valuemax=\"100\" style=\"width: {{progress}}%;\">\n"+"{{progress}}%"+" </div></div>\n"+ " <input type=\"file\" style=\"display: none\"/>\n"+ "</div>" ); }]); when i click on 'change' button which is returned from directive template,emptyfile() function is called and there i would like to re-render my directive. A: Your code will enter a digest cycle when you click the button. If you code invoked the emptyFile() function already (i assume from your question everything works), and all you wish it to show a change in your directive, simply make the elements in your directive dynamic. You can apply styles, or hide / show elements using {{foo}} where foo is a scope variable. $scope.foo = 'visible' $scope.emptyfile=function() { $scope.foo = 'hidden'; // may be needed in case emtyfile is not part of digest cycle $scope.$apply() } and in your temple: <div style="{{foo}}"....
doc_23536785
* *day 30 instead of 31? *it set 13 as time instead of 00? new Date('Dec 31, 2019').toISOString() // '2019-12-30T13:00:00.000Z' Basically what I'm trying to do is to convert original data format into YYYY-MM-DD. A: new Date('Dec 31, 2019') - this date will be shown in your local time format. e.g.: `Tue Dec 31 2019 00:00:00 GMT+1100` (Your Standard Time) However, new Date('Dec 31, 2019').toISOString() - this date will be shown like 2019-12-30T13:00:00.000Z. It means Dec 31, 2019 minus 11 hours(your time zone). In addition, to avoid strange behaviors, try to set explicitly year, month and day to avoid strange behavior. You should parse Date in the following format: // yyyy-mm-dd format // new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]]) let yourDate = new Date(parts[0], parts[1]-1, parts[2]); // Be careful: months are 0-based You can see valid Date times here.
doc_23536786
A: You're looking for the Convex Hull of the points. There are many viable algorithms for finding the hull; see wikipedia, for example.
doc_23536787
I have searched the python binding for Gtk, Gdk and GdkPixbuf without any luck. Any suggestion is welcome. Example Code: from gi.repository import GdkPixbuf figure_file = 'QWERTY.svg' width, height = 600, -1 preserve_aspect_ratio = True im_data = GdkPixbuf.Pixbuf.new_from_file_at_scale(figure_file, width, height, preserve_aspect_ratio) # Now I want to mask all parts im_data except 20x10 pixel rectangle at pixel(100,120) maksed_im_data = mask_pixbuf(im_data, 100, 120, 20, 10) mask_pixbuf function should return masked PixBuf (of the original size) where only the rectangular region of size 20 x 10 centered at (100,120) is visible. Other parts of the returned pixbuf is expected to be transparent.
doc_23536788
Article_Size_Class * *Article_ID *Size_Class Sizes_not_availabe * *Size_Class *Size_ID Size_Table * *Size_ID *Length So I got an Article_ID and now I want to list all the available product lengths from my Size_Table expect the ones listed in the Sizes_not_availabe table. I tried to do this, but unfortunately it is not working: SELECT * FROM Size_Table WHERE NOT EXISTS ( SELECT Size_ID FROM Sizes_not_availabe LEFT JOIN Article_Size_Class ON Article_Size_Class.Size_ID = Article_Size_Class.Size_ID WHERE Article_Size_Class.Article_ID= '00024-002' ) Thanks for helping! A: SELECT st.Length FROM Size_Table st WHERE st.Size_ID NOT IN (SELECT sna.Size_ID FROM Sizes_not_available sna INNER JOIN Article_Size_Class asc ON sna.Size_Class=asc.Size_Class WHERE asc.Article_ID= '00024-002')
doc_23536789
TypeError: Invalid property descriptor. Cannot both specify accessors and a value or writable attribute, #<Object> Here is my code, // declare global{ interface String { contains(s: string): boolean; } interface Object { contains(s: string) : boolean; } // } // String String.prototype.contains = function (s: string) : boolean { return String(this).includes(s); }; // Object Object.prototype.contains = function (s: string): boolean { return Object(this).hasOwnProperty(s); } //export {}; I import it into my function. Note: This function works well in live/local on its own. import 'custom/prototype/file'; export const myFunction : Function = (s: string) : Object => { const bool : boolean = s.contains('look for this string'); const obj = { name: "string" }; const fbool : boolean = obj.contains('name'); return { foo: s fboo: fbool }; } Now in my test.spec.ts file I ran a test using the myFunction above. I do not understand why it's giving me this error when it has no issues running by itself. import { myFunction } from 'index/file'; import 'custom/prototype/file'; describe.skip('test case', () => { it('test',() => { const object = myFunction('this is a random string'); }); }); Here is the full error log: TypeError: Invalid property descriptor. Cannot both specify accessors and a value or writable attribute, #<Object> at Function.defineProperty (<anonymous>) at Object.<anonymous> (D:\test1\test\test azure\utils\defaultContext.ts:2:8) at Module._compile (internal/modules/cjs/loader.js:1137:30) at Module.m._compile (D:\test1\test\test azure\node_modules\ts-node\src\index.ts:439:23) at Module._extensions..js (internal/modules/cjs/loader.js:1157:10) at Object.require.extensions.<computed> [as .ts] (D:\test1\test\test azure\node_modules\ts-node\src\index.ts:442:12) at Module.load (internal/modules/cjs/loader.js:985:32) at Function.Module._load (internal/modules/cjs/loader.js:878:14) at Module.require (internal/modules/cjs/loader.js:1025:19) at require (internal/modules/cjs/helpers.js:72:18) at Object.<anonymous> (D:\test1\test\test azure\tests\DV_Musculoskeletal.spec.ts:3:1) at Module._compile (internal/modules/cjs/loader.js:1137:30) at Module.m._compile (D:\test1\test\test azure\node_modules\ts-node\src\index.ts:439:23) at Module._extensions..js (internal/modules/cjs/loader.js:1157:10) at Object.require.extensions.<computed> [as .ts] (D:\test1\test\test azure\node_modules\ts-node\src\index.ts:442:12) at Module.load (internal/modules/cjs/loader.js:985:32) at Function.Module._load (internal/modules/cjs/loader.js:878:14) at Module.require (internal/modules/cjs/loader.js:1025:19) at require (internal/modules/cjs/helpers.js:72:18) at Object.implementationOfRequireOrImportForUnstableEsm [as requireOrImport] (D:\test1\test\test azure\node_modules\mocha\lib\esm-utils.js:101:12) at Object.exports.loadFilesAsync (D:\test1\test\test azure\node_modules\mocha\lib\esm-utils.js:88:34) at Mocha.loadFilesAsync (D:\test1\test\test azure\node_modules\mocha\lib\mocha.js:467:19) at singleRun (D:\test1\test\test azure\node_modules\mocha\lib\cli\run-helpers.js:125:15) at exports.runMocha (D:\test1\test\test azure\node_modules\mocha\lib\cli\run-helpers.js:190:10) at Object.exports.handler (D:\test1\test\test azure\node_modules\mocha\lib\cli\run.js:366:11) at D:\test1\test\test azure\node_modules\yargs\build\index.cjs:443:71
doc_23536790
I want to show the downloading progress on the web page, but the next code does not work in a content script properly. (async () => { const response = await fetch("https://i.imgur.com/Rvvi2kq.mp4"); const reader = response.body.getReader(); const contentLength = +response.headers.get('Content-Length'); alert(contentLength) // 0 // other code... })(); It works properly (shows 2886550, not 0) only if I run it in the context of the page in the same domain (i.imgur.com for this example). Does it can work (properly) in a content script or at least in a background script? And works when I fetch a data from not the same domain too? Is there any way to fetch a data (not just download to Downloads folder) for working with it after that and see downloading (fetching) progress? Upd: The code above* works properly in the background script, but only in Firefox and Chromium 76+ based browsers. It was a Chromium's bug, that the code shows 0. *It's a part of the code from here. A: Imgur.com's server does not send a Access-Control-Expose-Headers header exposing content-length, so download progress indicators are not possible. It could possibly be faster to serve static content with HTTP/2 from your own domain/server since you would not be opening new socket connections to other CDNs. You could also use your server as a proxy to Imjur.com, but you run the risk of them blocking your server's IP The fetch-progress-indicators examples show various download progress indicators with Fetch.
doc_23536791
My class containing the ObjectMapper : public class ServiceParent{ @Autowired protected ObjectMapper objectMapper; public void someMethod(){ ... Map<String, String> mapResponse = objectMapper.readValue("some json", new TypeReference<Map<String, String>>(){}); } Other class extending previous one public class ServiceChild extends ServiceParent{ ... } My test class : @SpringBootTest public class TestService{ @Mock ObjectMapper objectMapper; @InjectMocks ServiceChild serviceChild; @Test public void test(){ Map<String, String> mapResponse=new HashMap<String, String>(); mapResponse.put("access_token", "token_bouhon"); Mockito.when(objectMapper.readValue(Mockito.anyString(), Mockito.any(Class.class))).thenReturn(mapResponse); } So when I debug this, in ServiceParent, objectMapper isn't null but readValue(...) return null. Do you have an idea on how to return the correct mocked object? Thanks A: I faced the same NPE with the objectmapper. This issue is resolved after adding , my test class has class level annotation with @RunWith(MockitoJUnitRunner.class) and the fix @Before public void setupBefore() { MockitoAnnotations.initMocks(this); } A: @Mock creates a new mock. It's equivalent to calling mock(SomeClass.class) @MockBean creates a mock, like @Mock, but also replaces any bean already in the application context with the same type with that mock. So any code which Autowires that bean will get the mock. You need to use @MockBean
doc_23536792
java.lang.ClassCastException: SwingLibrary cannot be cast to org.robotframework.javalib.library.RobotJavaLibrary My Keyword is written like below *** Keywords *** Start Demo Application [Arguments] ${name} Start Application ${name} java ${MAIN CLASS} 10 seconds ${LIB DIRECTORY} Take Library Into Use SwingLibrary I see that my application does get invoked but I get error. Please help. A: EDIT: this issue was fixed in the 1.9.1 release. The newest version of SwingLibrary no longer implements AnnotationLibrary (which implements RobotJavaLibrary). It has the necessary methods so you should be able to subclass it and use that library with RemoteApplications. public class RemotableSwingLibrary extends SwingLibrary implements RobotJavaLibrary {}
doc_23536793
var reader = new window.FileReader(); reader.readAsDataURL(file); reader.onload = onReadAsDataURL; A: This is known as event registration, you assign a function to the onload property of the reader object, usually several events will fire and there will be checks on properties such as onload to see if there's any function assigned to these properties. If so the function assigned to the relevant property will be executed. It's actually quite straightforward, you register a function to a property, so that this function will be executed whenever the event for given property fires. See this and this for more info on the subject
doc_23536794
Failed to load resource: the server responded with a status of 400 (Bad Request) ContactMe.js:63 Error: Request failed with status code 400 at createError (createError.js:16:1) at settle (settle.js:17:1) at XMLHttpRequest.onloadend (xhr.js:66:1) this is the the server.js require("dotenv").config(); const express = require("express"); const cors = require("cors"); const path = require("path"); const contactRoute = require("./route/contactRoute"); const app = express(); app.use(express.json()); app.use(cors()); app.use("/", contactRoute); if (process.env.NODE_ENV === "production") { app.use(express.static("client/build")); app.get("*", (req, res) => res.sendFile(path.resolve(__dirname, "client", "build", "index.html")) ); } const port = process.env.PORT || 5000; app.listen(port, console.log(`server listing to port 5000 only`)); this is the contactRoute.js: const router = require("express").Router(); const nodemailer = require("nodemailer"); router.post("/contact", (req, res) => { let data = req.body; if ( data.name.length === 0 || data.email.length === 0 || data.message.length === 0 ) { return res.json({ msg: "Please Fill All The Fields!" }); } let smtpTransporter = nodemailer.createTransport({ service: "Gmail", port: 465, auth: { user: "here is my email", pass: "here is my password", }, }); let mailOptions = { from: data.email, to: "here is my email", subject: `message from ${data.name}`, html: ` <h3>Informations<h3/> <ul> <li>Name: ${data.name}<li/> <li>Email: ${data.email}<li/> </ul> <h3>Message</h3> <p>${data.message}<p/> `, }; smtpTransporter.sendMail(mailOptions, (error) => { try { if (error) return res.status(400).json({ msg: "Please Fill All The Fields!" }); return res.status(200).json({ msg: "Thank You For Contacting Mohammad." }); } catch (error) { if (error) return res.status(500).json({ msg: "There is server error" }); } }); }); module.exports = router; I tried a lot of things but couldn't figure out the error can someone help please Note:I found several similar questions on stack overflow but they were irrevelant or didn't work.
doc_23536795
<h:commandLink rendered="some contidion" > <td> <a href="home.xhtml"> <img src="icon.png" width="140" height="140" alt="alternate" /> </a> </td> <f:param name="parent" value="ABC" /> </h:commandLink> But on home.xhtml, I can't read it as: #{param.parent} What's the mistake I m doing. A: You are using h:commandLink in a wrong way. You don't need to embed a a:href. Use the action attribute. Or better if you don't want to call an action method use h:link: <h:link outcome="home" > <img ...> <f:param name="parent" value="ABC" /> </h:link> A: You can access your home.xhtml likes here <h:outputText value="Value, {0}"> <f:param value="#{yourBean.name}"/> </h:outputText> You can replace h:outputText into h:outputFormat or something likes this.
doc_23536796
A: In the way you want to achieve this based on description above : no, you can't. Only way to do something like this is build own app (with own app icon in launcher) and try open camera from your app by Intent, but before that show tutorial within your app. But it seems to be not nice idea for tutorial purpose. A: You cannot add more features in the application provided by different vendors. Each vendor(like Samsung, HTC) has its own application of Camera which is protected. If you want to do that then you will need to have permission of a vendor or become a vendor in the process. That entails to building your own OS or custom OS (Android Source Code is Open Source). Next best thing you could do is provide a helper application that gives tips and tricks and anything informative for guidelines. Then user can learn from your app which is available for download through Google Play. It is worth noting that almost every device hardware is different. Some features are device specific. Therefore quality and settings will also differ.
doc_23536797
<a href="a600characterslengthURL" target="_blank">Click here</a> and this is how is displayed on the email <div> <a href="a600characterslengthURL" target="_blank" data-saferedirecturl="..."> firtURLpart <wbr> secondURLpart <wbr> thirdURLpart <wbr> repeat.. </a> Click here </div> I dont know if is a Gmail security issue, or I'm missing some CSS. Didnt have this problem with a shorter URL, so I guess gmail is taking as suspicious.
doc_23536798
[self addChildViewController:tableViewController]; [self.view addSubview:tableViewController.view]; [tableViewController didMoveToParentViewController:self]; In fact, that works fine. Now the problem is that I do not want to add the tableViewController's view as a subview of the containerViewController's root view. Instead I want to add it as a subview of the containerView (see image) which itself is a subview of the containerViewController's root view. So I changed the above code as follows: [self addChildViewController:tableViewController]; [self.contentView addSubview:tableViewController.view]; [tableViewController didMoveToParentViewController:self]; Now when I launch the app it crashes immediately with this error: Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency', reason: 'child view controller: should have parent view controller: but actual parent is:' What is the problem here? Is it not possible to add a childViewController's view to a specific sub view of its containerViewController? Or how can I achieve this without an error in the view controller hierarchy? A: It doesn't really matter which view you are adding the child viewController to. If a view of a viewController is added to another viewController you need set it properly. tableViewController.view.frame = self.contentView.bounds; [self.contentView addSubview:tableViewController.view]; /*Calling the addChildViewController: method also calls the child’s willMoveToParentViewController: method automatically */ [self addChildViewController:tableViewController]; [tableViewController didMoveToParentViewController:self]; Source code A: //class name InfoViewController IBOutlet UIView *addViewToAddPlot; InfoViewController *InfoController; -(void) add_method { InfoController = [[InfoViewController alloc] initWithNibName:@"InfoViewController" bundle:nil]; InfoController.view.frame = self.addViewToAddPlot.bounds; [self containerAddChildViewController:InfoController]; } -(void) remove_method { [self containerRemoveChildViewController : InfoController]; } - (void)containerAddChildViewController:(UIViewController *)childViewController { [self addChildViewController:childViewController]; [self.addViewToAddPlot addSubview:childViewController.view]; [childViewController didMoveToParentViewController:self]; } - (void)containerRemoveChildViewController:(UIViewController *)childViewController { [childViewController willMoveToParentViewController:nil]; [childViewController.view removeFromSuperview]; [childViewController removeFromParentViewController]; } Add and remove viewcontroller ,#childviewcontroller A: To show a child_view_controller over a main_view_controller. step 1: create a main_view_controller in storyboard. step 2: create a child_view_controller with a UIview and some Label inside in storyboard. step 3: in main_view_controller's button action add the following code: - (IBAction)YourButtonAction:(id)sender { ChildViewControllerName *childViewControllerName = [self.storyboard instantiateViewControllerWithIdentifier:@"storyboardIdYouProvided"]; childViewControllerName.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height); [self.view addSubview:childViewControllerName.view]; [childViewControllerName didMoveToParentViewController:self]; }
doc_23536799
A: You need to provide common model data (typically an array) and have both tableview datasources use this common model data. How each datasource presents this data is up to them, and will influence how each table presents the data. If one tableview "edits" the model data, the other tableview can be told to redraw that item in the data array. This works both ways. This is classic MVC (M = data, V = tableview, C = tableview.datasource). A: I ended up using this example Sharing data between view controllers and other objects @ iPhone Dev SDK A: Take two tableview in common view controller. Just differentiate it with tag. When you gets the data from parsing simply reload table with tag. You can manage two tableviews in common base view controller.