id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23537000
This is what I have tryed. files = ["file1.xml", "file2.xml", "file3.xml"]; let res = get_files(files); //TypeError: res[0] is undefined console.log("res: " + res[0].getElementsByTagName("NAME")[0].childNodes[0].nodeValue); function get_files(files){ let ret_files = []; files.map(file => { //Create a new anonymous array full of promises (one per fetch). fetch(file); //Triger the download }).map(async prom => { //Another array with promises. return await prom; //Waits for ALL the files to download. }).forEach(p => { p.then(a => ret_files.push(a)); //Populate 'ret_files' array. //This works: console.log("Inside function: " + ret_files[0].getElementsByTagName("NAME")[0].childNodes[0].nodeValue); }); return ret_files; } As far as I can see, the function get_files() is returning immediately when called. How can I wait until the ret_files array is completely populated? A: Youve got a few problems in your code: files.map(file => { fetch(file); // triggers the download, but you dont do anything, not even return it }).map(async prom => // prom is undefined? return await prom; //Waits for undefined ?! And thats basically a noop }).forEach(p => { // p is undefined again p.then(a => ret_files.push(a)); // Why?! }); return ret_files; // you return *now* and dont wait for anything?! And here is how it should work: function getFiles(files){ return Promise.all(files.map(file => fetch(file))); } That just creates an array of fetch promises, and awaits all of them. You can use it like: (async function() { let res = await getFiles(files); console.log(res[0]); })()
doc_23537001
public class id { public int childID {get;set;} public int parentID {get;set;} public string text{get;set;} } and I want a loop, base on currentID (currentChildID) that has a parentID . e.g: in my list (supposedly this is the data): childID --- parentID --- text 1 0 aaa 2 1 bbb 3 2 ccc 4 2 ddd and supposedly my currentID was 1 so what I wanted was to get all childID that has parentID value of 1 . in the sample above its 2 . then create a condition inside getting text of 2 (which is bbb) . then after this loop verify if theres data in list that has parentID of 2 so in sample above its 3 and 4 ... then if theres no parentID value containing a number e.g: 3 and 4 loop will end . so its a continous looping till the childID value has no parentID value on the list ... edit: i haven't try any so far related with looping, except for completing data needed on list , but i guess its something like: int theCurrentID = 0; bool initial = idList.Any(n => n.currentID == childID); if (initial) { //loop and gettext foreach(var x in idList.Where(n => n.currentID == childID)) { theCurrentID = x.childID; //supposedly currentID } bool next = idList.Any(n => theCurrentID == parentID); //loop and gettext if (next) { foreach(var x in idList.Where(n => theCurrentID == parentID) { } } else { //parent not found } Note: this sample stops on second loop and dont verify if theres still parentID . A: Ok I'll try to help you but I'am still not 100% sure what you expecting :) First rename childID to ID and name of class because it is very confusing. public class MyClass { public int ID {get;set;} public int parentID {get;set;} public string text{get;set;} } //loop through all items foreach(var currentItem in idList.OrderBy(x=>x.ID)) { //get a list of parent items List<id> parents = idList.Where(x=>x.parentID == currentItem.ID); if(parents.Count == 0) { //we dont have any records which parentID is current item ID so stop executing loop further break; } //Here you loop through all parents and do what you want foreach(var parentItem in parents) { //Do what you want with parentItem } } P.s. code not tested A: Ok, one way to go for this is recursive function: private void Traverse(int childID, List<id> data) { //Pre-action:: Top to bottom approach, to work on items from top level //data.Where(x => x.childID == childID); foreach (var child in data.Where(x => x.parentID == childID)) { Traverse(child.childID, data); } //Post-action:: Bottom to top approach, to work on items from root level //data.Where(x => x.childID == childID); } Use this function as: int theCurrentID = 1; List<id> temp = new List<id>(); temp.Add(new id() { childID = 1, parentID = 0, text = "1" }); temp.Add(new id() { childID = 2, parentID = 1, text = "2" }); temp.Add(new id() { childID = 3, parentID = 2, text = "3" }); temp.Add(new id() { childID = 4, parentID = 3, text = "4" }); Traverse(theCurrentID, temp); I hope this helps.
doc_23537002
So - I am trying to rewrite the field value in the view to include an a tag with the appropriate link... Example: <a href="[field_course_numb_value]">My course</a> Instead I would like to use: <a href="[some way to get current path][field_course_numb_value]">My course</a> A: I ended up solving it by making a customfield: Php code field with the following: <?php print drupal_get_path_alias('node/'.$data->node_node_data_field_the_field_in_question); ?>
doc_23537003
var cities = ['USA/Aberdeen', 'USA/Abilene', 'USA/Akron', 'USA/Albany', 'USA/Albuquerque', 'China/Guangzhou', 'China/Fuzhou', 'China/Beijing', 'China/Baotou', 'China/Hohhot' ... ] var filters = ['Akron', 'Albuquerque', 'Fuzhou', 'Baotou']; My progress so far: var filterList; if (reject) { filterList = angular.copy(cities); _.each(filters, (filter) => { filterList = _.reject(filterList, (city) => city.indexOf(filter) !== -1); }); } else { filterList = []; _.each(filters, (filter) => { filterList.push(_.filter(cities, (city) => city.indexOf(filter) !== -1)); }); } filterList = _.flatten(filterList); return filterList; I'd like to DRY this up and use a more functional approach to achieve this if possible? A: A somewhat more functional version using Underscore might look like this: const cities = ['USA/Aberdeen', 'USA/Abilene', 'USA/Akron', 'USA/Albany', 'USA/Albuquerque', 'China/Guangzhou', 'China/Fuzhou', 'China/Beijing', 'China/Baotou', 'China/Hohhot'] const filters = ['Akron', 'Albuquerque', 'Fuzhou', 'Baotou']; var inList = names => value => _.any(names, name => value.indexOf(name) > -1); _.filter(cities, inList(filters)); //=> ["USA/Akron", "USA/Albuquerque", "China/Fuzhou", "China/Baotou"] _.reject(cities, inList(filters)); //=> ["USA/Aberdeen", "USA/Abilene", "USA/Albany", // "China/Guangzhou", "China/Beijing", "China/Hohhot"] A: I'm using vanilla JavaScript here (some() and filter()) but I hope you get the idea: const isValidCity = city => filters.some(filter => city.indexOf(filter) > -1) const filteredCities = cities.filter(isValidCity) Please note that this is a loop over a loop. So the time complexity is O(n * m) here. A: In your example all city keys share the same pattern: country + / + city. Your filters are all an exact match to the city part of these names. If this is a certainty in your data (which it probably isn't...), you could reduce the number of loops your code makes by creating a Map or object that stores each city per filter entry: * *Create an object with an entry for each city name *Make the key the part that you want the filter to match *Make the value the original name *Loop through the filters and return the name at each key. This approach always requires one loop through the data and one loop through the filters. For small array sizes, you won't notice a performance difference. When one of the arrays has length 1, you'll also not notice any differences. Again, note that this only works if there's a constant relation between your filters and cities. var cities = ['USA/Aberdeen', 'USA/Abilene', 'USA/Akron', 'USA/Albany', 'USA/Albuquerque', 'China/Guangzhou', 'China/Fuzhou', 'China/Beijing', 'China/Baotou', 'China/Hohhot' ] var filters = ['Akron', 'Albuquerque', 'Fuzhou', 'Baotou']; const makeMap = (arr, getKey) => arr.reduce( (map, x) => Object.assign(map, { [getKey(x)]: x }), {} ); const getProp = obj => k => obj[k]; const getKeys = (obj, keys) => keys.map(getProp(obj)); // Takes the part after the "/" const cityKey = c => c.match(/\/(.*)/)[1]; const cityMap = makeMap(cities, cityKey); const results = getKeys(cityMap, filters); console.log(results); A: Since you seem to be using AngularJS, you could utilize the built-in filter functionality. Assuming both the cities and filters array exist on your controller and you're displaying the cities array using ng-repeat, you could have something like this on your controller: function cityFilter(city) { var cityName = city.split('/')[1]; if (reject) { return filters.indexOf(cityName) === -1; } else { return filters.indexOf(cityName) > -1; } } And then in your template, you'd do something like this: <div ng-repeat="city in cities | filter : cityFilter"></div> Of course you'd have to modify your syntax a bit depending on your code style (for example, whether you use $scope or controllerAs).
doc_23537004
fun isDarkTheme(activity: Activity): Boolean { return activity.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES } IF it is correct, then can I please have it in Java? :) A: Here is the java Version private Boolean isDarkTheme(Activity activity) { return (activity.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES; } Java getResources() ->Kotlin resources Java getConfiguration() ->Kotlin configuration Java & ->Kotlin and as you see it's simple Setters and Getters in koltin are accessed by property name A: I realised there might be a little more going on here to someone who's completely unfamiliar with Kotlin, so just in case: boolean isDarkTheme(Activity activity) { return activity.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES } all the get calls get converted to property syntax in Kotlin, so you can just access them like fields. The rest of the stuff just moves around a bit
doc_23537005
I am having an issue passing the value to the second script. The session variable 'captcha_string' is fully visible in the first script, but is not passed to the second page. I am brand new at this, and frustrated. My understanding is, that as long as I start session, the entire $_SESSION array should be available. When I run the first script, I get a broken image tag, not the captcha i am hoping for. Hope this clears up my problem. This is what I have done for the first file: <?php session_start(); $possible_chars = array_merge(range('A','Z'),range('0','9')); shuffle($possible_chars); $string = substr(implode($possible_chars),0,5); $_SESSION['captcha_string']=$string; ?> <img src="captcha_generator.php" alt="Weinerdog!" /> and this is the bit from the second file where I try to grab the $string (captcha_string), which is named "captcha_generator.php: <?php session_start(); putenv('GDFONTPATH=' . realpath('.')); header("Content-type: image/png"); //import string for the captcha from $_SESSION $string = $_SESSION['captcha_string']; // Build an image resource using an existing image as a starting point. $backgroundimage = "captcha_wiener.jpg"; $im=imagecreatefromjpeg($backgroundimage); $colour = imagecolorallocate($im, rand(0,255), rand(0,255), rand(0,255)); // Output the string of characters using a true type font. // Above we set the font path to the current directory, this // means that arial.ttf font file must be in this directory. $font = 'arial.ttf'; $angle = rand(-5,5); imagettftext($im, 120, $angle, 50, 250, $colour, $font, $string); // Draw some annoying lines across the image. imagesetthickness($im, 10); for ($i = 0; $i <3; $i++) { imageline($im, rand(100,50), rand(150,200), rand(450,550), rand(200,250), $colour); } // Output the image as a PNG and the free the used memory. imagejpeg($im); imagedestroy($im); ?> This is, of course, strictly an exercise to make sure we can pass values using session. There is no problem with the rest of the code making the captcha, it has been tested and works. A: You're echo-ing some values with a content-type set to image/png, hence either you'll have the error of headers already sent, or, if the text wasn't sent yet (because cached by PHP), you'll have a broken image and you won't be able to see the text. Don't worry, it has happened to everyone including me :-)
doc_23537006
When not passing scope, or passing an empty scope Identity Server complains about no scopes have been allowed, because I don't want any? I have not set any anywhere How can I get an access token without scopes? A: According to OAuth 2.0 specification, an application can request one or more scopes. Which means, you must ask for at least one of the scopes. OIDC specification states that you must ask for at least "openid" scope (required; to indicate that the application intends to use OIDC to verify the user's identity). So, you cannot get access token without asking for "openid" scope. "OpenID Connect requests MUST contain the openid scope value"
doc_23537007
Parent_section(id) Assessment_Question(id,parent_section_id) Assessment_Answer(id,assessment_question_id) I am trying to inner join parent_section and assessment_qestion, and left join assessment_question and assessment_Answer So far joining parent_Section and assessment_question I have this, not sure how to do it for a third table? var queryResult= dsl.select() .from(PARENT_SECTION) .join(ASSESSMENT_QUESTION) .on(PARENT_SECTION.ID.eq(ASSESSMENT_QUESTION.PARENT_SECTION_ID)) .where(PARENT_SECTION.GATE_ID.eq(gateId)) .fetch() A: Just add another join where you would have added another join in plain SQL: var queryResult = dsl.select() .from(PARENT_SECTION) .join(ASSESSMENT_QUESTION) .on(PARENT_SECTION.ID.eq(ASSESSMENT_QUESTION.PARENT_SECTION_ID)) .leftJoin(ASSESSMENT_ANSWER) .on(ASSESSMENT_QUESTION.ID.eq(ASSESSMENT_ANSWER.ASSESSMENT_QUESTION_ID)) .where(PARENT_SECTION.GATE_ID.eq(gateId)) .fetch()
doc_23537008
<?xml version="1.0" encoding="utf-8"?> <merge xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="wrap_content" android:layout_height="wrap_content" xmlns:app="http://schemas.android.com/apk/res-auto" tools:parentTag="androidx.constraintlayout.widget.ConstraintLayout"> <FrameLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="@dimen/high_padding" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintLeft_toLeftOf="parent" android:id="@+id/draggable_view_component_main"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" /> </FrameLayout> ... </merge> As you can see Im coding some kind of customizable TextView. But when I execute this:textView.setRotation(45), I get this annoying result (image below). As it appears, the textview is not updating its width or height when rotated (I logged getWidth() and getHeight() inside onMeasure()). I already found these questions: * *TextView rotation keeps width and height *Vertical TextView taking too much space in Android But the answers only fix size when orientation is exactly 90 degrees (they just swap width and height) So, is there a way to make the width and height dynamically fit the textView when rotated? Thanks in advance ! EDIT Based on @avalerio 's answer, I found out how to calculate the width and height... public class CustomEditText extends androidx.appcompat.widget.AppCompatEditText { ... @Override public void setRotation(float rotation) { super.setRotation(rotation); requestLayout(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int oldwidth = getMeasuredWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight(); int oldheight = getMeasuredHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom(); int width = oldwidth; int height = oldheight; double angle = Math.toRadians(getRotation()); ... // a bunch of boring calculations ... width += getCompoundPaddingLeft() + getCompoundPaddingRight(); height += getCompoundPaddingTop() + getCompoundPaddingBottom(); setMeasuredDimension(width, height); } The height and width seem correct, but the textView is still limited to its original bounds. Logging getHeight() and getMeasuredHeight() give the correct values, but how can I make textView draw in the new bounds ?
doc_23537009
Below I try to be as descriptive as possible: Directory structure: β”œβ”€β”€ _includes β”‚ β”œβ”€β”€ footer.html β”‚ β”œβ”€β”€ head.html β”‚ β”œβ”€β”€ header.html β”‚ └── scripts.html β”œβ”€β”€ _layouts β”‚ └── default.html β”œβ”€β”€ _site β”‚ └── ... β”‚ β”œβ”€β”€ css β”‚ └── style.css β”œβ”€β”€ fonts β”‚ └── ... β”œβ”€β”€ img β”‚ └── ... β”œβ”€β”€ js β”‚ └── ... β”‚ β”œβ”€β”€_config.yml β”‚ β”œβ”€β”€_gitignore.txt β”‚ β”œβ”€β”€ CNAME β”‚ β”œβ”€β”€ index.html β”‚ └── new_page.md What I did so far? 1) <link href="css/style.css" rel="stylesheet"> added to head.html: chek! Structure <head>: <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="{{ site.description }}"> <meta name="author" content="{{ site.author }}"> <!-- Bootstrap Core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="css/style.css" rel="stylesheet"> <!-- Add icon library --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css"> </head> 2) default.html in _layouts folder: chek! Structure default.html: <!DOCTYPE html> <html lang="en"> {% include head.html %} <!-- The #page-top ID is part of the scrolling feature - the data-spy and data-target are part of the built-in Bootstrap scrollspy function --> <body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top"> {% include header.html %} {{ content }} {% include footer.html %} {% include scripts.html %} </body> </html> 3) index.html in rootdirectory: chek! (homepage is working fine!) 4) new_page.md in rootdirectory: chek! (css is not rendering!) tryed new_page.html: not working either :( 5) YAML front matter in new_page.md: chek! 6) layout in YAML front matter links to default: chek! 7) When I inspect the new_page url: http://127.0.0.1:4000/boilerplate/about/ I notice the <head> is fully structured with link to css.stylesheet. Structure _config.yml: # ----------------------- # # Main Configs # # ----------------------- # url: http://werkbaar.net baseurl: /boilerplate/ title: WerkBaAr email: aline@werkbaar.net author: aline description: > # "" copyright: credits: 'Credits: ' port: 4000 # ----------------------- # # Jekyll & Plugins # # ----------------------- # plugins: # - jekyll-seo-tag # - jekyll-sitemap # Build settings markdown: kramdown permalink: pretty # ----------------------- # # 3rd Party Settings # # ----------------------- # social: - title: twitter url: - title: github url: - title: linkedin url: Link to Repo: https://github.com/bomengeduld/boilerplate/tree/gh-pages Link to actual website: werkbaar.net A: The issue is in how you are including the CSS files in your head.html include. Lines #12 and #15: <!-- Bootstrap Core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="css/style.css" rel="stylesheet"> They are using a relative path, which means that when you go to a page that is in a sub-folder of your site, like werkbaar.net/about/, the browser expects the css files to be located at werkbaar.net/about/css/bootstrap.min.css and werkbaar.net/about/css/style.css respectively. An easy way to fix this, is to start with a / when declaring your CSS files, so that you tell the browser to start from the root of your website. e.g. <!-- Bootstrap Core CSS --> <link href="/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="/css/style.css" rel="stylesheet">
doc_23537010
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script> <script> $(document).ready(function(){ $("#flip").click(function(){ $("#panel").slideToggle("slow"); }); }); </script> <style type="text/css"> #panel,#flip { padding:5px; text-align:center; background-color:#e5eecc; border:solid 1px #c3c3c3; } #panel { padding:50px; display:none; } </style> $connect = mysql_connect("127.0.0.1" , "root" , "") or die ("Couldnt connect to database"); mysql_select_db("travellerfile") or die ("couldnt find the database"); $searchsurname = $_POST['Surname']; $searchfirstname = $_POST['Firstname']; $searchage = $_POST['Age']; $query = mysql_query("SELECT * FROM child WHERE Surname like '%$searchsurname%' and Firstname like '%$searchfirstname%' and Age like '%$searchage%'"); while($row = mysql_fetch_array($query)) { ?> <div id="flip"><?php echo $row['Firstname']; ?> <?php echo $row['Surname']; ?></div> <div id="panel"><?php echo $row['DateOfBirth']; ?> <br /> <img src="<?php echo $row['sourcepath']; ?>" width="100px" height="100px"> <form method="post" action="childdetail.php"> <input name="Button1" type="submit" value="View" /></form> A: You can't have duplicate element id's, I'd suggest that you change them to classes instead: <div class="flip"> <div class="panel"> As for the jQuery, you need to know which panel to slideToggle on, based on the corresponding flip. Given your current structure, you could use the following:- $('.flip').click(function() { $(this).next('.panel').slideToggle('slow'); }); Here's a simplified example of what you were trying to achieve
doc_23537011
And when making school projects, I'm sending the netbeans project, and there's a chance that the one that will test my code don't have the newest version. Do you think I should use lambda expressions? I do like that cleaner and simpler code, but I want it to work everywhere also. A: If you are using it at school, that means that probably your teacher has Java 8 as well. Feel free to use lambda expressions if you feel that it makes your code shorter. If you let Netbeans 8 convert that into a lambda expression, you'll get something like submitButton.addActionListener(e -> {doStuff();}). This is functionally equivalent. Literally by e -> {doStuff();} you mean "make me an object of a class with function of e that matches the argument type, ActionEvent, and has the body doStuff." Lambda expressions are an extremely powerful (and cool) functional programming API in Java 8.
doc_23537012
In a web api controller I have public RedirectToRouteResult GetSlideSet(int id) { var whatdoIHave = ObjectFactory.WhatDoIHave(); var dbctx = ObjectFactory.GetInstance<MyProject.Models.MyDbContext>(); return RedirectToRoute(WebApiConfig.DefaultRouteName, new {controller="SlideSet", id}); } WhatDoIHave reports: =========================================================================================================== ...snip... MyDbContext(MyProject.Models.MyDbContext) Scoped as: HttpContext ...snip... This is the only reference to MyDbContext in WhatDoIHave Yet I get an error when calling GetInstance: StructureMap.StructureMapException occurred HResult=-2146232832 Message=StructureMap Exception Code: 202 No Default Instance defined for PluginFamily MyProject.Models.MyDbContext, MyProject, Version=2.4.5.25029, Culture=neutral, PublicKeyToken=null Source=StructureMap ErrorCode=202 StackTrace: at StructureMap.BuildSession.<.ctor>b__0(Type t) in c:\BuildAgent\work\767273992e840853\src\StructureMap\BuildSession.cs:line 33 InnerException: Does anyone know what could be wrong or how even to troubleshoot this? Edit: To Clarify, MyDbContext absolutely has a parameterless constructor but it also has a non-parameterless one (not that it should matter). I even created a unit test in my test project: [Fact] public void get() { ObjectFactory.Initialize(x => x.Configure(c => c.Configure(r => r.For<MyDbContext>().HttpContextScoped()) )); ObjectFactory.GetInstance<MyDbContext>().ShouldNotBeNull(); } Which passes just fine. Oddly enough it was failing for a while in the same manner but then started succeeding while I was trying to narrow down the issue and I couldn't recreate the error. Does structuremap do some sort of system-wide caching? A: The issue had to do after all with the fact that MyDbContext had multiple constructors. MyDbContext() : base() { } MyDbContext(connectionString) : base(connectionString) { } Removing the second one fixed the issue in the unit test. This was confounded however by my unit test runner having issues and not being able to run the latest version of the code. I've got that sorted out and can now solve the issue with For<MyDbContext>().HttpContextScoped().Use(() => new MyDbContext())
doc_23537013
This is my Simple java source code: import rx.functions.Action1; import rx.Observable; public class HelloWorld{ public static void main(String[] args) { hello("Wjm"); } public static void hello(String... names){ Observable.from(names).subscribe(new Action1<String>(){ @Override public void call(String s){ System.out.println("Hello " +s +"!"); } }); } } This is my gradle.build source code: apply plugin: 'java' jar{ manifest{ attributes 'Main-Class':'HelloWorld' } } repositories { maven { url 'https://oss.jfrog.org/libs-snapshot' } } dependencies { compile 'io.reactivex:rxjava:1.1.0' runtime 'io.reactivex:rxjava:1.1.0' } This is my project structure: . β”œβ”€β”€ build β”‚Β Β  β”œβ”€β”€ classes β”‚Β Β  β”‚Β Β  └── main β”‚Β Β  β”‚Β Β  β”œβ”€β”€ HelloWorld$1.class β”‚Β Β  β”‚Β Β  └── HelloWorld.class β”‚Β Β  β”œβ”€β”€ dependency-cache β”‚Β Β  β”œβ”€β”€ libs β”‚Β Β  β”‚Β Β  └── proj1.jar β”‚Β Β  └── tmp β”‚Β Β  β”œβ”€β”€ compileJava β”‚Β Β  β”‚Β Β  └── emptySourcePathRef β”‚Β Β  └── jar β”‚Β Β  └── MANIFEST.MF β”œβ”€β”€ build.gradle └── src └── main └── java └── HelloWorld.java I run the command "gradle build" is successful, However, when i run "java -jar proj1.jar" in the build/libs/ path, and I got the error message as follows: Error: A JNI error has occurred, please check your installation and try again Exception in thread "main" java.lang.NoClassDefFoundError: rx/functions/Action1 at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) at java.lang.Class.privateGetMethodRecursive(Class.java:3048) at java.lang.Class.getMethod0(Class.java:3018) at java.lang.Class.getMethod(Class.java:1784) at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544) at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526) Caused by: java.lang.ClassNotFoundException: rx.functions.Action1 at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... 7 more I am a fresh in gradle, so i asked, but i do a test in android studio, same java code, and run successful. A: You've added the dependency correctly but.. when you run the application via jar prepared with gradle the dependency is missing. Why? Because you didn't configure the classpath for the jar being run correctly. To fix it you need to either: * *Use shadow plugin and prepare the jar in such a way that all the dependencies will repackaged and included into resulting jar. This is done with shadowJar task. *Configure classpath manually when the prepared jar is run. E.g.: java -cp ~/.gradle/caches/modules-2/files-2.1/io.reactivex/rxjava/1.1.0/748f0546d5c3c27f1aef07270ffea0c45f0c42a4/rxjava-1.1.0.jar:build/libs/37183502.jar org.opal.Elo *Use gradle application plugin and run the main class with gradle clean run. Application plugin can also prepare some distributions with scripts to run them. Have a look at the demo. A: My answer is not the best answer but it works for me. I just downloaded all jar libraries that my project needed and put them in root of my project (or you can create a LIB directory and put them there) and just run the command below in the root of my project : java -cp *:directory_of_my_jar/my_output_jar.jar Main where "Main" is the main class of your project. if you put main class in package , write the package and class name , for example : com.example.Main java -cp *:directory_of_my_jar/my_output_jar.jar com.example.Main
doc_23537014
server { listen 80; server_name symfony.dev; root /home/vagrant/Workspace/symfony/web; access_log off; error_log /var/log/nginx/symfony.dev-error.log error; location / { # try to serve file directly, fallback to app.php try_files $uri /app.php$is_args$args; } location ~ ^/(app|app_dev|config)\.php(/|$) { fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_split_path_info ^(.+\.php)(/.*)$; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param HTTPS off; } } I looked in /etc/nginx/nginx.conf, there is : include /etc/nginx/mime.types; And in mime.types exists css,js, etc. Help me please! Thnx in advance A: You have to execute this command to install the assets in web directory : php app/console assets:install
doc_23537015
I have a datatable that has a edit and delete button for each row. The table contains the correct data. When I press the delete button for a row, I send the user to a delete confirm view. The error happens in the delete view. This is the line that errors <form id="deleteForm" class="form-horizontal" method="post" action="@if (isset($guestlist)){{ URL::to('entir/guests/' . $guestlist->id . '/delete') }}@endif" autocomplete="off"> I believe the issue is due to the $guestlist not being a object. So in the controller I use the following function to get the data public function getData() { $guestlists = Guestlist::select(array('guestlists.id', DB::raw('CONCAT(guestlists.first_name, " ", guestlists.last_name) AS g_name'),'guestlists.start_date', 'guestlists.end_date', 'guestlists.notes', 'guestlists.vendor')); return Datatables::of($guestlists)->add_column('actions', '<a href="{{{ URL::to(\'entir/guests/\' . $id . \'/edit\' ) }}}" class="iframe glyphicon glyphicon-edit"> </a> <a href="{{{ URL::to(\'entir/guests/\' . $id . \'/delete\' ) }}}" class="glyphicon glyphicon-remove"> </a> ') ->remove_column('id') ->make(); } Here is the function to call the delete view public function getDelete($guestlist) { return View::make('site/entir/guests/delete', compact('guestlist')); } If I add dd($guestlist); before the return I can see that it does not contain the row data. For example, lets say the row has a first name, last name and a few other fields. The id of this row is 10. When I review the output of the dd(); I only see this string '10' (length=2) I would have expected the object guestlist and all the row data. I am not sure why this is happening. I am using a laravel starter site (https://github.com/andrewelkins/Laravel-4-Bootstrap-Starter-Site) and I replicated what the author did for his datatable with delete button. When I add dd(); to his delete user function I see his object and the row data... I am puzzled. Thanks A: Your query doesn't fetch any data. Append ->get() to it. Guestlist::select(array('guestlists.id', DB::raw('CONCAT(guestlists.first_name, " ", guestlists.last_name) AS g_name'),'guestlists.start_date', 'guestlists.end_date', 'guestlists.notes', 'guestlists.vendor'))->get(); http://laravel.com/docs/5.0/queries If you need the results in an array, append ->get()->toArray().
doc_23537016
the code i have below will not work. I copied the below code minus the line with the http address in it. It was set up to use a local file for the .msi installer. But i have to install this on 200 computers and its just a pain in the back side to download it on each computer. Is there a way to make this work with out downloading the file? or have it download for me? @echo off echo. echo Iinstall TightVNC echo. echo. echo COPYING SETUP FILES... ... .. . copy http://www.tightvnc.com/download/2.7.10/tightvnc-2.7.10-setup-64bit.msi C:\Users\%username%\Desktop\ echo. echo. echo INSTALLING AND CONFIGURING ... ... ... .. . . msiexec /i C:\Users\%username%\Desktop\tightvnc-2.7.10-setup-64bit.msi /quiet /norestart ADDLOCAL="Server,Viewer" VIEWER_ASSOCIATE_VNC_EXTENSION=1 SERVER_REGISTER_AS_SERVICE=1 SERVER_ADD_FIREWALL_EXCEPTION=1 VIEWER_ADD_FIREWALL_EXCEPTION=1 SERVER_ALLOW_SAS=1 SET_USEVNCAUTHENTICATION=1 VALUE_OF_USEVNCAUTHENTICATION=1 SET_PASSWORD=1 VALUE_OF_PASSWORD=c0nn3cT. SET_USECONTROLAUTHENTICATION=1 VALUE_OF_USECONTROLAUTHENTICATION=1 SET_CONTROLPASSWORD=1 VALUE_OF_CONTROLPASSWORD=C0nTr0l. echo. echo. echo CLEANING UP .. .. . del C:\Users\%username%\Desktop\tightvnc-2.7.10-setup-64bit.msi echo. echo. echo FINISHED! pause
doc_23537017
I'm also making use o the meta tag viewport. For this question I'm leaving it as attached bellow. I was expecting the content (header, content, footer) to fit on the viewport (img 1) on mobiles and it does in some but I noticed that in some devices it's actually showing only part of the content and giving me a horizontal scroll bar (img 2). I've been searching a lot about viewport but couldn't find a solution about how to make it looks like img 1 on all devices. Please advice. You can view the live code at ViewPort Test . I'm not gonna change this one. For tests I'll be using the following, development VIEWPORT <meta name=viewport content="width=device-width, initial-scale=1"> CSS *{ margin:0; padding:0; border:0; } div.header, div.content, div.footer{ width:100%; } div.header{ background:blue; } div.content{ background:orange; } div.footer{ background:purple; } div.wrapper{ width:1120px; border:10px solid green; padding:0 15px 0 15px; margin:0 auto; background:red; } HTML <div class="header"> <div class="wrapper"> <h1>Header</div> </div> </div> <div class="content"> <div class="wrapper"> <h1>Content</h1> </div> </div> <div class="footer"> <div class="wrapper"> <h1>Footer</h1> </div> </div> A: If you aren't using media queries and you just want the 1170px wide fixed layout to fill the mobile screen, then change this: <meta name=viewport content="width=device-width, initial-scale=1"> to this: <meta name="viewport" content="width=1170"> A: Great Stuff, however, I have discovered that if you are on a desktop and the viewport is set to a static width the backgrounds may not render on the portions of the screen not shown when you horizontal scroll. To fix this for non-responsive pages simply add a min-width to the body. body { min-width: 1170px; } Note, this is in addition to setting the viewport a static width <meta name=viewport content="width=1170"> A: Considering that this is a non-responsive website all the metatag viewport needs it the website width, on my case, 1170px. The metatag viewport looks like this now: <meta name=viewport content="width=1170">
doc_23537018
I would like to extend it such that the entire C column runs the same formula for values. Please help. If a script is necessary to achieve this, I'd like to explore that option too. A: Use Apps Script! Sheet functions (formulae) work great (especially if you are a master like player0), but I find it much easier to work within Apps Script for anything much more complicated than a simple INDEX MATCH. If you are willing to learn some JavaScript, I highly recommend learning some. Custom Functions You can write custom sheet functions in Apps Script that you can call with the traditional =FUNCTION() from a cell. The way it works is that you write a function in Apps Script that returns a two dimensional array corresponding to the area that it needs to fill. For example, if wanted a function to fill a 2 x 2 block with 1, you would need to make your function return: [[1,1],[1,1]] Or you can write it like this: [ [1, 1], [1, 1] ] Implementing Index Match There are many ways you can implement it, here is an example. The example spreadsheet has 2 tabs, "Ledger" and "Items". The goal of the function that follows is to get the costs of the items from the "Items" tab. function ledgerIndexMatch(){ // Initializing the location of data let ss = SpreadsheetApp.getActive(); let ledger = ss.getSheetByName("Ledger"); let source = ss.getSheetByName("Items"); let ledgerRange = ledger.getDataRange(); let sourceRange = source.getDataRange(); // Getting the values into a 2D array let ledgerValues = ledgerRange.getValues(); let sourceValues = sourceRange.getValues(); // Discarding the first row (headers) ledgerValues.shift(); sourceValues.shift(); // Initializing the output array let output = []; // This is where the INDEX MATCH happens // For each row in ledger ledgerValues.forEach(ledgerRow => { // Get the second column (index 1) let item = ledgerRow[1]; // Initialize the column let value = []; // For each row in the source sourceValues.some(sourceRow => { // Check if the item is there if (item == sourceRow[0]) { // if so, add to value value.push(sourceRow[1]); // stop looking for values return true // if not matched, keep looking } else return false }) // Add the found value (or blank if not found) // to the output array. output.push(value); }) return output; } Which can be used like this: Whats nice about Apps Script is that you can customize it to your heart's content. In this example, the function automatically detects the height of the respective tables, so you don't need to fiddle around with ranges. You might want to extend this function with arguments so that its more flexible. Or you could just have a few versions of it for different operations, if you don't have too many. Or refactor it... its up to you. References * *Apps Script *Custom Functions *Tutorials *SpreadsheetApp A: use: =ARRAYFORMULA(IFNA(VLOOKUP(C2:C, Items!E2:F, 2, 0)))
doc_23537019
Please help me. Thank you. A: If you are trying to reuse an image fetched in ActivityA in ActivityB without fetching again, you don't have to do anything apart from calling Picasso.with(context).load(url).into(imageView) at both places. If the url parameter is the same for both the activities, Picasso automatically fetches the image from cache(where it got stored when you called load in ActivityA) instead of making another network call. Picasso automatically caches your image in the RAM, and uses okhttp internally to cache it in the disk. So, you don't have to pass it explicitly through an intent. To check where it got loaded from, you can call Picasso.with(getContext()).setIndicatorsEnabled(true). This will put a colored flag on the top-left corner of every image. Red means it was called fetched from the network. Blue- disk. Green- RAM. In ActivityA, it should be Red since you're loading it from the network. In ActivityB, it should be Green(or blue), since you're fetching it from the cache. A: I think you need to create another imageView into ActivityB and when user click on some gridView element pass the imageUrl of element and load passed url on the ActivityB either way i think you can`t pass already loaded imageView to ActivityB without loaded image again..
doc_23537020
Im using fiddler to find out the GET and POST requests I need to make. Done that and my app is successfully recreating these as best as I can see. The steps are; 1) GET request with cookie container to login uri. server response sets new cookie called jsessionID 2) do POST request with login credentials and same cookie container containing previous jsessionID. Looking at the fiddler logs for successful POST request login (browser or my app) I see it sets a thing in the response header : "Set-cookie: supercookie=-; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Path=". What is this supercookie thing? Its not returned to me in the response cookie collection like the jsessionID. On rare occasions, there is along string of numbers with the supercookie instead of just "-". I made sure to clear all cookies before analyzing the request/response headers. If the super cookie thing is not being set in the reponse my login fails. So just wondering what's going on here? cheers! A: supercookie is just a name of another cookie. It's quite possible they are using that to prevent screen scraping. Make sure when you receive that response that the cookie container now holds that new supercookie cookie.
doc_23537021
My solution is to create a list of size 26 and append letters A-Z into each sequence using a variable called alphabet = "abcdefghijklmnopqrstuvwxyz" and iterating over it with a Repeat block and appending LETTER COUNT of ALPHABET to the list.The result is a list data structure with letters A_Z between location 1 to 26.In effect creating my own ASCII table. To do a converson say from number 26 to 'Z' I have to iterate over the list to get the correct CHAR value. It really slows down the program that is heavily dependent on the CHR() feature. Is there a better or more efficient solution? A: My solution is to create a list of size 26 and append letters A-Z into each sequence using a variable called alphabet = "abcdefghijklmnopqrstuvwxyz" Stop right there. You don't even need to convert it into a list. You can just look it up directly from the string. To get a character from an index is very easy. Just use the (letter () of []) block. To get the index of a character is more complex. Unfortunately, Scratch doesn't have a built-in way to do that. What i would do here is define a index of [] in [] custom pseudo-reporter block: define index of (char) in (str) set [i v] to [1] repeat until <<(i) = (length of (str))> or <(letter (i) of (str)) = (char)>> change [i v] by (1) view online You can then call the block as index of [a] in (alphabet) and it will set the i variable to 1. This code doesn't have any case for if the character isn't found, but the link i provided does include that, if you need. A: You could also use Snap! which is similar to Scratch, but has more blocks. Snap! has a unicode block, that will convert a character to its ASCII or unicode value.
doc_23537022
Once the download is complete the requestFinished is called via the ASIHTTPReqest delegate. That part is working correctly. I get the file and I see it on the file system. Then I immediately try to unzip the file from the requestFinished callback, but the unzip fails. If I call the method to unzip the file afterwards, via a user interface event after the fact, the unzip works perfectly. I even tried calling the unzip method via [self.performSelectorOnMainThread] but that doesn't work. Is the file locked? Is it not really there? Is there an easy way to say "wait a second and then do this"? Or is that even needed? Thanks for any help. A: 0x8badf00d got if fixed for me by using this [self performSelector:@selector(unzipAction) withObject:nil afterDelay:1.0f];
doc_23537023
File containing the action I want to test: technology.js (action) import { types } from "../types/types"; import swal from "sweetalert"; export const startFetchTechnologies = () => { return async (dispatch) => { try { dispatch(startLoading()); const res = await fetch( "http://url.com/techs" ); const data = await res.json(); dispatch(loadTechnologies(data)); } catch (error) { await swal("Error", "An error has occurred", "error"); } dispatch(finishLoading()); }; }; export const loadTechnologies = (data) => ({ type: types.loadTechnologies, payload: data, }); export const startLoading = () => ({ type: types.startLoadTechnologies, }); export const finishLoading = () => ({ type: types.endLoadTechnologies, }); File containing the tests I want to perform: technology.test.js (test) import { startFetchTechnologies } from "../../actions/technology"; import { types } from "../../types/types"; import configureMockStore from "redux-mock-store"; import thunk from "redux-thunk"; import fetchMock from "fetch-mock"; import expect from "expect"; // You can use any testing library const middlewares = [thunk]; const mockStore = configureMockStore(middlewares); describe("startFetchTechnologies", () => { afterEach(() => { fetchMock.restore(); }); beforeEach(() => { jest.setTimeout(10000); }); test("startFetchTechnologies", () => { // fetchMock.getOnce("/todos", { // body: { todos: ["do something"] }, // headers: { "content-type": "application/json" }, // }); const expectedActions = [ { type: types.startLoadTechnologies }, { type: types.loadTechnologies, payload: "asd" }, { type: types.endLoadTechnologies }, ]; const store = mockStore({}); return store.dispatch(startFetchTechnologies()).then(() => { // return of async actions expect(store.getActions()).toEqual(expectedActions); }); }); }); The console outputs the following: FAIL src/__test__/actions/technology.test.js (11.407 s) startFetchTechnologies βœ• startFetchTechnologies (10029 ms) ● startFetchTechnologies β€Ί startFetchTechnologies : Timeout - Async callback was not invoked within the 10000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 10000 ms timeout specified by jest.setTimeout.Error: 19 | }); 20 | > 21 | test("startFetchTechnologies", () => { | ^ 22 | 23 | // fetchMock.getOnce("/todos", { 24 | // body: { todos: ["do something"] }, I have tried increasing the timeout to 30000 and the test keeps failing. I hope you can help me! A: I have made the test pass but I am not sure if I am doing it correctly, could someone tell me if it is well done? Thank you! import { startFetchTechnologies } from "../../actions/technology"; import { types } from "../../types/types"; import configureMockStore from "redux-mock-store"; import thunk from "redux-thunk"; import fetchMock from "fetch-mock"; import expect from "expect"; // You can use any testing library const middlewares = [thunk]; const mockStore = configureMockStore(middlewares); describe("startFetchTechnologies", () => { beforeEach(() => { // jest.setTimeout(10000); }); afterEach(() => { fetchMock.restore(); }); test("startFetchTechnologies", () => { fetchMock.getOnce("https://url.com/tech", { body: { payload: ['asd'] }, headers: { "content-type": "application/json" }, }); const expectedActions = [ { type: types.startLoadTechnologies }, { type: types.loadTechnologies, payload: {payload: ['asd']} }, { type: types.endLoadTechnologies }, ]; const store = mockStore({}); return store.dispatch(startFetchTechnologies()).then(() => { // return of async actions expect(store.getActions()).toEqual(expectedActions); }); }); });
doc_23537024
class MainMenuVC: UIViewController { @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var checkinStatusLabel: UILabel! var employee : Employee? var time : String? var date : String? override func viewDidLoad() { super.viewDidLoad() getDateTimeFromServer() } func getDateTimeFromServer() { // request to server to get date and time // update the UI (date and time label) } } but the problem is, the time data will always be the same, of course since I request only once to the server so the 'minute' will be static. it will be a problem for this attendance app. let say when the user open that menu on 15:23, but when they actually tap the checkin button 7 minutes later, so the data that will be sent back to server is 15:23 (when the viewDidLoad firstly activated) not 15:30. so how do i tackle this problem so the time will always be updated and will always be the same as the time from server for my UI label and for my Date class ? A: This is a simple programming problem. You either need to * *Request the time from the server each time you need a time. or *Fetch the time from the server once, convert it to a Date, get the current date from your device, calculate the difference, and use that difference as an offset. The next time the user taps the checkin button, get the current Date from the device, add your offset, and use that as the current Date. I leave it to you to figure out the details of how to do that. Take a look at the Date class reference in Xcode. There are methods that let you convert between Dates and numeric values, and apply numeric offsets to Dates.
doc_23537025
<div id="attach" style="height: 500px; width: 500px; background: red;"></div> The page fragment in test.html: <div id="test"> <h3>this is a page fragment</h3> </div> I'm using jQuery as below: $('#attach').load("/test.html #test"); Based on jQuery documentation this should work, however I get the following error: Uncaught TypeError: Q[a].exec is not a function My version of jQuery is 1.10.2. I see that the page is loaded from the server but the page fragment is not extracted. Any thoughts as to why? Thanks.
doc_23537026
What I have tried: df = df[['Country', 'Year','NumInstances']].groupby(['Country', 'Year']).agg(['count']) df = df.sort_values(by='NumInstances', ascending=False) print(df) Error: ValueError: The column label 'NumInstances' is not unique. For a multi-index, the label must be a tuple with elements corresponding to each level. Before this gets mark as a duplicate, I have gone through all other suggested duplicates and it seems they all suggest using the same code as I have above. Is there something small that I am doing that may be incorrect? Thanks! A: I guess you need to remove multi-index - Try this - df = df[['Country', 'Year','NumInstances']].groupby(['Country', 'Year']).agg(['count']).reset_index() or - df = df[['Country', 'Year','NumInstances']].groupby(['Country', 'Year'], as_index=False).agg(['count']) A: Found the issue. Adding an agg to the NumInstances column made the NumInstances column name a tuple of ('NumInstances', 'sum'), therefore I just updated the sort code to: df = df.sort_values(by=('NumInstances', 'sum'), ascending=False)
doc_23537027
@IBAction func SAVEButtonTapped(sender: AnyObject) { let viewcontroller = SecondViewController(); viewcontroller.name = self.nametextfield.text; viewcontroller.phone = self.phonetextfield.text; viewcontroller.city = self.citytextfield.text; } A: I found my Problem @IBAction func SAVEButtonTapped(sender: AnyObject) { let viewcontroller = SecondViewController(); viewcontroller.name = self.nametextfield.text; viewcontroller.phone = self.phonetextfield.text; viewcontroller.city = self.citytextfield.text; } problem with this line let viewcontroller = SecondViewController() i changed it to let viewcontroller = self.storyboard!.instantiateViewControllerWithIdentifier("SecondViewController") as! SecondviewController With This change My code working fine thanks.. A: Try this in FirstViewController, - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { UIViewController *destinationVC = [segue destinationViewController]; If ([destinationVC isKindOfClass:[SecondViewController class]]) { SecondViewController *viewcontroller = (SecondViewController *)destinationVC; viewcontroller.name = self.nametextfield.text; viewcontroller.phone = self.phonetextfield.text; viewcontroller.city = self.citytextfield.text; } } Assuming that you have only one segue to SecondViewController. If you have multiple segue to SecondViewController then you can check segue identifier instead of isKindOfClass check. A: What you are doing will not work because your views will not be initialized until viewDidLoad: is executed. Basically, you're assigning values to nil objects. You either need to add string properties that you later assign to your view elements in viewDidLoad or do what Akhilrajtr mentioned if you are using a segue for your transition. A: pass the data between VC create a intent for destination VC,like below SecondViewController *controller = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil]; viewcontroller.name = self.nametextfield.text; viewcontroller.phone = self.phonetextfield.text; viewcontroller.city = self.citytextfield.text; [self.navigationController pushViewController:controller animated:YES];
doc_23537028
For various reasons, we want to (for testing) trigger the harder version (e.g. click all the images that show food) instead of just the "I am not a robot" checkbox. A: You might just use iMacros code. It makes google to suspect bot visiting and thus put forth the image puzzle. VERSION BUILD=9052613 TAB T=1 TAB CLOSEALLOTHERS ' you need to insert get other url where ReCaptcha is located. URL GOTO=http://... ' we generate random number to make robot wait some seconds (1-6 seconds) SET !VAR1 EVAL("var randomNumber=Math.floor(Math.random()*5 + 1); randomNumber;") WAIT SECONDS={{!VAR1}} FRAME F=1 TAG POS=1 TYPE=SPAN ATTR=ID:recaptcha-anchor
doc_23537029
In the following example, the bbar for the panel is displayed 2ems narrower than the panel it is attached to (it's left aligned) in IE6, where as in Firefox it is displayed as the same width as the panel. Can anyone suggest how to fix this? I seem to be able to work around either by specifying the width of the panel in ems or the padding in pixels, but I assume it would be expected to work as I have it below. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <link rel="stylesheet" type="text/css" href="ext/resources/css/ext-all.css"/> <script type="text/javascript" src="ext/ext-base.js"></script> <script type="text/javascript" src="ext/ext-all-debug.js"></script> <script type="text/javascript"> Ext.onReady(function(){ var main = new Ext.Panel({ renderTo: 'content', bodyStyle: 'padding: 1em;', width: 500, html: "Alignment issue in IE - The bbar's width is 2ems less than the main panel in IE6.", bbar: [ "->", {id: "continue", text: 'Continue'} ] }); }); </script> </head> <body> <div id="content"></div> </body> </html> A: Maybe you should try to force the width of the bbar: main.getBottomToolbar().setWidth(500) right after Panel creation? But I think the problem is that bbar is rendered into inner div of the panel, so different browsers interpret outer padding differently. Also you can try to set padding of the bbar to -1em. A: The problem comes from the custom bodyStyle padding. It makes the panel content larger, but not the toolbar. One possible solution is to further nest an Ext panel, like: var main = new Ext.Panel({ renderTo: 'content', width: 500, items: { bodyStyle: 'padding: 1em;', border: false, html: "Now alignment is fine." }, bbar: [ "->", {id: "continue", text: 'Continue'} ] }); The border: false is needed to avoid double bordering.
doc_23537030
$this->db->from('addresses'); $this->db->where('user_id', $this->session->userdata('user.id')); $this->db->like('country', $pSearch); $this->db->or_like('state', $pSearch); $this->db->or_like('city', $pSearch); $this->db->or_like('zip', $pSearch); which generates the following SQL SELECT * FROM (`addresses`) WHERE `user_id` = '1' AND `country` LIKE '%d%' OR `state` LIKE '%d%' OR `city` LIKE '%d%' OR `zip` LIKE '%d%' ORDER BY `country` asc LIMIT 15 Is there a way to make it generate it like this: SELECT * FROM (`addresses`) WHERE `user_id` = '1' AND (`country` LIKE '%d%' OR `state` LIKE '%d%' OR `city` LIKE '%d%' OR `zip` LIKE '%d%') ORDER BY `country` asc LIMIT 15 As i whant to get only the records for user_id = 1 and not for all users. A: That seems to be a bug/limitation in CI ActiveRecord. You could try Ignited Query, which has the ability to handle nested WHERE clauses, and probably can handle the nested WHERE/LIKE the way you like. Check out this thread also for more info.
doc_23537031
The only problem I am running into is that to draw in Java the drawing is from x & y which are both located at 0, moving x left(West), and y is going south. Resizing the width is simple since I am just using a method with a single parameter to increase or decrease width. With height, moving it up is fine (I have y set at 340 since that is the base I'd like to stay at). When I move the JSlider down, it moves down but will not reach the same height it was once at. I would really like to make is seem like the rectangle is moving the same way the JSlider is moving. Main Applet Page (Where the JSliders are located): import java.awt.BorderLayout; import java.awt.Color; import javax.swing.JApplet; import javax.swing.JLabel; import javax.swing.JSlider; import javax.swing.SwingConstants; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class ResizeRectangle extends JApplet { private JSlider sliderHeight; private JSlider sliderWidth; private JLabel title; private Contents content; private int oldValue = 0; public void init(){ setLayout(new BorderLayout()); title = new JLabel("Rectangle Resizer"); content = new Contents(); content.setBackground(Color.WHITE); //Slider for increasing the height sliderHeight = new JSlider(SwingConstants.VERTICAL, 10, 100, 10); sliderHeight.setMajorTickSpacing(10); sliderHeight.setPaintTicks(true); sliderHeight.addChangeListener( new ChangeListener(){ public void stateChanged(ChangeEvent e){ //If sliderHeight is greater than oldValue pass true for increase if(sliderHeight.getValue() > oldValue){ content.setHeight(sliderHeight.getValue(), true); } //Else if sliderHeight is less than oldValue pass false for increase else if(sliderHeight.getValue() < oldValue){ content.setHeight(sliderHeight.getValue(), false); } //Sets the value of sliderHeight to the value of oldValue to compare later oldValue = sliderHeight.getValue(); } } ); //Slider for increasing the widht sliderWidth = new JSlider(SwingConstants.HORIZONTAL, 10, 100, 10); sliderWidth.setMajorTickSpacing(10); sliderWidth.setPaintTicks(true); sliderWidth.addChangeListener( new ChangeListener(){ public void stateChanged(ChangeEvent e){ content.setWidth(sliderWidth.getValue()); } } ); content.setBackground(Color.WHITE); add(title, BorderLayout.NORTH); add(content, BorderLayout.CENTER); add(sliderWidth, BorderLayout.SOUTH); add(sliderHeight, BorderLayout.EAST); } } This is the code for setting the height (as well as width): import java.awt.Component; import java.awt.Graphics; public class Contents extends Component { private int height = 10; private int width = 10; //Initialize y to 340. private int y = 340; //Draw the rectangle public void paint(Graphics g){ g.fillRect(5, y, width, height); } public void setHeight(int h, boolean increase){ //If the slider is increasing, decrease y and increase height to give it the // look of rising if(increase){ y = y - h; height = height + h; } //else do the opposite else{ y = y + h; height = height - h; } //For debugging purposes System.out.println("h = "+h); System.out.println("y = "+y); System.out.println("height = "+height+"\n\n"); //Repaint the rectangle repaint(); } //Set the width and repaint public void setWidth(int w){ width = w; repaint(); } } This is my third month of learning Java and I would greatly appreciate any feedback. Thank you in advance. A: You have a logic issue with your code. The call used to change the height inside the change listener is content.setHeight(sliderHeight.getValue(), ...); which looks reasonable on first sight. However the method setHeight does not do what the name suggest (i.e. setting the hight) but instead increases or decreases the height by the amount given as first argument: if(increase){ y = y - h; height = height + h; } else { y = y + h; height = height - h; } Thus if the slider changes from 10 to 20 and back to 10 you have the following change of values: // initial values y = 340 height = 10 // change from 10 to 20, thus h=20 and increase as arguments for the method y -> 340 - 20 = 320 height -> 10 + 20 = 30 // change from 20 back to 10, i.e. h=10 and decrease y -> 320 + 10 = 330 height -> 30 - 10 = 20 What the method should do instead is indeed set the height, i.e. y = 340 - h; height = h;
doc_23537032
but it return the fatel error error Fatal error: require(): Failed opening required '/home/customer/www/easy-websites.online/public_html/../quickquiz/vendor/autoload.php' (include_path='.:/usr/local/php73/pear') in /home/customer/www/easy-websites.online/public_html/index.php on line 24 I have not seperate directory for quickapp but it show in error I am uploading all my project files and folder in public_html index.php require __DIR__.'/vendor/autoload.php'; $app = require_once __DIR__.'/bootstrap/app.php'; .htacess <IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews </IfModule> RewriteEngine On # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] </IfModule> file structure publichtml{ app bootstrap etc.. index.php .htaccess vendor { autoload.php} } index.php and .htaccess under public_html and autoload.php under vendor folder A: Deploy laravel app on Cpanel requires some different steps and can be handled by different ways for me this is the best way we can summarize in * *uploading files inside laravel public folder to Cpanel public_html *create another directory in Cpanel /home that will contain the rest of your laravel app (at the same level of Public_html) *upload the rest of the files exclude public to the new directory you just created *Open the index.php file on public_html/index.php and Replace the require path to be ./../YOUR_DIRECTORY_NAME/vendor/autoload.php *same for bootstrap in the same file replace app.php require path to the correct path by adding Your DIRECTORY_NAME *you may also need to change the import path of index.php in your DIRECTORY_NAME/server.php file For more information and a good explanation with images you can follow this tutorial Deploy Laravel Project on Shared Hosting CPanel
doc_23537033
If I set a height, it goes from https://i.stack.imgur.com/GH3UT.png to https://i.stack.imgur.com/rjj6D.png. Code #home { height: 600px; position: relative; } .overlay { position: absolute; left: 0; bottom: 0; width: 100vw; height: 250px; <- setting this causes it } Within my body I have body { position: absolute; } HTML Code <section id="home"> <div class="container-fluid"> <img src="assets/img/shape.svg" class="overlay"> </div> </section> Thanks in advance! A: By setting the height, the image is just resizing as you've told it to. Remove the height and on .overlay just set your bottom position to whatever negative value you're happy with.
doc_23537034
MY dataframe looks like: root |-- CreatedOn: string (nullable = true) |-- ID: string (nullable = true) |-- Industry: string (nullable = true) |-- region: string (nullable = true) |-- Customer: string (nullable = true) For eg. count number of times the ID and region were used in last 3/2/1 months. For this I have to scan the entire dataframe w.r.t to the current record. Current logic: 1. for i in df.collect() - Row-wise collect. 2. Filter the data 3 months before this row. 3. Generate features. The code is working fine but since it is a rowwise loop, it is running >10hrs. Is there any way I can replace the row-wise operation in Pyspark, since it is not leveraging the parallelism that pyspark provides. Something like groupby?? Sample data: S.No ID CreatedOn Industry Region 1 ERP 05thMa2020 Communications USA 2 ERP 28thSept2020 Communications USA 3 ERP 15thOct2020 Communications Europe 4 ERP 15thNov2020 Communications Europe 5 Cloud 1stDec2020 Insurance Europe Consider record#4.. Feature 1 (Count_3monthsRegion): I want to see how many times ERP was used in Europe in the last 3 months (w.r.t CreatedOn). The answer will be 1. (Although record#2 is ERP but in same region) Feature 2(Count_3monthsIndustry): I want to see how many times ERP was used in Communications in the last 3 months (w.r.t CreatedOn). The answer will be 2. Expected output: S.No ID CreatedOn Industry Region Count_3monthsRegion Count_3monthsIndustry 1 ERP 05thMay2020 Communications USA 0 0 2 ERP 28thSept2020 Communications USA 0 0 3 ERP 15thOct2020 Communications Europe 0 1 4 ERP 15thNov2020 Communications Europe 1 2 5 Cloud 1stDec2020 Insurance Europe 0 0
doc_23537035
A: This is only possible for private repositories managed by organisations. * *https://docs.github.com/en/organizations/managing-access-to-your-organizations-repositories/repository-permission-levels-for-an-organization If your repository is an organisation one, you can visit: * *https://github.com/`OWNER`/`REPO`/settings/access You can then add a collaborator and set their permission level to: * *Read: Recommended for non-code contributors who want to view or discuss your project *Triage: Recommended for contributors who need to proactively manage issues and pull requests without write access *Write: Recommended for contributors who actively push to your project *Maintain: Recommended for project managers who need to manage the repository without access to sensitive or destructive actions *Admin: Recommended for people who need full access to the project, including sensitive and destructive actions like managing security or deleting a repository
doc_23537036
How important is the safeness of a services password (mysql, for example) inside a single namespace? My thoughts: It's not important at all. Why? All related pods include the password anyway and the services are not available outside of the specific namespace. Though someone would gain access to a pod in that specific namespace, printenv would give him all he needs. My specific case (Helm): If I set up my mysql server as a requirement (requirements.yaml), I don't have to use any secrets or make effort to share the mysql password and can provide the password in values.yaml. A: While Kubernetes secrets aren't that secret, they are more secret than Helm values. Fundamentally I'd suggest this question is more about how much you trust humans with the database password than any particular process. Three approaches come to mind: * *You pass the database password via Helm values. Helm isn't especially access-controlled, so anyone who can helm install or helm rollback can also helm get values and find out the password. If you don't care whether these humans have the password (all deployments are run via an automated system; all deployments are run by the devops team who has all the passwords anyways; you're a 10-person startup) then this works. *The database password is in an RBAC-protected Secret. You can use Kubernetes role-based access control so that ordinary users can't directly read the contents of Secrets. Some administrator creates the Secret, and the Pod mounts it or injects it as an environment variable. Now you don't need the password yourself to be able to deploy, and you can't trivially extract it (but it's not that much work to dump it out, if you can launch an arbitrary container). *The application gets the database password from some external source at startup time. Hashicorp's Vault is the solution I've worked with here: the Pod runs with a Kubernetes service account, which it uses to get a token from Vault, and then it uses that to get the database password. The advanced version of this hands out single-use credentials that can be traced back to a specific Pod and service account. This is the most complex path, but also the most secure.
doc_23537037
import ( "code.google.com/p/go.net/websocket" "fmt" "log" "net/http" "os" ) type MessageReceived struct { Name string Nbmsg int } func Echo(ws *websocket.Conn) { msg := new(MessageReceived) for { websocket.JSON.Receive(ws, &msg) fmt.Printf("Received message: %+v\n", msg) if err := websocket.JSON.Send(ws, msg); err != nil { fmt.Println("Can't send echo") break } //os.Exit(0) } } func checkError(err error) { if err != nil { log.Printf("Fatal error: %s\n", err.Error()) os.Exit(1) } } func main() { http.Handle("/s", websocket.Handler(Echo)) fs := http.FileServer(http.Dir("web")) err := http.ListenAndServe(":8081",fs) checkError(err) } The page and static files gets served but when but i try to connect to the websocket from javascript i get WebSocket connection to 'ws://localhost:8081/s' failed: Error during WebSocket handshake: Unexpected response code: 404 The only way i could make it work is by serving static files from a different go application server and serving the websocket also from a separate server application using 2 different ports on the local host, what am i missing in the above sample? how could i serve files and the websocket from the same server? A: You're assigning the websocket.Handler to the DefaultServeMux, but only using the FileServer handler in your ListenAndServe call. Add the FileServer handler to the DefaultServe mux too, with some non-conflicting prefix: func main() { http.Handle("/s", websocket.Handler(Echo)) http.Handle("/f", http.FileServer(http.Dir("web")) err := http.ListenAndServe(":8081", nil) checkError(err) }
doc_23537038
I tried the code below and don't work it gives me wrong date , i think has something to do with the amount of digits $epoch = 1532131481886863; $dt = new DateTime("@$epoch"); // convert UNIX timestamp to PHP DateTime echo $dt->format('Y-m-d H:i:s'); A: The only thing I can think of is that the last six digits is microseconds. So splitting the number will give you correct date and time. echo date("Y-m-d H:i:s", substr($epoch, 0,-6)); // Optionally you can echo the microseconds also. echo " " . substr($epoch, -6); https://3v4l.org/QDQnc A: <?php // Divide by 1000*1000 because given number is epoch with microseconds // but the DateTime expects time in seconds // By dividing we will get 1532131481.886863 // We dont need the microseconds so we cast (int) on it to get 1532131481 $epoch = (int)((1532131481886863 /1000) /1000); $dt = new DateTime("@$epoch"); // convert UNIX timestamp to PHP DateTime echo $dt->format('Y-m-d H:i:s');
doc_23537039
private async Task DoAsync() { Console.WriteLine(@"(1.1)"); Thread.Sleep(200); Console.WriteLine(@"(1.2)"); await Task.Delay(1000); Console.WriteLine(@"(1.3)"); } and you call it asynchronously with Dispatcher: Console.WriteLine(@"(1)"); await Application.Current.Dispatcher.InvokeAsync(DoAsync); Console.WriteLine(@"(2)"); The output you'll get will be: (1) (1.1) (1.2) (2) (1.3) If you use Dispatcher.BeginInvoke() and you'll wait for Completed event, the effect will be the same (which is expected): Console.WriteLine(@"(1)"); var dispatcherOp = Dispatcher.BeginInvoke(new Func<Task>(DoAsync)); dispatcherOp.Completed += (s, args) => { Console.WriteLine(@"(2)"); }; What we see here is that the await in DoAsync() method makes Dispatcher believe the operation ended. My question: is it a bug or a feature? Do you know any document that describes this behavior? I couldn't find anything. I'm not asking for a workaround. A: It is a bug in your code, the object returned from Application.Current.Dispatcher.InvokeAsync(DoAsync); is a Task<Task>, you only await the outer task, not waiting for the inner task to complete. These situations is what .Unwrap() is for. Console.WriteLine(@"(1)"); await Application.Current.Dispatcher.InvokeAsync(DoAsync).Unwrap(); Console.WriteLine(@"(2)"); The output you will get will be: (1) (1.1) (1.2) (1.3) (2) What Unwrap is doing is effectively turning your code in to Console.WriteLine(@"(1)"); await (await Application.Current.Dispatcher.InvokeAsync(DoAsync)); Console.WriteLine(@"(2)"); But with a nicer looking format. For documentation see "How to: Unwrap a nested task"
doc_23537040
INSERT INTO movies table (movie_id, release_year, movie_title,movie_descrption, number_in_stock_,rental_or_sale_or_both, rental_daily_rate) INSERT INTO movies VALUES('10101', '1985','top gun', 'airplains', '50', 'both', '$5' And here is my table SQL database table for Movies tables CREATE TABLE movies_id ( movie_id VARCHAR NOT NULL PRIMARY KEY, release_year DATE NOT NULL, movie_title VARCHAR (50) NOT NULL, movie_description VARCHAR (50) NOT NULL, number_in_stock VARCHAR (50) NOT NULL, rental_or_sale_or_both VARCHAR (50) NOT NULL, rental_daily_rate VARCHAR (50) NOT NULL ); A: '1985' is not a correct DATE value, some field names are mistyped. Try with following statements: CREATE TABLE movies_id ( movie_id VARCHAR NOT NULL PRIMARY KEY, release_year DATE NOT NULL, movie_title VARCHAR (50) NOT NULL, movie_description VARCHAR (50) NOT NULL, number_in_stock VARCHAR (50) NOT NULL, rental_or_sale_or_both VARCHAR (50) NOT NULL, rental_daily_rate VARCHAR (50) NOT NULL ); INSERT INTO movies_id (movie_id, release_year, movie_title, movie_description, number_in_stock, rental_or_sale_or_both, rental_daily_rate) VALUES ('10101', '1985-01-01','top gun', 'airplains', '50', 'both', '$5') Working Demo A: Try to this first create this table and run the insert syntax Create Table movies(movie_id VARCHAR Not NULL PRIMARY key, release_year date not null, movie_title VARCHAR (50) NOT NULL, movie_description VARCHAR (50) NOT NULL, number_in_stock VARCHAR (50) NOT NULL, rental_or_sale_or_both VARCHAR (50) NOT NULL, rental_daily_rate VARCHAR (50) NOT NULL ); insert into movies values('10101', '1985','top gun', 'airplains', '50', 'both', '$5'); A: The correct way is: INSERT INTO movies (movie_id, release_year, movie_title,movie_descrption, number_in_stock_,rental_or_sale_or_both, rental_daily_rate) VALUES('10101', '1985','top gun', 'airplains', '50', 'both', '$5') or short version insert (considering the creation' order of attributes in table) INSERT INTO movies VALUES('10101', '1985','top gun', 'airplains', '50', 'both', '$5')
doc_23537041
var = [8113,8114,8112] def avg(): for i in range (len(var)): mycursor.execute("SELECT list_id, avg(called_count) FROM list WHERE list_id ={}".format(var[i])) myresult = mycursor.fetchall() for x in myresult: print(x[1]) avg() If I use print(x) then it will return: (8113, Decimal('1.5814')) (8114, Decimal('0.0928')) (8112, Decimal('1.9127')) If I just use print(x[1]) then it will return just the result 1.5816 0.0934 1.9128 I am trying to pass the output to a dataframe with 2 columns being "list_id" and "result" A: You could use pd.read_sql for this. Also, it would be possible to run just one query, rather than one for each element in the list, which would be faster. id_list_string = "','".join(var) sql_query = f"SELECT list_id, avg(called_count) FROM list WHERE list_id IN ('{id_list_string}');" df = pd.read_sql( sql=sql_query, con=mycursor ) The above solution also uses f-strings.
doc_23537042
What we have - * *SVN Code base where all of code has been stored. *Multiple unrelated dev orgs. *Current Org and code base have lots of Apex, Pages, Email templates, reports, dashboards, Workflow , Profiles, triggers and most of the standard as well as Custom Salesforce functionalities. What we want to do - 1. A simplified mechanism or way which can be used to deploy all of org to some unrealted dev / partner orgs. What we have tried - 1. We tried the same using Eclipse and it takes almost 6-7 hours to complete activity and that too has a probability of missing out things due to dependecies among multiple compinents. A very big headache with this approach. 2. Use Ant Migration tool. Using Force.com Migration tool and Ant commands, we tried deploying for first time to unrelated org. But it gave at least 400 -500 errors over command prompt. Not sure how to make this work. Do we have easer way or we need to go ahead and solve each issue one by one. We dont have provision for Change Sets or Sandbox / Production org as we are creating a package for multiple users. Please let me know about any other possible ways that can be used to migrate huge code base (standard + Custom SF components) to any unrelated dev org. Any help would be appreciated. Thanks, Kaushik A: When we need to deploy SF project to new org manually (or update current one manually), we usually deploy parts of a project in such sequence: * *static res *labels *groups *roles *letterhead *documents *OBJETCS *tabs *apps *email *classes *pages *components *layouts *triggers *workflows *reports *dashbords *homepage layouts *homepage components *profiles *permission sets This allows us to to avoid mistakes related to dependencies in the components of the project. Also we use some tools for continuous integration (e.g. Jenkins which deploys all changes (which are commited to repository) to CI org and every night deploys builds on QA org).
doc_23537043
<xsl:apply-templates select="file:file/file:description" /> Why are there 3 files ? I know one of my tags in the XML file is named "file", but why prefixing "file:" ? Here's the actual code: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml" xmlns:file="http://phpdox.de/xml#" exclude-result-prefixes="#default file" > <xsl:output method="html" indent="yes" encoding="utf-8" /> <xsl:template match="/"> <html> <body> <xsl:apply-templates select="file:file/file:description" /> </body> </html> <xsl:template match="file:description"> <header> <p><xsl:value-of select="@compact" /></p> <p><xsl:value-of select="file:description" /></p> </header> </xsl:template> </xsl:stylesheet> And the source XML file: <?xml version="1.0" encoding="UTF-8"?> <file xmlns="http://phpdox.de/xml#"> <class> <docblock> <description compact="foo bar"/> [...] A: Two of the three file tokens in file:file/file:description are namespace names. In XML and XSLT, a:b means "b in the a namespace". You can see the xmlns line explaining that file is a namespace once you know to look for it. So the string means to find file:description (which may just look like description if everything in your document is in the file namespace) under file:file. Make sense?
doc_23537044
how can i convert Input.GetTouch(0).deltaPosition.x to Input.GetMouseButtonDown(0) then drag left and right? A: There is no direct conversion between the two. I would create method, what returns the value, and implement the logic per platform. Something like this: #if UNITY_STANDALONE private Vector2 _prevPos; #endif private void Update() { if (IsPointer()) { Vector2 delta = GetDeltaPos(); // do the work } } private bool IsPointer() { #if UNITY_ANDROID return Input.touchCount > 0; #elif UNITY_STANDALONE return Input.GetMouseButton(0); #endif } private Vector2 GetDeltaPos() { #if UNITY_ANDROID return Input.GetTouch(0).deltaPosition; #elif UNITY_STANDALONE Vector2 ret = Input.mousePosition - _prevPos; _prevPos = Input.mousePosition; return ret; #endif } I know it's not nice, but works on both platforms.
doc_23537045
Image I want it to be working on each of the browser without any pixelate issue Requesting your best suggestion........... Thanks A: Just try this: { -webkit-text-stroke: 0.6px; } A: You cannot possibly control how a browser like Chrome renders fonts. You just have control over choosing the best font at best font-size.(Some fonts looks good only at certain font sizes - the font you are using looks good from 50px onward it seems. EDIT:Ah that is a different issue) If you / your client is so specific you can even get help from some custom rendering like * *Typeface.js *Cufon which uses canvas/flash to render fonts. Using it extensively can cause performance issues or slowness. There used to a font-smoothening, but I guess no longer supported, you can try it though -webkit-font-smoothing property has no effect in Chrome A: you can smooth fonts by using body { -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } read more: https://developer.mozilla.org/en-US/docs/Web/CSS/font-smooth
doc_23537046
Any help will be appreciated. I tried searching and found out like GitHub is not very good with very files but didn't find anything which can explain this behaviour. A: This probably has nothing to do with text files vs. binary files. GitHub Pages sites are build using background jobs. Depending on how busy the Pages servers are, how many jobs are ahead of yours, etc. you may see a build happen very quickly, or you may have to wait a while.
doc_23537047
This is what I am trying to do This is what I am able to do And this is the piece of code I am using: <nb-alert outline="basic" style="display: flex; justify-content: flex-start;"> <div> <div style="float: left;"> <nb-icon icon="alert-triangle" status="danger"></nb-icon> </div> <div style="align-self: center; padding:20px; white-space: pre-wrap;" > Error: Error details<br> Explanation: Explanation of Error<br> Status: Status of error<br> </div> </div> </nb-alert> Can you help me with this... Thanks in advance. A: You can use the below CSS code and set the height of the icon that you want. .nb-theme-default nb-alert { display: flex; align-items: center; flex-direction: row; }
doc_23537048
The results must look like this: https://imgur.com/vsOZjNi So far I have this, but I can't figure out how to fill the tables, its all empty: select mm as "Month", [1] as '2011', [2] as '2012', [3] as '2013', [4] as '2014' from( select year(h.orderdate) as yy, month(h.orderdate) as mm, d.OrderQty from sales.SalesOrderHeader h join sales.SalesOrderDetail d on h.SalesOrderID = d.SalesOrderID) o pivot(count(OrderQty) for yy in ([1],[2],[3],[4])) piv order by mm I need to match the result image I posted at the top of this post. Thank you in advance! A: Just use conditional aggregation. It is not clear if you want the number of orders or the sum of quantities, but the idea is: select month(h.orderdate) as mont, sum(case when year(h.orderdate) = 2011 then 1 else 0 end) as [2011], sum(case when year(h.orderdate) = 2012 then 1 else 0 end) as [2012], sum(case when year(h.orderdate) = 2013 then 1 else 0 end) as [2013], sum(case when year(h.orderdate) = 2014 then 1 else 0 end) as [2014] from sales.SalesOrderHeader h join sales.SalesOrderDetail d on h.SalesOrderID = d.SalesOrderID group by month(h.orderdate) order by month(h.orderdate); A: You can also use this if you want to go with the pivot route select mm as "Month", [2011], [2012], [2013], [2014] from( select month(h.orderdate) as mm,year(h.orderdate) as yy, d.OrderQty from sales.SalesOrderHeader h join sales.SalesOrderDetail d on h.SalesOrderID = d.SalesOrderID ) o pivot(count(OrderQty) for yy in ([2011], [2012], [2013], [2014])) piv order by mm If you don't want to hard code years in the query, you can also go with dynamic sql route with cte as ( select distinct year(h.orderdate) as yy from sales.SalesOrderHeader h join sales.SalesOrderDetail d on h.SalesOrderID = d.SalesOrderID ) select @years = SUBSTRING ((select ',[' + cast (yy as varchar(4)) +']' from cte order by yy for xml path ('')),2,1000) set @cmd = 'select mm as "Month", '+@years+' from( select month(h.orderdate) as mm,year(h.orderdate) as yy, d.OrderQty from sales.SalesOrderHeader h join sales.SalesOrderDetail d on h.SalesOrderID = d.SalesOrderID ) o pivot(count(OrderQty) for yy in ('+@years+')) piv order by mm ' exec sp_executesql @cmd
doc_23537049
We are able to use comm with success, but I am not getting the correct results when used with a conditional in script. #!/bin/bash # http://stackoverflow.com/a/14500821/175063 comm -23 <(sort /home/folder/old.txt) <(sort /home/folder/new.txt) if [ $? -eq 0 ];then echo "There are no changes in the files" else echo "New files were found. Return code was $?" fi It always returns: There are no changes in the files as the comm command, runs successfully but the contents of the files are different. I am very limited as to what can be added to this server as it is a corporate LINUX box. A: You should be able to use: ! comm -3 <(sort /home/folder/old.txt) <(sort /home/folder/new.txt) | grep -q '.*' The comm command will succeed (exit with status 0) whether it finds any differences or not, but grep only succeeds if it finds a match. -q prevents grep from printing the match(es), and the pattern '.*' matches anything. Thus, grep -q '.?' succeeds if its input is nonempty. But you wanted success if there was a match, so I added the ! at the beginning to invert the status. I also made one other change: comm -23 will print lines that're in the first file (old.txt) and not in the second one (new.txt), but it will not print lines that're in the second but not the first. comm -3 will print all lines that're unique to one of the files, so it'll find lines that've been removed or added between the two files. BTW, testing whether $? is zero is unnecessary; just use the command directly as the if condition: if ! comm -3 <(sort /home/folder/old.txt) <(sort /home/folder/new.txt) | grep -q '.*'; then echo "There are no changes in the files" else echo "New files were found. Return code was $?" fi A: Pipe the output of comm to wc -l to see if there were any new files found. new_file_count=$(comm -13 <(sort /home/folder/old.txt) <(sort /home/folder/new.txt) | wc -l) if [ $new_file_count -eq 0];then echo "There are no changes in the files" else echo "New files were found. Count is $new_file_count" fi I changed the comm command to use -13 so it will print the new files, since that's what your message suggests you want.
doc_23537050
Unfortunately for me, that's not what I'm after. For instance, 1 June 2012 -> 30 June 2012 crosses 4 boundaries, but covers 5 weeks. Is there an alternative query that I can run which will give me the number of weeks that a month intersects? UPDATE To try and clarify exactly what I'm after: For any given month I need the number of weeks that intersect with that month. Also, for the suggestion of just taking the datediff and adding one, that won't work. For instance February 2010 only intersects with 4 weeks. And the DateDiff calls returns 4, meaning that simply adding 1 would leave me the wrong number of weeks. A: Beware: Proper Week calculation is generally trickier than you think! If you use Datepart(week, aDate) you make a lot of assumptions about the concept 'week'. Does the week start on Sunday or Monday? How do you deal with the transition between week 1 and week 5x. The actual number of weeks in a year is different depending on which week calculation rule you use (first4dayweek, weekOfJan1 etc.) if you simply want to deal with differences you could use DATEDIFF('s', firstDateTime, secondDateTime) > (7 * 86400 * numberOfWeeks) if the first dateTime is at 2011-01-01 15:43:22 then the difference is 5 weeks after 2011-02-05 15:43:22 EDIT: Actually, according to this post: Wrong week number using DATEPART in SQL Server You can now use Datepart(isoww, aDate) to get ISO 8601 week number. I knew that week was broken but not that there was now a fix. Cool! THIS WORKS if you are using monday as the first day of the week set language = british select datepart(ww, @endofMonthDate) - datepart(ww, @startofMonthDate) + 1 * *Datepart is language sensistive. By setting language to british you make monday the first day of the week. *This returns the correct values for feburary 2010 and june 2012! (because of monday as opposed to sunday is the first day of the week). *It also seems to return correct number of weeks for january and december (regardless of year). The isoww parameter uses monday as the first day of the week, but it causes january to sometimes start in week 52/53 and december to sometimes end in week 1 (which would make your select statement more complex) A: SET DATEFIRST is important when counting weeks. To check what you have you can use select @@datefirst. @@datefirst=7 means that first day of week is sunday. set datefirst 7 declare @FromDate datetime = '20100201' declare @ToDate datetime = '20100228' select datepart(week, @ToDate) - datepart(week, @FromDate) + 1 Result is 5 because Sunday 28/2 - 2010 is the first day of the fifth week. If you want to base your week calculations on first day of week is Monday you need to do this instead. set datefirst 1 declare @FromDate datetime = '20100201' declare @ToDate datetime = '20100228' select datepart(week, @ToDate) - datepart(week, @FromDate) + 1 Result is 4.
doc_23537051
Using an existing CMS is not an option (don't know why), I never had to implement such a thing and I'm not able to find any tutorials, articles about this topic. Can you provide some basic logic, or good tutorial on how to build such a basic functionality, it seems like a general question but still the idea is to work for ASP.NET MVC 4. A: Don't forget, i just found out about these CMS projects (both opensource) * *BetterCMS *Ecms A: If I were you I would take a look at some open source examples out there for comparison and decide which features you want to implement and how they accomplish them. There are a few examples I found when searching: Orchard - An open source ASP.NET MVC based CMS that is highly rated. OSNet - Open Source ASP.NET CMS found on SourceForge. In addition this article has some good resources that you might find useful (scroll to the bottom for implementation specific details). Just do a little research on it before giving up, most of this stuff isn't hard to find and it's almost certainly been done before. A: I have created a basic one for my clients, i set up a seperate area (backend). With a basic authentication system using a flat file database (so no dependency on MS SQL or something). I used Biggy for this I used bootstrap as layout. Added a drop-zone file uploader (for images) Added a slider which pics the images, people could order this GUI is markdown or a basic HTML wysiwyg editor Packed it into a nuget package and saved it on a Nuget RSS feeds so i could easily load it into an existing package.
doc_23537052
As I click on the radio button1 = Group Box 2 currently the following happens: * *The text in button 1 changes to group box 1 *The group box 2 is displayed on the dialog *Group Box 1 is hidden I know how to hide the group boxes what I am not sure is the toggling part A: You can use the following approach: Create a function that will show/hide the relevant group box and update the text on the button. * *You can use this function to show/hide the controls and the group. The parameter received are the IDs of the radios and the group box. void CMFCApplication2Dlg::ShowHideControls(BOOL hide, int groupID, int radio1ID, int radio2ID) { GetDlgItem(groupID)->ShowWindow(hide ? SW_HIDE : SW_NORMAL); GetDlgItem(radio1ID)->ShowWindow(hide ? SW_HIDE : SW_NORMAL); GetDlgItem(radio2ID)->ShowWindow(hide ? SW_HIDE : SW_NORMAL); } *Create a function that control the toggling: void CMFCApplication2Dlg::ToggleGroup(BOOL group1Visible) { ShowHideControls(group1Visible, IDC_MY_GROUP, IDC_RADIO1, IDC_RADIO2); ShowHideControls(!group1Visible, IDC_MY_GROUP2, IDC_RADIO3, IDC_RADIO4); CString txt; txt.Format(L"Group Box %d", group1Visible ? 1 : 2); GetDlgItem(IDC_BUTTON_TOGGLE)->SetWindowText(txt); } *Call the ToggleGroup from: a) OnInitDialog with FALSE parameter. b) In button click event handler.
doc_23537053
and at some point i got very Weird Error. I've a Class Background In Package objects: package objects { import core.Assets; import starling.display.Image; import starling.display.Sprite; public class Background extends Sprite { private var sky1:Image; private var sky2:Image; public function Background() { sky1 = new Image(Assets.skyTexture); addChild(sky1); sky2 = new Image(Assets.skyTexture); sky2.y = -800; addChild(sky2); } public function update():void { sky1.y += 4; if(sky1.y == 800) { sky1.y = -800; } sky2.y +=4; if(sky2.y == 800) { sky2.y = -800; } } } } and Menu class in Package states: package states { import flash.display.Sprite; import core.Game; import interfaces.IState; import objects.Background; import starling.events.Event; public class Menu extends Sprite implements IState { private var game:Game; private var background:Background; public function Menu(game:Game) { this.game = game; addEventListener(Event.ADDED_TO_STAGE, init); } private function init(event:Event):void { background = new Background(); addChild(background); } public function update():void { } public function destroy():void { } } } on the line addChild(background); I get this weird Error and I'm sure there's no any Errors in any other Class Implicit coercion of a value of type Background to an unrelated type DisplayObject. Menu.as /Spacer/src/states line 31 Flex Problem When i debug without this Line i get no Errors. A: Your Menu class extends flash.display.Sprite but Background class extends starling.display.Sprite. The Menu class should be extended from the starling Sprite.
doc_23537054
The first step is trying to get the tag for the username and password input boxes. I've used inspect elements to determine the tags and I think they are "username" and "password". However, this does not work. Unfortunately, I've no experience of CSS. Here is my code. Sub MyLogin() Set ie = CreateObject("InternetExplorer.Application") With ie .Visible = True .Navigate "http://www.o2online.ie/o2/login/" Do Until .ReadyState = 4 DoEvents Loop .document.all.Item("username").Value = "MyUsername" .document.all.Item("password").Value = "MyPassword" .document.forms(1).submit End With End Sub Any help appreciated. Regards, Rueful A: As the login form is inside iframe it may not allow to access the control directly. Try below code Sub MyLogin() Set ie = CreateObject("InternetExplorer.Application") With ie .Visible = True .Navigate "https://www.o2online.ie/idm/login/lightBoxLogin.jsp?authn_try_count=0&contextType=external&username" Do Until .ReadyState = 4 DoEvents Loop .document.all.Item("username").Value = "MyUsername" .document.all.Item("password").Value = "MyPassword" .document.forms(0).submit .Navigate "http://www.o2online.ie/o2/login/" End With End Sub
doc_23537055
Sorry if this a FAQ, I did search thoroughly. A: Babel converts ES6 syntax into ES5 syntax. It is up to you to load a polyfill so that new ES6 library functions are available. Generally you'd do this with import 'babel/polyfill';
doc_23537056
Everything works fine for around 60 pulls and then suddenly I get the error: Use of uninitialized value $_ in substitution (s///) while ( my $row = $ia_applicant_query->fetchrow_arrayref ) { s/\t/ /g for @$row; # <------- THIS IS WHAT THE ERROR POINTS TO my $line = join "\t", map { defined $_ ? $_ : '.' } @$row; $mydb->func( "$line\n", "putline" ); } The error is then just repeated for the remaining 800 pulls. Any Idea what could be going wrong? A: That means one of the values in @$row is undef, which happens if the column is NULL. This can be avoided by replacing s/\t/ /g for @$row; my $line = join "\t", map { defined($_) ? $_ : '.' } @$row; with my $line = join "\t", map { defined($_) ? s/\t/ /gr : '.' } @$row; # 5.14+ or sub tabs_to_spaces { ( my $s = shift ) =~ s/\t/ /g; $s } my $line = join "\t", map { defined($_) ? tabs_to_spaces($_) : '.' } @$row;
doc_23537057
Context: java 6, Spring 3.1.4, camel 2.11.1, Oracle driver 10.2.0.2. I have this bean in camel context file: <bean id="myDataSource" class="**org.springframework.jdbc.datasource.DriverManagerDataSource**"> <property name="driverClassName" value="**oracle.jdbc.driver.OracleDriver"**/> <property name="url" value="jdbc:...."/> <property name="username" value="userhere"/> <property name="password" value="passwordhere"/> </bean> I've also tried with this class for the bean: class="org.apache.commons.dbcp.BasicDataSource" And a bean somewhere else using this bean. I have this in POM (By the way, I brought this dependency from another project that points to the same database, so it's the correct version): <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc14</artifactId> <version>10.2.0.2</version> <scope>provided</scope> </dependency> I also have this, because of different thing I've tried to make it work: <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-jdbc</artifactId> <version>2.11.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.1.4.RELEASE</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> * *The connection data (url, user and password), it's verified, and it's correct for each one of the environments' db I tried to connect. *I can see the ojdbc14 jar in Maven dependencies, I also see it when doing "maven run" with debug output enabled: [DEBUG] Adding project dependency artifact: ojdbc14 to classpath *I can see the class oracle.jdbc.driver.OracleDriver inside the jar. Yet, I'm getting these errors everytime: * *When using class="org.apache.commons.dbcp.BasicDataSource" as dataSource class: class="org.apache.commons.dbcp.BasicDataSource" [29 Nov 2013 13:39:03,257][e) thread #0 - timer://kickoff] DefaultErrorHandler ERROR Failed delivery for (MessageId: ID-vpar-alcantara-51044-1385743141288-0-1 on ExchangeId: ID-vpar-alcantara-51044-1385743141288-0-2). Exhausted after delivery attempt: 1 caught: org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'oracle.jdbc.driver.OracleDriver' org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'oracle.jdbc.driver.OracleDriver' at org.apache.commons.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1429) at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371) at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044) at org.apache.camel.component.jdbc.JdbcProducer.processingSqlBySettingAutoCommit(JdbcProducer.java:76) at org.apache.camel.component.jdbc.JdbcProducer.process(JdbcProducer.java:63) at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61) at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73) at org.apache.camel.processor.SendProcessor$2.doInAsyncProducer(SendProcessor.java:122) at org.apache.camel.impl.ProducerCache.doInAsyncProducer(ProducerCache.java:298) at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:117) at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73) at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:99) at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90) at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:72) at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73) at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:99) at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90) at org.apache.camel.processor.interceptor.BacklogTracerInterceptor.process(BacklogTracerInterceptor.java:84) at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73) at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:99) at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90) at org.apache.camel.processor.interceptor.TraceInterceptor.process(TraceInterceptor.java:91) at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73) at org.apache.camel.processor.RedeliveryErrorHandler.processErrorHandler(RedeliveryErrorHandler.java:391) at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:273) at org.apache.camel.processor.RouteContextProcessor.processNext(RouteContextProcessor.java:46) at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90) at org.apache.camel.processor.interceptor.DefaultChannel.process(DefaultChannel.java:335) at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73) at org.apache.camel.processor.Pipeline.process(Pipeline.java:117) at org.apache.camel.processor.Pipeline.process(Pipeline.java:80) at org.apache.camel.processor.RouteContextProcessor.processNext(RouteContextProcessor.java:46) at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90) at org.apache.camel.processor.UnitOfWorkProcessor.processAsync(UnitOfWorkProcessor.java:150) at org.apache.camel.processor.UnitOfWorkProcessor.process(UnitOfWorkProcessor.java:117) at org.apache.camel.processor.RouteInflightRepositoryProcessor.processNext(RouteInflightRepositoryProcessor.java:48) at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90) at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73) at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:99) at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90) at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:72) at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:99) at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:86) at org.apache.camel.component.timer.TimerConsumer.sendTimerExchange(TimerConsumer.java:135) at org.apache.camel.component.timer.TimerConsumer$1.run(TimerConsumer.java:63) at java.util.TimerThread.mainLoop(Timer.java:555) at java.util.TimerThread.run(Timer.java:505) Caused by: java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) at org.apache.commons.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1420) ... 46 more [29 Nov 2013 13:39:03,265][e) thread #0 - timer://kickoff] TimerConsumer WARN Error processing exchange. Exchange[Message: select vendor_style from supplier_ingest_style where bluefly_product_color is not null]. Caused by: [org.apache.commons.dbcp.SQLNestedException - Cannot load JDBC driver class 'oracle.jdbc.driver.OracleDriver'] org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'oracle.jdbc.driver.OracleDriver' at org.apache.commons.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1429) at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371) at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044) at org.apache.camel.component.jdbc.JdbcProducer.processingSqlBySettingAutoCommit(JdbcProducer.java:76) at org.apache.camel.component.jdbc.JdbcProducer.process(JdbcProducer.java:63) at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61) at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73) at org.apache.camel.processor.SendProcessor$2.doInAsyncProducer(SendProcessor.java:122) at org.apache.camel.impl.ProducerCache.doInAsyncProducer(ProducerCache.java:298) at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:117) at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73) at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:99) at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90) at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:72) at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73) at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:99) at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90) at org.apache.camel.processor.interceptor.BacklogTracerInterceptor.process(BacklogTracerInterceptor.java:84) at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73) at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:99) at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90) at org.apache.camel.processor.interceptor.TraceInterceptor.process(TraceInterceptor.java:91) at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73) at org.apache.camel.processor.RedeliveryErrorHandler.processErrorHandler(RedeliveryErrorHandler.java:391) at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:273) at org.apache.camel.processor.RouteContextProcessor.processNext(RouteContextProcessor.java:46) at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90) at org.apache.camel.processor.interceptor.DefaultChannel.process(DefaultChannel.java:335) at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73) at org.apache.camel.processor.Pipeline.process(Pipeline.java:117) at org.apache.camel.processor.Pipeline.process(Pipeline.java:80) at org.apache.camel.processor.RouteContextProcessor.processNext(RouteContextProcessor.java:46) at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90) at org.apache.camel.processor.UnitOfWorkProcessor.processAsync(UnitOfWorkProcessor.java:150) at org.apache.camel.processor.UnitOfWorkProcessor.process(UnitOfWorkProcessor.java:117) at org.apache.camel.processor.RouteInflightRepositoryProcessor.processNext(RouteInflightRepositoryProcessor.java:48) at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90) at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73) at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:99) at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90) at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:72) at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:99) at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:86) at org.apache.camel.component.timer.TimerConsumer.sendTimerExchange(TimerConsumer.java:135) at org.apache.camel.component.timer.TimerConsumer$1.run(TimerConsumer.java:63) at java.util.TimerThread.mainLoop(Timer.java:555) at java.util.TimerThread.run(Timer.java:505) Caused by: java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) at org.apache.commons.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1420) *When using class="org.springframework.jdbc.datasource.DriverManagerDataSource" java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.apache.camel.maven.RunMojo$1.run(RunMojo.java:459) at java.lang.Thread.run(Thread.java:744) Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myDataSource' defined in file [C:\GITWorkspace\vendorIngestion\target\classes\META-INF\spring\camel-context.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are: PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [oracle.jdbc.driver.OracleDriver] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1396) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1118) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:472) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139) at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:93) at org.apache.camel.spring.Main.createDefaultApplicationContext(Main.java:186) at org.apache.camel.spring.Main.doStart(Main.java:140) at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:61) at org.apache.camel.main.MainSupport.run(MainSupport.java:148) at org.apache.camel.main.MainSupport.run(MainSupport.java:343) at org.apache.camel.spring.Main.main(Main.java:73) ... 6 more Caused by: org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are: PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [oracle.jdbc.driver.OracleDriver] at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:102) at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1393) In both messages it can't load OracleDriver apparently, although I can't see why exactly. The first one says ClassNotfoundException, and the second one java.lang.IllegalStateException. Right now I'm running with maven pluggin in Eclipse, I also tried, just in case but knowing that's not a solution when running with Maven, to add the ojdbc jar to the eclipse classpath. But nothing worked. The oracle driver version is correct for our Orcale, the url is correct, so the user and password, I've tried to point to each one of the environments db I have access (local, dev, qa, staging). Nothing worked. Anyone has any idea why it can't find or load OracleDriver when in fact it's adding the jar to the classpath? A: Are you running this app on an application server? If the server doesn't have the JDBC driver on it's classpath try setting the scope to default (compile) for the Oracle driver dependency, since it's the default you can just omit the scope tag: <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc14</artifactId> <version>10.2.0.2</version> </dependency> The difference between both scopes: * *compile This is the default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects. *provided This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive. A: I am using a different version of the oracle driver (11.X.X.X) but can you try this and see if it works for: <bean id="dataSource" class="oracle.jdbc.pool.OracleDataSource" destroy-method="close" lazy-init="true"> <property name="dataSourceName" value="ds" /> <property name="DriverType" value="{your_driver_type}" /> <property name="user" value="{user}" /> <property name="password" value="{password}" /> </bean> I am using this configuration with the SQL Component and it works, so I guess it should work the same for Camel JDBC. A: Yes thanks for the solution. In my case writing "compile" and then doing **Maven update project worked** Problem: PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'driverClassName' threw exception; nested exception is java.lang.IllegalStateException: Could not load JDBC driver class [org.h2.Driver] Solution: I wrote scope for H2 dependency as follows nd then right click Project-->Maven--> update Project <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.4.195</version> <scope>compile</scope> </dependency>
doc_23537058
.delete-ad-reason-box { display: inline-block; width: 100%; border: 2px solid red; border-radius: 0.25rem; color: red; font-size: 1em; margin: 30px 0; padding: 20px 15px; line-height: 20px; } .delete-ad-reason-box i { font-size: 1.5em; margin-bottom: 10px; color: red; } /* Here's the ":active" */ .delete-ad-reason-box:hover, .delete-ad-reason-box:active { border: 2px solid red; background: red; color: white; } .delete-ad-reason-box:hover>i, .delete-ad-reason-box:active>i { color: white; } <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <a href="#" class="col-lg-4 col-md-4 col-sm-10 col-xs-10 col-10"> <div class="mx-auto delete-ad-reason-box" id="#"> <i class="fas fa-frown d-block"></i> Click Me </div> </a> A: You can't use : active for a div element. You can able to achieve it via javascript only A: I suggest you use only 1 anchor tag element for this one. :active :focus pseudo element only works on a tag. So simplify your html structure to this one. .click-me {display:block;color:red;border:1px solid red;width:100%;padding:20px 10px;text-decoration:none;font-weight:bold;} .click-me:hover,.click-me:active,.click-me:focus {border:1px solid transparent;color:#fff;background:red;} <a href="#" class="click-me">Click Me</a> This is a more simplified one and you don't need to add a div element inside the a tag.
doc_23537059
=if(SUM(TOTAL)>= 400000, num((((SUM(TOTAL)-400000)*0.0118)+12000),'€ #.##0'), How do I do this? Thank you. A: The formula is incomplete. It doesn't state what you want to return if the condition is not met. The DAX syntax would be =If(SUM(TableName[Total])>=40000,((SUM(TableName[Total])-40000)*0.0118)+12000,null) The "null" is returned when the sum of the total is less than 40000. Adjust as required. You can use formatting to apply the desired currency format. In DAX, the format is not applied inside the formula. Also, you may want to use an initial measure to calculate the total, then re-use that measure in other calculations. It is more efficient. Create a measure for the total, for e.g. Total Turnover = SUM(TableName[Total]) Then use that in the formula for the calculation measure WhateverName = If([Total Turnover]>=40000,(([Total Turnover]-40000)*0.0118)+12000,null)
doc_23537060
For example, I would like to hide the 'Name' field when 'Selector' is True and hide the 'Nickname' field when 'Selector' is False, for the following model in SQLAlchemy. class Foobar(Base): __tablename__ = 'foobar' Selector = Column(Boolean) Name = Column(String(100)) Nickname = Column(String(100))
doc_23537061
if (!isset($_GET[""])) $_GET[""] = false; The compiler does not report an error. OK, we have this construction without variable name. Is here one way to use this construction in practice? I think it's nonsense. I think that only $_GET is usable in practice, like: if (count($_GET) > 0) do something A: If you're talking about the usability of $_GET[""] - you can't set it using URL. If you go to the URL test.php?=3 you will get an empty $_GET If you go to the URL test.php?""=3 you will be able to access it using $_GET["\"\""] So there is no way to set a variable in the URL and retrieve it with $_GET[""]; You can set the key to an empty string from the code however: $_GET[""] = 3; echo $_GET['']; // 3 echo $_GET[""]; // 3 A: empty($_GET) and count($_GET) are working here for me! A: I can't understand what you want to achieve by this code: if (!isset($_GET[""])) $_GET[""] = false; It's possible for php to assign empty string as array key and it will be accessible like: $array[0][''] For your checking you can use such function for example: function GET($key, $default = null) { return isset($_GET[$key]) ? $_GET[$key] : $default; } A: if you test the following code with a url like 'http://domain.com': print_r($_GET); echo '<br>'; if(isset($_GET)) { echo '$_GET IS SET<br>'; } if(!empty($_GET)) { echo '$_GET IS NOT EMPTY<br>'; } if(count($_GET) > 0) { echo '$_GET IS NOT EMPTY<br>'; } you 'll get Array ( ) $_GET IS SET According to that then is up to you what you want to check or do keep in mind that $_GET is always set even if you do http://www.domain.com or this http://www.domain.com/index.php?test=adsf What you did with $_GET[''] = 'smthing' is like having an array arr['test'] = 'smthing'; altho you didn't gave a key of test instead an empty one, which you can't handle properly when it comes to $_GET. so you should check for smthing specific if you ask me. if(isset($_GET['test']) && $_GET['test'] == 'adsf') { doSomething(); } This is just a simple example further validation should occur.
doc_23537062
Those publishing options are locked when the HostInBrowser property in the project file is set to True, which is necessary for the application i'm developing, however i need to make the installation of dependencies user friendly, and possibly from the .net framework installer already hosted in my server, as it would cut down greatly the use of bandwidth. The program is intended to be used in intranet, as a "web page", by placing shortcuts on the desktop of each computer (which is done at the first run of the app), but most of the users don't have .NET Framework 4 installed. is there any way to accomplish this without converting it to an installable wpf application? Thanks in advance, JesΓΊs. A: No ClickOnce requires the .Net framework, because it's a component of it. All ClickOnce applications require that the correct version of the .NET Framework is installed on a computer before they can be run You can however set a prerequisite which is a higher version of the framework, provided they have at least version 2.0 to begin with. Commonly a bootstrapper written in managed code is used to overcome this limitation. You could use MSBuild for this, dotNetInstaller, or other third party tools. I've used dotNetInstaller a few times a recommend it, it's very flexible.
doc_23537063
twitter://user?screen_name=SCREEN_NAME I recently noticed that this opens the Twitter app as expected but it shows a screen as if I used it for the first time: The app is also completely frozen, I can't touch anything. If I keep the app open and klick on the UIButton in our app again, the profile will be shown correctly but still without being able to touch anything. The only way I can get this to work is if I start the Twitter app before and let it open (in background). If I select the UIButton in our app now, everything works fine, the profile is shown and I'm able to interact with the Twitter app. I think that there might be a problem of the Twitter app to handle such URL schemes on app start, but works when the app is already running. Does anyone else experience this problem or have a solution for this issue? A: Weirdly deleting and reinstalling the Twitter app fixed this problem. Still don't know why it happened though...
doc_23537064
I am using beanstalkd for my queuing. A: I am using Redis instead of Beanstalkd but this should be the same in both. Restarting Redis doesn't solve the problem. I looked at RedisQueues in the Laravel 4.2 API Docs and found: public Job|null pop(string $queue = null) //Pop the next job off of the queue. This is the same if you look at BeanstalkedQueue. I threw it in app/routes.php inside dd*, loaded that page and voila. Route::get('/', function() { dd(Queue::pop()); #return View::make('hello'); }); NOTE: Reload the page once per queue. The queue was pulled off the stack. I would like to see a cleaner solution but this worked for me more than once. *dd($var) = Laravel's die and dump function = die(var_dump($var)) Edit 1: For Redis The above obviously isn't the best solution so here is a better way. Be careful! FLUSHDB - Delete all the keys of the currently selected DB. This command never fails. For Redis use FLUSHDB. This will flush the Redis database not Laravel's database. In the terminal: $ redis-cli 127.0.0.1:6379> FLUSHDB OK 127.0.0.1:6379> exit A: Restart Beanstalk. On Ubuntu: sudo service beanstalkd restart A: I made an artisan command which will clear all the jobs in your queue. You can optionally specify the connection and/or the pipe. https://github.com/morrislaptop/laravel-queue-clear A: Important note: This solution works only for beanstalk There are two solutions: 1- From Your PHP Code To delete jobs programatically, you can do this: //Que the job first. (YourJobProcessor is a class that has a method called fire like `fire($job,$data)` $res = Queue::later(5, YourJobProcessor::class, $data, 'queue_name'); //get the job from the que that you just pushed it to $job = Queue::getPheanstalk()->useTube("queue_name")->peek($res); //get the job from the que that you just pushed it to $res = Queue::getPheanstalk()->useTube("queue_name")->delete($job); If everything went good, the job will not execute, else the job will execute after 5 seconds 2- From Command Line (Linux and Mac only) From command line (In linux and mac) you can use beanstool. For example, if you want to delete 100 ready jobs from the queue_name tube you can do the following: for i in {1..100}; do beanstool delete -t queue_name --state=ready; done A: For Redis users, instead of flushing, using redis-cli I ran this command: KEYS *queue* on the Redis instance holding queued jobs, then deleted whatever keys in the response DEL queues:default queues:default:reserved A: Only way I could do it was to restart my computer. Could not find a way to delete a job. A: I've used this php-based web admin console in the past. Otherwise, I believe you'll find yourself using Terminal + telnet, altho I can't find any documentation for deleting via telnet (Just viewing a list of jobs in queue). It seems that most articles tell you to use your code+library of choice and loop around queues jobs to delete them in this situation. A: Here is Laravel 5.1 compatible command, which allows you to clear Beanstalkd queue. The command takes queue name as argument ('default' by default). Do not forget to register it in app/Console/Kernel.php
doc_23537065
x = df1['DNA_2'] y = df1['DNA_1'] X = np.column_stack((x, y)) # create a 2D array from the two lists mod2 = GaussianMixture(n_components=5, covariance_type='tied', random_state=2) # build the gmm mod2.fit(X) I then use this model to make predictions which I then plot: df1['pred2'] = labels fig, ax = plt.subplots(1,1) ax.scatter(x, y, c=df1['pred2'].apply(lambda x: colors[x]), s = 0.5, alpha=0.2) H,X,Y = density_estimation(x,y) ax.contour(H, X, Y, 8, linewidths=0.5, cmap='viridis') to get: I wanted to know how to plot the gaussian curves for the 5 populations. I know I can get the means using mod1.means_ and variances using mod1.covariances_ (both 2D) but how do I plot this to get the curves for each populations? looking to get something like: A: If it's a 2D GMM like the picture, the only way is to plot a 2D density plot such as: https://pythonmachinelearning.pro/clustering-with-gaussian-mixture-models/ The line graph attached is for a 1D GMM with three components. To plot this, you need to plot the probability density component for each cluster/group.
doc_23537066
The script for build project: cd FlashClipboard; /usr/lib64/qt5/bin/qmake FlashClipboard.pro; make clean; make; cppcheck --enable=all --suppress=missingIncludeSystem . --xml --xml-version=2 . 2> ./tmp/cppcheck.xml; Post-Build Actions: But I have error: [Cppcheck] Starting the cppcheck analysis. [Cppcheck] Processing 1 files with the pattern 'tmp/cppcheck.xml'. [Cppcheck] Parsing throws exceptions. javax.xml.bind.UnmarshalException - with linked exception: [org.xml.sax.SAXParseException; systemId: file:/var/lib/jenkins/workspace/Flash%20Clipboard/tmp/cppcheck.xml; lineNumber: 1; columnNumber: 1; Premature end of file.] Build step 'Publish Cppcheck results' changed build result to FAILURE Build step 'Publish Cppcheck results' marked build as failure What is my mistake? A: sorry but are you sure the path is correct? Shouldn't it be: Cppcheck report XML: FlashClipboard/tmp/cppcheck.xml
doc_23537067
Background I'm creating a comic database for personal use, to track my comic reads. Every comic belongs to a series. Every comics has a release date. The release date of a series is the first release of the according comic. I have a eloquent function seriesByDate() for that: class Series extends Model { public $timestamps = false; protected $primaryKey = 'series_id'; protected $fillable = ['series_name', 'publisher_id']; public function publisher() { return $this->belongsTo(Publisher::class, 'publisher_id'); } public function comics() { return $this->hasMany(Comic::class, 'series_id', 'series_id'); } // instead of saving the release date of a complete series // we look for the first comic in this series and get the // comic's release date. public static function seriesByDate() { $firstRelease = DB::table('comics') ->select('series_id', DB::raw('MIN(comic_release_date) as first_release')) ->groupBy('series_id'); $seriesByDate = DB::table('series') ->leftJoinSub($firstRelease, 'first_release', function ($join) { $join->on('series.series_id', '=', 'first_release.series_id'); }) ->join('publishers', 'publishers.publisher_id', '=', 'series.publisher_id') ->select('series.series_id', 'series.series_name', 'first_release', 'publishers.publisher_name') ->get(); return $seriesByDate; } What i want I want the release_date somehow be permanent to my Series model. Meaning: When I do a App\Series::all() i already want to have the release_date as a column in my returned data. Similar to App\Series::with('publishers')->get() With my solution above i have to eplicitly execute App\Series::seriesByDate() Is this even possible? Can you please give me a hint? Edit / Update The linked video by @Musa shows how to properly do this in a model: https://stackoverflow.com/a/61558482/5754486 A: * *You can't. There is no magic for this. You might eventually write your own custom Relation but that would be unnecessarily complex, just for the sake of having a pretty related/accessor. Both solutions are not great performance-wise. *Not sure why you choose such a structure. Without any further context/explanation, I would strongly recommend you to have a release_date column directly inside your Series model as well. That will be waaaay faster than your current structure. *If you still want to stick with that structure, I would personally retrieve the release_date "php side" instead of "database side" : $series = App\Series::query() ->with([ 'publishers', 'comics' => function ($query) { $query->orderBy('created_at'); }, ]) ->get(); foreach ($series as $serie) { $serieTitle = $serie->title; $releaseDate = $serie->comics->first()->created_at; echo $serieTitle.' was first released '.$releaseDate->diffForHumans().'<br/>'; } (not tested) the only downside is that it will return a Collection of every "comics" a "serie" has. If you do not have 10k comics per serie and you do not load 1k serie per page, that should be fine. In any case, this looks more elegant and optimized/faster than your seriesByDate method. edit: also, you should watch "Advanced Querying With Eloquent" by Jonathan Reinink, at Laracon 2018 I believe. He discusses subqueries like the one you need. I am 100% sure you will find the best and most optimal Eloquent subquery one can forge for what you are trying to achieve : https://vimeo.com/showcase/7060635/video/255049572 A: you can defined an accessor then append the value class Series extends Model { protected $appends = ['series_date']; public function getSeriesDateAttribute() { return self::seriesByDate(); //OR build 'seriesByDate' manually, returning whatever you like. } }
doc_23537068
w3.org says: Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements. I'm leaning towards keeping ids but some part of me thinks that future developers would think the ID's aren't used and remove them. Any best practices here. Thanks. A: This is close to being opinion-based, by here is the summary that should help to make a choice. Why would you use an ID attribute: * *this is a common and familiar to everybody doing test automation way to locate elements *this is generally the fastest way to locate elements on a page because selenium gets it down to executing document.getElementById() which is optimized by the modern browsers (though, usually performance of the end-to-end UI tests is not critical) *it is a built-in locator in every selenium language binding *if you would use Firebug or Chrome Developer Tools - the CSS selector and XPath generation tools would generally provide more robust locators using the ids of the element whenever possible *you would build shorter CSS selectors and XPath expressions. E.g. #myid .someclass as opposed to [automation-id=myid] .someclass. Why would you use a custom attribute: * *if you would add, say, automation-id attributes to all the desired elements, you would somewhat namespace/scope it to the test automation - everybody would know what is this for just from the attribute name. Meaning, you would dramatically decrease chances of a developer changing the attribute intentionally as opposed to an id attribute, which can and is usually used for application client-side logic as well (reference to this and this answer) Also, here are some relevant threads: * *Is adding IDs to everything standard practice when using Selenium? *Which is the best and fastest way to find the element using webdriver? By.XPath or By.ID or anything else? And why? *Something Better than IDs for Identifying Elements in Selenium Tests A: I would go with the data attribute instead, as you (or someone else) might need to use an ID for targeting the element for JS later. No one is ever going to need to target your custom data attribute for anything other than testing.
doc_23537069
Here is the relevant code to start the dot.exe process: private void MakePng() { string args = "-o" + graphPath + " -Tpng " + dotPath; Process process = new Process(); ProcessStartInfo info = new ProcessStartInfo(); info.FileName = VizGraphPath; info.Arguments = args; info.UseShellExecute = false; info.CreateNoWindow = true; process.StartInfo = info; process.EnableRaisingEvents = true; process.Exited += new EventHandler(Process_Exited); process.Start(); } private void Process_Exited(object sender, EventArgs e) { UpdateCanvas(); } The various string variables named xxxPath are just static strings to the correct file paths. When the program starts up and I run this code everything works perfectly. But if I reset my graph and try to run this set of code again it fails to create a new PNG. The old one is still there. To test something out I added this line: private void MakePng() { string args = "-o" + graphPath + " -Tpng " + dotPath; File.Delete(graphPath); Which works the first time through. But the second time it throws a Exception stating File is still in use. So I'm guessing somehow when the Process I start exits, the File Handle it created is still in use even though it exited? Any suggestions about how to figure out why its still in use or how to fix it? My UpdateCanvas function is also accessing the file that is locked: public void UpdateCanvas() { Bitmap image = new Bitmap(graphPath); pbCanvas.Image = image; } Do i need to something when loading a bitmap from a file to release the file? It was indeed the Bitmap locking the file. I had to dispose of it before the file would be unlocked. A: Process class implements IDisposable, so you need to despose resources. Also, you can add WatForExit method to be sure, your process finished: private void MakePng() { string args = "-o" + graphPath + " -Tpng " + dotPath; using(Process process = new Process()) { ProcessStartInfo info = new ProcessStartInfo(); info.FileName = VizGraphPath; info.Arguments = args; info.UseShellExecute = false; info.CreateNoWindow = true; process.StartInfo = info; process.EnableRaisingEvents = true; process.Start(); process.WaitForExit(10*1000); //10 seconds } UpdateCanvas(); } A: Your file is locked by new Bitmap. Rewrite it with: public void UpdateCanvas() { Image img; using (var bmpTemp = new Bitmap(graphPath)) { img = new Bitmap(bmpTemp); } pbCanvas.Image = img; }
doc_23537070
[DllImport("user32.dll")] static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags); I'm getting two errors for this code: * *The modifier 'extern' is not valid for this item (on the closing square bracket of the attribute) *Expected class, delegate, enum, interface, or struct (on bool) What am I doing wrong? A: Make sure you're placing this declaration within a class definition, not outside it. Typically, you'd keep P/Invokes within a static class called NativeMethods, which you then invoke using a call like NativeMethods.SetLayeredWindowedAttributes(...). For example: internal static class NativeMethods { [DllImport("user32.dll")] public static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags); } If you want to call it without a type reference, then you need to put it in the same class as you're calling it in, but unless you're sure you won't use this P/Invoke anywhere else, I wouldn't recommend it. A: Because you must encapsulate this code on class class MainClass { [DllImport("user32.dll")] static extern bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags); ..... }
doc_23537071
body { background-color: black; } .button { background-color: white; border: 2px solid transparent; border-radius: 2em; color: #eff6f9; display: inline-block; font-family: Merriweather, Arial, sans-serif; font-weight: 300; font-style: italic; font-size: 0.7rem; font-weight: bold; letter-spacing: 1px; line-height: 1; padding: 1em 2em; text-shadow: none; transition: background-color 0.125s ease-in; margin-top: 3em; } .button a { font-size: 2em; text-decoration-line: none; color: black; text-decoration: none } .button:hover, .button:focus, .button:active { background-color: transparent; border-color: white; color: white; } .shop:hover>span, .shop:focus>span, .shop:active>span { color: white; } a:focus, .button a:hover { text-decoration: none; } <body> <div class="button" id="bu"> <a class="shop" href="https://app.nmpl.store/"> <span>Order Now</span> <i class="fas fa-shopping-cart"></i> </a> </div> Currently When I hover over the button only the border changes first and then the text in between the button, I want to change the color and background of the entire button when I hover just on the border also. pointer outside button Pointer on edge of button Pointer on text A: Really good example on why it's important to use the correct elements for the right job. Don't use divs where you don't need them. Get rid of the div and use a simple link element that you style to look like your button. body { background-color: black; } .button { background-color: white; border: 2px solid transparent; border-radius: 2em; display: inline-block; font-family: Merriweather, Arial, sans-serif; font-weight: 300; font-style: italic; font-size: 0.7rem; font-weight: bold; letter-spacing: 1px; line-height: 1; padding: 1em 2em; text-shadow: none; transition: background-color 0.125s ease-in; margin-top: 3em; text-decoration-line: none; text-decoration: none; color: black; } .button:hover, .button:focus, .button:active { background-color: transparent; border-color: white; color: white; } a:focus { text-decoration: none; } <a class="button" href="https://app.nmpl.store/"> <span>Order Now</span> <i class="fas fa-shopping-cart"></i> </a> A: Try the bellow snippet In this, I have changed .shop:hover>span, .shop:focus>span, .shop:active>span { color: white; } To .shop:hover>a>span, .shop:focus>a>span, .shop:active>a>span { color: white; } .button { background-color: white; border: 2px solid transparent; border-radius: 2em; color: #eff6f9; display: inline-block; font-family: Merriweather, Arial, sans-serif; font-weight: 300; font-style: italic; font-size: 0.7rem; font-weight: bold; letter-spacing: 1px; line-height: 1; padding: 1em 2em; text-shadow: none; transition: background-color 0.125s ease-in; margin-top: 3em; } .wrapper{ height:200px; width:200px; padding:10px; background-color:yellow; } .button a { font-size: 2em; text-decoration-line: none; color: black; text-decoration: none } .button .fa-w-18 { color: black; margin-left: 5px; } .button:hover, .button:focus, .button:active { background-color: transparent; border-color: white; color: white; } .shop:hover>.fa-w-18, .shop:focus>.fa-w-18, .shop:active>.fa-w-18 { color: white; } .button:hover>a>span, .button:focus>a>span, .button:active>a>span { color: white; } a:focus, .button a:hover { text-decoration: none; } <div class="wrapper"> <div class="button" id="bu"> <a class="shop" href="https://app.nmpl.store/"> <span>Order Now</span> <i class="fas fa-shopping-cart"></i> </a> </div> </div> A: I've just changed a couple of things in your code: HTML <body> <div id="bu"> <a class="shop button" href="https://app.nmpl.store/"> Order Now <i class="fas fa-shopping-cart"></i> </a> </div> CSS body { background-color: black; } .button { background-color: white; border: 2px solid #FFF; border-radius: 35px; color: #000; display: inline-block; font-family: Merriweather, Arial, sans-serif; font-weight: 300; font-style: italic; font-size: 15px; font-weight: bold; letter-spacing: 1px; line-height: 1; text-decoration:none; padding: 20px 30px; text-shadow: none; transition: background-color 0.125s ease-in; margin-top: 3em; } .button:hover, .button:focus, .button:active { background-color: transparent; border-color: white; color: white; } Hope that helps you :)
doc_23537072
I've written a Tokio server using services and I want to reuse the same codec and proto for the client. Part of the client is a function called read_prompt which returns a Stream. Essentially it is an infinite loop at which each iteration reads in some input from stdin. Here's the relevant code: main.rs use futures::{Future, Stream}; use std::env; use std::net::SocketAddr; use tokio_core::reactor::Core; use tokio_prime::protocol::PrimeClientProto; use tokio_prime::request::PrimeRequest; use tokio_proto::TcpClient; use tokio_service::Service; mod cli; fn main() { let mut core = Core::new().unwrap(); let handle = core.handle(); let addr_string = env::args().nth(1).unwrap_or("127.0.0.1:8080".to_string()); let remote_addr = addr_string.parse::<SocketAddr>().unwrap(); println!("Connecting on {}", remote_addr); let tcp_client = TcpClient::new(PrimeClientProto).connect(&remote_addr, &handle); core.run(tcp_client.and_then(|client| { client .call(PrimeRequest { number: Ok(0) }) .and_then(|response| { println!("RESP = {:?}", response); Ok(()) }) })).unwrap(); } cli.rs use futures::{Future, Sink, Stream}; use futures::sync::mpsc; use std::{io, thread}; use std::io::{Stdin, Stdout}; use std::io::prelude::*; pub fn read_prompt() -> impl Stream<Item = u64, Error = ()> { let (tx, rx) = mpsc::channel(1); thread::spawn(move || loop { let thread_tx = tx.clone(); let input = prompt(io::stdout(), io::stdin()).unwrap(); let parsed_input = input .parse::<u64>() .map_err(|_| io::Error::new(io::ErrorKind::Other, "invalid u64")); thread_tx.send(parsed_input.unwrap()).wait().unwrap(); }); rx } fn prompt(stdout: Stdout, stdin: Stdin) -> io::Result<String> { let mut stdout_handle = stdout.lock(); stdout_handle.write(b"> ")?; stdout_handle.flush()?; let mut buf = String::new(); let mut stdin_handle = stdin.lock(); stdin_handle.read_line(&mut buf)?; Ok(buf.trim().to_string()) } With the code above, the client sends a single request to the server before the client terminates. I want to be able to use the stream generated from read_prompt to provide input to the TcpClient and make a request per item in the stream. How would I go about doing this? The full code can be found at joshleeb/tokio-prime. A: The solution I have come up with (so far) has been to use the LoopFn in the Future-Rs crate. It's not ideal as a new connection still has to be made but it is at least a step in the right direction. main.rs use futures::{future, Future}; use std::{env, io}; use std::net::SocketAddr; use tokio_core::reactor::{Core, Handle}; use tokio_prime::protocol::PrimeClientProto; use tokio_prime::request::PrimeRequest; use tokio_proto::TcpClient; use tokio_service::Service; mod cli; fn handler<'a>( handle: &'a Handle, addr: &'a SocketAddr ) -> impl Future<Item = (), Error = ()> + 'a { cli::prompt(io::stdin(), io::stdout()) .and_then(move |number| { TcpClient::new(PrimeClientProto) .connect(addr, handle) .and_then(move |client| Ok((client, number))) }) .and_then(|(client, number)| { client .call(PrimeRequest { number: Ok(number) }) .and_then(|response| { println!("{:?}", response); Ok(()) }) }) .or_else(|err| { println!("! {}", err); Ok(()) }) } fn main() { let mut core = Core::new().unwrap(); let handle = core.handle(); let addr_string = env::args().nth(1).unwrap_or("127.0.0.1:8080".to_string()); let remote_addr = addr_string.parse::<SocketAddr>().unwrap(); println!("Connecting on {}", remote_addr); let client = future::loop_fn((), |_| { handler(&handle, &remote_addr) .map(|_| -> future::Loop<(), ()> { future::Loop::Continue(()) }) }); core.run(client).ok(); } cli.rs use futures::prelude::*; use std::io; use std::io::{Stdin, Stdout}; use std::io::prelude::*; #[async] pub fn prompt(stdin: Stdin, stdout: Stdout) -> io::Result<u64> { let mut stdout_handle = stdout.lock(); stdout_handle.write(b"> ")?; stdout_handle.flush()?; let mut buf = String::new(); let mut stdin_handle = stdin.lock(); stdin_handle.read_line(&mut buf)?; parse_input(buf.trim().to_string()) } fn parse_input(s: String) -> io::Result<u64> { s.parse::<u64>() .map_err(|_| io::Error::new(io::ErrorKind::Other, "invalid u64")) }
doc_23537073
public class MainActivity extends Activity implements OnClickListener { Button b1, b2,b3; ImageView i, i2, i3; TextView t1, t2, t3,t4; String s1, s2, s3, s4, s5; LinearLayout pooku; Button bk; int q, m, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, n[]; Random r1 = new Random(); Random r0 = new Random(); Handler handler = new Handler(); Runnable r; Timer t = new Timer(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = (Button) findViewById(R.id.button1); b2 = (Button) findViewById(R.id.button2); b3 = (Button) findViewById(R.id.button3); pooku = (LinearLayout) findViewById(R.id.pooka); i = (ImageView) findViewById(R.id.imageView1); t1 = (TextView) findViewById(R.id.textView1); t2 = (TextView) findViewById(R.id.textView2); t3 = (TextView) findViewById(R.id.textView3); t4= (TextView) findViewById(R.id.textView4); b1.setOnClickListener(this); b2.setOnClickListener(this); b3.setOnClickListener(this); imp(); } public TimerTask malli(){ return new TimerTask() { public void run() { runOnUiThread(new Runnable() { public void run() { t4.setText("times up"); t4.setVisibility(View.VISIBLE); } }); } }; } public void imp() { t.schedule(malli(), 3000); r2 = r1.nextInt(9) + 1; r3 = r1.nextInt(9) + 1; r4 = r2 + r3; r5 = r2 - r3; r6 = r2 * r3; n = new int[] { r4, r5, r6 }; doit(); while (r9 == r11 || r9 == r13 || r11 == r13) { doit(); } s1 = Integer.toString(r2); s2 = Integer.toString(r3); s3 = Integer.toString(r9); s4 = Integer.toString(r11); s5 = Integer.toString(r13); t1.setText(s1); t2.setText(s2); b1.setText(s3); b2.setText(s4); b3.setText(s5); int[] images = { R.drawable.plus, R.drawable.minus, R.drawable.multiply }; Random random = new Random(); m = images[random.nextInt(images.length)]; i.setImageResource(m); bk.setFocusable(true); bk.requestFocus(); bk.requestFocusFromTouch(); } public void doit() { r9 = 0; r11 = 0; r13 = 0; r8 = r1.nextInt(3) + 0; r9 = n[r8]; r10 = r1.nextInt(3) + 0; r11 = n[r10]; r12 = r1.nextInt(3) + 0; r13 = n[r12]; int[] buttons = { R.id.button1, R.id.button2, R.id.button3 }; q = buttons[r0.nextInt(buttons.length)]; bk = (Button) findViewById(q); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button1: click(r9, b1); break; case R.id.button2: click(r11, b2); break; case R.id.button3: click(r13, b3); break; } } public void click(int k, Button b) { if (m == R.drawable.plus && k == r4 || m == R.drawable.minus && k == r5 || m == R.drawable.multiply && k == r6) { t3.setVisibility(View.INVISIBLE); t4.setVisibility(View.INVISIBLE); this.t.cancel(); imp(); t4.setVisibility(View.INVISIBLE); } else { t3.setText("FINISH"); t3.setVisibility(View.VISIBLE); b.setPressed(true); b1.setClickable(false); b2.setClickable(false); b3.setClickable(false); b.requestFocusFromTouch(); } } } and logcat report is 04-04 16:47:47.681: E/AndroidRuntime(11493): Process: com.example.emo2, PID: 11493 04-04 16:47:47.681: E/AndroidRuntime(11493): java.lang.IllegalStateException: Timer was canceled 04-04 16:47:47.681: E/AndroidRuntime(11493): at java.util.Timer.scheduleImpl(Timer.java:561) 04-04 16:47:47.681: E/AndroidRuntime(11493): at java.util.Timer.schedule(Timer.java:459) 04-04 16:47:47.681: E/AndroidRuntime(11493): at com.example.emo2.MainActivity.imp(MainActivity.java:74) 04-04 16:47:47.681: E/AndroidRuntime(11493): at com.example.emo2.MainActivity.click(MainActivity.java:154) 04-04 16:47:47.681: E/AndroidRuntime(11493): at com.example.emo2.MainActivity.onClick(MainActivity.java:135) 04-04 16:47:47.681: E/AndroidRuntime(11493): at android.view.View.performClick(View.java:4443) 04-04 16:47:47.681: E/AndroidRuntime(11493): at android.view.View$PerformClick.run(View.java:18442) 04-04 16:47:47.681: E/AndroidRuntime(11493): at android.os.Handler.handleCallback(Handler.java:733) 04-04 16:47:47.681: E/AndroidRuntime(11493): at android.os.Handler.dispatchMessage(Handler.java:95) 04-04 16:47:47.681: E/AndroidRuntime(11493): at android.os.Looper.loop(Looper.java:136) 04-04 16:47:47.681: E/AndroidRuntime(11493): at android.app.ActivityThread.main(ActivityThread.java:5021) 04-04 16:47:47.681: E/AndroidRuntime(11493): at java.lang.reflect.Method.invokeNative(Native Method) 04-04 16:47:47.681: E/AndroidRuntime(11493): at java.lang.reflect.Method.invoke(Method.java:515) 04-04 16:47:47.681: E/AndroidRuntime(11493): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:82 7) 04-04 16:47:47.681: E/AndroidRuntime(11493): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643) 04-04 16:47:47.681: E/AndroidRuntime(11493): at dalvik.system.NativeStart.main(Native Method) A: Put in your button's onClickListener(): if (t != null) t.cancel(); Code Example: final TextView t1 = (TextView) findViewById(R.id.yourpay); final Timer t =new Timer(); t.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { public void run() { money = (PPS+Reserve); Reserve = (money); t1.setText("$" + money); //Place your text data here // Removed the stopping condition/counter } }); } }, 1000, 1000); // Do you really want to wait 1 second before executing the timer's code? If not, change the 1st "1000" to a "0" final Button b = (Button) findViewById(R.id.my_button_id); // Replace with your button's id b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (t != null) t.cancel(); } }); A: Just call cancel on Timer object in the first link of your button onClick method. A: You can use flags for this. In onclick you can set a flag to false and then implement a check in your timer to execute only when the flag is true/set. Instead of this.t.cancel in your OnClick write flag = false and then in your timer task public TimerTask malli(){ return new TimerTask() { public void run() { runOnUiThread(new Runnable() { public void run() { if(flag){ t4.setText("times up"); t4.setVisibility(View.VISIBLE); } } }); } };
doc_23537074
{ path: "/items", name: "items", component: () => import("./myViews/itemsView.vue") }, if I click one of them I go to route: { path: "/items/:id", name: "singleItem", ***component: () => import("./myViews/singleItemView.vue")*** }, inside that view I have another list of other items and I need the route to look like this: { path: "/items/:id/:subId", name: "singleSubItem", ***component: () => import("./myViews/singleItemView.vue")*** }, and I need to use the same component singleItemView for both routes. when I am at "/items/:id "I am listening from a value emitted from a child component and then pushing the route like this: <myComponent @completed="$router.push({name: 'singleSubItme', params: {id: 'id', subId:'subId'})"></myComponent> The url does change but it keeps the same component with the same state and I want it to reload. A: One possible solution is add :key to your router-view to force it re-render <router-view :key="$route.fullPath"></router-view> You can also watch $route inside singleItemView.vue to have custom action (for example, call API) watch: { '$route'(to, from) { const {id, subId} = to.params if (subId) { // do something } else { // do something else } } },
doc_23537075
Is it possible to control the session creation policy in Spring (Security) on a per request basis? Long version... I have been using normal login form user authentication for our application. Some of the controllers are @RestControllers and up to now, the default user session tracked by cookie has allowed it to work fine. (I.e. when an XHR request comes from a page, the request is authenticated to the previously logged in user as the browser sends the JSESSIONID cookie as usual) I now want to allow some of the @RestController end points to be called from a rest client, rather than browser, so I have created an API token authentication scheme - this works fine. One of the last bits of cleanup is that the REST calls generate a session, which I'd like to avoid if possible. I can't set the session policy to NEVER (because i'm still relying on sessions for my web users). I have tried IF_REQUIRED to no avail. I have looked at the HttpSessionSecurityContextRepository but it wraps the request, and a session is created whenever the response is flushed. (See stacktrace below) Is it possible elsewhere to hook into the session management on a per-request basis? I can distinguish the type of request easily enough based on the class type of the Authentication object. at myapp.cfg.WebConfig$1.sessionCreated(WebConfig.java:74) at io.undertow.servlet.core.ApplicationListeners.sessionCreated(ApplicationListeners.java:300) at io.undertow.servlet.core.SessionListenerBridge.sessionCreated(SessionListenerBridge.java:56) at io.undertow.server.session.SessionListeners.sessionCreated(SessionListeners.java:52) at io.undertow.server.session.InMemorySessionManager.createSession(InMemorySessionManager.java:187) at io.undertow.servlet.spec.ServletContextImpl.getSession(ServletContextImpl.java:741) at io.undertow.servlet.spec.HttpServletRequestImpl.getSession(HttpServletRequestImpl.java:370) at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:270) at org.springframework.security.web.context.HttpSessionSecurityContextRepository$SaveToSessionResponseWrapper.createNewSessionIfAllowed(HttpSessionSecurityContextRepository.java:427) at org.springframework.security.web.context.HttpSessionSecurityContextRepository$SaveToSessionResponseWrapper.saveContext(HttpSessionSecurityContextRepository.java:364) at org.springframework.security.web.context.SaveContextOnUpdateOrErrorResponseWrapper.onResponseCommitted(SaveContextOnUpdateOrErrorResponseWrapper.java:85) at org.springframework.security.web.util.OnCommittedResponseWrapper.doOnResponseCommitted(OnCommittedResponseWrapper.java:245) at org.springframework.security.web.util.OnCommittedResponseWrapper.access$000(OnCommittedResponseWrapper.java:33) at org.springframework.security.web.util.OnCommittedResponseWrapper$SaveContextServletOutputStream.flush(OnCommittedResponseWrapper.java:512) at org.springframework.security.web.util.OnCommittedResponseWrapper$SaveContextServletOutputStream.flush(OnCommittedResponseWrapper.java:513) at com.fasterxml.jackson.core.json.UTF8JsonGenerator.flush(UTF8JsonGenerator.java:1050) at com.fasterxml.jackson.databind.ObjectWriter.writeValue(ObjectWriter.java:953) A: Split your security configuration into separate sections for a form login (session based API access) and a stateless API token authentication scheme. Example: @Configuration @EnableWebSecurity public class SecurityConfiguration { @Order(1) @Configuration class ApiSecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/api/**") .authorizeRequests().anyRequest().authenticated() .and() .httpBasic().realmName("API") // your API token authentication scheme .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER) .and() .exceptionHandling().authenticationEntryPoint(new Http401AuthenticationEntryPoint("Form realm=\"API\"")); // prevent basic authentication popup in browser } } @Order(2) @Configuration class DefaultSecurityConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .formLogin().loginPage("/login").permitAll() .and() .logout().logoutSuccessUrl("/login").permitAll(); } } } Replace .httpBasic().realmName("API") with you own authentication scheme. Call your API with e.g. curl -v ... and verify that there is no Set-Cookie header in the response. Otherwise your code somewhere creates an http session on its own. A: You should try create-session policy as "stateless" for your API end points. If "stateless" is used, this implies that the application guarantees that it will not create a session. This differs from the use of "never" which mans that Spring Security will not create a session, but will make use of one if the application does. A: I had the exact same problem and could not find a clean solution. In the absence of better options, I'll post a semi working hack. DISCLAIMER: I have not used this solution (I fell back to sessions, at least for now), try it at your own risk. Override the default SecurityContextRepository: @Component public class CustomSecurityContextRepository extends HttpSessionSecurityContextRepository { @Override public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) { SecurityContext securityContext = super.loadContext(requestResponseHolder); // disable automatic saving of security context on response committed // WARNING: not sure how safe this is SaveContextOnUpdateOrErrorResponseWrapper response = (SaveContextOnUpdateOrErrorResponseWrapper)requestResponseHolder.getResponse(); response.disableSaveOnResponseCommitted(); return securityContext; } @Override public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) { Authentication authentication = context.getAuthentication(); // call super.saveContext according to your use case } } Finally, register this class in the WebSecurityConfigurerAdapter: @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.securityContext().securityContextRepository(customSecurityContextRepository); } If anyone has a better solution I would be interested in hearing it.
doc_23537076
My boss is trying to convince me to make a custom application to handle the whole thing, but I've been considering trying to pitch an Infopath + Sharepoint solution to him for the form management. However, I have absolutely no experience with either, so I don't know if any kind of integration with Quickbooks would be possible. So would an integration infopath/sharepoint with Quickbooks be feasible, and can you give me tips on where to look for info on how to implement it. Also, hiring a 'SharePoint Developer' is out of the question. So would a VB.Net/C# developer who has experience with web application development be able to address the programming skills required for a solution? I'm open to any ideas. A: I believe a .NET developer could probably handle this situation. You could possibly write code in the Infopath forms themselves, or create SharePoint workflows (using Visual Studio). It would probably be a decently complex and hard to maintain solution though. A: I have not expirience with Quickbooks... If Quickbooks has web services to perform operations you are interested in you most likely will be able to make InfoPath form to collect/submit data. InfoPath alone (as client application part of Office) may be enough - you should be able to quiclky prototype form you have InfoPath installed. For server side rendering of the InfoPath forms you need Enterprise edition of the SharePoint Server - not sure if this task alone would justify the purchase.
doc_23537077
My problem is that the proxy code is not re-generated. When I select to update the service reference, the following happens: * *A dialog with the title "Updating service reference 'name-of-reference'" is shown. This dialog has a progress bar. *The progressbar moves and the status text in the dialog is changed to "Updating configuration" *The progressbar moves a bit more, and the status text is chnaged to "Configuration update complete" The dialog doesn't show the text "Generating \something\" (can't remember the exact wording) which I would expedct. If I delete the service reference and add it again, the proxy is properly generated. I add the service using the exact same settings as before, so I don't think it's a issue I can solve by changing the service reference configuration on the client. One thing I suspect may be the problem is that I've renamed the default wsHttpBindings in app.config. I've also renamed the default endpoints. The reason behind this is that I need more than one endpoint and having one named 'some-default-name' and one with my own name is just confusing. The problem with deleting the service and adding it again is that Visual Studio adds a new binding in app.config (among other things) which should not be there. Anyone seen this problem before? Anyone knows of a solution to it? A: When we have had this problem it has usually been one of these errors: * *The size of the contract has increased, and is now so large that the WCF configuration does not allow it to be transferred. *A new class has been added to a WCF Interface and that class is not marked as serializable. *There is a compile error that stops the code from building and it therefore uses the old dll A: I've run into this problem with the following conditions: * *Our workstations are connected to an Active Directory domain (nearly everything uses Windows Authentication) *The service reference I'm trying to update is hosted on localhost, and is running under IIS Express (so the Application Pool user is running as the developer's personal domain user account) *Another developer has added or updated the reference to the project more recently than me. The only way I have figured out how to workaround this issue is to edit the configuration.svcinfo file for that service reference (you will need to show all files for the project to see it in visual studio), locate the following section: userPrincipalName value=&quot;user@domain.com&quot; and change the user to my own domain user. After saving the file, I have no trouble updating the reference until another developer updates the service reference (likely using the same workaround). Unfortunately, I haven't been able to figure out a permanent solution to this issue. A: My error was that I forgot to add the OperationContract attribute. A: In my case the problem was that the previous developer had added the service reference using his machine name rather than localhost. So when I told Visual Studio to update, it connected to his machine, which did not have the changes. I modified the service reference files and replaced his machine name with localhost and it was able to update the reference. A: I had this problem too. Deleted the service reference and recreated it again. A: My problem was that I had two methods with the same name. Everything builded fine, but I couldn't update service reference. When I tried to start just the WCF service, the error pops up. A: Two easy steps to solve that: * *Run Service, then stop it. *Update service reference. A: Highlight the service as the active project, F5 to run it in VisualStudio, it will start up in the service test app. Stop debugging. Then try to update your service reference - worked for me. A: I know this solution is a bit late, but after trying the posted solutions with no success, this worked: When you create a WebService, it generates a .dll file that you reference as your service reference. This .dll is (as most know) not recreated everytime you make changes to the .SVC file. You can see this if you go and view the date modified property of the web service .dll file, in my case it was three hours old! My solution was to make appropriate changes to the service contact, save it, and re-build the project which will cause it to recreate all the .dll's reflecting the changes you made to the service contact file (.svc). After this, update the service reference on the client app, and the changes are evident. * *Spades A: I had the same problem. Modified some of the data contracts. Tried to "Update Service Reference" and did not see the change. Dropped and re-added the service. Still didn't see the change when writing code in the client. Opened my client with Reflector and saw the service types had the change! So why was intellisense still showing old properties? Restarted Visual Studio and the modifications finally showed in intellisense. A: I had the same problem, this by me it was caused by GIT Merge Conflict, i was missing the following code from my csproj file <ItemGroup> <None Include="Service References\<SERVICE NAME>\Reference.svcmap"> <Generator>WCF Proxy Generator</Generator> <LastGenOutput>Reference.cs</LastGenOutput> </None> </ItemGroup> I have added this onder the line of Reference.svcmap A: Another solution to these kinds of problems is if your namespaces get jumbled in referenced projects that both consume the service. So: ProjectA - Consumes ServiceA ProjectB - Consumes ServiceA, Has Reference to ProjectA If you change ServiceA and update ProjectB, sometimes the namespaces can can change to look at ProjectA's version of the service.
doc_23537078
How does everyone make their theme when creating their sencha touch 2 apps? Is using sass the recommended way for this even though its so trial and error/look better? Does Sencha Architect let me do this? A: To try out SASS without really changing and compiling your project styles, you can use this online tool to visualize how it would look like : http://developerextensions.com/index.php/sencha-touch-2-1-themes-builder-demo A: I'd suggest you make use of SASS since it's not only the correct way to style your own Sencha Touch theme but also provide you some powerful global CSS variables and mixins that you cannot easily achieve through normal css. By using SASS, you need to install SASS and Compass. Follow this helpful tutorial on how to do it: http://www.netmagazine.com/tutorials/styling-user-interface-sencha-touch-application
doc_23537079
<?php /* Template Name: 'Template 1' * Template Post Type: cpt1, cpt2, cpt3 */ ?> My problem is when I'm creating a new post. I have to choose the template each time...(> screenshot) Not really convenient for my client. A repetitive handling. Would it be possible to force a default template ? Any ideas ? Thanks in advance for your time. A: You can achieve what you need by setting up custom templates for your CPTs that will conform to the WP template hierarchy, and accessing the common template from within these template files. Specifically, for the custom post types which you wish to have common templates, you could use the get_template_part() function within these files to access a common template structure. Template Hierarchy If you name your template files appropriately, WordPress knows that the template should be used by default for a given custom post type. For example, if you name a template file single-product.php, this template will be used for a custom post type registered with the slug product. The templates are selected in hierarchically, so if you need to you can even have WordPress display a custom template for a specific slug. The hierarchy for custom post types is: * *single-{post-type}-{slug}.php If you have custom post type {post-type} with slug {slug}, this template will be used. otherwise... *single-{post-type}.php If you have a custom post type {post-type} this template will be used. *single.php Otherwise, WP falls back to single.php *singular.php - used if there is no single.php *Finally, if there is no other option WP uses index.php. In your case, you might set up the various templates individually for each custom post type, but for the templates that should be the same, reference your common template parts from within these templates. For example, if you have custom post types cpt1 and cpt2 which should access the same template, create two templates (single-cpt1.php and single-cpt2.php) and add the following code to both of them: <?php get_template_part('templates/content', 'common-cpt'); ?> You can then add the common template data to a template file named templates/content-common-cpt.php and your problem should be solved. References * *get_template_part() *WordPress template hierarchy
doc_23537080
applicationContect.xml: <bean id="CalcValidate" class="com.fmr.pmsvcs.orders.fixture.utility.CalcValidate" > <property name="orderRestServiceL" > <ref local="OrderRestService" /> </property> </bean> And my class looks like bellow : CalcValidate.java public class CalcValidate { public static OrderRestService orderRestServiceL; public static OrderRestService getOrderRestServiceL() { return orderRestServiceL; } public static void setOrderRestServiceL(OrderRestService orderRestServiceL) { CalcValidate.orderRestServiceL = orderRestServiceL; } public static String getNetAssets(String user, BigInteger fundid, Order CalcOrder) throws Exception { PortfolioReferenceParameter par = orderRestServiceL.netAssets(user, fundid); if (par.getPortfolios().get(0) == null && CalcOrder.getPortfolioTna() == null && CalcOrder.getPortfolioTnaUsd() == null) { System.out .println(" ##### PASS Portfolio Net Asset are null in service and DB"); return OrderFixtureConstants.TRUE; } // *** Validate against Net Asset in Fund Base Currency if (!par.getPortfolios().get(0).getTotalNetAssets() .equals(CalcOrder.getPortfolioTna())) { return ("FAIL net Asset in response [" + CalcOrder.getPortfolioTna() + " ] doesn't match net Asset in DB [" + par.getPortfolios().get(0).getTotalNetAssets() + " ]"); } System.out.println(" ##### PASS net Asset in response [" + CalcOrder.getPortfolioTna() + " ] does match net Asset in DB [" + par.getPortfolios().get(0).getTotalNetAssets() + " ]"); // *** Validate against Net Asset in Fund Base Currency if (!par.getPortfolios().get(0).getTotalNetAssetsUSD() .equals(CalcOrder.getPortfolioTnaUsd())) { return ("FAIL net Asset USD in response [" + CalcOrder.getPortfolioTnaUsd() + " ] doesn't match net Asset in DB [" + par.getPortfolios().get(0).getTotalNetAssetsUSD() + " ]"); } System.out.println(" ##### PASS net Asset in response [" + CalcOrder.getPortfolioTnaUsd() + " ] does match net Asset in DB [" + par.getPortfolios().get(0).getTotalNetAssetsUSD() + " ]"); return OrderFixtureConstants.TRUE; } } In later part of my class I am calling a method like orderRestServiceL.getMethod(); Here "orderRestServiceL" coming as null. Anybody has any Idea how to resolve this? A: Your issue seems to be related to the Java class field. it is declared as static while it should be non-static: public class CalcValidate { private OrderRestService orderRestServiceL; public OrderRestService getOrderRestServiceL() { return orderRestServiceL; } public void setOrderRestServiceL(OrderRestService orderRestServiceL) { this.orderRestServiceL = orderRestServiceL; }
doc_23537081
It seems that Val only accepts strings that contains . as decimal separator. From the ASM code in _ValExt (which Val calls) it looks like it does not use DecimalSeparator. Can I safely rely on the fact (?) that Val accepts real number strings with . as decimal separator? A: Val is ancient, low level and a bit tricky to use. I would not recommend using it in user code. Rather use other routines to scan values, like StrToFloat, etc. If you use StrToFloat with TFormatSettings.Invariant, you can be sure that you get the dot ('.') as decimal separator. Take a look at the following piece of test code. On my German system, the decimal separator is a comma. So I tried the following: procedure Test; var E: Extended; S: Single; I: Integer; Code: Integer; begin Val('1.234', E, Code); if Code = 0 then Writeln('1.234 Extended: ', E) else Writeln('1.234 Extended: Error, code = ', Code); Val('1,234', E, Code); if Code = 0 then Writeln('1,234 Extended: ', E) else Writeln('1,234 Extended: Error, code = ', Code); Val('1.234', S, Code); if Code = 0 then Writeln('1.234 Single: ', S) else Writeln('1.234 Single: Error, code = ', Code); Val('1234', I, Code); if Code = 0 then Writeln('Integer: ', I) else Writeln('Integer: Error, code = ', Code); end; The output is: 1.234 Extended: 1.23400000000000E+0000 1,234 Extended: Error, code = 2 1.234 Single: 1.23399996757507E+0000 Integer: 1234 This clearly demonstrates that Val does not use the system-defined decimal separator, and only accepts the invariant decimal separator, i.e. '.'. The docs for System.Val are a little misleading here, IMO. UPDATE Seems I used E instead of S in the "single part" of the code. Apparently you also get the correct value if you pass a Single, so I guess the compiler (which knows what gets passed) somehow passes this information to the internal routine. Looking at the CPU window, you can see that if a floating point type is passed in, System.@ValExt is called, which returns the value on the top of the FPU stack (ST(0)). The compiler than adds the appropriate code to store that value (FSTP TBYTE, FSTP QWORD or FSTP DWORD for Extended, Double and Single, respectively). Similarly, for integral variables (up to 32 bit), System.@ValLong is called, which returns an Integer in EAX, and appropriate code to store the value in the right size is added by the compiler. For 64 bit integers, @ValInt64 is called, which returns a value in EDX:EAX. FWIW, it also shows that Writeln doesn't use the system-defined decimal separator.
doc_23537082
Here's what I tried so far: self.navigationController?.navigationBar.translucent = true self.navigationController?.navigationBar.backgroundColor = UIColor.blueColor() The navigation bar does not change. Even setting the translucency to true has no effect at all. I can change the tint color without any problems, but not the background color. But if I change the color in the storyboard, it works fine! Is there an option in the storyboard that I enabled/disabled by mistake? Can someone help me with this? Thanks. A: You should set the navigation bar's barTintColor instead of backgroundColor. This should be what you are looking for.
doc_23537083
Tom,1,2,3,4,5,6,7,8,9,10 Steve,1,2,3 Bob,1,2,3,4,5,6 Cthulhu,1,2,3,4,5 Greg,1,2,3,4,5,6,7,8,9,10,11,12,13,14 I can't figure out how to parse this with FileHelpers. I would imagine I should be able to do something like this: [DelimitedRecord(",")] public class MyRecord { public string Name; public List<int> Values; } But that doesn't appear to be possible with FileHelpers. The best I can seem to do is this: [DelimitedRecord(",")] public class MyRecord { public string Name; public string Values; public string[] ActualValuesInNiceArray { get { return Values.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries); } } } I then would need to split Values on commas to get the set of values for each record. Doesn't seem to be much of a point in using FileHelpers if I have to manually parse a portion of each record. Am I missing something? I've gone over docs/examples, but can't seem to find a solution for my format. Excel has no trouble with my format, so I would imagine there is a way to do it with an existing free library (FileHelpers or some other library). Any ideas? A: You can use an Array Field and the library will do the work: [DelimitedRecord(",")] public class MyRecord { public string Name; public int[] Values; } You can even use [FieldArrayLength(2, 8)] [DelimitedRecord(",")] public class MyRecord { public string Name; [FieldArrayLength(2, 8)] public int[] Values; } The set the min/max number of values I strongly recomend to download the last version of the library from here: http://teamcity.codebetter.com/viewType.html?buildTypeId=bt65&tab=buildTypeStatusDiv Check the artifacts section A: You could create a class MyRecord that holds all the potential values, e.g. [DelimitedRecord(",")] public class MyRecord { public string Name; public int Value1; ..... [FieldOptional] public int Value5; ...... [FieldOptional] [FieldNullValue(typeof(int), "-1" )] public int Value14; } and make most of those fields optional (no. 5 through 14 in my example) and combine that with e.g. a FieldNullValue to handle those non-existing fields (or make those optional fields a nullable int: public int? Value5
doc_23537084
Basically I wanted a near seamless way of downloading csv files from my dropbox folders from the commandline in R in one line of code so that I dont need to click on the allow button after the token request. Is this possible? Here is the code I used to wrap up a dropbox csv download. db.csv.download <- function(dropbox.path, ...){ cKey <- getOption('DropboxKey') cSecret <- getOption('DropboxSecret') reqURL <- "https://api.dropbox.com/1/oauth/request_token" authURL <- "https://www.dropbox.com/1/oauth/authorize" accessURL <- "https://api.dropbox.com/1/oauth/access_token/" require(devtools) install_github("ROAuth", "ropensci") install_github("rDrop", "karthikram") require(rDrop) dropbox_oa <- oauth(cKey, cSecret, reqURL, authURL, accessURL, obj = new("DropboxCredentials")) cred <- handshake(dropbox_oa, post = TRUE) raw.data <- dropbox_get(cred,dropbox.path) data <- read.csv(textConnection(raw.data), ...) data } Oh and if its not obvious I have put my dropbox key and secret in my .Rprofile file, which is what the getOption part is referring to. Thanks in advance for any help that is provided. (For bonus points...if anybody knows how to get rid of all the loading messages even for the install that would be great...) A: library(rDrop) # my keys are in my .rprofile, otherwise specifiy inline db_token <- dropbox_auth() # Hit ok to authorize once through the browser and hit enter back at the R prompt. save(db_token, file="my_dropbox_token.rdata") Dropbox token are non-expiring and can be revoked anytime from the Dropbox web panel. For future use: library(rDrop) load('~/Desktop/my_dropbox_token.rdata') df <- data.frame(x=1:10, y=rnorm(10)) > df x y 1 1 -0.6135835 2 2 0.3624928 3 3 0.5138807 4 4 -0.2824156 5 5 0.9230591 6 6 0.6759700 7 7 -1.9744624 8 8 -1.2061920 9 9 0.9481213 10 10 -0.5997218 dropbox_save(db_token, list(df), file="foo", ext=".rda") rm(df) df2 <- db.read.csv(db_token, file='foo.rda') > df2 x y 1 1 -0.6135835 2 2 0.3624928 3 3 0.5138807 4 4 -0.2824156 5 5 0.9230591 6 6 0.6759700 7 7 -1.9744624 8 8 -1.2061920 9 9 0.9481213 10 10 -0.5997218 If you have additional problems, please file an issue.
doc_23537085
My recorder is configured like this: public static int RECORDER_SAMPLERATE = 44100; ... mRecorder = new AudioRecord.Builder() .setAudioSource(MediaRecorder.AudioSource.MIC) .setAudioFormat( new AudioFormat.Builder() .setEncoding(AudioFormat.ENCODING_PCM_16BIT) .setSampleRate(RECORDER_SAMPLERATE) .setChannelIndexMask(AudioFormat.CHANNEL_IN_DEFAULT) .build()) .setBufferSizeInBytes(AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE, AudioFormat.CHANNEL_IN_DEFAULT, AudioFormat.ENCODING_PCM_16BIT) * 4) .build(); And my track is configured like this: mTrack = new AudioTrack.Builder().setAudioAttributes( new AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_MEDIA) .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build()) .setAudioFormat( new AudioFormat.Builder() .setEncoding(AudioFormat.ENCODING_PCM_16BIT) .setSampleRate(44100) .setChannelMask(AudioFormat.CHANNEL_OUT_STEREO).build()) .setBufferSizeInBytes(AudioTrack.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT)) .build(); I have tried different buffer sizes, different Usage and Content types, but still get the same distorted result. I hope someone can help with this
doc_23537086
I'm using the following to disable a value in a dropdown, which works fine. $('*[id^="dd"] option[value=' + info.products_options_values_id_affected + ']').attr("disabled",vOut); The problem is, if the user selected this option before it was disabled, it needs to reset the dropdown to its default(top) value. The problem is, all of the html is dynamically generated, and I don't know which dropdown contains the value being acted on. Every value in every dropdown has a unique id, so what I'm hoping to do is determine which dropdown contains an entry with the same value, not text, as the one selected by the code above, and reset it back to its top value. Is it possible to do a select in this way? Thanks! EDIT: Here's a sample of the generated html I'm working on: <select name="id[11]" onchange="edComboFunc(11)" id="dd11"> <option value="16">Choose Here</option> <option value="15">Color Changing</option> <option value="14">Amber</option> <option value="13">Blue</option> <option value="12">Green</option> <option value="20">White</option> <option value="21">Purple</option> <option value="22">Turquoise</option> <option value="27">Orange</option> <option value="11">Red</option> <option value="23">Pink</option> </select> A: I haven't tested this, but if I understood your question correctly this is what you're trying to do? If not, let me know please. $("option[value*='23']").parent("select");
doc_23537087
function getColour(d) { switch (d) { case 'IPMSAN': return '#00FF00'; case 'PARK': return '#000000'; ; } }; var legend = L.control({position: 'bottomright'}); legend.onAdd = function (map) { var div = L.DomUtil.create('div', 'info legend'); let faultstatus = ['IPMSAN', 'PARK']; // loop through the status values and generate a label with a coloured square for each value for (var i = 0; i < faultstatus.length; i++) { div.innerHTML += '<i class="circle" style="background:' + getColour(faultstatus[i]) + '"></i> ' + (faultstatus[i] ? faultstatus[i] + '<br>' : '+'); } return div; }; legend.addTo(map); As you can see, I set the color as follows but In my map i can't see an color only 'faultstatus ' ,Any help or guidance on how I can make it shown ? and this is the CSS: .legend { text-align: left; line-height: 30px; color: #555; } .legend i { width: 20px; height: 30px; float: left; margin-right: 8px; opacity: 0.7; } .legend .circle { border-radius: 50%; width: 10px; height: 10px; margin-top: 8px; }
doc_23537088
I am working on an android project and i have to make a smooth scrolling panel like shown in this app https://play.google.com/store/apps/details?id=com.paisaswipe.android I tried this with the help of panels, but when i tested it on a real android device then app goes crashed. And that layout is also not looks good and completely aligned. So, can anyone suggest me that how i can implement this thing in android??? A: Checkout https://github.com/frakbot/GlowPadBackport Example on Google Play: https://play.google.com/store/apps/details?id=net.sebastianopoggi.samples.ui.GlowPadSample
doc_23537089
Error: is.call(call) is not TRUE The results of a traceback(): 11: stop(sprintf(ngettext(length(r), "%s is not TRUE", "%s are not all TRUE"), ch), call. = FALSE, domain = NA) 10: stopifnot(is.call(call)) 9: standardise_call(call, env) 8: object_from_call(call, env, preref) 7: (function (call, ref, comment_ref) { preref <- parse.preref(as.character(comment_ref)) if (is.null(preref)) return() preref$object <- object_from_call(call, env, preref) preref$srcref <- list(filename = file, lloc = as.vector(ref)) add_defaults(preref) })(dots[[1L]][[1L]], dots[[2L]][[1L]], dots[[3L]][[1L]]) 6: mapply(FUN = f, ..., SIMPLIFY = FALSE) 5: Map(extract, parsed, refs, comment_refs) 4: FUN(c("/home/path/to/package/file1.r", "/home/path/to/package/file2.r", .... # list of files truncated "/home/path/to/package/doc.file.r")[[25L]], ...) 3: lapply(r_files(base_path), parse_file, env = env) 2: parse_package(base_path, load_code) 1: roxygenize("~/Current/r/path/to/package/") Has anyone experienced this problem before? I'm not even sure how to debug it further. A: This error occurs if, instead of the typical NULL value that one puts at the end of the documentation for the package, one uses NA. Simply updating to NULL will remove the error.
doc_23537090
I tried to use jQuery resize(), but it is not working properly. You can see working demo here: pepnest.com/hbs Here, when you resize browser, it cuts down height of slides. This is my code in JS file: $(document).ready(function(){ var width = $(window).width(); if (width < 368) { $('.bxslider').bxSlider({ minSlides: 1, maxSlides: 1, slideWidth: 200, slideMargin: 20, captions: true }); } else if (width < 700) { $('.bxslider').bxSlider({ minSlides: 1, maxSlides: 1, slideWidth: 280, slideMargin: 20, captions: true }); } else if (width < 980) { $('.bxslider').bxSlider({ minSlides: 2, maxSlides: 2, slideWidth: 280, slideMargin: 20, captions: true }); } else if (width < 1200) { $('.bxslider').bxSlider({ minSlides: 3, maxSlides: 3, slideWidth: 280, slideMargin: 20, captions: true }); } else { $('.bxslider').bxSlider({ minSlides: 4, maxSlides: 4, slideWidth: 280, slideMargin: 20, captions: true }); } $(window).resize(function(){ var width = $(window).width(); if (width < 368) { $('.bxslider').bxSlider({ minSlides: 1, maxSlides: 1, slideWidth: 200, slideMargin: 20, captions: true }); } else if (width < 700) { $('.bxslider').bxSlider({ minSlides: 1, maxSlides: 1, slideWidth: 280, slideMargin: 20, captions: true }); } else if (width < 980) { $('.bxslider').bxSlider({ minSlides: 2, maxSlides: 2, slideWidth: 280, slideMargin: 20, captions: true }); } else if (width < 1200) { $('.bxslider').bxSlider({ minSlides: 3, maxSlides: 3, slideWidth: 280, slideMargin: 20, captions: true }); } else { $('.bxslider').bxSlider({ minSlides: 4, maxSlides: 4, slideWidth: 280, slideMargin: 20, captions: true }); } }); }); Can anyone help me where I am going wrong? A: I'm sorry to say that this is not the way. Imagine your browser initializing a new slider at every pixel of movement you make re-sizing it. You have to destroy the bxSlider before initializing a new one! slider.destroySlider(); http://bxslider.com/options Besides that, you really do not have to fire the event at every re size action. Please check first if a 'redraw' is necessary (e.g. re sizing from 1020 to 1080 px doesn't need it) For example using jQuery: http://jsfiddle.net/r91ec9n6/3/ var resolutionLimits = [0, 368, 700, 980, 1200]; var currentResolutionLimit = null; var resizeHandler = function() { var foundResolution = 0; var windowSize = $(window.document).width(); for(var i = 0; i < resolutionLimits.length; i++) foundResolution = windowSize > resolutionLimits[i] ? i : foundResolution; if(foundResolution !== currentResolutionLimit){ currentResolutionLimit = foundResolution var currentResolution = resolutionLimits[currentResolutionLimit]; // This is only called when the resolution is changed beyond a limit AND at document load $(window.document.body).empty().append('Resolution changed, currently > ' + currentResolution); } } $(window).resize(resizeHandler).resize();
doc_23537091
I am trying to do this using foreach or purrr, but I keep getting stuck. STATA Code: foreach v in zip income child{ g `v`_agg="" **generate an empty column with the specified name (e.g. address_agg or income_agg)** foreach l in 20190601 20180401 20171001 20160801{ replace `v'_agg=`v'`l' if missing (`v'_agg) **replace agg variable with the latest version if missing** } } Here is the data example: zip20190601 zip20180401 zip20171001 zip20160801 income20190601 income20180401 income20171001 income20160801 child20160801 child20171001 child20180401 child20190601 1 NA 11440 12016 15686 75038 63573 82391 47517 0 1 1 2 2 13089 12626 13670 16155 89494 64984 62603 47252 0 1 1 2 3 13258 12249 13333 16819 NA NA 48231 45729 0 1 1 2 4 NA NA 18480 18611 89480 67348 55516 45863 0 1 1 2 5 13990 10497 12573 13406 70053 63850 87833 48332 1 2 2 3 6 17005 11491 15227 17518 78087 70741 46318 47823 1 2 2 3 7 17174 17006 13461 11189 76780 66649 54578 46196 1 2 2 3 8 12452 15317 18049 14284 76654 73583 70090 48281 0 1 1 2 9 18449 14262 11013 17810 91422 79722 53948 45986 0 1 1 2 10 11429 11731 13564 14603 84282 60190 45133 46956 0 1 1 2 structure(list(zip20190601 = c(NA, 13089L, 13258L, NA, 13990L, 17005L, 17174L, 12452L, 18449L, 11429L), zip20180401 = c(11440L, 12626L, 12249L, NA, 10497L, 11491L, 17006L, 15317L, 14262L, 11731L), zip20171001 = c(12016L, 13670L, 13333L, 18480L, 12573L, 15227L, 13461L, 18049L, 11013L, 13564L), zip20160801 = c(15686L, 16155L, 16819L, 18611L, 13406L, 17518L, 11189L, 14284L, 17810L, 14603L), income20190601 = c(75038L, 89494L, NA, 89480L, 70053L, 78087L, 76780L, 76654L, 91422L, 84282L), income20180401 = c(63573L, 64984L, NA, 67348L, 63850L, 70741L, 66649L, 73583L, 79722L, 60190L), income20171001 = c(82391L, 62603L, 48231L, 55516L, 87833L, 46318L, 54578L, 70090L, 53948L, 45133L), income20160801 = c(47517L, 47252L, 45729L, 45863L, 48332L, 47823L, 46196L, 48281L, 45986L, 46956L), child20160801 = c(0, 0, 0, 0, 1, 1, 1, 0, 0, 0), child20171001 = c(1, 1, 1, 1, 2, 2, 2, 1, 1, 1), child20180401 = c(1, 1, 1, 1, 2, 2, 2, 1, 1, 1), child20190601 = c(2, 2, 2, 2, 3, 3, 3, 2, 2, 2)), .Names = c("zip20190601", "zip20180401", "zip20171001", "zip20160801", "income20190601", "income20180401", "income20171001", "income20160801", "child20160801", "child20171001", "child20180401", "child20190601"), class = "data.frame", row.names = c(NA, -10L)) Goal: I am trying to create a current "agg" variable for each of the variables (zip_agg, child_agg, income_agg) by running a for loop through the different dated variables to replace values from the most recent data. If the most recent version is missing, it should go back to the next latest date. I have started to code it out but I know this is incorrect. variable_date<-c("20190601", "20180401", "20171001", "20160801") variable_list<-c("zip", "income", "child") # using foreach package foreach(x=variable_list, .combine = 'cbind') %:% foreach(y=variable_date, .combine = 'c') %do% { var_agg<-str_c(x, "_agg") #create variable name my.df%<>% mutate(var_agg=NA, var_agg=ifelse(is.na({{var_agg}})==T, my.df[str_c(x,y)], {{var_agg}})) Expected output Any help would be appreciated! A: Perhaps, an option is to reshape into 'long' format and then do the filter or slice based on the last date library(dplyr) library(tidyr) library(stringr) df1 %>% mutate(rn = row_number()) %>% pivot_longer(cols = -rn, names_to = c(".value", "date"), names_sep="_") %>% group_by(rn) %>% slice(which.max(date)) %>% ungroup %>% select(-rn) %>% rename_all( ~ str_c(., '_agg')) %>% bind_cols(df1, .) If we don't need the NA i.e. if the last element is NA based on the date, then an option is to summarise after arrangeing by 'date' df1 %>% mutate(rn = row_number()) %>% pivot_longer(cols = -rn, names_to = c(".value", "date"), names_sep="_") %>% arrange(rn, date) %>% group_by(rn) %>% summarise_at(vars(zip:child), ~ last(.[!is.na(.)])) %>% ungroup %>% select(-rn) %>% rename_all( ~ str_c(., '_agg')) %>% bind_cols(df1, .) #zip_20190601 zip_20180401 zip_20171001 zip_20160801 income_20190601 income_20180401 income_20171001 income_20160801 child_20160801 #1 NA 11440 12016 15686 75038 63573 82391 47517 0 #2 13089 12626 13670 16155 89494 64984 62603 47252 0 #3 13258 12249 13333 16819 NA NA 48231 45729 0 #4 NA NA 18480 18611 89480 67348 55516 45863 0 #5 13990 10497 12573 13406 70053 63850 87833 48332 1 #6 17005 11491 15227 17518 78087 70741 46318 47823 1 #7 17174 17006 13461 11189 76780 66649 54578 46196 1 #8 12452 15317 18049 14284 76654 73583 70090 48281 0 #9 18449 14262 11013 17810 91422 79722 53948 45986 0 #10 11429 11731 13564 14603 84282 60190 45133 46956 0 # child_20171001 child_20180401 child_20190601 zip_agg income_agg child_agg #1 1 1 2 11440 75038 2 #2 1 1 2 13089 89494 2 #3 1 1 2 13258 48231 2 #4 1 1 2 18480 89480 2 #5 2 2 3 13990 70053 3 #6 2 2 3 17005 78087 3 #7 2 2 3 17174 76780 3 #8 1 1 2 12452 76654 2 #9 1 1 2 18449 91422 2 #10 1 1 2 11429 84282 2 Update If there are no separation in the names, we can still use a regex lookaround to separate within names_sep df2 %>% mutate(rn =row_number()) %>% pivot_longer(cols = -rn, names_to = c(".value", "date"), names_sep="(?<=[a-z])(?=[0-9])") %>% arrange(rn, date) %>% group_by(rn) %>% summarise_at(vars(zip:child), ~ last(.[!is.na(.)])) %>% ungroup %>% select(-rn) %>% rename_all( ~ str_c(., '_agg')) %>% bind_cols(df2, .) # zip20190601 zip20180401 zip20171001 zip20160801 income20190601 income20180401 income20171001 income20160801 child20160801 child20171001 #1 NA 11440 12016 15686 75038 63573 82391 47517 0 1 #2 13089 12626 13670 16155 89494 64984 62603 47252 0 1 #3 13258 12249 13333 16819 NA NA 48231 45729 0 1 #4 NA NA 18480 18611 89480 67348 55516 45863 0 1 #5 13990 10497 12573 13406 70053 63850 87833 48332 1 2 #6 17005 11491 15227 17518 78087 70741 46318 47823 1 2 #7 17174 17006 13461 11189 76780 66649 54578 46196 1 2 #8 12452 15317 18049 14284 76654 73583 70090 48281 0 1 #9 18449 14262 11013 17810 91422 79722 53948 45986 0 1 #10 11429 11731 13564 14603 84282 60190 45133 46956 0 1 # child20180401 child20190601 zip_agg income_agg child_agg #1 1 2 11440 75038 2 #2 1 2 13089 89494 2 #3 1 2 13258 48231 2 #4 1 2 18480 89480 2 #5 2 3 13990 70053 3 #6 2 3 17005 78087 3 #7 2 3 17174 76780 3 #8 1 2 12452 76654 2 #9 1 2 18449 91422 2 #10 1 2 11429 84282 2 A: We can use max.col here. We divide the operation into two parts, first where we want to calculate the latest value for all "zip" and "income" columns and the second part where we want to calculate max value from "child" columns. variable_list <- c("zip", "income") #Part 1 df[paste0(variable_list, '_agg')] <- lapply(variable_list, function(x) { cols <- grep(x, names(df)) df[cols][cbind(1:nrow(df), max.col(!is.na(df[cols]), ties.method = "first"))] }) #Part 2 cols <- grep('child', names(df)) df$child_agg <- df[cols][cbind(1:nrow(df), max.col(df[cols]))] #Result df[13:15] # zip_agg income_agg child_agg #1 11440 75038 2 #2 13089 89494 2 #3 13258 48231 2 #4 18480 89480 2 #5 13990 70053 3 #6 17005 78087 3 #7 17174 76780 3 #8 12452 76654 2 #9 18449 91422 2 #10 11429 84282 2
doc_23537092
gamer_user where u.id = gamer_rec t2.user_id where gamer_user has user_name, and gamer_rec has company name SELECT t1.company,usc.`name`,ur.id,u.id,t1.user_name,t2.user_name FROM `game_social` AS usc JOIN gamer_rec t2 ON t2.user_id = `usc`.`user_id` JOIN gamer_rec t1 ON t1.user_id = `u`.`id` JOIN `gamer_user` AS u ON `usc`.`user_id` = `u`.`id` JOIN `gamer_user` AS ur ON `ur`.`email` = `usc`.`email` but i am getting error as [Err] 1054 - Unknown column 'u.id' in 'on clause' gamer_rec t1 or t2 user_id user_name 1 paul 2 thomas 3 Nancy gamer_user u or ur id user_id email 1 2 eabce@abce.com 2 1 aabc@abc.com 3 4 dabcd@abcd.com game_social id user_id email 1 2 aabc@abc.com 2 3 dabcd@abcd.com 3 1 eabce@abce.com 4 6 fabcf@abcf.com Here is the output.. please find t1.user_id and t2.user_id --- but i need t2.user_id = ur.id and t1.user_id= u.id are same A: You need to join a table before you can use it. So switch the joins: SELECT t1.company, t1.user_name, t2.user_name, usc.`name`, ur.id, u.id FROM game_social usc JOIN gamer_user u ON `usc`.`user_id` = `u`.`id` JOIN gamer_user ur ON `ur`.`email` = `usc`.`email` JOIN gamer_rec t1 ON t1.user_id = `u`.`id` JOIN gamer_rec t2 ON t2.user_id = `usc`.`user_id`
doc_23537093
A: Not sure about the v19 support library, but the v20 one has the following methods: public void setColorSchemeResources(int colorRes1, int colorRes2, int colorRes3, int colorRes4) Which allows you to set the colors by resource. But the following method also exists, which takes colors: public void setColorSchemeColors(int color1, int color2, int color3, int color4) The second one is your answer
doc_23537094
DECK = [] PLAYER = [] COMP = [] for x in PLAYER: if i,j in PLAYER: if i,j in DECK: p = DECK.index(i,j) p = -51+p DECK.pop(-p) I am aware that i,j does not work here. How can I represent the card in the hand so that I can index and remove it from the list that contains the deck? I think I'm probably way off on this stuff, I've only been learning Python for about four weeks now. Thanks in advance. A: Perhaps: for x in PLAYER: if x in DECK: DECK.remove(x) A: You should hand out cards from DECK to PLAYER and COMP. In that case, you wouldn't end up in such a situation. Something like: PLAYER.append(DECK.pop(index))
doc_23537095
Is there a way within angular-ui-router to suppress abstract states from being added to the history? A: Have the same problem. I hope it will help you How do I get the Back Button to work with an AngularJS ui-router state machine? It's a little bit hard for me and it seems there must be a simpler solution Edit: I did it. First of all you need your old state (also we have wrapper for localstorage, so you should change methods). angular .module('app') .run(appRunFunction); appRunFunction.$inject = ['$rootScope', 'localstorage']; function appRunFunction($rootScope, localstorage) { $rootScope.$on('$stateChangeSuccess', function(event, toState, toParam, fromState, fromParam) { localstorage.setValue('lastState', fromState.name); }); }; We also have written a service that redirects from an abstract state to regular state after comparison your next regular state with your last one angular .module('app.services') .factory('states', states); states.$inject = ['$state', 'localstorage']; function states($state, localstorage) { var service = {reloadWithParam: reloadWithParam}; return service; function reloadWithParam(param, value) { var fromState = localstorage.getValue('lastState') + '.' + localstorage.getValue('lastPage'); var toState = $state.current.name + '.' + value; var paramObject = {}; paramObject[param] = value; if (fromState === toState) { window.history.go(-1); } else { $state.go($state.current, paramObject, { notify: false}); localstorage.setValue('lastPage', value); } } }
doc_23537096
And then loading the newly generated component to my container, placed in the tabs, as i am creating the tabs dynamically as per the data. The process is working for first tab, but not for other tabs. That may mean, the container, where i am pushing my runtime component, is generated once, thus not reflecting for other tabs. HTML: <mat-tab-group [selectedIndex]="tabIndex" (selectedTabChange)="getNewTabFields($event)"> <mat-tab *ngFor="let tab of tabs" [label]="tab.displayName"> <div *ngIf="errorOccured" class="text-align-center"> No Data Found! </div> <ng-container #container></ng-container> </mat-tab> </mat-tab-group> Component: @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef; ngOnInit() { this.templateInitial = this.searchConfig.configurations[0].value.resultView; this.query = this.searchConfig.configurations[6].value.queryParams; this.collectionName = this.searchConfig.configurations[6].value.collectionName; this.loadSearchData(); } compileTemplate() { const metadata = { selector: `runtime-component`, template: this.templateInitial }; const _mydata = this.solrResponse.response.docs; const code: string = this.searchConfig.configurations[1].value['logic']; const result: string = ts.transpile(code); const runnalbe: any = eval(result); const compileClass = class RuntimeComponent { solrResponses = _mydata; presentLogic = runnalbe; }; const factory = this.createComponentFactorySync(this.compiler, metadata, compileClass ); if (this.componentRef) { this.container.remove(this.container.indexOf(this.componentRef)); this.componentRef = undefined; } this.componentRef = this.container.createComponent(factory); } private createComponentFactorySync(compiler: Compiler, metadata: Component, componentClass: any): ComponentFactory<any> { const decoratedCmp = Component(metadata)(componentClass); @NgModule({ imports: [CommonModule, SharedModule], declarations: [decoratedCmp] }) class RuntimeComponentModule { } const module: ModuleWithComponentFactories<any> = compiler.compileModuleAndAllComponentsSync(RuntimeComponentModule); this.componentInstance = module.componentFactories.find((f) => f.componentType === decoratedCmp); return module.componentFactories.find((f) => f.componentType === decoratedCmp); } getNewTabFields(event) { this.tabIndex = event.index; this.constructTabData(this.tabIndex); } constructTabData(i) { this.templateInitial = this.tabs[i].configurations.resultView; this.query = this.tabs[i].configurations.query[0].queryParams; this.collectionName = this.tabs[i].configurations.query[0].queryParams['collection'].split(' ')[0]; this.loadSearchData(); } loadSearchData(_row = 10, _start = 0) { this.solrSearchService.getSolrData(this.query, this.collectionName).subscribe((data: any) => { this.solrResponse = []; this.solrResponse = JSON.parse(data); this.compileTemplate(); }); } A: I would rather use for creating these containers the directive. HTML: <mat-tab-group [selectedIndex]="tabIndex" (selectedTabChange)="getNewTabFields($event)"> <div *ngIf="errorOccured" class="text-align-center"> No Data Found! </div> <ng-container myDirective *ngFor="let tab of tabs" [tab]="tab"></ng-container> </mat-tab-group> My directive: @Directive({ selector: '[myDirective]' }) export class MyDirective implements OnInit { @Input() tab: MyTamComponent; constructor(private resolver: ComponentFactoryResolver, private container: ViewContainerRef) {} ngOnInit(): void { const factory = this.resolver.resolveComponentFactory<MyTamComponent>(MyTamComponent); const component = this.container.createComponent(factory); // other stuff component.instance.label = tab.displayName; component.instance.ref = component; } }
doc_23537097
So, my app renders in a weird way: <my-app><div> <app-nav-bar _nghost-ile-2=""><ul _ngcontent-ile-2=""> <!--template bindings={ "ng-reflect-ng-for-of": "[object Object],[object Object],[object Object],[object Object]" }--><li _ngcontent-ile-2="" ng-reflect-raw-style="[object Object]" style="float: left;"> <a _ngcontent-ile-2="" ng-reflect-raw-class="[object Object]" ng-reflect-href="/" href="/">Home</a> </li><li _ngcontent-ile-2="" ng-reflect-raw-style="[object Object]" style="float: left;"> <a _ngcontent-ile-2="" ng-reflect-raw-class="[object Object]" ng-reflect-href="/index/books" href="/index/books">Books</a> </li><li _ngcontent-ile-2="" ng-reflect-raw-style="[object Object]" style="float: right;"> <a _ngcontent-ile-2="" ng-reflect-raw-class="[object Object]" class="active" ng-reflect-href="/index/about" href="/index/about">About</a> </li><li _ngcontent-ile-2="" ng-reflect-raw-style="[object Object]" style="float: right;"> <a _ngcontent-ile-2="" ng-reflect-raw-class="[object Object]" ng-reflect-href="/" href="/">Login</a> </li> </ul> </app-nav-bar> <router-outlet></router-outlet><app-hello _nghost-ile-4=""> <html _ngcontent-ile-4=""> <head _ngcontent-ile-4=""> <link _ngcontent-ile-4="" class="__meteor-css__" href="/merged-stylesheets.css?hash=d42394b95cde74014bba42c21ff2737c29b8fc61" rel="stylesheet" type="text/css"> <base _ngcontent-ile-4="" href="/"> </head> <body _ngcontent-ile-4=""> <my-app _ngcontent-ile-4="">Loading....</my-app> </body> </html> </app-hello> </div> </my-app> As you can see, my-app>(app-nav-bar+app-hello)>html>(head+body) etc.. File main.ts: import { bootstrap } from 'angular2-meteor-auto-bootstrap'; import { disableDeprecatedForms, provideForms } from '@angular/forms'; import {APP_ROUTER_PROVIDERS} from './app.routes' import { AppComponent } from './app.component'; bootstrap(AppComponent, [ disableDeprecatedForms(), provideForms(), APP_ROUTER_PROVIDERS ]); File app.routes.ts import { RouterConfig, provideRouter } from '@angular/router'; import { HelloComponent } from './imports/index' const routes: RouterConfig = [ { path: '', component: HelloComponent } ]; export const APP_ROUTER_PROVIDERS = [ provideRouter(routes) ]; File app.component.html: <div> <app-nav-bar></app-nav-bar> <router-outlet></router-outlet> </div> File index.html: <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <base href="/"> <meta viewport> </head> <body> <my-app>Loading....</my-app> </body> If someone can help me, i will be very happy =) A: I am not sure if it is the right answer, but looks like i missed package, that allows me to use static template directly. So, replacing import template from 'ex.controller.html' @Component({ ... template, ... }) With this @Component({ ... template: 'ex.controller.html', ... }) And deleted import helped a heavily.
doc_23537098
I have been using this which works, but I can't figure out how to do that with sum and case as I need to sum up the revenue together when it equals xyz code that works (replace(revenue, ',', '') code that doesn't work sum(replace(revenue, ',', '') case WHEN food in ('burgers', 'fries') then revenue else 0 end)) as foodsum group by foodcategory i also tried using a nested query but didn't work, does anyone have any recommendations? thanks! A: Here's the correct way on aggregating your revenue based on foodcategory. select case when food in ('burgers', 'fries') then sum(replace(revenue, ',', '')) else 0 end as foodsum from table1 group by foodcategory
doc_23537099
This doesn't work as I want because there are glitches - flickering, because the window is moved back to Left=0. I'm more interested in something like LocationChanging to prevent it from ever moving left or right. private void Window_LocationChanged(object sender, EventArgs e) { if (Left != 0) Left = 0; } A: One option is to catch WM_MOVING window message and manipulate its lParam. Since WM_MOVING comes before the Window moves, you can adjust the next position as you wish. using System; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Interop; public partial class MainWindow : Window { private const int WM_MOVING = 0x0216; [StructLayout(LayoutKind.Sequential)] private struct RECT { public int left; public int top; public int right; public int bottom; } private int _left; private int _width; public MainWindow() { InitializeComponent(); this.Loaded += OnLoaded; } private void OnLoaded(object sender, RoutedEventArgs e) { _left = (int)this.Left; _width = (int)this.Width; var handle = new WindowInteropHelper(this).Handle; var source = HwndSource.FromHwnd(handle); source.AddHook(new HwndSourceHook(WndProc)); } private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (msg == WM_MOVING) { var position = Marshal.PtrToStructure<RECT>(lParam); position.left = _left; position.right = position.left + _width; Marshal.StructureToPtr(position, lParam, true); } return IntPtr.Zero; } }