_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d701
train
You can just use a list for the sake of having a sorted - well - list. If you want to associate additional data, you could either use a tuple to store the data, or even create a custom object for it that stores the id in an additional field. You shouldn’t need to extend the list for that, you can just put any object into a list. For example this would be easily possible: >>> lst = [ ( 132, 'foobar' ), ( 58, 'other value' ) ] >>> lst.append( ( 70, 'some data value' ) ) >>> lst [(132, 'foobar'), (58, 'other value'), (70, 'some data value')] >>> lst.sort( key=lambda x: x[0] ) >>> lst [(58, 'other value'), (70, 'some data value'), (132, 'foobar')] >>> lst.sort( key=lambda x: x[1] ) >>> lst [(132, 'foobar'), (58, 'other value'), (70, 'some data value')] edit: In case you are using Python 3.1+, you could also use the collections.OrderedDict type. It is an extension to the normal dict which maintains the order just like list does. A: Using lists or arrays is problematic when you need to do insertions or deletions -- these are O(n) operations which can be devastatingly slow with large datasets. Consider using blist which has a list-like API but affords O(lg N) insertion and deletion. A: why not using a dictionary, with the key as the item of original array, and value is the id related to the key. of course you could access it in sorted order, like this: a = {'key':'id'} keys = a.keys() keys.sort() for k in keys: print a[key] A: Similar to poke's answer, you can use a 2d array -- but if the arrays are big, NumPy is generally a good bet for any kind of numerical data in Python. Just make a 2D array that looks like [ [1 614.124] [2 621236.139] [3 1243.612] ] and then you can sort with .sort().
unknown
d702
train
I suggest you do use w+b mode, but move writing to zipfile after closing the invoice XML file. From what you wrote it looks as you are trying to compress a file that is not yet flushed to disk, therefore with w+b it is still empty at time of compression. So, try remove 1 level of indent for invoices_package.write line (I can't format code properly on mobile, so can't post whole section).
unknown
d703
train
First you should turn on error displaying in your iis, or read the error log for its description, google it if not sure how. Without error description, it's way too difficult to check what is wrong. A: Problem solved! After banging my head against the wall for a day i found out that i stupidly declared the array inside the DO WHILE loop. Moved the declaration out of it and problem solved.
unknown
d704
train
You shouldn't add the templatetags directory to installed apps. You should put the templatetags directory inside an existing app, and add that to installed apps. A: Try to move templatetags folder to logicalhp A: Part of the problem was a typo in my settings.py (wrote the 'logicalhp.templatetags' when it was in 'itslogical'). The larger problem was that it was trying to get the attribute "STATIC_URL" from my settings. It included the quotes, so it was effectively settings.__getattr__('"STATIC_URL"'). To fix it, I added a strip. return settings.__getattr__(str(self.arg)) #before return settings.__getattr__(str(self.arg).strip('"')) #after (By the way, it's not like you can omit the quotes in the template; else it think's its a variable. )
unknown
d705
train
The answer I needed is based upon Levon's reply at: How to delete a table in SQLAlchemy? Basically, this did the trick: from sqlalchemy import MetaData from sqlalchemy.ext.declarative import declarative_base from [code location] import db Base = declarative_base() metadata = MetaData(db.engine, reflect=True) table = metadata.tables.get(table_name) table_to_delete = metadata.tables.get('table_name_for_table_to_delete') Base.metadata.drop_all(db.engine, [table_to_delete])
unknown
d706
train
Update: Please see the following tech note for iOS 8 support: http://www-01.ibm.com/support/docview.wss?uid=swg21684538 The link includes download links for patched versions of Worklight 5.0.6, 6.0, 6.1 and 6.2 as well as a list of fixed issues and other instructions. * *The relevant iFix is that from September 18th at the least. *The fix is Studio-only. *Users of Worklight 6.1.0.x should use the iFix from September 19th containing an App Store submission bug fix. *Users of Worklight 6.0.0.x should also delete the wlBuildResources folder from the tmp directory prior to generating the fixed version (close Eclipse > Delete > Open Eclipse). *Due to the nature of the defect (in native code, before the Worklight framework initializes), there are no alternatives other than the below... Scenarios: * *If a user has already upgraded to iOS8 and the application got stuck on the splash screen, AFAIK the way to handle it is to either: * *Uninstall/re-install the application from the App Store. *Install a newer app version (see below) from the App Store. *If a user did not yet upgrade to iOS8, it is best to use the fixed Worklight Studio to generate an updated app, increment its version and re-publish it. Then, Remote Disable the existing version and direct users to install the fixed version from the App Store; the fixed version should then continue to work after upgrading to iOS8. Old: Worklight in general does support iOS 8, but this is a specific scenario that requires further investigation. Thanks for the report, We're going to look into it.
unknown
d707
train
First of all, the class AlexaViewSet is not a serializer but a ViewSet. You didn't specify the serializer class on that ViewSet so I you need to specify that. On the other side, if you want to pass a custom query param on the URL then you should override the list method of this ViewSet and parse the query string passed in the request object to retrieve the value of group_by, validate it, and then perfom the aggregation youself. Another problem that I see is that you also need to define what is to aggregate a JSON field, which is not supported in SQL and it's very relative, so you may want to consider redesigning how you store the information of this JSON field if you want to perfom aggregations on fields inside it. I would suggest extracting the fields you want to aggregate from the JSON (when storing them in the database) and put them in a SQL column separately so you could perform aggregations later. The client could also pass the agregation operation as a query parameter, for example aggregation=sum or aggregation=avg. In a simple case, where you just need the average of the ranks this should be useful as an example (you could add TruncQuarter, etc.): class AlexaViewSet(viewsets.ModelViewSet): serializer_class = AlexaSerializer queryset = Alexa.objects.all() filter_fields = {'created_at': ['iexact', 'lte', 'gte']} http_method_names = ['get', 'post', 'head'] GROUP_CASTING_MAP = { # Used for outputing the reset datetime when grouping 'day': Cast(TruncDate('created_at'), output_field=DateTimeField()), 'month': Cast(TruncMonth('created_at'), output_field=DateTimeField()), 'week': Cast(TruncWeek('created_at'), output_field=DateTimeField()), 'year': Cast(TruncYear('created_at'), output_field=DateTimeField()), } GROUP_ANNOTATIONS_MAP = { # Defines the fields used for grouping 'day': { 'day': TruncDay('created_at'), 'month': TruncMonth('created_at'), 'year': TruncYear('created_at'), }, 'week': { 'week': TruncWeek('created_at') }, 'month': { 'month': TruncMonth('created_at'), 'year': TruncYear('created_at'), }, 'year': { 'year': TruncYear('created_at'), }, } def list(self, request, *args, **kwargs): group_by_field = request.GET.get('group_by', None) if group_by_field and group_by_field not in self.GROUP_CASTING_MAP.keys(): # validate possible values return Response(status=status.HTTP_400_BAD_REQUEST) queryset = self.filter_queryset(self.get_queryset()) if group_by_field: queryset = queryset.annotate(**self.GROUP_ANNOTATIONS_MAP[group_by_field]) \ .values(*self.GROUP_ANNOTATIONS_MAP[group_by_field]) \ .annotate(rank=Avg('rank'), created_at=self.GROUP_CASTING_MAP[group_by_field]) \ .values('rank', 'created_at') page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) For these values: GET /alexa [ { "id": 1, "created_at": "2020-03-16T12:04:59.096098Z", "extra": "{}", "rank": 2 }, { "id": 2, "created_at": "2020-02-15T12:05:01.907920Z", "extra": "{}", "rank": 64 }, { "id": 3, "created_at": "2020-02-15T12:05:03.890150Z", "extra": "{}", "rank": 232 }, { "id": 4, "created_at": "2020-02-15T12:05:06.357748Z", "extra": "{}", "rank": 12 } ] GET /alexa/?group_by=day [ { "created_at": "2020-02-15T00:00:00Z", "extra": null, "rank": 102 }, { "created_at": "2020-03-16T00:00:00Z", "extra": null, "rank": 2 } ] GET /alexa/?group_by=week [ { "created_at": "2020-02-10T00:00:00Z", "extra": null, "rank": 102 }, { "created_at": "2020-03-16T00:00:00Z", "extra": null, "rank": 2 } ] GET /alexa/?group_by=month [ { "created_at": "2020-02-01T00:00:00Z", "extra": null, "rank": 102 }, { "created_at": "2020-03-01T00:00:00Z", "extra": null, "rank": 2 } ] GET /alexa/?group_by=year [ { "created_at": "2020-01-01T00:00:00Z", "extra": null, "rank": 77 } ]
unknown
d708
train
you should check if your database has data that doesn't fit like an id value that is not present in the foreign table, delete any rows like that and the migration should work, it would help if you let us know what npm run deploy:fresh does, you might be doing something else wrong if the data is not clearing on a clean migration A: You need to use the same data type in both tables when using foreign keys. As an example, if you are using 'uuid' for id in agegroups table, then you must use uuid for users table foreign key (age_group_id)also. But here you used 'text' data type for foreign key. Please check whether both data types are similar or not.
unknown
d709
train
If you want the Dialog Border to appear in any colour you wish you have to use layout style and a theme. There is an excellent article about it here: http://blog.androgames.net/10/custom-android-dialog/
unknown
d710
train
.single('parameter') means the input field's name is 'parameter' In your case: app.use(multer({dest: './app/controller/store'}).single('photo')); You passed a 'photo' argument into single func. Then your form should look like this, change it: .. .. <input type="file" name="photo"> .. ..
unknown
d711
train
Though it may be more complicated, why not just have an onmousedown event on the <p> element, and thet event will then attach an onmousemove event and onmouseout event, so that if there is a mouse movement, while the button is down, then remove the class on the span elements, and once the user exits, the element then you can put them back. It may be a bit tricky, and you may want to also look for key presses, or determine other times you want to know when to put back the css classes, but this would be one option, I believe. A: It sounds like you need to go one step further and on highlight, remove the <span> and save a reference to it. Once the highlight is finished, re-insert the reference to the object. // copy start detected var savedTooltip = $('.tooltip').remove(); // later that day when copy finished $('p').append(savedTooltip); If position of the <span> in your markup is important, you'd have to create a temporary reference element so you'd know where to re-insert it in the DOM.
unknown
d712
train
you should to do several things but I think you don't do that. I create a simple project only for you and added to my GitHub just click in this link: GitHub first Project templates if it is helpful please, take a vote. A: First of all, you wrote scr, not src and this should be corrected. <!--It doesn't work--> <img scr="{% static "first_app/yp.jpg" %}" alt="oh oh"> After that you may need to clear "first_app/" part from your code, because you are adressing your directory directly in settings file.
unknown
d713
train
I've had this problem before, and if I recall correctly it had something to do with iOS not knowing the actual size until after the view has been drawn the first time. We were able to get it to update by refreshing after viewDidAppear (like you mentioned it's the appropriate size after refreshing), but that's not exactly the nicest solution. Something else you could try is adding constraint outlets to the cell that you manipulate wherever you do your cell setup. For example, if you needed a UI element to be a certain width in some cases but not others, you could add a width constraint that you change the value of. This lets your other elements resize themselves based on the other constraints in the view. The limitation here is that you need to know the width of one of your elements beforehand.
unknown
d714
train
Reference for CardView. It is just a RelativeLayout with a rounded corners and a drop shadow. So yes, the image was probably an image of a layout designed with CardViews. At the same time, it could also just be a layout that was custom built and a shadow drawn behind it, if that developer wanted to do the work themselves. You can easily replicate the layout by creating this in xml, I can provide an example if necessary. The CardView is not JUST designed for RecyclerView's but looks really good in a RecyclerView as the layout that is inflated IF a CardView layout makes sense to use. Again, it's just a RelativeLayout with extra features (rounded edges, and shadow)
unknown
d715
train
You can do this by enabling two-phase rendering: https://www.ibm.com/support/knowledgecenter/en/SSHRKX_8.5.0/mp/dev-portlet/jsr2phase_overview.html. Enable two-phase rendering in the portlet.xml like this: <portlet> ... <container-runtime-option> <name>javax.portlet.renderHeaders</name> <value>true</value> </container-runtime-option> </portlet> Then you can set the headers within the doHeaders method by using the setProperty or addProperty response methods: @Override protected void doHeaders(RenderRequest request, RenderResponse response) { response.addProperty("MyHeader", "MyHeaderValue"); }
unknown
d716
train
You sended string to model but you must send collection to model and then show in table A: Your view is expecting IEnumerable<Website.Models.OrderIndexViewModel> as the model but you are passing it a single instance of Website.Models.OrderIndexViewModel. This might be another bug in your code, as this will only ever render the last item from the select statement. So you'll want something like this, which will render a row for each result: var orders = new List<OrderIndexViewModel>(); while (reader.Read()) { var order = new OrderIndexViewModel(); order.CustomerOrderId = reader.GetInt32(0); order.FirstName = reader.GetString(1); order.ProductId = reader.GetInt32(2); order.Name = reader.GetString(3); order.Price = reader.GetDecimal(4); orders.Add(order); } cnn.Close(); return View(orders);
unknown
d717
train
When you use AND and OR together in any circumstances in any programming language ALWAYS use brackets. There is an implicit order which gets evaluated first (the AND or the OR condition) but you usually don't know the order and shouldn't be in need to look it up in the manual Also use Prepared statements for SQL queries which depends on variables. In your case you either write ... WHERE (host = ? OR challenger = ?) AND id = ? or ... WHERE host = ? OR (challenger = ? AND id = ?) depending on what condition you want. Also, when a SQL query fails for whatever reason check the error message you get from the database. It will tell you whats wrong with the query. However, a valid query which returns no rows (because the WHERE condition don't match for any row) is still a valid query and not an error, the result is just empty.
unknown
d718
train
I recommend trying it out for yourself, but the comment in the code #TODO/XXX: Remove as_lookup_value() once we have a cleaner solution # for dot-notation queries suggests that it does. I've ever only really used lists. A: You can filter for a Post that has an author named "Ralph" using raw queries: Post.objects.raw_query({'author.name': "Ralph"})
unknown
d719
train
I found a way. Just add httpServletRequest.getSession().setMaxInactiveInterval(intervalInSeconds) @RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public String login(HttpServletRequest request, HttpServletResponse servletresponse){ //Your logic to validate the login request.getSession().setMaxInactiveInterval(intervalInSeconds); } This worked for me. EDIT 1 Found another way to do this. This would be the correct way of doing this, @EnableJdbcHttpSession(maxInactiveIntervalInSeconds = intervalInSeconds)
unknown
d720
train
The string is slightly incorrect, but I hope all other requirements are met: // Create a font XFont font = new XFont("Verdana", 12, XFontStyle.Bold | XFontStyle.Underline); // Draw the text gfx.DrawString("Hello, World!", font, new XSolidBrush(XColor.FromArgb(255, 0, 0)), 100, 100, XStringFormats.Center);
unknown
d721
train
In your yamls, there is a path "/?..." for handling the query parameters but this path will not receive traffic from "/" path as there is no prefix match. So you have to create a path "/" with type prefix to solve the issue. Then you can ignore current "/?..." path as it will match prefix with "/" path. Please try this: ingress-srv.yaml __________________ apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: ingress-srv annotations: kubernetes.io/ingress.class: nginx nginx.ingress.kubernetes.io/use-regex: "use" spec: rules: - host: posts.com http: paths: - path: / pathType: Prefix backend: service: name: client-srv port: number: 3000 - path: /posts/create pathType: Prefix backend: service: name: posts-clusterip-srv port: number: 4000 - path: /posts pathType: Prefix backend: service: name: query-srv port: number: 4002 - path: /posts/?(.*)/comments pathType: Prefix backend: service: name: comments-srv port: number: 4001 - path: /?(.*) pathType: Prefix backend: service: name: client-srv port: number: 3000 A: so the issue was a really dumb one - I actually set nginx.ingress.kubernetes.io/use-regex: "use" instead of nginx.ingress.kubernetes.io/use-regex: "true"... After three days of checking through the documentation, I finally found it. If anyone encounters a similar problem - there you have it. A: You have to add following rules in your spec - path: / pathType: Prefix backend: service: name: client-srv port: number: 3000 This matches all paths. Reference - https://kubernetes.io/docs/concepts/services-networking/ingress/#examples
unknown
d722
train
You aren't ever calling the function in your worker. This code in the worker: import { parentPort } from "worker_threads"; async function worker() { console.log("started"); parentPort.postMessage("fixed!"); } Just defines a function named worker. It never calls that function. If you want it called immediately, then you must call it like this: import { parentPort } from "worker_threads"; async function worker() { console.log("started"); parentPort.postMessage("fixed!"); } worker(); FYI, in the worker implementations I've built, I usually either execute something based on data passed into the worker or the worker executes something based on a message it receives from the parent.
unknown
d723
train
i think i found it after a lot of blood, sweat, and tears. i found that the ObjectMapper i had configured was actually not the one that was being used. Jersey1 clientConfig.getSingletons().add(new JacksonJsonProvider(objectMapper)); Client client = new Client(urlConnectionClientHandler, clientConfig); JAXRS2 (what did not work) clientConfig.register(new JacksonJsonProvider(objectMapper)); Client client = ClientBuilder.newClient(cc); i found that the component creating the ObjectMapper that was ACTUALLY being used was a JacksonJaxbJsonProvider and that registering it with the ClientConfig did not work, but registering it on the client did. JAXRS2 (what did work) Client client = ClientBuilder.newClient(cc); client.register(new JacksonJaxbJsonProvider(objectMapper, JacksonJaxbJsonProvider.DEFAULT_ANNOTATIONS));
unknown
d724
train
You cannot protect your API keys for authorization when your API calls are initiated from the client (i.e., JavaScript). As you said, there will be no point of encrypting them as well. You'll need to have an authorization provider that can return the API key as part of the response. API Gateway allows you to have custom authorizer for your API. See Output from an Amazon API Gateway Custom Authorizer.
unknown
d725
train
If I got your question right, you can use union like this - select * from table_1 union select * from table_2 order by create_date desc EDIT Create a view like this - create view table_1And2 as select * from table_1 union select * from table_2 table_1And2 is not a good name, give a meaningful name. And modify your long query like this - SELECT table_1And2.id, table_1And2.created, table_1And2.qty, table_1And2.comments, table_1And2.last_update, table_7.firstname, SUBSTRING(table_7.lastname, 1, 1) AS lastname, table_8.title country, table_3.value AS sim, table_1And2.offer_request, table_5.manufacturer AS manufacturer, table_4.name AS model, table_6.value AS specifications, table_9.value as shipping, table_1And2.model AS mid, table_1And2.user_id, table_1And2.callme, table_1And2.phoneprice, table_1And2.phoneprice_eur, table_1And2.currency, table_1And2.sel_buy_show_all, table_1And2.seller_buyer FROM (`table_1And2`) LEFT JOIN `table_3` ON `table_3`.`id` = `table_1And2`.`sim` LEFT JOIN `table_4` ON `table_4`.`id` = `table_1And2`.`model` LEFT JOIN `table_5` ON `table_5`.`id` = `table_1And2`.`manufacturer` LEFT JOIN `table_6` ON `table_6`.`id` = `table_1And2`.`specifications` LEFT JOIN `table_7` ON `table_7`.`id` = `table_1And2`.`user_id` LEFT JOIN `table_8` ON `table_7`.`country`=`table_8`.`id` LEFT JOIN `table_9` ON `table_9`.`id` = `table_1And2`.`types` WHERE `table_1And2`.`status` = '1' AND `table_1And2`.`deleted` = '0' ORDER BY `last_update` DESC LIMIT 200 A: Also I see the answer of @Rehban is a good one for you, I will produce another solution if you do not need view: SELECT mainTable.id, mainTable.created, mainTable.qty, mainTable.comments, mainTable.last_update, table_7.firstname, SUBSTRING(table_7.lastname, 1, 1) AS lastname, table_8.title country, table_3.value AS sim, mainTable.offer_request, table_5.manufacturer AS manufacturer, table_4.name AS model, table_6.value AS specifications, table_9.value as shipping, mainTable.model AS mid, mainTable.user_id, mainTable.callme, mainTable.phoneprice, mainTable.phoneprice_eur, mainTable.currency, mainTable.sel_buy_show_all, mainTable.seller_buyer FROM (Select * From `table_1` union Select * From `table_2`) as mainTable LEFT JOIN `table_3` ON `table_3`.`id` = `mainTable `.`sim` LEFT JOIN `table_4` ON `table_4`.`id` = `mainTable `.`model` LEFT JOIN `table_5` ON `table_5`.`id` = `mainTable `.`manufacturer` LEFT JOIN `table_6` ON `table_6`.`id` = `mainTable `.`specifications` LEFT JOIN `table_7` ON `table_7`.`id` = `mainTable `.`user_id` LEFT JOIN `table_8` ON `table_7`.`country`=`table_8`.`id` LEFT JOIN `table_9` ON `table_9`.`id` = `mainTable `.`types` WHERE `mainTable `.`status` = '1' AND `mainTable `.`deleted` = '0' ORDER BY `last_update` DESC LIMIT 200
unknown
d726
train
There might be a more elegant solution but you can loop through the response_date values in df2 and create a boolean series of values by checking against the all the response_date values in df1 and simply summing them all up. df1['group'] = 0 for rd in df2.response_date.values: df1['group'] += df1.response_date > rd Output: summary participant_id response_date group 0 2.0 11 2016-04-30 0 1 3.0 11 2016-05-01 1 2 3.0 11 2016-05-02 1 3 3.0 11 2016-05-03 1 4 3.0 11 2016-05-04 1 Building off of @Scott's answer: You can use pd.cut but you will need to add a date before the earliest date and after the latest date in response_date from df2 dates = [pd.Timestamp('2000-1-1')] + df2.response_date.sort_values().tolist() + [pd.Timestamp('2020-1-1')] df1['group'] = pd.cut(df1['response_date'], dates) A: You want the .cut method. This lets you bin your dates by some other list of dates. df1['cuts'] = pd.cut(df1['response_date'], df2['response_date']) grouped = df1.groupby('cuts') print grouped.max() #for example
unknown
d727
train
Finally I have solved it. ReactiveMaps does not allow the location field in uppercase, so I had to change the indexed documents in elasticsearch taking in account this. "location": { "lat": 56.746423, "lon": 37.189268 }
unknown
d728
train
* *I think your pipe is fired before the 'filename' get any data. *You should not split with '/' Try this instead: var mime = require('mime-types'); // After npm install mime-types request .get(uri) .on('response', function (response) { var responseType = (response.headers['content-type'] || '').split(';')[0].trim(); var ext = mime.extension(responseType); filename += '.' + ext; var fileStream = fs.createWriteStream(filename) .on('finish', function() { //Download complete }) this.pipe(fileStream); }) P.S. You are downloading with 'request' module, not with express.
unknown
d729
train
You can add it to some other app, or even create just a file called static in the root of project_name and refer to the class inside this file in your settings.INSTALLED_APPS directly, but the recommended way to provide AppConfigs is inside an apps.py file inside the application package. If you have no app where this AppConfig could be placed, I think the best practice would be to create a package under project_name.project_name called static, with only an init.py file and an apps.py file. In this file you can create your AppConfig in the way you described. Your file structure will then look like this: -- project_name -- assets -- app1 -- templates -- project_name -- app1 -- app2 -- static -- __init__.py -- apps.py -- __init__.py -- settings.py -- urls.py -- wsgi.py
unknown
d730
train
Use Following code VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() { @Override public void onResponse(NetworkResponse response) { String resultResponse = new String(response.data); // parse success output } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("name", "Sam"); params.put("location", "India"); params.put("about", "UI/UX Designer"); params.put("contact", "xyz@email.com"); return params; } @Override protected Map<String, DataPart> getByteData() { Map<String, DataPart> params = new HashMap<>(); // file name could found file base or direct access from real path // for now just get bitmap data from ImageView params.put("avatar", new DataPart("file_avatar.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mAvatarImage.getDrawable()), "image/jpeg")); params.put("cover", new DataPart("file_cover.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mCoverImage.getDrawable()), "image/jpeg")); return params; } }; VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest); A: VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(com.android.volley.Request.Method.POST, url, new Response.Listener<NetworkResponse>() { @Override public void onResponse(NetworkResponse response) { } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }) { //pass String parameters here @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<>(); params.put("category", "image"); params.put("p_name", "myImage"); return params; } //pass header @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<String, String>(); headers.put("key", key); headers.put("tkey", tkey); headers.put("Content-Type", "application/multipart"); return headers; } //pass file here (*/* - means you can pass any kind of file) @Override protected Map<String, VolleyMultipartRequest.DataPart> getByteData() { Map<String, DataPart> up_params = new HashMap<>(); up_params.put("params", new DataPart(file_path, file_name, "*/*")); return up_params; } }; VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);
unknown
d731
train
argc and argv refer to command line inputs. When the program is run they are specified by the user. myprogram.exe --input1 fred See this: What does int argc, char *argv[] mean?
unknown
d732
train
Declare your DBLoader loader as global variable at the onCreateLoader loader = new DBLoader(this); return loader; put this at the onCreate method instead of onLoadFinished myAdapter = new MyCursorAdapter(this,null,0); bookList.setAdapter(myAdapter); put this at onLoadFinishied this.loader=(DBLoader)loader; adapter.changeCursor(cursor); A: After some searching, I saw a few examples on the internet where they use a getSupportLoaderManager().initLoader(1,null,this).forceLoad();. That seems to work. also calling loader.forceLoad() in the onCreateLoader() works too. On further checking, I saw this : https://issuetracker.google.com/issues/36925900 It seems we have to implement forceLoad in onStartLoading() as thus: protected void onStartLoading() { if (mCursor != null) { deliverResult(mCursor); } if (takeContentChanged() || mCursor == null) { forceLoad(); } } doing this will cease the need for a .forceLoad() in our Activity
unknown
d733
train
It looks like the function you're trying to call is compiled as a C++ function and hence has it's name mangled. PInvoke does not support mangled name. You need to add an extern "C" block around the function definition to prevent name mangling extern "C" { void* aaeonAPIOpen(uint reserved); } A: Using the undname.exe utility, that symbol demangles to void * __cdecl aaeonAPIOpen(unsigned long) Which makes the proper declaration: [DllImport("aonAPI.dll", EntryPoint="?aaeonAPIOpen@@YAPAXK@Z", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr aaeonAPIOpen(uint reserved);
unknown
d734
train
The composer program is a ascii text file, and as such the setuid bit has no effect on it. Since you are kicking off the process as root, you can do something like su www-data -c "composer ...."
unknown
d735
train
It's feasible, at least, using PyQt + QWebKit (an example here and here).
unknown
d736
train
This is a bug of jekyll-sitemap and it has already been fixed. You can upgrade jekyll-sitemap to v0.6.2 and everything will be ok. https://github.com/jekyll/jekyll-sitemap/issues/54
unknown
d737
train
Web-handler should return a response object, not None. The fixed code is: async def index(request): async with aiohttp.ClientSession() as client: data=await(email_verification(client)) await client.post('http://127.0.0.1:8000/acc/signup',data=data) return web.Response(text="OK") async def email_verification(client): async with client.get('http://www.mocky.io/v2/5c18dfb62f00005b00af1241') as resp: return await(resp.json())
unknown
d738
train
The latest versions of Matlab have hashes. I'm using 2007b and they aren't available, so I use structs whenever I need a hash. Just convert the integers to valid field names with genvarname.
unknown
d739
train
use jQuery $(window).scrollTop()
unknown
d740
train
i have found the issue, posting if will help somebody else. the problem was that mysqld went into infinite loop trying to create indexing to a specific database, after found to which database was trying to create the indexes and never succeed and was trying again and again. solution was to remove the database and recreate it, and the mysqld process went back to normal. and the infinite loop to create indexes dissapeared as well. A: I would say increasing connection may solve your problem temperately. 1st find out why the application is not closing the connection after completion of task. 2nd Any slow queries/calls on the DB and fix them if any. 3rd considering no slow queries/calls on DB and also application is closing the connection/thread after immediately completing the task, then consider playing with "wait_timeout" on mysql side. A: According to this answer, if you have MySQL 5.7 and 5.8 : It is worth knowing that if you run out of usable disc space on your server partition or drive, that this will also cause MySQL to return this error. If you're sure it's not the actual number of users connected then the next step is to check that you have free space on your MySQL server drive/partition. From the same thread. You can inspect and increase number of MySQL connections.
unknown
d741
train
You can create a text node and append it to the parent of img, and optionally remove img if needed. This code goes inside the error handler for img $('img').on('error', function(){ $(this).parent().append($('<div>Broken image</div>')); $(this).remove(); }) A: Ok, I think I have found a solution for you. I tried to use jQuery error function. This one helped me: To replace all the missing images with another, you can update the src attribute inside the callback passed to .error(). Be sure that the replacement image exists; otherwise the error event will be triggered indefinitely. In your example this would be the best: $('img').each(function() { var img = $(this); img.error(function() { img.replaceWith('<div class="error404">Image not found (error 404)</div>'); }).attr('src', img.attr('src')); }); I also made a jsFiddle example for you, which is working great for me. A: If you really need to use javascript for this try $(document).ready(function() { $('img').attr('alt', 'Alternative text'); }); But the same is achievable by barebone HTML <img src="path/to/image.jpg" alt="Alternative text"> A: You can change the alt if an error is thrown just like you're doing with the image. function imgMissing(image) { image.onerror = ""; image.alt = "Image not Found"; return true; } The HTML: <img src="image.jpg" onerror="imgMissing(this);" > A: EDIT: OK, I have found this solution working fine: <script type="text/javascript"> $(document).ready(function() { $('.post_body img').one('error', function() { $(this).replaceWith('<div>Image not found (error 404)</div>'); }); }); </script> Anyway one more think, I need to add CSS class "error404" for this "div", how to do that in JS? Thank you very much! CSS will be: .error404 { display: block; color: #667d99; font-weight: bold; font-size: 11px; border: 1px dotted; border-radius: 3px; padding: 5px; margin: 10px; background: #e7edf3; }
unknown
d742
train
You can just set the headers directly. $cookies = array( 'somekey' => 'somevalue' ); $endpoint = 'https://example.org'; $requestMethod = 'POST'; $timeout = 30; $headers = array( sprintf('Cookie: %s', http_build_query($cookies, null, '; ')) ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $endpoint); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_MAXREDIRS, 10); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // you may need to make this false depending on the servers certificate curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $requestMethod); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FAILONERROR, false); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); $response = curl_exec($ch); list($header, $body) = explode("\r\n\r\n", $response, 2); // now all the headers from your request will be available in $header
unknown
d743
train
Your code has undefined behavior. You cannot validly access the memory pointed at by an uninitialized pointer, like you do. The memset() function writes to memory, it does not magically allocate new memory (it takes as input the pointer to the memory to be written), you cannot in anyway use it "instead of" malloc(). You can try with an on-stack buffer: char log[128] = ""; of course you need to take care not to use more than 128 characters; your unbounded strcat() usage is dangerous. If your fringe compiler supports C99 you can of course do: const size_t flen = strlen(func); const size_t mlen = strlen(msg); char log[flen + 2 + mlen + 1]; // Space for func, msg, colon, space, terminator. A: Declare an array of chars with the size of func + size of msg instead of an uninitialized char pointer.
unknown
d744
train
I got the same error message in a new java installation when trying to use an SSL connection that enforces 256-bit encryption. To fix the problem I found I needed to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files (e.g. http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html) A: I had this line SSLContext sc = SSLContext.getInstance("SSL"); Had to change it to SSLContext sc = SSLContext.getInstance("TLSv1"); And now it works on both, java 7 and java 8 Note: (In java 7 SSL and TLS both worked with the same url, in java 8 just tried TLSv1 but I guess SSLv1 also works) A: Download the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files according to your JDK/JRE version and put it in lib/security folder By default,Java Cryptographic Extension is limited in accessing function and algorithm usage.We need to make it unlimited. A: According to the stack trace, the RecordVersion Unknow-0.0 is produced from here => referenced from here => which is invoked in InputRecord.readV3Record most of the time, these two values should not be 0, the reason for this happening is probably the wrong response from server while handshaking. (This is not an answer though, just some information for easier figuring out the problem and solution) A: This error is fixed in latest jre's, just upgrade the version of jre. This issue is caused by SNI
unknown
d745
train
Next to your question there are some other things to take into account: a. Always use Parameters when creating Sql: SqlCommand cmd = new SqlCommand("select * from personeel where wachtwoord = @Password", conn); cmd.Parameters.Add("@Password", password) b. Put your database methods in a separate class (Encapsulation, etc.) --> example: ReserverationsDataAccess c. To answer your main question we'll need some more info (see comments). A: i have made some changes to the code now. SqlCommand cmd = new SqlCommand("select * from personeel where wachtwoord =" + textBox1.Text + "", conn); SqlDataReader dr = cmd.ExecuteReader(); int count = 0; while(dr.Read()) { count += 1; } if (count ==1) { SqlCommand cmd1 = new SqlCommand("select afdeling from personeel where wachtwoord =" + textBox1.Text + "", conn); SqlDataReader dr1 = cmd1.ExecuteReader(); MessageBox.Show("OK"); if (dr1.Rows[0][0].ToString() == "keuken") { this.Hide(); keukenoverzicht keukenoverzicht = new keukenoverzicht(); keukenoverzicht.Show(); } else if (dr1.Rows[0][0].ToString() == "bar") { this.Hide(); baroverzicht baroverzicht = new baroverzicht(); baroverzicht.Show(); } else { this.Hide(); tafeloverzicht tafeloverzicht = new tafeloverzicht(); tafeloverzicht.Show(); } } else { MessageBox.Show("wachtwoord niet corect"); } textBox1.Clear(); conn.Close(); } } it have now 2 errors on dr1.rows -a- what needs to be changed to fix the error (rows) -b- cmd.Parameters.Add("@Password", password) is for ****** in the textbox ride? error rows
unknown
d746
train
Yes, the Playstore supports this feature named In-app-updates There is no official implementation for this here, but take a look at this. A: You can use In-app updates: In-app updates is a Google Play Core libraries feature that prompts active users to update your app. There are mainly two update flows. * *Flexible updates *Immediate updates Here is a detailed guide that describes how to support in-app updates in your app.
unknown
d747
train
You should consider using DS.ActiveModelAdapter instead of DS.RESTAdapter. See also https://stackoverflow.com/a/19209194/1345947
unknown
d748
train
You can do it with openssl pkeyutl which is a replacement for openssl rsautl that supports ECDSA. Suppose you want to hash and sign a 'data.txt' file with openssl. At first you need to hash the file: openssl dgst -sha256 -binary -out data.sha256 data.txt after you can sign it: openssl pkeyutl -sign -inkey private.pem -in data.sha256 -out data.sig However the signature is still in ASN.1 format. To receive r and s values of signature use openssl asn1parse: openssl asn1parse -inform DER -in data.sig
unknown
d749
train
There were breaking changes in redux-forms from v5 to v6. Previously you could do something similar to what you have to access the touched field. If you want to do something similar to see if there are errors on a field, you need to create your own component to pass to redux-form's Field component. Your custom component const CustomComponent = function(field) { return ( <div> <input type={field.type} {...field.input} /> {field.meta.touched && field.meta.error && <div className='error'>{field.meta.error}</div>} </div> ) } Then using it with the Field component <Field name="my-prop" component={CustomComponent} /> Also take a look at the migration guide, hope this helps! A: You are confusing v5 syntax with v6 syntax. In v6, your decorated form component is no longer passed this.props.fields. Re-read the migration guide, like @tyler-iguchi said.
unknown
d750
train
Just click (ctr+h) on keyboard.
unknown
d751
train
External table feature is publicly available feature as per documentation https://docs.snowflake.com/en/user-guide/tables-external-intro.html
unknown
d752
train
You could: print the space before: movielist = ' ' + '\n '.join(movie) print the space for each item: movielist = '\n'.join([' ' +i for i in movie]) Exemple: >>> print '\n '.join(movie) something something something otherthing otherthing >>> print ' '+'\n '.join(movie) something something something otherthing otherthing >>> print '\n'.join([' ' +i for i in movie]) something something something otherthing otherthing A: if you just want the items to be listed side by side then change your print statement to something like print "foo" % bar, Reference: python print end=' '
unknown
d753
train
You need a range value for every one of your ordinal values: var x = d3.scale.ordinal() .domain(["A", "B", "C", "D", "E"]) .range([0, 1/4 * width, 2/4 * width, 3/4 * width, width]); https://jsfiddle.net/39xy8nwd/
unknown
d754
train
Let me just expand a little bit what you've already been told in comments. That's how by-name parameters are desugared by the compiler: @tailrec def factorialTailRec(n: Int, f: => Int): Int = { if (n == 0) { val fEvaluated = f fEvaluated } else { val fEvaluated = f // <-- here we are going deeper into stack. factorialTailRec(n - 1, n * fEvaluated) } } A: Through experimentation I found out that with the call by name formalism, the method becomes... non-tail recursive! I made this example code to compare factorial tail-recursively, and factorial non-tail-recursively: package example import scala.annotation.tailrec object Factorial extends App { val ITERS = 100000 def factorialTailRec(n: Int) : Int = { @tailrec def factorialTailRec(n: Int, f: => Int): Int = { if (n == 0) f else factorialTailRec(n - 1, n * f) } factorialTailRec(n, 1) } for(i <-1 to ITERS) println("factorialTailRec(" + i + ") = " + factorialTailRec(i)) def factorial(n:Int) : Int = { if(n == 0) 1 else n * factorial(n-1) } for(i <-1 to ITERS) println("factorial(" + i + ") = " + factorial(i)) } Observe that the inner tailRec function calls the second argument by name. for which the @tailRec annotation still does NOT throw a compile-time error! I've been playing around with different values for the ITERS variable, and for a value of 100,000, I receive a... StackOverflowError! (The result of zero is there because of overflow of Int.) So I went ahead and changed the signature of factorialTailRec/2, to: def factorialTailRec(n: Int, f: Int): Int i.e call by value for the argument f. This time, the portion of main that runs factorialTailRec finishes absolutely fine, whereas, of course, factorial/1 crashes at the exact same integer. Very, very interesting. It seems as if call by name in this situation maintains the stack frames because of the need of computation of the products themselves all the way back to the call chain.
unknown
d755
train
property: value pairs must go inside a ruleset. font-family: 'Open Sans', Helvetica, Arial, sans-serif; … is not a valid stylesheet. foo { font-family: 'Open Sans', Helvetica, Arial, sans-serif; } … is. Re edit: The errors you are seeing are a side effect of the IE7 hacks at the beginning of the ruleset. Remove the IE7 hacks. The browser is a decade out of date and doesn't even get security updates now.
unknown
d756
train
You add(!) an extra callback function every time you call looper.output to the event 'output'. I don't know what you want to achieve, but to get this call only once use this.once('output', ...) or move the callback setting to the object or remove the old function first...
unknown
d757
train
You have installed SQLAlchemy, but you are trying to use the Flask extension, Flask-SQLAlchemy. While the two are related, they are separate libraries. In order to use from flask.ext.sqlalchemy import SQLAlchemy you need to install it first. pip install Flask-SQLAlchemy (You installed SQLAlchemy directly from source. You can also do that for Flask-SQLAlchemy.)
unknown
d758
train
Load testing; how many selenium clients are you running? One or two will not generate much load. First issue to think about; you need load generators and selenium is a poor way to go about this (unless you are running grid headless but still). So the target server is what, Windows Server 2012? Google Create a Data Collector Set to Monitor Performance Counters. Data collection and analysis of same is your second issue to think about. People pays loads of money for tools like LoadRunner because they provide load generators and sophisticated data collection of servers, database, WANs and LANS and analysis reports to pinpoint bottlenecks. Doing this manually is hard and not easily repeatable. Most folks who start down your path eventually abandon it. Look into the various load/performance tools to see what works best for you and that you can afford.
unknown
d759
train
This is bit tricky to perform in crystal reports as record selection is compulsory applied. However you can overcome this by using sub report. Calculate the report footer using report. This will surely work
unknown
d760
train
You can test for cursor visibility directly with GetCursorInfo() bool IsCursorVisible() { CURSORINFO ci = { sizeof(CURSORINFO) }; if (GetCursorInfo(&ci)) return ci.flags & CURSOR_SHOWING; return false; } I'm not sure what it means for this call to fail so I just have it returning false if it fails.
unknown
d761
train
I am going to explain how it works. But the code you have written is correct. Even I ran the code. let express = require('express'); let app = express(); app.use(express.static('../html&css')); let server = app.listen(8080, function () { app.get(function (req, res) { res.sendFile(); }); }); let port = server.address().port; console.log(`Express app listening at ${port}`); Now, what express.static do? it exposes the particular folder and makes auto routes. If you want to access main.css it will be hosted on localhost:8080/main/main.css In the main.html to use that CSS you just add a link. <link rel="stylesheet" href="main.css"> or <link rel="stylesheet" href="/main/main.css"> But, you cannot HTTP GET let's say localhost:8080/main that will not work. So, you need to run the server by typing node javascript/server.js and it will run just fine. But as the server.js is a backend code do not put it in the public folder. Maybe make a folder called src and put it there. A: Let's look a a few things. First, folder structure: According to your setup, you have your server.js file embedded within the public folder, albeit one level down. If you think of an MVC framework, see this sample tutorial, you want to put your server at the root of your application (not inside of the JavaScript folder inside public where you would serve any client-side javascript. Second, regarding middleware: When you call the express.static middleware, you will want to use the path module to create an absolute rather than relative path to the public folder, which is especially important for deployment. app.use(express.static(path.join(__dirname, 'public'))); Now, you will be able to access all the files in your public folder like so: http://localhost:8080/main/* http://localhost:8080/javascript/* Of course * refers to whatever files are there. Third, regarding app.listen: The callback to app.listen is expecting to be returned a server object. See the documentation. Rather than setting up a listener on a route here, you should establish that outside of the app.listen call. For instance, you may want to set up a basic get route to serve your main.html page on /. That's up to you. The express.static middleware is already serving this page as /main/main.html. app.get('/', function (req, res) { res.sendFile(path.join(__dirname, 'public', 'main.html')); }); let server = app.listen(8080);
unknown
d762
train
If you want to remove border-bottom of last 'li' element, then use following CSS:- .classname:last-child{ border-bottom:0; } Where classname is the class added to the 'li' element. .hide() will hide the last 'li' element, not border.
unknown
d763
train
you can do something like this: parser = configparser.ConfigParser() parser.read_dict({'section1': {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}, 'section2': {'keyA': 'valueA', 'keyB': 'valueB', 'keyC': 'valueC'}, 'section3': {'foo': 'x', 'bar': 'y', 'baz': 'z'}}) Check this for detailed info as well as some other alternative way to achieve this. Sample retrieval parser["section1"]["key1"] 'value1'
unknown
d764
train
Are the "Rules" in database given permission to "Write" * *Go to the firebase console and open your project. *Go to the database and search for "Rules" tab. *Check the rules are set as below { /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */ "rules": { ".read": true, ".write": true } } A: I've solved this issue. The issue was in this piece of code. const downnloadImageURI = imageRef.getDownloadURL().then(url => { this.setState( { imageURI: url, }, () => { alert('ImageURI ==> ', this.state.imageURI); this.saveUserInfo(); }, ); setState was not working and calback was not fired. And I've made it like this way const downnloadImageURI = imageRef.getDownloadURL().then(url => { this.saveUserInfo(url) );}
unknown
d765
train
In JavaScript, variables and functions can't have the same name. (More confusingly: functions are variables!) So that means that this line: let hour = hour(); Is not allowed, because you're trying to reassign the hour variable from being a function to being a value. (This is a side effect of using let. If you had used var then this would have silently did the wrong thing.) To fix the problem, just rename your variable to something that's not already a function. let myHour = hour();
unknown
d766
train
$r = ""; $j = 0; foreach ($orgs as $k => $v) { echo "\n\r" . $v->id . "\n\r"; if (1) { //you don't really need this, because it's allways true $a_view_modl = ArticleView :: model($v->id, $v->id); $connection = $a_view_modl->getDbConnection(); if $orgs is an associative array, it becomes: $r = ""; $j = 0; for($i = 0; $i < count($orgs); $i++) { echo "\n\r" . $orgs[$i]->id . "\n\r"; $a_view_modl = ArticleView :: model($orgs[$i]->id, $orgs[$i]->id); $connection = $a_view_modl->getDbConnection(); } better you do some checks first if you go for this solution. if you implement your solution with foreach which is in this case more readable, you can increment or decrement a given variable, like normal: $i++; //if you want the increment afterwards ++$i; //if you want the increment before you read your variable the same for decrements: $i--; //decrement after reading the variable --$i; //decrement before you read the variable A: A foreach loop is just a better readable for loop. It accepts an array and stores the current key (which is in this case an index) into $k and the value into $v. Then $v has the value you are using in the snippet of code. A for loop does only accept indexed arrays, and no associative arrays. We can rewrite the code by replacing $v with $orgs[ index ], where index starts from 0. $r = ""; $j = 0; for ($i = 0; $i < count($orgs); $i++) { echo "\n\r" . $orgs[$i]->id . "\n\r"; if (1) { $a_view_modl = ArticleView::model($orgs[$i]->id, $orgs[$i]->id); $connection = $a_view_modl->getDbConnection(); A: $r = ""; $j = 0; for($i = 0 ; $i < count($orgs); $i++) { $v = $orgs[$i]; echo "\n\r" . $v->id . "\n\r"; if (1) { $a_view_modl = ArticleView :: model($v->id, $v->id); $connection = $a_view_modl->getDbConnection(); } A: foreach ($orgs as $k => $v) { // Your stuff } for loop for ($i = 0; $i < count($orgs); $i++) { // Your stuff ... use $orgs[$i]; }
unknown
d767
train
I have developed a sample application. I have used string as record item, you can do it using your own entity. Backspace also works properly. public class FilterViewModel { public IEnumerable<string> DataSource { get; set; } public FilterViewModel() { DataSource = new[] { "india", "usa", "uk", "indonesia" }; } } public partial class WinFilter : Window { public WinFilter() { InitializeComponent(); FilterViewModel vm = new FilterViewModel(); this.DataContext = vm; } private void Cmb_KeyUp(object sender, KeyEventArgs e) { CollectionView itemsViewOriginal = (CollectionView)CollectionViewSource.GetDefaultView(Cmb.ItemsSource); itemsViewOriginal.Filter = ((o) => { if (String.IsNullOrEmpty(Cmb.Text)) return true; else { if (((string)o).Contains(Cmb.Text)) return true; else return false; } }); itemsViewOriginal.Refresh(); // if datasource is a DataView, then apply RowFilter as below and replace above logic with below one /* DataView view = (DataView) Cmb.ItemsSource; view.RowFilter = ("Name like '*" + Cmb.Text + "*'"); */ } } XAML <ComboBox x:Name="Cmb" IsTextSearchEnabled="False" IsEditable="True" ItemsSource="{Binding DataSource}" Width="120" IsDropDownOpen="True" StaysOpenOnEdit="True" KeyUp="Cmb_KeyUp" /> A: I think the CollectionView is what you are looking for. public ObservableCollection<NdfClassViewModel> Classes { get { return _classes; } } public ICollectionView ClassesCollectionView { get { if (_classesCollectionView == null) { BuildClassesCollectionView(); } return _classesCollectionView; } } private void BuildClassesCollectionView() { _classesCollectionView = CollectionViewSource.GetDefaultView(Classes); _classesCollectionView.Filter = FilterClasses; OnPropertyChanged(() => ClassesCollectionView); } public bool FilterClasses(object o) { var clas = o as NdfClassViewModel; // return true if object should be in list with applied filter, return flase if not } You wanna use the "ClassesCollectionView" as your ItemsSource for your Combobox
unknown
d768
train
I have done several projects involving scraping websites to obtain thousands of stock prices each day. The problem, as dano suggested, is related to your error handling: except Exception as e: return None This does nothing to handle failed requests. You can append the failed urls to a list, and at the end of your script run your "get" function again with those urls. If your information is critical, you can even define a function that tries at least 5-10 times to download the information of a stock before it returns None. More related to the multithreading question, you need to be careful with the number of requests per second/minute/hour and avoid exceeding the API/website rate limit. You can use multiple proxies for that. Hope it helps.
unknown
d769
train
Your Program class is defined as implementing the Runnable interface. It therefore must override and implement the run() method: public void run () { } Since your two Thread objects are using anonymous inner Runnable classes, you do not need and your should remove the implements Runnable from your Program class definition. public class Program { ... A: try this: class Program { public static void main(String[] args) { Thread thread1 = new Thread() { @Override public void run() { System.out.println("test1"); } }; Thread thread2 = new Thread() { @Override public void run() { System.out.println("test2"); } }; thread1.start(); thread2.start(); } Or you can create a separate class implementing Runnable and ovverriding method run(). Then in main method create an instance of Thread with you class object as argument : class SomeClass implements Runnable { @Override run(){ ... } } and in main: Thread thread = new Thread(new SomeClass()); A: When you implement an interface (such as Runnable) you must implement its methods, in this case run. Otherwise for your app to compile and run just erase the implements Runnable from your class declaration: public class Program { public void main (String[] args) { Thread thread1 = new Thread () { public void run () { System.out.println("test1"); } }; Thread thread2 = new Thread () { public void run () { System.out.println("test2"); } }; thread1.start(); thread2.start(); } }
unknown
d770
train
Using dynamically created progress bar or referencing it from an id, are both fine. Using a reference from XML allows you to have more control on the progress bars appearance, as you would have designed it sepcifically for your need (like appearance, where it has to appear, etc..). But if that is not the case, you can use a dynamically created one as in your current code as well. A: There is a lot of ways. One is to define ProgressDiaolog as a field in your AsyncTask, then add it to your onPreExecuted(): pDialog = new ProgressDialog(this); pDialog.setMessage("some downloading massage"); pDialog.setIndeterminate(false); pDialog.setMax(100); //you can adjust this pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); pDialog.setCancelable(false); pDialog.show(); Then you can update the progress by override updateProgress() in your AsyncTask and call pDialog.setProgress();
unknown
d771
train
I think you want to group the first "word" with the hyphen ^(\w+\-)*\w+$ This assumes that you want to match things like XX-XX XXX-X XX-XX-XX-XX-XX-XX-XX-XX XXX But not XX- XX--XX If there has to be a hyphen then this would work ^(\w+\-)+\w+$
unknown
d772
train
Instead of using .Copy to directly paste the values into the destination, you can use .PasteSpecial Paste:=xlPasteValues. I.e. something like .Range("e6").Copy StartSht.Cells(i + 1, 4).PasteSpecial Paste:=xlPasteValues for your first line. Or you can just set the cell equal to the range you're copying, as suggested in the comments on your question. .StartSht.Cells(i + 1, 4) = .Range("E6")
unknown
d773
train
The problem is most likely that request is not a valid json request. If that is the case then content will be equal to None which means it is not subscriptable.
unknown
d774
train
You can try : app.__vue__.$router.push({'name' : 'home'})
unknown
d775
train
I take no credit for this since I got every bit of it from going through multiple StackOverflow threads, but I got this working with: @interface MyViewController () - (IBAction) toggleSettingsInPopover: (id) sender; @property (nonatomic, strong) UIStoryboardPopoverSegue *settingsPopoverSegue; @end @implementation MyViewController @synthesize settingsPopoverSegue = _settingsPopoverSegue; - (IBAction) toggleSettingsInPopover: (id) sender { if( [self.settingsPopoverSegue.popoverController isPopoverVisible] ) { [self.settingsPopoverSegue.popoverController dismissPopoverAnimated: YES]; self.settingsPopoverSegue = nil; } else { [self performSegueWithIdentifier: @"Settings" sender: sender]; } } - (void) prepareForSegue: (UIStoryboardSegue *) segue sender: (id) sender { if( [segue.identifier isEqualToString: @"Settings"] ) { if( [segue isKindOfClass: [UIStoryboardPopoverSegue class]] ) self.settingsPopoverSegue = (UIStoryboardPopoverSegue *) segue; MySettingsViewController *msvc = segue.destinationViewController; msvc.delegate = self; } } @end In my storyboard I control-dragged from my settings bar button item to MyViewController and connected it to the toggleSettingsInPopover action. Then I control-dragged from MyViewController to the view for the settings to create the segue, set its type to popover, set its identifier to Settings, set its directions to up and left (the toolbar is at the bottom of the screen and the button is at the right end), then dragged from its Anchor to the bar button item I connected to the action. A: You have to anchor the segue to the UIBarButton by Ctrl-Dragging the Anchor Field from the segue Attribute Inspector to the UIBarButton. If you do it the opposite way, Ctrl-Dragging from the Button to the Window to be shown you won't have a possibility to control the behaviour from the Popoverwindow. (The important part is also in the last sentence of LavaSlider's Reply)
unknown
d776
train
So I feel your pain in refactoring all of your code. We went through the same thing with one of our apps at work and it was a pain. On the backside of it though, well worth it! The way ionic suggests you to organize your files is not sustainable. I have a couple thoughts and ideas for you based on going through the same thing that might help you out. First off, putting everything back in the same module is not the best idea, because then you end back where you started with the disorganized code as ionic would have you do it, rather than the organized code as Angular suggests. In general, Angular suggests some great patterns, and I think it's worth the struggle to get your code in line with their suggestions. Secondly, and this is the main point, are you using deep links in your app? If you are, there is a fantastic, barely documented feature you get with deeplinks to avoid circular dependency within pages. Suppose you have a page with the following deep link config: { component: MyCoolPage, // the page component class name: 'MyCoolPage', // I use the name of the class but can be any sting you want segment: 'cool-page' // optional, not related to the problem, // but it's probably best to use this field as well } Whenever you want to navigate to MyCoolPage, instead of doing navCtrl.push(MyCoolPage), you can now do navCtrl.push('MyCoolPage') // or whatever string name you gave the page. So now you're navigating to pages via string names, which eliminates the need for importing pages whenever you want to navigate to it. This feature has existed since ionic 2, although I did not realize you could do this until updating to ionic 3. Thirdly, more of a design consideration than anything else, you might want to reconsider navigating to pages from within components. Generally what we do is emit events up to the parent page components, and then have the page component handle pushing or popping the nav stack. Your BookListItemComponent shouldn't be causing you problems. If that is something in the shared module, used throughout the app, it shouldn't be depending on other modules. Your shared module shouldn't depend on anything else besides the ionic and angular modules you need to import.
unknown
d777
train
Simple way: You could call the CMD version of php from inside node and return the value via node. Hard way
unknown
d778
train
You can use the function getProfile() of the ICCProfile class. Usage: int profileId = ...; ICCProfile iccp = new ICCProfile(profileId, input); ICC_Profile icc_p = iccp.getProfile(); In accordance to the code at google result #1 for twelvemonkeys icc_profile. A: Found a solution. For this Twelvemonkeys package imageio-metadata is needed in version 3.4. Older version does not contain TIFFEntry class. /** * Extract ICC profile from an image file. * * @param file image file * @return ICC profile * @throws IOException on file errors */ protected ICC_Profile extractICCProfile(File file) throws IOException { ICC_Profile profile; try (ImageInputStream input = ImageIO.createImageInputStream(file)) { ImageReader reader = ImageIO.getImageReaders(input).next(); if (reader == null) { throw new IllegalArgumentException("No image reader for file: " + file); } try { reader.setInput(input); TIFFImageMetadata metadata = (TIFFImageMetadata) reader.getImageMetadata(0); TIFFEntry entry = (TIFFEntry) metadata.getTIFFField(TIFF.TAG_ICC_PROFILE); byte[] iccBytes = (byte[]) entry.getValue(); profile = ICC_Profile.getInstance(iccBytes); } finally { reader.dispose(); } } return profile; }
unknown
d779
train
When your working set (the amount of data read by all your processes) exceeds your available RAM, your throughput will tend towards the I/O capacity of your underlying disk. From your description of the workload, seek times will be more of a problem than data transfer rates. When your working set size stays below the amount of RAM you have, the OS will keep all data cached and won't need to go to the disk after having its caches filled.
unknown
d780
train
Similar kind of question is answered here You can achieve it using yaml aliases fr: activerecord: attributes: blog: &title_content title: Titre content: Contenu event: *title_content Refer yaml aliases for more info.
unknown
d781
train
Not in a "standards-based" way, no. The X-Windows system is independent of specific window managers, as such, there is no standard way to "maximize" a window. It ultimately depends on the features of the window manager in use...
unknown
d782
train
Both DAO and ActiveRecord are patterns to access data in a Database. DAO stands for "Data Acess Object". Following are the links to the relevant Wikipedia pages to read more about the individual patterns. * *ActiveRecord: http://en.wikipedia.org/wiki/Active_record_pattern *DAO: http://en.wikipedia.org/wiki/Data_access_object Note that the ruby gem activerecord is an implementation of the "Active Record" patterns, which happens to have the same name as the pattern.
unknown
d783
train
You can copy above code snippet as a service configuration to your services.yaml, which probably roughly looks like this: # app/config/services.yaml services: app.memcached_client: class: Memcached factory: 'Symfony\Component\Cache\Adapter\MemcachedAdapter::createConnection' arguments: [['memcached://my.server.com:11211', 'memcached://rmf:abcdef@localhost']] app.memcached_adapter: class: Symfony\Component\Cache\Adapter\MemcachedAdapter arguments: - '@app.memcached_client' Then in your configuration you should be able to reference the adapter using the client created by the factory, e.g. something like: # app/config/config.yaml framework: cache: app: app.memcached_adapter You might also be able to overwrite the default alias cache.adapter.memcached instead of having your own adapter. Your approach using Memcached::addServer might work as well, but just like with MemcachedAdapter::createConnection this will return the Client, which needs to be passed to the cache adapter. That's why there is a second service app.memcached_adapter, which is used in the cache configuration. Please be aware that I have not tested this, so this is rather a rough outline than a fully working solution, A: For one of my projects running Symfony 3.4 the configuration was simpler: Create a service that will be used as a client: app.memcached_client: class: Memcached factory: ['AppBundle\Services\Memcached', 'createConnection'] arguments: ['memcached://%memcache_ip%:%memcache_port%'] The AppBundle\Services\Memcached can have all the custom logic I need like so: class Memcached { public static function createConnection($dns) { $options = [ 'persistent_id' => 'some id' ]; // Some more custom logic. Maybe adding some custom options // For example for AWS Elasticache if (defined('Memcached::OPT_CLIENT_MODE') && defined('Memcached::DYNAMIC_CLIENT_MODE')) { $options['CLIENT_MODE'] = \Memcached::DYNAMIC_CLIENT_MODE; } return \Symfony\Component\Cache\Adapter\MemcachedAdapter::createConnection($dns, $options); } } And then I used that service in my config.yml: framework: cache: default_memcached_provider: app.memcached_client
unknown
d784
train
You can flatten the table before converting it to pandas: https://arrow.apache.org/docs/python/generated/pyarrow.Table.html#pyarrow.Table.flatten >>> table.flatten().to_pandas() a b.c b.d 0 [1, 2] True 1991-02-03 1 [3, 4, 5] False 2019-04-01 Then you can join on column b.d or b.c
unknown
d785
train
getDomain() needs to be added to the scope in the controller... $scope.getDomain = function(url) { // ... return domain; }; Then you can use it in your view... <td colspan="3" class="linkCol"> <a ng-href="{{ad.url}}" target="_blank" title="{{ad.url}}">{{ getDomain(ad.url) }}</a> </td>
unknown
d786
train
I have solved this problem. I have just modify the code and get sollution Here is my modified function function doPendingamt(val,cnt) { var req = Inint_AJAX(); req.onreadystatechange = function () { if (req.readyState==4) { if (req.status==200) { //document.getElementById('PENDING_AMT').value=""; //document.getElementById('PENDING_AMT').value=req.responseText; //retuen value $('input[name=PENDING_AMT['+cnt+']]').val(); $('input[name=PENDING_AMT['+cnt+']]').val(req.responseText); var elements = document.getElementsByClassName('purshasedocscss'); var totalAmt = 0; var pendingAmt = 0; var greater = 0; for(var x=0; x < elements.length; x++){ if(val == elements[x].value && elements[x].value != -1){ if(pendingAmtTmp > pendingAmt) { pendingAmt = pendingAmtTmp; } greater++; } } if(greater > 1) { for(var y=0; y < elements.length; y++){ if(val == elements[y].value && $('input[name=AMOUNT['+y+']]').val() != ''){ var amount = $('input[name=AMOUNT['+y+']]').val(); totalAmt = parseFloat(amount) + parseFloat(totalAmt); } } var amt = pendingAmt - totalAmt; $('input[name=PENDING_AMT['+cnt+']]').val(amt); } } } }; req.open("GET", "pendingamnt.php?val="+val); //make connection req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header req.send(null); //send value } Thank you who have give time for this issue.
unknown
d787
train
As they wrote here, htaccess works in all directories except cgi-bin. But, as you can see from here, there's a way around it. Basically, you edit the <Directory "C:/path/to/cgi-bin"> section of your httpd.conf file - and put there whatever would have been in the .htaccess file in cgi-bin. Remember to restart your apache after changes to httpd.conf One more tidbit: there's probably already a <Directory "/var/www/cgi-bin"> in your httpd.conf. Edit it - having duplicate sections causes gray hairs. The above worked for me for password protecting the cgi-bin directory, as using .htaccess in cgi-bin didn't work. Inserting it into the <Directory "C:/path/to/cgi-bin"> section of my httpd.conf file did work. It now says: <Directory "/var/www/cgi-bin"> AllowOverride None Options None Order allow,deny Allow from all AuthType Basic AuthName "Scripts" AuthUserFile /var/secret/.htpasswrd Require valid-user Satisfy All </Directory>
unknown
d788
train
You can try something like this: obj= eval(uneval(objSource)); It only works in FF but the idea is to serialize an object and the eval the serialized string instantiating (prototyping) a new object with the same properties as the first one. You can use also the function JSON.stringify as the "uneval" function.
unknown
d789
train
At the beginning of your script, you can use movieclipName._visible=false; Then you modify the same property to reverse that. A: Have you tried: on(load){ this._visible = false; }
unknown
d790
train
Delimiters! new Vue({ el: '#app', delimiters: ['[[', ']]'], data: { title: 'yadda yadda' } Apparently I had previously set them and stopped for whatever reason. (hence the inconsistency)
unknown
d791
train
At the time of writing this is a limitation in Serilog.Expressions, which will hopefully be addressed soon. Update: version 3.4.0-dev-* now on NuGet supports ToString(@l, 'u3'). You can work around it with conditionals: {'level': if @l = 'Information' then 'INF' else if @l = 'Warning' then 'WRN' else 'ERR'} With a few more branches for remaining levels. (Alternatively, you could write and plug in a user defined function along the lines of ToShortLevel(@l), and use that instead.)
unknown
d792
train
Just create a VIEW and SELECT from this VIEW to get what you're looking for.
unknown
d793
train
First, try not to use subqueries at all, they're very slow in MySQL. Second, a subquery wouldn't even help here. This is a regular join (no, Mr Singh, not an inner join): SELECT ud_id FROM user, mycatch WHERE catch_id>'$catch_id' AND user.user_id = mycatch.user_id A: Select m.longitude,m.latitude from user u left join mycatch m on u.user_id =m.user_id where u.ud_id=$ud_id and m.catch_id >$catch_id
unknown
d794
train
You can wrap each job into a coroutine that checks its timeout, e.g. using asyncio.wait_for. Limiting the number of parallel invocations could be done in the same coroutine using an asyncio.Semaphore. With those two combined, you only need one call to wait() or even just gather(). For example (untested): # Run the job, limiting concurrency and time. This code could likely # be part of _run_job_coroutine, omitted from the question. async def _run_job_with_limits(job, sem, timeout): async with sem: try: await asyncio.wait_for(_run_job_coroutine(job), timeout) except asyncio.TimeoutError: # timed out and canceled, decide what you want to return pass async def _run_test_invocations_async(jobs, max_concurrency, timeout): sem = asyncio.Semaphore(max_concurrency) return await asyncio.gather( *(_run_job_with_limits(job, sem, timeout) for job in jobs) )
unknown
d795
train
viewDidLoad is a method invoked after view has been loaded from nib file. You are not supposed to call it manually. If you have written the code to refresh the controls in viewDidLoad move that into a different method and invoke that method from your button event handler. - (void)adjustControlsForLanguage { NSUserDefaults *sprakvalet = [NSUserDefaults standardUserDefaults]; sprakval2 = [sprakvalet integerForKey:@"Sprak "]; if (sprakval2==0) { spraklabel.text = [NSString stringWithFormat:@"Language:"]; [lhb setTitle:@"english" forState:UIControlStateNormal]; [hlb setTitle:@"english" forState:UIControlStateNormal]; [fhb setTitle:@"english." forState:UIControlStateNormal]; [blandatb setTitle:@"english.." forState:UIControlStateNormal]; UIImage *encheck = [UIImage imageNamed:@"United_Kingdomchecked.png"]; [enbutton setImage:encheck forState:UIControlStateNormal]; UIImage *seuncheck = [UIImage imageNamed:@"Sweden.png"]; [sebutton setImage:seuncheck forState:UIControlStateNormal]; self.title = @"Game"; } else if(sprakval2==1) { spraklabel.text = [NSString stringWithFormat:@"Språk:"]; [lhb setTitle:@"swedish" forState:UIControlStateNormal]; [hlb setTitle:@"swedish" forState:UIControlStateNormal]; [flb setTitle:@"swedish" forState:UIControlStateNormal]; [fhb setTitle:@"swedish" forState:UIControlStateNormal]; [blandatb setTitle:@"swedish" forState:UIControlStateNormal]; self.title = @"Spel"; UIImage *secheck = [UIImage imageNamed:@"Swedenchecked.png"]; [sebutton setImage:secheck forState:UIControlStateNormal]; UIImage *enuncheck = [UIImage imageNamed:@"United_Kingdom.png"]; [enbutton setImage:enuncheck forState:UIControlStateNormal]; } } viewDidLoad - (void)viewDidLoad{ [super viewDidLoad]; [self adjustControlsForLanguage]; } Button Event Handlers -(IBAction) sprakEN { sprakval=0; NSUserDefaults *sprakvalet = [NSUserDefaults standardUserDefaults]; [sprakvalet setInteger:sprakval forKey:@"Sprak "]; [sprakvalet synchronize]; [self adjustControlsForLanguage]; } -(IBAction) sprakSE { sprakval=1; NSUserDefaults *sprakvalet = [NSUserDefaults standardUserDefaults]; [sprakvalet setInteger:sprakval forKey:@"Sprak "]; [sprakvalet synchronize]; [self adjustControlsForLanguage]; } EDIT : Since you are using tabBar based app, it's better to use the viewWillAppear to reload the language specific controls - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self adjustControlsForLanguage]; } - (void)viewDidLoad { [super viewDidLoad]; } A: This is because you are calling ViewDidload method through its super class in -(IBAction) sprakSE and -(IBAction) sprakEN methods. So replace [super viewDidLoad]; with [self viewDidLoad]; in both methods. It will work properly. Hope it helps you.
unknown
d796
train
To clarify, that's not a button, it's an anchor. You can add a server side event by adding runat=server and an event handler for the OnServerClick event. <a id="EnterToImagesLink" name="EnterToImagesLink" class="EnterLink" runat="server" OnServerClick="MyClickEvent"> </a> A: you can replace the anchor element "a" with ASP.NET control LinkButton control, it will produce the same type of HTML element (anchor/"a") and it provides you with Click event as well (server side). <asp:LinkButton ID="myLinkButton" runat="server" CssClass="EnterLink" Text="My LinkButton" OnClick="OnServerClickMethod" />
unknown
d797
train
I would recommend to design your API as a service loadable with ServiceLoader, similar to DOM API. Thus, your API will be loadable as: Entry entry = ServiceLoader.load(Entry.class).next(); And it will be easy to have many implementations of the same API.
unknown
d798
train
You wrote s in your regular expression instead of \s (meaning whitespace). If you want to enforce that there is exactly one space character (not multiple spaces and not tabs or other whitespace characters) then you can use this: /^[0-9A-Za-z]{1,10}(?: [0-9A-Za-z]{1,10})*$/ If you also want to allow underscores, you can use \w to make the expression more concise: /^\w{1,10}(?: \w{1,10})*$/ A: Try regexp like this if you don't expact space at begin and spaces should be longer than 1 character var regex = /^([0-9a-zA-Zs]+\s*)*$/; With possible space at begin you can use var regex = /^\s*([0-9a-zA-Zs]+\s*)*$/; If you expact exactly one space and no spaces at begin or end then use var regex = /^([0-9a-zA-Zs]+\s)*[0-9a-zA-Zs]+$/;
unknown
d799
train
This looks similar to the example shown here: https://wiki.eclipse.org/EclipseLink/Examples/JPA/nonJDBCArgsToStoredProcedures#Handling_IN_and_OUT_arguments The difference is you are using a DataModifyQuery which is designed around JDBC's executeUpdate to execute the query, and so returns an int instead of a resultset. You will want to use a DataReadQuery to obtain results.
unknown
d800
train
Are you running in development or production mode? SHOW FIELDS FROM foo is done by your model, as you noted, so it knows which accessor methods to generate. In development mode, this is done every request so you don't need to reload your webserver so often, but in production mode this information should be cached, even if you're running a three year old version of Rails. A: This is called by ActiveRecord reading the attributes of a model from your database. It won't happen multiple times in production, but in development mode, Rails queries the table each time to pick up on any changes that may have occurred. A: If you have this kind of problem again and need to track down how a query is being called I would suggest the Query Trace plugin: http://github.com/ntalbott/query_trace/tree/master. It adds a stack trace to the log for every SQL query. Very handy. A: This line actually comes from calling the model, i had an array in the application controller that looked like [Model1, Model2, Model3] and I changed it to look like ['Model1','Model2', 'Model3'] and that fixed all the extra calls.
unknown