id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23530700
But in order to not download the dependencies every time, we don’t clean the workspace anymore, which results in other issues. We would like to be able to clean the workspace. We see several options: * *Have a near cache on each Jenkins node, in order to be able to fast reconstruct the maven repository inside the workspace after cleanup. *Have one maven repo per workspace, but outside the workspaces. Disadvantage: disk space – 50+ repos with mostly the same artifacts. We already have this issue with the current setup. *Write a maven extension to separate releases from snapshots into two different maven repos. *Manually clean the workspace before checkout. Disadvantage: we would checkout the project twice – once by Jenkins, because the Jenkinsfile is stored with the project, and once after cleanup. *Use git clean and find a solution to skip the maven repo folder (-x?) What do you recommend?
doc_23530701
sizeof unary-expression sizeof ( type-id ) For example, I want to know how the standard would distinguish between unary-expression   sizeof   unary-expression ... primary-expression     (     expression ... primary-expression, id-expression, unqualified-id       identifier     ) and unary-expression   sizeof   (   type-id ... simple-type-specifier, type-name, typedef-name     identifier   ) Similar ambiguities arise for the other type-names that can be identifiers, I want to understand how this maps to the standard. [edit] To clarify: I'm very well able to disambiguate identifiers for a type-name according to how they were declared (typedef, class, etc.) - however I currently do not see how id-expression (or its contained unqualified-id) disambiguates when another parse may match a type-id. As brought up in the comments various rules exist for specific cases to disambiguate expressions vs. type-ids, but I don't yet see how they extend to this specific case (unless you extrapolate and assume type-id always wins over expressions, which has been suggested as a possible reading of the disambiguation rules in the comments). [end edit] My idea was to look for any constraints on what identifier can be an id-expression, but I can't find anything specific, the closest to a constraint I can see is the very unhelpful phrasing in 5.1.1/8 An identifier is an id-expression provided it has been suitably declared (Clause 7 [dcl.dcl]). Looking at the mentioned section I couldn't find what it means to refer to and on the web I've only found this question but the answer doesn't go into details beyond The phrase's intention is to disallow the usage of undeclared identifiers in expressions. So either this is resolved differently than I'm thinking, or there must be more meaning to "suitably declared" that I'm missing. PS: using the C++14 standard has no particular reason, its just what I've been working with at the time, answers for a newer standard are just as fine. Checking the mentioned sections in the newer standards myself didn't seem to have any obvious clarifications. A: This is the lexer hack: whether an identifier is an unqualified-id, a type-name, or a template-name is determined based on declarations that have already been processed or on the typename and template parser guides in dependent contexts. This is the only way to distinguish, say, the interpretations of A * b; as a simple-declaration of a pointer or as an expression-statement that discards the result of a multiplication. The standard is very vague about this: it merely mentions the interpretation of an identifier that appears in a declaration in places like [class.pre]/1: Its name becomes a class-name ([class.name]) within its scope. [temp.param]/3: A type-parameter whose identifier does not follow an ellipsis defines its identifier to be a typedef-name (if declared without template) or template-name (if declared with template) in the scope of the template declaration. [temp.local]/1, where it’s also dependent on syntax: The injected-class-name can be used as a template-name or a type-name. and [temp.names]/3, where it is part of a note because the normative text specifies the interpretation of a <: [Note 1: If the name is an identifier, it is then interpreted as a template-name. […] — end note]
doc_23530702
Can this be achieved using the Coordinator layout or I need to do my own hack? layout.xml: <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ececec"> <android.support.v7.widget.RecyclerView android:id="@+id/discoverRView" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="5dp" android:paddingRight="5dp"> </android.support.v7.widget.RecyclerView> <LinearLayout android:layout_width="match_parent" android:layout_height="100dp" android:background="#f00" app:layout_anchor="@+id/discoverRView" app:layout_anchorGravity="top" app:layout_scrollFlags="scroll" > </LinearLayout> </android.support.design.widget.CoordinatorLayout> A: Maybe there are better solutions, but this can be achieved by creating a custom CoordinatorLayout.Behavior and adding it to a CustomLinearLayout: //This is taken from a project of mine, it scrolls a Layout up if a snackbar shows up. public class MoveUpwardBehavior extends CoordinatorLayout.Behavior<View> { public MoveUpwardBehavior(){ //super(); } public MoveUpwardBehavior(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) { float translationY = Math.min(0, dependency.getTranslationY() - dependency.getHeight()); child.setTranslationY(translationY); return true; } @Override public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) { return dependency instanceof Snackbar.SnackbarLayout; } @Override public void onDependentViewRemoved(CoordinatorLayout parent, View child, View dependency) { super.onDependentViewRemoved(parent, child, dependency); child.setTranslationY(0); } } You'll need a custom LinearLayout, but this part is easy peasy: @CoordinatorLayout.DefaultBehavior(MoveUpwardBehavior.class) public class CustomLinearLayout extends LinearLayout { public CustomLinearLayout(Context context) { super(context); } public CustomLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); } public CustomLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public CustomLinearLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } } Surely, you'll need to use this layout in your xml: <com.your.project.CustomLinearLayout android:layout_width="match_parent" android:layout_height="100dp" android:background="#f00" app:layout_anchor="@+id/discoverRView" app:layout_anchorGravity="top"> </com.your.project.CustomLinearLayout> So, I think you get the idea. You'll need to update the behaviour to depend on the scroll of your RecyclerView. If you need more help, I can try to build a working example.
doc_23530703
Let's use the example in the documentation: library(tables) tab <- tabular( (Species + 1) ~ (n=1) + Format(digits=2)* (Sepal.Length + Sepal.Width)*(mean + sd), data=iris ) tab # Sepal.Length Sepal.Width # Species n mean sd mean sd # setosa 50 5.01 0.35 3.43 0.38 # versicolor 50 5.94 0.52 2.77 0.31 # virginica 50 6.59 0.64 2.97 0.32 # All 150 5.84 0.83 3.06 0.44 Then, using latex(tab) from the Hmisc package, one could convert the table object to LaTex, producing the following output: Is it possible to insert a \midrule above the All row to obtain the following table? A: I gues you could edit the latex directly: ltab <- Hmisc::latex(tab) ltab$text <- gsub("\nAll", "\n\\\\hline\nAll", ltab$text) Now ltab gives the following output:
doc_23530704
I am not sure if I am missing any configuration or if I am issuing the command from the wrong directory. My question is how do I ensure that "no specs found" error does not happen? I ran the command in /angular-phonecat/app directory as: npm run protractor The folder structure of the project is as follows: angular-phonecat |_____app |_____app.js |_____app.spec.js |_____index.html |_____e2e-tests |_____protractor.conf.js This is the content of app.spec.js: 'use strict'; describe('PhoneListController', function() { beforeEach(module('phonecatApp')); it('should create a `phones` model with 3 phones', inject(function($controller) { var scope = {}; var ctrl = $controller('PhoneListController', {$scope: scope}); expect(scope.phones.length).toBe(3); })); }); Protractor.conf.js is as follows: //jshint strict: false exports.config = { allScriptsTimeout: 11000, specs: [ '*.js' ], capabilities: { 'browserName': 'chrome' }, baseUrl: 'http://localhost:8000/', framework: 'jasmine', jasmineNodeOpts: { defaultTimeoutInterval: 30000 } }; A: End-to-end (e2e) tests, which are run with Protractor, are only intorduced on step 5. So, trying to run the tests in earlier step, will result in "no specs found" errors (as expected). You might be confused by the unit tests, which are introduced in earlier steps. These are different kinds of tests and are run with a different test runner (i.e. Karma, not Protractor).
doc_23530705
I use CSS ::selection , like below css *::selection { -webkit-appearance: none; outline: none; } But when you go to the lowermost part of the page, and select to the top, <p> and <img> cannot be selected, - this is correct, but to the right of all images "space" still appear in selection color! How can I disable or make transparent all images side selection color ? (I don't want selection background-color to white ,need transparent) DEMO A: Wrap the IMG tags in a tag like <p> too and the colour disappears <p> dnksdnsdnjvf ffm in ifn ifn ifn ifn ifn ifn ifn ifn ifn ifn ifn ifn ifn ifn ifn ifn ifn ifn ifn ifn fi nfijvdjfvv fv fnj vfjv fjv fjv fjnvfj jnf fj </p> <p><img src="http://thumb1.shutterstock.com/thumb_small/260389/212829874/stock-photo-green-tea-in-wooden-spoon-and-lemon-slice-212829874.jpg"></p> A: You can try something like this ::selection { background-color: rgba(0, 0, 0, 0.5); } body { background-image: url(http://www.homelogy.net/wp-content/uploads/2015/04/linen-1.jpg); } select this text click on Run Code Snippet and select the text you can replace the 0s with the rgb value. the last value, alpha, is the transparency, 1 = solid | 0 = transparent rgba stands for red-green-blue-alpha. You can search online for a hex to rgb converter to convert the #00bbaa colors to something like 200, 500, 300.
doc_23530706
I use 3 different servers to collect some data from the web. I want to insert all these data to a common DB. Is there any way I can do it in mongoDB? A: mongodb is a database server program. So you install a single server program (on one machine) and let your three applications access it as a client (each) thru TCP/IP. Don't have three mongodb servers sharing the same shared disk partition or remote network file system (à la NFS). (the server word has two different meanings: server programs and server machines; I am using it for server programs)
doc_23530707
container.AddFacility<WcfFacility>(); container.Register(Component.For<IServiceFactory>() .ImplementedBy<ServiceFactory>() .LifestyleSingleton()); container.Register(Component.For<IFooService>() .UsingFactoryMethod((kernel, context) => kernel.Resolve<IServiceFactory>() .CreateService(context.RequestedType)) .Named("FooService") .LifestylePerWcfOperation()); Here is my factory class: public class ServiceFactory : IServiceFactory { public IFooService CreateService(Type forType) { IFooService createdType = null; if (forType == typeof(IFooService)) createdType = new FooService(); return createdType; } } I have tried doing a strait .ImplementedBy<FooService>() and that works fine. It's only when I want to do it via a factory that I have a problem. Is this possible, meaning I'm missing something, or is it not possible? (I know that the code shown is pretty simple, I am only testing if its possible before fully implementing my factory code) A: you don't have to create a custom ServiceHost to do this, though you're right this is harder than it should be. The article that eouw0o83hf references first talks about an IInstanceProvider. That's the key, but you can wire it up using and WCF ServiceBehavior as well instead of a customer ServiceHost. I'm not sure what your FactoryMethod has to do with this - it sounds like it's a general wire up issue... or I'm not understanding your problem. I'll show below how I do the wire up without the ServiceHost and hopefully that fixes your problem. First create a class that implements IInstanceProvider - mine below calls out to my ObjectResolver class with wraps Windsor. I'll leave that out for brevity. using System; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; public class ObjectResolverInstanceProvider : IInstanceProvider { private readonly Type _serviceType; public ObjectResolverInstanceProvider(Type serviceType) { _serviceType = serviceType; } public object GetInstance(InstanceContext instanceContext) { return ObjectResolver.Resolve(_serviceType); } public object GetInstance(InstanceContext instanceContext, Message message) { return ObjectResolver.Resolve(_serviceType); } public void ReleaseInstance(InstanceContext instanceContext, object instance) { ObjectResolver.Release(instance); } } Then create a service behavior that assigns your instance provider to each endpoint's DispatchRuntime's InstanceProvider: using System; using System.Collections.ObjectModel; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Dispatcher; public class ConstructWithObjectResolverAttribute : Attribute, IServiceBehavior { public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { foreach (ChannelDispatcherBase cdb in serviceHostBase.ChannelDispatchers) { ChannelDispatcher cd = cdb as ChannelDispatcher; if (cd != null) { foreach (EndpointDispatcher ed in cd.Endpoints) { ed.DispatchRuntime.InstanceProvider = new ObjectResolverInstanceProvider(serviceDescription.ServiceType); } } } } public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters) { } public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { } } Next apply the service attribute to your service implementation... note you could do this in config if you wanted too, but I prefer applying it via an attribute like so: [ConstructWithObjectResolver] [ServiceBehavior(Namespace="YourNamespace")] public class FooService : IFooService {}
doc_23530708
Essentially my data structure (in this case an NSArray) might contain several NSDictionary instances at any given time, each one having the same keys, potentially different values. Some values repeat. I'd like to be able to know how many times a particular key/value appears. Example: { foo => 1, bar => 2 } { foo => 1, bar => 3 } { foo => 2, bar => 1 } In this case I'm interested that foo=>1 occured 2 times and foo=>2 occured 1 time. Is building an instance of NSCountedSet the best way to go about this? Perhaps a C linked-list? A: You may want to rethink how you are structuring your data. I'd track something like this while adding to the NSArray instead of trying to discover it at a later time. You might create a new class to handle adding and removing the data so that you can keep your own counts of the data. A: NSDictionary * dict1 = [[NSDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithInt:1], @"foo", [NSNumber numberWithInt:2], @"bar", nil]; NSDictionary * dict2 = [[NSDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithInt:1], @"foo", [NSNumber numberWithInt:3], @"bar", nil]; NSDictionary * dict3 = [[NSDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithInt:2], @"foo", [NSNumber numberWithInt:1], @"bar", nil]; NSArray * arrayOfDictionaries = [[NSArray alloc] initWithObjects: dict1, dict2, dict3, nil]; // count all keys in an array of dictionaries (arrayOfDictionaries): NSMutableDictionary * countKeys = [[NSMutableDictionary alloc] initWithCapacity:0]; NSCountedSet * counts = [[NSCountedSet alloc] initWithCapacity:0]; NSArray * keys; NSString * pairString; NSString * countKey; for (NSDictionary * dictionary in arrayOfDictionaries) { keys = [dictionary allKeys]; for (NSString * key in keys) { pairString = [NSString stringWithFormat:@"%@->%@", key, [dictionary valueForKey:key]]; if ([countKeys valueForKey:pairString] == nil) { [countKeys setValue:[NSString stringWithString:pairString] forKey:pairString]; } countKey = [countKeys valueForKey:pairString]; { [counts addObject:countKey]; } } } NSLog(@"%@", counts); [counts release]; [countKeys release]; [arrayOfDictionaries release]; [dict1 release]; [dict2 release]; [dict3 release]; A: NSCountedSet *keyCounts = [NSCountedSet set]; for (NSDictionary *dict in myDictionaries) [keyCounts unionSet:[NSSet setWithArray:[dict allKeys]]];
doc_23530709
Thus I am trying to extract the Json strings sent by different requests. The problem is that the tool provided by the browser (it is practically the same for both FF and Chrome) gives me the Json in a structured form. And I need to use it as strings. To rewrite all large and deeply structured strings from more than a hundred of requests manually is a horror. How can I copypaste the string representation of request parameters? A: I have found that in Chrome - near the "request payload" header there is a switch: view source <-> view parsed. The first variant shows the Json string. BTW, IE has buttons for that and FF... has nothing? A: In Firefox: Right click > Copy > Copy POST Data. You can also "Copy All As HAR" to get the raw body (of every request and response in the list), and "Edit and Resend" will show you the raw body in the UI.
doc_23530710
Map class uses the Cell class as vertices and Cell class uses a separate CellProperty class for setting and getting all the Cell properties. And finally Map class where I build the graph and try to write the graph into a DOT file. Map.h class Map { public: typedef boost::adjacency_list<boost::listS, boost::vecS, boost::undirectedS, Cell> Graph; typedef boost::graph_traits<Graph>::vertex_descriptor Vertex; explicit Map(std::string pGraphFilePath); virtual ~Map(); void LoadGraph(); private: Graph mGraph; std::vector<std::vector<Vertex>> mGrid; }; Map.cpp const unsigned int RowNum = 3; const unsigned int ColumnNum = 4; Map::Map(std::string pGraphFilePath) : mGraph(), mGrid() {} Map::~Map() {} void Map::LoadGraph() { int dummyID = 1; for (unsigned int row = 0; row < RowNum; row++) { mGrid.resize(RowNum); for (unsigned int col = 0; col < ColumnNum; col++) { mGrid[row].resize(ColumnNum); Vertex vID = boost::add_vertex(mGraph); mGraph[vID].SetProperty<unsigned int>("ID", dummyID); mGraph[vID].SetProperty<bool>("Navigable", true); mGrid[row][col] = vID; dummyID++; // add the edges for the contained cells in the grid if (col > 0) { boost::add_edge(mGrid[row][col - 1], mGrid[row][col], mGraph); } if (row > 0) { boost::add_edge(mGrid[row - 1][col], mGrid[row][col], mGraph); } } } // write cell properties boost::dynamic_properties propertiesOutPut; propertiesOutPut.property("ID", boost::get(boost::vertex_index, mGraph)); // As Navigable is an external property, it need to be mapped with the internal graph property // the lines below are the update after I got the answers and link for my query // cell.GetProperty() is a templated method the takes a default parameter, thus passing "false" bool parameter which returns the "Navigable" cell property auto valueNavigable = boost::make_transform_value_property_map([](Cell &cell) { return cell.GetProperty<bool>("Navigable", false); }, boost::get(boost::vertex_bundle, mGraph)); propertiesOutPut.property("Navigable", valueNavigable); std::ofstream fout("MyGraph.dot"); boost::write_graphviz_dp(fout, mGraph, propertiesOutPut, std::string("ID")); } The problem I am getting is with the propertiesOutPut.property() method for boost::get(). I can not figure out the correct parameters for boost::get(). Please help me out. Thanks !! A: You could use a transform_value_property_map on top of the propertymap that contains the vertex properties struct. (You didn't show it). I have a number of answers showing how to do that, although these are all using internal properties, there is no big difference because anu property map can be transformed in the same way, regardless of whether the property map is internal or external (that's the whole purpose of property maps: decoupling the way properties are accessed). Most relevant: * *Overloading streaming operators for a Boost Graph bundle output for GraphViz *Manually colouring of boost's graphs Other: * *see these search results: https://stackoverflow.com/search?tab=votes&q=user%3a85371%20make_transform_value_property_map
doc_23530711
var reader: FileReader = new FileReader(); reader.readAsArrayBuffer(file); reader.onloadend = function (e) { var fileContent = reader.result; ... } I need to get the content as byte array but I can't do it. If I try to convert in this way: var byteArray = new Int8Array(fileContent); I get this error: impossible to assign string to ArrayBuffer | ArrayLike | SharedArrayBuffer. Is fileContent a string? I think it should be an ArrayBuffer because I'm using readAsArrayBuffer. Is there a way to get byte array from uploaded file? Thanks A: You need to add type assertion var byteArray = new Int8Array(fileContent as ArrayBuffer);
doc_23530712
Everything works except the part where I am trying to save the image as a bitmap. I keep getting null. I can however populate my ImageView with the line ivTroopPhoto.setImageURI(result.getUri()); If anyone has used this API an can help me out with this issue. protected void onActivityResult(int requestCode, int resultCode, Intent data) { if ((requestCode == PIC_FROM_CAMERA) || (requestCode == PIC_FROM_GALLERY)) { if (resultCode == RESULT_OK) { Uri picUri = data.getData(); CropImage.activity(picUri) .setGuidelines(CropImageView.Guidelines.ON) .setFixAspectRatio(true) .setAspectRatio(1, 1) .start(this); } } if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { CropImage.ActivityResult result = CropImage.getActivityResult(data); if (resultCode == RESULT_OK) { ibCameraIcon.setVisibility(View.GONE); ivTroopPhoto.setVisibility(View.VISIBLE); ivTroopPhoto.setImageURI(result.getUri()); tvTroopPhoto.setText(R.string.change_photo); Log.d("dozer74", "==============================> Image Uri: " + result.getUri().getPath()); //Uri imageUir = data.getData(); try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), result.getUri()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); byte[] byteArray = byteArrayOutputStream .toByteArray(); String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT); Log.d("dozer74", "==========> Encoded Base64 Image: " + encoded); } catch (IOException e) { e.printStackTrace(); } } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) { Toast.makeText(this, String.format("Cropping failed: %s", result.getError()), Toast.LENGTH_LONG).show(); } } } A: I was able to work it out. I used the api's imageview and was able to get the image as a bitmap.
doc_23530713
Fatal error: Call to undefined function getactualeventid() This function is defined in my file functions.php and i include it on the top of my index.php file by following line: include '.\functions.php'; The file functions.php is in the same directory as my index.php. Are there settings on the server that I need to change? //EDIT In the beginning I used include 'functions.php'; but only a blank page has been loaded, so I tried it with include '.\functions.php'; and then I got at least a clear error message. I also tried include_once but it doesn't work. I tested the whole stuff on my localhost by using XAMPP where it runs without any problems. I still don't know what the problem is. A: First, the syntax should be: include('functions.php'); But I would recommend using include_once instead of include to avoid scenarios where your script might inadvertently attempt to load the same file more than once. include_once('functions.php'); But I would also encourage you to use a base path of some sort to prefix the location of the file so you are not constantly juggling relative locations. For example, in your main config file, you can define a base path like this: $BASE_PATH = '/the/path/to/the/codebase/'; Then when you do an include_once, the syntax would be: include_once($BASE_PATH . 'functions.php'); The benefit of this is no matter how deeply nested your codebase becomes, you will always be anchored to the value of $BASE_PATH. And your life will be made tons easier thanks to not having to worry about relative path issues. A: try this include('functions.php'); A: include 'functions.php'; And check your functions. A: you can also used require_once(youFileName.php). A: Use include 'functions.php' as your functions.php is on the same directory level where your index.php is , use include '../functions.php' if it is one level before index.php. Hope this helps.
doc_23530714
For example when load 2 elements or divs the movement very bad not fluid, i don´t know if howewer understand want to say For example i create this simple div for move with function dragabble : function win_move(idw) { jQuery(".wd_"+idw).draggable(); } And the result it´s move the div right, but in one moment go well and in other moment impossible move across screen Exists other plugin for do this function, or howewer it´s problem from plugin of jquery UI, or need some change o add something more for get the movement will be more fluid https://jsfiddle.net/gbd8fe3m/6/ Thank´s in advanced
doc_23530715
For example, public interface IEmployee { IAddress Address { get; set; } IAddress GetAddress(); void SetAddress(IAddress address); } public class Employee : IEmployee { // Complex production stuff here (causes DB access) } public class TestEmployee : IEmployee { // Simple unit testing stuff goes here (in memory only) } public static class EmployeeExtensions { public static IAddress GetAddress(this IEmployee employee) { // Some sort of magic (maybe using IOC) // 'employee' can be either of type 'Employee' or of type 'TestEmployee' } public static void SetAddress(this IEmployee employee, IAddress address) { // Again with the magic } } Ok, maybe not a great example but you get the idea... The key is that GetAddress and SetAddress can be called against both Employee and TestEmployee without code support from either of them. Unfortunately, this feels a little more like Java than C#. What I would really love to do for both is to work directly with the Address property and have it do all the same magic that the methods do. What I want to avoid is having to write code in the concrete classes to do it (especially in TestEmployee). Is there any way to provide default implementations for the Address property of IEmployee? I know that C# properties are actually methods under the hood. Anyway of providing implementations for those somehow? Could it be done in a different .NET language? A: As you already found out, you cannot add properties through extension methods. If it's a matter of easing the tests, you could use a mocking framework like Moq to avoid having to implement those properties on each class that inherits from the interface. A: There are a variety of ways to do this, I suppose. As suggested you may look at just creating a hierarchy so that these types of functions are handled by the base class. You may, however, be interested in a code-generation solution using T4 Templates (from Microsoft).
doc_23530716
<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> from my AndroidManifest.xml when I use gradle to build my APK. According to the website https://developers.google.com/android/guides/setup only when I choose "ECLIPSE WITH ADT" I have to add this line. For "ANDROID STUDIO" usage this is not mentioned. But in my case I use Eclipse (with ADT) as IDE but I build with gradle. (Actually it is a libGDX project). So I added the play-services by using gradle: compile "com.google.android.gms:play-services:8.1.0" So I run the app on a test device and I tested to login with play-services and it worked fine without having the line above in my AndroidManifest.xml But, maybe the login just does not need the "com.google.android.gms.version" value and another part of the play services lib needs it? But I cannot test all the possible ways to use the lib. Does anybody know for sure? Or for those of you who use Android Studio + play services: Does your AndroidManifest.xml have the line above? A: Yes, as of Google Play services 7.0 (improved in 7.5 to remove the restriction on applying to the full play-services dependency), the <meta-data> tag is automatically added to your Manifest file by Gradle via Manifest merging.
doc_23530717
Visitors of that website even they are not using my software can publish their own ads too. I want to combine that functions but don't know how to use two different auto-increment order. I'm not sure that's the best idea but i'm thinking this: when a website visitor entered an ad, id should be end with "1" and if that ad came from software user id should be and with "0". Is there a way to do that ?
doc_23530718
Client periodically sends a new request to my server asking for the playlist file. For example once in 10 seconds. I need to identify each client at server side. My first attempt is using cookies. It works pretty well if the client does support cookies. But I need to be able to identify all clients even though they don't support cookies. Can I create a session without using cookies but using only -for example- IP and header data? If so, how can I do that? Requirements: * *The URL which client consumes can not change. Client can not add any parameters to it and client can not do anything except requesting the playlist file. *One single request to the server should be enough to identify a user. *All requests should serve enough data to be known by server. I'm currently using express-session. I assume I can get what I want with creating a middleware like express-session. But I'm not sure how exactly I can do it. A: Try to use evercookie Or this one. It uses Etag (though, evercookie also uses etag as one of its approaches, but this one specifically uses it.) cookieless cookie A: user1551066's recommendation is pretty solid answer (great find!) But please keep in mind there's a point of diminishing returns when you get into edge-cases. If you simply displayed an error saying cookies are required, would that acceptable for a v1.0? Evercookie and cookieless cookie would likely handle most of the other situations... but have ways of being thwarted. Evercookie can be stopped by using private browsing. Cookieless cookie's approach can be defeated with privacy plugins that change the values used to create the fingerprint. These storage attempts might also be considered invasive by the happy path users (who do have cookies enabled). From a professional standpoint, I'd recommend focusing on the happy path first and just displaying an error for folks that have cookies disabled. Once you get your code up and running, then you can revisit the experience those folks have.
doc_23530719
Objects a and b are dummy objects showing the format of my data, where a and b represent distinct quadrats. Object df shows the format of my objective, although it is here generated manually. "abund" represents abundance, and associated numbers are percent cover values. Objects spA through spI represent nine dummy plant species names, of which five are present in quadrat a and seven are present in quadrat b. > a.names <- c("spA","spB","spC","spD","spE") > a <- t(data.frame(c(40,20,10,10,10), row.names = a.names)) > row.names(a) <- "a.abund" > a spA spB spC spD spE a.abund 40 20 10 10 10 > > b.names <- c("spC","spD","spE","spF","spG","spH","spI") > b <- t(data.frame(c(40,10,10,10,10,10,10), row.names = b.names)) > row.names(b) <- "b.abund" > b spC spD spE spF spG spH spI b.abund 40 10 10 10 10 10 10 > > df.names <- c("spA","spB","spC","spD","spE","spF","spG","spH","spI") > a.abund <- c(40,20,10,10,10,0,0,0,0) > b.abund <- c(0,0,40,10,10,10,10,10,10) > ( df <- t(data.frame(a.abund, b.abund, row.names = df.names)) ) spA spB spC spD spE spF spG spH spI a.abund 40 20 10 10 10 0 0 0 0 b.abund 0 0 40 10 10 10 10 10 10 A: If we convert the matrices to data.frame first, we can use rbindlist from the data.table package: a.names <- c("spA","spB","spC","spD","spE") a <- t(data.frame(c(40,20,10,10,10), row.names = a.names)) row.names(a) <- "a.abund" a b.names <- c("spC","spD","spE","spF","spG","spH","spI") b <- t(data.frame(c(40,10,10,10,10,10,10), row.names = b.names)) row.names(b) <- "b.abund" b a <- as.data.frame(a) b <- as.data.frame(b) df <- rbindlist(list(a, b), fill = TRUE) df > df spA spB spC spD spE spF spG spH spI 1: 40 20 10 10 10 NA NA NA NA 2: NA NA 40 10 10 10 10 10 10 A: Using base R nms <- union(colnames(a) , colnames(b)) ans <- matrix(0, nrow = 2, ncol = length(nms)) colnames(ans) <- nms d <- list(a,b) for( i in 1:2){ ans[i , match(colnames(d[[i]]) , colnames(ans))] <- d[[i]] } * *output > ans spA spB spC spD spE spF spG spH spI [1,] 40 20 10 10 10 0 0 0 0 [2,] 0 0 40 10 10 10 10 10 10
doc_23530720
This following code produces a form upon button press, the form has checkboxes and a richtextbox. Ideally I want any interaction to have an effect, so if I paste in a grid of ones and zeros the checkboxes update, and once a checkbox gets click, the corresponding one or zero in the textarea will update (So that I can then copy the grid (matrix) out and into another program. I know how to get the events using the visual studio GUI maker, but not from a programmatically created form like this. private void begin_button_Click(object sender, EventArgs e) { // Build the child form Form check_box = new Form(); check_box.FormBorderStyle = FormBorderStyle.FixedSingle; // Get the values from the textboxes int height = Convert.ToInt16(this.height_input.Text); int width = Convert.ToInt16(this.width_input.Text); // Set the dimensions of the form check_box.Width = width * 15 + 40; check_box.Height = ( height * 15 + 40 ) * 3; // Build checkboxes for the checkbox form CheckBox[] chk; chk = new CheckBox[height * width]; int count = 0; for (int i = 1; i <= height; i++) { for (int j = 1; j <= width; j++) { chk[count] = new CheckBox(); chk[count].Name = count.ToString(); chk[count].Width = 15; // because the default is 100px for text chk[count].Height = 15; chk[count].Location = new Point(j * 15, i * 15); chk[count].CheckedChanged += new EventHandler(this.CheckedChanged); check_box.Controls.Add(chk[count]); count += 1; //Console.WriteLine(" i: " + i + " j: " + j + " Count: " + count); } } RichTextBox output_area; output_area = new RichTextBox(); output_area.Location = new Point(chk[0].Location.X, chk[count-1].Location.Y + 30); check_box.Controls.Add(output_area); output_area.Text = "hello world\n1,1,1,1,1,1,1,1,1\n0,0,0,0,0,1,0,1\nthese ones and zeros are meant to update in real time!"; output_area.Width = check_box.Width - 40; output_area.Height = check_box.Height / 2; // Run the form check_box.ShowDialog(); } EDIT: I have added the event handler and it's working, however I can't access the checkbox form, only the main form. private void CheckedChanged(object sender, EventArgs e) { //throw new NotImplementedException(); CheckBox x = (CheckBox)sender; Console.WriteLine(x); Console.WriteLine(x.Name.ToString()); } A: Have a look at the .Designer file that the form designer generates for you! Anyway, in your loop, try something like this: chk[count].CheckedChanged += MyFancyHandler; And the handler itself will look just like a normal handler: private void MyFancyHandler( object sender, EventArgs e ) { // ... } Also notice that the sender argument there will contain a reference to whichever checkbox/control the event refers to. A: Below code updates matrix text in the rich text box when check box check state changed. RichTextBox output_area; CheckBox[] chk; Size MatrixSize; private void begin_button_Click() { // Build the child form Form check_box = new Form(); check_box.FormBorderStyle = FormBorderStyle.FixedSingle; check_box.StartPosition = FormStartPosition.CenterScreen; // Get the values from the textboxes int height = Convert.ToInt16("10"); int width = Convert.ToInt16("7"); MatrixSize = new Size(width, height); // Set the dimensions of the form check_box.Width = width * 15 + 40; check_box.Height = (height * 15 + 40) * 3; // Build checkboxes for the checkbox form chk = new CheckBox[height * width]; int count = 0; for (int i = 1; i <= height; i++) { for (int j = 1; j <= width; j++) { chk[count] = new CheckBox(); chk[count].Name = count.ToString(); chk[count].Width = 15; // because the default is 100px for text chk[count].Height = 15; chk[count].Location = new Point(j * 15, i * 15); check_box.Controls.Add(chk[count]); chk[count].CheckedChanged += new EventHandler(CheckBox1_CheckedChanged); count += 1; //Console.WriteLine(" i: " + i + " j: " + j + " Count: " + count); } } output_area = new RichTextBox(); output_area.Location = new Point(chk[0].Location.X, chk[count - 1].Location.Y + 30); check_box.Controls.Add(output_area); output_area.Text = "hello world\n1,1,1,1,1,1,1,1,1\n0,0,0,0,0,1,0,1\nthese ones and zeros are meant to update in real time!"; output_area.Width = check_box.Width - 40; output_area.Height = check_box.Height / 2; // Run the form check_box.ShowDialog(); } private void CheckBox1_CheckedChanged(Object sender, EventArgs e) { CheckBox c = (CheckBox)sender; Debug.WriteLine(c.Name); StringBuilder sb = new StringBuilder(); int count = 0; for (int i = 1; i <= MatrixSize.Height; i++) { for (int j = 1; j <= MatrixSize.Width; j++) { if (chk[count].Checked) { sb.Append("1,"); } else { sb.Append("0,"); } count += 1; } sb.Append("\r\n"); } output_area.Text = sb.ToString(); }
doc_23530721
A: I'm not entirely sure what you mean by the "data structure" of a class, but assuming you mean the members it contains, what you're looking for is reflection. Try this tutorial. A: Maybe you are missing the point: If you build a class which encapsulates some kind of internal data then you should NOT add a method which returns the internal data structure, but only the data that is encapsulated. (Which is kind of the idea of encapsulation) There should not be any need to "rearrange" your internal representation from the outside - because it is supposed to be internal and thus transparent in its use. (Meaning: You should not even be able to say what kind of data structure is used) A: If you serialize it, any object (that is serializable) will happily prints its internal structure to a binary stream. And yes, this breaks encapsulation. And yes, no one stops you from going to change the binary output and read it in again to create an altered object.   NB: there are more strange issues regarding serialization. For example, when deserializing objects new objects are created without their constructor ever being called. Et cetera. Serialization of objects is the maybe least object-oriented thing one can do with objects. A: You're mixing up some concepts here. Classes really are "data structures + methods", so in general you'd need a class to represent your class. Hey, a nice custom-built one would be the class your data is already in. You may be thinking of a class as a collection of simple fields, but this is not always the case. As others have mentioned, you can extract the data via reflection, e.g. public Map<String,Object> fields() { Map output=new hashMap<String,Object>(); for (Field f:getClass().getFields()) { try{ output.put(f.getName(), f.get(this)); } catch(... //IllegalArgument, IllegalAccess.. {... } } return output; } You can get into encapsulation issues here, in general the class should provide the data that you need to see from it, I tend to use things like this only for debugging. I'm not sure what you mean by "rearrange the structure". The class generally represents the structure of the data. If there's a transformation you want to accomplish, it probably belongs in a class method, e.g. are you thinking of something like a co-ordinates class that can provide a transformed version of itself into polar co-ordinates? A: A simple way to see the internal representation of an object is to serialise it using XStream. This will generate an XML representation of the class and its components (and so on). Does this break encapsulation ? Yes - in the sense that you're able to inspect the internal structure of the class. You can take that XML, change it, and provided that it matches the .class structure that it came from, deserialise it back into a .class instance.
doc_23530722
fig_dims = (15, 8) fig, ax = plt.subplots(figsize=fig_dims) sns_plot =sns.lineplot( x="xaxis", y=map_rows, marker='o', data = return_doc,dashes= False ) sns_plot.set_xticks(range(len(yx))) sns_plot.set_xticklabels(x ,rotation=90) ax.set_title('Word frequency') sns_plot.set(xlabel="Words", ylabel = "frequency") fig = sns_plot.get_figure() I am getting this error. Error occurred in action: Convert To Table, Aborting... Traceback (most recent call last): File "/home/shahid/.config/language-factory-ide/Transformation/Output/Convert To Table/script.py", line 146, in plt.plot([1, 2, 3, 4], [1, 4, 9, 16]) File "/home/shahid/Desktop/LF/pipeline-builder-ide/python/install/lib/python3.7/site-packages/matplotlib/pyplot.py", line 2761, in plot return gca().plot( File "/home/shahid/Desktop/LF/pipeline-builder-ide/python/install/lib/python3.7/site-packages/matplotlib/pyplot.py", line 879, in gca return gcf().gca(**kwargs) File "/home/shahid/Desktop/LF/pipeline-builder-ide/python/install/lib/python3.7/site-packages/matplotlib/pyplot.py", line 611, in gcf return figure() File "/home/shahid/Desktop/LF/pipeline-builder-ide/python/install/lib/python3.7/site-packages/matplotlib/pyplot.py", line 546, in figure **kwargs) File "/home/shahid/Desktop/LF/pipeline-builder-ide/python/install/lib/python3.7/site-packages/matplotlib/backend_bases.py", line 3337, in new_figure_manager return cls.new_figure_manager_given_figure(num, fig) File "/home/shahid/Desktop/LF/pipeline-builder-ide/python/install/lib/python3.7/site-packages/matplotlib/backends/_backend_tk.py", line 876, in new_figure_manager_given_figure window = tk.Tk(className="matplotlib") File "/home/shahid/Desktop/LF/pipeline-builder-ide/python/install/lib/python3.7/tkinter/init.py", line 2023, in init self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use) _tkinter.TclError: Can't find a usable init.tcl in the following directories: /tools/deps/lib/tcl8.6 /home/shahid/Desktop/LF/pipeline-builder-ide/python/install/lib/tcl8.6 /home/shahid/Desktop/LF/pipeline-builder-ide/python/lib/tcl8.6 /home/shahid/Desktop/LF/pipeline-builder-ide/python/install/library /home/shahid/Desktop/LF/pipeline-builder-ide/python/library /home/shahid/Desktop/LF/pipeline-builder-ide/python/tcl8.6.9/library /home/shahid/Desktop/LF/pipeline-builder-ide/tcl8.6.9/library This probably means that Tcl wasn't installed properly. I have tried uninstalling and installing tcl and tkinter. nothing seems to be working.
doc_23530723
.map(new Function<List<Post>, List<Post>>() { @Override public List<Post> apply(List<Post> posts) throws Exception { return realm.where(Post.class).equalTo(DatabaseContract.PostTable.USER_ID, userId).findAll(); } }) .onErrorResumeNext(new Function<Throwable, ObservableSource<? extends List<Post>>>() { @Override public ObservableSource<? extends List<Post>> apply(Throwable throwable) throws Exception { Log.d("rafael", throwable.getMessage()); return getLocalPostsObservable(userId, page); } }) Using lambda expression (converted using Intellij feature) it becomes: .map((Function<List<Post>, List<Post>>) posts -> realm.where(Post.class).equalTo(DatabaseContract.PostTable.USER_ID, userId).findAll()) .onErrorResumeNext(throwable -> { Log.d("rafael", throwable.getMessage()); return getLocalPostsObservable(userId, page); }) What I don't understand that why the type casting in map() from posts to Function<List<Post>, List<Post>> in (Function<List<Post>, List<Post>>) posts -> realm.where(Post.class).equalTo(DatabaseContract.PostTable.USER_ID, userId).findAll() Where at the same time there's no type casting in the second expression: throwable -> { Log.d("rafael", throwable.getMessage()); return getLocalPostsObservable(userId, page); } A: What's the return type of findAll()? I'd bet on a List<Post>, according to the return type of the Function<S, T>. My guess is that the cast to Function<S, T> is applied to the whole lambda expression, not only to the posts parameter nor its return value. As for the reason of its presence, it might be to avoid an ambiguous call of map(FunctionLike<S, T>); otherwise, it wouldn't be the first time that a code generation tool adds some useless stuff around. A: It's not the posts that is casted, but the entire lambda expression and because it does not fail compilation we can deduce that posts is actually of type List<Post> and findAll is also returning List<Post>. Could it be because of chaining methods like: where(..).equalTo(..).findAll(..) You can test if this is the case by taking that code inside a method that returns List<Post> and inside your lambda expression use that method instead. If intelli does not add a cast - the problem is there.
doc_23530724
That will teach me to stick to my initial gut response... T. I am tasked with creating a document uploading robot. The intention is to automate uploading member owned documents to an IIS-based web server. I am implementing this using PhantomJS. The issue I have run into is that the URL I'm supposed to be redirected to after logging in results in a 404 error unless the login comes from Internet Explorer. I have set the User Agent to Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0). What else can I do to convince IIS that PhantomJS is really Internet Explorer? A: I don't know how to get you the specific answer to your problem but there are some things you need to consider and test. It does not matter what browser you use. User Agents (browser) and servers communicate via HTTP. This means headers, request body, etc are the way things are identified. The User Agent string is NOT used by the server (IIS) to turn functionality on or off. What you need to do is record the request/response dialog between the user agent (Internet Explorer in your case) and see exactly what those headers look like. Then do the same for Phantom, Chrome and any other user agent you can test against. See what the headers, status codes, etc are and see what is different. Then make sure those values are supplied from PhantomJS. My guess is there is some sort of authentication credential being passed in IE that is not being defined in Phantom. ** Also note, MSFT started deprecating IE 18 months ago. It is only 'alive' for legacy enterprise web sites. So you may want to move on for any new web projects and set the minimum to the latest browser versions and one back. :)
doc_23530725
in the context of computing a picture in order to send a binary bitmap to some hardware that only knows a 1-bit depth of display, I am using the BitSet for the first time and I get some disappointing results: while populating the Bitset in a loop via the set(int bitIndex, boolean value) method, the resulting ByteArray has not always the same size, which does not suit the hardware that always expect the same 1024 bytes payload. Here is s SSCCCE that illustrates my problem, the result is when I am trying to set a bit at 0, the structure does not grow. On real data I often get arrays way below the expected 1024 (e.g. 592). What I am missing? 8192 iterations pixels has size of 1024 8192 iterations pixels has size of 0 <== WTF?! 8192 iterations pixels has size of 0 <== WTF?! import java.util.BitSet; public class TestBitset { public static void main(String[] args){ BitSet bs = new BitSet(); int c = 0; for (int band = 0; band <= 7; band++) { for (int x = 0; x <= 127; x++) { for (int bit = 0; bit <= 7; bit++) { boolean val = true; bs.set(band * 128 * 8 + x * 8 + bit, val); c++; } } } System.out.println(c + " iterations"); byte[] pixels = bs.toByteArray(); System.out.println("pixels has size of " + pixels.length); //-------------------------------------------------------- bs = new BitSet(); c = 0; for (int band = 0; band <= 7; band++) { for (int x = 0; x <= 127; x++) { for (int bit = 0; bit <= 7; bit++) { boolean val = false; bs.set(band * 128 * 8 + x * 8 + bit, val); c++; } } } System.out.println(c + " iterations"); pixels = bs.toByteArray(); System.out.println("pixels has size of " + pixels.length); //-------------------------------------------------------- bs = new BitSet(8192); c = 0; for (int band = 0; band <= 7; band++) { for (int x = 0; x <= 127; x++) { for (int bit = 0; bit <= 7; bit++) { boolean val = false /*bit % 7 == 1*/; bs.set(band * 128 * 8 + x * 8 + bit, val); c++; } } } System.out.println(c + " iterations"); pixels = bs.toByteArray(); System.out.println("pixels has size of " + pixels.length); } } A: Quoting the Javadoc of Bitset#toByteArray() for a BitSet s: Returns a new byte array containing all the bits in this bit set. More precisely, if byte[] bytes = s.toByteArray(); then bytes.length == (s.length()+7)/8 Note that BitSet#length() is documented as Returns the "logical size" of this BitSet: the index of the highest set bit in the BitSet plus one. Returns zero if the BitSet contains no set bits. Now, as all bits in loop 2 and 3 were initialized as false, s.length() = 0 and bytes.length will thus evaluate to 0+7/8 = 0 (int). Therefore, the observed length of the byte[] in loop 2 and 3 is correct.
doc_23530726
I want to Mask an Image with complex shape and need drag and crop functionalities for the Image inside complex shape like below example. but i need it in react js. https://jsbin.com/hawiricaqu/1/edit?js,output. So far i have tried using Group with "globalCompositeOperation" it is workign fine with single image but in loop masking is applying for all layers. <Group> <Image image={image} onClick={onClick} onTap={onClick} ref={imageRef} x={shapeProps.xcor} y={shapeProps.ycor} {...shapeProps} draggable onTransform={handleResize} onDragStart={(event) => { dispatch(handlePropertiesModal(false)); clearSelection(); }} onDragEnd={(e) => { onChange({ ...shapeProps, xcor: e.target.x(), ycor: e.target.y(), }); dispatch(handlePropertiesModal(true)); }} onTransformstart={() => dispatch(handlePropertiesModal(false))} onTransformend={() => dispatch(handlePropertiesModal(true))} filters={shapeProps.filters} /> {shapeProps?.mask_image && ( <Group ref={templateUpperRef} globalCompositeOperation="destination-in"> <Image image={base} onClick={onClick} onTap={onClick} x={shapeProps.xcor} y={shapeProps.ycor} {...shapeProps} /> </Group> )} {transformer} </Group>
doc_23530727
For a string like: The cat ate the dog and the mouse The expression should find cat and So far, I have: /\b\w*a\w*\b/g However this will return every match in each line, not just the first match (cat ate and). What is the easiest way to only return the first occurrence? A: Assuming you are onluy looking for words without numbers and underscores (\w would include those), I'd advise to maybe use: (?i)^.*?(?<!\S)([b-z]*a[a-z]*)(?!\S) And use whatever is in the 1st capture group. See an online demo. Or, if supported: (?i)^.*?\K(?<!\S)[b-z]*a[a-z]*(?!\S) See an online demo. Please note that I used lookaround to assert that the word is not inbetween anything other than whitespace characters. You may also use word-boundaries if you please and swap those lookarounds for \b. Also, depending on your application you can probably scratch the inline case-insensitive switch to a 'flag'. For example, if you happen to use JavaScript /^.*?(?<!\S)([b-z]*a[a-z]*)(?!\S)/gmi should probably be your option. See for example: var myString = "The cat ate the dog\nand the mouse"; var myRegexp = new RegExp("^.*?(?<!\S)([b-z]*a[a-z]*)(?!\S)", "gmi"); m = myRegexp.exec(myString); while (m != null) { console.log(m[1]) m = myRegexp.exec(myString); } A: If you want to match a word using \w you might also use a negated character class matching any character except a or a newline. Then match a word that consists of at least an a char with word boundaries \b ^[^a\n\r]*\b([^\Wa]*a\w*) The pattern matches: * *^ Start of string *[^a\n\r]*\b Optionally match any character except a or a newline *( Capture group 1 * *[^\Wa]*a\w* Optionally match a word character without a, then match a and optional word characters *) Close group 1 Regex demo Using whitespace boundaries on the left and right: ^[^a\n\r]*(?<!\S)([^\Wa]*a\w*)(?!\S) Regex demo A: The text could be matched with the regular expression (?=(\b[a-z]*a[a-z]*\b)).*\r?\n with the multiline and case-indifferent flags set. For each match capture group 1 contains the first word (comprised only of letters) in a line that contains an "a". There are no matches in lines that do not contain an "a". Demo The expression can be broken down as follows. (?= # begin a positive lookahead \b # match a word boundary ([a-z]*a[a-z]*) # match a word containing an "a" and save to # capture group 1 ) .*\r?\n # match the remainder of the line including the # line terminator
doc_23530728
public void friend_finder(){ try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://fifauz.com/selectall.php"); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); Log.e("log_tag", "connection success "); Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show(); } catch(Exception e){ Log.e("log_tag", "Error in http connection "+e.toString()); Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show(); } //convert response to string try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); Intent i = new Intent(getBaseContext(),MainActivity.class); startActivity(i); } is.close(); result=sb.toString(); } catch(Exception e) { Log.e("log_tag", "Error converting result "+e.toString()); } try { JSONArray jArray = new JSONArray(result); for(int i=0;i<jArray.length();i++){ JSONObject json_data = jArray.getJSONObject(i); String name = json_data.getString("Name"); //Double lati = json_data.getDouble("latitude"); // Double longi = json_data.getDouble("longitude"); String lati = json_data.getString("Lati"); String longi = json_data.getString("Long"); String s = name + lati + longi; double lati_d = Double.valueOf(lati.trim()).doubleValue(); double longi_d = Double.valueOf(longi.trim()).doubleValue(); Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show(); ListOverlay listOverlay = new ListOverlay(); GeoPoint currentLocation = new GeoPoint(lati_d,longi_d); //String marker; //String m = marker + String.valueOf(i); Marker marker = createMarker(R.drawable.person, currentLocation); List<OverlayItem> overlayItems = listOverlay.getOverlayItems(); overlayItems.add(marker); mapView.getOverlays().add(listOverlay); } } catch (Exception e) { Log.e("log_tag", "Error converting result "+e.toString()); } { // TODO: handle exception } } private Marker createMarker(int resourceIdentifier, GeoPoint geoPoint) { Drawable drawable = getResources().getDrawable(resourceIdentifier); return new Marker(geoPoint, Marker.boundCenterBottom(drawable)); } A: You can add marker in mapsforge map this way also. private void createPositionMarker(double paramDouble1, double paramDouble2) final LatLong localLatLong = new LatLong(paramDouble1, paramDouble2); TappableMarker positionmarker = new TappableMarker(R.drawable.destination, localLatLong); mapView.getLayerManager().getLayers().add(positionmarker); } private class TappableMarker extends Marker{ public TappableMarker(int icon, LatLong localLatLong) { super(localLatLong,AndroidGraphicFactory.convertToBitmap(MainActivity.this.getApplicationContext().getResources().getDrawable(icon)), 1*(AndroidGraphicFactory.convertToBitmap(MainActivity.this.getApplicationContext().getResources().getDrawable(icon)).getWidth())/2, -1*(AndroidGraphicFactory.convertToBitmap(MainActivity.this.getApplicationContext().getResources().getDrawable(icon)).getHeight())/2); } }
doc_23530729
Could someone with experience in this area, offer me examples of unit tests I could carry out on this model (in android) to get me started? - I'm referring to JUnit Testing via Google Android Testing Creating functions to JUnit test utilising(extending) TestCases (junit.framework) etc code for Contact model: public class Contact extends MainModel { private Long id; private String personName; private String phoneNumber; private String occupation; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getPersonName() { return personName; } public void setPersonName(String personName) { this.personName = personName; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getOccupation() { return occupation; } public void setOccupation(String occupation) { this.occupation = occupation; } } A: Been looking into similar junit tests in Android lately, this should defiantly get you started. It should explain how to test the getting and setting public class SurveyTest extends TestCase { private Survey survey; protected void setUp() throws Exception { super.setUp(); survey = new Survey(); } public void testSurvey() { survey.toString(); } public void testSurveyLongString() { fail("Not yet implemented"); } public void testGetId() { long expected = (long) Math.random(); survey.setId(expected); long actual = survey.getId(); Assert.assertEquals(expected, actual); } public void testGetTitle() { String expected = "surveytitle"; survey.setTitle(expected); String actual = survey.getTitle(); Assert.assertEquals(expected, actual); } public void testIsActive() { Boolean expected = true; survey.setActive(expected); Boolean actual = survey.isActive(); Assert.assertEquals(expected, actual); } public void testGetQuestions() { fail("Not yet implemented"); } } A: The only reasonable way that I've found to write unit tests for classes that don't depend on the Android libraries (Activities, Context, etc.) is to install Robolectric. Then, since Robolectric is based on JUnit, in addition to Robolectric tests, which do typically involve Context and friends, you have the infrastructure in place to support simple, non-Android JUnit tests.
doc_23530730
A: Another possibility is to use the VerifyVersionInfo function, which returns the correct result even if your application doesn't have the corresponding manifest file mentioned by user844541. Example: BOOL CompareWindowsVersion(DWORD dwMajorVersion, DWORD dwMinorVersion) { OSVERSIONINFOEX ver; DWORDLONG dwlConditionMask = 0; ZeroMemory(&ver, sizeof(OSVERSIONINFOEX)); ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); ver.dwMajorVersion = dwMajorVersion; ver.dwMinorVersion = dwMinorVersion; VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_EQUAL); VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_EQUAL); return VerifyVersionInfo(&ver, VER_MAJORVERSION | VER_MINORVERSION, dwlConditionMask); } Usage: if(CompareWindowsVersion(6, 3)) { // Windows 8.1 } A: Use ntdll!RtlGetVersion. This is what both GetVersionEx and VerifyVersionInfo use, and it gives the correct version number. It takes a pointer to an OSVersionInfoExW structure, like GetVersionExW does. If it succeeds, it returns STATUS_SUCCESS (0). A: Take a look at this article: Operating system version changes in Windows 8.1 Preview GetVersion(Ex) APIs have been deprecated. That means that while you can still call the APIs, if your app does not specifically target Windows 8.1 Preview, you will get Windows 8 versioning (6.2.0.0). What it says is that GetVersion lies to you about the real OS version unless you explicitly direct 8.1 in your manifest. You need to add the following to the app manifest: <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"> <application> * <!-- Windows 8.1 --> * <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/> <!-- Windows Vista --> <supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/> <!-- Windows 7 --> <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/> <!-- Windows 8 --> <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/> </application> </compatibility> If you don't want to do that you can check the following registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion Current version will give you 6.3 Current build nmber will be 9431 A: I'm not sure that you will want to go this deep but it is easily possibly to get exact operating system version through a simple WMI query call as described below. I've mentioned a method which you can plug directly in your code to get the exact operating system version. Required namespaces to be imported for this C# code snippet have been mentioned just above the function : using System; using System.Management; private string GetOsVersion() { var sccmManagementScope = new ManagementScope(@"\\" + System.Environment.MachineName + @"\root\cimv2"); var searchResult = new ManagementObjectSearcher(sccmManagementScope, new WqlObjectQuery("SELECT Version FROM Win32_OperatingSystem")); var resultSet = searchResult.Get(); var osVersion = string.Empty; foreach (ManagementObject managementObject in resultSet) { osVersion = Convert.ToString(managementObject["Version"]); } return osVersion; } Though I still strongly believe that System.Environment.OSVersion.Version should be able to meet most of your needs unless you have something very specific in regards to target Windows 8.1. In fact I used the same trick for one of requirements as System.Environment class actually lies about the OS version if your application is not manifested for Windows 8.1 operating system.
doc_23530731
# Load library library(ggplot2) # Convert to factors mtcars$gear <- factor(mtcars$gear) mtcars$cyl <- factor(mtcars$cyl) # Plot results p <- ggplot(data = mtcars, aes(x=gear, fill=cyl) ) + geom_bar() print(p) which gives, In this plot, each group (i.e., cyl) is a different colour and all bars are the same colour scheme. Now, what I'd like to do is have each bar as a single, different colour, but the groups are designated by alpha. For example, bars for gear values of 3, 4, and 5 may be red, blue, and green, respectively, and cyl values are depicted by alpha values of 1, 0.75, and 0.5, respectively. This way the bar for, say, gear equals 3 is all the same colour (red), but the cyls are shown as different shades. Is this possible? The code below implements the alpha values: # Function for adding alphas alpha_bar <- function(x)ifelse(x == 4, 1, ifelse(x == 6, 0.75, ifelse(x == 8, 0.5, NA))) # Add alphas mtcars$alpha <- alpha_bar(mtcars$cyl) # Plot results p <- ggplot(data = mtcars, aes(x=gear, fill=cyl, alpha = alpha) ) + geom_bar() print(p) This gets the alpha values correct. However, if I try to change the colours of each bar using something like this, p <- p + scale_fill_manual(values = c("red", "blue", "green")) it changes the colours of the cyl values rather than gear values. Any suggestions? A: Map both attributes: p <- ggplot(data = mtcars, aes(x=gear, alpha=cyl, fill=gear) ) + geom_bar() + scale_fill_manual(values = c("#CD3700", "#9ACD32", "#00868B")) p Keep in mind that mapping alpha values this way is considered to be bad visualizing of data. Why? Just look at the guide for cyl.
doc_23530732
The random numbers are generated in the add card component. I feel like I'm super close, but I can't figure out what I'm missing. const sortTypes = { up: { class: "sort-up", fn: (a, b) => a.number - b.number, }, down: { class: "sort-down", fn: (a, b) => b.number - a.number, }, default: { class: "sort", fn: (a, b) => a, }, }; const sortAll = () => { state = { currentSort: 'default' }; onSortChange = () => { const { currentSort } = this.state; let nextSort; if (currentSort === 'down') nextSort = 'up'; else if (currentSort === 'up') nextSort = 'default'; else if (currentSort === 'default') nextSort = 'down'; this.setState({ currentSort: nextSort }); }; }; return ( <body> <header> <div className="ui buttons"> <button type="button" onClick={addCard} className="ui button mb-1 mt-1 mr-1"><i className="plus icon"></i>Add Card</button> <div className="or mb-1 mt-1"></div> <button type="button" onClick={sortAll} className="ui positive button mb-1 mt-1 mr-1"><i className="redo icon"></i>Sort All</button> </div> </header> A: Issues * *Functional components are "instanceless" so there is no defined this to reference. *onSortChange is the button onClick handler you want to use to update the current sort. Solution * *Move the currentSort to component state in a useState hook. const [currentSort, setCurrentSort] = useState("default"); *Fix the onSortChange handler to correctly update state. const onSortChange = () => { let nextSort; if (currentSort === "down") nextSort = "up"; else if (currentSort === "up") nextSort = "default"; else if (currentSort === "default") nextSort = "down"; setCurrentSort(nextSort); }; *Use an in-line "sort" in the render return. Remember that array.prototype.sort is an in-place sort, i.e. it mutates the array. To get around accidentally mutating state first copy the array. {cards .slice() // <-- copy .sort(sortTypes[currentSort].fn) // <-- select sort function .map((cardNumber, index) => ( <MainCard number={cardNumber.number} key={cardNumber.id} onRemove={() => removeCard(cardNumber.id)} /> ))} *Attach correct handler to button <button type="button" onClick={onSortChange} className="ui positive button mb-1 mt-1 mr-1" > <i className="redo icon"></i>Sort All </button> Demo Full Code: const generateId = (seed = 0) => () => seed++; const getRandomNumber = function (min, max) { let getRandom = Math.floor(Math.random() * max + min); return getRandom; }; const sortTypes = { up: { class: "sort-up", fn: (a, b) => a.number - b.number }, down: { class: "sort-down", fn: (a, b) => b.number - a.number }, default: { class: "sort", fn: (a, b) => a } }; const MainCard = ({ number, onRemove }) => { return ( <div className="card"> <button onClick={onRemove} className="ui mini red basic icon button" style={{ position: "absolute", top: "0", right: "0" }} > X </button> {number} </div> ); }; export default function App() { const [cards, setCards] = useState([]); const [currentSort, setCurrentSort] = useState("default"); const addCard = () => { setCards((cards) => [ ...cards, { id: generateId(), number: getRandomNumber(0, 101) } ]); }; const removeCard = (id) => { setCards((cards) => cards.filter((el) => el.id !== id)); }; const onSortChange = () => { let nextSort; if (currentSort === "down") nextSort = "up"; else if (currentSort === "up") nextSort = "default"; else if (currentSort === "default") nextSort = "down"; setCurrentSort(nextSort); }; return ( <body> <header> <div className="ui buttons"> <button type="button" onClick={addCard} className="ui button mb-1 mt-1 mr-1" > <i className="plus icon"></i>Add Card </button> <div className="or mb-1 mt-1"></div> <button type="button" onClick={onSortChange} className="ui positive button mb-1 mt-1 mr-1" > <i className="redo icon"></i>Sort All </button> </div> </header> <div className="card-container"> {cards .slice() .sort(sortTypes[currentSort].fn) .map((cardNumber) => ( <MainCard number={cardNumber.number} key={cardNumber.id} onRemove={() => removeCard(cardNumber.id)} /> ))} </div> <aside className="showHide"></aside> <footer> <h3 className="text-center text-muted">Footer</h3> </footer> </body> ); }
doc_23530733
* *Userform pops up *Item from listbox is double clicked in the form. *That opens another workbook and runs code on each sheet. * *(This is done in another function and works perfectly and takes about 15 seconds ending with the focus on the new workbook.) *Closes the userform. (This causes it to hang from 7 seconds to 90 seconds depending on the other workbooks size.) Code below (please excuse the improper format, I had to use my phone... can't login via computer.) Private sub lb_blah_DblClick (Byval Cancel as MSForms.ReturnBoolean) Me.lbl_blah2.caption = "opening aND running" 'Open and edit xls - Works fine. LoadAndFormat me.lb_blah.value Me.lbl_blah2.caption = "Ran through format." Me.repaint '90 seconds with 29 sheets 'Me.hide 'Application.enableevents = false '70 seconds Unload me '90 seconds - 29 sheets End Sub A: I restarted my computer, and that seemed to fix it. I'm sorry.
doc_23530734
I've created project on chatting over LAN in java i want to implement video chatting and voice calling between two clients... ... please help me that how can i stream the video in Java? what library's should i use . . or any site from there i get information plz. A: The Java Media Framework provides functionality for networked video chatting.
doc_23530735
How do I let the user input the image that they want to be searched? This is what I have so far: client.on("message", (message) => { let args = message.content.substring(prefix.length).split(" "); switch (args[0]) { case "dog": image(message); break; } }); function image(message) { var options = { url: "http://results.dogpile.com/serp?qc=images&q=" + "dog", method: "GET", headers: { Accept: "text/html", "User-Agent": "Chrome", }, }; request(options, function (error, response, responseBody) { if (error) { return; } $ = cheerio.load(responseBody); var links = $(".image a.link"); var urls = new Array(links.length).fill(0).map((v, i) => links.eq(i).attr("href")); console.log(urls); if (!urls.length) { return; } // Send result message.channel.send(urls[Math.floor(Math.random() * urls.length)]); }); } A: Your current code is on the right track to doing what you want. You simply need to properly use your args variable. The Problem(s) First of all, you need to separate your args from your command. The code you provided in your question currently counts the command itself ("image") as the first arg and "dog" as the second arg, whereas "dog" is supposed to be the first argument of the command. So we need to separate the command from the args, and we can do so easily with Array.shift() which removes the first element of an array and returns it. In your current code, you have a switch statement that checks the value of the first arg in the message (args[0]), and if the first arg is "dog", you are searching for dog images. But what you want to do is you want to be able to search for more than just dogs, for whatever image the user wants. That means you'll first need to get rid of the argument-checking switch, because as it is now it will only allow users to search for "dog". Next, you need to realize that you want to search for an image of whatever the user puts in. So what's the value that the user is putting in? It's contained in args[0]. So if you want to be able to search for whatever args[0] is, instead of doing "http://results.dogpile.com/serp?qc=images&q=" + "dog" you need to instead do "http://results.dogpile.com/serp?qc=images&q=" + args[0]. In order to do that, you'll also need to give your image method access to args[0], which you can do by passing it in as an argument of the method. The Solution So here's how these simple fixes will look in your code: client.on("message", (message) => { let args = message.content.substring(prefix.length).split(" "); let command = args.shift(); //separates and removes command from args switch (command) { case "image": image(message, args[0]); break; } }); function image(message, query) { //'query' now represents 'args[0]' var options = { url: "http://results.dogpile.com/serp?qc=images&q=" + query, method: "GET", headers: { Accept: "text/html", "User-Agent": "Chrome", }, }; request(options, function (error, response, responseBody) { if (error) { return; } $ = cheerio.load(responseBody); var links = $(".image a.link"); var urls = new Array(links.length).fill(0).map((v, i) => links.eq(i).attr("href")); console.log(urls); if (!urls.length) { return; } // Send result message.channel.send(urls[Math.floor(Math.random() * urls.length)]); }); } However, note that this will only take the first argument and search for it (it will not include spaces). So if you did !image furry cats, it would only look up images of "furry" and not "furry cats". If you want to account for spaces, then use all of the args instead of just args[0]. You could do so by replacing all occurrences of args[0] in this code with args.join(" "). Let me know if I misunderstood your question. This answer is solely based off of the somewhat limited information you provided in your question and comment.
doc_23530736
A: There is no notion of inserting new variables into LLVM IR. The source language and LLVM IR are simply two different languages, and you should rather see the compilation as a translation step. Conceptually, it would be difficult to come up with a precise definition when a variable belongs to the original program or not. Consider for example this small C function: void test() { int i; i = 2; i = 3; } Compiling this function to LLVM IR would result in at least two variables (if no constant folding is applied) since of SSA form. Which one would be the original one, and which one inserted? This also gets complicated, when control flow and phi functions are involved: int a = 1; int b = 2; int c = 3; int func() { int result; if (a) { result = b; } else { result = c; } return result; } When translating this C function to LLVM IR and applying the -mem2reg pass we get the following: define i32 @func() #0 { %1 = load i32* @a, align 4 %2 = icmp ne i32 %1, 0 br i1 %2, label %3, label %5 ; <label>:3 ; preds = %0 %4 = load i32* @b, align 4 br label %7 ; <label>:5 ; preds = %0 %6 = load i32* @c, align 4 br label %7 ; <label>:7 ; preds = %5, %3 %result.0 = phi i32 [ %4, %3 ], [ %6, %5 ] ret i32 %result.0 } As you see, the virtual register name of result does not show up at the stage of assignment. It is only visible at the merge point. Here, the original place of the variable assignment was moved towards the end of the function. Again, it is questionable which variables got inserted, and which ones didn't. What you could do is to compile the original program with debug metadata and then process the debug information to find out variable declarations etc. In Clang you can output the debug information with the -g flag.
doc_23530737
My question is: Does MoonMail have any dashboard or I need to make the page to consume the APIs? A: If you're looking for a frontend package to interact with the MoonMail backend, here's what you're looking for. If your question is related to the "commercial" tool, you should contact support so they can give your API key to interact with your MoonMail data.
doc_23530738
Below is my code: this.cluster = new Cluster(this, 'Cluster', { vpc: props.vpc }); this.cluster.addCapacity('DefaultAutoScalingGroupCapacity', { instanceType: InstanceType.of(InstanceClass.R5D, InstanceSize.XLARGE24), minCapacity: 2, maxCapacity: 50, }); this.service = new ApplicationLoadBalancedEc2Service(this, 'Service', { cluster: props.ecsCluster, memoryLimitMiB: 768000, taskImageOptions: { containerPort: 8080, image: new ContainerImage({ package: Package.fromString('ECSMatching'), transformPackage: Package.fromString('ECSMatchingImage'), componentName: 'service', }), taskRole: getDefaultEcsTaskInstanceRole(this), environment: {'STAGE': props.stage} }, }); this.service.service.connections.allowFrom( Peer.ipv4(props.ecsCluster.vpc.vpcCidrBlock), Port.allTraffic(), 'Local VPC Access' ); this.service.targetGroup.setAttribute('deregistration_delay.timeout_seconds', '6000');
doc_23530739
Every time I click on "New Query", Management Studio stops then restarts. My laptop is running Windows 8.1 A: In SQL Server Management Studio (SSMS) try short-cut key CTRL+N to open a new query window.
doc_23530740
A: You should start writing simple dll's (you can also write simple aplication to load and execute dll's procedures). Next step is to program better dll's (mor functionality etc.). There is a plenty of tutorials on this matters. And then you should read api documentation for application you're writing plugin to (for winamp check this site: http://dev.winamp.com/plugin-developers)
doc_23530741
Min: 10xFalsePositive + 500xFalse Negative I wrote the following custom loss function: def custom_loss_func(y_train, y_pred): cm=metrics.confusion_matrix(y_train,y_pred) cm1 = pd.DataFrame(cm.reshape((1,4)), columns=['TN', 'FP', 'FN', 'TP']) cm1 = cm1.fillna(0) TC= 10*cm1.FP + 500*cm1.FN return float (TC) # Compiling the ANN ann.compile(optimizer = 'adam', loss = my_loss_fn, metrics = ['accuracy']) # Fitting the ANN to the Training set ann.fit(x_train,y_train,batch_size=32,epochs = 50, class_weight= class_weights) When I run the code I get the following error: NotImplementedError: Cannot convert a symbolic tf.Tensor (my_loss_fn/strided_slice:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported. I also tried a native Tensorflow implementation: def my_loss_fn(y_train, y_pred): FP = tf.keras.metrics.FalsePositives() FP.update_state(y_train, y_pred) FP=m.result().numpy() FN = tf.keras.metrics.FalseNegatives() FN.update_state(y_train, y_pred) FN=n.result().numpy() # Converted as Keras Tensors FP = tf.Variable(m) FN = tf.Variable(n) loss = 500*FN + 10*FP return loss This one gave me the follwing error: ValueError(f"No gradients provided for any variable: {variable}. " f"Provided `grads_and_vars` is {grads_and_vars}.") if vars_with_empty_grads: logging.warning( ("Gradients do not exist for variables %s when minimizing the loss. " "If you're using `model.compile()`, did you forget to provide a `loss`" "argument?"), ([v.name for v in vars_with_empty_grads])) Could anyone give me some help on this problem?
doc_23530742
I tried.... [code here] C9 - RETURN [STRING HERE] ...but it doesn't seem LD has a way to get relative data. So I can't even get the address location after C9. Any tips? A: Does this help? Strings Strings are just lots of characters put together in consecutive order. However, it is important to identify the beginning/ends of strings. So, here's how it's done: Null-Terminating Strings Strings that have a null term, or 0 at the end. .DB "String Data",0 Pre-determined Length Strings Strings where the first byte is the length of the string. .DB 11,"String Data" As you are doing things with strings, this also looks useful for null terminated strings. A: You can't store 5 ASCII characters ("hello") in a 2-byte register, which HL is. The only thing you can do is store these 5 characters somewhere in the memory and load HL with the address of this string (effectively, the address of its first character "h"). EDIT: If you need to find the location of your subroutine while it's executing, you can read the return address from the stack and then minimally disassemble the instruction just before the return address. If it's CALL (cc,) nn or JP (cc,) nn, the subroutine's address is encoded in the instruction's two last bytes. If it's JP (HL/IX/IY), the address is in the register (HL, IX or IY) used for the indirect jump. To be able to recover this address, you'll have to save these registers' values in your subroutine (using e.g. PUSH). If it's RET (cc), the address was on the stack when your subroutine started, but it may since have been overwritten by your routine's activities or that of the interrupt service routines. This is a tough case, but I hope it's not RET. You can't disassemble the instruction blindly and reliably at the same time because different instructions have different lengths and what you may recognize as JP (HL) can in fact be just a part of a longer CALL nn. But the code that invokes your subroutine is unlikely to change and chances are there's only one place or one method of invocation, which means that once you know the instruction that's used to invoke your subroutine, you don't need to guess anything anymore, just write your code assuming it's always that instruction. Using the above technique, you can use the layout you suggested in the question: [code here] C9 - RETURN [STRING HERE] You just need to recover the subroutine's address and add to it the subroutine's size. That'll be the address of the string. A: TI-83+/84+ I guess? Programs start at a fixed address, $9D95, so you can manually add the offset to that and use the absolute address.
doc_23530743
I found two "mistakes" on sentence: #if ((8 != sizeof(timer_reg_t)) * *Michael is using a sizeof(), executed at compilation time, on a preprocessor instruction, so far I know it won't ever works, indeed I got the message: error: missing binary operator before token "(" Am I missing something? *The second issue is a missing')'; I think it is only a mistyping error. The complete rule is here: 5.5 Structures and Unions Rules: a. Appropriate care shall be taken to prevent the compiler from inserting padding bytes within struct or union types used to communicate to or from a peripheral or over a bus or network to another processor. b. Appropriate care shall be taken to prevent the compiler from altering the intended order of the bits within bit-fields. Example: typedef struct { uint16_t count; // offset 0 uint16_t max_count; // offset 2 uint16_t _unused; // offset 4 uint16_t enable : 2; // offset 6 bits 15-14 uint16_t b_interrupt : 1; // offset 6 bit 13 uint16_t _unused1 : 7; // offset 6 bits 12-6 uint16_t b_complete : 1; // offset 6 bit 5 uint16_t _unused2 : 4; // offset 6 bits 4-1 uint16_t b_periodic : 1; // offset 6 bit 0 } timer_reg_t; // Preprocessor check of timer register layout byte count. #if ((8 != sizeof(timer_reg_t)) # error “timer_reg_t struct size incorrect (expected 8 bytes)” #endif A: You cannot evaluate the sizeof inside the preprocessor. It is evaluated by the compiler. You can simply check like this and should be fine as 8. #include <stdint.h> #include <stdio.h> typedef struct { uint16_t count; // offset 0 uint16_t max_count; // offset 2 uint16_t _unused; // offset 4 uint16_t enable : 2; // offset 6 bits 15-14 uint16_t b_interrupt : 1; // offset 6 bit 13 uint16_t _unused1 : 7; // offset 6 bits 12-6 uint16_t b_complete : 1; // offset 6 bit 5 uint16_t _unused2 : 4; // offset 6 bits 4-1 uint16_t b_periodic : 1; // offset 6 bit 0 } timer_reg_t; int main(){ printf("%d \n", sizeof(timer_reg_t)); return 0; } It will print 8. If you want to see the compile time verification, you can use a static_assert (from <assert.h>) as well: static_assert(sizeof(timer_reg_t) == 8, "sizeof(timer_reg_t) != 8"); A: You are correct on both counts. The line you quoted from the book Embedded C Coding Standard by Michael Barr ] has exactly the problems that you have identified. Your first concern for the line #if ((8 != sizeof(timer_reg_t)) (maintaining original line which is missing a closing parenthesis) is a serious one. Just as you indicated, the sizeof would be evaluated at compile time, i.e. post pre-processing time. Not only is the value not available then, pre-processor directives have already been processed and are gone at the time sizeof could be given a value. In fact, as long as neither sizeof or timer_reg_t have not been #define'd as symbolic constants, the preprocessor will see each of them as 0, effectively giving you #if ((8 != 0(0)) which is neither functional nor resembles the actual intent. The answers to this post as well as amirhm's answer here show ways that the goal of Michael Barr in that section of his book can be achieved. Your second concern, that of a missing ')', is also valid. I would classify it as a minor typo that would need to be fixed, but not of great consequence.
doc_23530744
I am getting this error: Uncaught SyntaxError: Unexpected identifier This small script is causing it :( Are there any errors in it? Thanks <script language="javascript"> document.onmousedown=disableclick; status="Right Click Disabled"; Function disableclick(event) { if(event.button==2) { alert(status); return false; } } </script> A: Here is the correct code below: document.onmousedown=disableclick; var status="Right Click Disabled"; function disableclick(event) { if(event.button==2) { alert(status); return false; } } WORKING DEMO
doc_23530745
The problem is that I can't display the buttons on the screen when running the program and can't make them works And I Don't know how implement the buttons inside of the user interface when using polygon Here is my code:- package java2d; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Java2D extends JFrame{ int xValues[]; int yValues[]; private JButton Right, Left; public Java2D() { super( "Drawing lines, rectangles and ovals" ); setSize( 500, 300 ); setVisible( true ); } public void paint( Graphics g ) { int xValues[] = { 40, 100, 130, 230, 260, 320, 320, 40 }; int yValues[] = { 120, 120, 40, 40, 120, 120, 170, 170 }; Polygon polygon1 = new Polygon( xValues, yValues, 8 ); g.setColor(Color.blue); g.drawPolygon( polygon1 ); Right = new JButton("Right"); Left = new JButton("Left"); Right.setSize(50, 50); Left.setSize(50, 50); Right.setLocation(100, 200); Left.setLocation(200, 200); g.add(Right); g.add(Left); } public void actionPerformed(ActionEvent event) { if(event.getActionCommand().equals("Right")){ for (int i=0; i<xValues.length;i++) { xValues[i] = xValues[i] + 10; yValues[i] = yValues[i] + 10; } } if(event.getActionCommand().equals("Left")){ for (int i=0; i<xValues.length;i++) { xValues[i] = xValues[i] + 10; yValues[i] = yValues[i] + 10; } } repaint(); } public static void main(String[] args) { Java2D application = new Java2D(); application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } } THANKS A: Many issues: * *Variable names should NOT start with an upper case character. *Custom painting is done by overriding the paintComponent() method of a JPanel and then you add the panel to the frame. Read the section from the Swing tutorial on Custom Painting for more information and working examples to get you started. Start with the working code and modify it for your requirement. *Never create Swing components in a painting method. The painting method is continually invoked when Swing determines the component needs to be repainted, so you don't want to keep creating new buttons. *Typically to add buttons to the frame you would create a JPanel and add the buttons to the panel. Then you add the panel to the frame using frame.add(buttonsPanel, BorderLayout.PAGE_START). Then you would add your painting panel to the frame using frame.add(paintingPanel, BorderLayout.CENTER). Read the section from the Swing tutorial on Layout Managers for more information and examples. *Instead of attempting to update the values of the Arrays used to create the Polygon you should be using the translate() method of the Polygon. Keep a reference to the Swing tutorial handy as it contains examples for most Swing basics.
doc_23530746
Branch getBranch(long branchId) { String query = "select distinct bran.branch.branchId,bran.branch.branchName from Location bran where bran.branch.branchId =:branchId"; Session session = getSession(); session.beginTransaction(); Query buildQuery = getSession().createQuery(query).setParameter("branchId", branchId); List<Object[]> countryList = buildQuery.list(); Branch branch = null; for(Object[] obj : countryList) { branch = new Branch((Long)obj[0] , (String)obj[1]); } session.close(); return branch; } But here I have to construct the object manually which i don't want. I want to read the result in object form and i dont want manual construction of object. My entity is like this public final class Location implements Comparable<Location>{ @Id @Column(name = Tables.LOCATION.LOCATION_ID, nullable = false, precision = 15, scale = 0, updatable = false, insertable = false) private long locationId; @Column(name = Tables.LOCATION.LOCATION_NAME, length = 60, updatable = false, insertable = false) private String locationName; @Embedded private Country country; @Embedded private Branch branch; Branch does not map to an entity whereas it is embeddable. I want to read the data in form of DTO so i have gone through ResultTransformer class but it workd only with sqlQuery not with HQL(Correct me if i am wrong). I cant change my query .Please help me A: Hibernate can do this for you by using the new keyword (called dynamic instantiation/constructor expression) in the HQL: Just change your query to: select new your.package.name.Branch(bran.branch.branchId,bran.branch.branchName) from Location bran where bran.branch.branchId =:branchId
doc_23530747
from tkinter import * root = Tk() root.title("TicTacToe") root.resizable(width=False, height=False) def button1(): print("Button1 Pressed!") background = Canvas(width="500", height="500", bg="#9EADC8", cursor="circle") background.pack() #line = <thing>.create_line(100, 100, 150, 500) boardimage = PhotoImage(file="TikTacToe.png") background.create_image(250, 250, image=boardimage,) button1 = Button(background, width="13", height="6", borderwidth=0, command=button1) button1.place(relx=0.18, rely=0.18) root.mainloop() So, I want it to have the button on top, but the canvas behind it to be visible, so it wont be a white button, and so when I display a X/O image then it will show through the button, but still have the button be able to be pressed and have the X/O image behind change. so how can I make the button completly invisible but interactable?
doc_23530748
`id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `user_type` varchar(20) NOT NULL, `first_name` varchar(25) NOT NULL, `last_name` varchar(25) NOT NULL, `email` varchar(30) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ; My login system is OK. It's working.. I have three 'user_type' 1.admin 2.supar admin 3.user I need , if login into admin & supar admin or user. its redirect three different view. A: Ok. Check the following steps and you may change it. Signin controller public function signin() { //Assume this is your session details after successful login check $data = array ( 'member_user_id' => $row['id'], 'member_username' => $username, 'member_usertype' => $row['user_type'], 'member_logged_in' => TRUE ); $this->session->set_userdata($data); switch($row['user_type']){ case 'user': redirect('user/dashboard'); break; case 'admin': redirect('admin/dashboard'); break; case 'super_admin': redirect('super_admin/dashboard'); break; } } And, you can validate the session in required controller method based on user type. so that user can not view admin or super admin pages vice versa. User Details Controller public function user_details(){ if ($this->CI->session->userdata('member_usertype') != 'user'){ redirect('login'); } //implementation code here } Admin Details Controller public function admin_details(){ if ($this->CI->session->userdata('member_usertype') != 'admin'){ redirect('login'); } //implementation code here } Super Admin Details public function super_admin_details(){ if ($this->CI->session->userdata('member_usertype') != 'super_admin'){ redirect('login'); } //implementation code here }
doc_23530749
So, first in my filters.py (code below) I have passed the queryset in ModelMultipleChoiceFilter with the widget SelectMultiple. But when I load the page, the select comes with pre-selected (selected="selected") options with all the queryset objects value in it. So, I basically want these select multiple options to be 'unselected' by default. Thanks in advance. #filters.py class JobFilter(django_filters.FilterSet): job_category = django_filters.ModelMultipleChoiceFilter(queryset=Interests.objects.all(), widget=forms.SelectMultiple(attrs={'class': "form-control", 'data-role': "tagsinput"})) class Meta: model = JobPost fields = ['job_category', 'job_type', 'intake', 'duration'] #html as per inspection mode <select name="job_category" class="form-control" data-role="tagsinput" id="id_job_category" multiple> <option value="45" selected="selected">Interests object (45)</option> <option value="46" selected="selected">Interests object (46)</option> </select>
doc_23530750
$ids = array( 1, 2, 3, 4, 5 ); $q = DB::select('field1', 'field2', 'field3')-> from('work')-> where('field1', 'in', $ids)->execute(); How can I sort them in my custom order, like MySQL's 'ORDER BY Field' do? A: Check out DB::Expr You can use it like so: ->order_by(DB::Expr('FIELD(`field`, 3,1,2)')) Note, you'll have to manually escape the contents
doc_23530751
This caused all kinds of nastiness, the majority of which I've worked through and resolved. I'm now left with the following the MVC project and I'm stuck: * *the Default Namespace is no longer recognised in the IDE *I have lost Intellisense in the project *the Refactor options are not available *SimpleMembershipInitializer has red squiggles indicating it can't be found However the solution builds and appears to work without issue - I'd appreciate some pointers as to where to look to clear the above. A: I found a solution in this instance, it has happened a few times since and simply unloading the project and reloading it has resolved the issue every time
doc_23530752
private string getMySqlStatement(MySqlCommand cmd) { string result = cmd.CommandText.ToString(); foreach (MySqlParameter p in cmd.Parameters) { string addQuote = (p.Value is string) ? "'" : ""; result = result.Replace(p.ParameterName.ToString(), addQuote + p.Value.ToString() + addQuote); } return result; } This works, but I was wondering if there was a more proper way to see the full statement with parameters applied. Reading up on this, it looks like the parameters aren't actually applied until it reaches the server - is this correct? In that case, I suppose I can stick to my function above, but I just wanted to know if there was a better way to do it. Note: I am just using this function for debugging purposes so I can see the MySQL statement. A: MySQL supports two protocols for client/server communication: text and binary. In the text protocol, there is no support for command parameters in the protocol itself; they are simulated by the client library. With Connector/NET, the text protocol is always used, unless you set IgnorePrepare=true in the connection string and call MySqlCommand.Prepare() for each command. So it's most likely the case that you are using the text protocol. This is good, because it will be easier to log the actual statements with parameters applied. There are three ways to view the statements being executed: Use Connector/NET Logging Add Logging=true to your connection string and create a TraceListener that listens for the QueryOpened event. This should contain the full SQL statement with parameters interpolated. Instructions on setting this up are here. Use MySQL Server Logging Enable the general query log on your server to see all queries that are being executed. This is done with the --general_log=1 --general_log_file=/var/path/to/file server options. Packet Sniffing If you're not using SslMode=Required (to encrypt the connection between client and server), then you can use WireShark to capture network traffic between your client and the server. WireShark has MySQL Protocol analysers that will inspect MySQL traffic and identify command packets (that contain SQL queries). This option is ideal if you aren't able to modify your client program nor change server logging settings.
doc_23530753
$options = ''; for($Year = date("Y"); $Year <= date("Y") + 5; $Year++) { $options .= "<option>$Year</option>\n"; } $Select = <<<QQxQQ <select> $options </select> QQxQQ; print "$Select"; But no luck... EDIT These examples are great, thanks guys. This is what I'm trying to iterate <li><a href="#"><span>$looped</span></a></li> Where $looped is a value of a fetched mysql column. As you can probably see, I'm trying to iterate an element of a list x amount of times (where x = number of rows of sql query). I thought trying to put the results into an array and then cycling through the array, however I still couldn't get the HTML code to go through the parser accordingly without being considered a string. A: How about this? <select> <?php for($Year = date("Y"); $Year <= date("Y") + 5; $Year++) { echo "<option>".$Year."</option>"; } ?> </select> A: You could try something like this: <?php $year = date('Y'); $end = ($year + 5); do { $option .= '<option>'.$year.'</option>'; } while (++$year <= $end); echo '<select>'.$option.'</select>'; ?> A: Heredocs have their place, but imo they are overrated and often used in the wrong context. Try this: $year = date("Y"); for( $Year = $year; $Year <= ($year+5); $Year++ ) { $options .= "<option value=\"$Year\">$Year</option>\n"; } echo "<select name='years' id='years'>"; echo $options; echo "</select>"; A: <select> <?php for($Year = date("Y"); $Year <= date("Y") + 5; $Year++) { echo "<option>$Year</option>\n"; } ?> </select>
doc_23530754
<Window x:Class="WpfTutorialStep1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Garbo" Height="900" Width="900" MinHeight="240" MinWidth="320"> <Window.InputBindings> <KeyBinding Key="+" Modifiers="Ctrl" Command="{Binding cmd_view_zoom_in}"/> <KeyBinding Key="-" Modifiers="Ctrl" Command="{Binding cmd_view_zoom_out}"/> <KeyBinding Key="0" Modifiers="Ctrl" Command="{Binding cmd_view_zoom_def}"/> </Window.InputBindings> </Windows> The above code gives me an error during compile: XLS0431: Invalid value for property 'Key':'+' XLS0431: Invalid value for property 'Key':'-' '0' cannot be used as a value for 'Key'. Nuumbers are not valid enumerator values,
doc_23530755
[ { "scoreCount": "108", "legendDesc": "Excellent ", "colorPatchCode": "#009900" }, { "scoreCount": "20", "legendDesc": "Fail ", "colorPatchCode": "#FF0000" } ] to convert Array format like , [ [ "scoreCount": "108", "legendDesc": "Excellent ", "colorPatchCode": "#009900" ], [ "scoreCount": "20", "legendDesc": "Fail ", "colorPatchCode": "#FF0000" ] ] Can any one help? A: [ "scoreCount": "108", "legendDesc": "Excellent ", "colorPatchCode": "#009900" ], is not valid structure. Array can contain single element. native , or object which contain another items(properties) , or array. A: What if try this: var arr = [ { "scoreCount": "108", "legendDesc": "Excellent ", "colorPatchCode": "#009900" }, { "scoreCount": "62", "legendDesc": "Good ", "colorPatchCode": "#99CC00" }, { "scoreCount": "55", "legendDesc": "Acceptable ", "colorPatchCode": "#FFFF00" }, { "scoreCount": "31", "legendDesc": "Poor ", "colorPatchCode": "#FF9900" }, { "scoreCount": "20", "legendDesc": "Fail ", "colorPatchCode": "#FF0000" } ]; for (i = 0;i<arr.length;i++) { var a = []; for (n in arr[i]) { a[n] = arr[i][n]; } arr[i] = a; } for (i = 0;i<arr.length;i++) { alert(arr[i]['scoreCount']); } A: http://jsfiddle.net/sPN7z/ var source = [ { "scoreCount": "108", "legendDesc": "Excellent ", "colorPatchCode": "#009900" }, { "scoreCount": "62", "legendDesc": "Good ", "colorPatchCode": "#99CC00" }, { "scoreCount": "55", "legendDesc": "Acceptable ", "colorPatchCode": "#FFFF00" }, { "scoreCount": "31", "legendDesc": "Poor ", "colorPatchCode": "#FF9900" }, { "scoreCount": "20", "legendDesc": "Fail ", "colorPatchCode": "#FF0000" } ]; var out = []; for (var i = 0; i < source.length; i++) { var tmp = []; for (var i2 in source[i]) { tmp.push(source[i][i2]); } out.push(tmp); } out would then be: [ ["108","Excellent ","#009900"], ["62","Good ","#99CC00"], ["55","Acceptable ","#FFFF00"], ["31","Poor ","#FF9900"], ["20","Fail ","#FF0000"] ] as the others said already.. you cannot store key values in javascript arrays. thats what json is for. A: Though the syntax is wrong, but if you want you can make this format of string anyway. But, as you know, you cannot read it back to JavaScript variable. A: You can use object oriented capabilities of javascript to accomplish this in more cleaner way. var jsonArray = [    {      "scoreCount": "108",      "legendDesc": "Excellent ",      "colorPatchCode": "#009900" }, {      "scoreCount": "62",      "legendDesc": "Good ",      "colorPatchCode": "#99CC00" }, {      "scoreCount": "55",      "legendDesc": "Acceptable ",      "colorPatchCode": "#FFFF00" }, {      "scoreCount": "31",      "legendDesc": "Poor ",      "colorPatchCode": "#FF9900" }, {      "scoreCount": "20",      "legendDesc": "Fail ",      "colorPatchCode": "#FF0000" } ]; function MyJsObject(scoreCount, legendDesc, colorPatchCode) {      this.scoreCount = scoreCount;      this.legendDesc = legendDesc;      this.colorPatchCode = colorPatchCode; } function createJSArray() {      var jsArray = new Array();      for(i = 0; i < jsonArray.length; i++) {          var m = new MyJsObject(jsonArray[i].scoreCount,                         jsonArray[i].legendDesc, jsonArray[i].colorPatchCode);          jsArray[i] = m;      }      alert(jsArray[4].scoreCount);//access any object like this }
doc_23530756
I have many to many relationships of User-Transactions-Merchant, where the user has many Merchants through Transactions and the Merchant has many customers through Transactions. That is pretty typical. I can get all of a merchant's customers through Ecto by doing something like this: def find_merchant_customers(%{"merchant_id" => id}) do merchant = Repo.get(Merchant, id) Repo.all assoc(merchant, :customers) end If I want to find a balance for a user with a specific merchant, I have SQL query like this which sums up the transactions and produced a balance for that merchant. def customer_balance(user_id: user_id, merchant_id: merchant_id) do q = from t in Transaction, select: fragment("SUM(CASE WHEN ? = 'credit' THEN (?) ELSE - (?) END)", t.type, t.amount, t.amount), where: t.user_id == ^user_id and t.merchant_id == ^merchant_id balance = Repo.one(q) || 0 do_balance(balance, "asset") |> Money.new(:USD) end The question How do I combine the two operations into one query such that the Join retrieves a list of users and populates the virtual attribute of Balance in the user. I know I could just run the first query and get the list of users then transform that data by retrieving each of the balances for each user, although that seems very inefficient. An alternative might be to understand how to assign the select fragement( to an attribute within the query as a sub-query. Any guidance would be helpful. My User Model defmodule MyApp.User do @moduledoc """ User struct for user related data """ import MyApp.Validation use MyApp.Model use Coherence.Schema schema "my_app_users" do field :email, :string field :first_name, :string field :last_name, :string field :role, :integer field :birthdate, Ecto.Date field :address1, :string field :address2, :string field :city, :string field :state, :string field :zip, :string field :status, :boolean, default: true field :verified_email, :boolean, default: false field :verified_phone, :boolean, default: false field :mobile, :string field :card, :string field :sms_code, :string field :balance, Money.Ecto, virtual: true field :points, :integer, virtual: true coherence_schema has_many :transactions, MyApp.Transaction has_many :merchants, through: [:transactions, :merchant] timestamps() end @doc """ Builds a changeset based on the `struct` and `params`. """ def changeset(struct, params \\ %{}) do struct |> cast(params, [:email, :first_name, :last_name, :password_hash, :role, :birthdate, :address1, :address2, :city, :state, :zip, :status, :mobile, :card, :sms_code, :status, :merchant_id, :verified_email, :verified_phone]) |> validate_required_inclusion([:email, :mobile]) |> validate_format(:email, ~r/(\w+)@([\w.]+)/) end defp put_password_hash(changeset) do case changeset do %Ecto.Changeset{valid?: true, changes: %{password: password}} -> put_change(changeset, :password_hash, Comeonin.Bcrypt.hashpwsalt(password)) _ -> changeset end end My Merchant Model defmodule MyApp.Merchant do @moduledoc """ Merchant Struct Merchant has an owner of a User - Which must exist """ use MyApp.Model use Arc.Ecto.Schema schema "my_app_merchants" do field :name, :string field :email, :string field :address1, :string field :address2, :string field :city, :string field :zip, :string field :state, :string field :status, :boolean, default: true field :description, :string field :image, MyRewards.Avatar.Type field :phone, :string field :website, :string has_many :transactions, MyApp.Transaction has_many :customers, through: [:transactions, :user] timestamps() end @doc """ Builds a changeset based on the `struct` and `params`. """ def changeset(struct, params \\ %{}) do struct |> cast(params, [:name, :email, :address1, :address2, :city, :zip, :state, :status, :description, :phone, :website, :status, :category_id, :user_id]) |> cast_attachments(params, [:image]) |> validate_required([:name]) |> validate_format(:email, ~r/(\w+)@([\w.]+)/) end end Query Functions def find_merchant_customers(%{"merchant_id" => id}) do merchant = Repo.get(Merchant, id) Repo.all assoc(merchant, :customers) end def customer_balance(user_id: user_id, merchant_id: merchant_id) do q = from t in Transaction, select: fragment("SUM(CASE WHEN ? = 'credit' THEN (?) ELSE - (?) END)", t.type, t.amount, t.amount), where: t.user_id == ^user_id and t.merchant_id == ^merchant_id balance = Repo.one(q) || 0 do_balance(balance, "asset") |> Money.new(:USD) end A: Move the fragment into a macro to keep the code clear: defmacro balance_amount(transaction) do quote do fragment("CASE WHEN ? = 'credit' THEN (?) ELSE - (?) END", unquote(transaction).type, unquote(transaction).amount, unquote(transaction).amount) end end Create a subquery with %{user_id, merchant_id, balance} def user_merchant_balance do from t in Transaction, select: %{user_id: t.user_id, merchant_id: t.merchant_id, balance: sum(balance_amount(t))}, group_by: [t.user_id, t.merchant_id] end Join to the subquery from the main query, use the map update syntax %{|} to populate the virtual field: def merchant_customers(merchant_id) do from u in User, join: b in subquery(user_merchant_balance()), on: u.id == b.user_id, where: b.merchant_id == ^merchant_id, select: %{u | balance: b.balance} end Edit: In Ecto 2.2, the balance field can be cast to Money.Ecto.Type def merchant_customers(merchant_id) do from u in User, join: b in subquery(user_merchant_balance()), on: u.id == b.user_id, where: b.merchant_id == ^merchant_id, select: %{u | balance: type(b.balance, Money.Ecto.Type)} end
doc_23530757
x <---> y <---> z edge(x,y). edge(y,z). path(Start,End,Path) :- % path/3: there is a `Path` from `Start` to `End` path(Start,End,[Start],Path). path(End,End,RPath,Path) :- % internal helper predicate `path/4` reverse(RPath,Path). path(Start,End,Visited,Path) :- edge(Start,Next), \+ memberchk(Next,Visited), path(Next,End,[Next|Visited],Path). Sample queries: ?- path(x,z,P). P = [x, y, z] ; % works as expected false. ?- path(z,x,P). false. % unexpectedly fails! What can I do to make above query succeed? A: If you want to handle an undirected graph: path(Start, End, Visited, Path) :- ( edge(Start, Next) ; edge(Next, Start) ), ... A: First, we write down the known facts by defining predicate edge/2: edge(x,y). edge(y,x). edge(y,z). edge(z,y). Then we use edge/2 in tandem with meta-predicate path/4 like so: ?- path(edge,Path,x,z). % one direction Path = [x,y,z] ; false. ?- path(edge,Path,z,x). % other direction Path = [z,y,x] ; false. How about the following very general query? What are all possible paths based on edge/2? ?- path(edge,Path,From,To). From = To, Path = [To] ; From = x , To = y, Path = [x,y] ; From = x , To = z, Path = [x,y,z] ; From = y , To = x, Path = [y,x] ; From = y , To = z, Path = [y,z] ; From = z , To = y, Path = [z,y] ; From = z , To = x, Path = [z,y,x] ; false.
doc_23530758
$json_data = array( "code"=>"200", "name"=>"My Name", "serial_number"=>"serial" ); $result = json_encode($json_data); The dataset is only one level. As I am creating this data set with a php loop. I want to be able to have multiple people but the code element be outside the users. So basically I want the json data to look like this: { "code": "404", "people": [ { "name": "Person 1", "serial_number": "xyz" }, { "name": "Person Two", "serial_number": "123" } ] } A: Basically you want to group array of objects by property "code". There are many questions about this. Here's one of the possible methods using array_reduce. $json_data = [ [ "code" => "200", "name" => "My Name1", "serial_number" => "serial1", ], [ "code" => "200", "name" => "My Name2", "serial_number" => "serial2", ], [ "code" => "400", "name" => "My Name3", "serial_number" => "serial3", ], ]; $result = array_values(array_reduce($json_data, function ($agg, $item) { if (!isset($agg[$item['code']])) { $agg[$item['code']] = [ "code" => $item['code'], "people" => [], ]; } $agg[$item['code']]['people'][] = [ "name" => $item["name"], "serial_number" => $item["serial_number"], ]; return $agg; }, [])); print_r($result); Output: Array ( [0] => Array ( [code] => 200 [people] => Array ( [0] => Array ( [name] => My Name1 [serial_number] => serial1 ) [1] => Array ( [name] => My Name2 [serial_number] => serial2 ) ) ) [1] => Array ( [code] => 400 [people] => Array ( [0] => Array ( [name] => My Name3 [serial_number] => serial3 ) ) ) )
doc_23530759
from(rabbitmq:pollingQueue?prefetchSize=1&concurrentConsumer=10) .process(pollingRequestStatus) // check status of the request, if not ready, requeue = true .Choice .when(requeue == true) // request not ready .to(rabbitmq:pollingQueue)//back to the same queue .endChoice .otherwise .to(proceedToSomethingElse) .endChoice.end; When the requeue happens, the message gets duplicated, is this an expected behavior when sending back the message to the same queue? I have also tried something like the following as suggested but it does not work,the message seems to be just consumed and won't requeue from(rabbitmq:pollingQueue? prefetchSize=1&concurrentConsumer=10) .onException(NotReadyException.class) .handled(true) .setHeader(RabbitMQConstants.REQUEUE, constant(true)) .end() .process(pollingRequestStatus) // check status of the request, if not ready, throw NotReadyEception .to(proceedToSomethingElse); The other two ways i have tried that at least does not create duplicates, 1.) on NotReadyExeption, send the message back to the pollingQueue from(rabbitmq:pollingQueue? prefetchSize=1&concurrentConsumer=10) .onException(NotReadyException.class) .to(rabbitmq:pollingQueue) //.delay(constant(8000)) //not sure why it throws error if i set delay .end .process(pollingRequestStatus); // check status of the request, if not ready, throw NotReadyEception This works, however, it runs too quick, like instantly. If i set delay(constant(number)), the following error is thrown, Exception in thread "main" org.apache.camel.FailedToCreateRouteException: Failed to create route route13 at: >>> From [bla bla bla...] at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:1062) at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:196) at org.apache.camel.impl.DefaultCamelContext.startRoute(DefaultCamelContext.java:984) at org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:3401) at org.apache.camel.impl.DefaultCamelContext.doStartCamel(DefaultCamelContext.java:3132) at org.apache.camel.impl.DefaultCamelContext.access$000(DefaultCamelContext.java:183) at org.apache.camel.impl.DefaultCamelContext$2.call(DefaultCamelContext.java:2961) at org.apache.camel.impl.DefaultCamelContext$2.call(DefaultCamelContext.java:2957) at org.apache.camel.impl.DefaultCamelContext.doWithDefinedClassLoader(DefaultCamelContext.java:2980) at org.apache.camel.impl.DefaultCamelContext.doStart(DefaultCamelContext.java:2957) at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:61) at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:2924) at com.mbww.ithink.runner.Main.main(Main.java:174) Caused by: java.lang.IllegalArgumentException: Route route13 has no output processors. You need to add outputs to the route such as to("log:foo"). at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:1060) 2.) On NotReadyException, redeliver based on redeliveryPolicy from(rabbitmq:pollingQueue? prefetchSize=1&concurrentConsumer=10) .onException(NotReadyException.class) .setFaultBody(constant(false)) .maximumRedeliveries(-1) // -1 = redeliver forever .redeliveryDelay(10000) .end .process(pollingRequestStatus); // check status of the request, if not ready, throw NotReadyEception Originally the idea of requeue is so that if the request is not ready, requeue the message to be back of the queue, set a delay and check the status of the next request, and avoid getting things like Ratelimit error. seems like the redelivery policy is the way to go now. Thanks A: To be able to requeue the message you have to turn off RabbitMQ's auto-acknowledgement. In that case you have to manually send the ack, nack or reject message back to the publisher. (https://www.rabbitmq.com/confirms.html) It means you have to manually call one of the basicAck, basicNack or basicReject function on the current Channel implementation. Translated to Camel: To turn of auto-acknowledgement add the autoAck=false to the endpoint parameters. AFAIK, the Camel Endpoint's underlying Channel is not accessible (source) so you can't directly call the Channel's basicReject(long deliveryTag, boolean requeue) function, but Camel does call it when the exchange is failed (exception occured during to routing). The workaround might be the following: (pseudocodish and I haven't tried it, but based on checking the camel-rabbitmq endpoint's source, especially this part) Updated workaround (tested and working): from("rabbitmq://localhost:5672/first?queue=test&concurrentConsumers=10prefetchSize=1&autoAck=false&autoDelete=false") .onException(NotReadyException.class) .log("Error for ${body}! Requeue") .asyncDelayedRedelivery().redeliveryDelay(5000) // wait 5 secs to redeliver and requeue .maximumRedeliveries(1) .setHeader(RabbitMQConstants.REQUEUE, constant(true)) .handled(true) .setFaultBody(constant(true)) .end() .log("Received: ${body}") .process((e) -> { if(notReady(e)) throw new NotReadyException(); // create a new Exception and throw it if the status is not ready } }) .to("direct:somethingElse"); Also I created a gist which implements almost a same scenario. Hope it helps! A: You don't need to send the message again, just set rabbitmq.REQUEUE property to true. If this property is set, rabbitmq component will automatically requeue the message instead of discarding it. From the docs: Camel 2.14.2: This is used by the consumer to control rejection of the message. When the consumer is complete processing the exchange, and if the exchange failed, then the consumer is going to reject the message from the RabbitMQ broker. The value of this header controls this behavior. If the value is false (by default) then the message is discarded/dead-lettered. If the value is true, then the message is re-queued. So, inside your processor you can do something like: exchange.getIn().setHeader("rabbitmq.REQUEUE", true); And then just check REQUEUE header == false in your route to call proceedToSomethingElse.
doc_23530760
Note that a and b are inclusive. N can be any finite size essentially. The purpose of the question was just to practice algorithms. Consider arr = [0,0,0,0,0,0,0] Consider that we want to flips the following inclusive intervals [1,3], [0,4] After process [1,3], we have arr = [0,1,1,1,0,0,0] and after processing [0,4], we have arr = [1,0,0,0,1,0,0], which is the final array. A: The obvious efficient way to do that is to not do that. Instead first collect at what indices the flipping changes, and then do one pass to apply the collected flipping information. Python implementation of a naive solution, the efficient solution, and testing: def naive(arr, intervals): for a, b in intervals: for i in range(a, b+1): arr[i] ^= 1 def efficient(arr, intervals): flips = [0] * len(arr) for a, b in intervals: flips[a] ^= 1 flips[b+1] ^= 1 xor = 0 for i, flip in enumerate(flips): xor ^= flip arr[i] ^= xor def test(): import random n = 30 arr = random.choices([0, 1], k=n) intervals = [] while len(intervals) < 100: a = random.randrange(n-1) b = random.randrange(n-1) if a <= b: intervals.append((a, b)) print(f'{arr = }') expect = arr * 1 naive(expect, intervals) print(f'{expect = }') result = arr * 1 efficient(result, intervals) print(f'{result = }') print(f'{(result == expect) = }') test() Demo output: arr = [1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0] expect = [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0] result = [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0] (result == expect) = True A: Cast to Int Array and use bitwise not if you are using C or C++. But this is an SIMD task so its parallelizable if you wish.
doc_23530761
I have an Account model: class Account include Mongoid::Document include Mongoid::Timestamps referenced_in :user end and User: class User include Mongoid::Document include Mongoid::Timestamps references_one :account end I have the following scenario(I set reference_one association): Scenario: Client views his account Given a user with id: "4ceede9b5e6f991aef000007" And the following accounts exist: | user_id | | 4ceede9b5e6f991aef000007 | ..... I think this is not so good idea use ids such way. What is the best practice of creating object with associations? I would be nice if pickle. for example, could help. A: You can set up blueprints like this: User.blueprint do name # ... end Account.blueprint do user # ... end And inside cucumber: Given the following accounts exist | user | | Fred | | Ethel | If pickle doesn't handle the step above, you can create your own step definition like this: Given /^the following accounts:$/ do |class_name, table| table.hashes.each do |attributes| u = User.make! :name => attributes[:user] Account.make! :user => u end end
doc_23530762
The delete works on the initial page load, but if I change pages or search the delete link does not work. <script type="text/javascript"> $(document).ready(function () { $('#dataTable').dataTable({ "aoColumnDefs": [ { "bSortable": false, "bSearchable": false, "aTargets": [2] } ] }); //modal popup $("#dialog-confirm").dialog({ autoOpen: false, resizable: false, height: 200, width: 400, modal: true, buttons: { "Delete": function () { $(this).dialog("close"); $("form")["delete"].submit(); }, Cancel: function () { $(this).dialog("close"); } } }); $(".deleteLink").click(function (e) { e.preventDefault(); $("#dialog-confirm").dialog("open"); }); // $.ajaxSetup({ cache: false }); }); Here is html. <table cellpadding="0" cellspacing="0" border="0" class="display" id="dataTable"> <thead> <tr> <th> @Html.LabelFor(p => Model.FirstOrDefault().LastName) </th> <th> @Html.LabelFor(p => Model.FirstOrDefault().FirstName) </th> <th> </th> </tr> </thead> <tbody> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.LastName) </td> <td> @Html.DisplayFor(modelItem => item.FirstName) </td> <td> @Html.ActionLink("Edit", "Edit", new { id = item.UserId }) | @Html.ActionLink("Details", "Details", new { id = item.UserId }) | @Html.ActionLink("Delete", "DeleteConfirmed", new { id = item.UserId }, new { @class = "deleteLink" }) @using (Html.BeginForm("DeleteConfirmed", "User", new { id = item.UserId})){} </td> </tr> } </tbody> Here is confirm dialog <div id="dialog-confirm" title="Delete the item?" style="display:none" > <p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>This item will be deleted. Are you sure?</p> A: <script type="text/javascript"> $(document).ready(function () { $('#dataTable').dataTable({ "aoColumnDefs": [ { "bSortable": false, "bSearchable": false, "aTargets": [2] } ] }); //modal popup $(".deleteLink").live('click', function (e) { var obj = $(this); e.preventDefault(); var dialogAppendData = '<div><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>' + 'This item will be deleted. Are you sure?</p></div>'; $(dialogAppendData).dialog({ autoOpen: true, resizable: false, modal: true, height: 200, width: 400, zIndex: 10000, title: 'Delete the item?', buttons: { 'Delete': function () { $.ajax({ url: '/User/DeleteUser', type: 'delete', dataType: 'json', data: { 'userId': obj.data('id') }, success: function (data) { $(obj).remove(); } }); $(this).dialog("close"); }, 'Cancel': function () { $(this).dialog("close"); } }, close: function (event, ui) { $(this).remove(); } }); }); }); </script> insteand of : @Html.ActionLink("Delete", "DeleteConfirmed", new { id = item.UserId }, new { @class = "deleteLink" }) //use below link. <a class = "deleteLink">Delete</a> //In controller UserController : [HttpDelete] public JsonResult DeleteUser(int userId) { var user = db.users.Find(userId); db.Users.Remove(user); db.SaveChanges(); //Or // U r logic for delete. return Json(true, JsonRequestBehavior.AllowGet); } A: <script type="text/javascript"> $(document).ready(function () { $('#dataTable').dataTable({ "aoColumnDefs": [ { "bSortable": false, "bSearchable": false, "aTargets": [2] } ] }); //modal popup $('.deleteLink').live('click', function (e) { e.preventDefault(); var obj = $(this); var dialogAppendData = '<div><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>' + 'This item will be deleted. Are you sure?</p></div>'; $(dialogAppendData).dialog({ autoOpen: true, resizable: false, modal: true, height: 200, width: 400, zIndex: 10000, title: 'Delete the item?', buttons: { 'Delete': function () { $("form")["delete"].submit(); $(this).dialog("close"); }, 'Cancel': function () { $(this).dialog("close"); } }, close: function (event, ui) { $(this).remove(); } }); }); // $.ajaxSetup({ cache: false }); }); </script>
doc_23530763
styled as follow: div.menubox { background-color: #FFFFFF; border: 1px solid #887777; border-radius: 0 5px 5px 0; box-shadow: 1px 1px 3px #998888; font-family: Lato,sans serif; font-size: 12px; left: -5px; margin-bottom: 2em; min-height: 675px; overflow: hidden; padding: 25px 0 2em; position: absolute; top: 195px; transition-duration: 0.5s; transition-property: top; width: 215px; z-index: 99; } It contains an ul and several li. Nothing of exceptional until i ask to firebug to print in console the menubox height. console.log(document.getElementById("menubox").offsetHeight) returns an outstanding "677.2px". It is the first time I step on such strange behaviour (I'm running firefox 17, with firebug 1.10.6, with a bunch of plugins, on an old windows XP installation). It is a known issue of one of the component or a new "feature"? ADDENDUM Removing the border-shadow, border-radius css properties (disabled by via firebug) the result doesn't change. chrome reports "649.5999755859375px" uhmm... need further investigation of the underlying javascript code EXTRA Ops, the javascript code was a dead line filling a variable, the true code is console.log(document.id("menubox").getStyle("height))` so mootools 1.4.5 is the main suspected (issuing manually the command on console return an integer pixel count) on both browser. The question is still live, though, have you encountered a similar behaviour, there is a workaround (beside rounding manually the result)? A: Fractional parts on pixels is not strange in CSS as it is not a "dott" on the screen rather an angular measurement. From the CSS 2.1 documentation: "Pixel units are relative to the resolution of the viewing device, i.e., most often a computer display. If the pixel density of the output device is very different from that of a typical computer display, the user agent should rescale pixel values. It is recommended that the reference pixel be the visual angle of one pixel on a device with a pixel density of 96dpi and a distance from the reader of an arm's length. For a nominal arm's length of 28 inches, the visual angle is therefore about 0.0213 degrees.” More information can be found here: http://inamidst.com/stuff/notes/csspx My guess is that you are mixing em:s with px:s and that will cause fragmented pixel values to be returned. Please note that there is nothing wrong with the behavior so I would not care as long as you don't run into trouble. Especially as you only have defined a min-height on the DOM-element.
doc_23530764
my code is something like this: connect(&myworkingthread,SIGNAL(updataprocess(int)),processbar2,SLOT(setValue(int))); for (int i=0;i<n;i++){ // each individual data will be loaded in this part... myworkingthread.start();// this thread will take 5 secs to finish, a signal is // also emitted to show the process of this thread(processbar2). // after working thread, the processed data will be saved... processbar1->setValue(i); // processbar is used to show the processing process //problem of this code: data is totally wrong because the next thread will start before the last one finish. } i also wants to show the process of myworkingthread which is supposed to be implemented by signal and slot. if i use the above code, the data is totally wrong. because the second thread will starts before the first one finish. then i change my code like this: connect(&myworkingthread,SIGNAL(updataprocess(int)),processbar2,SLOT(setValue(int))); for (int i=0;i<n;i++){ // each individual data will be loaded in this part... myworkingthread.start();// this thread will take 5 secs to finish // signal is also emitted to show the process of this thread(processbar2). myworkingthread.wait();// i will wait the thread until it finish // after working thread, the processed data will be saved... processbar1->setValue(i); // processbar is used to show the processing process } the problem of this code is that processbar of the thread is not working until the for loop goes through all the files. is there any way to make the thread process in a for loop? A: You need to call QApplication::processEvents(); see Simple example using QProgressDialog: Any ideas why this doesn't work properly? As far as I remenber, this should be called after the "emit" line in your thread...
doc_23530765
Now, I opened it on Python to see what is going on, and apparently the image is on RBGA format. I thought to convert it to RGB, and did it using the following code: img = Image.open(os.path.join(PNG_REPO, page)[:-4] + ".png") arr = np.array(img) rgbImage = cv2.cvtColor(arr, cv2.COLOR_RGBA2RGB) img = Image.fromarray(rgbImage) img.save("please.png") and then, weird stuff happened. The image seems to have become completely black (attached below) and opening it on Python, a local program or a browser doesn't make any difference anymore. Anyone has any idea what is going on? I think that I am losing it and I am completely stucked. A: In fact, SVG and PNG are totally different. SVG (Scallable vector graphics) is not a standard image format : the image is not stored as an raay of pixel (or derivative), but as a vectorized format. To display it, you would have to render the vectors into pixels, then display them. The big assets of this approach are the quality vs. size : for illustrations, you can have a fantastic quality for almost nothing in size, however, it requires more time to process, and the decoding is very different from other image formats, thus it is often not supported by image viewers, and the renders can depend a bit on the renderer. PNG (Portable network graphics) on the other hand is still based on pixel, and is very widely supported. As for your question, your image have an alpha (transparency) channel. When converting it to RGB, you are getting rid of this transparency, which opencv translates into a fixed color. Here, this color is (0,0,0), that is to say black. You should try this : img = Image.open(os.path.join(PNG_REPO, page)[:-4] + ".png") img.load() new_img = Image.new("RGB", img.size, (255, 255, 255)) new_img.paste(img, mask=img.split()[3]) # 3 is the alpha channel new_img.save("should_be_good.png")
doc_23530766
http://jsfiddle.net/tfgdveop/1/ <div class="container" style="background: white"> <div class="row"> <div class="col-xs-3" style="background: red; height: 300px;">catalog</div> <div class="col-xs-9" style="background: blue; height: 50px;">bNNER</div> <div class="col-xs-3 col-xs-push-6" style="background: yellow; height: 500px;">News</div> <div class="col-xs-6 col-xs-pull-3" style="background: green; height: 280px;">Catalog</div> <div class="col-xs-6 col-xs-pull-6" style="background: pink; height: 100px;">Promo</div> </div> </div> I need pink promo block 9 cols width, but if i made it wider 6, it fall under news block. A: I changed order a bit and Yellow News to float to right. I also removed all unnnecessary pulls and pushes. Here is the result: http://jsfiddle.net/tfgdveop/3/ <div class="container" style="background: white"> <div class="row"> <div class="col-xs-3" style="background: red; height: 300px;">catalog</div> <div class="col-xs-9"style="background: blue; height: 50px;">bNNER</div> <div class="col-xs-6"style="background: green; height: 280px;">Catalog</div> <div class="col-xs-3 pull-right"style="background: yellow; height: 500px;">News</div> <div class="col-xs-9" style="background: pink; height: 100px;">Promo</div> </div> </div> Is this what you are looking for?
doc_23530767
import socket from django.core.exceptions import ObjectDoesNotExist from django.db import Models class MyClass(models.Model): name = models.CharField(max_length=250, default=socket.gethostname(), unique=True) @staticmethod def update_some_list(some_list): for some_item in some_list: try: MyClass.objects.get(name=some_item) except ObjectDoesNotExist: # I also tried with MyClass.DoesNotExist MyClass.objects.create(name=some_item) The point here is that, when I run into this code, I have some "module-level" DoesNotExist that is thrown away, as if this try/except block is never hit: Traceback (most recent call last): File "/app/backend/shared/models.py", line 201, in update_some_list MyClass.objects.get(name=some_item) File "/usr/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/lib/python3.6/site-packages/django/db/models/query.py", line 399, in get self.model._meta.object_name shared.models.DoesNotExist: MyClass matching query does not exist. A: Consider using QuerySet.get_or_create, which shall eliminate the problem above. MyClass.objects.get_or_create(name=some_item) Also, please note, that if you access class inside the @staticmethod it makes sense to update it to be @classmethod. Also, in the question you are having: from django.db import Models instead of from django.db import models
doc_23530768
val route = pathPrefix("myapp") { path("search") { get { (mainActorRef ? DoSomething("foo")).mapTo[ReturningType].map { result => complete(HttpEntity(ContentTypes.`application/json`, result )) } } } } The problem is that the main actor communicates with other actors and gets an answer back from one of those actors like this: class MainActor extends Actor { override def receive: Receive = { case d:DoSomething => anotherActor ! DoThis(d) // received from anotherActor as reply to DoThis case r:DoThisResponse => // how do I send the response back to my “route”? pipe (Future{r}) to ??? } } How can I send this answer back to Akka-Http as response? Using "sender()" in the main actor doesn't work as it won't be the right reference. Should I pass in the DoSomething some reference to use with "tell" (!) inside the main actor? How do I pass this reference? A: Use forward instead of tell in the the MainActor when sending to anotherActor. That way anotherActor will not "see" MainActor as the sender . So, basically, you send new messages in the intermediate steps with forward, but the actor in the line can simply respond to sender, since it does not see the intermediate actors. Edit: a complete MainActor class MainActor extends Actor { override def receive: Receive = { //delegating some more work to another container case d:DoSomething => anotherActor forward DoThis(d) // sending a response back to "route" case r:DoThisResponse => sender ! Response } }
doc_23530769
I already did a reinstall of bundler, reinstall of ruby, restarted my terminal, capistrano/rvm and capistrano/bundler is added and required on Capfile 00:11 bundler:install 01 ~/.rvm/bin/rvm do bundle install --path /home/web/apps/catalog/shared/bundle --jobs 4 --without development test --deployment --quiet #<Thread:0x00000000017b12a8@/home/ubuntu/.rvm/gems/ruby-2.5.3@catalogIndustry/gems/sshkit-1.19.1/lib/sshkit/runners/parallel.rb:10 run> terminated with exception (report_on_exception is true): Traceback (most recent call last): 1: from /home/ubuntu/.rvm/gems/ruby-2.5.3@catalogIndustry/gems/sshkit-1.19.1/lib/sshkit/runners/parallel.rb:11:in `block (2 levels) in execute' /home/ubuntu/.rvm/gems/ruby-2.5.3@catalogIndustry/gems/sshkit-1.19.1/lib/sshkit/runners/parallel.rb:15:in `rescue in block (2 levels) in execute': Exception while executing as web@ec2-52-15-226-151.us-east-2.compute.amazonaws.com: bundle exit status: 1 (SSHKit::Runner::ExecuteError) bundle stdout: `rvm do bundle install --path /home/web/apps/catalog/shared/bundle --jobs 4 --without development test --deployment --quiet` was removed, use `rvm 1.9.2,1.9.3 do bundle install --path /home/web/apps/catalog/shared/bundle --jobs 4 --without development test --deployment --quiet` or `rvm all do bundle install --path /home/web/apps/catalog/shared/bundle --jobs 4 --without development test --deployment --quiet` instead. bundle stderr: Nothing written (Backtrace restricted to imported tasks) cap aborted! SSHKit::Runner::ExecuteError: Exception while executing as web@ec2-52-15-226-151.us-east-2.compute.amazonaws.com: bundle exit status: 1 bundle stdout: `rvm do bundle install --path /home/web/apps/catalog/shared/bundle --jobs 4 --without development test --deployment --quiet` was removed, use `rvm 1.9.2,1.9.3 do bundle install --path /home/web/apps/catalog/shared/bundle --jobs 4 --without development test --deployment --quiet` or `rvm all do bundle install --path /home/web/apps/catalog/shared/bundle --jobs 4 --without development test --deployment --quiet` instead. bundle stderr: Nothing written Caused by: SSHKit::Command::Failed: bundle exit status: 1 bundle stdout: `rvm do bundle install --path /home/web/apps/catalog/shared/bundle --jobs 4 --without development test --deployment --quiet` was removed, use `rvm 1.9.2,1.9.3 do bundle install --path /home/web/apps/catalog/shared/bundle --jobs 4 --without development test --deployment --quiet` or `rvm all do bundle install --path /home/web/apps/catalog/shared/bundle --jobs 4 --without development test --deployment --quiet` instead. bundle stderr: Nothing written Tasks: TOP => deploy:updated => bundler:install (See full trace by running task with --trace) The deploy has failed with an error: Exception while executing as web@ec2-52-15-226-151.us-east-2.compute.amazonaws.com: bundle exit status: 1 bundle stdout: `rvm do bundle install --path /home/web/apps/catalog/shared/bundle --jobs 4 --without development test --deployment --quiet` was removed, use `rvm 1.9.2,1.9.3 do bundle install --path /home/web/apps/catalog/shared/bundle --jobs 4 --without development test --deployment --quiet` or `rvm all do bundle install --path /home/web/apps/catalog/shared/bundle --jobs 4 --without development test --deployment --quiet` instead. bundle stderr: Nothing written ** DEPLOY FAILED ** Refer to log/capistrano.log for details. What else can i do to resolve this error and deploy the website? A: Seems that Capistrano can't determine correct RVM ruby version. You can point it by hand # deploy.rb set :rvm_ruby_version, '2.5.3' # or if you have single ruby version set :rvm_ruby_version, 'default'
doc_23530770
I have done this, but creating a list just for counting doesn't feel right approach .. public static void main(String[] args) { List<String> firstList = new ArrayList<>(); firstList.add("first"); List<String> secondList = new ArrayList<>(); secondList.add("second"); Map<String, List<String>> myMap = new HashMap<>(); myMap.put("one", firstList); myMap.put("two", secondList); int size = myMap.entrySet().stream() .map(entry -> entry.getValue()) .flatMap(list -> list.stream()) .collect(Collectors.toList()) .size(); System.out.println("Size of all elements in map is:" + size); } A: Both of the previous answers are good, but can be shortened a bit more by going straight for the values(), rather than iterating the entrySet(): // Streaming version int size = myMap.values().stream() .mapToInt(list -> list.size()) .sum(); // Standard loop version int size = 0; for (List<String> list : myMap.values()) size += list.size(); A: This is at least more readable int size = myMap.values().stream() .mapToInt(Collection::size) .sum(); or if you want to look like a functional programming guru, use: int size2 = myMap.values().stream() .reduce(0, (acc, val) -> acc + val.size(), Integer::sum); EDIT: using the .values() :] A: Another way: private static int size = 0; public static void main(String[] args) { List<String> firstList = new ArrayList<>(); firstList.add("first"); List<String> secondList = new ArrayList<>(); secondList.add("second"); Map<String, List<String>> myMap = new HashMap<>(); myMap.put("one", firstList); myMap.put("two", secondList); myMap.values().forEach(value -> {size += value.size();}); System.out.println("Size of all elements in map is:" + size); }
doc_23530771
I try to use this class separately HttpUpload.java it work as well for me but it do one file for time. Can helps to modify these code for take this option for upload multiple ?and Thanks public class HttpUpload extends AsyncTask { private Context context; private String imgPath; private HttpClient client; private ProgressDialog pd; private long totalSize; //private static final String url = "http://192.168.1.122:1337/upload"; public HttpUpload(Context context, String imgPath) { super(); this.context = context; this.imgPath = imgPath; } @Override protected void onPreExecute() { //Set timeout parameters int timeout = 10000; HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, timeout); HttpConnectionParams.setSoTimeout(httpParameters, timeout); //We'll use the DefaultHttpClient client = new DefaultHttpClient(httpParameters); /* pd = new ProgressDialog(context); pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pd.setMessage("Uploading Picture..."); pd.setCancelable(false); pd.show();*/ } @Override protected Void doInBackground(Void... params) { try { File file = new File(imgPath); //Create the POST object HttpPost post = new HttpPost(url); //Create the multipart entity object and add a progress listener //this is a our extended class so we can know the bytes that have been transfered MultipartEntity entity = new MyMultipartEntity(new ProgressListener() { @Override public void transferred(long num) { //Call the onProgressUpdate method with the percent completed publishProgress((int) ((num / (float) totalSize) * 100)); Log.d("DEBUG", num + " - " + totalSize); } }); //Add the file to the content's body // ContentBody cbFile = new FileBody( file, "image/jpeg" ); ContentBody cbFile = new FileBody( file, "" ); entity.addPart("source", cbFile); //After adding everything we get the content's lenght totalSize = entity.getContentLength(); //We add the entity to the post request post.setEntity(entity); //Execute post request HttpResponse response = client.execute( post ); int statusCode = response.getStatusLine().getStatusCode(); if(statusCode == HttpStatus.SC_OK){ //If everything goes ok, we can get the response String fullRes = EntityUtils.toString(response.getEntity()); Log.d("DEBUG", fullRes); } else { Log.d("DEBUG", "HTTP Fail, Response Code: " + statusCode); } } catch (ClientProtocolException e) { // Any error related to the Http Protocol (e.g. malformed url) e.printStackTrace(); } catch (IOException e) { // Any IO error (e.g. File not found) e.printStackTrace(); } return null; } @Override protected void onProgressUpdate(Integer... progress) { //Set the pertange done in the progress dialog // pd.setProgress((int) (progress[0])); } @Override protected void onPostExecute(Void result) { //Dismiss progress dialog //pd.dismiss(); } } A: You can save your desired imgPaths into an array, then loop over them and execute your asyncTask.
doc_23530772
I can successfully ping the internal IP addresses of corresponding VMs, but it times out when I ping the Filestore instance from an AWS VM. One issue is that the CIDR block from GCP is on 10.10.0.0/16, while the Filestore instance sits on 10.8.79.89. Is it possible to establish an NFS mount between the two platforms, and if so, what might be required to accomplish this? As for setting up the VPN connection, I basically followed this tutorial to a tee: https://cloud.google.com/files/CloudVPNGuide-UsingCloudVPNwithAmazonWebServices.pdf Thanks!
doc_23530773
I want to use MongoDB in the old-fashioned way like: http://php.net/manual/en/mongocollection.find.php A: You can get the MongoClient from the DocumentManager using $mongoClient = $dm->getConnection()->getMongo(); Similarly, you can get a MongoCollection instance for document class className using $mongoCollection = $dm->getDocumentCollection('className')->getMongoCollection(); or more simply $mongoCollection = $dm->getConnection()->getMongo() ->selectCollection('collectionName');
doc_23530774
<br><a href="urlvalue" >URL Name 1</a> text</br> <br><a href="urlvalue" >URL with a longer url</a>text</br> <br><a href="urlvalue" >URL Name3 and this one too?</a> text</br> I want to import the data on this page to excel. So, I want to convert the data here to something like this: URL value | URL Name | Text I'd actually settle for: URL value | URL Name I am using this: I have used the simple-html-dom <?php require ('simple_html_dom.php'); $html = file_get_html('Etext_alt2.html'); foreach($html->find('a') as $element) echo $element->href .'<br>'; ?> this gives me a nice listing of the URL values. It seems like I should be able to access the other attributes, but nothing works. Am I using the wrong thing? What would be the best way to do this? A: Working example for your task without parsing HTML: $html = '<br><a href="urlvalue" >URL Name 1</a> text</br> <br><a href="urlvalue" >URL with a longer url</a>text</br> <br><a href="urlvalue" >URL Name3 and this one too?</a> text</br>'; preg_match_all('#<br><a href="(.*)" >(.*)</a>(.*)</br>#', $html, $matches, PREG_SET_ORDER); foreach ($matches as $row) { echo "{$row['1']} | {$row['2']} | {$row['3']}" . PHP_EOL; }
doc_23530775
In my models.py file, I have imported the necessary... from audit_log.models.fields import LastUserField, LastSessionKeyField class Transaction(models.Model): title = models.CharField(max_length=100) updated_by = LastUserField() update_session = LastSessionKeyField() This is exactly how they have implemented those fields in the documentation at https://django-audit-log.readthedocs.io/en/0.7.0/change_tracking.html#tracking-who-made-the-last-changes-to-a-model Hence I can't see what I'm doing wrong. Even when I update the updated_by field to include the on_delete argument, I get the same error when I try and make migrations. What am I missing?
doc_23530776
Im making an application for a friend, but when I run it, it gives me a warning, and recently started crashing. I tried debugging the problem, and it gave me a completely different problem. class DBApplication : DBInfo { private MySqlConnection connection = new MySqlConnection(); private int customer_id; public string lastname; //constructor public DBApplication() { OrderID(); } public string OrderID() { customer_id = 8; //add the DataBase query to the string. string query = "SELECT * FROM wdb_customer WHERE=" + customer_id; if (OpenConnection() == true) { MySqlCommand myComm = connection.CreateCommand(); MySqlDataReader Reader; myComm.CommandText = query; /*when I debugged, it said this was the problem? but i dont understand why.*/* Reader = myComm.ExecuteReader(); while (Reader.Read()) { lastname = Reader["customer_name"].ToString(); } Reader.Close(); } return lastname; } } the first problem "the variable DB_App is either undeclared or was never assigned." thats from this script. partial class Form1 { ... private DBApplication DB_App = new DBApplication(); ... private void InitializeComponent() { this.OrderID.Text = DB_App.lastname; } I have also tried DB_App.OrderID(); same problem. A: Your query is invalid since you miss a column name in WHERE clause To apply a quick fix change string query = "SELECT * FROM wdb_customer WHERE=" + customer_id; to string query = "SELECT * FROM wdb_customer WHERE customer_id = " + customer_id; ^^^ use real column name here On a side note: do not build SQL query strings directly from user input; use parameters instead. It prevents your code from SQL injections. Read more here This being said your code might look like this ... myComm.CommandText = "SELECT * FROM wdb_customer WHERE customer_id = @customer_id"; myComm.Parameters.AddWithValue("@customer_id", customer_id); Reader = myComm.ExecuteReader(); ...
doc_23530777
but without success!! Someone can help me, please? I'm testing the following code: let folders = view () { StorageBlobLogs | where TimeGenerated > ago(7d) | where OperationName has_any ("PutBlob", "PutBlock", "PutBlockList") | where Uri has_any ("landing") | where Uri !contains "catchall" and Uri !contains ".archive" and Uri !contains "azuretmpfolder" | extend feedSplit1 = tostring(split(Uri, "/2022/")\[0\]) | extend feedSplit2 = tostring(split(feedSplit1, "/landing/")\[1\]) // magic here | extend feedSplitF = replace_regex(feedSplit2, @"(\[\\/0-9\])","") // end of magic | extend feedSplit = tostring(split(Uri, '/')\[4\]) | extend feed = column_ifexists('feedSplit', "") | extend feed = iif(feed == 2022, "", feed) | extend feed = iif(feed == 'loganalytics-export', strcat(split(Uri, '/')\[5\], "/", split(Uri, '/')\[6\]), feed) | where TimeGenerated > ago(7d)} ; let Weekago = view () { folders | where TimeGenerated < ago(6d) | summarize countweekago = count() by folder }; let today = view () { folders | where TimeGenerated > ago(1d) | summarize counttoday = count() by folders }; countweekago | join today on $left.folder == $right.folders | project countweekago, counttoday, folders A: It should be "Weekago" and not "countweekago", "countweekago" is not declared
doc_23530778
I need to combine some NHibernate calls with a third-part library inside the same transaction. A: ISession.Connection returns the IDBConnection object. For the transaction see the blog post below. //http://ayende.com/blog/1583/i-hate-this-code private static IDbTransaction GetTransaction(ISession session) { using (var command = session.Connection.CreateCommand()) { session.Transaction.Enlist(command); return command.Transaction; } } A: We can start transaction inside of an NHibernate session, and easily get an access to DbConnection (could be casted even to SQL or Oracle one - if that makes sense). Then do the stuff with it and apply final commit/rollback: var session = ... // get an NHiberante ISession var transaction = session.BeginTransaction(); var conn = session.Connection; var dbConnection = conn as System.Data.Common.DbConnection; // do the stuff with DbConnection transaction.Commit(); // or transaction.Rollback();
doc_23530779
So what do I do now in order to try to submit this program to official debian repos? A: try persuading upstream to remove debian/ from their release-tarball, as mentioned here: If upstream has a debian directory in their releases, you should contact them and ask if they can remove the debian/ directory from their tarball releases. There's no need to remove the debian directory from their revision control system (although if it's out of date they may decide to do so anyway), but at the very least the directory shouldn't appear in releases. If you are upstream yourself, well, you can ask yourself to do it. If they don't want to do that, you should repackage the upstream tarball to exclude the debian/ directory, and use a slightly modified version. e.g. if upstream has released 1.666.3 then your re-packaged upstream tarball would be 1.666.3~repack0 (and the Debian package would have versions like 1.666.3~repack0-1).
doc_23530780
* *Split the file into smaller blobs *Upload the file parts, once all the parts are uploaded then make an API call and mark the item as upload completed. So far, I have been able to create an end-to-end poc, but I am trying to improve on my code to upload only n chunks at a time then proceed to next batch and wait until all chunks are uploaded. For the splitting logic I am using, bufferCount + forkJoin but I want to be able to call an API after all chunks are complete. Instead, it gets triggered after each batch completes. * *The next batch should not get triggered if the previous batch fails. const apiCallouts = parts.map((part, idx) => { const formData = new FormData(); formData.append('part', part); const opts = { ...baseOptions(this.conf) }; delete opts.headers['content-type']; return this.http.put(// Perform API Callout) }); const mergeObs = from(apiCallouts).pipe( bufferCount(5), concatMap(buffer => forkJoin(buffer)) ); What would be the best way to go about this? A: Instead, it gets triggered after each batch completes. I think for this you could use the toArray() operator: const mergeObs = from(apiCallouts).pipe( bufferCount(5), concatMap(buffer => forkJoin(buffer)), // `forkJoin` in this case will return an array. // So, we can use `mergeAll()` to explode the array. mergeAll(), // Accumulate everything and emit on `complete`. toArray(), ); The next batch should not get triggered if the previous batch fails. I'd say here it depends on what you want to happen if a batch fails. For example, if you want to end the entire stream, you could use something as follows: /* ... */ concatMap(buffer => forkJoin(buffer)), mergeAll(), toArray(), // `NEVER` will immediately emit a `complete` notification. // If you want your `next` callback to be called, you can replace `NEVER` // with something like `of('a message')`. // Note: `err` would come from `concatMap`'s inner observable. catchError(err => NEVER) Or you might want to retry only that specific batch that failed: /* */ bufferCount(5), concatMap( buffer => forkJoin(buffer).pipe( // Or, you could use `retryWhen` for more flexibility. retry(3), ) ), /* ... */
doc_23530781
One of the workbooks is my English one and the other a Spanish, I just need to find out what is in the English one that isn't in the Spanish one and vice versa. There is the same field called part_no in both tables A: If you want to avoid VBA, you can use the MATCH function. This function will return the location of the first argument in the array of the second argument. If it is not found MATCH will return NA. Hope this helps!
doc_23530782
My Command: awk 'BEGIN{found=1}NR==1,/^Match/{ if ( $0 == "PermitRootLogin yes" ) \ { found=0 } }END { exit found }' /etc/ssh/sshd_config A: awk '/^PermitRootLogin yes$/{f=1} /^Match/{exit} END{exit !f}' /etc/ssh/sshd_config A: Question @EdMorton I was after clarification on the use of '!f' in your solution and how this gives the correct exit 0 code? Specifically, what the negation '!' part is doing? UPDATE OK, I've finally wrapped my head around the exclamation mark on the awk exit code. For anyone else out there for whom this wasn't immediately obvious too, the way to think of the exclamation point is not as a negation but as an invert function. * *The truth is, gawk/awk returns EXIT_SUCCESS ('0') even if your regex does not match. Try it yourself. No match = no output but still shell exit code 0. Awk will however, perform a command based on whether the regex pattern is found or not, so we use that fact to perform a variable assignment ('f=1' in this case) if our conditions have been met. The conditions in my example below, are: - if NR is equal to line 6 AND the regex pattern is matched. *Here's the tricky part. Since EXIT_SUCCESS is a '0' for applications and we gave our flag variable f a numerical value of '1', we need to invert this number with the exclamation mark in front of the exit variable !f. Now we get a '0' exit code from awk if our regex pattern was successful and a '1' exit code if it did not match. One other observable truth worth mentioning here: Awk's default action on a regex pattern match is to print the whole line matching the pattern. Once we tell awk to perform a task, like setting a flag {f=1} or giving the {exit} command, awk no longer prints the matched regex pattern to stdout. Instead, awk now performs the task we told it to and quietly exits. TODO=~/Dropbox/todo.txt awk 'NR==6 && /due:[0-9]{4}-[0-9]{2}-[0-9]{2}/{exit;f=1} END {exit !f}' \ $TODO ; echo $? 0
doc_23530783
When I'm accessing http://www.google.de via curl and without squid the http header looks like this: curl -v http://www.google.de * Rebuilt URL to: http://www.google.de/ * Hostname was NOT found in DNS cache * Trying 172.217.17.67... * Connected to www.google.de (172.217.17.67) port 80 (#0) > GET / HTTP/1.1 > User-Agent: curl/7.37.0 > Host: www.google.de > Accept: */* > < HTTP/1.1 200 OK < Date: Mon, 17 Sep 2018 12:32:19 GMT ... When using squid it looks like this: curl -x http://127.0.0.1:3128 -v http://www.google.de * Rebuilt URL to: http://www.google.de/ * Hostname was NOT found in DNS cache * Trying 127.0.0.1... * Connected to 127.0.0.1 (127.0.0.1) port 3128 (#0) > GET http://www.google.de/ HTTP/1.1 > User-Agent: curl/7.37.0 > Host: www.google.de > Accept: */* > Proxy-Connection: Keep-Alive > < HTTP/1.1 200 OK < Date: Mon, 17 Sep 2018 12:19:22 GMT ... The GET seems to be rewritten. Now some services in the internet blocking requests with the full URL in the GET request. How can I configure squid (if it's possible) to let the GET untouched? Thanks in advance!! Regards, Matthias
doc_23530784
var counter = 0; kick(print); function kick(f) { setTimeout(function(){ f(); // problem here; kick(); }, 500); } function print(){ console.log(counter++); } Browser console gives following error: Uncaught TypeError: f is not a function How can I properly call f() at the required point? A: Pass f round again: function kick(f) { setTimeout(function(){ f(); // problem here; kick(f); }, 500); }
doc_23530785
Ex in C#: // Namespace X class A : B { public void methodA(){...} } // Namespace Y class B { public void methodB(){...} } In other code using A: using X; // do I need using Y? ... A obj = new A(); obj.methodB(); // calls methodB() using instance of A ... A: if A is in namespace X and B in Y, you can't do // Namespace X class A : B { ... }; you need to do: class A : Y::B { ... }; So you see you had to inherit B using the qualification and there's nothing special going on there. This is in C++ btw. If A needs anything more from Y it'll need to similarly qualify it. Anybody using A needs to qualify it with X::A or import everything or just A, depending, to use it - using X::A; or using namespace X;. That has no effect on what happens to the visibility of things inside Y though. The only thing that might surprise you is Koenig Lookup, so maybe read that. A: No namespaces are not inherited by classes in C++ (and in C#). However due to the ADL (Argument Dependent Lookup) you can "inherit" some names from the namespace of a base class. Here is a demonstrative program #include <iostream> namespace N1 { struct A {}; void f( const A & ) { std::cout << "N1::f( const A & )\n" << '\n'; } } namespace N2 { struct B : N1::A { B() { f( *this ); } }; } int main() { N2::B b; return 0; } Its output is N1::f( const A & ) To "inherit" a namespace you can use the using directive in a namespace or in a block scope. For example namespace N1 { struct A {}; } namespace N2 { using namespace N1; struct B : A { }; } Take into account that you may not use the using directive in a class scope. Or you can introduce only some names by means of a using declaration. A: Classes do not inherit namespaces. using only imports the symbols in a namespace into the current source file. It has no effect on your classes themselves. This C# code: using System; public class A { public void Run() { Console.WriteLine("Foobar"); } } Is completely equivalent in its effects, both in the CIL emitted as well as how users of A will use the class or derive it, to this code: public class A { public void Run() { System.Console.WriteLine("Foobar"); } } Let's say that we import a type that we return from a method: using System.IO; public class A { public Stream createStream() { // implementation irrelevant } } If we then declare class B : A in another source file, the createStream() method is inherited, and it still returns System.IO.Stream, even if the source file B is declared in doesn't have using System.IO, and users of class B do not need to import System.IO in order to use the stream returned by createStream(); the system knows the fully-qualified type is System.IO.Stream. public class B : A { public void doSomethingWithStream() { // We can use a System.IO.Stream object without importing System.IO using (var s = createStream()) { } } } public class C { public static void doSomethingElseWithStream(B b) { // As can other stuff that uses B. using (var s = b.createStream()) { } } } A: No, there is no such thing as a inherited namespace. Namespace does not have anything that can be derived/inherited. If you want to inherit a class A that is in different namespace, you need to add "using namespace ..."
doc_23530786
>>> import pandas as pd >>> df = pd.DataFrame([['a','a','b','b'],[6,7,8,9]]).T >>> df A B 0 a 6 1 a 7 2 b 8 3 b 9 The values of the column A shall be the column names of the new dataframe. The result of the transformation should look like this: a b 0 6 8 1 7 9 What I came up with so far didn't work completely: >>> pd.DataFrame({ k : df.loc[df['A'] == k, 'B'] for k in df['A'].unique() }) a b 0 6 NaN 1 7 NaN 2 NaN 8 3 NaN 9 Besides this being incorrect, I guess there probably is a more efficient way anyway. I'm just really having a hard time understanding how to handle things with pandas. A: You were almost there but you need the .values as the list of array and then provide the column names. pd.DataFrame(pd.DataFrame({ k : df.loc[df['A'] == k, 'B'].values for k in df['A'].unique() }), columns=df['A'].unique()) Output: a b 0 6 8 1 7 9 A: Using a dictionary comprehension with groupby: res = pd.DataFrame({col: vals.loc[:, 1].values for col, vals in df.groupby(0)}) print(res) a b 0 6 8 1 7 9 A: Use set_index, groupby, cumcount, and unstack: (df.set_index(['A', df.groupby('A').cumcount()])['B'] .unstack(0) .rename_axis([None], axis=1)) Output: a b 0 6 8 1 7 9
doc_23530787
models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass forms.py from django import forms from .models import User class RegisterForm(forms.ModelForm): username = forms.CharField(max_length=100, required=False) email = forms.EmailField(label='', max_length=100, widget=forms.TextInput(attrs={'placeholder': 'email@example.com'})) password = forms.CharField(label='', max_length=100, widget=forms.PasswordInput(attrs={'placeholder': 'Password'})) class Meta: model = User fields = ['username', 'email', 'password'] views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import RegisterForm def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() return redirect('trade') else: form = RegisterForm() return render(request, 'users/register.html', {'form': form}) AUTH_USER_MODEL = 'users.User' is set I tried to set email unique=True in models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): email = models.EmailField(unique=True) Now I get "The view users.views.register didn't return an HttpResponse object. It returned None instead" instead. Keep in mind that this is my first django project on my own :) Help is appriciated! EDIT with solution: Well I solved this. All answers are in django documentation(who would've tought). The problem is if your are new as I am to python and django reading the documentation about custom user model can be very overwhelming. Main goal was to set email as login method. To do that you would have to set USERNAME_FIELD = 'email' in your model. And to be able to do that you have to make your model based not on AbstractUser, but on AbstractBaseUser(https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#specifying-a-custom-user-model) and rewrite how you create users. Seemed pretty hard to me but django has a very nice example how to do that right at the end of documentation(https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#a-full-example). I just copied the code, replaced 'date_of_birth' with 'username' and got exactly what I wanted plus a little bit of understandig how things work on top of that. A: With regards the error "The view users.views.register didn't return an HttpResponse object. It returned None instead", this is happening because register doesn't return something in all of the flows. In the case where the request is a POST the first if statement is true, so that's the branch we're in. If the form is valid, all is good, but if it's not, nothing is returned. We don't enter the else part because that only happens when request isn't a POST you could fix it by doing the following: def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form.save() return redirect('trade') else: form = RegisterForm() return render(request, 'users/register.html', {'form': form}) This way, in all situations you return something. With regards the original error. Since you are inheriting from AbstractUser you are inheriting the username field and all the behaviours associated with it. In particular, it is still required to be unique. This is how it is defined in AbstractUser: username = models.CharField( _('username'), max_length=150, unique=True, help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) This is going to cause you problems if you are submitting blank values to your username. Your form will allow it, but it won't be allowed at the database level. There I would overwrite username, just add something like this: username = models.CharField( max_length=150, blank=True, )
doc_23530788
NoMethodError in Profiles#show Showing c:/Users/Rashed/Desktop/Ministry-Web-Application (new)/app/views/profiles/show.html.erb where line #17 raised: undefined method `company' for nil:NilClass The issue seems to be with my code on the show page to render the nested Experience fields, however I cant seem to figure out how to solve the issue, despite searching for ages for a solution. here is the code for my project: show.html.erb: <div class="row"> <div class="col-md-offset-1 col-md-8"> <p id="notice"><%= notice %></p> <p><strong>Full Name:</strong>&nbsp;&nbsp;<%= @profile.name %></p> <p><strong>Civil ID no:</strong>&nbsp;&nbsp;<%= @profile.civil %></p> <p><strong>Date of Employment:</strong>&nbsp;&nbsp;<%= @profile.date_of_employment %></p> <p><strong>Mobile no:</strong>&nbsp;&nbsp;<%= @profile.mobile %></p> <p><strong>Work Email:</strong>&nbsp;&nbsp;<%= @profile.work_email %></p> <p><strong>Personal Email</strong>&nbsp;&nbsp;<%= @profile.personal_email %></p> <p><strong>Internal no:</strong>&nbsp;&nbsp;<%= @profile.internal_no %></p> <p><strong>Nationality:</strong>&nbsp;&nbsp;<%= @profile.nationality %></p> <p><strong>Gender:</strong>&nbsp;&nbsp;<%= @profile.gender %></p> <p><strong>Academic Degree:</strong>&nbsp;&nbsp;<%= @profile.academic_degree %></p> <p><strong>Major:</strong>&nbsp;&nbsp;<%= @profile.major %></p> <p><strong>Company / Workplace</strong>&nbsp;&nbsp;<%= @experience.company %></p> <p><strong>Company / Workplace</strong>&nbsp;&nbsp;<%= @experience.period_of_employment %></p> <p><strong>Company / Workplace</strong>&nbsp;&nbsp;<%= @experience.title %></p> <%= link_to 'Edit', edit_profile_path(@profile) %> | <%= link_to 'Back', profiles_path %> </div> </div> profiles_controller.rb class ProfilesController < ApplicationController before_action :set_profile, only: [:show, :edit, :update, :destroy] respond_to :html def index @profiles = Profile.all respond_with(@profiles) end def show respond_with(@profile) end def new @profile = Profile.new @profile.experiences.build respond_with(@profile) end def edit end def create @profile = Profile.new(profile_params) @profile.user_id = current_user.id @profile.save respond_with(@profile) end def update @profile.update(profile_params) respond_with(@profile) end def destroy @profile.destroy respond_with(@profile) end private def set_profile @profile = Profile.find(params[:id]) end def profile_params params.require(:profile).permit(:name, :civil, :date_of_employment, :mobile, :work_email, :personal_email, :internal_no, :nationality, :gender, :academic_degree, :major, :work_experience, experiences_attributes: [:company, :period_of_employment, :title]) end end _form.html.erb <%= simple_form_for(@profile) do |f| %> <%= f.error_notification %> <div class="form-inputs"> <%= f.input :name, label: 'Full Name:' %> <%= f.input :civil, label: 'Civil ID:' %> <%= f.input :gender, collection: ['Male', 'Female'], label: 'Gender:', as: :radio_buttons, :include_blank => false %> <%= f.input :date_of_employment, label: 'Date of Employement:', as: :date, start_year: Date.today.year - 50, end_year: Date.today.year, order: [:day, :month, :year], input_html: { class: 'inline-date' } %> <%= f.input :mobile, label: 'Mobile no:' %> <%= f.input :work_email, label: 'Work Email:' %> <%= f.input :personal_email, label: 'Personal Email:' %> <%= f.input :internal_no, label: 'Internal no:' %> <%= f.input :nationality, collection: ['Kuwaiti', 'Non-Kuwaiti'], label: 'Nationality:', as: :radio_buttons, :include_blank => false %> <%= f.input :academic_degree, collection: ["Pre-Bachelor's Degree", "Diploma", "Bachelor's Degree", "Master's Degree", "Ph.D"], label: 'Academic Degree', as: :select, :include_blank => 'Choose Your Degree...' %> <%= f.input :major, collection: ["Architecture", "Civil Engineering", "Mechanical Engineering", "Chemical Engineering", "Computer Engineering", "Interior Designer", "Electrical Engineering", "Civil Engineering / Structure", "Administration"], label: 'Major', as: :select, :include_blank => 'Choose Your Major...' %> <%= f.input :nationality, collection: ['Kuwaiti', 'Non-Kuwaiti'], label: 'Nationality:', as: :radio_buttons, :include_blank => false %> <%= f.input :work_experience, collection: ['No', 'Yes'], label: 'Previous Work Experience?', as: :radio_buttons, :include_blank => false %> <%= f.simple_fields_for :experiences, Experience.new do |builder| %> <%= buidler.input :company %> <%= buidler.input :period_of_employment, label: 'Period of Employement:', as: :date, start_year: Date.today.year - 50, end_year: Date.today.year, order: [:day, :month, :year], input_html: { class: 'inline-date' } %> <%= builder.input :title, label: 'Job Title' %> <% end %> </div> <div class="form-actions"> <%= f.button :submit %> </div> <% end %> Experience Model: class Experience < ActiveRecord::Base belongs_to :profile end Profile Model: class Profile < ActiveRecord::Base belongs_to :users has_many :experiences accepts_nested_attributes_for :experiences end Thanks in advance! A: Each Profile has many Experiences so when you do @profile.experiences, it returns a collection and not a single record. You need to iterate over these and show them like this: <% @profile.experiences.each do |experience| do %> <p><strong>Company / Workplace</strong>&nbsp;&nbsp;<%= experience.company %></p> <p><strong>Company / Workplace</strong>&nbsp;&nbsp;<%= experience.period_of_employment %></p> <p><strong>Company / Workplace</strong>&nbsp;&nbsp;<%= experience.title %></p> <% end %> A: Could you try this <div class="row"> <div class="col-md-offset-1 col-md-8"> <p id="notice"><%= notice %></p> <p><strong>Full Name:</strong>&nbsp;&nbsp;<%= @profile.name %></p> <p><strong>Civil ID no:</strong>&nbsp;&nbsp;<%= @profile.civil %></p> <p><strong>Date of Employment:</strong>&nbsp;&nbsp;<%= @profile.date_of_employment %></p> <p><strong>Mobile no:</strong>&nbsp;&nbsp;<%= @profile.mobile %></p> <p><strong>Work Email:</strong>&nbsp;&nbsp;<%= @profile.work_email %></p> <p><strong>Personal Email</strong>&nbsp;&nbsp;<%= @profile.personal_email %></p> <p><strong>Internal no:</strong>&nbsp;&nbsp;<%= @profile.internal_no %></p> <p><strong>Nationality:</strong>&nbsp;&nbsp;<%= @profile.nationality %></p> <p><strong>Gender:</strong>&nbsp;&nbsp;<%= @profile.gender %></p> <p><strong>Academic Degree:</strong>&nbsp;&nbsp;<%= @profile.academic_degree %></p> <p><strong>Major:</strong>&nbsp;&nbsp;<%= @profile.major %></p> <% @profile.experiences.each do |experience| %> <p><strong>Company / Workplace</strong>&nbsp;&nbsp;<%= experience.try(:company) %></p> <p><strong>Company / Workplace</strong>&nbsp;&nbsp;<%= experience.try(:period_of_employment) %></p> <p><strong>Company / Workplace</strong>&nbsp;&nbsp;<%= experience.try(:title) %></p> <% end %> <%= link_to 'Edit', edit_profile_path(@profile) %> | <%= link_to 'Back', profiles_path %> </div> Hope it helps!
doc_23530789
A: When I registered for their service i was facing the same question, without an imminent answer on hand. So I wrote them on Twitter and got a response in about an hour, which stated that they will process my request imidiately. And they did. They created a batch just for me (the whole process from registration till the end implementation on my side was done in less than one day). thumbs up for their customer service! I have never seen better :) A: with monday being a holiday you might have an extra day to wait. have a little bit of patience, it is totally worth the wait. I migrated from BugSense to HockeyApp to Crashlytics. The fact that they're free is insane. I've got a couple feature requests in to them and they quickly got back to me and said that they have them on the roadmap. They're a cool group of people and were just scooped up by Twitter. Enjoy it.
doc_23530790
var counter=1; window.setInterval(function slide() { var imgCount = $("#afisha img").length; for (i=1; i <= imgCount; i++) { var Image = document.getElementById(i); counter = counter + 1; if(counter > imgCount){counter=1;} Image.src="images/afisha/img" + counter + ".jpg"; } if (counter==imgCount) counter=1; else counter = counter +1; },5000); Now I want to make a Pause button, when it's pressed it will stop the image to change. How do I achieve that? This is HTML: <div id="afisha"> <img src="images/afisha/img1.jpg" id="1" /> <img src="images/afisha/img2.jpg" id="2" /> <img src="images/afisha/img3.jpg" id="3" /> <img src="images/afisha/img4.jpg" id="4" /> <img src="images/afisha/img5.jpg" id="5" /> <img src="images/afisha/img6.jpg" id="6" /> <img src="images/afisha/img7.jpg" id="7" /> <img src="images/afisha/img8.jpg" id="8" /> <img src="images/afisha/img9.jpg" id="9" /> <div class="navigation"> <span class="previous" onclick="slideManuallyPrev()"></span> <span class="pause"></span> <span class="next" onclick="slideManuallyNext()"></span> </div> </div> EDIT : I've tried using clearInterval() method but it's not working. Where did I go wrong?: var pauseCount = 1; var timer=setInterval(slide,1000); function pauseSlider() { if ((pauseCount % 2) == 1) { clearInterval(timer); } else {var timer=setInterval(slide,1000);} pauseCount++; } span .pause onlick is pauseSlider(). UPDATE: Found my mistake: var keyword in the else condition. A: The simplest way would be to define a global variable, say var playing=true, change its value when the user presses pause, and then check inside the setTimeout's function if playing is true before continue (something like if(!playing) return;). Other way could be to stop the timer on pause and set it again on play (or pause again). It is possible to do the following: var timer=setInterval(slide,5000); Then stop it with: clearInterval(timer); And then set it again with the previous code. Note that just the function name is used as the setInterval's handler. A: You should consider storing the result of your setInterval() function within a variable. This will allow you to call the clearInterval() function whenever you elect to stop it : // Create your interval var interval = window.setInterval(function slide() { ... }, 5000); // Call this function when you want to stop it function pause(){ // Pause the interval clearInterval(interval); } Example You can see a complete example that demonstrating starting and stopping here and an example of what it looks like below : A: you can do it with css3 like this codepen http://codepen.io/mlegg10/pen/RaEpqq $(document).ready(function() { var icon = $('.play'); icon.click(function() { icon.toggleClass('active'); return false; }); }); $background:#f9f9f9; $foreground:#2c3e50; $foreground-light:#34495e; $size:25px; $ratio:1.2; $transition-time:0.3s; body { text-align:center; } .play { display:block; width: 0; height: 0; border-top: $size solid transparent; border-bottom: $size solid transparent; border-left: ($size*$ratio) solid $foreground; margin: ($size * 2) auto $size auto; position:relative; z-index:1; transition: all $transition-time; -webkit-transition: all $transition-time; -moz-transition: all $transition-time; left:($size*0.2); &:before { content:''; position:absolute; top:($size*-1.5); left:($size*-2.3); bottom:($size*-1.5); right:($size*-0.7); border-radius:50%; border: ($size*0.2) solid $foreground; z-index:2; transition: all $transition-time; -webkit-transition: all $transition-time; -moz-transition: all $transition-time; } &:after { content:''; opacity:0; transition: opacity ($transition-time * 2); -webkit-transition: opacity ($transition-time * 2); -moz-transition: opacity ($transition-time * 2); } &:hover, &:focus { &:before { transform: scale(1.1); -webkit-transform: scale(1.1); -moz-transform: scale(1.1); } } &.active { border-color:transparent; &:after { content:''; opacity:1; width:($size); height:($size*1.6); background:$foreground; position:absolute; right: ($size*0.1); top: ($size*-0.8); border-left:($size*0.4) solid $foreground; box-shadow:inset ($size*0.6) 0 0 0 $background; } } } h1 { text-transform:uppercase; color:$foreground-light; letter-spacing:2px; font-size:2em; margin-bottom:0; } .headline { display:block; color:$foreground; font-size:1.5em; margin-bottom:1.5em; } <a href="#" title="Play video" class="play"></a> <h1>CSS3 Play/Pause button</h1> <span class="headline">click/touch the button to see the animation.</span> A: you can do it with css3 like this codepen http://codepen.io/mlegg10/pen/RaEpqq EDIT: the inserted code below doesn't show here for some reason but works on the codepen link $(document).ready(function() { var icon = $('.play'); icon.click(function() { icon.toggleClass('active'); return false; }); }); $background:#f9f9f9; $foreground:#2c3e50; $foreground-light:#34495e; $size:25px; $ratio:1.2; $transition-time:0.3s; body { text-align:center; } .play { display:block; width: 0; height: 0; border-top: $size solid transparent; border-bottom: $size solid transparent; border-left: ($size*$ratio) solid $foreground; margin: ($size * 2) auto $size auto; position:relative; z-index:1; transition: all $transition-time; -webkit-transition: all $transition-time; -moz-transition: all $transition-time; left:($size*0.2); &:before { content:''; position:absolute; top:($size*-1.5); left:($size*-2.3); bottom:($size*-1.5); right:($size*-0.7); border-radius:50%; border: ($size*0.2) solid $foreground; z-index:2; transition: all $transition-time; -webkit-transition: all $transition-time; -moz-transition: all $transition-time; } &:after { content:''; opacity:0; transition: opacity ($transition-time * 2); -webkit-transition: opacity ($transition-time * 2); -moz-transition: opacity ($transition-time * 2); } &:hover, &:focus { &:before { transform: scale(1.1); -webkit-transform: scale(1.1); -moz-transform: scale(1.1); } } &.active { border-color:transparent; &:after { content:''; opacity:1; width:($size); height:($size*1.6); background:$foreground; position:absolute; right: ($size*0.1); top: ($size*-0.8); border-left:($size*0.4) solid $foreground; box-shadow:inset ($size*0.6) 0 0 0 $background; } } } h1 { text-transform:uppercase; color:$foreground-light; letter-spacing:2px; font-size:2em; margin-bottom:0; } .headline { display:block; color:$foreground; font-size:1.5em; margin-bottom:1.5em; } <a href="#" title="Play video" class="play"></a> <h1>CSS3 Play/Pause button</h1> <span class="headline">click/touch the button to see the animation.</span>
doc_23530791
A: The usual way to deal with this is checking out the branch feature/my-changes, then make the changes according to the review comments, create a new commit and push your branch. A: Yes.Since you have not yet merged the branch (also if it is merged) you can clearly make changes in the same branch and then commit and you can use the same Pull Request again for Review and merge.
doc_23530792
Mac OSX 10.6.8 ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0] and rubygems-1.8.9 But when I type in sudo gem install rails I get the following errors: ERROR: Error installing rails: ERROR: Failed to build gem native extension. /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby extconf.rb mkmf.rb can't find header files for ruby at /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/ruby.h Gem files will remain installed in /Library/Ruby/Gems/1.8/gems/bcrypt-ruby-3.0.1 for inspection. Results logged to /Library/Ruby/Gems/1.8/gems/bcrypt-ruby-3.0.1/ext/mri/gem_make.out Thank for your help. A: I think the rails-dev* libraries are missing. So, you can just install the "rails-dev*" libraries on your system and try again to install the rails gem. A: Are you using the system ruby? I suggest you: * *Install rvm *Install Ruby 1.9.2 using rvm *Install Ruby on Rails 3.1 Good luck A: You may want to use an open source pre-packaged Rails stack, like RubyStack (disclaimer, I am one of the developers). It is basically an all-in-one installer package, so there is nothing to compile / install (it can as easily be removed) A: You should check the log files that it pushes errors to, but it's more than likely that various gcc libraries are missing. [Re]Install XCode and try again.
doc_23530793
http://listings.myrealpage.com/wps/recip/25064/m.form It just sits there and tried to load. I do get one error saying this Uncaught SecurityError: Blocked a frame with origin "http://listings.myrealpage.com" from accessing a frame with origin "MYSITE". Protocols, domains, and ports must match. I'm not really understanding that because all the other links contain the same listings.myrealpage in them and work fine. The code I have for the iFrame is this <iframe src="LINK" name="frame2" scrolling="auto" frameborder="no" height="800px" width="100%"> </iframe> That's the same too for all the others but replacing the src part with the other links. Hopefully there's an answer for this. Thanks A: That error message is due to the same-origin-policy Usually, this is sent in a HTTP header and causes the browser to deny a load of IFRAME content unless there's an exact match of port, protocol and domain. E.g. port - usually 443 for SSL, or 80 if standard HTTP - protocol (http for parent page and iframe, or https for both) and domain (blah.domain.com and blah2.domain.com would be a non-match) Either remove the restriction of the same-origin-policy (you may not be able to do this if you do not govern the server), or, satisfy it. Then, you'll be able to render that content within a frame. You could use something like Fiddler to determine the erroneous url (It's free to download from Telerik) and where the request occurs.
doc_23530794
i need the code to be by using JavaScript and i don't want any jquery because i did part of it before with jquery with this $.get('some website ', function(data) { $('.result').html(data); alert('Load was performed.'); }); but i want JavaScript code to get the html from link which i want to define it inside the code for example i have website like www.something.com/page.html and i need to take the sourse code of page.html and inject it inside popup.html that mean the extension will show me page.html i hope that wanna be good explanation A: This should do the trick, but be aware of the security implications of injecting a bunch of HTML into another document -- it's an easy way to cause XSS: var element = ... // some element in your popup.html document var request = new XMLHttpRequest(); request.onload = function() { element.innerHTML = this.responseText; }; request.open("get", "http://www.some.com/page.html", true); request.send(); You'll also need to add a permission to your manifest to allow your extension to do cross-site XHRs to "http://www.some.com". Assuming no other permissions: "permissions": [ "http://www.somecom/" ], From a security POV, it makes more sense to just ask some.com for JSON data, parse that through JSON.parse() and then build whatever UI you need in the Chrome extension. Makes your extension also more stable/flexible because all UI is contained in the Chrome extension, not spread across extension and some.com. Alternatively, if page.html is sufficiently static, bundle it into your extension and inject it with a code snippet similar to the one above, but use chrome.extension.getUrl('page.html') as the URL for request.open(). Regardless of whether your page.html comes from another site or from within the extension, you might need to fix relative URLs of images, scripts, style sheets (Chrome won't do this for you here), e.g. by prefixing their src/href attributes with http://www.some.com/ to point them to the intended resources again.
doc_23530795
If you visit this page on a regular display driven by a color-managed OS' (iOS 9.3+, macOS), many of the images look different between sRGB and the alternate gamut image. Why do they differ? To my eyes, they differ in the same way on a wide-gamut display (iMac 27" retina, iPad Pro) - the oranges and reds are boosted. So it seems having a wide-gamut display isn't adding much. I would have guessed the wide-gamut images would be color-sync'd "down" to be indistinguishable from the sRGB version. So why is a difference very apparent? A: In a color-managed workflow the input source profile will be converted to the display profile to display images regardless of whether the input is sRGB or something wider like AdobeRGB. If the input space is smaller than the display space then there should not be any change in the perceived color. If the input space is larger, then the conversion will use some sort of rendering intent to try to map (or clip) the gamut of the input space to the screen space. The reason the sRGB images look different than the wider profile images is because the gamut of your monitor is different than sRGB. Regular gamut monitors are not sRGB monitors - they might be similar, but there are not the same. If you are using a relatively new monitor, theres a good chance that it's gamut will extend beyond sRGB in certain areas. So when you convert from a wide space to your screen's space you'll likely see colors that are still out of the sRGB gamut, but within your display's
doc_23530796
values := []int64{143, 123, 123, 542....} // ~10,000 elements query, args, err := sqlx.In(query, values) if err != nil { return nil, err } query = dbInterface.Rebind(query) err = dbInterface.Select(&list, query, args...) Query: SELECT * FROM table_name WHERE some_id IN (?) ORDER BY created_at; A: You need to make sqlx produce one of these: * *the values syntax: where some_id in (values (143), (123)) *join an array: select * from t inner join unnest(array[143, 123]) u (id) on u.id = t.id A: I ultimately created a TEMP TABLE for the ids and performed a JOIN. This greatly improved the query performance.
doc_23530797
I know I can do this in SQL but i'm trying to do it in scala select (case when x = y then x else concat(x + ". " + y) end) as match from test in scala df.select(when(col("x") == col("y"), col("x") ) .otherwise(concat(col("x"),lit('. '), col("y"))) .as("match")) I get the following error when i test error: type mismatch; found : Boolean required: org.apache.spark.sql.Column A: Use === instead of == for equality checks on scala spark. df.select(when(col("x") === col("y"), col("x") ) .otherwise(concat(col("x"),lit('. '), col("y"))) .as("match")) A: This is more of a spark question than a scala question. You should be using === instead of ==.
doc_23530798
For example: See categories box A: This is all you need: http://blog.yjl.im/2010/01/stick-div-at-top-after-scrolling.html A: in your css write #my-box { position: fixed; } it will probably move it from the center so you will have to do some math if it is a fixed width and height box like #my-box-fixed { position: fixed; width:200px; height: 150px; top: 50%; left: 50%; margin-left: -100px; // half of the width margin-top: -75px; // half of the height } A: Also, in javascript you can do: document.getElementById("my-box-fixed").style.position = "fixed"; A: you can do it whit jquery: $().ready(function () { var $scrollingDiv = $("#YouDivID"); $(window).scroll(function () { $scrollingDiv .stop() .animate({ "marginTop": ($(window).scrollTop() + 5) + "px" }, "1000"); }); });
doc_23530799
I am using this: http://www.devx.com/webdev/Article/10483/0/page/2 to create a multipage form using visibility and div sections. Seems to work very well. I now need to be able to print (printer) one page from another page. Possible? I'm trying to use the printThis plugin by Jason Day. I am calling the plugin like so: $.getScript("printThis.js", function(){ }); (plugin is in the current directory...will address that later) <input type="button" id="B1" value="Go Back" onClick="showLayer('page1')"> <input type="button" id="B2" value="Print App" onClick="$("#page1").printThis()"> First button works as expected...goes back to page1 Second button does nothing...is syntax right? Or am I just trying to do something that can't be done? A: Your first button is correct. The second button is not however. Your double quotes " within your jQuery selector is causing the onClick attribute to close prematurely. Try one of the following methods: Inline Option 1 - Escape Double Quotes <input type="button" id="B2" value="Print App" onClick="$(\"#page1\").printThis()"> Inline Option 2 - Use Single Quotes <input type="button" id="B2" value="Print App" onClick="$('#page1').printThis()"> Option 3 - Remove Obtrusive JavaScript (Strongly Recommended) <!-- Place this code in the <head></head> section of your page --> <script type="text/javascript"> $(document).ready(function () { $('#B2').on('click', function () { $('#page1').printThis(); }); }); </script>