_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d9301
train
If you only need to create the missing files, and not get a list of the files that were missing you can you the touch task, which will create if the files don't exist. <Touch Files="@(MyInteropLibs)" AlwaysCreate="True" /> If you only want to create the missing files, and avoid changing timestamps of the existing files, then batching can help <Touch Files="%(MyInteropLibs.FullPath)" AlwaysCreate="True" Condition=" ! Exists(%(MyInteropLibs.FullPath)) "/> If you want a list of the files created then <Touch Files="%(MyInteropLibs.FullPath)" AlwaysCreate="True" Condition=" ! Exists(%(MyInteropLibs.FullPath)) "> <Output TaskParameter="TouchedFiles" ItemName="CreatedFiles"/> </Touch> <Message Text="Created files = @(CreatedFiles)"/> A: I am not very experienced with MSBuild so there may be better solutions than this but you could write a FilesExist task that takes the file list and passes each file to File.Exists returning true if they do exist and false otherwise and thenn react based on the result Sorry I can't provide code to help out, my knowlege of MSBuild sytax is not strong A: You can find out pretty easily using Exec. To test if ALL of a set of files exists: The DOS FOR /D command accepts a semicolon-separated list of files - i.e. a flattened item array. <!-- All exist --> <Exec Command="for /D %%i in (@(MyFiles)) do if not exist %%i exit 1" IgnoreExitCode="true"> <Output TaskParameter="ExitCode" PropertyName="ExistExitCode"/> </Exec> To test if ANY of a set of files exists: The DOS DIR command accepts a semicolon-separated list of files. It sets the %ERRORLEVEL% to 0 if it finds any files in the list, nonzero if it finds none. (This is the simpler case, but it does not address the original question...) <!-- Any exists --> <Exec Command="dir /B @(MyFiles)" IgnoreExitCode="true"> <Output TaskParameter="ExitCode" PropertyName="DirExitCode"/> </Exec> Then most likely you will want to define a boolean property based on the output. EDIT: BTW this is a code smell. Usually when you find yourself wanting to do this, it's an indication that you should set the Outputs property of the target so it will loop over the items.
unknown
d9302
train
You could add a color attribut to span.caption-text? For example in your source/_static/custom.cssput: @import url("default.css"); span.caption-text { color: red; } A: @aflp91 will indeed change caption text in the side bar, but also the caption text in the toctree as well. If you want the caption color to change in side bar - and side bar only - you should add this .wy-menu > .caption > span.caption-text { color: #ffffff; }
unknown
d9303
train
I guess problem in below statement Toast.makeText(getApplicationContext(), " 0 selected", Toast.LENGTH_LONG).show(); change to Toast.makeText(this, " 0 selected", Toast.LENGTH_LONG).show(); or Toast.makeText(tp.this, " 0 selected", Toast.LENGTH_LONG).show(); Edit:-------------------------------------------------------------------------- public class Tp extends Activity implements OnItemSelectedListener{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tp); String[] technology = {"PHP", "Ruby", "Java", "SQL"}; ArrayAdapter<String> adp = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, technology); final Spinner spinnertech = (Spinner) findViewById(R.id.spinner); spinnertech.setAdapter(adp); spinnertech.setOnItemSelectedListener(this); } if this is not working then include listview in xml file. A: This is your problem java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list' If you are using ListActivity, your layout file R.layout.activity_tp must have a ListView with android:id="@android:id/list" attribute. Look here: http://developer.android.com/reference/android/app/ListActivity.html for example.
unknown
d9304
train
after poking around some more and trying things on my own, I found a "solution" that kind of works: <!--#exec cmd="printf $(($page * $slidesPerPage + 1))" --> This just prints the output to page and doesn't store it in a variable, but it's enough for me right now. If someone has a better/nicer solution, please let me know.
unknown
d9305
train
You can simply call .to_i on a DateTime object: timestamp = DateTime.now.to_i # => 1501617998 DateTime.strptime(timestamp.to_s, '%s') # => Tue, 01 Aug 2017 20:07:10 +0000 The timestamp is the seconds since Epoch. Multiply it by a thousand and you get milliseconds. In your case, you must make a hook for this case: attr_values = attributes.map do |attr| attr_value = value.send(attr) attr_value = attr_value.to_i * 1000 if attr_value.is_a?(DateTime) attr_value end csv << attr_values This means everytime an attribute returns a DateTime object, it will be converted to a timestamp * 1000. If you want to filter only few attrs to convert DateTime -> Timestamp, test the attr with a whitelist instead of testing attr_value's class.
unknown
d9306
train
Yes, there is another way : you can install an event-filter on the QMdiSubWindow you create : MdiSubWindowEventFilter * p_mdiSubWindowEventFilter; ... QMdiSubWindow * subWindow = mdiArea->addSubWindow(pEmbeddedWidget); subWindow->installEventFilter(p_mdiSubWindowEventFilter); subWindow->setAttribute(Qt::WA_DeleteOnClose, true); // not mandatory, depends if you manage subWindows lifetime with bool MdiSubWindowEventFilter::eventFilter(QObject * obj, QEvent * e) { switch (e->type()) { case QEvent::Close: { QMdiSubWindow * subWindow = dynamic_cast<QMdiSubWindow*>(obj); Q_ASSERT (subWindow != NULL); // // do what you want here // break; } default: qt_noop(); } return QObject::eventFilter(obj, e); } A: I had the same trouble, but in my case the task was more specific: "How to hide a subwindow when I press the close button instead of closing". So I solved this with the following: subwindow->setAttribute(Qt::WA_DeleteOnClose, false); Perhaps it's not a relevant answer but it may be useful for someone. A: I don't think there is any other way than as you describe (overriding the close event) to do precisely what you're asking. There might be other ways of achieving what you want without doing that depending on why you want to know when its closed. Other options could be the use of the destroyed signal, checking QApplication::focusWidget(), or perhaps having the parent inspect its children. Edit in response to comment: Signals and slots are disconnected automatically upon destruction of QObjects, and I would suggest looking at using QSharedPointers or QScopedPointers to handle your QObjects' lifespans instead. By applying these techniques, you shouldn't need a signal from a closed window. A: Here is what I ended coding. #ifndef __MYSUBWINDOW_H #define __MYSUBWINDOW_H #include <QMdiSubWindow> #include <QCloseEvent> #include <QDebug> class MyQMdiSubWindow : public QMdiSubWindow { Q_OBJECT signals: void closed( const QString ); protected: void closeEvent( QCloseEvent * closeEvent ) { emit closed( this->objectName() ); closeEvent->accept(); } }; #endif Note that for my problem I need a way to identify which subwindow user is closing, and objectName does the work for me. A: You can create QWidget based class like: class CloseWatcher : public QWidget { Q_OBJECT private: QString m_name; signals: void disposing( QString name ); public CloseWatcher( QWidget * p ) : QWidget( p ) , m_name( p->objectName() ) {} ~CloseWatcher() { emit disposing( m_name ); } }; and just use it: // anywhere in code QMdiSubWindow * wnd = getSomeWnd(); CloseWatcher * watcher = new CloseWatcher( wnd ); connect( watcher, SIGNAL( disposing( QString ) ), reveiver, SLOT( onDispose( QString ) ) );
unknown
d9307
train
I fixed this issue with a directive import { OnInit, Directive, EventEmitter, Output } from '@angular/core'; import { MatSelect } from '@angular/material/select'; @Directive({ selector: '[athMatOptionDirective]' }) export class MatOptionDirective implements OnInit { @Output() matOptionState: EventEmitter<any> = new EventEmitter(); constructor(private matSelect: MatSelect) { } ngOnInit() { this.matSelect.openedChange.subscribe(isOpen => { if(isOpen) return this.matOptionState.emit(true) return this.matOptionState.emit(false) }) } } in your html component: <mat-form-field> <mat-select athMatOptionDirective (matOptionState)="getMatOptionState(event)"> </mat-select> </mat-form-field typescript component: getMatOptionState(event) { console.log('is mat-option open?', event) } Many thanks to Juri Strumpflohner (https://juristr.com/blog/2020/06/access-material-select-options) example here: stackblitz
unknown
d9308
train
Match works on 1 row or column. You are using 3 - B,C and D. Rewrite the first formula like this: Sub TestMe() Debug.Print WorksheetFunction.match("TestValue", Range("B:B"), 0) End Sub
unknown
d9309
train
Your first snippet is how you respond to incoming text messages with XML or TwiML (one thing) from twilio.twiml.messaging_response import MessagingResponse while your second snippet is how you send text messages via REST API (another thing) from twilio.rest import Client Looking at your first snippet, if you're responding with an empty string to incoming text messages, you will not get a text back (Twilio will not do anything), as such: instead of return "" try return str(resp) and make sure msg is not empty.
unknown
d9310
train
Since you've tagged this sungridengine I'll assume that's what you are using. Explicitly requesting by name a node that is currently empty doesn't guarantee that nobody will submit a job later that will be assigned to the same host. To achieve this the admin needs to create an exclusive resource and associate it with each execution host. You can then request said resource to get the whole node.
unknown
d9311
train
There are a couple of things you can do in a transition period. * *Add the @deprecated JSDoc flag. *Add a console warning message that indicates that the function is deprecated. A sample: /** * @deprecated Since version 1.0. Will be deleted in version 3.0. Use bar instead. */ function foo() { console.warn("Calling deprecated function!"); bar(); } A: Here's what we've found for Visual Studio 2013 : http://msdn.microsoft.com/en-us/library/vstudio/dn387587.aspx It's not tested yet as we haven't made the switch, but it looks promising. In the meantime, I am inserting a flag at page load depending on context such as : <% #if DEBUG Response.Write("<script type=\"text/javascript\"> Flags.Debug = true; </script>"); #endif %> and then I call a method that throws an error if the flag is true, or redirect to the new call if it is in release configuration. A: function obsolete(oldFunc, newFunc) { const wrapper = function() { console.warn(`WARNING! Obsolete function called. Function ${oldFunc.name} has been deprecated, please use the new ${newFunc.name} function instead!`) newFunc.apply(this, arguments) } wrapper.prototype = newFunc.prototype return wrapper }
unknown
d9312
train
You can use < input type='hidden' name='data' value="<?php echo $data[text]; ?>" > in the form Finally, you can put this block to remove. if(isset($_POST['submit']) { $query = "delete from info where text = '$_POST[data]'"; //run the query here } A: What is it that you want particularly? Do you mean you want the application to get check box elements and store them in the database. Then get that data and apply to each a delete command? be specific my friend and we can help.
unknown
d9313
train
You are currently searching for documents that match current query, but not filtering the data inside of documents, particulary notes array. You have to add filter on the next aggregation operation const query = "asdf"; db.collection.aggregate([ { $search: { index: "Journal-search-index", text: { query: query, path: "content", }, }, }, { $project: { notes: { $filter: { input: "$notes", as: "note", cond: { $regexMatch: { input: "$$note", regex: query, options: "i", }, }, }, }, }, }, ]); Playground Example
unknown
d9314
train
* *You aren't subscribing the observable and trying to compare an observable to a string. When you compare if (res === "False" || res === null), res variable is still an observable. *Having nested subscriptions isn't a good practice. And it won't help you here if you wish to make each request sequentially until one request emits False or if null. You could try create an array of requests and subscribe to it sequentially using RxJS from function and concatMap operator. Then break the sequence using the takeUntil operator if the condition is satisfied. Try the following import { Subject, from, of } from 'rxjs'; import { takeUntil, concatMap } from 'rxjs/operators'; private getData() { let closeRequest$ = new Subject<any>(); let response = Observable<responseService>; let requests = Observable<responseService>[]; for (let i =0; i < lin.length; i++) { requests.push(this.http.post<responseService>(this.Url, {}, options)) // <-- don't map response here } from(requests).pipe( concatMap(request => of(request)), takeUntil(closeRequest$) ).subscribe( response => { if (!response['status'] && response['status'] === "False") { // <-- check for `response.status` truthiness // response is false this.someVar = { status: "FALSE", message: "ERROR" }; this.closeRequest$.next(); this.closeRequest$.complete(); } else { this.someVar = status; } }, error => { } ); }
unknown
d9315
train
When you write the cookie to the browser, you need to specify an expiration date or a max age. However, note that max-age is ignored by Interent Explorer 8 and below. So if you're expecting to get usage from that browser, you can just rely on expires. Example: <script type="text/javascript"> function setMyCookie() { var now = new Date(); var expires = new Date(now.setTime(now.getTime() + 60 * 60 * 1000)); //Expire in one hour document.cookie = 'n=1;path=/;expires='+expires.toGMTString()+';'; } </script> And your button can call this function like so: <input type="button" onclick="setMyCookie();">Set Cookie</input> Note that I've also included the path to indicate that this cookie is site-wide. You can read more about expiring cookies with the date or max-age here: http://mrcoles.com/blog/cookies-max-age-vs-expires/ A: You can do: onClick="setupCookie();" function setupCookie() { document.cookie = "n=1"; setTimeout(function() { document.cookie = "n=0"; }, 3600000); // 1 hour } A: On click you can call some javascript function and while creating cookie itself you can set expire time please refer this javascript set cookie with expire time
unknown
d9316
train
You created a type called userdata so now you need to declare an instance of the type to use it: userdata u; then you pass the address of the instance: scanf("%c", &u.name); A: By using the typedef keyword, you've declared userdata as a type alias for a struct. It's not a variable name. If you remove the typedef keyword, you'll declare a variable with that name. Also, you need to use the %s format specifier to read and write strings. The %c format specifier is used for single characters. Also, since strings are terminated by a null byte, the age member of your struct should be longer. A: You are trying to assign a value to a TYPE, not a variable. When you define typedef, you do not create a variable, you create an alias for the type. Let's say you have the int type, but you don't like it being called int. Then you can do typedef and name the type int as you want: typedef int MyType; // Create an alias for an int type You do NOT create a variable of this type. Your solution is to create a variable of userdata and set it to: userdata data; scanf("%s", &data.name); In addition, as @dbush rightly noted, you need to use the %s specifier to read strings: the %c specifier is used only for single characters.
unknown
d9317
train
Thanks to @Miguel's response I realized that I forgot to monkey patch the standard library and that seem to have done the trick! from gevent import monkey monkey.patch_all()
unknown
d9318
train
Yep, this is how I've done it a few times as well. You need separate routing rules to use getCurrentRouteName(). The problem you have with the links is that you cannot pass the "module" parameter in this way. It's not a valid parameter for the Symfony link_to() helper. Instead, you can pass it this way: link_to('Customers', '@customer_index?url_variable=something'); customer_index: url: /:url_variable param: { module: customer, action: index, url_variable: some_default_value } The default value is optional, but the link_to helper will throw an error if you don't pass the variable and the route doesn't have a default value for it. Also, just pointing this out as you've got it twice wrong in your code above: $this>getContext()->getRouting()->getCurrentRouteName(); ...should be: $this->getContext()->getRouting()->getCurrentRouteName();
unknown
d9319
train
It sounds like the printer is not configured to understand ZPL. Look at this article to see how to change the printer from line-print mode (where it simply prints the data it receives) to ZPL mode (where it understands ZPL commands). Command not being understood by Zebra iMZ320 Basically, you may need to send this command: ! U1 setvar "device.languages" "zpl" Notice that you need to include a newline character (or carriage return) at the end of this command. A: zebra 0.0.3a is for EPL2, Not for ZPL2 !!!! See the site : https://pypi.python.org/pypi/zebra/
unknown
d9320
train
I think you can change the asset_host field : http://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html#M001688
unknown
d9321
train
The approach you're taking to your rule structure won't work. Firebase security rules cascade, meaning that a permission given to any node will apply to any of its children and on down the tree. You cannot grant read or write access on a node and then revoke it further down. (But you can grant permissions not granted above.) See the docs on rule cascading. In your case, you want to have some user data that be can written to by anyone and some that cannot. It's not clear from your example whether you want NoWrite to be written only by the authenticated user, or by nobody. Depending on how you will be reading this data, you will need to either separate these data into different collections, or make $uid inaccessible and define your rules only for ForEveryone and NoWrite. The first approach might look like this: "rules": { "users-public": { "$uid": { ".read": "true", ".write": "true", }, "users-nowrite": { "$uid": { ".read": "true", ".write": "$uid === auth.uid" } } Or the second, like this: "rules": { "users": { "$uid": { "ForEveryone": { ".read": "true", ".write": "true" }, "NoWrite" : { ".read": "true", ".write": "$uid === auth.uid" } } } As to your syntax error, you need a comma , after the closing brace before "NoWrite". A: Here are your rules, properly spaced so you can see the relationship between the parent nodes and child nodes. It seems this is not what you want. So this isn't really an answer but will lead to a better question that we can answer. Will update once we know what the OP is after. { "rules": { "users": { "$uid": { ".read": "$uid === auth.uid", ".write": "$uid === auth.uid", "ForEveryone": { ".read": true, ".write": true }, "NoWrite" : { ".read": true, ".write": false } } //end uid } //end users } //end rules } //outside closure
unknown
d9322
train
There is developer documentation available here: * *Executing Code in the Background *Playing Background Audio *Audio Session Programming Guide A: I had solved this question by referring iOS Application Background tasks and make some changes in .plist file of our application.. Happy coding...
unknown
d9323
train
github wiki / gollum-wiki doesn't inherently provide anything explicit for organizing pages into sub-directories. Any page can be linked from any other page irrespective of where it logically belongs. This is a powerful feature that makes wikis very flexible. One way to implement a sub-directories structure would be to follow a naming convention. Example: Having all pages related to subject1 have names that start with subject1, and so on.
unknown
d9324
train
As Scott Craner commented (please accept his answer, if he writes one): SUMPRODUCT((B1:B5="FC")*(C1:C5*C2:C6)) This approach uses array references, multiplies them together, and then takes the SUMPRODUCT of the results. Working out from the second set of nested terms: * *C1:C5 returns the array [100,5,120,3,26] *C2:C6 (offset by one row) returns [5,120,3,26,7] Multiplying these arrays gives the intermediate array: * *[500,600,360,78,182] Which is each number in column C multiplied by the one after it. However only every other result (indicated by the value "FC" in column B) is to be included in the final sum. This is accomplished using the other nested term, which tests the value of each cell of the specified range in order: * *B1:B5="FC" returns the array [TRUE,FALSE,TRUE,FALSE,TRUE] Excel treats TRUE/FALSE values as 1/0 when multiplying (though not for addition/subtraction), so the SUMPRODUCT function sees: * *[1,0,1,0,1]*[500,600,360,78,182] => [500,0,360,0,182] and then adds the values of the resulting products: * *500 + 0 + 360 + 0 + 182 = 1042 A: For this specific example. {=SUM((IF(B1:B6="FC",C1:C6,0)*IF(B2:B7="ST",C2:C7,0)))} This will only work if FC and ST alternate just like in the example. If it does not, you could quickly change it to fit this format by sorting column A primarily and column B secondarily. Notice the array in the second if statement is offset by one cell. This allows the arrays to multiply in the manner desired. Also, since it is an array formula, make sure you use CTRL+SHIFT+Enter when you put it in its cell.
unknown
d9325
train
Using Get-MailboxJunkEmailConfiguration -Identity BSmith | Get-Memeber shows that the TrustedSendersAndDomains property is a multiValuedProperty string, i.e. an Array. You can try changing the value of the $_.approved_senders into an array with -Split $existingconfig = get-mailboxjunkemailconfiguration $_.address $existingconfig.trustedsendersanddomains += ($_.approved_senders -Split ",")
unknown
d9326
train
Finally I figured out the problem . The problem was there in constructing adapter twice . Now I've removed the next adapter construction and the setAdapter() as well and it's working without any errors. Previous Code: private List<TImelineDataList> timelineDatalist; @Override public void onViewCreated(@NonNull View v, @Nullable Bundle savedInstanceState) { timelineDataList= new ArrayList<>(); **adapter=new CustomRecyclerViewAdapter(timelineDataList);**//Here recyclerView.setItemViewCacheSize(30); recyclerView.setDrawingCacheEnabled(true); recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH); recyclerView.setLayoutManager(new LinearLayoutManager(ctx,LinearLayoutManager.HORIZONTAL,false)); recyclerView.setAdapter(adapter); } void addTimelineData(String email,String time,String img_link,String caption){ timelineDataList.add(new TimelineData(email,time,img_link,caption)); **adapter=new CustomRecyclerViewAdapter(timelineDataList);**//Here adapter.notifyDataSetChanged(); recyclerView.setAdapter(adapter); } private Emitter.Listener handlePosts = new Emitter.Listener(){ @Override public void call(final Object... args){ try { JSONArray jsonArray=(JSONArray)args[0]; for(int i=0;i<jsonArray.length();i++){ try { JSONObject ob=jsonArray.getJSONObject(i); demo_email=ob.getString("_pid"); demo_time=ob.getString("time"); demo_link=ob.getString("img_link"); demo_caption=ob.getString("caption"); addTimelineData(demo_email,demo_time,demo_link,demo_caption); } catch (JSONException e) { e.printStackTrace(); } } } catch (Exception e) { Log.e("error",e.toString()); } } }; New Code: private List<TImelineDataList> timelineDatalist= new ArrayList<>();; @Override public void onViewCreated(@NonNull View v, @Nullable Bundle savedInstanceState) { adapter=new CustomRecyclerViewAdapter(timelineDataList); recyclerView.setItemViewCacheSize(30); recyclerView.setDrawingCacheEnabled(true); recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH); recyclerView.setLayoutManager(new LinearLayoutManager(ctx,LinearLayoutManager.HORIZONTAL,false)); recyclerView.setAdapter(adapter); } void addTimelineData(String email,String time,String img_link,String caption){ timelineDataList.add(new TimelineData(email,time,img_link,caption)); adapter.notifyDataSetChanged(): } private Emitter.Listener handlePosts = new Emitter.Listener(){ @Override public void call(final Object... args){ try { JSONArray jsonArray=(JSONArray)args[0]; for(int i=0;i<jsonArray.length();i++){ try { JSONObject ob=jsonArray.getJSONObject(i); demo_email=ob.getString("_pid"); demo_time=ob.getString("time"); demo_link=ob.getString("img_link"); demo_caption=ob.getString("caption"); addTimelineData(demo_email,demo_time,demo_link,demo_caption); } catch (JSONException e) { e.printStackTrace(); } } } catch (Exception e) { Log.e("error",e.toString()); } } }; A: Call adapter.notifyDataSetChanged() method to update RecyclerView adapter after adding data into arraylist which is attached to adapter. You can also call method notifyItemInserted(index) which can show item added with animation effect. A: The proper way is to call notifyDataSetChanged on the adapter or other methods from that family. The problem with setting adapter will be that your scroll position will be lost. It looks like the problem is in your CustomRecyclerViewAdapter. Good practice is to move timelineDatalist into the CustomRecyclerViewAdapter and have something like: void addTimelineData(String email,String time,String img_link,String caption){ adapter.addToTimelineDataList(new TimelineData(email,time,img_link,caption)); adapter.notifyDataSetChanged(); } Please post your CustomRecyclerViewAdapter for more details. A: I think its usual to use setAdapter multiple times as it won't create any issues in functionality. But if you want to use notifyDataSetChanged() then try not to reinitialize your data while receiving the data if you perform yourData = newData then this will reinitialize your old data and notifyDataSetChanged() will not work on that if its string then try concatenating in the current instance. A: make some change in method like below code .. void addTimelineData (String email, String time, String img_link, String caption){ timelineDataList.clear() timelineDataList.add(new TimelineData(email, time, img_link, caption)); setAdapter(); } and make one setAdapter method like.. public void setAdapter(){ if (adpter==null){ if(!timelineDataList.isEmpty()){ adapter = new CustomRecyclerViewAdapter(timelineDataList); } } else{ adapter.notifyDataSetChanged(); } } and remove the code onCreate() define recyclerView.setAdapter(adapter);
unknown
d9327
train
The InProcess transport is what you want. It is a full-fledged transport, but uses method calls and some tricks to avoid message serialization. It is ideally suited to testing, but is also production-worthy. When used with directExecutor(), tests can be deterministic. InProcess transport is used in the examples. See HelloWorldServerTest for one usage. private static Server server; private static Channel channel; @BeforeAll @SneakyThrows static void setupServer() { // This code, except for the server.start(), // could be moved to the declarations above. server = InProcessServerBuilder.forName("test-name") .directExecutor() .addService(new MySystemImpl()) .build() .start(); channel = InProcessChannelBuilder.forName("test-name") .directExecutor() .build(); } @AfterAll @SneakyThrows static void teardownServer() { server.shutdownNow(); channel.shutdownNow(); // Useful if you are worried about test // code continuing to run after the test is // considered complete. For a static usage, // probably not necessary. server.awaitTermination(1, SECONDS); channel.awaitTermination(1, SECONDS); }
unknown
d9328
train
You were very close to something that would work, but the value for the augmentation of SliderPropsColorOverrides should just be true rather than PaletteColorOptions. In my example sandbox I have the following key pieces: createPalette.d.ts import "@mui/material/styles/createPalette"; declare module "@mui/material/styles/createPalette" { interface Palette { brown: PaletteColor; } interface PaletteOptions { brown: PaletteColorOptions; } } Slider.d.ts import "@mui/material/Slider"; declare module "@mui/material/Slider" { interface SliderPropsColorOverrides { brown: true; } } There was one other problem that I addressed in a rather ugly fashion. The Slider prop-types were still causing a runtime validation message for the color prop. I found comments in some open issues about color customization that mention this prop-types aspect and I suspect it will eventually be addressed by MUI, but it might not be addressed for a while. In my sandbox, I work around this by creating a SliderPropTypesOverride.ts file in which I copied MUI's SliderRoot.propTypes.ownerState and then modified the color portion to include "brown". This copying of the prop-types definitely isn't ideal from a maintenance standpoint, but at the moment I don't see another way to address the runtime warning in dev mode. Then this all gets used as follows: demo.tsx import React from "react"; import { createTheme, ThemeProvider } from "@mui/material/styles"; import "./SliderPropTypesOverride"; import Slider from "@mui/material/Slider"; const defaultTheme = createTheme(); const theme = createTheme({ palette: { brown: defaultTheme.palette.augmentColor({ color: { main: "#A52A2A" }, name: "brown" }) } }); export default function Demo() { return ( <ThemeProvider theme={theme}> <Slider color="brown" /> </ThemeProvider> ); } Related answers: * *Typescript Module augmentation is not working: Property 'main' does not exist on type 'PaletteColorOptions' *How to add custom colors name on Material UI with TypeScript? A: I would review the documentation on this. https://mui.com/customization/palette/ It doesn't seem that you're able to override the color of the component directly and instead (if you have one) need to create a global theme object with the appropriate declaration files in order to override the color. Also see this answer: Extending the color palette with TS
unknown
d9329
train
Have you tried setting the refreshControl to the corresponding property on your tableView instead of adding it as a subview? tableView.refreshControl = refreshControl That should do it. edit: If you support any iOS earlier than 10, you will not be able to add it to the tableView directly but will instead need to add it to your UITableViewController, assuming you are using one. self.refreshControl = refreshControl
unknown
d9330
train
You are close to a solution in using the ToolStripControlHost, but you will need to derive from that class as shown in the linked-to example. The frustrating thing with that example is that it does not decorate the derived class with the System.Windows.Forms.Design.ToolStripItemDesignerAvailabilityAttribute to make it available on the design surface. The following is a minimalist implementation to get a working example. You may need to override the automatic sizing to suit your needs/wants for the control. The implementation overrides the Text property to prevent designer from assigning invalid text to the underlying DateTimerPicker control. <System.Windows.Forms.Design.ToolStripItemDesignerAvailability( System.Windows.Forms.Design.ToolStripItemDesignerAvailability.ToolStrip _ Or System.Windows.Forms.Design.ToolStripItemDesignerAvailability.StatusStrip _ Or System.Windows.Forms.Design.ToolStripItemDesignerAvailability.MenuStrip)> _ Public Class TSDatePicker : Inherits ToolStripControlHost Public Sub New() MyBase.New(New System.Windows.Forms.DateTimePicker()) End Sub Public ReadOnly Property ExposedControl() As DateTimePicker Get Return CType(Control, DateTimePicker) End Get End Property <Browsable(False), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> Public Overrides Property Text As String Get Return ExposedControl.Text End Get Set(value As String) ' verify valid date Dim dt As DateTime If DateTime.TryParse(value, dt) Then ExposedControl.Text = value End If End Set End Property End Class A: Was going to add as a comment but I trust it justifies an answer. The only way I have succeeded in this is to add one at design time (to the form) and set Visible to False and use the menu item to set Visible to True (may also need to set the position and/or bring it to the front). You do need to manually handle setting Visible to False again.
unknown
d9331
train
Add to app/config/Routes.php: $routes->setTranslateURIDashes(true);
unknown
d9332
train
This line should look like this CustomPage.where(:id => @custom_page.last.id).first.update(:url => url) Since where returns ActiveRecord::Relation which is in form of a array so you need to fetch the object out of the array A: You could pass the id to update method like this CustomPage.update(@custom_page.last.id, :url => url) But in this particular case, you can do @custom_page.last.update_attribute(:url, url) Please note that these methods doesn't invoke validations. To do that, call @custom_page.last.update_attributes(:url => url)
unknown
d9333
train
Spinbox will accept an explicit list of values: Spinbox(values=(1, 10, 100, 1000)) Of course, you don't want to enumerate all the evens from 0 to 1000, use range, starting at 0 and with a step of 2: Spinbox(values=list(range(0, 1000+1, 2))).pack()
unknown
d9334
train
Try this $str = "(pron.: /ˌhjuˠˈlɒri/)"; $a = preg_replace('#\/(.*?)\/#','',$str); var_dump($a); And after this if you want to remove the pron.:, use str_replace. Output string(9) "(pron.: )" Codepad
unknown
d9335
train
It is really a slow and painfull process to convert a a existing theme to a react theme. CSS are not a issue, the issue are all the javascripts that pretends to manipulate the DOM directly. My advice is to search components that are replicas of the functionality already in the theme and then style it according to the css (adjustment will be necessary) of the original theme. If you want a reference on HOW wrap standard libraries in a react component, take a look at the official docs about the topic: https://reactjs.org/docs/integrating-with-other-libraries.html
unknown
d9336
train
I guess you should read specflow documentation about parallel test runs http://specflow.org/documentation/Parallel-Execution/ It's said: You may not be using the static context properties ScenarioContext.Current, FeatureContext.Current or ScenarioStepContext.Current. Actually your error is self-descriptive - you've created item in dictionary with key "siteTitle"
unknown
d9337
train
You can change the inside of the panel build variant. A: The latest AS3.0 canary 8 fixed this issue
unknown
d9338
train
So, it seems that is not actually possible to do this. I have found it by checking it in 2 different ways: * *If you try to create a function through the API explorer, you will need to fill the location where you want to run this, for example, projects/PROJECT_FOR_FUNCTION/locations/PREFERRED-LOCATION, and then, provide a request body, like this one: { "eventTrigger": { "resource": "projects/PROJECT_FOR_TOPIC/topics/YOUR_TOPIC", "eventType": "google.pubsub.topic.publish" }, "name": "projects/PROJECT_FOR_FUNCTION/locations/PREFERRED-LOCATION/functions/NAME_FOR_FUNTION } This will result in a 400 error code, with a message saying: { "field": "event_trigger.resource", "description": "Topic must be in the same project as function." } It will also say that you missed the source code, but, nonetheless, the API already shows that this is not possible. * *There is an already open issue in the Public Issue Tracker for this very same issue. Bear in mind that there is no ETA for it. I also tried to do this from gcloud, as you tried. I obviously had the same result. I then tried to remove the projects/project-a/topics/ bit from my command, but this creates a new topic in the same project that you create the function, so, it's not what you want.
unknown
d9339
train
This works fine for me. df = pd.DataFrame({'Ad_URL':['u1', 'u2', 'u3'], 'Title':['t1', 't2', 't3']}) def Ad_Link(df): return ('<a href="{}">{}</a>'.format(df['Ad_URL'],df['Title'])) df['Link'] = df[['Ad_URL','Title']].apply(lambda x:Ad_Link(x), axis=1) print(df) Output: Ad_URL Title Link 0 u1 t1 <a href="u1">t1</a> 1 u2 t2 <a href="u2">t2</a> 2 u3 t3 <a href="u3">t3</a> A: First your code working for me nice. But added multiple solutions with same output: df = pd.DataFrame({'Ad_URL':['u1', 'u2', 'u3'], 'Title':['t1', 't2', 't3']}) def Ad_Link(df): return ('<a href="{}">{}</a>'.format(df['Ad_URL'],df['Title'])) df['Link'] = df[['Ad_URL','Title']].apply(lambda x:Ad_Link(x), axis=1) #change variable in function to x def Ad_Link1(x): return ('<a href="{}">{}</a>'.format(x['Ad_URL'],x['Title'])) df['Link1'] = df[['Ad_URL','Title']].apply(lambda x:Ad_Link1(x), axis=1) #removed lambda function def Ad_Link2(x): return ('<a href="{}">{}</a>'.format(x['Ad_URL'],x['Title'])) df['Link2'] = df.apply(Ad_Link2, axis=1) #pass columns names to lambda function, changed function def Ad_Link3(url, link): return ('<a href="{}">{}</a>'.format(url, link)) df['Link3'] = df.apply(lambda x: Ad_Link3(x['Ad_URL'],x['Title']), axis=1) #only lambda function solution df['Link4'] = df.apply(lambda x: '<a href="{}">{}</a>'.format(x['Ad_URL'], x['Title']), axis=1) print (df) Ad_URL Title Link Link1 Link2 \ 0 u1 t1 <a href="u1">t1</a> <a href="u1">t1</a> <a href="u1">t1</a> 1 u2 t2 <a href="u2">t2</a> <a href="u2">t2</a> <a href="u2">t2</a> 2 u3 t3 <a href="u3">t3</a> <a href="u3">t3</a> <a href="u3">t3</a> Link3 Link4 0 <a href="u1">t1</a> <a href="u1">t1</a> 1 <a href="u2">t2</a> <a href="u2">t2</a> 2 <a href="u3">t3</a> <a href="u3">t3</a>
unknown
d9340
train
Found the solution for this issue. UIHostingController is in fact just a normal UIViewController (with some add-ons for SwiftUI). Which means everything which is available for a UIViewController is as well available for UIHostingController. So the solution for this is to set everything related to the navigation bar on UIHostingController and not in the wrapped SwiftUI View. let vc = UIHostingController(rootView: Content()) vc.title = "My custom title" Also all navigations buttons work much better if directly set on UIHostingController. A good alternative is also to directly derive from UIHostingController and implement custom needed behavior there. A: To force UIHostingController to set up its navigation item we can pre-render it in a separate window: let window = UIWindow(frame: .zero) window.rootViewController = UINavigationController(rootViewController: hostingController) window.isHidden = false window.layoutIfNeeded() The window could even be cached for pre-rendering other views.
unknown
d9341
train
Try the SQL order by option $get_status_mood=mysqli_query($con, "select id, name from category order by name asc"); A: You can sort it using array_column and array_multisort functions. $keys = array_column($array, 'name'); array_multisort($keys, SORT_ASC, $array); A: You can try it with usort this sort an array by values using a user-defined comparison function function cmp($a, $b) { return strcmp($a["name"], $b["name"]); } usort($vc_array, "cmp"); A: $a = array(); $a[] = array('id' => 1, 'name' => 'status_category_confide'); $a[] = array('id' => 2, 'name' => 'status_category_love'); $a[] = array('id' => 3, 'name' => 'status_category_household'); function cmp($x, $y) { if (strcmp($x['name'], $y['name']) == 0) { return 0; } return (strcmp($x['name'], $y['name']) < 0) ? -1 : 1; } usort($a, "cmp"); print_r($a);
unknown
d9342
train
function [ x, fs ] = generate1(N,m,A3) f1 = 100; f2 = 200; T = 1./f1; t = (0:(N*T/m):(N*T))'; %' wn = randn(length(t),1); %zero mean variance 1 x = 20.*sin(2.*pi.*f1.*t) + 30.*cos(2.*pi.*f2.*t) + A3.*wn; %[pks,locs] = findpeaks(x); %plot(x); fs = 1/(t(2)-t(1)); end and see absfft = abs(fft(y)); plot(fs/2*linspace(0,1,length(absfft)/2+1),2*absfft(1:end/2+1)) or plot(linspace(-fs/2,fs/2,length(absfft)),fftshift(absfft)) the x-axis in your plot is from 0 to fs/2 and then from -fs/2 to 0
unknown
d9343
train
A rolling object is iterable, which allows for a solution like this: # drop NAs and group by date into lists of values df_per_date = df.dropna().groupby('date').apply(lambda g: g.value.to_list()) # compute medians across windows ('sum' concatenates multiple lists into one list) medians = [np.median(window.agg(sum)) for window in df_per_date.rolling(5)] # result medians = pd.Series(index=df_per_date.index, data=medians) medians By the way, I loaded the data like this: # load the data df = pd.read_csv(pd.io.common.StringIO(""" 2019-01-07 NaN 2019-01-08 NaN 2019-01-08 0.02 2019-01-09 31.45 2019-01-10 NaN 2019-01-10 71.87 2019-01-10 90.18 2019-01-11 NaN 2019-01-12 12.67 2019-01-12 5.68 2019-01-12 11.23 2019-01-12 21.67 2019-01-12 14.77 2019-01-12 5.18 2019-01-13 14.38 2019-01-13 NaN 2019-01-13 71.13 2019-01-13 20.02 2019-01-13 103.10 2019-01-14 NaN 2019-01-15 32.48 2019-01-16 37.37 2019-01-16 31.05 2019-01-16 7.00 2019-01-17 NaN 2019-01-17 39.65 2019-01-18 23.68 2019-01-18 0.08 2019-01-18 41.35 2019-01-19 NaN 2019-01-19 45.85 2019-01-19 3.98 2019-01-19 4.60 2019-01-19 NaN 2019-01-19 NaN 2019-01-20 3.60 2019-01-20 5.03 2019-01-20 15.70 """.strip()), sep='\s+', names=['date', 'value'], parse_dates=['date']) A: If the data is not too long, cross merge can work: df['key'] = 1 df = df.reset_index() (df.merge(df, on='key', suffixes=['','_']) .loc[lambda x: x['index'].ge(x['index_']) & x['index'].sub(x['index_']).le('7D')] .groupby('index')['column_'].median() ) Output: index 2019-01-07 NaN 2019-01-08 0.020 2019-01-09 15.735 2019-01-10 51.660 2019-01-11 51.660 2019-01-12 13.720 2019-01-13 17.395 2019-01-14 17.395 2019-01-15 20.020 2019-01-16 21.670 2019-01-17 21.670 2019-01-18 20.845 2019-01-19 20.020 2019-01-20 21.850 Name: column_, dtype: float64
unknown
d9344
train
As per the documentation for FtpWebRequest: Multiple FtpWebRequests reuse existing connections, if possible. Admittedly that does not really tell you much but if you look at the documentation for the ConnectionGroupName property, it tells you that you can specify the same ConnectionGroupName for multiple requests in order to reuse the connection. Here is more information on managing connections in .NET. Alternatively, you should be able to use the WebClient class to issue multiple related FTP requests and although I can't say for sure, I would imagine that it would reuse the connection. Unlike FtpWebRequest which can only be used once, WebClient can be used to make multiple requests.
unknown
d9345
train
This link should have the information you need: http://codex.wordpress.org/Function_Reference/add_meta_box There's also a tutorial on this subject here: http://wptheming.com/2010/08/custom-metabox-for-post-type/ A: This post solved my problem: order posts by custom field I made a custom field instead (which suited this even better than a metabox) named "pub_year": <?php $loop = new WP_Query( array( 'post_type' => 'bocker', 'posts_per_page' => 10, 'product_category' => 'ex-jugoslaviskt', 'meta_key' => 'pub_year', 'orderby' => 'meta_value', 'order' => 'DESC' ) ); ?>
unknown
d9346
train
When working in VBA it pays to be specific rather than rely on objects such as ActiveDocument Sub Kopiera_Excel_Till_Word(FilVag As String) Selection.Copy Dim appWord As Word.Application Set appWord = New Word.Application Dim FilNamnVag As String Dim docWord As Word.Document Set docWord = appWord.Documents.Add docWord.Range.Paste Application.CutCopyMode = False docWord.SaveAs2 Filename:= _ FilVag, FileFormat:= _ wdFormatXMLDocument, LockComments:=False, Password:="", AddToRecentFiles _ :=True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts _ :=False, SaveNativePictureFormat:=False, SaveFormsData:=False, _ SaveAsAOCELetter:=False, CompatibilityMode:=15 docWord.Close SaveChanges:=False appWord.Quit Application.CutCopyMode = False End Sub
unknown
d9347
train
I managed for now to connect to the DB. <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "database"; // create conntection $conn = new mysqli($servername, $username, $password, $dbname); // check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT item_name FROM items"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "-".$row["item_name"]. "<br>"; } } $conn->close(); ?>
unknown
d9348
train
You could try use JSON web tokens instead https://www.red-gate.com/simple-talk/dotnet/net-development/jwt-authentication-microservices-net/ https://jwt.io/
unknown
d9349
train
It looks like the intention of your tag is to reduce the amount of boilerplate GSP code needed when rendering a form. Have you considered using the bean-fields plugin instead?
unknown
d9350
train
A relatively simple approach is a brute-force approach. This splits the periods into days for each class. Then joins and aggregates to get the total: with cte1(id, d, endd, class) as ( select id, startd, endd, class from table1 union all select id, d + interval '1' day, endd, class from cte1 where d < endd ), cte2(id, d, endd, class) as ( select id, startd, endd, class from table2 union all select id, d + interval '1' day, endd, class from cte2 -- edit here where d < endd ) select cte1.id, count(*) from cte1 join cte2 on cte1.id = cte2.id and cte1.d = cte2.d group by cte1.id; Here is a db<>fiddle.
unknown
d9351
train
I finally figured this out. The firebase config file should have had a .then and .catch for the promise. Once I added this, it works fine now. I researched 3 days to figure this out. Taking a course, and the guy who produced this course didn't add this, although it was two years ago maybe it wasn't required then, but it is now.
unknown
d9352
train
When jQuery creates the dialog box, it copies everything in the learning_activity_wisard_dialog div to a new DOM node, including the script tag. So, the tag runs once when the page loads, then again when the dialog is rendered. Move your script out of that div, or just use some bool to track whether it's already run or not. A: When you do $('#learning_activity_wizard_dialog').dialog(dialogOpts); it will run the script again. If you do not want this to happen, move that script tag out of the div that will later become a dialog. A: http://jsfiddle.net/uRhQT/ i guess this is your problem, adding script tag inside a html that will load again using jquery. The solution to this what you have only ... use the script outside the div. Reason: The script tag content is executed when defined inline. So When your dialogbox is shown, the contents are copied to the dialogbox which makes it new inline script. So it gets executed and another alert box is shown.
unknown
d9353
train
I think you need a query like this: SELECT `myDate` , MAX(CASE WHEN `item` = 'audit' THEN `amount` END) AS `audit` , MAX(CASE WHEN `item` = 'fs_delete' THEN `amount` END) AS `fs_delete` , MAX(CASE WHEN `item` = 'log_print' THEN `amount` END) AS `log_print` , MAX(CASE WHEN `item` = 'sys_error' THEN `amount` END) AS `sys_error` , MAX(CASE WHEN `item` = 'sys_info' THEN `amount` END) AS `sys_info` FROM `audit` GROUP BY `myDate`; [SQL Fiddle Demo]
unknown
d9354
train
So, I was wondering the exact same thing, and when I saw this question and its answer, I said "Screw it, I'm making one!" And so I did. Two days later, here's my answer to you: http://tustin2121.github.io/jsPlistor/ jsPListor (version 1 as of Aug 8th, 2013) will allow you to paste in the contents of an xml plist into it (via the Import button) and edit it with drag and drop and the like. When you're done, hit Export and it will package it all up into a valid plist for you to copy and paste back into the file. There's still some bugs and glaring vacancies (like the Data Editing Dialog), but it functions. Future versions will attempt to allow saving via html5 download, and loading of files into data rows. Feel free to examine, contribute, and submit bugs at the github repo: https://github.com/tustin2121/jsPlistor A: I have resigned myself to the fact that there probably isn't one I will ever find. What I have found, however, is that JSON format and text PList format are very similar, and there are plenty of JSON editors available online and for windows and mac both. It may not be suitable for your needs, but it suited my needs just fine. By using nothing more than a couple of find & replaces in Notepad you can get 90% of the way to a plist file. The only big issue is semicolons vs. commas. If you're working on a small enough file, that could be done manually. With larger files, a simple utility app to convert JSON to PList files would probably be pretty simple to whip up if you've got the urge. Again, this all applies only to text formatted plist files. Most plist editors on mac at least can save a plist in text format. A: There's Plistinator - its a native C++/Qt app for Mac, Windows and Linux desktop. So not an online tool, but it is at least portable and runs cross-platform (in case that is what the request for a web-based editor was about). I'm not sure if the JS version handles binary files (Plistinator does). If you have a Mac you could edit them via the JS editor if you convert binary to XML via plutil -convert xml myfile.plist Note that will over-write myfile.plist with the XML version, which may not represent all the same information that the binary version can. Full-disclosure: I am the author of Plistinator and the $12.99 goes to pay for my ramen & rent. A: I don't think there are any plist editors online, at least not as functional as Plist Editor with Xcode. You could use an online XML-editor, like Xmlia2.0, and code it yourself. Why would you ever want an online tool for editing XML-files when you've got Plist Editor from xcode? A: I wrote one once back in the day (for the old non-XML plist files). The structure is very regular, so it's not hard to create something that looks and acts more or less like the XCode plist editor. I don't know off-hand of any online XML editors, but they must exist. Given a DTD-savvy XML editor, you ought to be able to edit plist files pretty easily. A: Any web app that accepts .txt documents will edit plists just fine. Likewise for .xml
unknown
d9355
train
1st Pass the PHP array to JavaScript using json_encode: var phpArray = <?php echo json_encode($array); ?>; 2nd Bind to the change event of that <select>: $('#tour').on('change', /* see below */); 3rd Update the value: function (event) { $('#distance').val(phpArray[$(this).val()]); } A: what you want to do is not possible. PHP is a server side script. What you could do in order to make your scripts working is to pass the php Array to Javascript when loading the page. That way Javascipt is able to read it and to change the input. Option would be to use AJAX or define a JS array with the php Array's data: var js_array = <? echo json_encode($you_array); ?>; For this solution you need to add a in your HTML page's if you're pointing to your JS script external. For a longer explanation why using your php Array in Javascript that easy is not possible, see here: Difference between Javascript and PHP
unknown
d9356
train
Check the box to enable editing in SP during your form publish.
unknown
d9357
train
A few things to consider here: * *By putting your call to /payment/create in your useEffect hook, you are creating a new PaymentIntent every time your component updates. This is quite inefficient and will leave you with many unused PaymentIntents, cluttering up your Stripe account. Instead you should only create the PaymentIntent when your user intends to purchase something, like when they click the "buy" button. *You are passing in the total amount to be charged from the client. This means that it is trivial for a malicious user to add many things to their basket and then edit that request to ensure that they are charged a much lower amount than you expect. All logic pertaining to calculating amount totals should be done on the server, not the client. *Your server logs don't show any failure in actual payments. Since you are confirming on the client, it's possible that you are getting an error there but redirecting before you see the error. You should listen for the error object instead of immediately redirecting: stripe.confirmCardPayment(clientSecret, { payment_method: { card: elements.getElement(CardElement) } }).then((result) => { if (result.error) { // payment failed, do something with the error console.log(result.error.message); } else { setSucceeded(true); setError(null) setProcessing(false) history.replace('/order') }); You can also inspect your Stripe logs by looking at your dashboard: https://dashboard.stripe.com/test/logs
unknown
d9358
train
The over-arching strategy (including in deciding when to apply either of your strategies needs) to be "Avoid coding the same thing multiple times". If you code something more than once, it is an opportunity to have several unintended variations (e.g. a set of errors in one version and not in another) and a maintenance burden (if you change one, it is necessary to go through all the other places where the same logic is coded, and update each). Use strategy 1 to handle actions that - according to your design - are applicable to all situations. Use strategy 2 to handle actions that - according to your design - are specific to only a few situations. You can also combine the strategies, and collect meaningful sets of actions (meaningful in the sense that code which employs one action will probably need to employ other particular actions) at various points.
unknown
d9359
train
Hey there fellow Czech programmer! <3 This might get the job done, i think... import pandas as pd df = pd.read_csv('MOCK_DATA.csv') # group by actor_link and count the number of movies g = df.groupby(['actor','actor_link'])['movie'].apply(list).reset_index(name='list_of_movies') # output res to a csv file g.to_csv('actor_movies.csv', header=False, index=False) Tested on this file: actor,actor_link,movie Yardley McGilroy,www.csfd/Yardley McGilroy.cz,Sharknado 2: The Second One Woodman Meese,www.csfd/Woodman Meese.cz,The Amazing Catfish Marijo Thorburn,www.csfd/Marijo Thorburn.cz,"Soldier, The" Arron Rosenfield,www.csfd/Arron Rosenfield.cz,Barcelona Olga Wainscot,www.csfd/Olga Wainscot.cz,Addicted Bradan Ivashev,www.csfd/Bradan Ivashev.cz,Fury Lu Manjin,www.csfd/Lu Manjin.cz,"Sea Inside, The (Mar adentro)" Shelby Kitt,www.csfd/Shelby Kitt.cz,"Set-Up, The" Barbaraanne Yakushkin,www.csfd/Barbaraanne Yakushkin.cz,"Princess Blade, The (Shura Yukihime)" Abbey Munkton,www.csfd/Abbey Munkton.cz,Twin Peaks: Fire Walk with Me Vittoria Clayal,www.csfd/Vittoria Clayal.cz,"Cider House Rules, The" Vickie Ormrod,www.csfd/Vickie Ormrod.cz,Hustler White Artemas Solomonides,www.csfd/Artemas Solomonides.cz,Satyricon Lucita Whittick,www.csfd/Lucita Whittick.cz,"Exterminator, The" Cullen Kear,www.csfd/Cullen Kear.cz,Non-Stop Tine Slaney,www.csfd/Tine Slaney.cz,Measuring the World (Die Vermessung der Welt) Allister Caulcott,www.csfd/Allister Caulcott.cz,Beat the Devil Dannie Sheara,www.csfd/Dannie Sheara.cz,Casanova's Big Night Montague Casetti,www.csfd/Montague Casetti.cz,Someone Like Him (Einer wie Bruno) Dara French,www.csfd/Dara French.cz,Gozu (Gokudô kyôfu dai-gekijô: Gozu) Debby Winterson,www.csfd/Debby Winterson.cz,Dr. Jekyll and Mr. Hyde Phaedra Eneas,www.csfd/Phaedra Eneas.cz,Edges of the Lord Obidiah Bastiman,www.csfd/Obidiah Bastiman.cz,Rendezvous Lindy Lilbourne,www.csfd/Lindy Lilbourne.cz,Night Moves Devon Obert,www.csfd/Devon Obert.cz,Rabbit Without Ears 2 (Zweiohrküken) Conrade Urrey,www.csfd/Conrade Urrey.cz,Heavens Fall Jaine Chasson,www.csfd/Jaine Chasson.cz,Jimi Hendrix: Hear My Train A Comin' Filberte Southerton,www.csfd/Filberte Southerton.cz,"Capture of Bigfoot, The" Ulric Hargitt,www.csfd/Ulric Hargitt.cz,Pilgrimage Gal Pavia,www.csfd/Gal Pavia.cz,Big Hero 6 Niels Dannell,www.csfd/Niels Dannell.cz,More Than a Game Kari Jobe,www.csfd/Kari Jobe.cz,Jimi: All Is by My Side Tonia Hatton,www.csfd/Tonia Hatton.cz,Star Trek: Nemesis Rozele Kaas,www.csfd/Rozele Kaas.cz,Captive (Cautiva) Urson Bourdel,www.csfd/Urson Bourdel.cz,RKO 281 Teddi Mohammed,www.csfd/Teddi Mohammed.cz,Canvas Blair Mosedale,www.csfd/Blair Mosedale.cz,Escape from Fort Bravo Cleon Sloley,www.csfd/Cleon Sloley.cz,Survival Quest Yasmin Snap,www.csfd/Yasmin Snap.cz,Strictly Sexual Audy Rubinfeld,www.csfd/Audy Rubinfeld.cz,Queen of Montreuil Shepperd Matusiak,www.csfd/Shepperd Matusiak.cz,"Dark Side of the Heart, The (Lado oscuro del corazón, El)" Storm Harrowing,www.csfd/Storm Harrowing.cz,"Artist, The" Vlad Geare,www.csfd/Vlad Geare.cz,Pleasure at Her Majesty's Stacey Kiff,www.csfd/Stacey Kiff.cz,Marilyn in Manhattan Darla Dongall,www.csfd/Darla Dongall.cz,Hometown Legend Nathan Lythgoe,www.csfd/Nathan Lythgoe.cz,Tales of Terror Krishnah Bernet,www.csfd/Krishnah Bernet.cz,Circus of Horrors Elnore Haggett,www.csfd/Elnore Haggett.cz,"Thing About My Folks, The" Wasn't able to get rid of the quotation marks because that would break the csv parsing, hope that's not too big of a problem... A: I think you can get desired output using group by aggregation as follows. import pandas as pd import io string = """name,actor_link,movie_link Tom Hanks,https://www.csfd.cz/tvurce/330-tom-hanks/,https://www.csfd.cz/film/10135-forrest-gump/ Tom Hanks,https://www.csfd.cz/tvurce/330-tom-hanks/,https://www.csfd.cz/film/2292-zelena-mile/""" df = pd.read_csv(io.StringIO(string), sep=",") df = df.groupby(['name','actor_link']).agg(list_of_movies=('movie_link',list)).reset_index()
unknown
d9360
train
should that be the @2x size, or should I double that, and set that to the @2x size? Listen to your intuition. It's not called [email protected] but image@2x... do you just use their naming guidelines and dump them into your project somewhere? After your graphics designer has sent you the necessary files, yes. But not just "somewhere". Rather into the root of your app bundle.
unknown
d9361
train
There is a lot going on here... A few changes I did to get a functional example from your data: * *You must create a 'data' field inside 'series': series: [{ data: [] }] *You must set the 'data' attribute from 'series[0]' and pass the data field from your JSON: options.series[0].data = text[1].data; *You must use numbers as y coordinate data, so you should use dot as decimal separator and do not use quotes: {"name":"Traf_BH_TCH_Erl","data":[11.23,3.36,4.08,11.96,9.97]} *You are not using X axis with date format properly, but you can search for that after you get your first Highcharts working. ;) Functional example: JSFiddle
unknown
d9362
train
Can try as follows to update the table. update POSITIONS as a set total = (select sum(total) from positions as b where a.col1 = b.col1 and a.col2 = b.col2 and a.col3 = b.col3) WHERE a.date is not null If you don't want the total of row with date to be included in the sum, then you have to tweek the query accordingly. The following assumptions were made as your question is not very clear. 1) There will be only one row with non empty date 2) No need to update if all the dates available are empty Next time, try to include as much info as possible with your question for us to guide better. Regards. A: First, you calculate SUM total value Group by A,B,C Where date not null. Then, you update total = SUM (calculated step one). Last, you select DISTINCT A,B,C,total Try this code: UPDATE POSITIONS AS P SET total = (SELECT SUM(total) FROM POSITIONS WHERE A = P.A AND B = P.B AND C = P.C) WHERE date IS NOT NULL SELECT DISTINCT A,B,C,total FROM POSITIONS WHERE date IS NOT NULL A: WITH CTE_Position AS ( SELECT 'Test' AS A, 1 AS B, 1 AS C, 5 AS Total, CONVERT(DATE, '05/10/2018') AS [Date] UNION ALL SELECT 'Test' AS A, 1 AS B, 2 AS C, 6 AS Total, NULL AS [Date] UNION ALL SELECT 'Test' AS A, 2 AS B, 3 AS C, 5 AS Total, CONVERT(DATE, '05/10/2018') AS [Date] UNION ALL SELECT 'Test' AS A, 2 AS B, 4 AS C, 6 AS Total, NULL AS [Date] UNION ALL SELECT 'Test' AS A, 3 AS B, 5 AS C, 5 AS Total, CONVERT(DATE, '05/10/2018') AS [Date] UNION ALL SELECT 'Test' AS A, 3 AS B, 6 AS C, 6 AS Total, NULL AS [Date] UNION ALL SELECT 'Test' AS A, 4 AS B, 7 AS C, 5 AS Total, CONVERT(DATE, '05/10/2018') AS [Date] ) SELECT p1.A, p1.B, p1.C ,Total = (CASE WHEN SUM(p2.Total) IS NULL OR SUM(p2.Total) = 0 THEN SUM(p1.Total) ELSE SUM(p1.Total + p2.Total) END) ,p1.[Date] FROM CTE_Position p1 LEFT JOIN CTE_Position p2 ON p1.A = p2.A AND p1.B = p2.B AND p2.[Date] IS NULL WHERE p1.[Date] IS NOT NULL GROUP BY p1.A, p1.B, p1.C, p1.[DATE]
unknown
d9363
train
I suspect is it just the method of calculation inside the sum function SELECT c.customerid , c.companyname , o.orderdate , SUM((od.unitprice * od.Quantity) * (1 - od.Discount)) AS totalsales FROM customers AS c INNER JOIN orders AS o ON o.customerid = c.CustomerID INNER JOIN [Order Details] AS od ON o.OrderID = od.OrderID WHERE o.OrderDate >= '1996-10-01' AND o.orderdate < '1996-11-01' -- move up one day, use less than GROUP BY c.customerid , c.companyname , o.orderdate ORDER BY totalsales DESC ; * *(od.unitprice * od.Quantity) provides total discounted price, then *the discount rate is (1 - od.Discount) *multiply those (od.unitprice * od.Quantity) * (1 - od.Discount) for total discounted price Please note I have changed the syntax of the joins! PLEASE learn this more modern syntax. Don't use commas between table names in the from clause, then conditions such as AND o.customerid = c.CustomerID move to after ON instead of within the where clause.. Also, the most reliable date literals in SQL Server are yyyymmdd and the second best is yyyy-mm-dd. It's good to see you using year first, but I would suggest using dashes not slashes, or (even better) no delimiter. e.g. WHERE o.OrderDate >= '19961001' AND o.orderdate < '19961101' Also note that I have removed the <= and replaced it with < and moved that higher date to the first of the next month. It is actually easier this way as every month has a day 1, just use less than this higher date.
unknown
d9364
train
Throwing ""ImportError: No module named dexterity.localcommands.dexterity" + "plone" into a searchengine leads straight to Plone 4.3.4 - ImportError: No module named dexterity.localcommands.dexterity where S. McMahon states it's a bug reported in https://github.com/plone/Installers-UnifiedInstaller/issues/33 and already fixed for Plone-5-installers, but not for Plone-4. The bug is likely caused of the newest setuptools-version and FWIW, I accidentally found these infos one day in the tweets of "glyph", which look helpful: "Public Service Announcement: make @dstufft’s life easier, and do not use the `python-pip´ package from Debian or Ubuntu. It’s broken." (1) "Instead, install pip and virtualenv with get-pip.py, ideally into your home directory. (Sadly, https://pip2014.com/ is still relevant.)" (2) I will have a closer look at the salvation-promising-script get-pip.py, when running into probs again, but for now, I simply don't upgrade anything :-D (1)https://twitter.com/glyph/status/640980540691234816 (2)https://twitter.com/glyph/status/640980540691234816 A: (copied from my own comment on a similar issue in github) I've had fights like this in the past with zopeskel / paster. Nowadays though I avoid it.... choosing to use: * *mrbob for templating eggs *creating dexterity types through the web see plone training *OR alternatively creating dexterity types directly in code without templating - there's a lot less boilerplate code in dexterity cf archetypes I suspect your issue is because your install of 4.3.6 may have upgraded zopeskel or one of it's dependencies to something with different requirements on localcommands/templates. If you want to continue this fight (and I don't recommend it), then you could try pinning all your zopeskel dependencies to latest versions (though Zopeskel has to be less than 3.0 I believe)
unknown
d9365
train
I found the answer. While it shows my stupidity, I wanted to post it here in case others have the same issue. When I created the RDS (custom) PostGreSQL I specified I database name. Little did I know that about 20 fields down in the form, there is a second location you specify the dbname. If you do not, it says it does not create the db and assigns no name (the console shows "-" as the name. The first name is for the first part of the endpoint. The second time you specify the name is for the database itself. I am using the PostGreSQL for the security/login when I setup the RDS. Hope this helps someone.
unknown
d9366
train
I have very similar problem, app is restarted after swapping to production slot and that causes unwanted downtime. After a lot of searching I found the following: In some cases after the swap the web app in the production slot may restart later without any action taken by the app owner. This usually happens when the underlying storage infrastructure of Azure App Service undergoes some changes. When that happens the application will restart on all VMs at the same time which may result in a cold start and a high latency of the HTTP requests. While you cannot control the underlying storage events you can minimize the effect they have on your app in the production slot. Set this app setting on every slot of the app: WEBSITE_ADD_SITENAME_BINDINGS_IN_APPHOST_CONFIG: setting this to “1” will prevent web app’s worker process and app domain from recycling when the App Service’s storage infrastructure gets reconfigured. You can find the whole Ruslany post, that I found very helpful here
unknown
d9367
train
There's a subtlety between /Library and /System/Library that I do not understand. Therefore, this answer is flawed. However. Even with that gap, I suggest you do this. * *Backup your data. All of it. Backup any apps you installed. *Buy 10.7 Lion. *Install. I don't think you need to do a "fresh" install. But some Mac users strongly suggest fresh installs of each new OS release. *Restore your files. Don't delete Python. iLife (for one) requires it. A: Don't mess with the pre-installed python. It will break dependencies on your mac. It happened to me, I had to re-install to fix it. A better thing to do is to install a new version of python.
unknown
d9368
train
The priority list: * *== *&& *|| A: First ==, then &&, then ||. Your expression will be evaluated as y[i] = (((z[i] == a) && b) || c). https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html A: The actual expression is evaluated as y[i] = ( ((z[i] == a) && b) || c ) You probably want to look here for more info on operator precedence. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html A: This would be : y[i] = ((( (z[i]) == a )&& b) || c) ref: http://introcs.cs.princeton.edu/java/11precedence/ A: Here's the full list of ALL OPERATORS: Full list of operators in Java Got it from "Java ist auch eine Insel" = "Java is also an island"
unknown
d9369
train
Buildbot offers a mechanism to access those properties. It is described in http://docs.buildbot.net/current/manual/cfg-properties.html#using-properties-in-steps You will need to use Interpolate class to get the value that you are looking for: for example, Interpolate('%(prop:event.change.id)s. Please note the introduction section that describes possible mistakes people make when they start using this functionality. A: What and where is this file cbuildbot_stages.py ? You could override the default buildbot behavior with what you want in your buildbot config file. Standard OOP practice. A: Well I am using buildbot to build chromium os. cbuildbot_stages.py script is in /chromite/buildbot/ directory. I want to access the gerrit change id in buildbot stages.
unknown
d9370
train
If you have access to the gerrit server, check whether you have granted enough permissions to the git folder of your gerrit.
unknown
d9371
train
You should limit your selectors to just the current .comment-box div. $(function() { $(".user-comment-box").slice(-5).show(); // select the first 5 hidden divs $(".see-more").click(function(e) { // click event for load more e.preventDefault(); let current_post = $(this).closest(".comment-box"); var done = $('<div class="see-more=done"></div>'); current_post.find(".user-comment-box:hidden").slice(-5).show(); // select next 5 hidden divs and show them if (current_post.find(".user-comment-box:hidden").length == 0) { // check if any hidden divs $(this).replaceWith(done); } }); });
unknown
d9372
train
About certificate, you can use a self signed certificate, the only difference is that the users will see a big warning when installing that the publisher is unknown. About timestamping, I only know that the adt tool that packages the app is attempting to connect to a timestamping server, I am not sure what protocol is used, you will need to check this and unblock this. If the installer is not timestamped then the issue is that after the certificate expires you can continue using this installer and need to do a new one with a certificate that is not expired. As an example, if I use a certificate that expires tomorrow today and the installer is not timestamped then it will not work after tomorrow but if it was timestamped then it will continue to work after the certificate expired because it was created before the expiration I seen the installer is damaged erors a few times on our customers machine, usually on Windows, sometimes uninstalling and reinstalling AIR helped but not always, the problem is that the error message is not detailled enough to fix this, in rare cases I had to create .exe installers for those customers but I suggest to try the installers on a few machines first and use the native .exe installers if anything else is not working.
unknown
d9373
train
It's because of the large payload. Move the large payload code portion to the client-side(useEffect) and it will be resolved. A: I had the same issue. But when I changed getserversideprops to getstaticprops it worked.
unknown
d9374
train
First of all, yes there is a crazy regex you can give to String.split: "[^A-Z0-9]+|(?<=[A-Z])(?=[0-9])|(?<=[0-9])(?=[A-Z])" What this means is to split on any sequence of characters which aren't digits or capital letters as well as between any occurrence of a capital letter followed by a digit or any digit followed by a capital letter. The trick here is to match the space between a capital letter and a digit (or vice-versa) without consuming the letter or the digit. For this we use look-behind to match the part before the split and look-ahead to match the part after the split. However as you've probably noticed, the above regex is quite a bit more complicated than your VALID_PATTERN. This is because what you're really doing is trying to extract certain parts from the string, not to split it. So finding all the parts of the string which match the pattern and putting them in a list is the more natural approach to the problem. This is what your code does, but it does so in a needlessly complicated way. You can greatly simplify your code, by simply using Pattern.matcher like this: private static final Pattern VALID_PATTERN = Pattern.compile("[0-9]+|[A-Z]+"); private List<String> parse(String toParse) { List<String> chunks = new LinkedList<String>(); Matcher matcher = VALID_PATTERN.matcher(toParse); while (matcher.find()) { chunks.add( matcher.group() ); } return chunks; } If you do something like this more than once, you might want to refactor the body of this method into a method findAll which takes the string and the pattern as arguments, and then call it as findAll(toParse, VALID_PATTERN) in parse. A: Try this way, this will gives you digits value, then remaining string can be separated as string Pattern p = Pattern.compile("\\d+"); Matcher m = p.matcher("JD85DS8796"); m.find(); String inputInt = m.group(); textview.setText(inputInt);
unknown
d9375
train
Using Invoke-WebRequest is analogous to opening a link in your browser. It's a legitimate way to download files from Azure Storage, however to do that you'll need the URI to include a SAS (Shared Access Signature), which you'll have to have generated before you use it in your code. The PowerShell to achieve this is: #Download via URI using SAS $BlobUri = 'https://yourstorageaccount.blob.core.windows.net/yourcontainer/yourfile.txt' $Sas = '?sv=2015-04-05&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D' $OutputPath = 'C:\Temp\yourfile.txt' $FullUri = "$BlobUri$Sas" (New-Object System.Net.WebClient).DownloadFile($FullUri, $OutputPath) Alternatively, if you have the Azure PowerShell module installed, you can do it without any of that added pain: # Download via Azure PowerShell $StorageAccountName = 'yourstorageaccount' $StorageAccountKey = Get-AzureStorageKey -StorageAccountName $StorageAccountName $StorageContext = New-AzureStorageContext $StorageAccountName -StorageAccountKey $StorageAccountKey.Primary $FileName = 'yourfile.txt' $OutputPath = 'C:\Temp' $ContainerName = 'yourcontainer' Get-AzureStorageBlobContent -Blob $FilebName -Container $ContainerName -Destination $OutputPath -Context $StorageContext A: I ended up to resolve similar requirement with Azure PowerShell Az module as follows: $BlobFilePath = 'dir\blob.file' # Relative path in blob starting from container $OutputFilePath = 'C:\temp\blob.file' # Path to download the file to $StorageAccountName = 'storageaccountname' $ContainerName = 'blob-container-name' # Prompt for Azure Account creds, if working from VM with managed identity could add also switch -Identity to use that identity directly Connect-AzAccount $StorageContext = New-AzStorageContext -StorageAccountName $StorageAccountName Get-AzStorageBlobContent -Blob $BlobFilePath -Container $ContainerName -Destination $OutputFilePath -Context $StorageContext A: $StartTime = $(get-date) $datetime = $(get-date -f yyyy-MM-dd_hh.mm.ss) $connection_string = '' $AzureBlobContainerName = '' $destination_path = "c:\download" If(!(test-path $destination_path)) { New-Item -ItemType Directory -Force -Path $destination_path } $storage_account = New-AzStorageContext -ConnectionString $connection_string # Download from all containers #$containers = Get-AzStorageContainer -Context $storage_account # Download from specific container $containers = Get-AzStorageContainer -Context $storage_account | Where-Object {$_.Name -eq "$AzureBlobContainerName"} $containers Write-Host 'Starting Storage Dump...' foreach ($container in $containers) { Write-Host -NoNewline 'Processing: ' . $container.Name . '...' $blobs = Get-AzStorageBlob -Container $container.Name -Context $storage_account $container_path = $destination_path + '\' + $container.Name new-item -ItemType "directory" -Path $container_path Write-Host -NoNewline ' Downloading files...' foreach ($blob in $blobs) { $fileNameCheck = $container_path + '\' + $blob.Name if(!(Test-Path $fileNameCheck )) { Get-AzStorageBlobContent -Container $container.Name -Blob $blob.Name -Destination $container_path -Context $storage_account } } Write-Host ' Done.' } Write-Host 'Download complete.' $elapsedTime = $(get-date) - $StartTime $totalTime = "{0:HH:mm:ss}" -f ([datetime]$elapsedTime.Ticks) Write-Output " -OK $totalTime" | Out-String
unknown
d9376
train
Try Setting the GroupName Property in your code: Use: rad.GroupName = "priceGrp"
unknown
d9377
train
I'd probably split it up into seperate components and pass parameters down the component tree for example {isEnabled ? <IsLoadingComponent loading={loading} items={items}> : <ComponentThree/>} A: You might find it useful to split the component up into a "Loading" version and a "Loaded" version so you don't have to handle both states in the same component. Then the component basically just renders the "Loading" or "Loaded" version depending on the flag. But even without that, you can at least make that easier to debug by using if/else if etc. and assigning to a temporary variable: let comp; if (isEnabled) { if (loading) { comp = <div> <LoadingComponent/> </div>; } else if (items.length === 0) { comp = <> <ComponentOne/> <Container> <img src={Image} alt="Image" /> </Container> </>; } else { comp = <ComponentTwo />; } } else { comp = <ComponentThree />; } Then just {comp} where that nested conditional was. A: I think you are making a simple thing very complicated. What we can do instead is that make use of "&&". { isEnabled && loading && <LoaderComponent /> } {isEnabled && !items.length && <> <ComponentOne/> <Container> <img src={Image} alt="Image" /> </Container> </> } {isEnabled && items.length && <ComponentTwo/>} {!isEnabled && <ComponentThree />} A: Though I want to support the argument the others made (split into multiple components), you can already achieve a bit more readability by dropping unnecessary fragments (<></>) and/or parenthesis and by using "better"(opinion) indentation. return ( isEnabled ? loading ? <div><LoadingComponent/></div> : items.length === 0 ? <> {/* this is the only place a fragment is actually needed */} <ComponentOne/> <Container> <img src={Image} alt="Image"/> </Container> </> : <ComponentTwo/> : <ComponentThree/> ); Alternatively, early returns do help a lot with readability. For example: const SomeComponent = () => { // ...snip... if (!isEnabled) { return <ComponentThree/>; } if (loading) { return <div><LoadingComponent/></div>; } if (items.length > 0) { return <ComponentThree/>; } return ( <> <ComponentOne/> <Container> <img src={Image} alt="Image"/> </Container> </> ); }
unknown
d9378
train
setTimeout need to use in useEffect instead. And add clear timeout in return useEffect(() => { const timeOut = setTimeout(() => { theNext(index); if (index === departments.length - 1) { setIndex(0); setSelectedIndex(0); } }, 4000); return () => { if (timeOut) { clearTimeout(timeOut); } }; }, []); A: Here is a simple solution. first of all, you have to remove all the timers like this. useEffect(() => { return () => remover timers here ; },[]) and put this import React, { useEffect,useRef, useState } from 'react' const Example = () => { const isScreenMounted = useRef(true) useEffect(() => { isScreenMounted.current = true return () => isScreenMounted.current = false },[]) const somefunction = () => { // put this statement before every state update and you will never get that earrning if(!isScreenMounted.current) return; /// put here state update function } return null } export default Example;
unknown
d9379
train
If you create a 2D array of plots, e.g. with: >>> fig, axarray = plt.subplots(3, 4) then axarray is a 2D array of objects, with each element containing a matplotlib.axes.AxesSubplot: >>> axarray.shape (3, 4) The problem is that when you index axarray[0], you're actually indexing a whole row of that array, containing several axes: >>> axarray[0].shape (4,) >>> type(axarray[0]) numpy.ndarray However, if you address a single element in the array then you can set its attributes in the normal way: >>> type(axarray[0,0]) matplotlib.axes.AxesSubplot >>> axarray[0,0].set_title('Top left') A quick way of setting the attributes of all of the axes in the array is to loop over a flat iterator on the axis array: for ii,ax in enumerate(axarray.flat): ax.set_title('Axis %i' %ii) Another thing you can do is 'unpack' the axes in the array into a nested tuple of individual axis objects, although this gets a bit awkward when you're dealing with large numbers of rows/columns: fig, ((ax1, ax2, ax3, ax4), (ax5, ax6, ax7, ax8), (ax9, ax10, ax11, ax12)) \ = plt.subplots(3,4) A: When using this method: fig, ax = plt.subplots(nrows=2, ncols=3, sharex=True, sharey=True) you have two choices, either call the elements of the array ax like you have suggested (but you will need to use two indices or flatten it): ax[0][0].plot(... ax.flat[0].plot(... this second line is useful if you loop over the plots. Or you can modify in the following way: fig, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(nrows=2, ncols=3, sharex=True, sharey=True) It will depend on your use case which is better, I typically call the array ax if there is a chance I will change the number of subplot.
unknown
d9380
train
Version with Files shorter and easier to understand. Other version is more flexible. It is not very useful when you have only one file to write, but if you have many files in different storages it can save you some resources. EDIT Here is Files.write source code: public static Path write(Path path, byte[] bytes, OpenOption... options) throws IOException { // ensure bytes is not null before opening file Objects.requireNonNull(bytes); try (OutputStream out = Files.newOutputStream(path, options)) { int len = bytes.length; int rem = len; while (rem > 0) { int n = Math.min(rem, BUFFER_SIZE); out.write(bytes, (len-rem), n); rem -= n; } } return path; } As you can see it doesn't use NIO inside, only good old OutputStream. EDIT 2 In fact Files.newOutputStream don't return FileOutputStream as I expected. It returns OutputStream defined in Channels.newOutputStream which use NIO inside. A: * *Files.write(...) use OutputStream instead of RandomAccessFile.getChannel(). it some different mechanisms, so better to google it for understand *Files.write(...) much shorter and incapsulate logic of writting to file *When you use such 'low' code, you need to look after many things. For example, in your example you didn't close your channel. So, in conclusion, if you need to just write – better to use Files or another high-level API. If you need some 'additional' features during read/write, you need to use RandomAccessFile or InputStream/OutputStream
unknown
d9381
train
I have found the solution for my problem. You should use the following code to set the Button selected: //HERE THE CODE IS WORKING candidatesButtons.get(0).requestFocusFromTouch(); candidatesButtons.get(0).setSelected(true); Maybe it will be useful to someone
unknown
d9382
train
another way using 'regex' and 'idmax. df = pd.DataFrame({'xyz1': [10, 20, 30, 40], 'xyz2': [11, 12,13,14],'xyz3':[1,2,3,44],'abc':[100,101,102,103]}) df['maxval']= df.filter(regex='xyz').apply(max, axis=1) df['maxval_col'] = df.filter(regex='xyz').idxmax(axis=1) abc xyz1 xyz2 xyz3 maxval maxval_col 100 10 11 1 11 xyz2 101 20 12 2 20 xyz1 102 30 13 3 30 xyz1 103 40 14 44 44 xyz3 A: Does this work for you? import pandas as pd df = pd.DataFrame([(1,2,3,4),(2,1,1,4)], columns = ['xyz1','xyz2','xyz3','abc']) cols = [k for k in df.columns if 'xyz' in k] df['maxval'] = df[cols].apply(lambda s: max(zip(s, s.keys()))[0],1) df['maxcol'] = df[cols].apply(lambda s: max(zip(s, s.keys()))[1],1) df Out[753]: xyz1 xyz2 xyz3 abc maxval maxcol 0 1 2 3 4 3 xyz3 1 2 1 1 4 2 xyz1
unknown
d9383
train
It sounds like you'll need to repopulate the DataView from the database and refresh your databinding on the UltraCombo; probably pretty close to the same code you use to initially populate the DataView and set the UltraCombo databinding. You may get a more complete answer if you post some code.
unknown
d9384
train
There's no such specific intent action which tells that a file is downloaded. However, you should listen for the following broadcast to detect that a phone is disconnected and then check programatically if a file is downloaded. <intent-filter> <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED"/> </intent-filter>
unknown
d9385
train
Add origin/ to the name of the branch: differenceCommit(fileName,branchName) { return new Promise(function (resolve,reject) { let repo, changes; open("./master") .then(function (repoResult) { repo = repoResult; return repo; }) .then(function (commitId) { return repo.getBranchCommit("origin/dev"); }) ///Difference Before Push .then(function (commit) { return commit.getDiffWithOptions("origin/dev"); }) .then(function (diffList) { console.log("************************"); }); }
unknown
d9386
train
Wrap the logic in a method: private static DateTime GetDateTimeValue(SqlDataReader reader, string fieldName) { int ordinal = reader.GetOrdinal(fieldName); return reader.IsDBNull(ordinal) ? reader.GetDateTime(ordinal) : DateTime.MinValue; } ...and call it: Event_Start_Date1 = GetDateTimeValue(reader, "event_start_date1"); A more general and reusable approach could be to make it into an extension method that can (optionally) take a default value as input: public static class SqlDataReaderExtensions { public static DateTime GetDateTimeValue(this SqlDataReader reader, string fieldName) { return GetDateTimeValue(reader, fieldName, DateTime.MinValue); } public static DateTime GetDateTimeValue(this SqlDataReader reader, string fieldName, DateTime defaultValue) { int ordinal = reader.GetOrdinal(fieldName); return reader.IsDBNull(ordinal) ? reader.GetDateTime(ordinal) : defaultValue; } } This assumes that you cannot change the model. If you have that option, go with a Nullable<DateTime> instead, and have the GetDateTimeValue method default to returning null. A: Check for DBNull and based on that you can assign MinValue. int ordinal = reader.GetOrdinal("event_start_date1"); Event_Start_Date1 = reader.IsDBNull(ordinal)? DateTime.MinValue: reader.GetDateTime(ordinal); A: Use a nullable DateTime: public DateTime? EventStartDate { get; set; } Which is similar to: public Nullable<DateTime> EventStartDate { get; set; } Read more about Nullable Types To get the default value of DateTime, you can use either DateTime.MinValue or default(DateTime): while (reader.Read()) { Status = reader["status"].ToString(); var startDate = reader.GetOrdinal("event_start_date1"); EventStartDate = if reader.IsDBNull(startDate) ? reader.GetDateTime(ordinal) : default(DateTime); } Essentially, DateTime is a value-type, not a reference type, and there can't be a null DateTime (or whatever other Value Type) compile-time variable, in order for it to be capable to hold a null value it has to be wrapped in the Nullable<T>). In .NET all the non-nullable types have a default value which can be obtained via the default keyword (e.g. default(DateTime)). A: Use DataReader.IsDBNull to check if the value is null: Event_Start_Date1 = reader.IsDBNull("event_start_date1") ? DateTime.MinValue : reader.GetDateTime(reader.GetOrdinal("event_start_date1")); The above sentence is in the following format: Condition ? accepted action : rejected action A: you can use a try-catch while (reader.Read()) { Status = reader["status"].ToString(); try{ Event_Start_Date1 = reader.GetDateTime(reader.GetOrdinal("event_start_date1")); } catch{ Event_Start_Date1 = //some other thing } or you can use GetSqlDateTime() while (reader.Read()) { Status = reader["status"].ToString(); Event_Start_Date1 = reader.GetSqlDateTime(reader.GetOrdinal("event_start_date1")); }
unknown
d9387
train
I'm assuming you want to turn the website directory on your web server into a Mercurial repository. If that's the case, you would create a new repository somewhere on that computer, then move the .hg directory in the new repository into the website directory you want to be the root of the repository. You should then be able to run hg add * --exclude vendor --exclude web/Upload hg commit -m "Adding site to version control." to get all the non-user files into version control. I recommend, however, that you write a script or investigate tools that will deploy your website out of a repository outside your web root. You don't want your .hg directory exposed to the world. Until you get a deploy script/tool working, make sure you tell your webserver to prohibit/reject all requests to your .hg directory.
unknown
d9388
train
It's by design. Changing code does not make sense for VS created functions (precompiled functions) as your code already compiled to dll. if you take a look on kudu (https://{your-function-app-name}.scm.azurewebsites.net/DebugConsole) you will see that folder stracture is different for portal and VS created functions. More info about portal and VS created functions: https://learn.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-csharp
unknown
d9389
train
There is no use in sending those label texts around. It is unnecessary traffic, and one more thing that needs to be filtered/validated. You create the form on the server side, so you already have access to the texts of the labels there. I'd advise you to store these texts in constants, like: define('TEXT_EMAIL', 'Email Address'); So when you create the form, you can just type: <label for="email"><?=TEXT_EMAIL?></label> and use the same constant (TEXT_EMAIL and the others) when you build the email body. This way, you will also be in an easy situation if you need to add support for other languages. A: ... maybe add the label values to dynamically created hidden fields in the form? Just name the fields (prefix them?) in such a way that you can identify them easily on the server side. A: You are right to consider hidden form fields if you're not POSTing the data to the server through an Ajax request. Assuming a regular form submission, only values of input and textarea elements are sent to the server. Adding appropriate hidden input elements and setting the values of these from the labels is your only option.
unknown
d9390
train
From the document DataFrame.plot.scatter : have parameters s and c , which can change the size and color of the point
unknown
d9391
train
Assuming that your codepen would look something like this from your explanations. The solution would be to add margin instead of top on the element 2 and vertically align the first element to top so it sticks to the top border. .element-2 { margin-top: 200px; } .element-1 { vertical-align: top; }
unknown
d9392
train
yes, MonetDB uses parallel processing where possible. See the documentation https://www.monetdb.org/Documentation/Cookbooks/SQLrecipes/DistributedQueryProcessing
unknown
d9393
train
Yes, the fastest way to have it done is use master/slave setup for you jenkins. So, what you need to do is to add slave to the machine on which your terraform is running. A: Generally, it's a good idea to keep your Jenkins machine as clean as possible, therefore you should avoid installing extra packages on it like Terraform. A better approach for this problem would be creating a Dockerfile with your Terraform binary and all the plugins that you need already built-in, then all you need to do in your Jenkins pipeline is build and execute your Terraform docker. This is an example of such Dockerfile: FROM hashicorp/terraform:0.11.7 RUN apk add --no-cache bash python3 && \ pip3 install --no-cache-dir awscli RUN mkdir -p /plugins # AWS provider ENV AWS_VERSION=1.16.0 ENV AWS_SHA256SUM=1150a4095f18d02258d1d52e176b0d291274dee3b3f5511a9bc265a0ef65a948 RUN wget https://releases.hashicorp.com/terraform-provider-aws/${AWS_VERSION}/terraform-provider-aws_${AWS_VERSION}_linux_amd64.zip && \ echo "${AWS_SHA256SUM} terraform-provider-aws_${AWS_VERSION}_linux_amd64.zip" | sha256sum -c - && \ unzip *.zip && \ rm -f *.zip && \ mv -v terraform-provider-aws_* /plugins/ COPY . /app WORKDIR /app ENTRYPOINT [] The Terraform documentation also contains a section on best practices running Terraform in CI: https://www.terraform.io/guides/running-terraform-in-automation.html A: I have created a Global Shared Library awesome-jenkins-utils with which you can use different version of terraform simultaneously in same pipeline. Additionally you can easily map build parameters to terraform variables
unknown
d9394
train
You would do this via a check constraint, see here: http://www.w3schools.com/sql/sql_check.asp Yes you can put regex in a check constraint, here is an example: CREATE TABLE dbo.PEOPLE ( name VARCHAR(25) NOT NULL , emailaddress VARCHAR(255) NOT NULL , CONSTRAINT PEOPLE_ck_validemailaddress CHECK ( dbo.RegExValidate( emailaddress, N'^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$' ) = 1 ) ) Your regular expression would be: [A-Z][A-Z][A-Z][-][0-9][0-9][0-9][0-9][0-9][0-9][0-9] Here is a great tool to build and test reg expr http://www.regexr.com/
unknown
d9395
train
For price => $(".itemprices").text(); For title => $(".product-name").prop('title'); //NEW CODE See if you have multiple products ,Assign separate ID to every Product DIV (you already have class assigned to it).Then use # instead of '.' (DOT) . So use var idStored=$(this).attr('id'); idStored.text(); idStored.text().prop('title'); And then Call these Manipulation on Hover of the div ,Or onClick A: Try the following: In your addBasket(basket, move) function add the following line: var currentLIelement = $(move).parents('li'); So, currentLIelement will be your parent <li> element of dragged element. Now, to get the title you need to call this: $(currentLIelement).find('.product-name').prop('title') And to get the price you need to call this: $(currentLIelement).find('.itemprices').text() NOTE: In your code I found live() method - As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.
unknown
d9396
train
That's not how to deal with many-to-many relationships in forms. You can't iterate through fields in a form and save them, it really doesn't work that way. In this form, there's only one field, which happens to have multiple values. The thing to do here is to iterate through the values of this field, which you'll find in the cleaned_data dictionary (when the form is valid). So, in your view, you do something like: if f.is_valid(): for group in f.cleaned_data['group']: calentry.groups.add(group) Note you're not 'saving' the AddEventToGroupForm form at all. I would make it a standard forms.Form, rather than a ModelForm, as you're not really depending on any of the ModelForm functionality.
unknown
d9397
train
Please include gtCstPDFDoc unit in your PAS file. The enumeration TgtImageFormat is from that. UPDATE: The enumeration values start with if and so it is ifJPEG.
unknown
d9398
train
Use :terminal (requires Vim 8.1+) :-tab terminal git --no-pager diff Using fugitive.vim we can create a command: command! -bang Tdiff execute '-tab terminal ' . call(fugitive#buffer().repo().git_command, ['--no-pager', 'diff'] + (<bang>0 ? ['--cached'] : [])) Use :Tdiff to do git diff and :Tdiff! to do git diff --cached For more help see: :h :tab :h :terminal
unknown
d9399
train
. does not match a newline character by default. Since the dkim in your test string is on the second line and your regex pattern tries to match any non-newline character from the beginning of the string with ^.*, it would not find dkim on the second line. You should either use the re.DOTALL flag to allow . to match a newline character: dkim = re.match(r"^.*dkim=(\w+)", auth_results, flags=re.DOTALL) or remove the unnecessary match from the beginning of the string altogether: dkim = re.search(r"dkim=(\w+)", auth_results) A: First, re.match works from the beginning. so your r"dkim=(\w+)" trial doesn't work. Second, the . symbol matches characters except the new line character. If you want it to, you should explictly force it using re.S or re.DOTALL flag. Also, you can use [\s\S] or [\w\W] to match any characters. Try this: re.match(r"^[\s\S]*dkim=(\w+)", auth_results).group(1) or this: re.match(r"^.*dkim=(\w+)", auth_results, re.DOTALL).group(1)
unknown
d9400
train
Pressure data is available if the device supports it (i.e. a force touch trackpads). Force touch trackpads have shipped on MacBooks since circa 2015. Force touch is also available on the Magic Trackpad. This blog post has a method for detecting force touch devices, although I didn't try it. My machine is a 2016 MacBook Pro with a force touch trackpad. I can get the pressure using this code: [self.window trackEventsMatchingMask:NSEventMaskPressure timeout:NSEventDurationForever mode:NSEventTrackingRunLoopMode handler:^(NSEvent * _Nonnull event, BOOL * _Nonnull stop) { NSLog(@"%f", event.pressure); }]; Output: 2018-02-09 18:16:10.986036-0800 forcetouch[4587:4164200] 0.437820 2018-02-09 18:16:10.993772-0800 forcetouch[4587:4164200] 0.457504 2018-02-09 18:16:11.001883-0800 forcetouch[4587:4164200] 0.476486 2018-02-09 18:16:11.010654-0800 forcetouch[4587:4164200] 0.494812 2018-02-09 18:16:11.017738-0800 forcetouch[4587:4164200] 0.512497 2018-02-09 18:16:11.028129-0800 forcetouch[4587:4164200] 0.529556 2018-02-09 18:16:11.033769-0800 forcetouch[4587:4164200] 0.546021 2018-02-09 18:16:11.042117-0800 forcetouch[4587:4164200] 0.561905 2018-02-09 18:16:11.049869-0800 forcetouch[4587:4164200] 0.577240 However, I see you are using an event tap. I tried your code, and when I check kCGMouseEventPressure I get 1. When I check event.pressure I also get 1. So I receive a value where you do not - I guess you do not have force touch hardware? But I do not receive the actual pressure value. I'm not sure how to get this using an event tap. This works for me on a 2016 MacBook Pro. Note that this machine has a force touch trackpad. I'm not sure what this will return on a machine without the force touch trackpad. However hopefully this gives you some more ideas. Force touch for developers NSEvent - pressure A: The snippet from the answer above: [self.window trackEventsMatchingMask:NSEventMaskPressure timeout:NSEventDurationForever mode:NSEventTrackingRunLoopMode handler:^(NSEvent * _Nonnull event, BOOL * _Nonnull stop) { NSLog(@"%f", event.pressure); }]; appears to be stopping the window from responding to any mouse events. I think it may be due to this quote from https://developer.apple.com/documentation/appkit/nswindow/1419727-trackevents Each event is removed from the event queue and then passed to the tracking handler I am not an expert in Cocoa's event architecture, but it occurs to me that trackEventsMachingTask intercepts the event. My workaround is this: NSEvent *(^monitor)(NSEvent *event) = ^NSEvent *(NSEvent *event) { NSLog(@"pressure = %f", event.pressure); return event; }; [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskPressure handler:monitor]; According to https://developer.apple.com/documentation/appkit/nsevent/1534971-addlocalmonitorforevents, addLocalMonitorForEventsMatchingMask's block argument is passed the pointer to the event, and as long as the block does not return nil, the event is dispatched regularly.
unknown