text
stringlengths
15
59.8k
meta
dict
Q: Ruby thread safe thread creation I came across this bit of code today: @thread ||= Thread.new do # this thread should only spin up once end It is being called by multiple threads. I was worried that if multiple threads are calling this code that you could have multiple threads created since @thread access is not synchronized. However, I was told that this could not happen because of the Global Interpreter Lock. I did a little bit of reading about threads in Ruby and it seems like individual threads that are running Ruby code can get preempted by other threads. If this is the case, couldn't you have an interleaving like this: Thread A Thread B ======== ======== Read from @thread . Thread.New . [Thread A preempted] . . Read from @thread . Thread.New . Write to @thread Write to @thread Additionally, since access to @thread is not synchronized are writes to @thread guaranteed to be visible to all other threads? The memory models of other languages I've used in the past do not guarantee visibility of writes to memory unless you synchronize access to that memory using atomics, mutexes, etc. I'm still learning Ruby and realize I have a long way to go to understanding concurrency in Ruby. Any help on this would be super appreciated! A: You need a mutex. Essentially the only thing the GIL protects you from is accessing uninitialized memory. If something in Ruby could be well-defined without being atomic, you should not assume it is atomic. A simple example to show that your example ordering is possible. I get the "double set" message every time I run it: $global = nil $thread = nil threads = [] threads = Array.new(1000) do Thread.new do sleep 1 $thread ||= Thread.new do if $global warn "double set!" else $global = true end end end end threads.each(&:join)
{ "language": "en", "url": "https://stackoverflow.com/questions/57660980", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Spotify API device list empty after short inactivity period I'm trying to use the Spotify API for a personal project. My problem is that the "devices" endpoint that normally returns a list of my available devices (my phone) returns an empty array if I swipe out of the Spotify app for a short while before requesting the device list. For example: I open the Spotify app in my phone. I send a Postman request to the "devices" endpoint of the Spotify API and confirm that my phone is listed as an available device for playback. I then swipe out of the Spotify app, into another app and click around there for 30 seconds or so. I then send the same Postman request to the "devices" endpoint and receive an empty array. My phone is immediately forgotten after a short period of inactivity in the Spotify app, and thus any requests to play a song etc. fail since no available device is found. Has anyone managed to force their device to stay on the API's radar, or found a way to "wake" their device before sending a request that targets it to the API? I am currently using iOS. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/72955341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android Polyline - Adding point by point I'm currently having a map, and each 10 meters I use LocationListener to refresh my location and get the new Latitude and Longitude. Now I wish that the route the user is taking will be displayed with a red line. So everytime the OnLocationChange() from LocationListener class is called, I want to update the map with a line between the last location and the new location. So far I've added the following: private void initializeDraw() { lineOptions = new PolylineOptions().width(5).color(Color.RED); lineRoute = workoutMap.addPolyline(lineOptions); } during the OnLocationChanged I call this: drawTrail(); now what should I insert into this function so that each time it adds the newly attained location as a point and draws a line from the last to the new point. Thanks A: First translate Location into LatLng: LatLng newPoint = new LatLng(location.getLatitude(), location.getLongitude()); Then add a point to existing list of points: List<LatLng> points = lineRoute.getPoints(); points.add(newPoint); lineRoute.setPoints(points);
{ "language": "en", "url": "https://stackoverflow.com/questions/17157454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to get the current (working) directory in Scala? How can I get the current directory (working directory) of the executing program in Scala? A: Use this: import scala.reflect.io.File File(".").toAbsolute A: I use new java.io.File(".").getAbsolutePath, but all the other answers work too. You don't really gain anything by using Scala-specific API here over regular Java APIs A: import scala.sys.process._ val cwd = "pwd".!! //*nix OS A: Use this System.getProperty("user.dir") Edit: A list of other standard properties can be found here. https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html A: Use java.nio: import java.nio.file.Paths println(Paths.get(".").toAbsolutePath) Remark on scala.reflect.io.File: I don't see any reason to look into scala.reflect packages for such mundane tasks. Getting the current working directory has usually nothing to do with Scala's reflection capabilities. Here are more reasons not to use scala.reflect.io.File: link. A: os-lib makes it easy to get the current working directory and perform other filesystem operations. Here's how to get the current directory: os.pwd It's easy to build other path objects from os.pwd, for example: os.pwd/"src"/"test"/"resources"/"people.csv" The syntax is intuitive and easy to remember, unlike the other options. See here for more details on how to use the os-lib project.
{ "language": "en", "url": "https://stackoverflow.com/questions/49859866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Colspan in Backendlayout not working (TYPO3 8.7 LTS) The 3 columns in my backendlayout should be equal size, independent of their content. In my case their width get determined by their content though. Glad about any hints! Environment: * *TYPO3 8.7.0 *PHP 7.0.13 *MySQL 5.6.34 Installed Extensions: * *gridelements dev-master c5120b0e *realurl 2.2.0 *slickcarousel 8.x-dev *vhs 4.1.0 The TS was generated using the wizard. It is a 3 columns layout with 2 rows. The second row has 3 cols (colspan = 1) and the first one has 1 col (colspan = 3). mod.web_layout.BackendLayouts { MainTemplate { title = MainTemplate name = MainTemplate icon = EXT:amtemplate/ext_icon.png config { backend_layout { colCount = 6 rowCount = 2 rows { 1 { columns { 1 { name = LLL:EXT:amtemplate/Resources/Private/Language/locallang.xlf:amtemplate_be_layout_maintemplate.sliderarea colPos = 1 colspan = 6 } } } 2 { columns { 1 { name = LLL:EXT:amtemplate/Resources/Private/Language/locallang.xlf:amtemplate_be_layout_maintemplate.left colPos = 2 colspan = 2 } 2 { name = LLL:EXT:amtemplate/Resources/Private/Language/locallang.xlf:amtemplate_be_layout_maintemplate.main_content colPos = 0 colspan = 2 } 3 { name = LLL:EXT:amtemplate/Resources/Private/Language/locallang.xlf:amtemplate_be_layout_maintemplate.right colPos = 3 colspan = 2 } } } } } } } } A: Worked here in 8.7.1 without any problems. Maybe you wann update to the latest release? A: There are two different concepts you are mixing up here, namely colspan and width. The colspan attribute is used to tell a cell of a table how many of the other cells of another row it should overlap. So this has nothing to do with fixed widths even though it might feel like that, when you got the same content in each cell or no content at all. As soon as you fill the table cells with different content, the width of each cell might differ even though some of these cells might use the same colspan value. So colspan actually just defines the relation between the cells but not their width. Still the core somehow circumvents that behaviour by applying min and max width values to several parts of the page module via CSS, so the cells will stay within a certain width range. Now that you have installed gridelements, there can not be such a range anymore, because there might be nested grid structures that have to consume way more space. So gridelements uses a CSS removing that range and thereby restores the default behaviour of HTML table cells.
{ "language": "en", "url": "https://stackoverflow.com/questions/43539314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android OpenGL ES app crashes logging back in I'm using OpenGL ES 2.0 on Android to make a basic game. I discovered that if I hit the home key on my device (emulator or real device) when the GLSurfaceView is present and then log back into the app from the Android home screen the app will crash. In contrast, if I I hit the back key while the GLSurfaceView is present which then takes me back to my MainActivity / MainView then everything is fine. I assume this has to do with how the GL Thread is managed, and when I close the app immediately the state is saved as opposed to being popped off the activity stack like when I hit the back button to go to my MainActivity. My question is how should I best deal with destroying the GLSurfaceView state information? If the user hits the home key I want the information to reset and not be saved. Should I override onStop in the class that implements GLSurfaceView.Renderer and delete the GLSL program? I can give a rough picture of how my activites are laid out below. MainActivity class: public MainActivity extends Activity GameView view; public onCreate ( ... ) { } GameView class: public GameView extends GLSurfaceView Renderer renderer; public onCreate (...) { // set EGL information and renderer }; Renderer class: public Renderer implements GLSurfaceView.Renderer // implements the surface change, created, and draw methods A: Make sure that your android version supports OpenGL ES 2.0 rendering on it's background state. Because whenever you press the home key app enters background state and gives background thread for your application, that may cause crashes. Mostly in iOS and android it is best to identify the app state and pause the rendering in background state. Refer further in this link Run Android OpenGL in Background as Rendering Resource for App? A: I found out that I needed to override the 'onSurfaceDestroyed( SurfaceHandle handle) method in the class that extends GLSurfaceView and clean up my resources. @Override public void surfaceDestroyed(SurfaceHolder holder) { super.surfaceDestroyed(holder); ResourceManager.getInstance().cleanUp(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/28975856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Update a MYSQL Column Based On Varying Conditions I need to update a MYSQL Table Here is a very simple look at Table_A ID VALUE RESULT 1 4 0 2 2 0 3 7 0 I want to update the RESULT Column based on conditions So my query statement needs to look something like UPDATE Tabel_A SET RESULT = (if some condition) 1 OR (if another condition) 2 OR (if a different condition) 3 Or should I use something like UPDATE Tabel_A SET RESULT = (CASE 1) 1 (CASE 2) 2 (CASE 3) 3 I am not sure how to structure the query Thanks A: I'll prefer to use CASE here. UPDATE TAble1 SET Result = CASE value WHEN 1 THEN x WHEN 2 THEN y .... ELSE z END or UPDATE TAble1 SET Result = CASE WHEN value = 1 THEN x WHEN value = 2 THEN y .... ELSE z END
{ "language": "en", "url": "https://stackoverflow.com/questions/14672688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: [Android - Kitkat ]Get/pick an image from Android's built-in Gallery app programmatically Try to pick only one particular image from the SD card.I am able to pick images from gallery and Photos app in kikat.But not getting file path when i pick image from recents am getting file path as null. I tried https://stackoverflow.com/a/2636538/1140321. A: This works for Kitkat public class BrowsePictureActivity extends Activity{ private static final int SELECT_PICTURE = 1; private String selectedImagePath; private ImageView imageView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.browsepicture); imageView = (ImageView)findViewById(R.id.imageView1); ((Button) findViewById(R.id.button1)) .setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE); } }); } public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (requestCode == SELECT_PICTURE) { Uri selectedImageUri = data.getData(); if (Build.VERSION.SDK_INT < 19) { selectedImagePath = getPath(selectedImageUri); Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath); imageView.setImageBitmap(bitmap); } else { ParcelFileDescriptor parcelFileDescriptor; try { parcelFileDescriptor = getContentResolver().openFileDescriptor(selectedImageUri, "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor); parcelFileDescriptor.close(); imageView.setImageBitmap(image); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } /** * helper to retrieve the path of an image URI */ public String getPath(Uri uri) { if( uri == null ) { return null; } String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(uri, projection, null, null, null); if( cursor != null ){ int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } return uri.getPath(); } } You need to add permission <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
{ "language": "en", "url": "https://stackoverflow.com/questions/20514973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: only rotate button and not it's text on button click I rotate a button on click: <button class="btn" type="button">Go</button> css: .btn:focus { transform: rotate(180deg); } now the problem is txt also rotates on btn click. How can I don't rotate the txt or rotate it 360 on button click? A: Wrap the button text in a span, and rotate that on :focus of the button by another 180 degree: .btn:focus { transform: rotate(180deg); } .btn:focus span { display: inline-block; transform: rotate(180deg); } <button class="btn" type="button"><span>Go</span></button> A: Wrap the text with a span and rotate it to the other direction: .btn:focus { transform: rotate(180deg); } .btn:focus > span { display: block; transform: rotate(-180deg); } <button class="btn" type="button"> <span>Go</span> </button>
{ "language": "en", "url": "https://stackoverflow.com/questions/52707370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SiteMapPath not working with route attribute in nodes I have this xml sitemap: <?xml version="1.0" encoding="utf-8" ?> <mvcSiteMap xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-4.0" xsi:schemaLocation="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-4.0 MvcSiteMapSchema.xsd"> <mvcSiteMapNode title="Home" controller="Home" action="Index" key="home"> <mvcSiteMapNode title="Access Control" route="AccessControl_default" controller="Home" action="Index" key="access-control"> <mvcSiteMapNode title="My dashboard" route="AccessControl_default" controller="Dashboard" action="Index" key="dashboard"/> <mvcSiteMapNode title="Personnel" route="AccessControl_default" clickable="false" key="personnel"> <mvcSiteMapNode title="Groups" route="AccessControl_default" controller="Personnel" action="Groups" key="groups"/> <mvcSiteMapNode title="Members" route="AccessControl_default" controller="Personnel" action="People" key="people"/> </mvcSiteMapNode> </mvcSiteMapNode> </mvcSiteMapNode> </mvcSiteMap> This is the targeted route defined in area route configuration: context.MapRoute( "AccessControl_default", "accesscontrol/{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }, new[] { "UI.WebPortal.Areas.AccessControl.Controllers" } ); Then navigation menu tree is shown with @Html.MvcSiteMap().SiteMap() but breadcrumb is not working when using @Html.MvcSiteMap().SiteMapPath(). Is it because I'm using routing explicitly? and what could be the solution? A: While you use areas, just add area="...." to nodes under them. ... <mvcSiteMapNode title="Groups" route="AccessControl_default" area="AccessControl" controller="Personnel" action="Groups" key="groups"/> ...
{ "language": "en", "url": "https://stackoverflow.com/questions/31563724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iPhone -- [UITextField sizeToFit] does not always account for cursor When I call sizeToFit on a UITextfield that is being edited, the size reacts in an inconsistent way to the cursor. Sometimes it accounts for it; sometimes it doesn't. If it doesn't, part of the first letter is clipped. Has anyone found a way around this? A: I just ran into this problem (it's fixed in iOS 5). My solution was to add a 4-point padding to the width: [textField_ sizeToFit]; textField_.frame = CGRectMake(textField_.frame.origin.x, textField_.frame.origin.y, CGRectGetWidth(textField_.frame) + 4, CGRectGetHeight(textField_.frame)); A bit tedious but got the job done for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/4016038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mismatch between the processor architecture I have an issue with these two famous warnings which are raised during compilation of our solution. There are many forums about these already and I read those, but they still don't solve my issue completely... 1. There was a mismatch between the processor architecture of the project being built "MSIL" and the processor architecture of the reference "XXX", "AMD64". This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project. 2. Referenced assembly 'XXX' targets a different processor than the application. The reason why these appear in our case is clear. Our solution is compiled as AnyCPU and we want to keep it this way, as we do not want to compile it twice (once as x86 and second as x64). However, we use external DLL which is either x86 or x64 (it is not delivered as AnyCPU). We develop the application on 64bit windows, so we use the x64 DLL version as reference in the visual studio during development. When we deliver the application to end-users, the installer is customized to copy the proper DLL based on the platform of the target system, e.g. when it is installed on 64bit windows, it copies the x64 DLL version and when it is installed on 32bit windows, it copies the x86 DLL version. Therefore, we know that everything is finally ok, and we can ignore those messages. And therefore, I just want to make them disappear:-) The first warning can be supressed by the following tag in the project file: <PropertyGroup> <ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch>None</ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch> </PropertyGroup> But I did not find anywhere how to get rid of the other message? Is this possible as well? I know that this is just small issue and I can live with that. However, there is something like "Warning Free Build Initiative" going on in my company, so I'd like to get rid of all warnings we have. Thank you in advance for any hints, Tomas
{ "language": "en", "url": "https://stackoverflow.com/questions/32141358", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Delete AWS Cloud formation stack with resources created by it Based on this page I can do: aws cloudformation delete-stack \ --stack-name my-stack It says I can attach the command: [--retain-resources <value>] Does that mean that if I don't specify that line, all the resources created by the stack will be removed? I'm trying to delete everything generated by the stack, which is a lot. How can I achieve this? Thanks A: Yes, those resources will be kept if you specify the [--retain-resources <value>], if you dont Cloudformation will delete all the resources in the stack name (including the nested stacks as well) you are providing given you have permissions to do. If any of the resources inside the cloudformation stack has retain policy set they won't be deleted. During deletion, AWS CloudFormation deletes the stack but does not delete the retained resources. From the same page aws cloudformation delete-stack You might wanna read this too How do I retain some of my resources when I delete an AWS CloudFormation stack? You can specify the retain policy as well in cloudformation template.
{ "language": "en", "url": "https://stackoverflow.com/questions/65762063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: What does this error "Thread 1: EXC_BAD_ACCESS (code=2, address=0x30d51fff8)" mean? How do I fix it import UIKit class ViewController: UIViewController { @IBOutlet weak var triviaLabel: UILabel! @IBOutlet weak var trueButton: UIButton! @IBOutlet weak var falseButton: UIButton! @IBOutlet weak var progressBar: UIProgressView! var quiz = [Question(text: "Blah blah", answer: "True"), Question(text: "Ha ha", answer: "True"),Question(text: "Bruh bruh", answer: "False")] var questionNumber = 0 override func viewDidLoad() { super.viewDidLoad() updateQuestion() } @IBAction func answerButtonPressed(_ sender: UIButton) { let userAnswer = sender.currentTitle let actualAnswer = quiz[questionNumber].answer if userAnswer == actualAnswer { } else { } if questionNumber < quiz.count-1 { questionNumber += 1 }else { questionNumber = 0 } updateQuestion() } func updateQuestion() { triviaLabel.text = quiz[questionNumber].text // Get the error here updateQuestion() } } The build succeeds and the app launches but there comes a blank screen and the error occurs. I tried mapping the label again with the storyboard. I speculate that there is some problem with the label declaration or connection.
{ "language": "en", "url": "https://stackoverflow.com/questions/75044756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Should Context be injected with Dagger? I know it is possible to inject Context with Dagger. We can see examples here and here. On the other end, there are numerous posts about not placing context on a static variable to avoid leaks. Android Studio (lint) also warms about this: Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run) I understand that by injecting a Context with Dagger, we are placing it on a singleton class, so context is somehow static. Doesn't this go against the lint warning? Injecting the context seems to create cleaner code, since you don't have to pass it to several classes (that don't need it) so that they can further pass it to other classes that need it for some reason (getting a resource for instance). I am just concerned that this may cause some undesired leak or breaks lint in some way. A: You should never store/reference activity context (an activity is a context) for longer than the lifetime of the activity otherwise, as you rightly say, your app will leak memory. Application context has the lifetime​ of the app on the other hand so is safe to store/reference in singletons. Access application context via context.getApplicationContext(). A: If you are aware of Android lifecycles and are careful to distinguish the Application Context and the Context of Activities and Services then there is no fault injecting the Context using Dagger 2. If you are worried about the possibility of a memory leak you can use assertions to prevent injection of the wrong Context: public class MyActivityHelper { private final Context context; @Inject public MyActivityHelper (Context context) { if (context instanceof Application) { throw new IllegalArgumentExecption("MyActivityHelper requires an Activity context"); } } } Alternatively you could use Dagger 2 Qualifiers to distinguish the two so you don't accidentally inject an app Context where an Activity Context is required. Then your constructor would look something like this: @Inject public class MyActivityHelper (@Named("activity") Context context) { Note also, as per David's comment, a Dagger 2 @Singelton is not necessarily a static reference.
{ "language": "en", "url": "https://stackoverflow.com/questions/44357735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Can a factory method pattern use different overloads I have a use case where I need to build a factory class that returns different concrete types based on an enum being passed. However, each of those types require different constructor parameters. So, in that case does it make sense to have multiple methods with different signatures, or is that not a factory pattern at all? I'm thinking something like class CarFactory { public ModelS TeslaMaker (List<Battery> batteries){/*return ModelS*/} public Mustang FordMaker (Engine engine) {/*return a Mustang*/} } instead of say class CarFactory { public Car GetCar(CarType carType) //where CarType is an enum (Ford=0,Tesla=1) { switch(carType) { case CarType.Ford: return new Mustang(); }//just an example } } EDIT: In my case I actually need to return a family of classes. So, if it's a Tesla, return a ModelS, a ModelSService, ModelSWarranty, etc. So I'm going to go with the Abstract Factory approach which will wrap the suggestions given here. A: So, in that case does it make sense to have multiple methods with different signatures, or is that not a factory pattern at all? It doesn't make any sense to have a factory with specific methods. If your client code has to decide which specific method should it use, why wouldn't it call the specific car's constructor directly? In your example, factory methods would merely be wrappers over specific constructors. On the other hand having a single factory method that is called with an enum gives your client a chance to decide dynamically which car should it create, the decision could for example be based on a database query. There are some possible ways around your current approach. One option would be to have a hierarchy of classes that represent constructor parameters. You don't even need the enum then because the parameter type is enough to infer which specific car should be created: public abstract class CarCreationParams { } public class FordCreationParams : CarCreationParams { public Engine engine; } ... public class CarFactory { public Car GetCar( CarCreationParams parms ) { if ( parms is FordCreationParams ) return new Ford( ((FordCreationParams)parms).engine ); ... Another option would be to think whether you really need your Fords to be created with external engines (aggregation) or rather they own their engines (composition). In the latter case, you would expose parameterless constructors to your specific car types: public class Ford : Car { public Engine engine; // car is composed of multiple parts, including the engine public Ford() { this.engine = new FordEngine(); } which makes the implementation of the factory much easier. A: No that is not a good example of factor pattern. Rather if your Car class is dependent on different types of Components you can have factories for those too. E.G For Car and Engine you can have like: public interface ICar { IEngine Engine { get; set; } } public class Mustang : ICar { private IEngine _engine = EngineFactory.GetEngine(EngineType.Mustang); public IEngine Engine { get { return _engine; } set { _engine = value; } } } public class CarFactory { public ICar GetCar(CarType carType) { switch (carType) { case CarType.Ford: return new Mustang(); } } } Similarly for Engine public interface IEngine { } public class MustangEngine : IEngine { } public class EngineFactory { public static IEngine GetEngine(EngineType engine) { switch (engine) { case EngineType.Mustang: return new MustangEngine(); } } } A: In case you need different parameters for object creation(batteries for Tesla or Engine for Ford) you can choose between different solutions: - pass all of these parameters while creating a factory - it will be specific factory for all types of car with such available details; class SpecificCarFactory { public SpecificCarFactory(IList<Battery> batteries, IList<Engine> engines) { //save batteries etc into local properties } public Car GetCar(CarType carType) { switch(carType) { case CarType.Ford: return new Mustang(_engines.First()); } } } * *encapsulate parameters into class object and get them from factory method parameter; class CarFactory { public Car GetCar(CarDetail carDetail) //where CarDetails encapsulates all the possible car details { switch(carDetail.type) { case CarType.Ford: return new Mustang(carDetail.Engine);//just an example } } } A: Yes, It is factory pattern. factory pattern says to create factories of Object but let subclass decide the way to instantiate the object . This is true in your case your deciding based on type of Enum
{ "language": "en", "url": "https://stackoverflow.com/questions/36787091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set/remove attributes dynamically in c#? I am using from attribute validation in my project. [Required(ErrorMessage = "DepartmentCode is Required")] public string DepartmentCode { get; set; } In some case DepartmentCode isn't required. How can I dynamically ignore Validation in my case? A: Take a look at: Remove C# attribute of a property dynamically Anyway I think the proper solution is to inherit an attribute from RequiredAttribute and override the Validate() method (so you can check when that field is required or not). You may check CompareAttribute implementation if you want to keep client side validation working. A: Instead of dynamically adding and removing validation, you would be better served to create an attribute that better serves this purpose. The following article demonstrates this (MVC3 with client-side validation too): http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx A: I would remove the RequiredAttribute from your model and check it once you've hit your controller and check it against whatever causes it to not be required. If it falls into a case where it is required and the value is not filled in, add the error to the ModelState manually ModelState.AddModelError("DepartmantCode", "DepartmantCode is Required"); You would just lose the validation on the client side this way A: I've got round this issue in the model, in some cases it's not ideal but it's the cheapest and quickest way. public string NonMandatoryDepartmentCode { get { return DepartmentCode; } set { DepartmentCode = value; } } I used this approach for MVC when a base model I inherited contained attributes I wanted to override.
{ "language": "en", "url": "https://stackoverflow.com/questions/9380321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Why do Spark jobs require so much memory? I am experiencing memory issues when running PySpark jobs on our cluster with YARN. YARN keeps killing my executors for running out of memory, no matter how much memory I give them, and I cannot understand the reason for that. Example screenshot: Screenshot from SparkUI The amount of data that one task is processing is even slightly lower than the usually recommended 128 MB, and yet it gets killed for exceeding 10 GB (6 GB executor memory + 4 GB overhead). What is going on there? The only answer that I keep bumping in everywhere I look is to increase the memory allocation even more, but, obviously, there is a physical limit to that at some point (and we do want to run other MapRed/Spark jobs simultaneously), so rather than increasing the memory allocation mindlessly, I would like to understand why so much memory is used. Any help on that will be greatly appreciated! If you need any additional input from me, I'll be glad to provide it, if I can. UPDATE: Found the culprit. By carefully restructuring and analyzing the code I managed to localize the code which is running out of memory. I use a rather complicated UDF there. I'll try and rework that bit of code, maybe it will solve the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/50874168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Graphics rendering in thread game loop. Changing data on arrays I have two objects of 2D int arrays called: originalMap and rendedMap which they contain numbers that correspond to the puzzle game map. From the thread class i obtain the map array from the class call Puzzle.java and modifying the one. int [][] rendedMap = Puzzle.getRendedMap().getMap(); int [][] originalMap = Puzzle.getMapObj().getMap(); This is my thread loop: drawPuzzle(canvas, map); takes the canvas and the array and draws a map. while(running){ if(!holder.getSurface().isValid()) continue; canvas = holder.lockCanvas(); if(runSolution && movements.size()>0){ executeSolution(); drawPuzzle(canvas, rendedMap); if(finished){//checks if the execution finished runSolution=false; } if(message.equals("No more actions") || message.equals("Out of bounds, try again!")){ System.out.println(message); drawPuzzle(canvas, originalMap); } }else{ drawPuzzle(canvas, originalMap); } drawMovements(canvas); holder.unlockCanvasAndPost(canvas); } } And this is the method that i modify the array: public void executeSolution(){ numOfPlanets = 2; for(int x=0;x<rendedMap.length-1; x++){ for(int y=0;y<rendedMap[x].length-1; y++){ //Checks where the robot is and saves its initial position if(rendedMap[x][y]>=7 && rendedMap[x][y]<=9){ initX=x; initY=y; initial=true; System.out.println("Initial X: "+initX +" Y: "+initY ); direction = rendedMap[x][rendedMap[x].length-1]; System.out.println("Direction: "+direction ); } }//end inner for }//end for if(movements.size()>0){ for(int i=0; i<movements.size();i++){ if(movements.get(i).getColour().equals("none")){ if(movements.get(i).getMotion().equals("straight")){ if(direction==RIGHT){ if(rendedMap[initX][initY+1]==0){ finished=true; message = "Out of bounds, try again!"; return; }else{ rendedMap[initX][initY+1]= rendedMap[initX][initY+1]+6; rendedMap[initX][initY]=rendedMap[initX][initY]-6; } } }//action if }//color if }//movements for loop if(numOfPlanets > 0 ){ finished = true; message ="No more actions"; } }//movements if statement } My problem is when i render the renderMap array for some reason originalMap changes as well and when i am trying to draw back the originalMap it doesn't change back. I have even print them out and checked line by line and they are the same. Any tips what might cause this? I spend like days to figure it out. A: if(direction==RIGHT) { if(rendedMap[initX][initY+1]==0) { finished=true; message = "Out of bounds, try again!"; return; } else { rendedMap[initX][initY+1]= rendedMap[initX][initY+1]+6; rendedMap[initX][initY]=rendedMap[initX][initY]-6; } } check your rendedMap array is been initialized because this can often lead to contextual errors, especially within the android IDE. A: if(!holder.getSurface().isValid()) continue; canvas = holder.lockCanvas(); if(runSolution && movements.size()>0){ executeSolution(); drawPuzzle(canvas, rendedMap); if(finished){//checks if the execution finished runSolution=false; } if(message.equals("No more actions") || message.equals("Out of bounds, try again!")){ System.out.println(message); drawPuzzle(canvas, originalMap); } }else{ drawPuzzle(canvas, originalMap); } drawMovements(canvas); recall your drawPuzzle beforte surface view is locked down as the else causes it may not be executed in that contextual loop, as I said befor it is a problem that is comon with our organization apps hope this helps! do hesistate to ask for more assistence sorry for english I am indian
{ "language": "en", "url": "https://stackoverflow.com/questions/14735541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django m2m_changed signal with additional model I have a model looking like this: class Recipe(models.Model): name = models.CharField(_('Name')) components = models.ManyToManyField(RecipeComponent, through='alchemy.RecipeComposition') total_weight = models.FloatField(_('How much recipe will weight')) class RecipeComponent(models.Model): name = models.CharField(_('Name')) class RecipeComposition(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) component = models.ForeignKey(RecipeComponent, on_delete=models.CASCADE) number = models.FloatField(_('Defines how much of the component you need'), default=1) I have to do some calculations (for example total weight) of the recipe after any updates in RecipeComposition. Trying to do like this unfortunately doesn't help: @receiver(m2m_changed, sender=Recipe.components.through, weak=False) def recipe_components_changed(sender, **kwargs): print("meow >^-_-^<") # some calculations for recipe.total_weight here Found question with same problem but it's old (3 yrs ago) and has no correct answer. There is a link to ticket 17688 there which is opened 6 yrs ago but still not solved. I do not want to use post_save like this: @receiver(post_save, sender=RecipeComposition) because in this case when new Recipe created total_weight will be recalculated after each component added. Are there any other ideas how to make this work?
{ "language": "en", "url": "https://stackoverflow.com/questions/51019866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Type 'List' is not a subtype of type 'Map' I'm developing a flutter application that depends on API REST calls.The Response from the API is a bit complex. I can see the response from the log when calling my API (e.g : api/products) : But i have this Error : type 'List< dynamic >' is not a subtype of type 'Map< String, dynamic >' I've seen all the questions/answers on the internet without any result. I've tried with a simple RestAPI like : https://my-json-server.typicode.com/typicode/demo/posts and it works. but it doesn't in my case API Response Example : [ { "id":1, "tenant":{ "id":1, "code":"company", "name":"company" }, "type":{ "code":"activity", "name":"ActivitΓ©" }, "subType":{ "code":"ticket", "name":"Ticket" }, "inventoryType":{ "code":"external_source", "name":"Source externe" }, "externalReference":"CAL6970", "externalSystem":{ "code":"koedia", "name":"Koedia" }, "active":true, "durationDays":12, "durationNights":14, "durationHours":9, "durationMinutes":10, "supplier":{ "id":1, "tenant":{ "id":1, "code":"company", "name":"company" }, "name":"Jancarthier" }, "group":null, "subGroup":null, "name":"HΓ΄tel KoulnouΓ© Village", "translations":[ { "id":1, "name":"HΓ΄tel KoulnouΓ© Village", "locale":"fr" }, { "id":24, "name":"HΓ΄tel KoulnouΓ© Village", "locale":"en" } ], "vatPercentage":"0.00", "longitude":null, "latitude":null, "departureTime":null, "arrivalTime":null, "arrivalDayPlus":1, "stars":4, "localities":[ { "id":41, "locality":{ "id":34, "code":"ARM", "name":"Armenia" }, "role":{ "code":"stop", "name":"Escale" } }, { "id":49, "locality":{ "id":55, "code":"hossegor", "name":"Hossegor" }, "role":{ "code":"drop_off", "name":"Retour" } }, { "id":50, "locality":{ "id":55, "code":"hossegor", "name":"Hossegor" }, "role":{ "code":"localisation", "name":"Localisation" } } ] } ] StackTrace : I/flutter ( 2865): type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' [Updated] : return ProductsResponse.fromJson(response) instead of response ProductsRespository : import 'dart:async'; import 'package:day_experience/models/product/ProductResponse.dart'; import 'package:day_experience/networking/ApiProvider.dart'; class ProductRepository { ApiProvider _provider = ApiProvider(); Future<ProductsResponse> fetchProducts() async { final response = await _provider.getFromApi("products"); // here line 11 where exception is thrown return ProductsResponse.fromJson(response); } } ProductsBloc : import 'dart:async'; import 'package:day_experience/models/product/ProductResponse.dart'; import 'package:day_experience/networking/Response.dart'; import 'package:day_experience/repository/ProductRepository.dart'; class ProductBloc { ProductRepository _productRepository; StreamController _productListController; bool _isStreaming; StreamSink<Response<ProductsResponse>> get productListSink => _productListController.sink; Stream<Response<ProductsResponse>> get productListStream => _productListController.stream; ProductBloc() { _productListController = StreamController<Response<ProductsResponse>>(); _productRepository = ProductRepository(); _isStreaming = true; fetchProducts(); } fetchProducts() async { productListSink.add(Response.loading('Getting Products.')); try { ProductsResponse productsResponse = await _productRepository.fetchProducts(); if (_isStreaming) productListSink.add(Response.completed(productsResponse)); } catch (e) { if (_isStreaming) productListSink.add(Response.error(e.toString())); print(e); } } dispose() { _isStreaming = false; _productListController?.close(); } } Response : class Response<T> { Status status; T data; String message; Response.loading(this.message) : status = Status.LOADING; Response.completed(this.data) : status = Status.COMPLETED; Response.error(this.message) : status = Status.ERROR; @override String toString() { return "Status : $status \n Message : $message \n Data : $data"; } } enum Status { LOADING, COMPLETED, ERROR } ApiProvider : import 'package:day_experience/networking/CustomException.dart'; import 'package:http/http.dart' as http; import 'dart:io'; import 'dart:convert'; import 'dart:async'; class ApiProvider { final String _baseApiUrl = "URL_API/"; Future<dynamic> getFromApi(String url) async { var responseJson; try { final response = await http.get(Uri.encodeFull(_baseApiUrl + url),headers:{"Accept":"application/json"} ); print(response); responseJson = _response(response); } on SocketException { throw FetchDataException('No Internet connection'); } return responseJson; } dynamic _response(http.Response response) { switch (response.statusCode) { case 200: var responseJson = json.decode(response.body); print(responseJson); return responseJson; case 400: throw BadRequestException(response.body.toString()); case 401: case 403: throw UnauthorisedException(response.body.toString()); case 500: default: throw FetchDataException( 'Error occured while Communication with Server with StatusCode : ${response.statusCode}'); } } } Model : ProductResponses import 'ExternalSystem.dart'; import './InventoryType.dart'; import './Localities.dart'; import 'SubType.dart'; import 'Supplier.dart'; import 'Tenant.dart'; import './Translation.dart'; import './Type.dart'; class ProductsResponse { final int id; final Tenant tenant; final Type type; final SubType subType; final InventoryType inventoryType; final String externalReference; final ExternalSystem externalSystem; final bool active; final int durationDays; final int durationNights; final int durationHours; final int durationMinutes; final Supplier supplier; final String name; final List<Translation> translations; final String vatPercentage; final int arrivalDayPlus; final int stars; final List<Localities> localities; final String group; final String subGroup; final double longitude; final double latitude; final String departureTime; final String arrivalTime; ProductsResponse({this.id, this.tenant , this.type, this.subType, this.inventoryType, this.externalReference, this.externalSystem, this.active, this.durationDays, this.durationNights, this.durationHours, this.durationMinutes, this.supplier, this.name, this.translations, this.vatPercentage, this.arrivalDayPlus, this.stars, this.localities, this.group, this.subGroup, this.longitude, this.latitude, this.departureTime, this.arrivalTime}); factory ProductsResponse.fromJson(Map<String, dynamic> json) { return ProductsResponse( id: json['id'], tenant: json['tenant'] != null ? Tenant.fromJson(json['tenant']) : null, type: json['type'] != null ? Type.fromJson(json['type']) : null, subType: json['subType'] != null ? SubType.fromJson(json['subType']) : null, inventoryType: json['inventoryType'] != null ? InventoryType.fromJson(json['inventoryType']) : null, externalReference: json['externalReference'], externalSystem: json['externalSystem'] != null ? ExternalSystem.fromJson(json['externalSystem']) : null, active: json['active']?json['active']:null, durationDays: json['durationDays']?json['durationDays']:null, durationNights: json['durationNights']?json['durationNights']:null, durationHours: json['durationHours']?json['durationHours']:null, durationMinutes: json['durationMinutes']?json['durationMinutes']:null, supplier: json['supplier'] != null ? Supplier.fromJson(json['supplier']) : null, name: json['name']?json['name']:null, translations: json['translations'] != null ? (json['translations'] as List).map((i) => Translation.fromJson(i)).toList() : null, vatPercentage: json['vatPercentage']?json['vatPercentage']:null, arrivalDayPlus: json['arrivalDayPlus']?json['arrivalDayPlus']:null, stars: json['stars']?json['stars']:null, localities: json['localities'] != null ? (json['localities'] as List).map((i) => Localities.fromJson(i)).toList() : null, group: json['group'] != null ? json['group'] : null, subGroup: json['subGroup'] != null ? json['subGroup'] : null, longitude: json['longitude'] != null ? json['longitude'] : null, latitude: json['latitude'] != null ? json['latitude'] : null, departureTime: json['departureTime'] != null ? json['departureTime'] : null, arrivalTime: json['arrivalTime'] != null ? json['arrivalTime'] : null, ); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['externalReference'] = this.externalReference; data['active'] = this.active; data['durationDays'] = this.durationDays; data['durationNights'] = this.durationNights; data['durationHours'] = this.durationHours; data['durationMinutes'] = this.durationMinutes; data['name'] = this.name; data['vatPercentage'] = this.vatPercentage; data['arrivalDayPlus'] = this.arrivalDayPlus; data['stars'] = this.stars; if (this.tenant != null) { data['tenant'] = this.tenant.toJson(); } if (this.type != null) { data['type'] = this.type.toJson(); } if (this.subType != null) { data['subType'] = this.subType.toJson(); } if (this.inventoryType != null) { data['inventoryType'] = this.inventoryType.toJson(); } if (this.externalSystem != null) { data['externalSystem'] = this.externalSystem.toJson(); } if (this.supplier != null) { data['supplier'] = this.supplier.toJson(); } if (this.translations != null) { data['translations'] = this.translations.map((v) => v.toJson()).toList(); } if (this.localities != null) { data['localities'] = this.localities.map((v) => v.toJson()).toList(); } if (this.group != null) { data['group'] = this.group; } if (this.subGroup != null) { data['subGroup'] = this.subGroup; } if (this.longitude != null) { data['longitude'] = this.longitude; } if (this.latitude != null) { data['latitude'] = this.latitude; } if (this.departureTime != null) { data['departureTime'] = this.departureTime; } if (this.arrivalTime != null) { data['arrivalTime'] = this.arrivalTime; } print(data); return data; } } [Updated] : removed ProductsRepository (should only access via bloc) ProductView import 'package:day_experience/blocs/ProductBloc.dart'; import 'package:day_experience/models/product/ProductResponse.dart'; import 'package:day_experience/networking/Response.dart'; import 'package:day_experience/repository/ProductRepository.dart'; import 'package:day_experience/view/widget/Loading.dart'; import 'package:day_experience/view/widget/ProductList.dart'; import 'package:flutter/material.dart'; import 'package:day_experience/view/widget/Error.dart'; class ProductView extends StatefulWidget { @override _ProductViewState createState() => _ProductViewState(); } class _ProductViewState extends State<ProductView> { ProductBloc _bloc = new ProductBloc(); @override void initState() { super.initState(); _bloc.fetchProducts(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( elevation: 0.0, automaticallyImplyLeading: false, title: Text('Products', style: TextStyle(color: Colors.white, fontSize: 20)), backgroundColor: Color(0xFF333333), ), backgroundColor: Color(0xFF333333), body: RefreshIndicator( onRefresh: () => _bloc.fetchProducts(), child: StreamBuilder<Response<ProductsResponse>>( stream: _bloc.productListStream, builder: (context, snapshot) { if (snapshot.hasData) { switch (snapshot.data.status) { case Status.LOADING: return Loading(loadingMessage: snapshot.data.message); break; case Status.COMPLETED: return ProductList(productList:snapshot.data.data); break; case Status.ERROR: return Error( errorMessage: snapshot.data.message, onRetryPressed: () => _bloc.fetchProducts(), ); break; } } return Container(); }, ), ), ); } } Tenant Example same logic for others(Translation,Type,SubType..) class Tenant { final int id; final String code; final String name; Tenant({this.id, this.code, this.name}); factory Tenant.fromJson(Map<String, dynamic> json) { return Tenant( id: json['id'], code: json['code'], name: json['name'], ); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['code'] = this.code; data['name'] = this.name; return data; } } A: You can copy paste run full code below Because your json string produce a List<ProductResponse> not ProductResponse In your code you can directly return response.body as String and parse with productsResponseFromJson code snippet List<ProductsResponse> productsResponseFromJson(String str) => List<ProductsResponse>.from( json.decode(str).map((x) => ProductsResponse.fromJson(x))); Future<List<ProductsResponse>> fetchProducts() async { ApiProvider _provider = ApiProvider(); String response = await _provider.getFromApi("products"); // here line 11 where exception is thrown return productsResponseFromJson(response); //return ProductsResponse.fromJson(response); } Future<String> getFromApi(String url) async { String _response(http.Response response) { switch (response.statusCode) { case 200: print(response.body); //var responseJson = jsonDecode(response.body); //print(responseJson); return response.body; working demo full code import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; // To parse this JSON data, do // // final productsResponse = productsResponseFromJson(jsonString); import 'dart:convert'; List<ProductsResponse> productsResponseFromJson(String str) => List<ProductsResponse>.from( json.decode(str).map((x) => ProductsResponse.fromJson(x))); String productsResponseToJson(List<ProductsResponse> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson()))); class ProductsResponse { int id; Tenant tenant; ExternalSystem type; ExternalSystem subType; ExternalSystem inventoryType; String externalReference; ExternalSystem externalSystem; bool active; int durationDays; int durationNights; int durationHours; int durationMinutes; Supplier supplier; dynamic group; dynamic subGroup; String name; List<Translation> translations; String vatPercentage; dynamic longitude; dynamic latitude; dynamic departureTime; dynamic arrivalTime; int arrivalDayPlus; int stars; List<Locality> localities; ProductsResponse({ this.id, this.tenant, this.type, this.subType, this.inventoryType, this.externalReference, this.externalSystem, this.active, this.durationDays, this.durationNights, this.durationHours, this.durationMinutes, this.supplier, this.group, this.subGroup, this.name, this.translations, this.vatPercentage, this.longitude, this.latitude, this.departureTime, this.arrivalTime, this.arrivalDayPlus, this.stars, this.localities, }); factory ProductsResponse.fromJson(Map<String, dynamic> json) => ProductsResponse( id: json["id"], tenant: Tenant.fromJson(json["tenant"]), type: ExternalSystem.fromJson(json["type"]), subType: ExternalSystem.fromJson(json["subType"]), inventoryType: ExternalSystem.fromJson(json["inventoryType"]), externalReference: json["externalReference"], externalSystem: ExternalSystem.fromJson(json["externalSystem"]), active: json["active"], durationDays: json["durationDays"], durationNights: json["durationNights"], durationHours: json["durationHours"], durationMinutes: json["durationMinutes"], supplier: Supplier.fromJson(json["supplier"]), group: json["group"], subGroup: json["subGroup"], name: json["name"], translations: List<Translation>.from( json["translations"].map((x) => Translation.fromJson(x))), vatPercentage: json["vatPercentage"], longitude: json["longitude"], latitude: json["latitude"], departureTime: json["departureTime"], arrivalTime: json["arrivalTime"], arrivalDayPlus: json["arrivalDayPlus"], stars: json["stars"], localities: List<Locality>.from( json["localities"].map((x) => Locality.fromJson(x))), ); Map<String, dynamic> toJson() => { "id": id, "tenant": tenant.toJson(), "type": type.toJson(), "subType": subType.toJson(), "inventoryType": inventoryType.toJson(), "externalReference": externalReference, "externalSystem": externalSystem.toJson(), "active": active, "durationDays": durationDays, "durationNights": durationNights, "durationHours": durationHours, "durationMinutes": durationMinutes, "supplier": supplier.toJson(), "group": group, "subGroup": subGroup, "name": name, "translations": List<dynamic>.from(translations.map((x) => x.toJson())), "vatPercentage": vatPercentage, "longitude": longitude, "latitude": latitude, "departureTime": departureTime, "arrivalTime": arrivalTime, "arrivalDayPlus": arrivalDayPlus, "stars": stars, "localities": List<dynamic>.from(localities.map((x) => x.toJson())), }; } class ExternalSystem { String code; String name; ExternalSystem({ this.code, this.name, }); factory ExternalSystem.fromJson(Map<String, dynamic> json) => ExternalSystem( code: json["code"], name: json["name"], ); Map<String, dynamic> toJson() => { "code": code, "name": name, }; } class Locality { int id; Tenant locality; ExternalSystem role; Locality({ this.id, this.locality, this.role, }); factory Locality.fromJson(Map<String, dynamic> json) => Locality( id: json["id"], locality: Tenant.fromJson(json["locality"]), role: ExternalSystem.fromJson(json["role"]), ); Map<String, dynamic> toJson() => { "id": id, "locality": locality.toJson(), "role": role.toJson(), }; } class Tenant { int id; String code; String name; Tenant({ this.id, this.code, this.name, }); factory Tenant.fromJson(Map<String, dynamic> json) => Tenant( id: json["id"], code: json["code"], name: json["name"], ); Map<String, dynamic> toJson() => { "id": id, "code": code, "name": name, }; } class Supplier { int id; Tenant tenant; String name; Supplier({ this.id, this.tenant, this.name, }); factory Supplier.fromJson(Map<String, dynamic> json) => Supplier( id: json["id"], tenant: Tenant.fromJson(json["tenant"]), name: json["name"], ); Map<String, dynamic> toJson() => { "id": id, "tenant": tenant.toJson(), "name": name, }; } class Translation { int id; String name; String locale; Translation({ this.id, this.name, this.locale, }); factory Translation.fromJson(Map<String, dynamic> json) => Translation( id: json["id"], name: json["name"], locale: json["locale"], ); Map<String, dynamic> toJson() => { "id": id, "name": name, "locale": locale, }; } void main() { runApp(MyApp()); } Future<List<ProductsResponse>> fetchProducts() async { ApiProvider _provider = ApiProvider(); String response = await _provider.getFromApi("products"); // here line 11 where exception is thrown return productsResponseFromJson(response); //return ProductsResponse.fromJson(response); } class ApiProvider { Future<String> getFromApi(String url) async { var responseJson; try { //final response = await http.get(Uri.encodeFull(_baseApiUrl + url),headers:{"Accept":"application/json"} ); String jsonString = ''' [ { "id":1, "tenant":{ "id":1, "code":"company", "name":"company" }, "type":{ "code":"activity", "name":"ActivitΓ©" }, "subType":{ "code":"ticket", "name":"Ticket" }, "inventoryType":{ "code":"external_source", "name":"Source externe" }, "externalReference":"CAL6970", "externalSystem":{ "code":"koedia", "name":"Koedia" }, "active":true, "durationDays":12, "durationNights":14, "durationHours":9, "durationMinutes":10, "supplier":{ "id":1, "tenant":{ "id":1, "code":"company", "name":"company" }, "name":"Jancarthier" }, "group":null, "subGroup":null, "name":"HΓ΄tel KoulnouΓ© Village", "translations":[ { "id":1, "name":"HΓ΄tel KoulnouΓ© Village", "locale":"fr" }, { "id":24, "name":"HΓ΄tel KoulnouΓ© Village", "locale":"en" } ], "vatPercentage":"0.00", "longitude":null, "latitude":null, "departureTime":null, "arrivalTime":null, "arrivalDayPlus":1, "stars":4, "localities":[ { "id":41, "locality":{ "id":34, "code":"ARM", "name":"Armenia" }, "role":{ "code":"stop", "name":"Escale" } }, { "id":49, "locality":{ "id":55, "code":"hossegor", "name":"Hossegor" }, "role":{ "code":"drop_off", "name":"Retour" } }, { "id":50, "locality":{ "id":55, "code":"hossegor", "name":"Hossegor" }, "role":{ "code":"localisation", "name":"Localisation" } } ] } ] '''; http.Response response = http.Response(jsonString, 200); print(response); responseJson = _response(response); } on Exception { //throw FetchDataException('No Internet connection'); } return responseJson; } String _response(http.Response response) { switch (response.statusCode) { case 200: print(response.body); //var responseJson = jsonDecode(response.body); //print(responseJson); return response.body; /* case 400: throw BadRequestException(response.body.toString()); case 401: case 403: throw UnauthorisedException(response.body.toString()); case 500: default: throw FetchDataException( 'Error occured while Communication with Server with StatusCode : ${response.statusCode}');*/ } } } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; List<ProductsResponse> productResponseList; void _incrementCounter() async { productResponseList = await fetchProducts(); print('${productResponseList[0].inventoryType}'); setState(() { _counter++; }); } @override void initState() { // TODO: implement initState super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ productResponseList == null ? CircularProgressIndicator() : Text('${productResponseList[0].inventoryType.name}'), Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), ); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/60805129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Spring @Autowired(required = true) is null I have a webmodule with JSF 2 end Spring 4.3. In a backing bean I use @Autowired for DI of a service of a JAR. In EAR module there are WAR, JAR with @Service Spring and JAR with Spring configuration file. Below a web.xml snippet: <context-param> <param-name>locatorFactorySelector</param-name> <param-value>classpath:beanRefContext.xml</param-value> </context-param> <context-param> <param-name>parentContextKey</param-name> <param-value>sharedContext</param-value> </context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener> applicationContext.xml: <context:annotation-config /> <context:spring-configured /> <!-- package of @Service class in jar module in EAR-- > <context:component-scan base-package="com.ipdb.service" /> beanRefContext.xml: <bean id="sharedContext" class="org.springframework.context.support.ClassPathXmlApplicationContext"> <constructor-arg> <list> <value>spring-ctx.xml</value> </list> </constructor-arg> </bean> When I Use @Autowired(required=null) in a Backing Bean the value is null (there is not any exception). My JSF bean @Component @ManagedBean @ViewScoped public class PortfolioController { @Autowired(required = true) private PortfolioService portfolioService; ... Can you help me, please. A: PortfolioController is considered a JSF context bean adding @Component to @ManagedBean is totally wrong you can't mark same class as bean in two different contexts (JSF and Spring ). Two solutions either make PortfolioController a spring bean thus remove the @ManagedBean and @ViewScoped or inject PortfolioController via JSF injection annotation @ManagedProperty @ManagedProperty("#{portfolioService}") private PortfolioService portfolioService; A: if the applicationContext.xml is in your jar dependency, then you need to add asterisk after classpath: <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext.xml</param-value> </context-param> With the asterisk spring search files applicationContext.xml anywhere in the classpath not only the current project.
{ "language": "en", "url": "https://stackoverflow.com/questions/38551532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: For excel VBA, using "for each...next" statement. How can you use all the iterated elements at once Here is a sample code that im testing Sub Selek() Dim fd As FileDialog Set fd = Application.FileDialog(msoFileDialogFilePicker) Dim item As Variant With fd If .Show = -1 Then For Each item In .SelectedItems MsgBox item Next item Else End If End With Range("K1") = item End Sub This script shows selected items one by one in different message boxes but I want all selected ones in just a single msgbox. Followup question. I also need to work with the file paths found for each selected item. I realize I couldn't assign them to a variable once I'm outside of the "With" section. My solution is when I'm still in the "With" block, then I assign the item to a cell and then once I'm out of the "With" block then thats when I assign it to a variable. Is there a way to use the element directly without doing this?
{ "language": "en", "url": "https://stackoverflow.com/questions/63925955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why `boost::bind()` can't be replaced with `std::bind()` here? In this part of code from the example: int main() { boost::asio::io_service io; printer p(io); boost::thread t(boost::bind(&boost::asio::io_service::run, &io)); io.run(); t.join(); return 0; } If I replace the boost::bind(&boost::asio::io_service::run, &io) to std::bind(&boost::asio::io_service::run, &io) I get the compilation error: .../usr/lib/c++/v1/functional:1843:1: note: candidate template ignored: couldn't infer template argument '_Fp' bind(_Fp&& __f, _BoundArgs&&... __bound_args) ^ /usr/lib/c++/v1/functional:1852:1: note: candidate template ignored: couldn't infer template argument '_Rp' bind(_Fp&& __f, _BoundArgs&&... __bound_args) ^ 1 error generated. Why this error happen? Why std::bind(&printer::print1, &p) works, but std::bind(&boost::asio::io_service::run, &io) doesn't work? A: The compiler is telling you that it could not figure out the type of the first argument to std::bind. If you look at io_service::run, you will see that it is overloaded. The compiler had a choice, and this is a possible reason for the compiler not figuring out the type. To test this, you can use a cast: std::bind(static_cast<size_t (boost::asio::io_service::*)()>(&boost::asio::io_service::run), &io) This way makes the choice explicit in the code. With a modern compiler, you don't need to use bind at all. You can do something like this: [&]() { io.run(); } That avoids all the problems with the std::bind template. You need to consider variable lifetime and copies vs. references.
{ "language": "en", "url": "https://stackoverflow.com/questions/20158311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to convert date format range in php for ex below I am getting date range from input 22 Mar, 2021 - 22 Apr, 2021, so what my question is , in MySQL 2019-01-30 00:00:00 (created_at), how to set date range search laravel query A: You can use php's native functiion to convert string to date format. $startDate = date('Y-m-d', strtotime('22 Mar, 2021'));//2021-03-22 $endDate = date('Y-m-d', strtotime('22 Apr, 2021'));//2021-04-22 Now you can perform laravel search query. For example: DB::table('yourTable') ->whereBetween('created_at', [$startDate, $endDate]) ->get(); See Document: strtotime
{ "language": "en", "url": "https://stackoverflow.com/questions/66743731", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rspec not accessing datas updated via capybara? I have a form containing a "name" regular input field and a "content" CKeditor textarea. As described here I can fill in the form and if I stop here I can see the "name" and "content" columns correctly updated in the Test DataBase. Fine. Now, if I do : template = ContractTemplate.all.last puts "#{template.name}" # => "template_name" puts "#{template.content}" # => "<p>template_content</p>" And then problem begins, if I try to update those two attributes (still using Capybara), I now always fall back on values saved at the "create" action, although they ARE correctly updated into the database. It's just like there where no update of the values. I've tried to do ContractTemplate.reload , but it doesn't work. Full spec is like this : it 'should edit a contract template', :js => true do visit contract_templates_path click_link "Add" fill_in "contract_template_name", :with => "test_template_name" fill_in_ckeditor "contract_template_content", :with => "test_template_content" click_button "Save" template = ContractTemplate.all.last template.name.should eq("test_template_name") # pass, content created template.content.should eq("<p>\r\n\ttest_template_content</p>\r\n") # pass visit contract_template_path(template.id) fill_in "contract_template_name", :with => "edited_test_template_name" fill_in_ckeditor "contract_template_content", :with => "edited_test_template_content" click_button "Save" template.name.should eq("edited_test_template_name") # Fail, because == "test_template_name" template.content.should eq("<p>\r\n\tedited_test_template_content</p>\r\n") # Fail, not updated too end My approach may be wrong, but since the "content" attribute is filled using a wisiwig editor, I just can't see any other way to test if the save action really updates name and content... BTW there is no view in the app where I could display the result of the textarea, it's all going to be rendered as PDF. Could someone help me ? A: You need a template.reload after your second save. Otherwise, the template record will contain the values from when it was first loaded. A: I GOT IT ! I just had to turn transactionnal fixtures to false inside spec_helper.rb : RSpec.configure do |config| ... config.use_transactional_fixtures = false # true by default ... end Now everything runs fine. Ho my... 4 hours on this, I was just getting mad.
{ "language": "en", "url": "https://stackoverflow.com/questions/17432409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Efficient way to convert units from one system to another I'm having an hard time figuring an efficient way to converts differents types of unit to various other types. Switch cases would work, but IMO that's not an efficient way has I will have 3 different Systems (SI, Imperial and US). My converter (inside my app) will always convert from SI to something or from something to SI. It kinds of lower the complexity, but yet I still need advice on how to make clean code. I had defined that my input parameters for conversion would be Value(number) and Unit(string). I would have 2 functions. SIToSomething(value, unit) and SOmethingToSi(value, unit). Unit is defined because I would be converting length, weight, qty etc.. What would you suggest ? A: How about this: var converters = { 'SIToImperial' : { 'cm' : function(val) { // implementation, return something }, 'kg' : function(val) { // implementation, return something } //, etc. }, 'SIToUS' : { 'cm' : function(val) { // implementation, return something }, 'kg' : function(val) { // implementation, return something } //, etc. }, 'USToSI' : { 'cm' : function(val) { /* ... */ } // etc } // , etc } SIToSomething(value, unit, system) { return converters["SITo" + system][unit](value); } var meterInImperial = SIToSomething(100, 'cm', 'Imperial'); var fiftyKilosInUS = SIToSomething(50, 'kg', 'US'); A: What you can do is have a base unit, and for each target unit, define conversion functions to/from this base unit. Then, to convert from A to B, for example, you'd have this: A -> base -> B This way, you only need two conversion functions per unit (not counting the base unit): var units = { a: { toBase: function(value) { return value * 2; }, fromBase: function(value) { return value / 2; } }, b: { toBase: function(value) { return 1.734 * value + 48; }, fromBase: function(value) { return (value / 1.734) - 48; } } } function convertFromTo(unitA, unitB, value) { return unitB.fromBase(unitA.toBase(value)); } convertFromTo(units.a, units.b, 36489); A: Do all conversions to/from SI. For example if converting Imperial->US, you'd go Imperial->SI->US. This is minimal effort you can put in. It also gets you SI "for free".
{ "language": "en", "url": "https://stackoverflow.com/questions/17219261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Writing UTF-8 fields from mysql in PHP to CSV format I am using a php class, where it writes and stores CSV files in the folder of my site. But am unable to write UTF-8 characters of different languages which is present in my database. I am using the following class to write csv file. How can I add support to write utf-8 characters to this class. I have tried google and other places, but no finding any luck. class b3rtCSVWriter { var $filename; var $delimiter; var $fileHandle; var $fileBuffer; var $fileBufferSize; var $errorList; /*function b3rtCSVWriter() { }*/ function __construct() { $this->filename = ''; $this->delimiter = ','; $this->fileHandle = NULL; $this->fileBuffer = ''; $this->fileBufferSize = 4096; $this->errorList = array(); } function __destruct() { $this->closeFile(); } function setFilename($filename) { $this->filename = $filename; return $this->openFile(); } function setDelimiter($delimiter) { if (strlen($delimiter) != 1) { $this->setError('Invalid delimiter'); return FALSE; } $this->delimiter = $delimiter; return TRUE; } function getErrors() { return $this->errorList; } function putRecord($recordData) { if ($this->errorList) return ($this->fileHandle === NULL ? '' : FALSE); $rowBuffer = ''; // Check if recordData is an array if (isset($recordData) && is_array($recordData)) { $currentFieldIndex = -1; $lastFieldIndex = count($recordData) - 1; // Loop through every array item foreach($recordData as $recordValue) { $currentFieldIndex++; $isQuotedField = FALSE; // Set isQuotedField if a " is present and replace " with "" if (strpos($recordValue, '"') !== FALSE) { $isQuotedField = TRUE; $recordValue = str_replace('"', '""', $recordValue); } // Set isQuotedField if a delimiter or newline is present if ((strpos($recordValue, $this->delimiter) !== FALSE) || (strpos($recordValue, "\n") !== FALSE)) $isQuotedField = TRUE; // Put field inside " if isQuotedField is set if ($isQuotedField) $recordValue = '"'.$recordValue.'"'; // Add recordValue to rowBuffer and, if not at last field, a delimiter $rowBuffer .= $recordValue . ($currentFieldIndex != $lastFieldIndex ? $this->delimiter : ''); } } // Add EOL to rowBuffer, even when it's empty $rowBuffer .= "\r\n"; // If no file is currently open, return rowBuffer as is if ($this->fileHandle === NULL) return $rowBuffer; else // Else write rowBuffer to file return $this->writeFile($rowBuffer); } function openFile() { $this->closeFile(); if ($this->filename == '') $this->setError('Invalid filename'); if ($this->errorList) return FALSE; $this->fileHandle = @fopen($this->filename, 'w'); if (!$this->fileHandle) { $this->setError('Could not open file'); $this->fileHandle = NULL; return FALSE; } if (!flock($this->fileHandle, LOCK_EX)) { $this->setError('Could not lock file'); $this->closeFile(); return FALSE; } return TRUE; } function writeFile($toWrite, $forceWrite = FALSE) { if ($this->fileHandle === NULL) { $this->setError('No file specified'); return FALSE; } $this->fileBuffer .= $toWrite; if ($forceWrite || (strlen($this->fileBuffer) > $this->fileBufferSize)) { if (@fwrite($this->fileHandle, $this->fileBuffer, strlen($this->fileBuffer)) === FALSE) { $this->setError('Could not write to file'); return FALSE; } $this->fileBuffer = ''; } return TRUE; } function closeFile() { if (is_resource($this->fileHandle)) { // Force buffer to be written $this->writeFile('', TRUE); if (!fflush($this->fileHandle)) $this->setError('Could not flush output to file'); if (!flock($this->fileHandle, LOCK_UN)) $this->setError('Could not unlock file'); if(!@fclose($this->fileHandle)) $this->setError('Could not close file'); } $this->fileHandle = NULL; } function setError($error) { $this->errorList[] = $error; } } After browsing from so many days, I found that I would have to need to add BOM to fix UTF-8 in Excel, but was unseccessful in adding to this class. $fp = fopen('php://output', 'w'); fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) )); fclose($fp); A: Add it here: $this->fileHandle = @fopen($this->filename, 'w'); if (!$this->fileHandle) { $this->setError('Could not open file'); $this->fileHandle = NULL; return FALSE; } fputs($this->fileHandle, chr(0xEF) . chr(0xBB) . chr(0xBF));
{ "language": "en", "url": "https://stackoverflow.com/questions/22816496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ignore Rewrite Rule for images folder I have a .htaccess file on a website I'm working on which rewrites urls from mydomain.com/sub/folder/ to mydomain.com?index.php?controller=sub&view=folder Unfortunately the way I've written it means I can't access images, stylesheets and other linked files anymore. Could anyone tell me how best to exclude specific directories / URL requests from the rewrite rule? Apologies if this is a bit of a newbie question, I'm still wrapping my head around this mod rewrite stuff! The .htaccess file looks like this: RewriteEngine on RewriteRule ^([a-zA-Z0-9-]+)/?$ index.php?Controller=$1 RewriteRule ^([a-zA-Z0-9-]+)/([a-zA-Z0-9-_]+)/? index.php?Controller=$1&View=$2 A: If your images are in mydomain.com/images and you are linking to them using relative links on the page mydomain.com/sub/folder/ the browser is going to try to attempt to access the image via mydomain.com/sub/folder/images/i.gif. But if you change your links to absolute links, the browser will correctly attempt to load mydomain.com/images/i.gif. However, the RewriteRule will change it to: mydomain.com/index/php?Controller=images&View=i.gif. To avoid this you need to add a few RewriteConds: RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([a-zA-Z0-9-_]+)\/?$ index.php?Controller=$1 RewriteRule ^([a-zA-Z0-9-_]+)/([a-zA-Z0-9-_]+)\/? index.php?Controller=$1&View=$2 So that when attempting at access an existing file/directory, don't rewrite to index.php.
{ "language": "en", "url": "https://stackoverflow.com/questions/8042631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I save the array to a text file and import it back? Basically, I want to know how to get my array that gets data from peoples input saved to a text file and automatically imported back into the array when the program starts again. Edit: Now after this, it seems saving and reopening adds data to the same subarrays My code: import json import time datastore=[] datastore = json.load(open("file.json")) menuon = 1 def add_user(): userdata = input("How many users do you wish to input?") print("\n") if (userdata == 0): print("Thank you, have a nice day!") else: def add_data(users): for i in range(users): datastore.append([]) datastore[i].append(input("Enter Name: ")) datastore[i].append(input("Enter Email: ")) datastore[i].append(input("Enter DOB: ")) add_data(int(userdata)) def print_resource(array): for entry in datastore: print("Name: "+entry[0]) print("Email: "+entry[1]) print("DOB: "+entry[2]) print("\n") def search_function(value): for eachperson in datastore: if value in eachperson: print_resource(eachperson) while menuon == 1: print("Hello There. What would you like to do?") print("") print("Option 1: Add Users") print("Option 2: Search Users") print("Option 3: Replace Users") print("Option 4: End the program") menuChoice = input() if menuChoice == '1': add_user() if menuChoice == '2': searchflag = input("Do you wish to search the user data? y/n") if(searchflag == 'y'): criteria = input("Enter Search Term: ") search_function(criteria) if menuChoice == '3': break if menuChoice == '4': print("Ending in 3...") time.sleep(1) print("2") time.sleep(1) print("1") json.dump(datastore, open("file.json", "w")) menuon=0 A: This module would do what you want: http://docs.python.org/3/library/pickle.html An example: import pickle array = ["uno", "dos", "tres"] with open("test", "wb") as f: pickle.dump(array, f) with open("test", "rb") as f: unpickled_array = pickle.load(f) print(repr(unpickled_array)) Pickle serializes your object. In essence this means it converts it to a storeable format that can be used to recreate a clone of the original. Check out the wiki entry if you're interested in more info: http://en.wikipedia.org/wiki/Serialization A: Python docs have a beautiful explanation on how to handle text files among other files to read/write. Here's the link: http://docs.python.org/2/tutorial/inputoutput.html Hope it helps! A: You need to serialize the array somehow to store it in a file. Serialize basically just means turn into a representation that is linear. For our purposes that means a string. There are several ways (csv, pickle, json). My current favorite way to do that is json.dump() and json.load() to read it back in. See json docs import json def save_file(): with open('datafile.json', 'w') as f: json.dump(datastore, f) def load_file(): with open('datafile.json', 'r') as f: datastore = json.load(f) A: Use JSON; Python has a json module built-in : import json datastore = json.load(open("file.json")) // load the file datastore["new"] = "new value" // do something with your data json.dump(datastore, open("file.json", "w")) // save data back to your file You could also use Pickle to serialize a dictionary, but JSON is better for small data and is human-readable and editable with a simple text editor, where as Pickle is a binary format. I've updated your code to use JSON and dictionaries, and it works fine : import json import time datastore = json.load(open("file.json")) menuon = 1 def add_user(): userdata = input("How many users do you wish to input?") print("\n") if (userdata == 0): print("Thank you, have a nice day!") else: def add_data(users): for i in range(users): datastore.append({"name":input("Enter Name: "), "mail":input("Enter Email: "), "dob":input("Enter DOB: ")}) add_data(int(userdata)) def print_resource(array): for entry in datastore: print("Name: "+entry["name"]) print("Email: "+entry["mail"]) print("DOB: "+entry["dob"]) print("\n") def search_function(value): for eachperson in datastore: for i in eachperson.keys(): if value in eachperson[i]: print_resource(eachperson) while menuon == 1: print("Hello There. What would you like to do?") print("") print("Option 1: Add Users") print("Option 2: Search Users") print("Option 3: Replace Users") print("Option 4: End the program") menuChoice = input() if menuChoice == '1': add_user() if menuChoice == '2': searchflag = input("Do you wish to search the user data? y/n") if(searchflag == 'y'): criteria = input("Enter Search Term: ") search_function(criteria) if menuChoice == '3': break if menuChoice == '4': print("Ending in 3...") time.sleep(1) print("2") time.sleep(1) print("1") json.dump(datastore, open("file.json", "w")) menuon=0
{ "language": "en", "url": "https://stackoverflow.com/questions/20223236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Post data in C# and use response in CefSharp I'm trying to post parameters to a website and use the response in my CefSharp browser. Using my current code it posts the data and loads the html in CefSharp. The html page that loads is exactly what I want meaning the post works but as soon as I click a button it just loads up the website without an of the parameters I posted. How could I use the cookies from the request so that if I click the button everything should remain the way it was posted. Here is the code i'm using to post: using (var client = new HttpClient()) { var values = new Dictionary<string, string> { { }, { }, { }, <----- Parameters go here { }, { }, }; //WebClient client2 = new WebClient(); client.DefaultRequestHeaders.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); var content = new FormUrlEncodedContent(values); var response = await client.PostAsync("URL", content); var responseString = await response.Content.ReadAsStringAsync(); CookieContainer cookies = new CookieContainer(); HttpClientHandler handler = new HttpClientHandler(); handler.CookieContainer = cookies; chrome.LoadHtml(responseString, "URL");
{ "language": "en", "url": "https://stackoverflow.com/questions/42441793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make Recycle Bin in ASP.Net i want to create a Recycle Bin in my web project, i use a Details View with EDIT and DELETE option to present and edit data from database and its worked perfectly but want a Recycle Bin for Deleted Data and if Owner wants to delete completely Delete from Recycle . if u have some codes or idea or some links help me please ! A: You shall have a field in db which means isDeteled or isRecycled and when it is set to 1 show it in recycleBin/ if user finally deletes record delete if from db. Better choice is to have status field for enum Active/Archived/Deleted or Active/Archived/Deleted/Purged when the record in last state of this enum delete it in real time, or by SQL clean-up job or something like this.
{ "language": "en", "url": "https://stackoverflow.com/questions/25645142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Losing custom gridview font when new page selected I am using this code to change the font color in a grid view for a single column depending on value: For Each row As GridViewRow In gvSearch.Rows If row.Cells(8).Text.Trim = "Used" Then row.Cells(8).CssClass = "CautionRow" End If Next This code runs after the gridview databind. However, the gridview has pages available and this code only changes the first page of the grid view. I can resolve the problem by not allowing pages, but this is a tacky solution. Any suggetions? A: Register PageIndexChanging event onpageindexchanging="gvSearch_PageIndexChanging" Then in event handler do your font changing logic like Sub gvSearch_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs) { For Each row As GridViewRow In gvSearch.Rows If row.Cells(8).Text.Trim = "Used" Then row.Cells(8).CssClass = "CautionRow" End If Next } A: Actually found my own answer thanks to help from my fellow programmer. Here's what really works: In the style sheet (.css) add this: .CautionRow { color: red; } ... then add this to your code: Protected Sub gvSearch_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViwRowEventArgs) Handles gvSearch.RowDatabound If e.Row.Cells.Count > 1 Then If e.Row.Cells(8).Text.ToString.ToLower.Trim = "used" Then e.Row.Cells(8).CssClass = "CautionRow" End If End If End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/24922092", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't attach Unity script to a GameObject I'm a new Unity user, and I'm having issues when trying to attach a C# script to a GameObject: Can't add script component XYZ, because the script class cannot be found. Make sure there are no errors and that the file name and class name match. Searching online this issue usually happens when the class name and file name are different, but I've checked that and they are the same. I even tried creating a new empty/default C# script and tried attaching that, but no luck. This is completely empty project, and there are no other scripts with compile errors. GIF showing the error Any ideas, help would be appreciated? I'm running Unity 2019.1.of2 Personal on Ubuntu 19.04 A: I managed to solve the issue with help from the comments above. The issue was that Unity was unable to compile/build the project, hence as 3Dave and Corey Smith said - if there are any compile errors you are unable to attache scripts to GameObjects. I also realized I was unable to run the project. I first though it might be an issue with .NET versions on Ubuntu, but it turned out to be issue with libssl1.0 library (if you have a greater version then Unity won't work on Ubuntu 19.04). See this post for reference: https://forum.unity.com/threads/empty-log-errors-in-2019-1-0f2.669961/#post-4545013 Installing libssl1.0 solved the compile issues, I'm now able to attache scripts to GameObjects and run the project. A: Old question, but I solved this problem using the Help menu and then Reset Packages to defaults.
{ "language": "en", "url": "https://stackoverflow.com/questions/59594391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Javascript not working on mobile site I'm using JavaScript to submit the current URL, all works fine until I enter to mobile screen, then the JavaScript appears to be gone, this is not only for "mobile" apparently the problem is based on the screen width. $( document ).ready(function() { $( "#widgetu117_input" ).keyup(function( event ) { var getUrl = window.location; var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1]; }) }) This is my code. The form was build using muse (not my doing) A: I found a solution, it works for me. instead of using document ready, i changed everything to be a function and then, call it with settimeout at 7 seconds (tried with 3 but the problem persisted). Hope nobody has this problem it was tricky to solve.
{ "language": "en", "url": "https://stackoverflow.com/questions/45728832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Returning a strongly typed promiseValue from angular $modalInstance with TypeScript TypeScript newb Question. I'm trying to return a strongly typed promise from angular's $modalInstance. I have something similar to: this.$modal.open(options).result.then(result => { Currently result is type 'any'. How do I cast it or affect it to be of type MyType? (see below) }); interface myType { a: string, b: number } result: myType; ... $modalInstance.close(this.result) A: I actually had to wrap the $modal and $modalInstance services to take a type T. The above answer (which I had initially tried) will not work because the $modalInstance result is a promise of type 'any'. The wrapped $modalInstance is a promise of type T. module my.interfaces { export interface IMyModalService<T> { open(options: ng.ui.bootstrap.IModalSettings): IMyModalServiceInstance<T>; } export interface IMyModalScope<T> extends ng.ui.bootstrap.IModalScope { $dismiss(reason?: any): boolean; $close(result?: T): boolean; } export interface IMyModalServiceInstance<T> extends ng.ui.bootstrap.IModalServiceInstance { close(result?: T): void; dismiss(reason?: any): void; result: angular.IPromise<T>; opened: angular.IPromise<any>; rendered: angular.IPromise<any>; } A: this.$modal.open(options).result.then((result: myType) => { Now result is declared to be of your type });
{ "language": "en", "url": "https://stackoverflow.com/questions/32401777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Transition not working properly on vue when div is being hiding I have simple transition to toggle a div text, however the transition works only when the text is being hiding, however when I click to show the text the transition doesn't work here it is my code: <template> <div> <transition name="fade"> <div v-if="this.showName">My name is Simon</div> </transition> <button @click="showName = !showName">Toggle</button> </div> </template> <script> export default { data(){ return { showName: false, } }, name: "StatusComponent" } </script> <style scoped> .fade-enter-from{ opacity: 0; } .fade-enter-to{ opacity: 1; } .fade-enter-active{ transition: all 2s ease; } .fade-leave-from{ opacity: 1; } .fade-leave-to{ opacity: 0; } .fade-leave-active{ transition: all 2s ease; } </style> A: <div> <p v-if="showName">My name is Simon</p> </div> You should open a p tag under the div tag
{ "language": "en", "url": "https://stackoverflow.com/questions/70311429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Crash startActivityForResult(intent,1); I have a problem in my android application, I have a hand page, I change my business with startActivityForResult (intent, CODE_DE_MON_ACTIVITE). It works, but then when I replace this page since the second activity with the same code but nothing works. The application crashes. Knowing that I have all the activities in the Manifest. Log: 06-28 13:09:47.765: D/AndroidRuntime(254): Shutting down VM 06-28 13:09:47.765: W/dalvikvm(254): threadid=3: thread exiting with uncaught exception (group=0x4001b188) 06-28 13:09:47.765: E/AndroidRuntime(254): Uncaught handler: thread main exiting due to uncaught exception 06-28 13:09:47.775: E/AndroidRuntime(254): java.lang.RuntimeException: Unable to start activity ComponentInfo{referencehit.android/referencehit.android.AddTournamentActivity}: java.lang.NullPointerException 06-28 13:09:47.775: E/AndroidRuntime(254): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496) 06-28 13:09:47.775: E/AndroidRuntime(254): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512) 06-28 13:09:47.775: E/AndroidRuntime(254): at android.app.ActivityThread.access$2200(ActivityThread.java:119) 06-28 13:09:47.775: E/AndroidRuntime(254): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863) 06-28 13:09:47.775: E/AndroidRuntime(254): at android.os.Handler.dispatchMessage(Handler.java:99) 06-28 13:09:47.775: E/AndroidRuntime(254): at android.os.Looper.loop(Looper.java:123) 06-28 13:09:47.775: E/AndroidRuntime(254): at android.app.ActivityThread.main(ActivityThread.java:4363) 06-28 13:09:47.775: E/AndroidRuntime(254): at java.lang.reflect.Method.invokeNative(Native Method) 06-28 13:09:47.775: E/AndroidRuntime(254): at java.lang.reflect.Method.invoke(Method.java:521) 06-28 13:09:47.775: E/AndroidRuntime(254): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) 06-28 13:09:47.775: E/AndroidRuntime(254): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 06-28 13:09:47.775: E/AndroidRuntime(254): at dalvik.system.NativeStart.main(Native Method) 06-28 13:09:47.775: E/AndroidRuntime(254): Caused by: java.lang.NullPointerException 06-28 13:09:47.775: E/AndroidRuntime(254): at referencehit.android.AddTournamentActivity.onCreate(AddTournamentActivity.java:38) 06-28 13:09:47.775: E/AndroidRuntime(254): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 06-28 13:09:47.775: E/AndroidRuntime(254): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459) 06-28 13:09:47.775: E/AndroidRuntime(254): ... 11 more 06-28 13:09:47.788: I/dalvikvm(254): threadid=7: reacting to signal 3 06-28 1 3:09:47.788: E/dalvikvm(254): Unable to open stack trace file '/data/anr/traces.txt': Permission denied Have you an idea of ​​my problem? A: Have you actually assigned a value to the Intent? Simply coding Intent intent; will throw a NullPointerException when you call startActivity(intent); like the one you got. Alternately, have you added your second activity to the Manifest file? Android won't launch an Activity that isn't in its Manifest. A: Add followin permission to ur AndroidManifest.xml <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> If u have forgotten to add it, then add it.
{ "language": "en", "url": "https://stackoverflow.com/questions/11245638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Function with arguments in requestAnimationFrame I'm trying to define a recursive function with arguments using "requestAnimationFrame". animate(frameElapsed,points,canvas){ console.log("test"); if(frameElapsed<points.length-1){ requestAnimationFrame(this.animate(frameElapsed+1,points,canvas)); } ... } When I do this, i get the error "Argument of type 'void' is not assignable to parameter of type 'FrameRequestCallback'. So I tried to define an anonymous function that calls animate to solve this problem. animate(frameElapsed,points,canvas){ console.log("test"); if(frameElapsed<points.length-1){ requestAnimationFrame(function() { this.animate(frameElapsed+1,points,canevas); }); } ... } Then, I get "ERROR TypeError: Cannot read property 'animate' of undefined" in my web console. I can't manage to solve this problem. Is there a way to pass arguments to af function called back by requestAnimationFrame ? Thank you for your help ! A: user120242's solution worked for me ! animate(frameElapsed, points, canvas) { console.log("test"); if(frameElapsed < points.length - 1) { requestAnimationFrame(() => { this.animate(frameElapsed + 1, points, canvas); }); } ... } Thank you for your help !
{ "language": "en", "url": "https://stackoverflow.com/questions/62554546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Codeigniter - array of json objects in post In fire bug I view my jquery post request parameters, its like this adults 1 applicants[] [object Object] attendees 1 children 0 In this post request the array called applicants contains json object which I want ti iterate over and pull out values in my codeigniter controller. The json string may look like this ({attendees:"2", adults:"2", children:"0", grptype:"2", 'applicants[]':[{firstname:"John", lastname:"Doe", age:"33", allergies:"true", diabetic:"true", lactose:"false", note:"nuts"}, {firstname:"Jane", lastname:"Doe", age:"34", allergies:"true", diabetic:"false", lactose:"false", note:"pollen"}] }) Look at the applicants[] above, see I have info for two people as a json object. I am not sure how access the data in my controller. see this $applicants = $this->input->post('applicants'); $this->output->append_output("<br/>Here: " . $applicants[0].firstname ); I was thinking $applicants[0] woild refer to the json object and I could just pull outs values on demand. Not sure hat I am doing wrong. Thanks guys. EDIT So I have adjusted my json and it looks like this adults 2 applicants[] {firstname:"John", lastname:"Doe", age:"23", allergies:"true", diabetic:"true", lactose:"false", note:"nuts"} applicants[] {firstname:"Jane", lastname:"Doe", age:"23", allergies:"false", diabetic:"false", lactose:"false", note:""} attendees 2 children 0 Now I am still getting an error saying **Message: json_decode() expects parameter 1 to be string, array given** Any ideas ? EDIT 2 Ok mu data now liiks like this adults 1 applicants[] {"firstname": "John", "lastname": "Doe", "age": "34", "allergies": "true", "diabetic": "true", "lactose": "false", "note": "nuts"} attendees 1 children 0 In the controller id did this $applications = $this->input->post('applicants'); foreach ( $applications as $item) { $item = json_decode($item, true); $this->output->append_output(print_r($item)); } This is the result of that logic Array ( [firstname] => John [lastname] => Doe [age] => 34 [allergies] => true [diabetic] => true [lactose] => false [note] => nuts ) Not sure what I am doing wrong, no matter what I do to access the dater I get an error to the effect that I cannot access it like that. How do I pull out the values ? A: You have to decode it on the server using $applications = json_decode($this->input->post('applicants'), true); So, it'll become an associative array and you can use it like an array, without the second argument (true) in json_decode the json will be converted to an object. Until you decode it, it's only a string (json/java script object notation string). Update: Since it's already an array of objects then you don't need to use json_decode, just loop the array in your view like foreach($applicants as $item) { echo $item->firstname . '<br />'; echo $item->lastname . '<br />'; // ... } According to the edit 2 it should be access as an array echo $item['firstname'] . '<br />' A: try this plz $applicants = $this->input->post('applicants'); $json_output = json_decode($applicants ); foreach ( $json_output as $person) { $this->output->append_output("<br/>Here: " . $person->firstname ); } or $json_output = json_decode($applicants,TRUE ); echo $json_output[0][firstname] ;
{ "language": "en", "url": "https://stackoverflow.com/questions/19073619", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Race conditions I'm currently stuck trying to understand two things related to race conditions. Issue 1: I have been presented with the following question: We consider the digital circuit and the value of its inputs a, and b as given below. For all logic gates, we assume that there is a gate delay of exactly one time unit (i.e. the gate delay equals the time between two dotted lines in the diagram). Give the values of c, d, e, f in the digital circuit for every point of time between 0 and 8. And the answer given is as follows: How exactly is this achieved? This is what I think so far: * *c starts at 1 because a start at 0 *d starts at 0 because b start at 1 *When time is equal to 2 a becomes 1... there is a propogation delay of 1 for c to switch over to 0 hence it becomes 0 at 3 time units *Same logic applies to d *e and f are meant to be constant 1 or 0 but seem to be affected by something. What's really going on here? Is it related to a boolean function or soemthing. If so what? Issue 2: Does anyone have a simple way or logical approach in which to produce a simple circuit (using XOR, AND, OR, NOT, NAND boolean functions with: * *static race condition - when the value is meant to be constant *dynamic race condition - when a value is expected to change Many thanks in advance! A: Okay, so race conditions in asynchronous circuits happen when inputs change at different times for a gate. Let's say your logical function looks like this Ξ» = ab + ~b~a the most straightforward way to implement this function with gates looks like NOTE: I assume your basic building blocks are AND, OR, and NOT. Obviously in CMOS circuits, NAND, NOR and NOT is how you build circuits, but the general principal stays the same. I also assume AND, NOR, and NOT have the same delay when in reality NAND and NOR have different delays if the output goes form 0 to 1 or 1 to 0, and NOT is about 20% faster than NAND or NOR. a ->| AND |-------->| OR | -> Ξ» b ->| 1 | | | | | a ->| NOT |->|AND|->| | b ->| NOT |->| 2 | | | Now, assume that AND and NOT both have a delay of 2ns. That means the OR gate sees the value at it's first position change 2 ns before it sees the value at its second position change. Which means if a and b both go from 1 to 0, you would expect Ξ» to stay the same, since the output of the first AND gate is going from 1 to 0, but the output of the AND gate goes from 0 to 1, meaning the OR condition stays true. However, if you get the output from the second AND gate a little bit after the first AND gate, then your OR gate will momentarily see 0,0 at it's input while transitioning from 1,0 to 0,1. Which means Ξ» will have a momentary dip and it'll look like __ a |___________ __ b |___________ ____ AND1 |_________ _______ AND2 ______| ______ _____ Ξ» |_| If you look at the inputs of the OR gate right between when AND1 goes down and AND2 goes up, it propagates a 0 through the OR gate, and sure enough, there's a dip in the output 2ns later. That's a general overview for how race conditions arise. Hope that helps you understand your question.
{ "language": "en", "url": "https://stackoverflow.com/questions/11002774", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to Write a Data Trigger to open Popup by Clicking dynamic Button in WPF? I'm having a dynamic Button in my WPF application, while clicking any one of the button the popup should open and the corresponding Button should turn the Background Color to Orange and rest of the Button should be in default Backgroud Color using DataTrigger and one more condition, at the time of Popup close, the corresponding Button Background Color should turn to the Default Color. Note: I Can't able to give Name for the Buttons because of Dynamic Creation. Here I placed 5 Buttons without Name Property, Consider the Button as Dynamic Creation My XAML Source Code is <Grid> <Grid Height="30px" VerticalAlignment="Top" Margin="0,50,0,0"> <Grid.ColumnDefinitions> <ColumnDefinition Width="100px"/> <ColumnDefinition Width="100px"/> <ColumnDefinition Width="100px"/> <ColumnDefinition Width="100px"/> <ColumnDefinition Width="100px"/> </Grid.ColumnDefinitions> <Button Content="One" Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75"/> <Button Content="Two" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75"/> <Button Content="Three" Grid.Column="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75"/> <Button Content="Four" Grid.Column="3" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75"/> <Button Content="Five" Grid.Column="4" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75"/> </Grid> <Grid> <Popup Name="sPop" Placement="Mouse" StaysOpen="False"> <Grid> <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" TextWrapping="Wrap" Text="Welcome to Popup Screen"/> </Grid> </Popup> </Grid> </Grid> A: You cannot do it using DataTriggers. DataTriggers are for Data-Based scenarios, so if you are using DataBinding, then use them. Recommended approach : Assign a name to your Popup. And use Behaviors. <Button ...> <Button.Style> <Style TargetType="Button"> <Style.Triggers> <Trigger Property="IsFocused" Value="True"> <Setter Property="Background" Value="Red"/> </Trigger> </Style.Triggers> </Style> </Button.Style> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <i:Interaction.Behaviors> <ei:ConditionBehavior> <ei:ConditionalExpression> <ei:ComparisonCondition LeftOperand="{Binding IsFocused, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" RightOperand="True"/> </ei:ConditionalExpression> </ei:ConditionBehavior> </i:Interaction.Behaviors> <ei:ChangePropertyAction TargetObject="{Binding ElementName=Popup1}" PropertyName="IsOpen" Value="True"/> </i:EventTrigger> </i:Interaction.Triggers> </Button> To use Blend assemblies : Add reference to System.Windows.Interactivity and Microsoft.Expression.Interactions and following namespaces : xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" To revert back old Background of the source Button : <Button> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <i:Interaction.Behaviors> <ei:ConditionBehavior> <ei:ConditionalExpression> <ei:ComparisonCondition LeftOperand="{Binding IsFocused, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" RightOperand="True"/> </ei:ConditionalExpression> </ei:ConditionBehavior> </i:Interaction.Behaviors> <!-- Store Button's old Background --> <ei:ChangePropertyAction TargetObject="{Binding ElementName=Popup1}" PropertyName="Tag" Value="{Binding Background, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}"/> <!-- Change Button's Background --> <ei:ChangePropertyAction PropertyName="Background" Value="Purple"/> <!-- Open Popup --> <ei:ChangePropertyAction TargetObject="{Binding ElementName=Popup1}" PropertyName="IsOpen" Value="True"/> <!-- Save this Button, Popup will use it to revert back its old Background --> <ei:ChangePropertyAction TargetObject="{Binding ElementName=Popup1}" PropertyName="PlacementTarget" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}"/> </i:EventTrigger> </i:Interaction.Triggers> </Button> <Popup x:Name="Popup1" Placement="Mouse" StaysOpen="False"> <i:Interaction.Triggers> <i:EventTrigger EventName="Closed"> <ei:ChangePropertyAction TargetObject="{Binding PlacementTarget, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Popup}}" PropertyName="Background" Value="{Binding Tag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Popup}}" /> </i:EventTrigger> </i:Interaction.Triggers> <Grid> <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" TextWrapping="Wrap" Text="Welcome to Popup Screen"/> </Grid> </Popup> A: I tried to achieve what you asking for without using DataTrigger. This is simple style trigger for changing background: <Style TargetType="Button"> <Style.Triggers> <Trigger Property="Button.IsFocused" Value="True"> <Setter Property="Button.Background" Value="Red" /> </Trigger> </Style.Triggers> </Style> Each your button can handle Click event: <Button Content="One" Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" Click="Button_Click" /> ... And we need to take your Popup somehow. I just named it: <Popup Name="popup" Placement="Mouse" StaysOpen="False"> ... Click event is simple: private void Button_Click(object sender, RoutedEventArgs e) { var button = sender as Button; if (popup.IsOpen) { popup.IsOpen = false; } popup.PlacementTarget = button; popup.IsOpen = true; } So it works like you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/34304313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Expensive to set UILabel.attributedText to the same value? I have a view controller within my app that I use for debugging purposes to display some of the internals of the app (only for local xcode builds, the app store version doesn't have this controller). In this controller, I have a label which I want to reflect the state of an internal component (specifically, I want it to display whether that component is enabled or disabled). My questions: #1: Is it expensive to set the .attributedText property of a UILabel to the same value as it was before, or should I cache the old value and only set the property when it changes? #2: What about the .text (non-attributed) property? I'm currently using the following code: // Schedule timer to update the control panel. (This is debug-only, so not worth // the complexity of making this event-based) Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [weak self] timer in DispatchQueue.main.async { // Stop timer if we've been dealloced or are no longer being presented guard let strongSelf = self, strongSelf.isBeingPresented else { timer.invalidate() return } // "Something Enabled / Disabled" label let somethingIsEnabled = strongSelf.someDepenency.isEnabled let somethingEnabledString = NSMutableAttributedString(string: "Something ") somethingEnabledString.append(NSAttributedString(string: isEnabled ? "Enabled" : "Disabled", attributes: isEnabled ? nil : [NSForegroundColorAttributeName: UIColor(xtHardcodedHexValue: "0xCD0408")])) strongSelf.somethingEnabledLabel?.attributedText = somethingEnabledString } } A: Before I share some numbers, I'd highly recommend to not perform such premature optimizations. Consider the following code: private func getAttributedString() -> NSMutableAttributedString{ let attributedString = NSMutableAttributedString(string: "Something ") attributedString.append(NSAttributedString(string: "Enabled", attributes: [NSForegroundColorAttributeName: UIColor(rgb: 0xCD0408)])) return attributedString } //overwrites attributed text 100000 times @IBAction func overwriteAttributedText(_ sender: Any) { let timeBeforeAction = Date.init() print ("Time taken to overwrite attributed text is ") for _ in 1 ... 100000{ label.attributedText = getAttributedString() } let timeAfterAction = Date.init() let timeTaken = timeAfterAction.timeIntervalSince(timeBeforeAction) print(timeTaken) } //overwrites attributed text 100 times @IBAction func cacheAttributedText(_ sender: Any) { let timeBeforeAction = Date.init() print ("Time taken to selectively overwrite attributed text is ") for i in 1 ... 100000{ if i % 1000 == 0 { label.attributedText = getAttributedString() } } let timeAfterAction = Date.init() let timeTaken = timeAfterAction.timeIntervalSince(timeBeforeAction) print(timeTaken) } //overwrites text 100000 times @IBAction func overWriteText(_ sender: Any) { let defaultText = "Hello World" let timeBeforeAction = Date.init() print ("Time taken to overwrite text is ") for _ in 1 ... 100000{ label.text = defaultText } let timeAfterAction = Date.init() let timeTaken = timeAfterAction.timeIntervalSince(timeBeforeAction) print(timeTaken) } Here are the results: Time taken to overwrite attributed text is 0.597925961017609 Time taken to selectively overwrite attributed text is 0.004891037940979 Time taken to overwrite text is 0.0462920069694519 The results speak for themselves, but I leave it you if such optimizations are even needed. A: While 7to4 is correct in regards to premature optimizations, the demo code he's using is misleading. The .attributedText setter itself is actually faster than setting .text; creating the attributed string is the bottleneck. Here's a modified version of his code that includes a method where the attributed string is pre-cached: private func getAttributedString() -> NSMutableAttributedString{ let attributedString = NSMutableAttributedString(string: "Something ") attributedString.append(NSAttributedString(string: "Enabled", attributes: [NSAttributedStringKey.foregroundColor: UIColor.red])) return attributedString } //overwrites attributed text 100000 times @IBAction func overwriteAttributedText(_ sender: Any) { let timeBeforeAction = Date.init() print ("Time taken to overwrite attributed text is ") for _ in 1 ... 100000{ label.attributedText = getAttributedString() } let timeAfterAction = Date.init() let timeTaken = timeAfterAction.timeIntervalSince(timeBeforeAction) print(timeTaken) } //overwrites attributed text 100000 times with a cached string @IBAction func overwriteAttributedTextWithCachedString(_ sender: Any) { let timeBeforeAction = Date.init() let attributedString = getAttributedString() print ("Time taken to overwrite attributed text with cached string is ") for _ in 1 ... 100000{ label.attributedText = attributedString } let timeAfterAction = Date.init() let timeTaken = timeAfterAction.timeIntervalSince(timeBeforeAction) print(timeTaken) } //overwrites text 100000 times @IBAction func overWriteText(_ sender: Any) { let defaultText = "Hello World" let timeBeforeAction = Date.init() print ("Time taken to overwrite text is ") for _ in 1 ... 100000{ label.text = defaultText } let timeAfterAction = Date.init() let timeTaken = timeAfterAction.timeIntervalSince(timeBeforeAction) print(timeTaken) } Results: Time taken to overwrite attributed text is 0.509455919265747 Time taken to overwrite attributed text with cached string is 0.0451710224151611 Time taken to overwrite text is 0.0634149312973022 On average, the .attributedText setter itself is about 30~40% faster than the .text setter. That said, take note that it probably takes a lot of labels before this actually becomes a bottleneck. Also remember that (if by some crazy circumstance) this is your bottleneck, this optimization is only effective if the attributed string is pre-allocated ahead of time.
{ "language": "en", "url": "https://stackoverflow.com/questions/43592287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: NVARCHAR to VARCHAR2 insert I have the following table structure: UDA_ID (NUMBER) Translation (NVARCHAR2) I need to insert in the table UDA_ID (NUMBER) Translation (VARCHAR2) How do i convert NVARCHAR2 to VARCHAR2 ? A: You can try like this: insert into mytable(Translation) (select to_char(Translation) from sometable); or like insert into mytable(Translation) (select to_char('yourValue') from dual);
{ "language": "en", "url": "https://stackoverflow.com/questions/34648744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: VB 6.0 debugging breakpoint doesn't hit I have a VB 6.0 Project having Class (cls) files. When I start (Debug) my project, and try to execute following statement in Classic ASP page, Set objMyObject = Server.CreateObject("ProjName.ClassName") No breakpoint is hit and following error occurs. Microsoft VBScript runtime error '800a01ad' ActiveX component can't create object While if I use the same statement in another VB Project (test project) then breakpoint hits with no error. Can anyone help ? A: Well you are trying to create an instance of a COM object with the name 'ProjName.ClassName' - which is unlikely to be a real COM object. Either your COM class needs to be one that has been registered in Windows, or it needs to be a class defined within your VB project. The example in MSDN is: Sub CreateADODB() Dim adoApp As Object adoApp = CreateObject("ADODB.Connection") End Sub Where ADODB.Connection is a COM class that has been previously registered in Windows. The code you have provided above is trying to instantiate a non existant class (unless it is already within the same VB project). You say that the other project this works, then I will hazard a guess that the test project has a class called ClassName. Ok -Updated. The error code is not 'DLL Missing' - It is likely to be some reason why the COM object could not be instantiated. The following Microsoft support page suggests some reasons and ways of tracking down the problem. Its likely to be some sort of missing dependency to the DLL. http://support.microsoft.com/kb/194801
{ "language": "en", "url": "https://stackoverflow.com/questions/6792162", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Line Chart (Currency) I'm trying to develop a line chart using a third-party API and I'm using both react-chartjs-2 and chart.js The problem is, the line doesn't appear in the chart and I assume the reason is: the date. This is my first time to develop a web application using Chart.js. Also, I read the documentations and couldn't find a solution. dateDate which is an array that contains all dates. The Array has dates inside of it, not objects. I console.log'd the date in using the map loop and it worked, but it doesn't appear in the chart. I don't know the reason behind it. Here is the console.log: 2023-01-10 App.jsx:66 2023-01-11 App.jsx:66 2023-01-12 App.jsx:66 2023-01-13 App.jsx:66 2023-01-14 App.jsx:66 2023-01-15 App.jsx:66 2023-01-16 App.jsx:66 2023-01-17 App.jsx:66 2023-01-18 App.jsx:66 2023-01-19 App.jsx:66 2023-01-20 App.jsx:66 2023-01-21 App.jsx:66 2023-01-22 App.jsx:66 2023-01-23 RESTful API When you check the picture of the API, you'll find out that the date is the key and its value is an object of all costs. So, I have to separate them all. Line Chart function App() { const [euroCurrencyData, setEuroCurrencyData] = useState([]); const [dateData, setDateData] = useState([]); const [candianCurrencyData, setCandianCurrencyData] = useState([]); // CHART DATA const [chartData, setChartData] = useState({ labels: dateData.map((date) => date), datasets: [ { label: "EUR", data: euroCurrencyData.map((currency) => currency.EUR), backgroundColor: ["red", "green", "blue", "black"], }, { label: "CAD", data: candianCurrencyData.map((currency) => currency.CAD), backgroundColor: ["green", "blue", "yellow", "green"], }, ], }); // EURO FETCH const getEuroData = async () => { const res = await axios.get( "https://api.freecurrencyapi.com/v1/historical?apikey=fGfh2W2M2jvc4drZkLCdOUhJSvQqRn0ZONHPWvTq&currencies=EUR&date_from=2022-12-23T07%3A50%3A10.865Z&date_to=2023-01-23T07%3A50%3A10.866Z" ); const data = res.data.data; const euroCurrency = Object.values(data); const currencyDate = Object.keys(data); setEuroCurrencyData(euroCurrency); setDateData(currencyDate); }; // CANDIAN FETCH const getCandianData = async () => { const res = await axios.get( "https://api.freecurrencyapi.com/v1/historical?apikey=fGfh2W2M2jvc4drZkLCdOUhJSvQqRn0ZONHPWvTq&currencies=CAD&date_from=2022-12-23T13%3A05%3A35.472Z&date_to=2023-01-23T13%3A05%3A35.473Z" ); const data = res.data.data; const candianCurrency = Object.values(data); setCandianCurrencyData(candianCurrency); }; useEffect(() => { getEuroData(); getCandianData(); }, []); return ( <div className="App"> <div className="line-chart-container"> <LineChart chartData={chartData} /> </div> </div> ); } import { Line } from "react-chartjs-2"; import { Chart as ChartJS } from "chart.js"; import Chart from "chart.js/auto"; const LineChart = ({ chartData }) => { return <Line data={chartData} />; };
{ "language": "en", "url": "https://stackoverflow.com/questions/75222647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: gperftools: modify makefile to install in a different folder? I was installing gperftools: https://code.google.com/p/gperftools/ Everything worked, and I see that the project links to /usr/local/lib I'd like to put the library in a folder local to my project, instead. The reasoning behind this is that I'm putting the project on different machines, and I just need to link against the libprofiler and libtcmalloc libraries, instead of the entire package, that also comes with the pprof and such. The machines also have different architectures, so I actually need to build into that directory, instead of copy-pasting over Is this a trivial thing to do? A: gperftools uses autoconf/automake, so you can do ./configure --prefix=/path/to/whereever make make install This works for all autotools projects, unless they are severely broken. On that note, it is generally a good idea to read the INSTALL file in a source tree to find out about this sort of stuff. There is one in the gperftools sources, and this is documented there.
{ "language": "en", "url": "https://stackoverflow.com/questions/27387958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Microsoft.EntityFrameworkCore dont have method IsOptional() for PropertyBuilder I try transfer my solution from .Net Framowork to .Net Core.When I did mapping and I dint found method IsOptional() for PropertyBuilder: .Net Framowork: public class PictureMap : EntityTypeConfiguration<PictureExt> { public PictureMap() { this.ToTable("Picture"); this.HasKey(p => p.Id); this.Property(p => p.SeoFilename).HasMaxLength(300); this.Property(p => p.ExternalUrl).IsOptional(); } } and its work , but use EntityFrameworkCore:look in image where I might found IsOptional()? A: There is not IsOptional in EntityFrameworkCore but there is IsRequired to do the oposite. By default field are nullable if the C# type is nullable. A: You can achieve the same effect with IsRequired(false). This will override annotations like [Required] so be careful. On another thread, it was pointed out that annotations that affect EF models or make no sense [Display...] should not be part of the EF model. Move them to a ViewModel or DTO object.
{ "language": "en", "url": "https://stackoverflow.com/questions/52328577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reading multiple offline html files to a list in R I have rawdata as 20 offline html files stored in following format ../rawdata/1999_table.html ../rawdata/2000_table.html ../rawdata/2001_table.html ../rawdata/2002_table.html . . ../rawdata/2017_table.html These files contain tables that I am extracting and reshaping to a particular format. I want to read these files at once to a list and process them one by one through a function that I have written. What I tried: I put the names of these files into an Excel file called filestoread.xlsx and used a for loop to load these files using the names mentioned in the sheet. But it doesn't seem to work filestoread <- fread("../rawdata/filestoread.csv") x <- list() for (i in nrow(filestoread)) { x[[i]] <- read_html(paste0("../rawdata/", filestoread[i])) } How can this be done? Also, after reading the HTML files I want to extract the tables from them and reshape them using a function I wrote after converting it to a data table. My final objective is to rbind all the tables and have a single data table with year wise entries of the tables in the html file. A: First save path of your data on one of the following ways. Either, hardcoded filestoread <- paste0("../rawdata/", 1999:2017, "_table.html") or reading all html files in the directory filestoread <- list.files(path = "../rawdata/", pattern="\\.html$") Then use lapply() library(rvest) lapply(filestoread, function(x) try(read_html(x))) Note: try() runs the code even when there is a file missing (throwing error). The second part of your question is a little broad, depends on the content of your files, and there are already some answers, you could consider e.g. this answer. In principle you use a combination of ?html_nodes and ?html_table.
{ "language": "en", "url": "https://stackoverflow.com/questions/51707309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: deleting arrays during run time in C++ to spare some memory I have a C++ script running with a C++98 version on a microcontroller ( No upgrade is possible). In this script I need to initialize two vectors of doubles of 405 already existing elements each. I tried initializating two arrays : double a[405]= {7.05925826e+07, ...}; and double b [405]= {arr[0], arr[0]*arr[1]...};. a[405] is defined in the following way: double a[405] = {a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15], a[16], a[17], a[18], a[19], a[20], a[21], a[22], a[23], a[24], a[25], a[26], a[0]*a[0], a[0]*a[1], a[0]*a[2], a[0]*a[3], a[0]*a[4], a[0]*a[5], a[0]*a[6], a[0]*a[7], a[0]*a[8], a[0]*a[9], a[0]*a[10], a[0]*a[11], a[0]*a[12], a[0]*a[13], a[0]*a[14], a[0]*a[15], a[0]*a[16], a[0]*a[17], a[0]*a[18], a[0]*a[19], a[0]*a[20], a[0]*a[21], a[0]*a[22], a[0]*a[23], a[0]*a[24], a[0]*a[25], a[0]*a[26], a[1]*a[1], a[1]*a[2], a[1]*a[3], a[1]*a[4], a[1]*a[5], a[1]*a[6], a[1]*a[7], a[1]*a[8], a[1]*a[9], a[1]*a[10], a[1]*a[11], a[1]*a[12], a[1]*a[13], a[1]*a[14], a[1]*a[15], a[1]*a[16], a[1]*a[17], a[1]*a[18], a[1]*a[19], a[1]*a[20], a[1]*a[21], a[1]*a[22], a[1]*a[23], a[1]*a[24], a[1]*a[25], a[1]*a[26], a[2]*a[2], a[2]*a[3], a[2]*a[4], a[2]*a[5], a[2]*a[6], a[2]*a[7], a[2]*a[8], a[2]*a[9], a[2]*a[10], a[2]*a[11], a[2]*a[12], a[2]*a[13], a[2]*a[14], a[2]*a[15], a[2]*a[16], a[2]*a[17], a[2]*a[18], a[2]*a[19], a[2]*a[20], a[2]*a[21], a[2]*a[22], a[2]*a[23], a[2]*a[24], a[2]*a[25], a[2]*a[26], a[3]*a[3], a[3]*a[4], a[3]*a[5], a[3]*a[6], a[3]*a[7], a[3]*a[8], a[3]*a[9], a[3]*a[10], a[3]*a[11], a[3]*a[12], a[3]*a[13], a[3]*a[14], a[3]*a[15], a[3]*a[16], a[3]*a[17], a[3]*a[18], a[3]*a[19], a[3]*a[20], a[3]*a[21], a[3]*a[22], a[3]*a[23], a[3]*a[24], a[3]*a[25], a[3]*a[26], a[4]*a[4], a[4]*a[5], a[4]*a[6], a[4]*a[7], a[4]*a[8], a[4]*a[9], a[4]*a[10], a[4]*a[11], a[4]*a[12], a[4]*a[13], a[4]*a[14], a[4]*a[15], a[4]*a[16], a[4]*a[17], a[4]*a[18], a[4]*a[19], a[4]*a[20], a[4]*a[21], a[4]*a[22], a[4]*a[23], a[4]*a[24], a[4]*a[25], a[4]*a[26], a[5]*a[5], a[5]*a[6], a[5]*a[7], a[5]*a[8], a[5]*a[9], a[5]*a[10], a[5]*a[11], a[5]*a[12], a[5]*a[13], a[5]*a[14], a[5]*a[15], a[5]*a[16], a[5]*a[17], a[5]*a[18], a[5]*a[19], a[5]*a[20], a[5]*a[21], a[5]*a[22], a[5]*a[23], a[5]*a[24], a[5]*a[25], a[5]*a[26], a[6]*a[6], a[6]*a[7], a[6]*a[8], a[6]*a[9], a[6]*a[10], a[6]*a[11], a[6]*a[12], a[6]*a[13], a[6]*a[14], a[6]*a[15], a[6]*a[16], a[6]*a[17], a[6]*a[18], a[6]*a[19], a[6]*a[20], a[6]*a[21], a[6]*a[22], a[6]*a[23], a[6]*a[24], a[6]*a[25], a[6]*a[26], a[7]*a[7], a[7]*a[8], a[7]*a[9], a[7]*a[10], a[7]*a[11], a[7]*a[12], a[7]*a[13], a[7]*a[14], a[7]*a[15], a[7]*a[16], a[7]*a[17], a[7]*a[18], a[7]*a[19], a[7]*a[20], a[7]*a[21], a[7]*a[22], a[7]*a[23], a[7]*a[24], a[7]*a[25], a[7]*a[26], a[8]*a[8], a[8]*a[9], a[8]*a[10], a[8]*a[11], a[8]*a[12], a[8]*a[13], a[8]*a[14], a[8]*a[15], a[8]*a[16], a[8]*a[17], a[8]*a[18], a[8]*a[19], a[8]*a[20], a[8]*a[21], a[8]*a[22], a[8]*a[23], a[8]*a[24], a[8]*a[25], a[8]*a[26], a[9]*a[9], a[9]*a[10], a[9]*a[11], a[9]*a[12], a[9]*a[13], a[9]*a[14], a[9]*a[15], a[9]*a[16], a[9]*a[17], a[9]*a[18], a[9]*a[19], a[9]*a[20], a[9]*a[21], a[9]*a[22], a[9]*a[23], a[9]*a[24], a[9]*a[25], a[9]*a[26], a[10]*a[10], a[10]*a[11], a[10]*a[12], a[10]*a[13], a[10]*a[14], a[10]*a[15], a[10]*a[16], a[10]*a[17], a[10]*a[18], a[10]*a[19], a[10]*a[20], a[10]*a[21], a[10]*a[22], a[10]*a[23], a[10]*a[24], a[10]*a[25], a[10]*a[26], a[11]*a[11], a[11]*a[12], a[11]*a[13], a[11]*a[14], a[11]*a[15], a[11]*a[16], a[11]*a[17], a[11]*a[18], a[11]*a[19], a[11]*a[20], a[11]*a[21], a[11]*a[22], a[11]*a[23], a[11]*a[24], a[11]*a[25], a[11]*a[26], a[12]*a[12], a[12]*a[13], a[12]*a[14], a[12]*a[15], a[12]*a[16], a[12]*a[17], a[12]*a[18], a[12]*a[19], a[12]*a[20], a[12]*a[21], a[12]*a[22], a[12]*a[23], a[12]*a[24], a[12]*a[25], a[12]*a[26], a[13]*a[13], a[13]*a[14], a[13]*a[15], a[13]*a[16], a[13]*a[17], a[13]*a[18], a[13]*a[19], a[13]*a[20], a[13]*a[21], a[13]*a[22], a[13]*a[23], a[13]*a[24], a[13]*a[25], a[13]*a[26], a[14]*a[14], a[14]*a[15], a[14]*a[16], a[14]*a[17], a[14]*a[18], a[14]*a[19], a[14]*a[20], a[14]*a[21], a[14]*a[22], a[14]*a[23], a[14]*a[24], a[14]*a[25], a[14]*a[26], a[15]*a[15], a[15]*a[16], a[15]*a[17], a[15]*a[18], a[15]*a[19], a[15]*a[20], a[15]*a[21], a[15]*a[22], a[15]*a[23], a[15]*a[24], a[15]*a[25], a[15]*a[26], a[16]*a[16], a[16]*a[17], a[16]*a[18], a[16]*a[19], a[16]*a[20], a[16]*a[21], a[16]*a[22], a[16]*a[23], a[16]*a[24], a[16]*a[25], a[16]*a[26], a[17]*a[17], a[17]*a[18], a[17]*a[19], a[17]*a[20], a[17]*a[21], a[17]*a[22], a[17]*a[23], a[17]*a[24], a[17]*a[25], a[17]*a[26], a[18]*a[18], a[18]*a[19], a[18]*a[20], a[18]*a[21], a[18]*a[22], a[18]*a[23], a[18]*a[24], a[18]*a[25], a[18]*a[26], a[19]*a[19], a[19]*a[20], a[19]*a[21], a[19]*a[22], a[19]*a[23], a[19]*a[24], a[19]*a[25], a[19]*a[26], a[20]*a[20], a[20]*a[21], a[20]*a[22], a[20]*a[23], a[20]*a[24], a[20]*a[25], a[20]*a[26], a[21]*a[21], a[21]*a[22], a[21]*a[23], a[21]*a[24], a[21]*a[25], a[21]*a[26], a[22]*a[22], a[22]*a[23], a[22]*a[24], a[22]*a[25], a[22]*a[26], a[23]*a[23], a[23]*a[24], a[23]*a[25], a[23]*a[26], a[24]*a[24], a[24]*a[25], a[24]*a[26], a[25]*a[25], a[25]*a[26], a[26]*a[26]}; and then converting them using this function: std::vector<double > ArrayToVector(double* arr, size_t arr_len) { return std::vector<double>(arr, arr + arr_len); } std::vector<double> vec1= ArrayToVector(a,405); std::vector<double> vec2= ArrayToVector(b,405); The conversion of the arrays into a vectors causes memory problems. I am looking for a way to delete the first array a[405] just after converting it to vector in order to spare some memory for the second array conversion. I tried using new operator but that didn't work for me . Any other solution to reduce memory usage is appreciated. Then I use a[] and b[] to calculate their scalar product using this function: double scalar_product(std::vector<double> a, std::vector<double> b) { if( a.size() != b.size() ) // error check { //puts( "Error a's size not equal to b's size" ) ; return -1 ; // not defined } // compute double product = 0; for (unsigned int i = 0; i <= a.size() - 1; i++) product += (a[i])*(b[i]); // += means add to product return product; } A: As some people have already suggested in comments, you don't really need to convert your arrays to vectors - just work directly with the arrays. All you need to add is the size of the arrays as a third parameter to your function. For that you obviously need to know the size, but since this is running on a microcontroller, where memory budget is tight, I'm relatively certain that you have access to the size info. So it could look like: double scalar_product(double a[], double b[], unsigned int size) { // compute double product = 0; for (unsigned int i = 0; i <= size - 1; i++) product += (a[i])*(b[i]); // += means add to product return product; } I'm assuming that their sizes are the same (they should) but even if not, you could use this to calculate a (partial) scalar product for two differently sized arrays, by supplying the shorter one's size. A: You are not allocating your double[] arrays dynamically via new[], so they cannot be freed dynamically. They are being declared in automatic memory, so they will be freed only when they go out of scope. Since you are concerned with limited memory usage, your best option is to simply not convert your double[] arrays to std::vector<double> at all. Change your scalar_product() function instead so it can handle the original double[] arrays as-is, eg: double scalar_product(const double *a, size_t a_size, const double *b, size_t b_size) { if( a_size != b_size ) // error check { //puts( "Error a's size not equal to b's size" ) ; return -1 ; // not defined } // compute double product = 0; for (size_t i = 0; i < a_size; ++i) product += (a[i])*(b[i]); // += means add to product return product; } double a[405] = ...; double b[405] = ...; double product = scalar_product(a, 405, b, 405); /* if, for some reason, you also needed to get the product of vectors, you can do this: double scalar_product(const std::vector<double> &a, const std::vector<double> &b) { return scalar_product(&a[0], a.size(), &b[0], b.size()); } vector<double> a = ...; vector<double> b = ...; double product = scalar_product(a, b); */ Or: double scalar_product(const double *a, const double *b, size_t n) { // compute double product = 0; for (size_t i = 0; i < n; ++i) product += (a[i])*(b[i]); // += means add to product return product; } double a[405] = ...; double b[405] = ...; double product = scalar_product(a, b, 405); /* if, for some reason, you also needed to get the product of vectors, you can do this: double scalar_product(const std::vector<double> &a, const std::vector<double> &b) { return (a.size() == b.size()) ? scalar_product(&a[0], &b[0], a.size()) : -1.0; } vector<double> a = ...; vector<double> b = ...; double product = scalar_product(a, b); */ Alternatively, you can let the compiler deduce the array sizes for you, if you are passing in the original arrays directly, and not passing in pointers to the arrays: template<size_t a_size, size_t b_size> double scalar_product(const double (&a)[a_size], const double (&b)[b_size]) { if( a_size != b_size ) // error check { //puts( "Error a's size not equal to b's size" ) ; return -1 ; // not defined } // compute double product = 0; for (size_t i = 0; i < a_size; ++i) product += (a[i])*(b[i]); // += means add to product return product; } double a[405] = ...; double b[405] = ...; double product; product = scalar_product(a, b); // OK double *pa = a; double *pb = b; product = scalar_product(pa, pb); // COMPILER ERROR /* this approach doesn't work with vectors, so you will need a separate overload of scalar_product() for that... */ Or: template<size_t N> double scalar_product(const double (&a)[N], const double (&b)[N]) { // compute double product = 0; for (size_t i = 0; i < N; ++i) product += (a[i])*(b[i]); // += means add to product return product; } double a[405] = ...; double b[405] = ...; double product; product = scalar_product(a, b); // OK double c[404] = ...; double d[405] = ...; product = scalar_product(c, d); // COMPILER ERROR /* this approach doesn't work with vectors, so you will need a separate overload of scalar_product() for that... */ Otherwise, if the array size is constant at compile-time, then just hard-code it: const size_t ArrSize = 405; double scalar_product(const double (&a)[ArrSize], const double (&b)[ArrSize]) { // compute double product = 0; for (size_t i = 0; i < ArrSize; ++i) product += (a[i])*(b[i]); // += means add to product return product; } double a[ArrSize] = ...; double b[ArrSize] = ...; double product = scalar_product(a, b); /* this approach doesn't work with vectors, so you will need a separate overload of scalar_product() for that... */ A: An array must be dynamically allocated (using the new[] operator) in order to use the delete[] operator to free it. As the comments have mentioned, you should post how you create your arrays so we can get a better understanding of how they are stored in memory. double a* = new double[size]; // do stuff with a delete[] a; The above example is legal and will do what you asked.
{ "language": "en", "url": "https://stackoverflow.com/questions/64557853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to find the distribution in python? I have data set from Goodreads with Number of books read over a year with details like number of pages of the each book, date read etc. I want to know in which month/week I have read most/least. How do I do that in Python ?
{ "language": "en", "url": "https://stackoverflow.com/questions/34505475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iCloud - Moving the file completed I can able to move a file from the local directory to iCloud using the condition setUbiquitous:YES. The file has been moved successfully. If the file size is large, it takes certain time to complete moving. Is there any method to identify, if the file has completed moving to iCloud? Thanks in advance for your answers. A: Note: I haven't done this myself, so all the info below is purely from reading the documentation: The NSMetadataItem class has, among others, an attribute key called NSMetadataUbiquitousItemIsUploadedKey. Knowing this, you should be able to set up an NSMetadataQuery that notifies you once the item has been uploaded. A: You can check with NSUURL getResourceValue:forKey:error: method NSURLUbiquitousItemIsUploadedKeyβ€”Indicates that locally made changes were successfully uploaded to the iCloud server. NSURLUbiquitousItemIsUploadingKeyβ€”Indicates that locally made changes are being uploaded to the iCloud server now. NSURLUbiquitousItemPercentUploadedKeyβ€”For an item being uploaded, indicates what percentage of the changes have already been uploaded to the server. For details: https://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/iCloud/iCloud.html#//apple_ref/doc/uid/TP40007072-CH5-SW1
{ "language": "en", "url": "https://stackoverflow.com/questions/8047950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: OSX equivalent of SymGetLineFromAddr or SymGetLineFromAddr64 I want to add source file and line numbers to my backtraces, on Windows there is a nice function SymGetLineFromAddr64 which provides such information if available. I can't find something similar on mac. dladdr outputs only symbol name without file information. A: There is no public equivalent to SymGetLineFromAddr64 on OS X, but you can get source file and line number with the atos(1) developer tool. Here is some sample code to get a fully symbolized backtrace. #import <Foundation/Foundation.h> static NSArray * Backtrace(NSArray *callStackReturnAddresses) { NSMutableArray *backtrace = [NSMutableArray new]; for (NSNumber *address in callStackReturnAddresses) { NSString *hexadecimalAddress = [NSString stringWithFormat:@"0x%0*lx", (int)sizeof(void*) * 2, address.unsignedIntegerValue]; NSTask *task = [NSTask new]; NSPipe *pipe = [NSPipe pipe]; task.launchPath = @"/usr/bin/xcrun"; task.arguments = @[ @"atos", @"-d", @"-p", @(getpid()).description, hexadecimalAddress ]; task.standardOutput = pipe; NSString *symbol = @"???"; @try { [task launch]; NSData *data = [pipe.fileHandleForReading readDataToEndOfFile]; symbol = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; symbol = [symbol stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]; [task waitUntilExit]; } @catch (NSException *exception) {} [backtrace addObject:[NSString stringWithFormat:@"%@ %@", hexadecimalAddress, symbol]]; } return [backtrace copy]; } static void test(void) { NSLog(@"%@", Backtrace([NSThread callStackReturnAddresses])); } int main(int argc, const char * argv[]) { test(); return 0; } Running this code will produce the following output: 0x000000010000134e test (in a.out) (main.m:31) 0x000000010000131b main (in a.out) (main.m:36) 0x00007fff8c0935fd start (in libdyld.dylib) + 1
{ "language": "en", "url": "https://stackoverflow.com/questions/29230654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Rubycas-server character encoding issue (Internal server error) Since a couple of months ago we are using in production environment a rubycass-server 1.0 validating against Active directory (Microsoft 2008 r2 server). We are using ruby 1.9.2p180, sinatra-1.1.3... We are having problems with Spanish and Catalan languages. If a user types Γ± or Γ§ … in the login or password field when he sends the form it produces an β€œinternal server error” message. I have activated the debug mode in the config.yml options but when this error rises it does not appear any hint into the log file. A couple of days ago I tried the last version of rubycas 1.1.0 and this error (Internal server..) didn’t happen but if the login/password had any of this characters the validation always failed with the message β€œpassword incorrect”. I think it is an encoding error. Has anybody found a solution to this problem? Thanks in advance, A: Solved. Problem was caused because we were using an old version of net-ldap (0.1.1). I updated this gem to the last version (0.3.1) and works like a charm.
{ "language": "en", "url": "https://stackoverflow.com/questions/10976728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: alternative method for getting http response in android I get the null response with HttpResponse response = client.execute(post); This method some time give correct response but mostly give the null response without any code change. I also tried it using the AsyncTask, but got same behavior. Following is my code with AsyncTask. If any suggestion please tell me. Thank you. protected void onPreExecute() { client = new DefaultHttpClient(); HttpConnectionParams.setConnectionTimeout(client.getParams(), TIMEOUT_MS); HttpConnectionParams.setSoTimeout(client.getParams(), TIMEOUT_MS); post = new HttpPost("http://www.google.co.in/m"); pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("hl", "en")); pairs.add(new BasicNameValuePair("gl", "us")); pairs.add(new BasicNameValuePair("source", "android-launcher-widget")); pairs.add(new BasicNameValuePair("q", "persistent")); try { post.setEntity(new UrlEncodedFormEntity(pairs)); SystemClock.sleep(400); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.dialog.setMessage("starts..."); this.dialog.show(); } @Override protected HttpResponse doInBackground(Void... arg0) { try { HttpResponse response = client.execute(post); //this returns null responce if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return response; } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { //Toast.makeText(url.this, "problem in execute....", 20).show(); // TODO Auto-generated catch block //put the balance is empty dialog box here. e.printStackTrace(); }catch(NullPointerException e) { e.printStackTrace(); } return null; } my log says.. 04-20 20:19:55.877: WARN/System.err(365): java.net.UnknownHostException: www.google.co.in 04-20 20:19:55.897: WARN/System.err(365): at java.net.InetAddress.lookupHostByName(InetAddress.java:506) 04-20 20:19:55.897: WARN/System.err(365): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294) 04-20 20:19:55.907: WARN/System.err(365): at java.net.InetAddress.getAllByName(InetAddress.java:256) 04-20 20:19:55.907: WARN/System.err(365): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136) 04-20 20:19:55.907: WARN/System.err(365): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 04-20 20:19:55.927: WARN/System.err(365): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 04-20 20:19:55.927: WARN/System.err(365): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:348) 04-20 20:19:55.937: WARN/System.err(365): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 04-20 20:19:55.937: WARN/System.err(365): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 04-20 20:19:55.947: WARN/System.err(365): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 04-20 20:19:55.947: WARN/System.err(365): at comm.sample.Urlasync$AddStringTask.doInBackground(Urlasync.java:82) 04-20 20:19:55.947: WARN/System.err(365): at comm.sample.Urlasync$AddStringTask.doInBackground(Urlasync.java:1) 04-20 20:19:55.947: WARN/System.err(365): at android.os.AsyncTask$2.call(AsyncTask.java:185) 04-20 20:19:55.957: WARN/System.err(365): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306) 04-20 20:19:55.957: WARN/System.err(365): at java.util.concurrent.FutureTask.run(FutureTask.java:138) 04-20 20:19:55.957: WARN/System.err(365): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088) 04-20 20:19:55.967: WARN/System.err(365): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581) 04-20 20:19:55.967: WARN/System.err(365): at java.lang.Thread.run(Thread.java:1019) A: I ran into this same problem a few days ago. Running the HttpResponse on its own thread fixed the Null response. Try using java threading instead of the android async task. http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html
{ "language": "en", "url": "https://stackoverflow.com/questions/5695326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Testing ServiceLoader in Eclipse Plugins I have four Eclipse plugin projects (create a new Java Project, right-click, configure, Convert to Plugin Project) in my workspace. The first (my.runtime) contains an interface (MyFactoryInterface) and a class (MyClient) that defines a method (List<String> getAllFactoryNames()) that loads all implementations of that interface via java.util.ServiceLoader and calls a method (String getName()) on them, collecting the results and returning them in a list. To test that class, I have a JUnit test in the second project (my.runtime.test, set up with my.runtime as Fragment-Host), checking if the name returned by a dummy implementation(MyDummy, returning "Dummy") I have in the my.runtime.test project is in the list returned by MyClient.getAllFactoryNames(). So far, it works fine. In the third project (my.extension, with my.runtime as dependency) I have a class (MyHello) that uses the names returned by MyClient.getAllFactoryNames() to return a list of greetings ("Hello "+name). Again, to test this, I have a project (my.extension.test, with my.extension as Fragment-Host) containing another Implementation (MyWorld, returning "World" as name) and a JUnit test case checking if "Hello World" is in the greetings returned by MyHello.getGreetings(). This test fails, as MyClient still only finds the MyDummy implementation, and not the MyWorld implementation. Both implementations are accompanied by matching entries in META-INF/services/my.runtime.MyFactoryInterface files. I currently use the following code to load the implementations: ServiceLoader<MyFactoryInterface> myFactoryLoader = ServiceLoader.load(MyFactoryInterface.class); for (MyFactoryInterface myFactory : myFactoryLoader) { I know that I can supply a ClassLoader as a second argument to ServiceLoader.load, but I have no idea how to get one that knows all plugin projects... any suggestions? Or is ServiceLoader not the right tool for this problem? A: If anyone stumbles over the same problem: the combination of ServiceLoader.load(MyFactoryInterface.class, Thread.currentThread().getContextClassLoader()) in MyClient and Thread.currentThread().setContextClassLoader(MyWorld.class.getClassLoader()); in the second test did the job.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Return from function or pass into function? What would be the better way to process this data? Is this just a matter of personal preference? Guessing 2 is less prone to accidently modifying the monday...friday arrays and there is less code at this layer. Is there a best practices approach? Is there a performance difference? * *Like this? // Arrays to hold what stock price belongs to what day of the week - Note these arrays are used some way down the line var monday = [], tuesday = [], wednesday = [], thursday = [], friday = [] // Sort each stock date into a day of the week FindDayFromDate(historyData, monday, tuesday, wednesday, thursday, friday); // Find the average price for each day of the week const avgPrices = FindAveragePricePerDay(monday, tuesday, wednesday, thursday, friday); *Like this? // Sort each stock date into a day of the week - sortedDays contains arrays of monday...friday const sortedDays = FindDayFromDate(historyData); // Find the average price for each day of the week - Expand sortedDays inside function to access monday...friday const avgPrices = FindAveragePricePerDay(sortedDays); A: A good function should always be free from side-effects. It should be pure and just do one specific job at a time. As a software programmer/developer, we must write source code that actually produce the output based on input. Such kind of strong pure function actually avoid all kind of side effects and code smell. Let's look at few examples to understand this. Assume we have a function named as Greeting like below function Greeting(name) { return `Hello ${name}`; } It is pure because you will always get the output Hello {name} for the name passed via parameter. Let's have a look at another version of same function with many side-effects. var greeting = "Hey"; function Greeting(name) { return `${greeting} ${name}`; } Now, this function is not pure. Guess why ? Because we are not sure what output we will receive because function is actually dependent on the outer variable named as greeting . So if someone change the value of variable greeting to something else let's say Hello then obviously the output of function will change. So the function is now tightly coupled with the outer variable. That's why it is not pure function anymore. So to conclude, you must have to write your function in such a way that there is no dependency and no side-effect and it will always do one job. That is the best practice :) Happy Coding :) A: I believe the second Function "FindAveragePricePerDay" calling can be adjusted to act on single day, so that it can be reused on other places const avgPrices = sortedDays.map(day => FindAveragePricePerDay(day)); /* you can also simplify the FindAveragePricePerDay using the reduce method following this parameters array.reduce(function(total, currentValue, currentIndex, arr), initialValue) so all the second line would be */ const avgPrices = day.reduce((t,c,i,arr) => t + c/arr.length, 0); for more info about array.reduce check this
{ "language": "en", "url": "https://stackoverflow.com/questions/72597471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Joining multiple columns into one with union, exclude results with same id I want to join columns from multiple tables to one column, in my case column 'battery_value' and 'technical_value' into column 'value'. I want to fetch data for only given category_ids, but because of UNION, I get data from other tables as well. I have 4 tables: Table: car car_id model_name 1 e6 Table: battery battery_category_id car_id battery_value 1 1 125 kW Table: technical_data technical_category_id car_id technical_value 1 1 5 3 1 2008 Table: categories category_id category_name category_type 1 engine power battery 1 seats technical 3 release year technical From searching, people are suggesting that I use union to join these columns. My query now looks like this: SELECT CARS.car_id category_id, CATEGORIES.category_name, value, FROM CARS left join (SELECT BATTERY.battery_category_id AS category_id, BATTERY.car_id AS car_id, BATTERY.value AS value FROM BATTERY WHERE `BATTERY`.`battery_category_id` IN (1) UNION SELECT TECHNICAL_DATA.technical_category_id AS category_id, TECHNICAL_DATA.car_id AS car_id, TECHNICAL_DATA.value AS value FROM TECHNICAL_DATA WHERE `TECHNICAL_DATA`.`technical_category_id` IN (3)) tt ON CARS.car_id = tt.car_id left join CATEGORIES ON category_id = CATEGORIES.id So the result I want is this, because I only want to get the data where category_id 1 is in battery table: car_id category_id category_name technical_value 1 1 engine power 125 kW 1 3 release year 2008 but with the query above I get this, category_id 1 from technical table is included which is not something I want: car_id category_id category_name value 1 1 engine power 125 kW 1 1 seats 125 kW 1 3 release year 2008 How can get exclude the 'seats' row? A: For the results you want, I don't see why the cars table is needed. Then, you seem to need an additional key for the join to categories based on which table it is referring to. So, I suggest: SELECT tt.*, c.category_name FROM ((SELECT b.battery_category_id AS category_id, b.car_id AS car_id, b.value AS value, 'battery' as which FROM BATTERY b WHERE b.battery_category_id IN (1) ) UNION ALL (SELECT td.technical_category_id AS category_id, td.car_id AS car_id, td.value AS value, 'technical' as which FROM TECHNICAL_DATA td WHERE td.technical_category_id IN (3) ) ) tt LEFT JOIN CATEGORIES c ON c.id = tt.category_id AND c.category_type = tt.which; That said, you seem to have a problem with your data model, if the join to categories requires "hidden" data such as the type. However, that is outside the scope of the question.
{ "language": "en", "url": "https://stackoverflow.com/questions/65981983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Accessing bazel files outside the docker I am quite new to docker environment and need help in understanding / fixing the below issue. Scenario: I am running an application (assume App1) inside the docker. This application/docker uses bazel framework. So the run time files (some C++ .h and .cc files) which are getting generated are saved inside directory Bazel-App1. I can use those generated files in some other code inside the docker. However I am not able to link those files (which are inside the bazel-App1 directory) to the codes which I am writing outside the docker. Is there a way I can get access to those files? Kindly let me know if you need more details to suggest me a fix.
{ "language": "en", "url": "https://stackoverflow.com/questions/52135032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What does the dot do in Racket? I know the dot for creating a procedure, which can take an arbitrary amount of arguments, but I saw several other examples, which use the dot in other places. One example is from the docs of csv-reading: (define next-row (make-csv-reader (open-input-file "fruits.csv") '((separator-chars #\|) (strip-leading-whitespace? . #t) (strip-trailing-whitespace? . #t)))) To me this looks like a list of configuration parameters is "set", but what does the dot do there? Another example is from a web application tutorial from the docs (in the formlet section) as well: ; new-post-formlet : formlet (values string? string?) ; A formlet for requesting a title and body of a post (define new-post-formlet (formlet (#%# ,{input-string . => . title} ,{input-string . => . body}) (values title body))) My guess for this example is, that the dots somehow allow to write => as an infix operator. I was able to put the => at the front of the lists and leave the dots away and it still worked at some point. I didn't try with the final version of the tutorial's code though. However, this "infixing" wouldn't fit the first example, I think. A: The dot is not uniquely a racket thing, but a lisp thing. A list is made out of pairs and one pair has the literal form (car . cdr) and a list of the elements 2, 3 is made up like (2 . (3 . ())) and the reader can read this, however a list that has a pair as it's cdr can be shown without the dot and the parens such that (2 . (3 . ())) is the same as (2 3 . ()). Also a dot with the special empty list in the end can be omitted so that (2 3) is how it can be read and the only way display and the REPL would print it. What happens if you don't have a pair or null as the cdr? Then the only way to represent it is as a dotted. With (2 . (3 . 5)) you can only simplify the first dot so it's (2 3 . 5). The literal data structure looks like an assoc with pairs as elements where the car is the key and cdr is the value. Using a new pair is just wast of space. As an parameter list an interpreter looks at the elements and if it's a pair it binds the symbol in car, but if it's not a pair it is either finished with null or you have a rest argument symbol. It's convenient way to express it. Clojure that don't have dotted pairs use a & element while Common Lisp does dotted in structures, but not as a parameter specification since it supports more features than Scheme and Clojure and thus use special keywords to express it instead. The second is #lang racket specific and is indeed used to support infix. If you write (5 . + . 6) a reader extension will change it to (+ 5 6) before it gets evaluated. It works the same way even if it's quoted or actual code and curlies are of course equal to normal and square parentheses so the second one actually becomes: (define new-post-formlet (formlet (#%# ,(=> input-string title) ,(=> input-string body)) (values title body))) If you were to use #!r5rs or #!r6rs in racket (5 . + . 6) will give you a read error.
{ "language": "en", "url": "https://stackoverflow.com/questions/41967505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What is the C++ equivalent of Python's "in" operator? What is the C++ way of checking if an element is contained in an array/list, similar to what the in operator does in Python? if x in arr: print "found" else print "not found" How does the time complexity of the C++ equivalent compare to Python's in operator? A: I guess one might make use of this thread and create a custom version of in function. The main idea is to use SFINAE (Substitution Failure Is Not An Error) to differentiate associative containers (which have key_type member) from sequence containers (which have no key_type member). Here is a possible implementation: namespace detail { template<typename, typename = void> struct is_associative : std::false_type {}; template<typename T> struct is_associative<T, std::enable_if_t<sizeof(typename T::key_type) != 0>> : std::true_type {}; template<typename C, typename T> auto in(const C& container, const T& value) -> std::enable_if_t<is_associative<C>::value, bool> { using std::cend; return container.find(value) != cend(container); } template<typename C, typename T> auto in(const C& container, const T& value) -> std::enable_if_t<!is_associative<C>::value, bool> { using std::cbegin; using std::cend; return std::find(cbegin(container), cend(container), value) != cend(container); } } template<typename C, typename T> auto in(const C& container, const T& value) { return detail::in(container, value); } Small usage example on WANDBOX. A: This gives you an infix *in* operator: namespace notstd { namespace ca_helper { template<template<class...>class, class, class...> struct can_apply:std::false_type{}; template<class...>struct voider{using type=void;}; template<class...Ts>using void_t=typename voider<Ts...>::type; template<template<class...>class Z, class...Ts> struct can_apply<Z,void_t<Z<Ts...>>, Ts...>:std::true_type{}; } template<template<class...>class Z, class...Ts> using can_apply = ca_helper::can_apply<Z,void,Ts...>; namespace find_helper { template<class C, class T> using dot_find_r = decltype(std::declval<C>().find(std::declval<T>())); template<class C, class T> using can_dot_find = can_apply< dot_find_r, C, T >; template<class C, class T> constexpr std::enable_if_t<can_dot_find<C&, T>{},bool> find( C&& c, T&& t ) { using std::end; return c.find(std::forward<T>(t)) != end(c); } template<class C, class T> constexpr std::enable_if_t<!can_dot_find<C&, T>{},bool> find( C&& c, T&& t ) { using std::begin; using std::end; return std::find(begin(c), end(c), std::forward<T>(t)) != end(c); } template<class C, class T> constexpr bool finder( C&& c, T&& t ) { return find( std::forward<C>(c), std::forward<T>(t) ); } } template<class C, class T> constexpr bool find( C&& c, T&& t ) { return find_helper::finder( std::forward<C>(c), std::forward<T>(t) ); } struct finder_t { template<class C, class T> constexpr bool operator()(C&& c, T&& t)const { return find( std::forward<C>(c), std::forward<T>(t) ); } constexpr finder_t() {} }; constexpr finder_t finder{}; namespace named_operator { template<class D>struct make_operator{make_operator(){}}; template<class T, char, class O> struct half_apply { T&& lhs; }; template<class Lhs, class Op> half_apply<Lhs, '*', Op> operator*( Lhs&& lhs, make_operator<Op> ) { return {std::forward<Lhs>(lhs)}; } template<class Lhs, class Op, class Rhs> auto operator*( half_apply<Lhs, '*', Op>&& lhs, Rhs&& rhs ) -> decltype( named_invoke( std::forward<Lhs>(lhs.lhs), Op{}, std::forward<Rhs>(rhs) ) ) { return named_invoke( std::forward<Lhs>(lhs.lhs), Op{}, std::forward<Rhs>(rhs) ); } } namespace in_helper { struct in_t:notstd::named_operator::make_operator<in_t> {}; template<class T, class C> bool named_invoke( T&& t, in_t, C&& c ) { return ::notstd::find(std::forward<C>(c), std::forward<T>(t)); } } in_helper::in_t in; } On a flat container, like a vector array or string, it is O(n). On an associative sorted container, like a std::map, std::set, it is O(lg(n)). On an unordered associated container, like std::unordered_set, it is O(1). Test code: std::vector<int> v{1,2,3}; if (1 *in* v) std::cout << "yes\n"; if (7 *in* v) std::cout << "no\n"; std::map<std::string, std::string, std::less<>> m{ {"hello", "world"} }; if ("hello" *in* m) std::cout << "hello world\n"; Live example. C++14, but mainly for enable_if_t. So what is going on here? Well, can_apply is a bit of code that lets me write can_dot_find, which detects (at compile time) if container.find(x) is a valid expression. This lets me dispatch the searching code to use member-find if it exists. If it doesn't exist, a linear search using std::find is used instead. Which is a bit of a lie. If you define a free function find(c, t) in the namespace of your container, it will use that rather than either of the above. But that is me being fancy (and it lets you extend 3rd party containers with *in* support). That ADL (argument dependent lookup) extensibity (the 3rd party extension ability) is why we have three different functions named find, two in a helper namespace and one in notstd. You are intended to call notstd::find. Next, we want a python-like in, and what is more python like than an infix operator? To do this in C++ you need to wrap your operator name in other operators. I chose *, so we get an infix *in* named operator. TL;DR You do using notstd::in; to import the named operator in. After that, t *in* c first checks if find(t,c) is valid. If not, it checks if c.find(t) is valid. If that fails, it does a linear search of c using std::begin std::end and std::find. This gives you very good performance on a wide variety of std containers. The only thing it doesn't support is if (7 *in* {1,2,3}) as operators (other than =) cannot deduce initializer lists I believe. You could get if (7 *in* il(1,2,3)) to work. A: The time complexity of Python's in operator varies depending on the data structure it is actually called with. When you use it with a list, complexity is linear (as one would expect from an unsorted array without an index). When you use it to look up set membership or presence of a dictionary key complexity is constant on average (as one would expect from a hash table based implementation): * *https://wiki.python.org/moin/TimeComplexity In C++ you can use std::find to determine whether or not an item is contained in a std::vector. Complexity is said to be linear (as one would expect from an unsorted array without an index). If you make sure the vector is sorted, you can also use std::binary_search to achieve the same in logarithmic time. * *http://en.cppreference.com/w/cpp/algorithm/find *Check if element is in the list (contains) *Check if element found in array c++ *http://en.cppreference.com/w/cpp/algorithm/binary_search The associative containers provided by the standard library (std::set, std::unordered_set, std::map, ...) provide the member functions find() and count() and contains() (C++20) for this. These will perform better than linear search, i.e., logarithmic or constant time depending on whether you have picked the ordered or the unordered alternative. Which one of these functions to prefer largely depends on what you want to achieve with that info afterwards, but also a bit on personal preference. (Lookup the documentation for details and examples.) * *How to check that an element is in a std::set? *How to check if std::map contains a key without doing insert? *https://en.wikipedia.org/wiki/Associative_containers *http://en.cppreference.com/w/cpp/container If you want to, you can use some template magic to write a wrapper function that picks the correct method for the container at hand, e.g., as presented in this answer. A: You can use std::find from <algorithm>, but this works only for datatypes like: std::map and std::vector (etc). Also note that this will return, iterator to the first element that is found equal to the value you pass, unlike the in operator in Python that returns a bool. A: You can approach this in two ways: You can use std::find from <algorithm>: auto it = std::find(container.begin(), container.end(), value); if (it != container.end()) return it; or you can iterate through every element in your containers with for ranged loops: for(const auto& it : container) { if(it == value) return it; } A: Python does different things for in depending on what kind of container it is. In C++, you'd want the same mechanism. Rule of thumb for the standard containers is that if they provide a find(), it's going to be a better algorithm than std::find() (e.g. find() for std::unordered_map is O(1), but std::find() is always O(N)). So we can write something to do that check ourselves. The most concise would be to take advantage of C++17's if constexpr and use something like Yakk's can_apply: template <class C, class K> using find_t = decltype(std::declval<C const&>().find(std::declval<K const&>())); template <class Container, class Key> bool in(Container const& c, Key const& key) { if constexpr (can_apply<find_t, Container, Key>{}) { // the specialized case return c.find(key) != c.end(); } else { // the general case using std::begin; using std::end; return std::find(begin(c), end(c), key) != end(c); } } In C++11, we can take advantage of expression SFINAE: namespace details { // the specialized case template <class C, class K> auto in_impl(C const& c, K const& key, int ) -> decltype(c.find(key), true) { return c.find(key) != c.end(); } // the general case template <class C, class K> bool in_impl(C const& c, K const& key, ...) { using std::begin; using std::end; return std::find(begin(c), end(c), key) != end(c); } } template <class Container, class Key> bool in(Container const& c, Key const& key) { return details::in_impl(c, key, 0); } Note that in both cases we have the using std::begin; using std::end; two-step in order to handle all the standard containers, raw arrays, and any use-provided/adapted containers. A: I think one of the nice features of the "in" operator in python is that it can be used with different data types (strings v/s strings, numbers v/s lists, etc). I am developing a library for using python constructions in C++. It includes "in" and "not_in" operators. It is based on the same technique used to implement the in operator posted in a previous answer, in which make_operator<in_t> is implemented. However, it is extended for handling more cases: * *Searching a string inside a string *Searching an element inside vector and maps It works by defining several overloads for a function: bool in__(T1 &v1, T2 &v2), in which T1 and T2 consider different possible types of objects. Also, overloads for a function: bool not_in__(T1 &v1, T2 &v2) are defined. Then, the operators "in" and "not_in" call those functions for working. The implementation is in this repository: https://github.com/ploncomi/python_like_cpp
{ "language": "en", "url": "https://stackoverflow.com/questions/44622964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "61" }
Q: Angular 2 How to make singleton service available to lazy loaded modules According to my understanding of Angular 2 rc5, to make a service from another module (not AppModule) available as a singleton to every component, even those lazy-loaded, we don't include the service in the providers array of that other module. We instead export it with RouterModule.forRoot() and import the result in AppModule According to the docs: The SharedModule should only provide the UserService when imported by the root AppModule. The SharedModule.forRoot method helps us meet this challenge...the SharedModule does not have providers...When we add the SharedModule to the imports of the AppModule, we call forRoot. In doing so, the AppModule gains the exported classes and the SharedModule delivers the singleton UserService provider at the same time I'm really struggling with how to make a 3rd-party service (a service used by a module in the imports array of my AppModule) available to lazy loaded routes. I have no control over this 3rd-party module, so I cannot just remove that service from the NgModule.providers array of that module and place it inside RouterModule.forRoot() as I would with one of my services. The specific service is MdIconRegistry, which is in providers for the MdIconModule of Angular Material 2 alpha 7-3. This service is used to register svg icons that can then be displayed on the page with the <md-icon svgIcon='iconName'> tag. So: * *I imported MdIconModule in my root AppModule *I used the service in question to register svg icons in my AppComponent The icon is visible and works well, but only in the modules that were loaded at launch. Lazy-loaded modules cannot see these icons, so I suspect that the Angular injector is not injecting the same instance of the MdIconRegistry service. tl;dr: How can I make the service from a 3rd-party module a singleton available to my lazy-loaded components? Here is a plunker that demonstrates the problem (coded in typescript). PS: This just got the attention of the MdIconModule developer on github. A: I do not think it has anything to do with the component being lazy-loaded. LazyLoadedComponent is not part of the AppModule – it is part of the LazyModule. According to the docs, a component can only be part of one module. If you try adding LazyLoadedComponent to AppModule also, you would get an error to that effect. So LazyLoadedComponent is not even seeing MdIconModule at all. You can confirm this by looking at the template output in the debugger – it is unchanged. <md-icon svgIcon="play"></md-icon> The solution appears to be adding the MdIconModule to the LazyModule, and while this alone does not fix the problem, it does add an error to the output. Error retrieving icon: Error: Unable to find icon with the name ":play" And the template output now looks like this, so we know it is loading. <md-icon role="img" svgicon="play" ng-reflect-svg-icon="play" aria-label="play"></md-icon> I added the call to addSvgIconSet from LazyLoadedComponent, and that got it working… so this proves there is an instance of the MdIconRegistry service per component – not what you want, but may point you in the right direction. Here’s the new plunk - http://plnkr.co/edit/YDyJYu?p=preview After further review, I found this in the docs: Why is a service provided in a lazy loaded module visible only to that module? Unlike providers of the modules loaded at launch, providers of lazy loaded modules are module-scoped. Final Update! Here is the answer. MdIconModule is not properly setup for lazy loaded components... but we can easily create our own module that IS properly set up and use that instead. import { NgModule } from '@angular/core'; import { HttpModule } from '@angular/http'; import { MdIcon } from '@angular2-material/icon'; import { MdIconRegistry } from '@angular2-material/icon'; @NgModule({ imports: [HttpModule], exports: [MdIcon], declarations: [MdIcon] }) export class MdIconModuleWithProviders { static forRoot(): ModuleWithProviders { return { ngModule: MdIconModuleWithProviders, providers: [ MdIconRegistry ] }; } } Plunk updated and fully working. (sorry, updated the same one) -> http://plnkr.co/edit/YDyJYu?p=preview One might submit a pull request such that Angular Material exports modules of both styles. A: New to Angular 6 there is a new way to register a provider as a singleton. Inside the @Injectable() decorator for a service, use the providedIn attribute. Set its value to 'root'. Then you won't need to add it to the providers list of the root module, or in this case you could also set it to your MdIconModuleWithProviders module like this: @Injectable({ providedIn: MdIconModuleWithProviders // or 'root' for singleton }) export class MdIconRegistry { ...
{ "language": "en", "url": "https://stackoverflow.com/questions/39010654", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Exit position Pine Script How can I exit or close a position on a specific time of exchange in Pine Script. Example I have long position and want to close it on or before 1500 hrs as per Indian Time Zone. Please help? A: You can use the time() function for that. Here is an example where it marks candles between 1200 and 1500. It shouldn't be difficult to adapt according to your needs. //@version=5 indicator("My Script", overlay=true) timeAllowed = input.session("1200-1500", "Allowed hours") // Check to see if we are in allowed hours using session info on all 7 days of the week. timeIsAllowed = time(timeframe.period, timeAllowed + ":1234567") plotchar(timeIsAllowed, size=size.small)
{ "language": "en", "url": "https://stackoverflow.com/questions/70817255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android device how to run one program? Here is the question I have android device version 4.1.1 and Δ± want change the android working style. For example I restart my android device and want to see my application on screen just one. Another app for example camera or notepad Δ± dont want to see that just one program in my android device and I use that . How can Δ± programming that ? Δ± will try again Δ± wanna root my android device for my claims how can Δ± do that
{ "language": "en", "url": "https://stackoverflow.com/questions/33837438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to automatically drop down DateTimePicker in Vb.net through a Citrix client Through a variety of reasons I am forced to use the incredibly frustrating vb.net DateTimePicker control, in the even more frustrating Citrix client, for an application. This isn't actually my main problem, the problem is, I have to make the datetimepicker automatically drop down when the user presses any button (besides tab, escape, etc). I really need to get this to work, the users won't really take no for an answer. I would prefer to not get a new custom control, but if one exists that is easy to implement (and doesn't allow the user to type in the date) then I would be open to it. This is what I've done so far, it works perfectly well outside of Citrix, but when it triggers in Citrix the DateTimePicker doesn't refresh when the user navigates around it. Meaning the square is over the current date, and the user can press arrow keys to their heart's content, but it never shows this to the user. (Even if the user uses the mouse to drop it down.) Again outside of Citrix this works fine. 'Used to manually dropdown datetimepickers Private dateTimePickerControl As DateTimePicker Private Declare Auto Function SendMessage Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr Public Sub DropDownCalendar() Const WM_LBUTTONDOWN As Int32 = &H201 Const WM_LBUTTONUP As Int32 = &H202 Dim x As Integer = Me.dateTimePickerControl.Width - 10 Dim y As Integer = CInt(Me.dateTimePickerControl.Height / 2) Dim lParam As Integer = x + y * &H10000 'click down, and show the calendar SendMessage(Me.dateTimePickerControl.Handle, WM_LBUTTONDOWN, CType(1, IntPtr), CType(lParam, IntPtr)) 'Click-up, and activate the calendar (without this the calendar is shown, but is not active, and doesn't work as expected) SendMessage(Me.dateTimePickerControl.Handle, WM_LBUTTONUP, CType(1, IntPtr), CType(lParam, IntPtr)) End Sub Private Sub dteDate_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles dteDate.KeyDown Try If e.KeyCode = Keys.Delete Then sender.customFormat = " " e.Handled = True ElseIf e.KeyCode <> Keys.Tab And e.KeyCode <> Keys.ShiftKey Then sender.focus() dateTimePickerControl = sender DropDownCalendar() End If Catch ex As Exception MsgBox(ex.Message) End Try End Sub I'm completely at a loss. Is such a thing even possible in Citrix? In a previous attempt I used SendKeys("{F4}") which worked fine outside of Citrix, but in Citrix would just drop down a frozen white background. Does anyone have any ideas that could help me out here? A: Sometimes we've had to add DoEvents when sending messages like this in our VB app hosted on Citrix. See if this works for you: Private Declare Auto Function SendMessage Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr Private Sub DropDownCalendar(ctl As DateTimePicker) Const WM_LBUTTONDOWN = &H201 Const WM_LBUTTONUP = &H202 If ctl Is Nothing Then Exit Sub End If ctl.Select() Dim lParam = (ctl.Width - 10) + (CInt(ctl.Height / 2) * &H10000) 'click down, and show the calendar SendMessage(ctl.Handle, WM_LBUTTONDOWN, CType(1, IntPtr), CType(lParam, IntPtr)) Application.DoEvents() 'Click-up, and activate the calendar (without this the calendar is shown, but is not active, and doesn't work as expected) SendMessage(ctl.Handle, WM_LBUTTONUP, CType(1, IntPtr), CType(lParam, IntPtr)) End Sub Private Sub dteDate_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles dteDate.KeyDown Try If e.KeyCode = Keys.Delete Then CType(sender, DateTimePicker).CustomFormat = " " e.Handled = True ElseIf e.KeyCode <> Keys.Tab And e.KeyCode <> Keys.ShiftKey Then DropDownCalendar(CType(sender, DateTimePicker)) End If Catch ex As Exception MsgBox(ex.Message) End Try End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/29629834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Xamarin Forms OnAppLinkRequestReceived event - Shell.Current is null I am testing App Links / Deep Linking / Universal Links on my Xamarin Forms app. I have an app that correctly intercepts URLs as expected, but when I go to navigate to the page using Shell in my app, Shell.Current is null. Visual Studio 2022, Android Pixel 4 emulator, Xamarin Forms version 5.0.0.2291 Setup: Simple onAppLinkRequestReceived handler. The debugger executes and breaks at this code, so I know my applinks are set up properly. protected override async void OnAppLinkRequestReceived(Uri uri) { base.OnAppLinkRequestReceived(uri); var shellRoute = uri.PathAndQuery; try { Log.Information("User followed applink for {shellRoute}", shellRoute); Shell.Current.GoToAsync(shellRoute); } catch(Exception ex) { Log.Error(ex, "User encountered an error attempting to navigate to an applink request", shellRoute); } } The problem here is that Shell.Current is null so I nullref. I expect shell.current should always be valid? I am testing this using Android's suggested test technique, found here: .\adb shell am start -W -a android.intent.action.VIEW -d "my-url" my-package-id a null shell current value appears unexpected especially when other examples on the web indicate that navigation straight from the applinkrequest event should be valid?
{ "language": "en", "url": "https://stackoverflow.com/questions/71023111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set up the event Datagridviewcombobox cell selectionchanged? I have a DataGridViewComboBoxCell control with some items into it. I would like to get the values when user chooses a value from the dropdown. I cant use DataGridViewComboBoxColumn where EditingControlShowing can be used. I need similar event handler for DataGridViewComboBoxCell. Can anyone help pls. Please find code sample below: private DataGridViewComboBoxCell NameDropDown = new DataGridViewComboBoxCell(); public void SetDropDown(int index) { NameDropDown = new DataGridViewComboBoxCell(); DropDownValues(index); for (int j = 0; j < DropDownOld.Items.Count; j++) { NameDropDown.Items.Add(DropDownOld.Items[j]); } dataGridView1.Rows[index].Cells[4] = NameDropDown; } A: Yes, you can use the EditingControlShowing event to get a handle to the combobox. Then hook up an event handler for the SelectedIndexChanged or whatever event you want and code it..! DataGridViewComboBoxEditingControl cbec = null; private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { if (e.Control is DataGridViewComboBoxEditingControl) { cbec = e.Control as DataGridViewComboBoxEditingControl; cbec.SelectedIndexChanged -=Cbec_SelectedIndexChanged; cbec.SelectedIndexChanged +=Cbec_SelectedIndexChanged; } } private void Cbec_SelectedIndexChanged(object sender, EventArgs e) { if (cbec != null) Console.WriteLine(cbec.SelectedItem.ToString()); }
{ "language": "en", "url": "https://stackoverflow.com/questions/45412562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Cannot register nested generic interface in .NET Core I am trying to register the nested generic type in DI container, but unable to register throws {Open generic service type requires registering an open generic implementation type. (Parameter descriptors)} error Implemented Interface method looks like: public class CustomerEvent<TEntity> : IEventConsumer<EntityInsertedEvent<TEntity>>, IEventConsumer<EntityUpdatedEvent<TEntity>>, IEventConsumer<EntityDeletedEvent<TEntity>> where TEntity : BaseEntity { public void HandleEvent(EntityInsertedEvent<TEntity> eventMessage) { throw new NotImplementedException("Inserted"); } public void HandleEvent(EntityUpdatedEvent<TEntity> eventMessage) { throw new NotImplementedException("Updated"); } public void HandleEvent(EntityDeletedEvent<TEntity> eventMessage) { throw new NotImplementedException("Deleted"); } } Tried Assembly.GetExecutingAssembly() .GetTypes() .Where(item => item.GetInterfaces() .Where(i => i.IsGenericType) .Any(i => i.GetGenericTypeDefinition() == typeof(IEventConsumer<>)) && !item.IsAbstract && !item.IsInterface) .ToList().ForEach(assignedTypes => { assignedTypes.GetInterfaces() .Where(i => i.GetGenericTypeDefinition() == typeof(IEventConsumer<>)).ToList() .ForEach(imp => { services.AddScoped(imp, assignedTypes); }); }); but failed A: There is no easy way to do this. Typically, you need to map an open-generic abstraction to an open-generic implementation, like this: services.AddTransient(typeof(IEventConsumer<>), typeof(CustomerEvent<>)); This, however, will not work in your case because MS.DI is unable to figure out how the generic type argument for IEventCustomer<T> should maps to the generic type argument of CustomerEvent<TEntity>. When resolving an IEventCustomer<EntityInsertedEvent<Order>>, for instance, it will try to create a CustomerEvent<EntityInsertedEvent<Order>>, while it should have been creating a CustomerEvent<Order>. This is not a limitation of .NET or the CLR, but a limitation that is specific to the MS.DI DI Container, because some other DI Containers are actually able to make these kinds of mappings. Unfortunately, with MS.DI, there is no easy way out. The only thing you can do is making all possible closed-generic registrations explicitly, e.g.: s.AddTransient<IEventConsumer<EntityInsertedEvent<Order>>, CustomerEvent<Order>>(); s.AddTransient<IEventConsumer<EntityInsertedEvent<Customer>>, CustomerEvent<Customer>>(); s.AddTransient<IEventConsumer<EntityInsertedEvent<Product>>, CustomerEvent<Product>>(); s.AddTransient<IEventConsumer<EntityInsertedEvent<Employee>>, CustomerEvent<Employee>>(); s.AddTransient<IEventConsumer<EntityInsertedEvent<etc>>, CustomerEvent<etc>>();
{ "language": "en", "url": "https://stackoverflow.com/questions/63786924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP - how to watch for cookie (every second or time interval)? I want to watch for cookie and if this cookie exist do somethink. I tried this : while (true) { sleep(1); if ($_COOKIE['name']) { doSomethink(); } } But this code really make execution to 'sleep'. Is there a way to watch without stopping the execution? A: if this is a browser activity, a better way to do this may be a javascript setInverval() with an ajax call to a php function. Otherwise, I'd recommend running the PHP script via CRON. There's no other way that I know to run PHP asynchronously, which is probably what you're trying to accomplish.
{ "language": "en", "url": "https://stackoverflow.com/questions/16642941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to access In XCUITestCase UITableViewRowAction and How to take action from XCUITestCase Leftswape delete tableViewCell Basically I want to access the UItableViewRowAction event in XCUITestCase. But I couldn't find any solution for this. A: I assume you have a table view with cells that can be swiped left, and that swiping shows a delete button entitled DELETE. Then you could do the following: let firstCell = XCUIApplication().cells.element(boundBy: 0) firstCell().swipeLeft() let deleteButton = firstCell.buttons[β€žDELETEβ€œ] deleteButton.tap() EDIT: Thanks for your edit! Your delete button does not have any title text. Thus, you cannot access the button with firstCell.buttons[β€žDELETEβ€œ]. From your screen shot it looks as if the delete button was the only button in the cell. If so, you could try firstCell.buttons.firstMatch. If you have more buttons, you could access the delete button using firstCell.buttons.element(boundBy: 0) where β€ž0β€œ had to be replaced by the correct index.
{ "language": "en", "url": "https://stackoverflow.com/questions/62337192", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Azure invalid AccessToken i am trying to use Microsoft.Azure.Management.Resources library to manage some Azure resources. I have registered app in Azure AD and i gave it all permissons. I took its ApplicationId and Secret + TennantId and SubscriptionId and tried to obtaion AccessToken like this: var clientCredential = new ClientCredential(_model.DeploymentDetails.CliendId, _model.DeploymentDetails.ClientSecret); var context = new AuthenticationContext("https://login.windows.net/"+model.DeploymentDetails.TennantId); _accessToken = context.AcquireTokenAsync("https://management.azure.com/", clientCredential).Result.AccessToken; _resourceManagementClient = new ResourceManagementClient(new TokenCloudCredentials(_model.DeploymentDetails.SubscriptionId,_accessToken)); I get some AccessToken. BUT when i try to use it like this: var x = _resourceManagementClient.ResourceGroups.List(...); I get this error: Additional information: InvalidAuthenticationToken: The received access token is not valid: at least one of the claims 'puid' or 'altsecid' or 'oid' should be present. If you are accessing as application please make sure service principal is properly created in the tenant. Any ideas? Thank you very much. A: As far as I know, Microsoft.Azure.Management.Resources.dll that implements the ARM API. We need to assign application to role, after that then we can use token in common. More information about how to assign application to role please refer to the article .This blog also has more detail steps to get AceessToken.
{ "language": "en", "url": "https://stackoverflow.com/questions/40498446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Detecting the termination of multiple child processes I have to write code for creating multiple child processes using a parent. Parent process should be sleeping until it creates the number of processes. Child processes send SIGCHLD signal to parent process to interrupt from the sleep and force the parent to call wait for the Collection of status of terminated child processes. I have write following code on UBUNTU: #include <stdlib.h> /* needed to define exit() */ #include <unistd.h> /* needed for fork() and getpid() */ #include <signal.h> /* needed for signal */ #include <stdio.h> /* needed for printf() */ int main(int argc, char **argv) { void catch(int); /* signal handler */ void child(int); /* the child calls this */ void parent(int pid); /* the parent calls this */ int pid; /* process ID */ int i; /* Number of processes*/ signal(SIGCHLD, catch); /* detect child termination */ for(i=0;i<5;i++) { pid = fork(); /* create child process*/ switch (pid) { case -1: /* something went wrong */ perror("fork"); exit(1); case 0: /* a fork returns 0 to the child */ child(i+1); break; default: /* a fork returns a pid to the parent */ //parent(pid); break; } } exit(0); } void child(int id) { printf("\tchild%d: I'm the child\n",id); sleep(10); /* do nothing for 3 seconds */ printf("\tchild: I'm exiting\n"); exit(id); /* exit with a return code of 123 */ } void parent(int pid) { printf("parent: I'm the parent\n"); sleep(15); /* do nothing for five seconds */ printf("parent: exiting\n"); } void catch(int snum) { int pid; int status; pid = wait(&status); printf("parent: child process exited with value %d\n",WEXITSTATUS(status)); /* WEXITSTATUS(status): * Since only the last 8 bits are available * it will be logical to mask the upper bit by * doing a bitwise and operation with 255. * A system defined macro does this for us. */ } And I am getting output like this: parent: I'm the parent child1: I'm the child child: I'm exiting parent: child process exited with value 1 parent: exiting parent: I'm the parent child2: I'm the child child: I'm exiting parent: child process exited with value 2 parent: exiting parent: I'm the parent child3: I'm the child child: I'm exiting parent: child process exited with value 3 parent: exiting parent: I'm the parent child4: I'm the child child: I'm exiting parent: child process exited with value 4 parent: exiting parent: I'm the parent child5: I'm the child child: I'm exiting parent: child process exited with value 5 parent: exiting whereas I want output like this: parent: I'm the parent child1: I'm the child child: I'm exiting parent: child process exited with value 1 child2: I'm the child child: I'm exiting parent: child process exited with value 2 child3: I'm the child child: I'm exiting parent: child process exited with value 3 child4: I'm the child child: I'm exiting parent: child process exited with value 4 child5: I'm the child child: I'm exiting parent: child process exited with value 5 parent: exiting what changes I should make in my code...? please help..!!! A: As far as I understand the code, the main function exits after starting the children. You need to add code that waits until all children have exited, means the SIGCHLD signal was caught for each exit of your child. A: You are printing parent: I'm the parent and parent: exiting within the loop. If you want them to be printed only once, move them out of the loop. You may also want to look into using the wait or waitpid functions for waiting for child process termination instead of using a signal handler and sleep.
{ "language": "en", "url": "https://stackoverflow.com/questions/35538452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to create empty data table using PrimeNG I am creating a UI that allows users to input data in batches. Similar to an Excel spreadsheet but the columns are already fixed. I'm already using PrimeNG DataTable for other parts of my web app, and I would like to continue using it for the aforementioned feature if possible. Thanks. A: I figured it out. My initial code was correct but because there was an issue when the backing array of the data table was being updated via push. I had to create a separate array with the empty objects and assign it to the backing array.
{ "language": "en", "url": "https://stackoverflow.com/questions/44901856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Verify the palindrome in Java. Can you help me to find what's the issue with this code Can you help me to find the bug in this code. When I test this with a string that is not a palindrome, I get the message that it is a palindrome. import java.util.*; public class Main{ public static void main(String args[]){ String input = ""; System.out.println("Enter the string to verify palindrome"); Scanner scan = new Scanner(System.in); input = scan.nextLine(); Main m = new Main(); if(m.palindrome(input)) System.out.println(" The string " + input + " is a palindrome "); else System.out.println(" The string " + input + " is not a palindrome "); } private boolean palindrome(String input){ String reverse = input; int j; for(int i=0;i<=reverse.length()-1;i++){ for( j=reverse.length()-1;j>=0;){ if(reverse.charAt(i)== reverse.charAt(j)){ return true; } else{ return false; } }j--; } return false; } } A: if(reverse.charAt(i)== reverse.charAt(j)){ return true; } You are returning true if the first and the last character are the same without going on to check any other character. I'd say the better approach is to continue stepping through the word until you find a character that does not match or until you finish. If you find a character that does not match, return false. If you finish, return true.
{ "language": "en", "url": "https://stackoverflow.com/questions/19214088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best practices on how to stream data to server .NET Say I want to have a server that can accept 2GB file over network, HTTP. And the data is easily readable with well known format, think something like CSV. Is there a way to gradually process the data the user has uploaded into file upload "INPUT = FILE" control while the data is still uploading through 32kbps modem? I'm reading HttpRequest Stream, and other streaming documentation, but haven't found a confirmation if IIS, ASP.NET even allows it and if I'm just not wasting my time. And, from development perspective, is it possible to simulate slow stream? A: Use WCF Streaming that you can use netTcpBinding or basicHttpBinding. I have used it and It is super fast and efficient - really impressive. And yes you can simulate slow transfer, you just need to write to your stream slowly (pauses in the middle).
{ "language": "en", "url": "https://stackoverflow.com/questions/5745108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to print matrix with int10h? Well as my question says, I need to print a matrix with the int10h but not just that, this matrix is of 0 and 1 where the 0 has to represent the color blue and the 1 the color red. So my question is how do I print this matrix and how do I make the be color blue and red be color red when printing? I am using TASM and can use either 16 or 32bit registers. Here is an example: oneMatrix db 00000000000 00000110000 00011110000 00000110000 00000110000 00000110000 00011111100 00000000000 So as you can kind of see there, the 1 form a shape of a one. How do I print this using int 10h and where 0 is color blue and 1 is color red? A: Use the BIOS.WriteCharacterAndAttribute function 09h. Put either blue or red foregroundcolor in BL depending on the character at hand (read from the matrix). mov si, offset oneMatrix mov cx, 1 ; ReplicationCount mov bh, 0 ; DisplayPage More: ... position the cursor where next character has to go lodsb mov bl, 01h ; BlueOnBlack cmp al '0' je Go mov bl, 04h ; RedOnBlack Go: mov ah, 09h ; BIOS.WriteCharacterWithAttribute int 10h ... iterate as needed Take a look at this recent answer. There's some similarity... If you need the output to create a glyph on a graphics screen, then next code will help: mov si, offset oneMatrix mov bh, 0 ; DisplayPage mov bp, 8 ; Height mov dx, ... ; UpperleftY OuterLoop: mov di, 11 ; Width mov cx, ... ; UpperleftX InnerLoop: lodsb cmp al '0' mov al, 1 ; Blue je Go mov al, 4 ; Red Go: mov ah, 0Ch ; BIOS.WritePixel int 10h inc cx ; Next X dec di jnz InnerLoop inc dx ; Next Y dec bp jnz OuterLoop
{ "language": "en", "url": "https://stackoverflow.com/questions/62626308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: subqueries inside laravel raw syntax I am trying to use DB::raw('raw sql query') to run the query below: $rates = DB::raw('SELECT mid, x.qty_t/x.qty_total, x.qty_t, x.qty_total, FROM (SELECT mid, SUM(CASE WHEN (mtc="qty") THEN 1 ELSE 0 END) AS qty_total, SUM(CASE WHEN (mtc="qty") THEN rte ELSE 0 END) AS qty_t, STDDEV(CASE WHEN (mtc="qty") THEN rte ELSE 0 END) AS qty_sd FROM t_r GROUP BY mid) x')->get(); I'm getting a syntax error after (SELECT on mid, mtc and t_r. How can I get this to work using raw? A: You need to wrap DB::select around it. Something like this should work. $rates = DB::select(DB::raw('SELECT mid, x.qty_t/x.qty_total, x.qty_stddev, x.qty_total, FROM (SELECT mid, SUM(CASE WHEN (mtc="qty") THEN 1 ELSE 0 END) AS qty_total, SUM(CASE WHEN (mtc="qty") THEN rte ELSE 0 END) AS qty_t, STDDEV(CASE WHEN (mtc="qty") THEN rte ELSE 0 END) AS qty_sd FROM t_r GROUP BY mid) x'))->get();
{ "language": "en", "url": "https://stackoverflow.com/questions/53600839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python dataframe:: get count across two columns for each unique value in either column I have a python dataframe with columns, 'Expected' vs 'Actual' that shows a product (A,B,C or D) for each record ID Expected Actual 1 A B 2 A A 3 C B 4 B D 5 C D 6 A A 7 B B 8 A D I want to get a count from both columns for each unique value found in both columns (both columns dont share all the same products). So the result should look like this, Value Expected Actual A 4 2 B 2 3 C 2 0 D 0 3 Thank you for all your help A: I would do it following way import pandas as pd df = pd.DataFrame({'Expected':['A','A','C','B','C','A','B','A'],'Actual':['B','A','B','D','D','A','B','D']}) ecnt = df['Expected'].value_counts() acnt = df['Actual'].value_counts() known = sorted(set(df['Expected']).union(df['Actual'])) cntdf = pd.DataFrame({'Value':known,'Expected':[ecnt.get(k,0) for k in known],'Actual':[acnt.get(k,0) for k in known]}) print(cntdf) output Value Expected Actual 0 A 4 2 1 B 2 3 2 C 2 0 3 D 0 3 Explanation: main idea here is having separate value counts for Expected column and Actual column. If you wish to rather have Value as Index of your pandas.DataFrame you can do ... cntdf = pd.DataFrame([acnt,ecnt]).T.fillna(0) print(cntdf) output Actual Expected D 3.0 0.0 B 3.0 2.0 A 2.0 4.0 C 0.0 2.0 A: You can use apply and value_counts df = pd.DataFrame({'Expected':['A','A','C','B','C','A','B','A'],'Actual':['B','A','B','D','D','A','B','D']}) df.apply(pd.Series.value_counts).fillna(0) output: Expected Actual A 4.0 2.0 B 2.0 3.0 C 2.0 0.0 D 0.0 3.0
{ "language": "en", "url": "https://stackoverflow.com/questions/69393976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to include CocoaPods framework inside a MacOS system extension? I'm trying to create an application that uses a system extension (NEFilterPacketProvider to be exact). Currently I'm using CocoaPods to manage my dependencies. Everything works fine, up until the point when I try to use a framework inside my system extension. I have created a private pod spec that is being depended on by the system extension target. The build itself is fine. The problem comes after I try to install and run my system extension. It fails to start, because the framework cannot be found. After some investigation, it turns out that the framework is not included as part of system extension, but rather copied inside the main application bundle. System extension target simply references the relative framework directory of the application, as part of runtime framework search paths. This is problematic, because system extension is copied to /Library/SystemExtension/* after installation. Because the search path is relative, it no longer works, since extension has been copied outside the application. After doing some Googling, it seems that the "way" of CocoaPods is to keep all of the frameworks inside application bundle. Ideally, I would like to have CocoaPods copy the framework into my system extension bundle. This would ensure that the system extension can operate as a standalone binary, without having to depend on application being present at a hardcoded path. I'm wondering if there are any better solutions than just adding /Application/XXX.app/Contents/Frameworks to runtime framework search paths, and telling the user that the extension won't work otherwise.
{ "language": "en", "url": "https://stackoverflow.com/questions/64929562", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Music21 Analyze Key always returns c minor? I've been trying to use the Python module Music21 to try and get the key from a set of chords, but no matter what I put in it always seems to return c minor. Any ideas what I'm doing wrong? I've tried a variety of input strings, the print statement spits out all the right chord names but the resulting key is always c minor! I'm using Python 3.7.4 on Windows with VSCode. string = 'D, Em, F#m, G, A, Bm' s = stream.Stream() for c in string.split(','): print(harmony.ChordSymbol(c).pitchedCommonName) s.append(harmony.ChordSymbol(c)) key = s.analyze('key') print(key) A: It works if you give the ChordSymbol some length of time. The analysis weights the components by time, so a time of zero (default for ChordSymbols) will give you nonsense. d = harmony.ChordSymbol('D') d.quarterLength = 2 s = stream.Stream([d]) s.analyze('key') A: It looks like music21 Analyze is not working ok with ChordSymbol. As an alternative, you can manually set all the chord's notes, and analyze that. The code: string = 'D, Em, F#m, G, A, Bm' s = stream.Stream() for d in string.split(','): print(harmony.ChordSymbol(d).pitchedCommonName) for p in harmony.ChordSymbol(d).pitches: n = note.Note() n.pitch = p s.append(n) key = s.analyze('key') print(key) returns a D major key, as expected.
{ "language": "en", "url": "https://stackoverflow.com/questions/59010500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trying to sync zip file using git LFS, says I'm out of space I have a zip file that's about 600MB. I have the file setup to track using LFS. The zip changes frequently so I need to update it in the remote repo often. I have no problem pushing the file to LFS if my LFS storage is empty. However, when I try to push it if the file already exists in LFS, I get an error: "Your LFS push failed because you're out of file storage". The updated file is still not more than 600MB. I have a 1 GB limit with Bitbucket. My assumption was that the file would just be updated on remote with each push if it has changed. However, that apparently is not true. In order to get the file pushed to remote, I have to manually login to Bitbucket and delete the file from LFS so I can push the updated version. I'm assuming I am not doing something correctly and shouldn't need to manually delete my LFS to push changes to remote. I apparently am gravely misunderstanding how to use git LFS. My apologies if this topic already exists. I swear I tried looking for it. A: Could it be that LFS tries to upload the new version of large file before deleting the previous one? If this is the case you need at least 1.2GB in order to update a 600MB file. To test it, you could try with a smaller test version of the zip file (about 300MB). If you are able to update it and logging in Bitbucket you find previous version is no longer there, you know the problem is your 1GB limit. A: For any object storage(zip file, blob etc), the whole file is uploaded and a pointer is created to keep track of latest version. If blob size is more than your allocated quota, you will face space issue as 2 different versions of same blob(of almost same size) will actually double the space usage.
{ "language": "en", "url": "https://stackoverflow.com/questions/63157515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Running a script in bash I have a script in one of my application folders.Usually I just cd into that locatin in Unix box and run the script e.g. UNIX> cd My\Folder\ My\Folder> MyScript This prints the required result. I am not sure how do I do this in Bash script.I have done the following #!/bin/bash mydir=My\Folder\ cd $mydir echo $(pwd) This basically puts me in the right folder to run the required script . But I am not sure how to run the script in the code? A: If you can call MyScript (as opposed to ./MyScript), obviously the current directory (".") is part of your PATH. (Which, by the way, isn't a good idea.) That means you can call MyScript in your script just like that: #!/bin/bash mydir=My/Folder/ cd $mydir echo $(pwd) MyScript As I said, ./MyScript would be better (not as ambiguous). See Michael Wild's comment about directory separators. Generally speaking, Bash considers everything that does not resolve to a builtin keyword (like if, while, do etc.) as a call to an executable or script (*) located somewhere in your PATH. It will check each directory in the PATH, in turn, for a so-named executable / script, and execute the first one it finds (which might or might not be the MyScript you are intending to run). That's why specifying that you mean the very MyScript in this directory (./) is the better choice. (*): Unless, of course, there is a function of that name defined. A: #!/bin/bash mydir=My/Folder/ cd $mydir echo $(pwd) MyScript A: I would rather put the name in quotes. This makes it easier to read and save against mistakes. #!/bin/bash mydir="My Folder" cd "$mydir" echo $(pwd) ./MyScript A: Your nickname says it all ;-) When a command is entered at the prompt that doesn't contain a /, Bash first checks whether it is a alias or a function. Then it checks whether it is a built-in command, and only then it starts searching on the PATH. This is a shell variable that contains a list of directories to search for commands. It appears that in your case . (i.e. the current directory) is in the PATH, which is generally considered to be a pretty bad idea. If the command contains a /, no look-up in the PATH is performed. Instead an exact match is required. If starting with a / it is an absolute path, and the file must exist. Otherwise it is a relative path, and the file must exist relative to the current working directory. So, you have two acceptable options: * *Put your script in some directory that is on your PATH. Alternatively, add the directory containing the script to the PATH variable. *Use an absolute or relative path to invoke your script.
{ "language": "en", "url": "https://stackoverflow.com/questions/16053046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Show loading icon whenever the browser loading icon is active This might be a stretch, but I'm wondering whether or not it might be possible. I'm working on a website that uses PHP for its backend. The problem is, some of the PHP scripts I'm running are quite lengthy, and can translate into page load times that can last a few seconds. Ideally, I would be able to display a loading icon whenever the page is being loaded, but the circumstances differ depending on the page: * *In some cases, the page is being loaded for the first time, *In others, the page is being reloaded after a same-page form submit, *Sometimes the form is processed by an off-page script, which then redirects back to the page on which the form is situated (in these cases, since nothing is echoed in the external script the user isn't aware that the script is being processed elsewhere as the page content doesn't change). I understand a loading icon could be displayed in each of these cases depending on the trigger, but cannot find a general solution that would display an icon whenever the page is simply loading (regardless of the trigger). I've noticed that some browsers show a loading icon in the place of the favicon whenever the page is loading (or, at least, Google Chrome does). Is it be possible to know when the browser loading icon is active and display a page loading icon concurrently? If not, any alternate solution would be much appreciated. A: Buffering Case your PHP scripts are causing a slow load you must put' em in buffer. So, when the load is finished you can free this buffer. This isn't so hard to implement. See the PHP output buffering control documentation for this: PHP Output Buffering Control Finished the loading of the buffer You can make like this: http://jsfiddle.net/S9uR9/ $(window).load(function () { //hideLoading(); }); hideLoading = function() { $('.loading').fadeOut(2000, function() { $(".content").fadeIn(1000); }); }; hideLoading(); In your page, try to remove the commented line in $(window).load() function and comment the last line hideLoading();. Detecting browser’s activity I've noticed that some browsers show a loading icon in the place of the favicon whenever the page is loading (or, at least, Google Chrome does). Is it be possible to know when the browser loading icon is active and display a page loading icon concurrently? You can try another alternative. You can detect the network activity. This is more complex to implement, however more interesting, principally if you want a mobile approach. See this article, can help.
{ "language": "en", "url": "https://stackoverflow.com/questions/18658918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Unable to build Card-View I am trying to insert a card view in my layouts, but it is giving this rendering error. Missing styles. Is the correct theme chosen for this layout? Use the Theme combo box above the layout to choose a different layout, or fix the theme style references. Failed to find style with id 0x7fff001a in current theme. I have already included this in the app's gradle: * *compile 'com.android.support:cardview-v7:23.1.0' Also, the theme that I am using in styles is * *Theme.AppCompat.Light.NoActionBar The styles.xml is here: <style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar"> <item name="colorPrimary">@color/primaryColor</item> <item name="colorPrimaryDark">@color/primaryColorDark</item> <item name="colorAccent">@color/accentColor</item> <item name="cardStyle">@style/CardView.Light</item> </style> The cardview is here: <android.support.v7.widget.CardView xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" app:cardCornerRadius="4dp" app:elevation="5dp"/> The error message talks about style with id 0x7fff001a. What is it referring to? A: Try to Gradle Clean and Rebuild and Sync all Gradle files. After that restart Android Studio, and go to: When you create the style incorrectly or from an existing style, this problem usually occurs. So select the "Graphical Layout" select "AppTheme"-->The tab with a blue star. And select any of the predefined style. In my case "Light" which should resolve the problem. In case still the problems remain just temporary remove <item name="cardStyle">@style/CardView.Light</item> from your theme and give a try.
{ "language": "en", "url": "https://stackoverflow.com/questions/33513312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to reload NSTableView data when NSSearchField text changes I'm a bit stumped on how to reload a NSTableView's data upon a searchField's text changing. I assumed that I needed to filter the array that the tableView uses to populate itself based upon string matching and the call tableView.reloadData() all inside of controlTextDidChange() but when I test the code it doesn't work. I'm assuming that this will be a pretty simple fix and most of the info I've found on this topic has been a bit complicated. So I don't know how simple or complicated the solution really is Here is my controlTextDidChange() func: func controlTextDidChange(_ obj: Notification) { noteRecords.filter { $0.title.contains(searchField.stringValue) } tableView.reloadData() } If someone could please explain how to reload the tableViews data using the filtered array upon the searchField's text changing that would be very much appreciated. Also if it's easier to replace the searchField with a plain NSTextField let me know. Edit here's the func that populates the tableView: func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let note = allRecords[row] let cellIdentifier = NSUserInterfaceItemIdentifier(rawValue: "NoteInCloudCell") if tableColumn == tableView.tableColumns[0] { let cell = tableView.makeView(withIdentifier: cellIdentifier, owner: nil) as? NoteInCloudCell cell?.noteTitle.stringValue = note.title cell?.cloudID.stringValue = note.cloudID return cell } else { return nil } } A: Create a second array of the same type as noteRecords and name it allRecords Assign the complete set of records to allRecords and use noteRecords as data source array Replace controlTextDidChange with func controlTextDidChange(_ obj: Notification) { let query = searchField.stringValue if query.isEmpty { noteRecords = allRecords } else { noteRecords = allRecords.filter { $0.title.localizedCaseInsensitiveContains(query) } tableView.reloadData() } A more sophisticated way is a diffable data source.
{ "language": "en", "url": "https://stackoverflow.com/questions/71531283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using adapter pattern to plug multiple file types into single interface I'm trying to build a program to compare data in various file formats (e.g., CSV, JSON and XML). I want to be able to use a single interface that can handle different file formats and is easily extendible with additional file formats. The main interface should be able to compare two files with different formats (e.g., CSV and JSON). This will require a step to extract and convert the data into a dict for example. It seems the object-oriented adapter pattern is perfectly suited for this. Unfortunately, I am not familiar with this design pattern and do not fully understand how to implement it. I have created a small outline, but cannot understand how to integrate the parts: class DataComparer: def __init__(self, source, target): self.source = source self.target = target def compare(self): # do comparison class CSV: def __init__(self, csv_file): self.csv_file = csv_file def extract_convert(self): # extract and convert class JSON: def __init__(self, json_file): self.json_file = json_file def extract_convert(self): # extract and convert class XML: def __init__(self, xml_file): self.xml_file = xml_file def extract_convert(self): # extract and convert Does anyone know how to approach this problem with the adapter design pattern? Suggestions for other design patterns are also welcome. Your help us much appreciated!
{ "language": "en", "url": "https://stackoverflow.com/questions/72212065", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deploying an Azure Web App through Jenkins I am trying to deploy an Azure Web App through a Jenkins scripted pipeline using the Azure App Service Plugin. This is my deploy-command (GUIDs have been changed): azureWebAppPublish azureCredentialsId: 'a0774bb6-e471-47s9-92dc-5aa7b4t683e8', resourceGroup: 'my-demo-app', appName: 'MY-DEMO-APP', filePath: 'public/*, package.json' When running the script I get the following error: The client '03a1b3f9-a6fb-48bd-b016-4e37ec712f14' with object id '03a1b3f9-a6fb-48bd-b016-4e37ec712f14' does not have authorization to perform action 'Microsoft.Web/sites/read' over scope '/subscriptions/81fd39sw-3d28-454c-bc78-abag45r5d4d4/resourceGroups/my-demo-app/providers/Microsoft.Web/sites/MY-DEMO-APP' or the scope is invalid. If access was recently granted, please refresh your credentials. The strange thing is, the ID of this "client" that's missing authorization does not appear anywhere in the build plan. It's neither the ID or a part of the service principal nor the ID of the Container Registry credentials. It also doesn't appear on the machine that executes the build (I checked both the GUID of the mother board and the windows installation). Also the term client is not used for any part of the build plan, so I don't really know what's the actual issue in this case. A: Please check out this tutorial that explains how to Set up continuous integration and deployment to Azure App Service with Jenkins and One of the best method to deploy to Azure Web App (Windows) from Jenkins : https://learn.microsoft.com/en-us/azure/jenkins/java-deploy-webapp-tutorial A: To find the Azure AD user with the object id '03a1b3f9-a6fb-48bd-b016-4e37ec712f14', go to Azure portal, open Cloud Shell and run Get-AzureADUser -ObjectId '03a1b3f9-a6fb-48bd-b016-4e37ec712f14' To diagnose or troubleshoot the issue, go to Azure Portal -> Resource Groups -> my-demo-app -> MY-DEMO-APP -> Access control (IAM) -> Role assignments -> and then search for above found AD User and check if that user has atleast read permission. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/58286357", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: pgAdmin 4 v3 Auto Indent not working Since upgrading to 4.3, Auto Indent is not working (working in a Query Tool tab). When pressing enter at the end of a line of code, the cursor appears at a random position on the next line (sometimes right at the end) and not at the correct indentation position. This is very frustrating, as I have to click at the beginning of the line and indent correctly myself for every new line. I have tried Chrome and Edge with no difference. I have changed the Tab Size and Use Spaces Options without any luck. I am using Windows 10 Pro. Anyone else with this problem? A: UPDATE!!! This issue is fixed in pgAdmin 4 Version 4.3! Thank you pgAdmin Team! Note: This is still an issue up through pgAdmin 4 version 4.2 Updated: Feb 19, 2109 :( /* Issue: (Tested on Windows Server 2012 R2, Chrome and Firefox, pgAdmin 4 3.2) Using nested functions in a variable assignment, or just in a SQL statement causes multiple tabs to be added when hitting enter for a new line anywhere later in your code. If you uncomment the first line with nested functions (below), all carriage returns lower in the code create new lines with many unwanted tabs. Uncomment the line below and hit enter at the end of the line, or before another line of code. */ /* x := upper(substr('uncomment to test this. Hit enter after the semicolon.', 13)); */ /* My workaround is to unnest the functions and use multiple statements. Note: Be sure the offending line above is commented out. */ x := substr('uncomment to test this. Hit enter after after the semicolon.', 13); x := upper(x); A: Have tried your suggestion and it does work. But it does seem odd that we have to comment out the entire offending line (i.e. with the nested text) to make this work. I haven't had this issue with other editors. For example, entering the same text in SQL Developer as follows: SELECT * FROM employees WHERE deptno IN (SELECT deptno FROM departments WHERE loc = 'CHICAGO'); Pressing enter will place the cursor under the 2nd WHERE (same as Postgres). I clear the tabs with Shift+Tab to column 1, and going forward I am fine. Each new line, cursor is at the beginning. This doesn't work with Postgres. I am still new to a lot of this. Thank you for sharing.
{ "language": "en", "url": "https://stackoverflow.com/questions/51612558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Gremlin : How to get all the vertex details in the traversal? Sample Data A knows B A knows C A knows D B knows E C knows F Desired Output B C D E F I tried the following query, but it's not working, g.V('A'). out('knows'). as('x'). out('knows'). as('x'). project('Employee'). by(select('x')) A: If you just want to get all the vertices in the path you can do: g.V('A').repeat(out("knows")).emit().label() example: https://gremlify.com/c533ij58a98z8
{ "language": "en", "url": "https://stackoverflow.com/questions/62259384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Virtualenv Installation via pip & conda on Mac I want to install virtualenv on macOS. I tried pip install virtualenv which resulted in the below Collecting virtualenv Could not fetch URL https://pypi.python.org/simple/virtualenv/: There was a problem confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590) - skipping Decided to use conda instead conda install virtualenv which gave me CondaHTTPError: HTTP None None for url https://repo.continuum.io/pkgs/free/osx-64/repodata.json.bz2 Elapsed: None An HTTP error occurred when trying to retrieve this URL. HTTP errors are often intermittent, and a simple retry will get you on your way. SSLError(SSLError(SSLError("bad handshake: Error([('SSL routines', 'ssl3_get_server_certificate', 'certificate verify failed')],)",),),) Please help with alternative suggestion.
{ "language": "en", "url": "https://stackoverflow.com/questions/44288952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get multiple url parameters in to isset I was wondering, how i could get two parameters from URL. I have a URl like this: www.example.com/simplepay-cancel/?r=eyJyIjo1MDE3LCJ0Ijo1MDIyOTI5NTIsImUiOiJDQU5DRUwiLCJtIjoiT01TNTMxNDU1MDEiLCJvIjoiMTE2Njk4ODAyOTk1NjMwIn0%3D&s=h%2FkKbYJWL3EYZiW%2FfGxaUhEkx3d7E0EGBCieMGUjWlT%2B9tUhKBDJU4JglMVpYloj It containes two parameter the r and s. Both are encrypted. I ried to get with the following : if ( (isset($_GET['r']) && isset($_GET['s']))) { echo 'Hello'; } It work only if i set r parampeter in to the URL. This is a Wp site, and id I set to s paramater it fail and goes to 404 page. How I could get both parameter? Thank you! A: Below example will help you to "Get Multiple Parameters with same name from a URL in PHP".
{ "language": "en", "url": "https://stackoverflow.com/questions/74638737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: In scrapy, 'start_urls' not defined when passed as an input argument The following spider with fixed start_urls works: import scrapy from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor class NumberOfPagesSpider(CrawlSpider): name = "number_of_pages" allowed_domains = ["funda.nl"] # def __init__(self, place='amsterdam'): # self.start_urls = ["http://www.funda.nl/koop/%s/" % place] start_urls = ["http://www.funda.nl/koop/amsterdam/"] le_maxpage = LinkExtractor(allow=r'%s+p\d+' % start_urls[0]) rules = (Rule(le_maxpage, callback='get_max_page_number'),) def get_max_page_number(self, response): links = self.le_maxpage.extract_links(response) max_page_number = 0 # Initialize the maximum page number for link in links: if link.url.count('/') == 6 and link.url.endswith('/'): # Select only pages with a link depth of 3 page_number = int(link.url.split("/")[-2].strip('p')) # For example, get the number 10 out of the string 'http://www.funda.nl/koop/amsterdam/p10/' if page_number > max_page_number: max_page_number = page_number # Update the maximum page number if the current value is larger than its previous value filename = "max_pages.txt" # File name with as prefix the place name with open(filename,'wb') as f: f.write('max_page_number = %s' % max_page_number) # Write the maximum page number to a text file If I run it by scrapy crawl number_of_pages, it writes a .txt file as expected. However, if I modify it by commenting in the def __init__ lines and commenting out the start_urls = line, and try to run it with a user-defined input argument, scrapy crawl number_of_pages -a place=amsterdam I get the following error: le_maxpage = LinkExtractor(allow=r'%s+p\d+' % start_urls[0]) NameError: name 'start_urls' is not defined So according to the spider, start_urls is not defined, even though in the code it is fully determined in the initialization. How can I get this spider to work with start_urls defined by an input argument? A: Your le_maxpage is a class level variable. When you pass the argument to __init__, you're creating an instance level variable start_urls. You used start_urls in le_maxpage, so for the le_maxpage variable to work, there needs to be a class level variable named start_urls. To fix this issue, you need to move your class level variables to instance level, that is to define them inside the __init__ block. A: Following masnun's answer, I managed to fix this. I list the updated code below for the sake of completeness. import scrapy from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor class NumberOfPagesSpider(CrawlSpider): name = "number_of_pages" allowed_domains = ["funda.nl"] def __init__(self, place='amsterdam'): self.start_urls = ["http://www.funda.nl/koop/%s/" % place] self.le_maxpage = LinkExtractor(allow=r'%s+p\d+' % self.start_urls[0]) rules = (Rule(self.le_maxpage, ),) def parse(self, response): links = self.le_maxpage.extract_links(response) max_page_number = 0 # Initialize the maximum page number for link in links: if link.url.count('/') == 6 and link.url.endswith('/'): # Select only pages with a link depth of 3 page_number = int(link.url.split("/")[-2].strip('p')) # For example, get the number 10 out of the string 'http://www.funda.nl/koop/amsterdam/p10/' if page_number > max_page_number: max_page_number = page_number # Update the maximum page number if the current value is larger than its previous value filename = "max_pages.txt" # File name with as prefix the place name with open(filename,'wb') as f: f.write('max_page_number = %s' % max_page_number) # Write the maximum page number to a text file Note that the Rule does not even need a callback because parse is always called.
{ "language": "en", "url": "https://stackoverflow.com/questions/38422546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: UPDATE Statement without changing value Currently, I am working on node with express library using mysql connector. So most likely I am working with string literal SQL Query. Now, I have implemented a design wherein I do have a constant formula on query. Table Structure: ╔═══╦═════════════════════╦═══════════════╗ β•‘ β•‘ Field Name β•‘ Type β•‘ ╠═══╬═════════════════════╬═══════════════╣ β•‘ 1 β•‘ groupLevel β•‘ varchar β•‘ β•‘ 2 β•‘ insideBranchAccess β•‘ boolean β•‘ β•‘ 3 β•‘ outsideBranchAccess β•‘ boolean β•‘ β•‘ 4 β•‘ ipadFunctionID β•‘ varchar β•‘ β•‘ 5 β•‘ createdBy β•‘ varchar β•‘ β•‘ 6 β•‘ approvedBy β•‘ varchar β•‘ β•šβ•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β• SQL Query: INSERT INTO iPadFunctionAccess (groupLevel, insideBranchAccess, outsideBranchAccess, ipadFunctionID, createdBy, approvedBy) VALUES ? ON DUPLICATE KEY UPDATE insideBranchAccess = VALUES(insideBranchAccess), outsideBranchAccess = VALUES(outsideBranchAccess), updatedBy = VALUES(createdBy); So the ? is where I insert my data. The sample data that I insert is this (5, false, true, 'IIU.A05', 'SYSTEM', 'SYSTEM') Actual Database: The sample data that I am getting from the application is this. [ { "id": "DEP.A03", "groupLevel": "5", "insideBranchAccess": true, "outsideBranchAccess": true }, { "id": "DEP.S02", "groupLevel": "5", "insideBranchAccess": true }, { "id": "DEP.S04", "groupLevel": "5", "outsideBranchAccess": true } ] So as you can see, the insideBranchAccess and outsideBranchAccess is kinda optional. I have seen this answer so I have come up with this kind of query. So incase that I only got insideBranchAccess my query should be like this (5, true, outsideBranchAccess, 'IIU.A05', 'SYSTEM', 'SYSTEM') and vice versa. Actual Database: However, when I do this, the outsideBranchAccess always return to false even though the previous data from the database is true. Any thoughts? MySQL Fiddle: HERE
{ "language": "en", "url": "https://stackoverflow.com/questions/62080491", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to change plot from connecting points to vertical sticks? The following code will create a plot by connecting points. import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 5, 0.1); y = np.sin(x) plt.plot(x, y) plt.show() How can I change the plot to vertical sticks instead of connecting points? I.e., change to the type of plot of the following example: Thanks. A: Use plt.bar import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 5, 0.1); y = np.sin(x) plt.bar(x, y, width=0.08,edgecolor='None',color='k',align='center') plt.show()
{ "language": "en", "url": "https://stackoverflow.com/questions/30260221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: frola editor react doesn't reflect any changes I'm using this npm https://github.com/Zeyton-co/react-froala-editor, I've passed in some of the config like this <FroalaEditor base='https://cdnjs.cloudflare.com/ajax/libs/froala-editor/2.3.4' value={this.state.editorValue} config={ {shortcutsEnabled:['show', 'bold', 'underline', 'strikeThrough', 'indent', 'outdent', 'undo', 'redo', 'insertImage', 'createLink']} } /> But I can't see the changes. A: There is another repo which is officially maintained by the Froala team and would be better to use that one: https://github.com/froala/react-froala-wysiwyg. It also supports two way bindings.
{ "language": "en", "url": "https://stackoverflow.com/questions/43691651", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to update the multiple file names in request from csv file using Jmeter We have a POST api and we can send multiple files in a request. I created a csv file with all file Names. Its updating same filename each json object. How can i get the unique filename in json object from csv? Or is there any approch to get unique files from a file? Request: [ { "filePath": "Filename1", "orgId": "org123", "Domain": "abcd.com", }, { "filePath": "Filename2", "orgId": "org123", "Domain": "abcd.com", },{ "filePath": "Filename3", "orgId": "org123", "Domain": "abcd.com", },{ "filePath": "Filename4", "orgId": "org123", "Domain": "abcd.com", },{ "filePath": "Filename5", "orgId": "org123", "Domain": "abcd.com", } ] A: I don't think it's possible using CSV Data Set Config, it reads next line on each iteration of each virtual user (or according to Sharing Mode setting), but none of the Sharing Modes allows reading multiple lines in a single shot, moreover you need to pass them into single request somehow. If you need to create one section like this: { "filePath": "filename from CSV here", "orgId": "org123", "Domain": "abcd.com", } per line in the CSV file you could do this using JSR223 PreProcessor and the following Groovy code: def payload = [] new File('test.csv').readLines().each { line -> payload.add([filePath: line, orgId: 'org123', Domain: 'abcd.com']) } vars.put('payload', new groovy.json.JsonBuilder(payload).toPrettyString()) generated JSON could be accessed as ${payload} where required A: You can create multiple variable names under CSV Data Set Config element(for FileName1,FileName2..etc)and use them.
{ "language": "en", "url": "https://stackoverflow.com/questions/74398215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: multipart PUT request using AFNetworking What's the correct way to code a multipart PUT request using AFNetworking on iOS? (still Objective-C, not Swift) I looked and seems like AFNetworking can do multipart POST but not PUT, what's the solution for that? Thanks A: Here is code for Afnetworking 3.0 and Swift that worked for me. I know its old thread but might be handy for someone! let manager: AFHTTPSessionManager = AFHTTPSessionManager() let URL = "\(baseURL)\(url)" let request: NSMutableURLRequest = manager.requestSerializer.multipartFormRequestWithMethod("PUT", URLString: URL, parameters: parameters as? [String : AnyObject], constructingBodyWithBlock: {(formData: AFMultipartFormData!) -> Void in formData.appendPartWithFileData(image!, name: "Photo", fileName: "photo.jpg", mimeType: "image/jpeg") }, error: nil) manager.dataTaskWithRequest(request) { (response, responseObject, error) -> Void in if((error == nil)) { print(responseObject) completionHandler(responseObject as! NSDictionary,nil) } else { print(error) completionHandler(nil,error) } print(responseObject) }.resume() A: You can use multipartFormRequestWithMethod to create a multipart PUT request with desired data. For example, in AFNetworking v3.x: AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; NSError *error; NSURLRequest *request = [manager.requestSerializer multipartFormRequestWithMethod:@"PUT" URLString:@"http://example.com/rest/api/" parameters:@{@"foo" : @"bar"} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { NSString *value = @"qux"; NSData *data = [value dataUsingEncoding:NSUTF8StringEncoding]; [formData appendPartWithFormData:data name:@"baz"]; } error:&error]; NSURLSessionDataTask *task = [manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { if (error) { NSLog(@"%@", error); return; } // if you want to know what the statusCode was if ([response isKindOfClass:[NSHTTPURLResponse class]]) { NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode]; NSLog(@"statusCode: %ld", statusCode); } NSLog(@"%@", responseObject); }]; [task resume]; If AFNetworking 2.x, you can use AFHTTPRequestOperationManager: AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; NSError *error; NSURLRequest *request = [manager.requestSerializer multipartFormRequestWithMethod:@"PUT" URLString:@"http://example.com/rest/api/" parameters:@{@"foo" : @"bar"} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { NSString *value = @"qux"; NSData *data = [value dataUsingEncoding:NSUTF8StringEncoding]; [formData appendPartWithFormData:data name:@"baz"]; } error:&error]; AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"%@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"%@", error); }]; [manager.operationQueue addOperation:operation]; Having illustrated how one could create such a request, it's worth noting that servers may not be able to parse them. Notably, PHP parses multipart POST requests, but not multipart PUT requests. A: You can create an NSURLRequest constructed with the AFHTTPRequestSerialization's multipart form request method NSString *url = [[NSURL URLWithString:path relativeToURL:manager.baseURL] absoluteString]; id block = ^(id<AFMultipartFormData> formData) { [formData appendPartWithFileData:media name:@"image" fileName:@"image" mimeType:@"image/jpeg"]; }; NSMutableURLRequest *request = [manager.requestSerializer multipartFormRequestWithMethod:@"PUT" URLString:url parameters:nil constructingBodyWithBlock:block error:nil]; [manager HTTPRequestOperationWithRequest:request success:successBlock failure:failureBlock]; A: I came up with a solution that can handle any supported method. This is a solution for PUT, but you can replace it with POST as well. This is a method in a category that I call on the base model class. - (void)updateWithArrayOfFiles:(NSArray *)arrayOfFiles forKey:(NSString *)key params:(NSDictionary *)params success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure { id block = [self multipartFormConstructionBlockWithArayOfFiles:arrayOfFiles forKey:key failureBlock:failure]; NSMutableURLRequest *request = [[self manager].requestSerializer multipartFormRequestWithMethod:@"PUT" URLString:self.defaultURL parameters:nil constructingBodyWithBlock:block error:nil]; AFHTTPRequestOperation *operation = [[self manager] HTTPRequestOperationWithRequest:request success:success failure:failure]; [operation start]; } #pragma mark multipartForm constructionBlock - (void (^)(id <AFMultipartFormData> formData))multipartFormConstructionBlockWithArayOfFiles:(NSArray *)arrayOfFiles forKey:(NSString *)key failureBlock:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure { id block = ^(id<AFMultipartFormData> formData) { int i = 0; // form mimeType for (FileWrapper *fileWrapper in arrayOfFiles) { NSString *mimeType = nil; switch (fileWrapper.fileType) { case FileTypePhoto: mimeType = @"image/jpeg"; break; case FileTypeVideo: mimeType = @"video/mp4"; break; default: break; } // form imageKey NSString *imageName = key; if (arrayOfFiles.count > 1) // add array specificator if more than one file imageName = [imageName stringByAppendingString: [NSString stringWithFormat:@"[%d]",i++]]; // specify file name if not presented if (!fileWrapper.fileName) fileWrapper.fileName = [NSString stringWithFormat:@"image_%d.jpg",i]; NSError *error = nil; // Make the magic happen [formData appendPartWithFileURL:[NSURL fileURLWithPath:fileWrapper.filePath] name:imageName fileName:fileWrapper.fileName mimeType:mimeType error:&error]; if (error) { // Handle Error [ErrorManager logError:error]; failure(nil, error); } } }; return block; } Aso it uses FileWrapper Interface typedef NS_ENUM(NSInteger, FileType) { FileTypePhoto, FileTypeVideo, }; @interface FileWrapper : NSObject @property (nonatomic, strong) NSString *filePath; @property (nonatomic, strong) NSString *fileName; @property (assign, nonatomic) FileType fileType; @end A: For RAW Body : NSData *data = someData; NSMutableURLRequest *requeust = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[self getURLWith:urlService]]]; [reqeust setHTTPMethod:@"PUT"]; [reqeust setHTTPBody:data]; [reqeust setValue:@"application/raw" forHTTPHeaderField:@"Content-Type"]; NSURLSessionDataTask *task = [manager uploadTaskWithRequest:requeust fromData:nil progress:^(NSProgress * _Nonnull uploadProgress) { } completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { }]; [task resume]; A: .h + (void)PUT:(NSString *)URLString parameters:(id)parameters constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock success:(void (^)(NSURLResponse *response, id responseObject))success failure:(void (^)(NSURLResponse * response, NSError *error))failure error:(NSError *__autoreleasing *)requestError; .m: + (void)PUT:(NSString *)URLString parameters:(id)parameters constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock success:(void (^)(NSURLResponse * _Nonnull response, id responseObject))success failure:(void (^)(NSURLResponse * _Nonnull response, NSError *error))failure error:(NSError *__autoreleasing *)requestError { NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"PUT" URLString:(NSString *)URLString parameters:(NSDictionary *)parameters constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block error:(NSError *__autoreleasing *)requestError]; AFURLSessionManager *manager = [AFURLSessionManager sharedManager];//[AFURLSessionManager manager] NSURLSessionUploadTask *uploadTask; uploadTask = [manager uploadTaskWithStreamedRequest:(NSURLRequest *)request progress:(void (^)(NSProgress *uploadProgress)) uploadProgressBlock completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { if (error) { failure(response, error); } else { success(response, responseObject); } }]; [uploadTask resume]; } Just like the classic afnetworking. Put it to your net work Util :)
{ "language": "en", "url": "https://stackoverflow.com/questions/30387985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to get alert text message inside my notification center using titanium studio for android and ios I need to display alert message in notification center for both (iOS and Android) titanium App. I am using an enterprise apple account for my app. I can play sound in the background service mode in titanium, but I also want to see alert message inside the notification center for my app. Currently, I only see that inside General -> profile -> my verified entriprise application. How do I enable notification? I cant get alert text/badge in notification center and even there is no application settings inside settings in my iPad device. This code is in place to register for push notifications: Titanium.Network.registerForPushNotifications({ types: [ Titanium.Network.NOTIFICATION_TYPE_BADGE, Titanium.Network.NOTIFICATION_TYPE_ALERT, Titanium.Network.NOTIFICATION_TYPE_SOUND ], success:function(e) { var deviceToken = e.deviceToken; label.text = "Device registered. Device token: \n\n"+deviceToken; Ti.API.info("Push notification device token is: "+deviceToken); Ti.API.info("Push notification types: "+Titanium.Network.remoteNotificationTypes); Ti.API.info("Push notification enabled: "+Titanium.Network.remoteNotificationsEnabled); }, error:function(e) { label.text = "Error during registration: "+e.error; }, callback:function(e) { // called when a push notification is received. alert("Received a push notification\n\nPayload:\n\n"+JSON.stringify(e.data)); } }); How do I get notification messages inside the application's notification center section? A: My assumptions from your questions: * *You want to use Appcelerator Arrow Push to send a push notification using https://platform.appcelerator.com *You want the push notification to appear in the iOS Notification Centre You code does not show that you actually send the deviceToken to Arrow or any other back-end where you'd send the push notification. Please follow: https://appcelerator.github.io/appc-docs/latest/#!/guide/Subscribing_to_push_notifications-section-37551717_Subscribingtopushnotifications-SubscribingtoPushNotificationswithDeviceTokens The app does not control where a push notification appears. This is controlled in iOS via Settings > Notifications per app.
{ "language": "en", "url": "https://stackoverflow.com/questions/33859307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Koan Support Issue I need a little help with the code listed below. I'm working with Koans right now and am stuck on a problem...Probably making it more difficult than what it should be. If anyone can help me out that would be great...Just need to know what goes in "FILL_ME_IN". // Some ways of asserting equality are better than others. it('should assert equality a better way', function() { var expectedValue = FILL_ME_IN; var actualValue = 1 + 1; // toEqual() compares using common sense equality. expect(actualValue).toEqual(expectedValue); }); Thanks! A: As @Rogier Spieker mentioned, a more real world example would be something like Your code, usually in a separate file function addNumbers(a,b){ return a +b; } Your tests it('adds two numbers', function() { var actualValue = addNumbers(1,1); // toEqual() compares using common sense equality. expect(actualValue).toEqual(2); });
{ "language": "en", "url": "https://stackoverflow.com/questions/35870721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Odd HTML validation error I'm getting an odd HTML validation error from this piece of JavaScript any help appreciated, I think it may be causing a bug in the slider function that I'm working with... <script type="text/javascript" charset="utf-8"> sfHover = function() { var sfEls = document.getElementById("nav2").getElementsByTagName("LI"); for (var i=0; i<sfEls.length; i++) { sfEls[i].onmouseover=function() { this.className+=" sfhover"; } sfEls[i].onmouseout=function() { this.className=this.className.replace(new RegExp(" sfhover\\b"), ""); } } } if (window.attachEvent) window.attachEvent("onload", sfHover); </script> The errors are Error: character ";" not allowed in attribute specification list and Error: element "sfEls.length" undefined from the line for (var i=0; i and Error: end tag for "sfEls.length" omitted, but OMITTAG NO was specified from the closing script tag A: Your Javascript contains special characters for XML (< and &). Therefore, it's invalid markup. You need to wrap it in a CDATA section, which will prevent the XML parser from parsing its contents: <script type="text/javascript"> //<![CDATA[ ... //]]> </script> The comments are necessary to prevent the CDATA section from causing Javascript syntax errors in browsers that don't recognize it
{ "language": "en", "url": "https://stackoverflow.com/questions/4985690", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }