_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d1801 | train | You are best off leaving the system's perl alone. Instead, use perlbrew to install your own perls.
You can install cpanm without using cpan using
curl -L http://cpanmin.us | perl - App::cpanminus
for your local perl.
In addition, you might have to install the command line tools for XCode.
If you can't, you may want to look into installing build tools from MacPorts and putting those in your path ahead of the system paths, but after your local perl because you don't necessarily want to mess with a perl that MacPorts might install either. | unknown | |
d1802 | train | Hi dear sorry for the details . I think the total amount sent to paypal is not calculated correctly .
when you set the subtotal within details can you confirm that the subtotal set there is calculated using this formula
subtotal = sum((item1 price * quantity) + ... (item2 price * Quantity))
then check the total set to amount is calculated using this formula
total = subtotal + shipping
Just make sure that the amount sent to paypal is correctly calculated | unknown | |
d1803 | train | I am guessing that since you are showing the required files based on the same criteria isset($_POST['name']) and since both forms have the name field you end up showing the code in both requires regardless of which form is submitted. You should simply change the form field names on on of the forms such that they are different.
A: Both forms have the same action attribute, they both point back to the same page (note that the hash is not sent to the server). As they both have a field called name and you are checking for that, both actions get executed regardless of which form was sent in.
You can do either:
*
*use different scripts / form processors (don't post back to the same page)
*use a different check for each form, for example by adding a hidden input that will allow you to distinguish between the forms.
A: Add
formaction="Your_URL"
Attribut in Button | unknown | |
d1804 | train | You need to specify the API version you wish to use. Set the version before you make any calls. 2020-10 is the default for now.
See the documentation, it explains everything to you.
https://help.shopify.com/en/api/versioning
A: The ShopifyAPI package specifies the allowed versions in the 'shopify/api_version.py' file. In my case the Shopify platform latest API version is '2022-10' but the latest version allowed by the ShopifyAPI package is '2022-07'.
It seems that the ShopifyAPI package is not always updated quickly after the release of a new API version on the Shopify platform. Try aligning the API version to one of the versions allowed to work around this error. | unknown | |
d1805 | train | My thoughts ...
For DDD, you're best served by taking guidance from the Ubiquitous Language of the domain when discussed with a domain expert.
The term "SetPublishedStatusBy" probably wouldn't come up in that discussion.
I think the most likely outcome of that discussion would be:
*
*An Administrator and publish a post.
*A Publicist can submit a post that an Administrator must approve before it is published.
*An Administrator can approve a submitted post that has been Submitted by a Publicist, which will result in the post being published.
*An Administrator can reject a submitted post.
My Post aggregate would then end up looking something like:
class Post
{
void Submit()
{
this.Status = Submitted;
}
void Publish()
{
this.Status = Published;
}
void Approve()
{
if (this.Status != Submitted) throw "This post is not pending approval.";
this.Status = Published;
}
void Reject()
{
if (this.Status != Submitted) throw "This post is not pending approval.";
this.Status = Rejected;
}
}
When creating the post, the UI would either be calling Publish or Submit in your API, depending on the context. The API would then check that current user can perform the requested Publish or Submit.
Two other options:
*
*Introduce an Aggregate called PostRequest that Publicists have permission to create and only create a Post when that is approved by an Administrator.
*If you want the rules to be more dynamic, i.e. a user just hits 'Publish', whether they are a Publicist or an Administrator and then the outcome is either a published post or a submitted post depending on the rules of the day, then you'd want an orchestration / saga / task layer in between your API and the Aggregate which can interact with User service to decide whether the the first call to the Posts service should be a "Submit" or a "Publish". | unknown | |
d1806 | train | def guitar_params
params.require(:guitar).permit(:make, :model, :year, :color, :serial, :price, :condition, :kind, :bodykind, :frets, :one_owner, :user_id, photos_attributes: [:photo])
end
A: You're running into mass assignment protection which is preventing the photos from being saved. Add this line to your Guitar model:
attr_accessible :photos_attributes
A: in my case I need create a document.
# config/initializer/paperclip.rb
require 'paperclip/media_type_spoof_detector'
module Paperclip
class MediaTypeSpoofDetector
def spoofed?
false
end
end
end
This document is necessary create in config > initializers. If your SO is windows, you need add this line in config/environments/development.rb:
Paperclip.options[:comand_path] = "/ImageMagick-6.8.9-Q16/" | unknown | |
d1807 | train | You are working too hard. All you need to do is create a .plist file with the app identifier and path in it and add it to the /System/Library/LaunchDaemon folder. Then make sure your app is in the /Applications folder. Reboot and it will work each time the phone is booted.
Google "Chris Alvares daemon" and look at his tutorial...
A: i don't think launchD can trigger GUI-level apps. Anything that is "Aqua" level has to be a "StartupItem" or a "Login Item". You can still start them as root, based on where they are started from, and who they are owned by, but launchd doesn't touch that stuff... I dont think you can even have a menu bar icon if you want launchd to handle it....
also if you are talking jailbroken iphones... if you wan to open a GUI app from the "mobileterminal" you should look in Cydia for the app that "does that". it's not as easy as just launching the executable.. there is some funky springboard interaction.. that that utility takes care of. it is callled...... "AppsThruTerm" (bigboss repo) once installed.. you launch your "app" with the command att blahblahblah | unknown | |
d1808 | train | There is a chance you have tmp declared somewhere else that can be seen from here causing this issue (i.e. it is declared public in another module). Try changing the name to isolate it, also, I've never declared a variable in a loop before, While I'm not sure of the implications, I would not recommend it.
Dim subProj As Subproject
Dim tmp10 As Boolean
For Each subProj In prj.Subprojects
tmp10 = subProj.IsLoaded
If Not tmp10 Then
ExportTaskToExcel subProj.SourceProject, StartDate, EndDate
End If
Next
You may have done it for a specific reason but you could omit the variable altogether: -
Dim subProj As Subproject
For Each subProj In prj.Subprojects
If Not subProj.IsLoaded Then
ExportTaskToExcel subProj.SourceProject, StartDate, EndDate
End If
Next | unknown | |
d1809 | train | Well most endpoint security products have:
- an on-demand scanning component.
- a real-time scanning component.
- hooks into other areas of the OS to inspect data before "released". E.g. Network layer for network born threats.
- a detection engine - includes file extractors
- detection data that can be updated.
- Run time scanning elements.
There are many layers and components that all need to work together to increase protection.
Here are a few scenarios that would need to be covered by a security product.
*
*Malicious file on disk - static scanning - on-demand. Maybe the example you have.
A command line/on-demand scanner would enumerate each directory and file based on what was requested to be scanned. The process would read files and pass streams of data to a detection engine. Depending on the scanning settings configured and exclusions, files would be checked. The engine can understand/unpack the files to check types. Most have a file type detection component. It could just look at the first few bytes of a file as per this - https://linux.die.net/man/5/magic. Quite basic but it gives you an idea on how you can classify a file type before carrying out more classifications. It could be as simple as a few check-sums of a file at different offsets.
In the case of your example of a trojan file. Assuming you are your own virus lab, maybe you have seen the file before, analyzed it an written detection for it as you know it is malicious. Maybe you can just checksum part of the file and publish this data to you product. So you have virusdata.dat, in it you might have a checksum and a name for it. E.g.
123456789, Troj-1
You then have a scanning process, that loads your virus data file at startup and opens the file for scanning. You scanner checksums the file as per the lab scenario and you get a match with the data file. You display the name as it was labelled. This is the most basic example really and not that practical bu hopefully it serves some purpose. Of course you will see the problem with false positives.
Other aspects of a product include:
*
*A process writing a malicious file to disk - real-time.
In order to "see" file access in real-time and get in that stack you would want a file system filter driver. A file system mini filter for example on Windows: https://msdn.microsoft.com/en-us/windows/hardware/drivers/ifs/file-system-minifilter-drivers. This will guarantee that you get access to the file before it's read/written. You can then scan the file before it's written or read by the process to give you a chance to deny access and alert. Note in this scenario you are blocking until you come to a decision whether to allow or block the access. It is for this reason that on-access security products can slow down file I/O. They typically have a number of scanning threads that a driver can pass work to. If all threads are busy scanning then you have a bit of an issue. You need to handle things like zip bombs, etc and bail out before tying up a scanning engine/CPU/Memory etc...
*A browser downloading a malicious file.
You could reply on the on-access scanner preventing a file hitting the disk by the browser process but then the browsers can render scripts before hitting the file system. As a result you might want to create a component to intercept traffic before the web browser. There are a few possibilities here. Do you target specific browsers with plugins or do you go down a level and intercept the traffic with a local proxy process. Options include hooking the network layer with a Layered Service Provider (LSP) or WFP (https://msdn.microsoft.com/en-us/windows/hardware/drivers/network/windows-filtering-platform-callout-drivers2). Here you can redirect traffic to an in or out of process proxy to examine the traffic. SSL traffic poses an issue here unless you're going to crack open the pipe again more work.
*Then there is run-time protection, where you don't detect a file with a signature but you apply rules to check behavior. For example a process that creates a start-up registry location for itself might be treated as suspicious. Maybe not enough to block the file on it's own but what if the file didn't have a valid signature, the location was the user's temp location. It's created by AutoIt and doesn't have a file version. All of these properties can give weight to the decision of if it should be run and these form the proprietary data of the security vendor and are constantly being refined. Maybe you start detecting applications as suspicious and give the user a warning so they can authorize them.
This is a massively huge topic that touches so many layers. Hopefully this is the sort of thing you had in mind.
A: Among the literature, "The Art of Computer Virus Research and Defense" from Peter Szor is definitely a "must read". | unknown | |
d1810 | train | As of now, this seems like an actual bug/limitation in Weblogic 12.1.3 so I am posting my workaround as a possible solution.
To make the Stateful bean go through passivation successfully, one needs to implement methods annotated with javax.ejb.PrePassivate and javax.ejb.PostActivate. The @PrePassivate method will make the stateless bean reference point to null, and the @PostActivate method will perform a lookup for that bean when the bean is being activated again.
@PrePassivate
public void prePassivate() {
noStateBean = null;
}
@PostActivate
public void postActivate() {
// The lookup string is correct assuming the ejb module is deployed within an ear. If your setup is different the JNDI lookup name may be slightly different.
noStateBean = InitialContext.doLookup("java:module/NoStateBean!NoState");
}
If there are no comments or other answers in the next couple of weeks or so, I will mark this answer as the solution. | unknown | |
d1811 | train | In such a situation, we can create a temporary folder which can contain the same file with lastPathExtension will be document.fileExtension and we can pass this newly file path to UIDocumentInteractionController.init(url: newFileUrl)
For Example:
func openUnsupportedFileWithPath(documentName : String, fileurl : URL, fileExtension : String, aDocument: SILDocumentDB? = nil, sourceView: UIView? = nil) -> Void {
// Create new temporary path
let paths: String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
var newFileUrl: String = paths.appending("/Downloads/TemporaryFolder)")
newFileUrl = newFileUrl.appendingFormat("%@","\(documentName)")
let destinationPathUrl : URL
do {
// Move newly filePath with new fileName and fileExtension
destinationPathUrl = URL(fileURLWithPath: destinanewFileUrltionPath)
try FileManager.default.moveItem(at: fileurl, to: destinationPathUrl)
} catch {
print(error)
}
//Pass newly filePath to UIDocumentInteractionController
documentInteractionController = UIDocumentInteractionController.init(url: newFileUrl)
documentInteractionController?.name = documentName
documentInteractionController?.delegate = self
let canPreview = documentInteractionController?.presentPreview(animated: true)
if (canPreview == false) {
let activityViewController = UIActivityViewController.init(activityItems: [fileurl], applicationActivities: nil)
activityViewController.setValue(documentName, forKey: "subject")
if ISIPAD {
activityViewController.popoverPresentationController?.sourceView = sourceView ?? self.view
}
self.present(activityViewController, animated: true, completion: nil)
}
}
And UIDocumentInteractionController get dismiss, remove the temporary filePath on documentInteractionControllerDidEndPreview(_ controller: UIDocumentInteractionController) method.
public func documentInteractionControllerDidEndPreview(_ controller: UIDocumentInteractionController) {
documentInteractionController = nil
let paths: String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let filePath: String = paths.appending("/Downloads/TemporaryFolder)")
let _fileManager : FileManager = FileManager.default
if filePath.length > 0 {
if _fileManager.fileExists(atPath: filePath) {
do{
try _fileManager.removeItem(atPath: filePath)
}catch let error as NSError{
print("\(error.localizedDescription)")
}
}
}
} | unknown | |
d1812 | train | *
*Make sure fp is not NULL before trying to write to it. For example:
if(fp == NULL)
{
fprintf(stderr, "Cannot open file\n");
return EXIT_FAILURE; // defined in stdlib.h
}
*You need to open the file with something other than "r", which only allows file reading. Read the man page for fopen to find out which mode would work the best for you. Example:
*
*"w" - Truncate to zero length or create file for writing.
*"a" - Append; open or create file for writing at end-of-file.
A: You opened the file for reading only, and are attempting to write to it.
Use "a" if you want to append to the end of the existing file.
Edit: As others have noted, you're also not checking to see if the file was opened. fopen will return NULL if it fails and set the global variable errno to a value that indicates why it failed. You can get a human-readable explanation using strerror(errno)
if( fp == NULL ) {
printf( "Error opening file: %s\n", strerror( errno ) );
}
A: You are opening it in readonly mode! Need to use w or a for writing/appending to the file :)
fopen("/home/c-sandbox/index.html", "w");
A: You should check that fopen does not return NULL. I suspect it is returning NULL and either the fprintf and/or fclose calls are getting messed up.
A: #include <stdio.h>
main()
{
FILE *fp;
fp=fopen("/home/c-sandbox/index.html", "r");
if(!fp)
{
perror ("The following error occurred");
return ;
}
fgets(line,len,fp);
printf("%s",line);
fclose(fp);
fp=fopen("/home/c-sandbox/index.html", "a");
if(!fp)
{
perror ("The following error occurred");
return ;
}
fprintf(fp, "Testing...\n");
fclose(fp)
}
for reading "hello, world" string present in file.
after reading write to the same file "Testing..." | unknown | |
d1813 | train | If you take a look through the Fabric JS documentation you'll notice that every object extends the Fabric.Object.
The Fabric.Object has a remove() method that you can call to remove any Fabric.Object or class that extends Fabric.Object, which is just about every class that can be rendered onto a canvas, with the exception of a handful of less commonly used classes.
Take a look at the documentation of the remove() function here:
http://fabricjs.com/docs/fabric.Object.html#remove
Also there is a hierarchy of classes on the main page of their documentation which can be found here:
http://fabricjs.com/docs/ | unknown | |
d1814 | train | Try http://iirf.codeplex.com/ (free) or http://www.isapirewrite.com (free to try) | unknown | |
d1815 | train | Use GroupBy.transform instead aggregation for Series/DateFrame with same DatatimeIndex like original, so possible division:
def absolute_to_relative_agg(df, agg):
"""
set_index before using
"""
return df.div(df.groupby([pd.Grouper(freq=agg)]).transform('sum'))
relative_df = absolute_to_relative_agg(df, 'M')
Another way for call function is DataFrame.pipe:
relative_df = df.pipe(absolute_to_relative_agg, 'M')
print (relative_df)
value_in_question
date
2019-01-01 0.032901
2019-01-02 0.045862
2019-01-03 0.048853
2019-01-04 0.008475
2019-01-05 0.041376
...
2019-03-27 0.062049
2019-03-28 0.002165
2019-03-29 0.048341
2019-03-30 0.007937
2019-03-31 0.015152
[90 rows x 1 columns]
A: For the sums, you can groupby the index month:
In [31]: month_sum = df.groupby(df.index.strftime('%Y%m')).sum()
...: month_sum
...:
Out[31]:
value_in_question
201901 1386
201902 1440
201903 1358
You can then use .map to align the month with the correct rows of your DataFrame:
In [32]: map_sum = df.index.strftime('%Y%m').map(month_sum['value_in_question'])
...: map_sum
...:
Out[32]:
Int64Index([1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386,
1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386,
1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1440, 1440,
1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440,
1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440,
1440, 1440, 1440, 1440, 1358, 1358, 1358, 1358, 1358, 1358, 1358,
1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358,
1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358,
1358, 1358],
dtype='int64')
Then you just need to do the division:
In [33]: df['value_in_question'].div(map_sum)
Out[33]:
date
2019-01-01 0.012987
2019-01-02 0.018759
2019-01-03 0.000000
2019-01-04 0.056277
2019-01-05 0.019481
...
2019-03-27 0.031664
2019-03-28 0.007364
2019-03-29 0.050074
2019-03-30 0.033873
2019-03-31 0.005155
Name: value_in_question, Length: 90, dtype: float64
A: Use Grouper with freq='M'.
The code is:
relative_df = df.groupby(pd.Grouper(freq='M'))\
.value_in_question.apply(lambda x: x.div(x.sum()).mul(100))
It returns a Series with index the same like in original DataFrame
and values equal to relative value_in_question for the current month. | unknown | |
d1816 | train | It depends on the kind of data that is displayed in your ListView.
You can store the data into a SQLite database. This means designing an appropriate schema and implementing create/read/update/delete methods.
The process is too long to be explained here in detail; I invite you to read the Notepad tutorial on the official Android developer site.
A: Depending on the amount of data you are saving you can have many options.
I am assuming you are starting out so it is probably best to go with a straight forward solution utilizing the SQLiteDB instead of preferences or saving to a file.
This is a link to a complete solution for creating the views adapters and database objects.
You could just cut and paste, but read through it and it will be better for you in the long run
Complete ListView Database Tutorial
Android SQLite Basics
List View loaded from XML Resource File
A: In order to do this, you need to think of a strategy for saving data. The most common one is through a SQLite Android DB, nevertheless you might also use Internal Storage if your data is not that complex. Also saving data on Android has been a common topic (check this post)
A: Have a look at the Java Serialization API.
It has its drawbacks (concurrent access....), but maybe it's enough for you.
That's just a quick google hit for that topic.
http://java.sun.com/javase/technologies/core/basic/serializationFAQ.jsp
A: You can use SharedPreferences | unknown | |
d1817 | train | What you're looking for is known as reverse tethering. See https://android.stackexchange.com/questions/2298/how-to-set-up-reverse-tethering-over-usb for a solution.
A: Have you tried sharing your internet connection on your laptop, and connect your phone through it?. Make sure you disable data connection on your phone to assure you are connected through WiFi | unknown | |
d1818 | train | It's just a syntax sugar.
This:
class MyClass()
{
public string SomeProperty{ get; set; } = "SomeValue";
}
will be unwrapped by compiler into this:
class MyClass()
{
public MyClass()
{
_someProperty = "SomeValue";
}
// actually, backing field name will be different,
// but it doesn't matter for this question
private string _someProperty;
public string SomeProperty
{
get { return _someProperty; }
set { _someProperty = value; }
}
}
Reflection is about metadata. There are no any "SomeValue" stored in metatada. All you can do, is to read property value in regular way.
I know I could use a field to get the value
Without instantiating an object, you can get values of static fields only.
To get values of instance fields, you, obviously, need an instance of object.
A: Alternatively, if you need default value of property in reflection metadata, you can use Attributes, one of it from System.ComponentModel, do the work: DefaultValue. For example:
using System.ComponentModel;
class MyClass()
{
[DefaultValue("SomeValue")]
public string SomeProperty{ get; set; } = "SomeValue";
}
//
var propertyInfo = typeof(MyClass).GetProperty("SomeProperty");
var defaultValue = (DefaultValue)Attribute.GetCustomeAttribute(propertyInfo, typeof(DefaultValue));
var value = defaultValue.Value; | unknown | |
d1819 | train | Like Zar's saying you cant use +, you have to do it like this:
background: url("@{theme-images-dir}bx_loader.gif") center center no-repeat #fff;
A: It's a parsing error that's saying that you can't put a '+' in your URL, you need to have a closing parenthesis. I'm betting that string concatenation is not supported. See this to get an alternative to string concatenation: Concatenate strings in Less | unknown | |
d1820 | train | The plus sign is the good thing to do but you have to be sure that one of the strings you are searching for is not in more than 50% of the rows of your table.
Also consider using quotes to match the full expression: +"Anderson City ZIP" | unknown | |
d1821 | train | I understand you're trying to read properties from an assembly that you did not reference in your project. In that case, reflection is the answer.
Read the info from that assembly, wherever the dll is. Load the Settings class, get the Default settings, and access the parameter you want.
As an example, I have a dll called se2.dll, with a parameter that I'd normally access as:
string parameterValue = se2.Settings2.Default.MyParameter;
Now, from a different project, I have to use reflection like this:
// load assembly
System.Reflection.Assembly ass = System.Reflection.Assembly.LoadFrom(@"M:\Programming\se2\se2\bin\Debug\se2.exe");
// load Settings2 class and default object
Type settingsType = ass.GetType("se2.Settings2");
System.Reflection.PropertyInfo defaultProperty = settingsType.GetProperty("Default");
object defaultObject = defaultProperty.GetValue(settingsType, null);
// invoke the MyParameter property from the default settings
System.Reflection.PropertyInfo parameterProperty = settingsType.GetProperty("MyParameter");
string parameterValue = (string)parameterProperty.GetValue(defaultObject, null); | unknown | |
d1822 | train | How to flatten the json into columns as the example above, using SQL in bigquery?
Consider below approach
select _airbyte_ab_id, _airbyte_emitted_at,
json_value(employee, '$.employeeNumber') employeeNumber,
json_value(employee, '$.firstName') firstName,
json_value(employee, '$.lastName') lastName
from your_table,
unnest(json_extract_array(_airbyte_data, '$.employees')) employee
if applied to sample data in your question - output is
A:
... in a perfect world, I would not have to define each column name, but have it run dynamically by reading the "Fields" array
For case when your have fields defined dynamically and potentially even different from row to row - i recommend considering below flattening approach
select _airbyte_ab_id, _airbyte_emitted_at,
md5(employee) employee_hash,
json_value(field, "$.id") key,
regexp_extract(employee, r'"' || json_value(field, "$.id") || '":"(.*?)"') value
from your_table,
unnest(json_extract_array(_airbyte_data, '$.employees')) employee,
unnest(json_extract_array(_airbyte_data, '$.fields')) field
if applied to sample data in your question - output is | unknown | |
d1823 | train | Using interactive messing pass mobile location to apple watch and calculate distance to shown on watch
Refer below apple link for communicating with the counterpart app
https://developer.apple.com/documentation/watchconnectivity/wcsession | unknown | |
d1824 | train | you used, @Transactional annotation can rollback in case if savedAdminUser or savedUser variables is null. Also you Should throw an exception like below.
@Override
@Transactional
public SaveBuilderResponse create(UserDto newUser) throws Exception {
try {
AdminUser adminUser = autoMapper.map(newUser, AdminUser.class);
User userToSave = autoMapper.map(newUser, User.class);
AdminUser savedAdminUser = adminUserRepository.save(adminUser);
User savedUser = userRepository.save(builderToSave);
return new SaveUserResponse(savedUser);
} catch (Exception ex) {
throw ex;
}
}
A: If you don't want to engage with custom exception you can simply do (before the last return statement) :
if (adminUser == null || savedBuilder == null) {
//do whatever you want
return null;
} | unknown | |
d1825 | train | Your query was very nearly correct, but the URL was considered "invalid" as you noted. The solution is to properly escape the query string values.
http://download.finance.yahoo.com/d/quotes.csv?s=@^HSI&f=sl1d1t1c1ohgv&e=.csv
becomes
http://download.finance.yahoo.com/d/quotes.csv?s=%40%5EHSI&f=sl1d1t1c1ohgv&e=.csv
Changing just those two characters into their %-encoded values allows YQL to pull back the CSV data.
select * from csv where url='http://download.finance.yahoo.com/d/quotes.csv?s=%40%5EHSI&f=sl1d1t1c1ohgv&e=.csv'
Aside: YQL doesn't like that the CSV has an empty line at the end of the file, this will cause issues when you try to use the columns where clause. If you're okay with having the columns called col<number> and want to skip the last (empty) row then use and col8 is not null at the end of your query.
A: This is the correct url:
http://quote.yahoo.com/d/quotes.csv?s=<symbol>&f=sl1d1t1c1ohgv&e=.csv
For Coca Cola:
http://quote.yahoo.com/d/quotes.csv?s=KO&f=sl1d1t1c1ohgv&e=.csv
Result: "KO",69.74,"9/2/2011","4:00pm",-0.71,69.7201,69.99,69.50,8765529
For HSI:
http://quote.yahoo.com/d/quotes.csv?s=^HSI&f=sl1d1t1c1ohgv&e=.csv
"^HSI",19616.40,"9/5/2011","4:01am",-596.51,19830.50,19830.50,19567.77,0
Here is an API document:
http://www.gummy-stuff.org/Yahoo-data.htm
A: The above solutions don't fully answer the question unfortunately, you will only get the first 51-52 results (the first page) and not the full index.
I don't think this is possible in raw YQL but you will need to write some code to get the HTML and then loop through each page of components and build your own datatable up from it.
I have tried a few ways and have a C# script that can do it, it would also be trivial to do this in Python and just load it into a pandas dataframe as you go along or just a plain list/tuple if all you want is the symbols to build up a component list for testing a portfolio against.
If people are still interested in this solution I can post the link to it. | unknown | |
d1826 | train | You could prevent this by inserting a copy of the dictionary or list of dictionary
In [1]: from copy import deepcopy
In [2]: from pymongo import MongoClient
In [3]: data = [{'a': 2}, {'a': 3}]
In [4]: with MongoClient() as client:
...: client.test.collection.drop()
...: result = client.test.collection.insert_many(deepcopy(data))
...:
In [5]: result.inserted_ids
[ObjectId('5a819d34d99e830381e025b0'), ObjectId('5a819d34d99e830381e025b1')]
In [6]: data
Out[6]: [{'a': 2}, {'a': 3}] | unknown | |
d1827 | train | UPDATE add text-algin: center to the parent to center the anchor and set border: solid 1px black; to your anchor:
div.container {
position: relative;
height: 110px;
width: 120px;
border: dashed 1px red;
}
div.container div.text {
position: absolute;
bottom: 0px;
right: 0;
left: 0;
text-align: center;
}
a{border: solid 1px black;}
<div class="container">
<div class="text">
<a href="#">Google.com</a>
</div>
</div>
Add Width: 100% and text-align: center
div.container {
position: relative;
height: 110px;
width: 120px;
border: dashed 1px red;
}
div.container div.text {
position: absolute;
bottom: 0px;
text-align: center;
width:100%;
border: solid 1px black;
}
<div class="container">
<div class="text">
<a href="#">Google.com</a>
</div>
</div>
or left: 0;, right: 0; and text-align: center;
div.container {
position: relative;
height: 110px;
width: 120px;
border: dashed 1px red;
}
div.container div.text {
position: absolute;
bottom: 0px;
left: 0;
right: 0;
text-align: center;
border: solid 1px black;
}
<div class="container">
<div class="text">
<a href="#">Google.com</a>
</div>
</div>
or you can combine `margin-left: 50%;` and `transform: translate(-50%)`
div.container {
position: relative;
height: 110px;
width: 120px;
border: dashed 1px red
}
div.container div.text {
position: absolute;
bottom: 0px;
border: solid 1px black;
margin-left: 50%;
-webkit-transform: translate(-50%);
-moz-transform: translate(-50%);
transform: translate(-50%)
}
<div class="container">
<div class="text">
<a href="#">Google.com</a>
</div>
</div>
A: display:block;
margin:auto;
makes elements centered. So you could edit your code to become:
div.container div.text {
bottom: 0px;
border: solid 1px black;
display:block;
margin:auto;
}
A: .text{ width: 100%; text-align: auto; }
The text wrapping div will then be as wide as its container, so text align will work as expected. The reason text-align isn't working for you on your current code is because the "text" div is only as wide as the link, therefore centering its contents does nothing.
A: PROVIDED the link is the bottom/last element in the div-
add this to the div:
text-align: center; //centers the text
and then set the link to:
margin-top: auto; // pushes the text down to the bottom
worked in my case.
Simple and quick, but only works provided your link is the last element in the div. | unknown | |
d1828 | train | Just run the following commands:
apt-get -y remove mysql-server
apt-get -y autoremove
apt-get -y install software-properties-common
add-apt-repository -y ppa:ondrej/mysql-5.6
apt-get update
apt-get -y install mysql-server | unknown | |
d1829 | train | It's a bit unclear what you mean by "choose automat the number" and "select the number", and you didn't tag with your Excel version. But, if you have Excel 2007 or later, perhaps this will help.
Let's assume your first "Date" value (17-Jan-1994) is located in cell A2.
*
*In cell C2, add the following formula, which will return TRUE if the value in A2 is the last day of the month (otherwise it will return FALSE):
=EOMONTH(A2, 0) = A2
*Formula-copy cell C2 all the way down to the last row in the table.
*On the Ribbon's "Data" tab, in the "Sort & Filter" section, click the "Filter" button (it looks like a funnel).
*Click the dropdown that now exists in column C, click the "FALSE" item so as to remove its checkmark, and then click the "OK" button.
*Your table will be filtered so as to display only rows where the "Date" value represents the last day of the month. You can now select the values in column B and copy/paste them, or do whatever you like with them.
Result: | unknown | |
d1830 | train | As Russ said, sometimes you have to add the Content-Type header to explicitly set the mime type; and sometimes, you also have to add a Content-Disposition header, perhaps to a value like
"attachment; filename=doc1.doc"
If Russ' fix doesn't work for you, try adding this additional header.
A: try setting the MIME Type, possibly to application/msword or application/doc
EDIT:
If the server doesn't know the mime type of the file then it defaults to text/plain and displays the bytes. | unknown | |
d1831 | train | Debug and kindly see that the paymentStatus and fulfilledStatus values.As you said, it might be going into the if loop with those conditions satisfying. | unknown | |
d1832 | train | There is an other way, you can define a Class DataHolder and static variable for sharing variable between Activity
Example
class DataHolder {
public static String appleColor = "";
}
Then you can use like this:
Intent intent = new Intent(Main2Activity.this, MainActivity.class);
DataHolder.appleColor = "RED";
Then
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
TextView textView = (TextView)findViewById(R.id.textView7);
Intent intent = getIntent();
textView.setText(DataHolder.appleColor);
}
}); | unknown | |
d1833 | train | calback(get & set) is plain wrong it will change to 0 in JavaScript (try (function () {}) & (function() {}) in chrome console), there is no & operator that will combine functions in JavaScript. type GetSet = Get & Set is a type definition in TypeScript which only means that the definition is a combination of both. However, there is no such thing in JavaScript.
If you want to pass two functions in JavaScript, you have to either use Tuple/Array or Object Literal.
callback([get, set]);
// or
callback({ get, set });
However, In this case, the callback definition should change as follow,
type Get = (<T>(a: RecoilValue<T>) => T)
type Set = (<T>(s: RecoilState<T>, u: (((currVal: T) => T) | T)) => void)
export type GetSet = { get: Get, set: Set };
// some external functions
let get: Get;
let set: Set;
function callback({ get, set }: GetSet) {
}
function perform() {
callback({ get , set }); // <--- this is correct way
}
You can combine get set as a single function as shown below...
function getOrSet(... a: any[]) {
if (a.length === 1) {
return get(a[0]);
}
return set(a[0], a[1]);
}
If you look at how jQuery was organized, you can call same method without parameter to get value and if you pass a parameter, it will set the value.
This might require rewriting many definitions. | unknown | |
d1834 | train | There is a class that comes with asp.net identity called UserManager
this class will help with the user information management you can first find a user using either
*
*FindByIdAsync
*FindByEmailAsync
*FindByUserName
with the user object, you can then update it with new information for the user profile
and then use the method UpdateAsync to update the user information in the database.
when it comes to getting a list of users you can use the IdentityDbContext class to get the list of users from.
A: Create a dbcontext object "context" and you also need to create a model class "UserEdit" and include those fields in it which you wants to edit.
private ApplicationDbContext context = new ApplicationDbContext();
// To view the List of User
public ActionResult ListUsers ()
{
return View(context.Users.ToList());
}
public ActionResult EditUser(string email)
{
ApplicationUser appUser = new ApplicationUser();
appUser = UserManager.FindByEmail(email);
UserEdit user = new UserEdit();
user.Address = appUser.Address;
user.FirstName = appUser.FirstName;
user.LastName = appUser.LastName;
user.EmailConfirmed = appUser.EmailConfirmed;
user.Mobile = appUser.Mobile;
user.City = appUser.City;
return View(user);
}
[HttpPost]
public async Task<ActionResult> EditUser(UserEdit model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var manager = new UserManager<ApplicationUser>(store);
var currentUser = manager.FindByEmail(model.Email);
currentUser.FirstName = model.FirstName;
currentUser.LastName = model.LastName;
currentUser.Mobile = model.Mobile;
currentUser.Address = model.Address;
currentUser.City = model.City;
currentUser.EmailConfirmed = model.EmailConfirmed;
await manager.UpdateAsync(currentUser);
var ctx = store.Context;
ctx.SaveChanges();
TempData["msg"] = "Profile Changes Saved !";
return RedirectToAction("ListUser");
}
// for deleting a user
public ActionResult DeleteUser(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var user = context.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(context.Users.Find(id));
}
public async Task<ActionResult> UserDeleteConfirmed(string id)
{
var user = await UserManager.FindByIdAsync(id);
var result = await UserManager.DeleteAsync(user);
if (result.Succeeded)
{
TempData["UserDeleted"] = "User Successfully Deleted";
return RedirectToAction("ManageEditors");
}
else
{
TempData["UserDeleted"] = "Error Deleting User";
return RedirectToAction("ManageEditors");
}
}
Below is the View for ListUser:
@model IEnumerable<SampleApp.Models.ApplicationUser>
@{
ViewBag.Title = "ListUsers";
}
<div class="row">
<div class="col-md-12">
<div>
<h3>@ViewBag.Message</h3>
</div>
<div>
<h2>ManageEditors</h2>
<table class="table">
<tr>
<th>
S.No.
</th>
<th>
Email
</th>
<th>
EmailConfirmed
</th>
<th>
FirstName
</th>
<th>
LastName
</th>
<th>
Mobile
</th>
<th></th>
</tr>
@{ int sno = 1;
foreach (var item in Model)
{
<tr>
<td>
@(sno++)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@Html.DisplayFor(modelItem => item.EmailConfirmed)
</td>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Mobile)
</td>
<td>
@Html.ActionLink("Edit", "EditUser", new { email=item.Email})
@Html.ActionLink("Delete", "DeleteUser", new { id = item.Id })
</td>
</tr>
}
}
</table>
</div>
</div>
</div>
// below is my UserEdit Model
public class UserEdit
{
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Mobile")]
public string Mobile { get; set; }
[Display(Name = "Address")]
public string Address { get; set; }
[Display(Name = "City")]
public string City { get; set; }
public bool EmailConfirmed { get; set; }
}
//below is my IdentityModel.cs class which have ApplicationDbContext class
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace SampleApp.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
//Extra column added to auto generated Table by Code First approach (ASPNETUSERS) by Entity Framework
public string FirstName { get; set; }
public string LastName { get; set; }
public string DOB { get; set; }
public string Sex { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Mobile { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
}
Hope this help you :) | unknown | |
d1835 | train | I feel that your code is not very well organized. Without entering into too much trouble, I would use obce_nad_300_sheet as an object an move it around. Like this:
def create_footer(sheet, suma_cell, starting_row, flag):
"""
Function to creade footer of listok
flag = 0 / 1 / 2 (data sheet where to write header)
"""
sheet.write(row, 4, 'Test')
I don't know how the library works however. Does it "commit" the changes with a call to write or need some sort of a save or commit method after that?
Without knowing too much about your situation nor the library, I would probably create an object inheriting from xlsxwriter.Workbook, store the sheets in an attribute of that object (probably a dict of {"sheet_name": WorkSheet}) and write the methods in the object. It could look like this:
class MyWorksheet(xlsxwriter.Workbook):
def __init__(self, *args, **kwargs):
[...]
super(MyWorksheet, self).__init__(*args, **kwargs)
self.sheets = {}
[...]
def add_worksheet(self, name):
[...]
self.sheets[name] = super(MyWorksheet, self).add_worksheet(name)
[...]
def create_footer(self, sheet_name, suma_cell, starting_row, flag):
[...]
self.sheets[sheet_name].write(row, 4, "Test")
[...]
And then in what you call main file do:
my_sheet = MyWorksheet()
my_sheet.add_worksheet("Listky_obce_nad_300")
my_sheet.create_footer("Listky_obce_nad_300", suma, starting, flag) | unknown | |
d1836 | train | When you declare fields and variables, it's usually helpful to give them a more specific static type than Object. Because you have declared mTitleText as an Object, the compiler only knows how to invoke methods on the general Object class definition. setText is not such a method, so it's not legal to call it without a cast or other trickery.
What you should do is figure out the type that your field should be. I don't know Android, but I presume that there is a text label class which defines your setText method. If you change your fields to be defined as that,
private EditText mTitleText;
you will find that things should work much better :-)
A: Unless you set those two fields somewhere else, they are not being initialized. So when you use them later, they are null and are causing exceptions. Java reference types initialize to null. Basic data types, which are not nullable, initialize to 0.
A: Your mBodyText field needs to be typed to allow access to the setText method.
e.g:
private BodyText mBodyText;
A: its not working because your objects not initialized.
mTitleText text should be a TextView
then you need to initialize it
mTitleText = findViewById( R.id.yourviewid );
and then do
mTitleText.setText(title);
A: They are marked as private so you can't the them outside of your class. If you want to get access outside of your class you have to use the keyword public in front of your field. BUT this is not recommended use properties instead
A: In this case you need to assign values to the two member variables. I believe the NoteEdit class has a layout xml file associated with it. You need to assign the text field objects from that layout to the objects before you try to reference their properties.
mTitleText = ( TextView ) findViewById( R.id.name_of_the_field_in_the_layout_file )
The answer above is also correct. You should assign types to those variables at the top of your class, not just make them Objects
A: Declaring the name and type of a reference is one thing; initializing it to point to a valid memory location on the heap is another. You need to initialize data members in a constructor for your class.
The default constructor initializes references to null by default. If you haven't written a constructor to initialize your data member references, that could be an explanation why you're having trouble. | unknown | |
d1837 | train | In RedisCacheManager ,property usePrefix default value is false,so we should set usePrefix=true in JavaConfig:
@Bean
public RedisCacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
cacheManager.setUsePrefix(true);
return cacheManager;
} | unknown | |
d1838 | train | #include<string>
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;
class HotelRoom
{
private:
int roomnum; // Room numbers
int roomcap; // Room capacity
int roomoccuoystst = 0;
int maxperperroom;
double dailyrate;
public:
HotelRoom()
{
roomcap = 0;
maxperperroom = 2;
dailyrate = 175;
}
int gettotal = 0;
int gettotallist = 0;
string room;
string guestroom, message;
void viewrooms()
{
char viewselect, back;
cout << "Which room list would you like to view ?. 1 - Add rooms, 2 - Reserved rooms : ";
cin >> viewselect;
switch (viewselect)
{
case '1':
viewaddromm();
break;
case '2':
viewresromm();
break;
default:
cout <<
"Please select from the option provided or go back to the main menu. 1 - view rooms, 2 - to the mail menu or any other key to exit the program : ";
cin >> back;
switch (back)
{
case '1':
viewrooms();
break;
case '2':
menu();
break;
default:
exitpro();
}
}
}
void viewresromm()
{
string roomtochange, items;
string guestroomdb;
// int newaccupancy;
// char decisionmade,savinf;
string fname, lname, nationality;
string checkaddroom;
ifstream getdatafromaddroom; // creation of the ifstream object
getdatafromaddroom.open("reserveroom.out");
if (getdatafromaddroom.fail()) // if statement used for error
// checking
{
cout << "Could not open file" << endl; // message that will be
// printed if the program
// cannot open the file
return;
}
cout << endl;
cout << "First Name" << '-' << "Last Name" << '-' << "Nationality" << '-' << "Guest(s)" <<
'-' << "Room #" << endl;
cout << "-------------------------------------------------------" << endl;
// string items;
while (!getdatafromaddroom.eof())
{
// getdatafromaddroom
// >>fname>>lname>>nationality>>occup>>guestroomdb;
getline(getdatafromaddroom, items);
// cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<'
// '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<'
// '<<setw(9)<<guestroomdb<<endl;
gettotallist++;
if (getdatafromaddroom.eof())
break;
cout << items << endl;
}
for (int getlist = 0; getlist < gettotallist; getlist++)
{
cout << items << endl;
// cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<'
// '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<'
// '<<setw(9)<<guestroomdb<<endl;
}
}
void viewaddromm()
{
// int occup,rmchoose,up;
string roomtochange;
string guestroomdb;
// int newaccupancy;
// char decisionmade,savinf;
string fname, lname, nationality;
string checkaddroom;
fstream getdatafromaddroom; // creation of the ifstream object
getdatafromaddroom.open("addroom.out");
if (getdatafromaddroom.fail()) // if statement used for error
// checking
{
cout << "Could not open file" << endl; // message that will be
// printed if the program
// cannot open the file
return;
}
cout << endl;
cout << "First Name" << '-' << "Last Name" << '-' << "Nationality" << '-' << "Guest(s)" <<
'-' << "Room #" << endl;
cout << "-------------------------------------------------------" << endl;
string items;
while (!getdatafromaddroom.eof())
{
// getdatafromaddroom
// >>fname>>lname>>nationality>>occup>>guestroomdb;
getline(getdatafromaddroom, items);
// cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<'
// '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<'
// '<<setw(9)<<guestroomdb<<endl;
gettotallist++;
if (getdatafromaddroom.eof())
break;
cout << items << endl;
}
for (int getlist = 0; getlist < gettotallist; getlist++)
{
cout << items << endl;
// cout<<setw(5)<<fname<<' '<<setw(10)<<lname<<'
// '<<setw(10)<<nationality<<' '<<setw(10)<<occup<<'
// '<<setw(9)<<guestroomdb<<endl;
}
}
void exitpro()
{
cout << "Program closing......Goodbye" << endl;
// system("Pause");
exit(0);
}
void Addroom()
{
std::string mess = __func__;
mess += " is not yet implimented.";
throw new std::logic_error(mess.c_str());
}
void reserveroom()
{
std::string mess = __func__;
mess += " is not yet implimented.";
throw new std::logic_error(mess.c_str());
}
void modifyroom()
{
std::string mess = __func__;
mess += " is not yet implimented.";
throw new std::logic_error(mess.c_str());
}
void menu()
{
while (true)
{
char menuchoice;
cout << "[-------------------------------------------------------]" << endl;
cout << "[-Welcome to the hotel booking and reseration menu-]" << endl;
cout << "[--------------------------------------------------------]" << endl;
cout << setw(30) << "Addroom -- 1" << endl;
cout << setw(30) << "Reserve a room -- 2" << endl;
cout << setw(30) << "Modify a room -- 3" << endl;
cout << setw(30) << "View rooms -- 4" << endl;
cout << setw(30) << "Exit -- 5" << endl;
cin >> menuchoice;
switch (menuchoice)
{
case '1':
Addroom();
break;
case '2':
reserveroom();
break;
case '3':
modifyroom();
break;
case '4':
viewrooms();
break;
case '5':
exitpro();
}
}
}
};
int main()
{
try
{
HotelRoom room;
room.menu();
}
catch(std::logic_error * ex)
{
std::cout << ex->what();
}
}
you have a lot more to go with this project. I've fixed the portion you specifically asked about and its now a runninng application with somewhat approperate diagnostics. I'm not going to get too deep into how this language works but you have several functions that were not implimented, missing return types, and just general logic errors like trying to use a file after you determined it wasnt open. it runs now, and you can get a clear indication of what you need to complete. You also had several unused varables.
i added , at minimal,
void Addroom()
{
std::string mess = __func__;
mess += " is not yet implimented.";
throw new std::logic_error(mess.c_str());
}
void reserveroom()
{
std::string mess = __func__;
mess += " is not yet implimented.";
throw new std::logic_error(mess.c_str());
}
void modifyroom()
{
std::string mess = __func__;
mess += " is not yet implimented.";
throw new std::logic_error(mess.c_str());
}
and a return type to menu.
`void menu()
you cannot call functions you have not yet written, and all functions have a return type even if they return nothing.
Good luck! | unknown | |
d1839 | train | You'll need to call describe_log_groups() and do the filtering within your code.
The only filter available is the ability to specify a logGroupNamePrefix. | unknown | |
d1840 | train | It doesn't work like that. Your return is not allowed there because you are inside a coroutine context on those { }
But actually the best way to do it is to create some method and handle that response instead of returning it. On your case I'm a little confused:
Transform:
GlobalScope.launch(Dispatchers.Main) {
lateinit var response: Response<Void>
response = executeOperations.await()
return response
}
Into:
GlobalScope.launch(Dispatchers.IO) {
lateinit var response: Response<Void>
response = executeOperations.await()
withContext(Dispatchers.Main){
handleResponse(response)
}
}
Plus, your heavy work musn't happen in the Dispatchers.Main but in Dispatchers.IO | unknown | |
d1841 | train | Yes, you can actually use Logic Apps in this case. You can connect to Salesforce to SAP. Configuration depends on the requirements that you have.
You can even use the web Services by Exposing SAP functionality to the cloud with Azure App Services which will use a combination of API Apps to create a Logic App that exposes BAPI functionality to an external website.
A: I would not recommend an Salesforce to SAP integration from scratch. This is too much effort and you need to take care of things like error handling, delta load and security. Instead I would propose to use a tool that was made for such scenarios.
In case you only need data replication, you can go with something like SAP CPI or Mulesoft. They even offer templates, that make your life easier. You should be aware that these options can be expensive in regards to their licenses/subscriptions.
Another way would be a solution like Vigience Overcast, that offers data replication as well, but also real time access to SAP from within Salesforce. Overcast goes beyond exchanging data between the two systems, but also allows you to create the user interface. They even have pre-defined, ready-to-use apps for the most common use cases. | unknown | |
d1842 | train | You need to wrap DB::select around it. Something like this should work.
$rates = DB::select(DB::raw('SELECT
mid,
x.qty_t/x.qty_total,
x.qty_stddev,
x.qty_total,
FROM
(SELECT
mid,
SUM(CASE WHEN (mtc="qty") THEN 1 ELSE 0 END) AS qty_total,
SUM(CASE WHEN (mtc="qty") THEN rte ELSE 0 END) AS qty_t,
STDDEV(CASE WHEN (mtc="qty") THEN rte ELSE 0 END) AS qty_sd
FROM
t_r
GROUP BY
mid) x'))->get(); | unknown | |
d1843 | train | You're missing the @endif directive. Your blade syntax needs to be:
@if(Auth::user())
<li>{{ HTML::link('logout', 'Logout') }}</li>
@else
<li>{{ HTML::link('login','login') }}</li>
@endif
Without the @endif directive, you'll get the "unexpected end of file" error. | unknown | |
d1844 | train | You should test the behaviour of this API. This means you should care about the response rather than the implementation details. You should pass in an input, such as req.body, to assert whether the result is in line with your expectations.
Since your code cannot be executed, I will arbitrarily add some code to demonstrate
E.g.
a.router.js:
import express from 'express';
const router = express.Router();
const _ = require('lodash');
router.use(express.json());
router.post('/', async (req, res, next) => {
try {
let data = req.body;
console.log('data: ', data);
if (!_.isEqual(data, { hello: 'hello' })) {
res.send('Not Equal');
} else {
throw new Error('Equal');
}
} catch (e) {
res.send(`Error: ${e.message}`);
}
});
export default router;
a.router.test.js:
import a from './a.router';
import express from 'express';
import supertest from 'supertest';
describe('API Calls', () => {
const app = express();
let request;
beforeAll(() => {
app.use(a);
request = supertest(app);
});
test('Successful call to post /', async () => {
const body = {
Hello: 'Not Hello',
};
const res = await request
.post('/')
.set('Content-Type', 'application/json')
.set('Authorization', 'authToken')
.send(body);
expect(res.text).toEqual('Not Equal');
});
test('should handle error', async () => {
const body = {
hello: 'hello',
};
const res = await request
.post('/')
.set('Content-Type', 'application/json')
.set('Authorization', 'authToken')
.send(body);
expect(res.text).toEqual('Error: Equal');
});
});
test result:
PASS examples/67536129/a.router.test.js (8.606 s)
API Calls
✓ Successful call to post / (48 ms)
✓ should handle error (5 ms)
console.log
data: { Hello: 'Not Hello' }
at examples/67536129/a.router.js:9:13
console.log
data: { hello: 'hello' }
at examples/67536129/a.router.js:9:13
-------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
a.router.js | 100 | 100 | 100 | 100 |
-------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 9.424 s | unknown | |
d1845 | train | client is an instance variable of CitiesDialog
every CitiesDialog that you make is going to have it's own client.
That kind of initialization is just for when you first make an instance of your class. you can change client afterwards.
A: This is perfectly normal to see in Java.
What you see here is private AsyncHttpClient, which is by itself just a class variable.
Then you see the declaration new AsyncHttpClient(), which gets assigned to client. This will happen for every new object that gets created.
To address whether this is the norm? I think yes, a common use case is lists, it is best to initialize them as early as possible:
public class A {
private final List<String> list = new ArrayList<>();
}
This will prevent that you get a NPE at a later point, because you have forgotten to declare the list.
One other thing that also helps is to declare the field final if it should never be changed after assignment, then it is also ensured by the compiler that the field gets initialized either in the declaration or in a constructor.
A:
Does each instance of CititiesDialog have a separate client object?
Yes, since it is not marked as static.
is this the norm in Java? to initialize variables outside the scope of constructors/methods, etc...
It's not abnormal, especially if you have multiple constructors and do not want to duplicate initialization.
A:
And lastly, is this the norm in Java? to initialize variables outside the scope of constructors/methods
Actually this is just syntactic sugar which eliminates the need to repeat the same initialization in each costructor. When compiled, the initialization code will become a part of each constructor (except those which delegate to other constructors). | unknown | |
d1846 | train | You cannot reference the same table in a subquery, but you can instead do it in a JOIN (which is allowed in UPDATE and DELETE statements):
UPDATE person a
JOIN (SELECT MAX(id) AS id FROM person WHERE address = 'LA, California') b
ON a.id = b.id
SET a.age = 25
Another way you can do it is by using the ORDER BY / LIMIT technique:
UPDATE person
SET age = 25
WHERE address = 'LA, California'
ORDER BY id DESC
LIMIT 1
A: You can try as:
UPDATE person t1
INNER JOIN (SELECT MAX(id) AS id FROM person
WHERE t2.address = 'LA, California') t2
ON t1.id = t2.id
SET t1.age = 25;
or
SELECT MAX(t2.id)
INTO @var_max_id
FROM person t2
WHERE t2.address = 'LA, California';
UPDATE person t1
SET t1.age = 25
WHERE t1.id = IFNULL(@var_max_id, -1); | unknown | |
d1847 | train | I've not used the spring.main.allow-bean-definition-overriding=true property, but specifying specific config in a test class has worked fine for me as a way of switching between objects in different tests.
You say...
It turns out that the injected GameMap into my test is a mock instance from TestConfiguration instead of the real thing from RealMapTestConfiguration.
But RealMapTestConfiguration does return a mock
package com.stackoverflow.impl;
@Configuration
public class RealMapTestConfiguration {
@Bean
public GameMap gameMap() {
return Mockito.mock(GameMap.class);
}
}
A: I think the problem here is that including ContextConfiguration nullifies (part of) the effect of @SpringBootTest. @SpringBootTest has the effect of looking for @SpringBootConfiguration in your application (starting from the same package, I believe). However, if ContextConfiguration is applied, then configurations are loaded from there.
Another way of saying that: because you have ContextConfiguration in your test, scanning for @Configuration classes is disabled, and TestConfiguration is not loaded.
I don't think I have a full picture of your configuration setup so can't really recommend a best practice here, but a quick way to fix this is to add TestConfiguration to your ContextConfiguration in your test. Make sure you add it last, so that it overrides the bean definitions in the other two configurations.
The other thing that might work is removing @ContextConfiguration entirely and letting the SpringBootApplication scanning do its thing - that's where what you said about the bean definition that is closest may apply.
A: In that case just don't use @Configuration on configuration class and import it to the test manually using @Import, example:
@SpringBootTest
@Import(MyTest.MyTestConfig.class)
public class MyTest {
@Autowired
private String string;
@Test
public void myTest() {
System.out.println(string);
}
static class MyTestConfig {
@Bean
public String string() {
return "String";
}
}
} | unknown | |
d1848 | train | These are the crucial parts of my revised implementation, with ideas drawn from the commenters:
*
*Convert object to struct, shrink data types to smaller ints, and rearrange so that the object should fit into a 64-bit value, which is better for a 64-bit machine:
struct Indices
{
/// <summary>
/// Index into source vector of source uint to read.
/// </summary>
public readonly int iFromUintVector;
/// <summary>
/// Index into target vector of target byte to write.
/// </summary>
public readonly short iToByteVector;
/// <summary>
/// Index into source uint of source bit to read.
/// </summary>
public readonly byte iFromUintBit;
/// <summary>
/// Index into target byte of target bit to write.
/// </summary>
public readonly byte iToByteBit;
public Indices(int fromUintVector, byte fromUintBit, short toByteVector, byte toByteBit)
{
iFromUintVector = fromUintVector;
iFromUintBit = fromUintBit;
iToByteVector = toByteVector;
iToByteBit = toByteBit;
}
}
*Sort the PrecomputedIndices so that I write each target byte and bit in ascending order, which improves memory cache access:
Comparison<Indices> sortByTargetByteAndBit = (a, b) =>
{
if (a.iToByteVector < b.iToByteVector) return -1;
if (a.iToByteVector > b.iToByteVector) return 1;
if (a.iToByteBit < b.iToByteBit) return -1;
if (a.iToByteBit > b.iToByteBit) return 1;
return 0;
};
Array.Sort(PrecomputedIndices, sortByTargetByteAndBit);
*Unroll the loop so that a whole target byte is assembled at once, reducing the number of times I access the target array:
public byte[] Interleave(uint[] vector)
{
var byteVector = new byte[BytesNeeded + 1]; // An extra byte is needed to hold the extra bits and a sign bit for the BigInteger.
var extraBits = Bits - BytesNeeded << 3;
int iIndex = 0;
var iByte = 0;
for (; iByte < BytesNeeded; iByte++)
{
// Unroll the loop so we compute the bits for a whole byte at a time.
uint bits = 0;
var idx0 = PrecomputedIndices[iIndex];
var idx1 = PrecomputedIndices[iIndex + 1];
var idx2 = PrecomputedIndices[iIndex + 2];
var idx3 = PrecomputedIndices[iIndex + 3];
var idx4 = PrecomputedIndices[iIndex + 4];
var idx5 = PrecomputedIndices[iIndex + 5];
var idx6 = PrecomputedIndices[iIndex + 6];
var idx7 = PrecomputedIndices[iIndex + 7];
bits = (((vector[idx0.iFromUintVector] >> idx0.iFromUintBit) & 1U))
| (((vector[idx1.iFromUintVector] >> idx1.iFromUintBit) & 1U) << 1)
| (((vector[idx2.iFromUintVector] >> idx2.iFromUintBit) & 1U) << 2)
| (((vector[idx3.iFromUintVector] >> idx3.iFromUintBit) & 1U) << 3)
| (((vector[idx4.iFromUintVector] >> idx4.iFromUintBit) & 1U) << 4)
| (((vector[idx5.iFromUintVector] >> idx5.iFromUintBit) & 1U) << 5)
| (((vector[idx6.iFromUintVector] >> idx6.iFromUintBit) & 1U) << 6)
| (((vector[idx7.iFromUintVector] >> idx7.iFromUintBit) & 1U) << 7);
byteVector[iByte] = (Byte)bits;
iIndex += 8;
}
for (; iIndex < PrecomputedIndices.Length; iIndex++)
{
var idx = PrecomputedIndices[iIndex];
var bit = (byte)(((vector[idx.iFromUintVector] >> idx.iFromUintBit) & 1U) << idx.iToByteBit);
byteVector[idx.iToByteVector] |= bit;
}
return byteVector;
}
*
*#1 cuts the function from taking up 35% of the execution time to 30% of the execution time (14% savings).
*#2 did not speed the function up, but made #3 possible.
*#3 cuts the function from 30% of exec time to 19.6%, another 33% in savings.
Total savings: 44%!!! | unknown | |
d1849 | train | This feature is provided in the System.Windows.Forms.ComboBox. Check out the AutoCompleteMode
To do the things you described, you need to set the Items property of the ComboxBox to have all your options "United Kingdom", "United States", etc. Then, change the AutoCompleteMode to "SuggestAppend". Change the AutoCompleteSource to "ListItems" | unknown | |
d1850 | train | For future users that which may have the same problem, my problem was that args send the path with "" like "http://something" and if we put get("/slingshot/node/content/workspace/SpacesStore/f32afa20-4c73-4e6c-84e4-1c12d5964a95/txt.txt") don't have "". So, we can put the args on the string and make string.substring(1,string.length-1) to delete "". | unknown | |
d1851 | train | function countTotalRecords(type){
var count =0;
var i=0;
var j=1000;
var columns = [];
var filters= [];
columns.push(new nlobjSearchColumn('internalid'));
var search = nlapiCreateSearch(type,filters,columns);
var resultSet = search.runSearch();
do{
var result =resultSet.getResults(i,j);
count += result.length;
i=j;
j=j+1000;
}while(result.length == 1000);
return count;
}
I found a way to count the total Records including line items. Thanks | unknown | |
d1852 | train | In V1 you source a file without specifying the encoding of that file (test_abc.R). The "encoding"-section of source help says:
By default the input is read and parsed in the current encoding of the R session. This is usually what it required, but occasionally re-encoding is needed, e.g. if a file from a UTF-8-using system is to be read on Windows (or vice versa).
The "Umlaute" can't be read correctly and function compare_text returns c(c, c2) because c != c2 is TRUE.
In V2 the "Umlaute" are read correctly and compare_text function returns null (no difference is found).
It's R itself that reads the file within the source function. R uses the default encoding of the OS. On Windows, this is (mostly?) "Windows code page 1252", which differs from UTF-8. You can test it on your machine with Sys.getlocale(). That's why you have to tell R that the file you want to source is encoded UTF-8 | unknown | |
d1853 | train | If I correctly understood your model you can set it in .onReceive modifier, like
.onAppear {
self.userProfile.fetchWithAF()
}
.onReceive(self.userProfile.$userProfileModel) { model in
self.fullName = model?.payload[0].fullName ?? ""
} | unknown | |
d1854 | train | In theory you could create the layout with all the buttons available - if they are only a few -, and hide the selectable ones with android:visibility="gone" in xml.
Later on you keep track of the selections in an internal Object or ArrayList, and change visibility for the selected buttons in each subsequent Activity's onCreate or onResume.
Another solution is to create an xml with the spare space for the additional buttons, and add them from code. In this case you have to keep track of all information about the added buttons in code, not just the states, but the theory is the same.
If you want to save the layout over application restarts as well, you will have to save that information yourself, Android does not have this built-in. | unknown | |
d1855 | train | If I understand correctly you can write those sql queries to a script-or bunch of script files- file and directly run on mysql without copy/paste.
mysql -u user -ppass < script.sql | unknown | |
d1856 | train | I have load Transaction class from containers classloader and it worked.
final KieSession kSession = container
.getKieContainer()
.newKieBase(configuration)
.newKieSession();
Class<?> classA = container.getKieContainer().getClassLoader().loadClass("com.example.Transaction");
Object transaction = classA.getDeclaredConstructor().newInstance();
kSession.insert(transaction);
kSession.fireAllRules(); | unknown | |
d1857 | train | You can still do it, just first convert string to number.
var value = "16865112.0";
value = +value; // convert to number
var fV = Number(value).toLocaleString();
console.log(fV);
A: You are calling Number.toLocaleString on String. You need to convert it to Number first by calling parseInt or Number() constructor (you can change your current locale too).
$.get("https://api.coinmarketcap.com/v1/ticker/", function(data, status) {
for (var i = 0; i < data.length - 1; i++) {
if (data[i].id == "bitcoin") {
$("#total_supply").html(Number(data[i].total_supply).toLocaleString('en-US'));
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="total_supply"></div> | unknown | |
d1858 | train | You can use recursion and passing node and depth as parameters
function Node(code, parent) {
this.code = code;
this.children = [];
this.parentNode = parent;
}
Node.prototype.addNode = function (code) {
var l = this.children.push(new Node(code, this));
return this.children[l-1];
};
let result = [], depth = {};
function dfs(node){
node.depth = 0;
let stack = [node];
while(stack.length > 0){
let root = stack[stack.length - 1];
let d = root.depth;
result[d] = result[d] || [];
result[d].push(root.code);
stack.length--;
for(let element of root.children){
element.depth = root.depth + 1;
stack.push(element);
}
}
}
var tree = new Node("ROOT");
tree.addNode("A1").addNode("A2").addNode("A3").addNode("A4");
tree.addNode("B1").addNode("B2").addNode("B3");
tree.addNode("C1").addNode("C2");
dfs(tree);
console.log(result.reverse());
A: It is possible to write this in a recursive way which would benefit from tail optimisation
function reduceTree(tree) {
const getCode = n => n.code;
const _reduce = (level = [tree], acc = [[getCode(tree)]], depth = 1) => {
const children = level.reduce((a, e) => a.concat(e.children), []);
if (!children.length) {
return acc;
}
acc[depth] = children.map(getCode);
return _reduce(children, acc, depth + 1);
};
return _reduce().reverse();
}
reduceTree(tree);
/*
[
["A4"],
["A3", "B3"],
["A2", "B2", "C2"],
["A1", "B1", "C1"],
["ROOT"]
]
*/
A: That's it - thanks to marvel308 for pointing out that there is required an additional helper node.depth
function Node(code, parent) {
this.code = code;
this.depth = -1;
this.children = [];
this.parentNode = parent;
}
Node.prototype.dfs= function() {
var result = [], stack = [];
this.depth = 0;
stack.push(this);
while(stack.length > 0) {
var n = stack[stack.length - 1], i = n.depth;
if(!result[i]) result.push([]);
result[i].push(n); /* get node or node.code, doesn't matter */
stack.length--;
var children = n.children;
/* keep the original node insertion order, by looping backward */
for(var j = n.children.length - 1; j >= 0; j--) {
var c = children[j];
c.depth = n.depth + 1;
stack.push(c);
}
}
return result.reverse(); /* return an array */
}; | unknown | |
d1859 | train | The answer, sadly, is that Xcode simply doesn't support scaling in AppKit storyboards. It only supports scaling in UIKit storyboards.
You should file a feature request at https://bugreport.apple.com. | unknown | |
d1860 | train | Hah... I made it work... Simply changed ::base.html.twig with AcmeHelloBundle::base.html.twig ;) | unknown | |
d1861 | train | This might do the trick:
$res = array();
for ($i = 0; $i + 1 < count($arr); $i = $i + 2) {
$res[$arr[$i]] = $arr[$i + 1];
}
A: Assuming the array has even number of members you can do:
for($i=0 ; $i<count($arr)-1 ; $i+=2) {
$new_array[$arr[$i]] = $arr[$i+1];
}
Where $arr is your existing array and $new_array is the new resultant associative array.
Working Ideone link
A: Try something like this:
$new_arr = array();
for ($i = 0; $i < count($arr); $i += 2) {
$new_arr[$arr[$i]] = $arr[$i + 1];
}
Note that the value indexed by the last key is undefined if $arr contains an odd number of items.
A: Of course it's possible.
function array_pair($arr) {
$retval = array();
foreach ($arr as $a) {
if (isset($key)) {
$retval[$key] = $a;
unset($key);
}
else {
$key = $a;
}
}
return $retval;
}
Or you could do:
function array_pair($arr) {
$retval = array();
$values = array_values($arr);
for ($i = 0; $i < count($values); $i += 2)
$retval[$values[$i]] = $values[$i + 1];
return $retval;
}
A: An approach with odd / even indices.
$new_arr = array();
$key = NULL;
for($i=0; $i<count($arr); $i++){
if($i % 2){ // even indices are values, store it in $new_arr using $key
$new_arr[ $key ] = $arr[$i];
}
else{ // odd indices are keys, store them for future usage
$key = $arr[$i];
}
}
Note: the last value will be ignored if the array length is odd. | unknown | |
d1862 | train | Try to run npm install jest-serializer before doing npm start. If that is still not working,
rm -rf node modules
npm install
npm start | unknown | |
d1863 | train | First of all you have to have function that does the calculation, so you pass that function to the test case.
Example:
import unittest
# Defined the function that does the calculation
def sum_numbers(x, y):
return x + y
class TestSum(unittest.TestCase):
def test_sum(self):
self.assertEqual(sum_numbers(2, 2), 4)
if __name__ == '__main__':
unittest.main()
Now this test will evaluate to ok and you can add more test to test_sum | unknown | |
d1864 | train | You can clean your index, i.e. remove extra strings before loc, and then use isin method as suggested by @not_a_robot:
s = set(['loc.08652', 'loc.14331', 'loc.08650', 'loc.06045', 'loc.10160', 'loc. 08656']
# the set has been cleaned here so that it doesn't contain spaces
df[df.index.str.replace(".*(?=loc)", "").isin(s)] | unknown | |
d1865 | train | It indeed looks like a bug. Two possible (nasty) workarounds:
Via Application.OnMessage:
procedure TMainForm.ApplicationEventsMessage(var Msg: tagMSG;
var Handled: Boolean);
var
P: TPoint;
begin
if Msg.message = WM_LBUTTONDOWN then
if Screen.ActiveControl <> nil then
if Screen.ActiveControl.ClassNameIs('TElInpEdit') then
begin
GetCursorPos(P);
with Screen.ActiveControl do
if not PtInRect(ClientRect, ScreenToClient(P)) then
Perform(WM_KILLFOCUS, 0, 0);
end;
end;
Or subclass the component:
type
TElXTree = class(ElXTree.TElXTree)
private
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
end;
TForm1 = class(TForm)
ElXTree1: TElXTree;
...
procedure TElXTree.CMMouseLeave(var Message: TMessage);
var
P: TPoint;
begin
GetCursorPos(P);
if not PtInRect(ClientRect, ScreenToClient(P)) then
if Screen.ActiveControl <> nil then
if Screen.ActiveControl.ClassNameIs('TElInpEdit') then
Screen.ActiveControl.Perform(WM_KILLFOCUS, 0, 0);
inherited;
end;
Note: this one is nót preferred since it alters the behaviour of the component: just hovering the mouse outside of the grid closes the inplace editor. But I added it because it might bring others to other solutions.
A: It can be a focus problem. Look at code you have written in OnExit OnEnter methods of your form. | unknown | |
d1866 | train | It has to be available by an URL. The D:\MySharedHTML\test.html is very definitely not a valid URL. A valid URL look like this http://localhost:8080/MySharedHTML/test.html.
Whether to use <jsp:include> or <c:import> depends on whether the URL is an internal or an external URL. The <jsp:include> works only on internal URLs (thus, resources in the same webapp, also the ones privately hidden in /WEB-INF). The <c:import> works additionally also on external URLs (thus, resources in a completely different webapp, but those have to be publicly accessible; i.e. you have got to see the desired include content already when copypasting the URL in browser's address bar).
In your particular case, you seem to have it elsewhere in the server's local disk file system which is not available by a true URL at all. In that case you've basically 2 options:
*
*Add the root folder of that path as a virtual host to the server configuration. How to do that depends on the server make/version which you didn't tell anything about. To take Tomcat as an example, that would be a matter of adding the following entry to its /conf/server.xml:
<Context docBase="D:\MySharedHTML" path="/MySharedHTML" />
This way all of the folder's contents is available by http://localhost:8080/MySharedHTML/*, including the test.html. This way you can use <c:import> on it (note: <jsp:include> is inapplicable as this is not in the same webapp).
<c:import url="/MySharedHTML/test.html" />
*Create a servlet which acts as a proxy to the local disk file system. Let's assume that you're using Servlet 3.0 / Java 7 and that you can change ${Htmlpath} variable in such way that it merely returns test.html, then this should do:
@WebServlet("/MySharedHTML/*")
public class PdfServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filename = request.getPathInfo().substring(1);
File file = new File("D:\\MySharedHTML", filename);
response.setHeader("Content-Type", getServletContext().getMimeType(filename));
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "inline; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
Files.copy(file.toPath(), response.getOutputStream());
}
}
(when not using Servlet 3.0 / Java 7 yet, just fall back to the obvious web.xml regisration and InputStream/OutputStream loop boilerplate)
As the servlet runs in the same webapp, <jsp:include> should work just fine:
<jsp:include page="/MySharedHTML/${HtmlFilename}" />
A: You don't include by full path. The folder MySharedHTML will need to be under your application folder, and you include by relative path.
So say your webapp was at
c:\Program Files\Apache Software Foundation\Tomcat\webapps\myapp\
You would put your MySharedHTML in there
c:\Program Files\Apache Software Foundation\Tomcat\webapps\myapp\MySharedHTML
And then include by relative path:
<jsp:include page="./MySharedHTML/test.html" />
A: Alternatively we can achieve with the help of symlink or shortlink or softlink, so that there will be no much coding. What I did in my case is created a softlink for MySharedHTML, which is under my application web content to some path in D drive.
As symlinks are disabled by default to enable them in your Tomcat server, you need add below configuration to context.xml, which is under conf folder of tomcat server.
<Context allowLinking="true"> | unknown | |
d1867 | train | SELECT GENDER, R = ROW_NUMBER() OVER (PARTITION BY GENDER ORDER BY GENDER)
FROM PERSON
ORDER BY R, GENDER DESC | unknown | |
d1868 | train | Found the issue. For some reason a setting was enabled on my iPhone. When I switched it off it worked perfectly.
Settings -> Accessibility -> Voice Over -> VoiceOver Recognition -> Screen Recognition -> Apply to Apps
This setting had the app added to it. When I removed the app from this list it worked fine | unknown | |
d1869 | train | Try to console your selectedGroupValue on useEffect hook , solve it like this
import React, { useState } from 'react';
const App = () => {
const [selectedGroupValue, setSelectedGroupValue] = useState();
const filterOnSelectChange = (e) => {
setSelectedGroupValue(e.target.value);
};
React.useEffect(() => {
console.log(selectedGroupValue);
}, [selectedGroupValue]);
return (
<>
<select
name="selectmedgroup"
id="selectmedgroup"
value={selectedGroupValue}
onChange={filterOnSelectChange}
>
<option value="" defaultValue hidden>
-Select Group-
</option>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<option value="d">D</option>
</select>
</>
);
};
export default App; | unknown | |
d1870 | train | If you have defined your layout using display: flex.
justify-self will be ignored, i.e it will have no effect.
It will only have effect when you have used block or grid or have positioned an element using absolute.
You can read more on that here.
With display:flex, following properties are supported.
justify-content: flex-end; // horizontal axis when flex direction is row.
align-items: flex-end: // vertical axis when flex direction is row.
So if you are trying to place the footer at right-bottom of your parent container i.e content.
Try this :
.footer{
padding-top: 2vh !important;
border-top: 1px solid rgba(0,173,181,1) !important;
justify-content: flex-end !important;
align-items: flex-end !important;
} | unknown | |
d1871 | train | try this one...SMS Blacklist for Android to block spam | unknown | |
d1872 | train | If you have letters above the elephant and it doesn't relate to the name of any object in the folder, the carets will disappear. Can I just also say this was not a feature on pgadmin3 so it's not a solid picnic. | unknown | |
d1873 | train | Aaron Gallagher implemented a solution: http://blog.habnab.it/blog/2013/06/25/emacsclient-and-tramp/
It works (AFAIU) like:
*
*emacs server is started with tcp
*He opens a connection to a remote system with tramp-sh, opening a forward port ("back channel")
*tramp-sh is advised to copy an extended auth cookie file to the remote system
*On the remote system he calls a special emacsclient.sh shell script that emulates emacsclient but prefixes the file names with the corresponding tramp prefix that is found in the extended auth cookie
I've added a comment to his blog post proposing this idea to be discussed and enhanced on emacs-devel.
A: If you are doing this to enable people to remotely edit files you may want to look at 'tramp mode'
http://emacswiki.org/emacs/TrampMode
A: This should provide a starting point for what you want.
From the info node (emacs) emacsclient Options
`--server-file=SERVER-FILE'
Specify a "server file" for connecting to an Emacs server via TCP.
An Emacs server usually uses an operating system feature called a
"local socket" to listen for connections. Some operating systems,
such as Microsoft Windows, do not support local sockets; in that
case, Emacs uses TCP instead. When you start the Emacs server,
Emacs creates a server file containing some TCP information that
`emacsclient' needs for making the connection. By default, the
server file is in `~/.emacs.d/server/'. On Microsoft Windows, if
`emacsclient' does not find the server file there, it looks in the
`.emacs.d/server/' subdirectory of the directory pointed to by the
`APPDATA' environment variable. You can tell `emacsclient' to use
a specific server file with the `-f' or `--server-file' option, or
by setting the `EMACS_SERVER_FILE' environment variable.
Even if local sockets are available, you can tell Emacs to use TCP
by setting the variable `server-use-tcp' to `t'. One advantage of
TCP is that the server can accept connections from remote machines.
For this to work, you must (i) set the variable `server-host' to
the hostname or IP address of the machine on which the Emacs server
runs, and (ii) provide `emacsclient' with the server file. (One
convenient way to do the latter is to put the server file on a
networked file system such as NFS.)
You also may want to look at variables server-auth-dir, server-auth-key and server-port
A: I think what you're asking for is impossible by definition, because if you give a remote user unrestricted access to your Emacs, this is just as much "user spoofing" as letting that remote user access a shell via ssh. To spell it out, from a security point of view this is probably a bad idea.
Also, the results of letting two users access one Emacs aren't as good as you might hope. It isn't designed with simultaneous access in mind. It's years since I tried it, so things might have moved on a bit, but when I did it was quirky to say the least.
Still, I'll try to answer your question.
It sounds like you're thinking about this back-to-front, because, counter-intuitively, in network terms, the X11 display is the server, and the X11 application is the client. This is surprising because typically the display is local to the user and the application is running on some remote server.
You can instruct a running emacs to connect to a remote display and open a new window with M-x make-frame-on-display. For this to work, the owner of that display will need to grant you access to it.
We will assume host-l is the computer that is running Emacs, and that you want to make it accessible to a user of display 0 on host-r. Be aware that you've said you don't want to use SSH forwarding, so following this method will cause all traffic will go across the network unencrypted.
First, make sure that display host-r:0 is accepting TCP connections. You don't mention your operating system, but this is probably the default on Unix and probably isn't on Linux (for security reasons). If, for example, the following mentions -nolisten tcp then you'll need to change this configuration.
host-r$ ps -ef | grep X
Next, get the user of host-r to run the following, and send you the output. Be sure to warn them that this will allow you to take complete control of their current desktop session, should you choose.
host-r$ xauth list $DISPLAY
host-r/unix:0 MIT-MAGIC-COOKIE-1 01234567890abcdef0123456789abcd
This is, effectively, the "password" for the display. On host-l, put it where Emacs will be able to find it with:
host-l$ xauth add host-r:0 MIT-MAGIC-COOKIE-1 01234567890abcdef0123456789abcd
Now enter M-x make-frame-on-display host-r:0 and an Emacs window should pop up on the remote display. | unknown | |
d1874 | train | Maybe try an iterative approach?
from typing import List
def remove_words(words: List[str]):
index = 0
while index < len(words):
if words[index][2] != 'o':
words.pop(index)
else:
index += 1
# return words -- OPTIONAL
if __name__ == "__main__":
original_list = ["house", "ghost", "there", "loose"]
remove_words(original_list)
print(original_list) # ['ghost', 'loose']
Note on Performance
While the solution above answers the OP, it is not the most performant nor is it a "pure function" since it mutates external scope state (https://en.wikipedia.org/wiki/Pure_function).
from timeit import timeit
def remove_words():
# defining the list here instead of global scope because this is an impure function
words = ["house", "ghost", "there", "loose"]
index = 0
while index < len(words):
if words[index][2] != 'o':
words.pop(index)
else:
index += 1
def remove_words_with_list_comprehension():
# defining the list here to ensure fairness when testing performance
words = ["house", "ghost", "there", "loose"]
return [word for word in words if word[2] == 'o']
if __name__ == "__main__":
t1 = timeit(lambda : remove_words_with_list_comprehension(), number=1000000)
t2 = timeit(lambda : remove_words(), number=1000000)
print(f"list comprehension: {t1}")
print(f"while loop: {t2}")
# OUTPUT
# list comprehension: 0.40656489999673795
# while loop: 0.5882093999971403 | unknown | |
d1875 | train | As mentioned by @cooper before, the ssID wasn't properly added to the URL, and also there's a few changes to be made the url and your fetchapp
//Send active sheet as email attachment
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheetgId = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getSheetId();
var email = Session.getUser().getEmail();
var subject = "Order no.";
var body = "Hello";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" + "&exportFormat=pdf";
var result = UrlFetchApp.fetch(url)
var contents = result.getContent();
MailApp.sendEmail("[email protected]",subject ,body, {attachments:[{fileName:colB_Data+".pdf", content:contents, mimeType:"application//pdf"}]});
You're sending an HTTP GET directly to your same drive, so the user, I assume, is logged to a google account and has access to the spreadsheet, therefore you don't really need a token again.
Second you forgot to add the variables to the parameters in the export mode URL and I changed the export format to pdf.
A: It didn't work without token so I used this:
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ssID = ss.getId();
var sheetgId = ss.getActiveSheet().getSheetId();
var sheetName = ss.getName();
var token = ScriptApp.getOAuthToken();
var email = "[email protected]";
var subject = "Important Info!";
var body = "PFA the report \n\nCheers,\n Roportobot";
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?" + "format=xlsx" + "&gid="+sheetgId+ "&portrait=true" + "&exportFormat=pdf";
var result = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var contents = result.getContent();
MailApp.sendEmail(email,subject ,body, {attachments:[{fileName:sheetName+".pdf", content:contents, mimeType:"application//pdf"}]}); | unknown | |
d1876 | train | What a cool little bug, I've never seen that before!
By the looks of things you'll need to add display:none to some of your divs. You'll need to use Javascript to see what's in view and see what's not. You'll get the added bonus of not using any system resources unnecessarily as you won't be painting any of the pages that aren't in view. | unknown | |
d1877 | train | You need to track event.target which gives where is has been called i.e
const closeModal = (event) => {
const modal = document.getElementById("myModal");
if (event.target === modal) {
setShowModal(false);
}
};
<Background id="myModal" onClick={closeModal}>
Here is the demo: https://codesandbox.io/s/cranky-hodgkin-o77em?file=/src/components/Modal.js
A: The problem is due to event bubbling. Everytime you click any descendants of the Background element, the click handlers of them fires and bubbles up until it reaches the Background element firing the handler of itself. To solve this, you can either stop the propagation of the click handler of the child elements using stopPropagation() method or you can simply add ID to background and determine if the id matches the background only then firing the showModal method.
<Background onClick={closeModal} id="bg">
const closeModal = (e) => {
if (e.target.id === 'bg') {
setShowModal(false);
}
};
It is not necessary to add id to the close button and check for the targeted button's id since clicking on the button definitely closes the modal.
A: I seen an comment asking how to achieve this with useRef (included typescript types):
const modalBackgroundRef = useRef<HTMLDivElement>(null);
const closeModal = () => {
// Close the modal...
};
const onClickBackground = (event: MouseEvent<HTMLDivElement>) => {
if (event.target === modalBackgroundRef.current) closeModal();
};
return (
<div id="modal-background" tabIndex={-1} ref={modalBackgroundRef} onClick={onClickBackground}>
// Modal goes here...
</div>
); | unknown | |
d1878 | train | I propose the following RegEx:
delve\(\s*([^,]+?)\s*,\s*['"]([^.]+?)['"]\s*\)
and the following replacement format string:
$1?.$2
Explanation: Match delve(, a first argument up until the first comma (lazy match), and then a second string argument (no care is taken to ensure that the brackets match as this is rather quick'n'dirty anyways), then the closing bracket of the call ). Spacing at reasonable places is accounted for.
which will work for simple cases like delve(someVar, "key") but might fail for pathological cases; always review the replacements manually.
Note that this is explicitly made incapable of dealing with delve(var, "a.b.c") because as far as I know, VSC format strings don't support "joining" variable numbers of captures by a given string. As a workaround, you could explicitly create versions with two, three, four, five... dots and write the corresponding replacements. The version for two dots for example looks as follows:
delve\(([^,]+?)\s*,\s*['"]([^.]+?)\.([^.]+?)['"]\s*\)
and the format string is $1?.$2?.$3.
You write:
e.g.
delve(seo,'meta')
delve(item, "image.data.attributes.alternativeText")
desired result
seo?.meta
item?.image.data.attributes.alternativeText
but I highly doubt that this is intended, because delve(item, "image.data.attributes.alternativeText") is in fact equivalent to item?.image?.data?.attributes?.alternativeText rather than the desired result you describe. To make it handle it that way, simply replace [^.] with . to make it accept strings containing any characters (including dots). | unknown | |
d1879 | train | Not sure if this is the result that you want, but you can just add another condition in your left join like this:
FROM 1_transactions t
LEFT JOIN addresses a ON a.id=t.fk_addresses_id
LEFT JOIN 1_finance_add_details f ON t.id=f.fk_transactions_id
LEFT JOIN addresses e ON e.id=f.employ_fk_addresses_id AND t.trans_type=2
WHERE trans_location=1 AND t.id=19;
Note: this would render the field of addresses e NULL on every t with type != 2. | unknown | |
d1880 | train | While in general you should not use pandas iterrows, because it is very slow, I am going to use it in my answer in part because you do not need to use pandas at all: you just want to iterate over the rows in your CSV:
import pandas as pd
df = pd.DataFrame.from_dict({'name': {0: 'john', 1: 'liza'}, 'lastname': {0: 'smith', 1: 'jones'}, 'group': {0: 'sales', 1: 'hr'}, 'password': {0: 'abc1', 1: 'abc2'}})
template = """- name: {fname[0]}. {lname}
password: {pword}
groups: {groups}
"""
with open('output.txt', 'w') as fp:
# iterrows returns the index, which we ignore with _
for _, (name, lastname, group, password) in df.iterrows():
fp.write(template.format(fname = name, lname = lastname, pword = password, groups = group))
Here we use a template string that we will substitute the values into using keyword arguments in the string format method. This will write the output to output.txt. Notice the keywords correspond directly to the keywords used in the template. The resulting text file appears as:
- name: j. smith
password: abc1
groups: sales
- name: l. jones
password: abc2
groups: hr | unknown | |
d1881 | train | Sure - using an INT IDENTITY is probably the easiest and safest bet.
SQL Server handles all everything for you - you just get a nice, clean number and be done with it.
If you want to, you can also combine a consecutive number (your ID) with e.g. a project or product prefix to create "case numbers" like PROJ-000005, OTHR-000006 and so forth. This can be very easily done by using a computed column in your table - something like this:
ALTER TABLE dbo.YourTable
ADD PrefixedNumber AS Prefix + '-' + RIGHT('000000' + CAST(ID AS VARCHAR(10)), 6) PERSISTED
Then your table would have an identity column ID with auto-generated numbers, some kind of a customer or project or product determined Prefix, and your computed column PrefixedNumber would contain those fancy prefixed case numbers. | unknown | |
d1882 | train | As chepner has noted, in a shell line-reading loop the only way to know whether a given line is the last one is to try to read the next one.
You can emulate "peeking" at the next line using the code below, which allows you to detect the desired condition while still processing the lines uniformly.
This solution may not be for everyone, because the logic is nontrivial and therefore requires quite a bit of extra, non-obvious code, and processing is slowed down as well.
Note that the code assumes that the last line has a trailing \n (as all well-formed multiline text input should have).
#!/usr/bin/env bash
eof=0 peekedChar= hadEmptyLine=0 lastLine=0
while IFS= read -r line || { eof=1; (( hadEmptyLine )); }; do
# Construct the 1-2 element array of lines to process in this iteration:
# - an empty line detected in the previous iteration by peeking, if applicable
(( hadEmptyLine )) && aLines=( '' ) || aLines=()
# - the line read in this iteration, with the peeked char. prepended
if (( eof )); then
# No further line could be read in this iteration; we're here only because
# $hadEmptyLine was set, which implies that the empty line we're processing
# is by definition the last one.
lastLine=1 hadEmptyLine=0
else
# Add the just-read line, with the peeked char. prepended.
aLines+=( "${peekedChar}${line}" )
# "Peek" at the next line by reading 1 character, which
# we'll have to prepend to the *next* iteration's line, if applicable.
# Being unable to read tells us that this is the last line.
IFS= read -n 1 peekedChar || lastLine=1
# If the next line happens to be empty, our "peeking" has fully consumed it,
# so we must tell the next iteration to insert processing of this empty line.
hadEmptyLine=$(( ! lastLine && ${#peekedChar} == 0 ))
fi
# Process the 1-2 lines.
ndx=0 maxNdx=$(( ${#aLines[@]} - 1 ))
for line in "${aLines[@]}"; do
if [[ -z $line ]]; then # an empty line
# Determine if this empty line is the last one overall.
thisEmptyLineIsLastLine=$(( lastLine && ndx == maxNdx ))
echo "empty line; last? $thisEmptyLineIsLastLine"
else
echo "nonempty line: [$line]"
fi
((++ndx))
done
done < file | unknown | |
d1883 | train | I got the same error while trying to set up keycloak in quarkus dev environment.
I found out there was a problem with the resource configuration. First I fixed a part of the problem by setting to true the Authorization Enabled setting in the client setting page.
It gave me another error: invalid_scope, Requires uma_protection scope
I'm guessing it's a client scope to add. I found a issue stating that it should be a scope and not a client scope but can't find it anymore.
anyway, the easiest way I found to fix this configuration for my dev environment was to reimport the quarkus realm from this file: quarkus-realm.json
it seems to be up to date and working. Next you can check the config to find out your missing params. | unknown | |
d1884 | train | One point to bear in mind is that you would presumably not be distributing the source code for the Compact Edition. This might make your project fail some definitions of "Open source" if the Compact Edition is closely integrated with the rest of your code. This in turn might make it inelligible to be hosted on certain FOSS web servers (I'm thinking of Google Code) and might result in your prtoject getting a bad name amond more zealous FOSS supporters.
A: As long as you don't need replication with a big MS SQL Server you are fine with SQL CE.
A: IANAL, and I do not know if the EULA is compatible with every open source license.
But, as long as you sign up for redistribution rights you should be fine to redistribute it with an open source project. | unknown | |
d1885 | train | I'm not sure that in the example is drawing process over video. As for me It's a 3d model with video background. And you could sync prerecorded states with 3d object transformations (position, rotation, mesh transformations), or create well textured object.
Here for your tutorial how to draw over the 3D objects
A: Easy! Use Adobe After Effects (or any number of other compositing programs). | unknown | |
d1886 | train | Found the solution; replace this in the beginning of Graphics/GraphicsCapabilities.cs:
#if OPENGL
#if GLES
using OpenTK.Graphics.ES20;
//...
with:
#if MONOMAC
using MonoMac.OpenGL;
#elsif OPENGL
#if GLES
using OpenTK.Graphics.ES20;
//... | unknown | |
d1887 | train | If you really need to produce a stand-alone SWF file (and not just a config file for you own "player"), I would probably do it like this;
1) Create your editor in whatever system you feel like (flash, jquery etc).
2) Build a config file in the client. This is used, together with all the resources the user added, to play back the animation.
3) Upload said assets and config file to your web server.
4) Use the flex compiler (on the server) to produce the resulting SWF, combining your player with generated AS3 which embeds the uploaded resources as needed, to make it available to the player.
5) Give the user a download link for the newly generated SWF file.
A: I don't think there is any swf compiler available for Flash (actionescript). You may create a swf that allows users to create an animation, save it as a home-made vector format, and then replay it. But I don't believe you can create and independant swf file with only the created animation in it.
Just think about a player in Flash, and a format that the player will read (xml, json, name it...). You can either generate the input with jQuery or Flash, and then feed it into your player to display it. You will eventually need two files.
A: Apparently this library allows you to compile SWFs at runtime. I haven't used it myself (yet) and don't know how stable or flexible it is, but it appears to be what you're looking for. I'd recommend giving it a spin and seeing if it's sufficient.
I'm not exactly sure how it saves the file, so you might run into security problems since it's a web application. Hopefully it should be OK though. | unknown | |
d1888 | train | No. You'll have to do it manually. You should look into responsive CSS layouts. These will adjust the content of the page as the width of the browser changes. So same page will work in a full browser window and mobile.
Look at
*
*http://www.columnal.com/
*http://lessframework.com/
*http://speckyboy.com/2011/11/17/15-responsive-css-frameworks-worth-considering/
A: I got it, we can use skweezer API for this. If you want to see your website in mobile compatible format try this
http://www.skweezer.com/s.aspx?q=www.example.com
Replace www.example.com with your website URL.
For more details, visit http://company.skweezer.com/ | unknown | |
d1889 | train | How about something like this (written in pure Ruby; it could be refactored to use some Rails-specific features like .constantize):
module ClassErrorable
module ClassMethods
def error(message = nil)
klass = Object::const_get(exception_class_name)
raise klass.new(message || "There's been an error!")
end
def exception_class_name
name + 'Error'
end
end
def self.included(base)
base.extend ClassMethods
Object::const_set(base.exception_class_name, Class.new(Exception))
end
def error(message = nil)
self.class.error(message)
end
end | unknown | |
d1890 | train | The answer seems to be by Matthias:
Use from AppName.modules import settings and then access the data in the module with settings.value. According to PEP-8, the style guide for Python code, wildcard imports should be avoided and would in fact lead to undesirable behaviour in this case.
Thanks you all for the help! | unknown | |
d1891 | train | I don't see where you runs parse_product. It will not execute it automatically for you. Besides function like your parse_product with response is rather to use it in some yield Requests(supage_url, parse_product) to parse data from subpage, not from page which you get in parse. You should rather move code from parse_product into parse like this:
def parse(self, response):
options = Options()
chrome_path = which("chromedriver")
driver = webdriver.Chrome(executable_path=chrome_path)#, chrome_options=options)
driver.set_window_size(1920, 1080)
p = 0 # The home depot URLs end in =24, =48 etc basically products are grouped 24 on a page so this is my way of getting the next page
start_url = 'https://www.homedepot.com/b/Home-Decor-Artificial-Greenery-Artificial-Flowers/N-5yc1vZcf9y?Nao='
scroll_pause_time = 1
screen_height = driver.execute_script("return window.screen.height;") # get the screen height of the web
while p < 25:
driver.get(start_url + str(p))
#sleep(2)
i = 1
# scrolling
while True: #this is the infinite scoll thing which reveals all javascript generated product tiles
driver.execute_script("window.scrollTo(0, {screen_height}*{i});".format(screen_height=screen_height, i=i))
i += 1
sleep(scroll_pause_time)
scroll_height = driver.execute_script("return document.body.scrollHeight;")
if (screen_height) * i > scroll_height:
break
# after scrolling
self.html = driver.page_source
p = p + 24
resp = Selector(text=self.html)
for products in resp.xpath("//div[@class='product-pod--padding']"):
date = datetime.now().strftime("%m-%d-%y")
brand = products.xpath("normalize-space(.//span[@class='product-pod__title__brand--bold']/text())").get()
title = products.xpath("normalize-space(.//span[@class='product-pod__title__product']/text())").get()
link = products.xpath(".//div//a//@href").get()
model = products.xpath("normalize-space(.//div[@class='product-pod__model'][2]/text())").get()
review_count = products.xpath("normalize-space(.//span[@class='product-pod__ratings-count']/text())").get()
price = products.xpath("normalize-space(.//div[@class='price-format__main-price']//span[2]/text())").get()
yield {
'Date scraped' : date,
'Brand' : brand,
'Title' : title,
'Product Link' : "https://www.homedepot.com" + remove_tags(link),
'Price' : "$" + price,
'Model #' : model,
'Review Count' : review_count
}
But I would do other changes - you use p = p + 24 but when I check page in browser then I see I need p = p + 48 to get all product. Instead of p = p + ... I would rather use Selenium to click button > to get next page.
EDIT:
My version with other changes.
Everyone can run it without creating project.
#!/usr/bin/env python3
import scrapy
from scrapy.utils.markup import remove_tags
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from shutil import which
from scrapy.selector import Selector
from time import sleep
from datetime import datetime
class HdSpider(scrapy.Spider):
name = 'hd'
allowed_domains = ['www.homedepot.com']
start_urls = ['https://www.homedepot.com/b/Home-Decor-Artificial-Greenery-Artificial-Flowers/N-5yc1vZcf9y?Nao='] #Add %%Nao= to end of URL you got from search or category
def parse(self, response):
options = Options()
chrome_path = which("chromedriver")
driver = webdriver.Chrome(executable_path=chrome_path) #, chrome_options=options)
#driver.set_window_size(1920, 1080)
print(dir(driver))
driver.maximize_window()
scroll_pause_time = 1
# loading first page
start_url = 'https://www.homedepot.com/b/Home-Decor-Artificial-Greenery-Artificial-Flowers/N-5yc1vZcf9y?Nao=0'
driver.get(start_url)
screen_height = driver.execute_script("return window.screen.height;") # get the screen height of the web
#while True: # all pages
for _ in range(5): # only 5 pages
#sleep(scroll_pause_time)
# scrolling page
i = 1
while True: #this is the infinite scoll thing which reveals all javascript generated product tiles
driver.execute_script(f"window.scrollBy(0, {screen_height});")
sleep(scroll_pause_time)
i += 1
scroll_height = driver.execute_script("return document.body.scrollHeight;")
if screen_height * i > scroll_height:
break
# after scrolling
resp = Selector(text=driver.page_source)
for products in resp.xpath("//div[@class='product-pod--padding']"):
date = datetime.now().strftime("%m-%d-%y")
brand = products.xpath("normalize-space(.//span[@class='product-pod__title__brand--bold']/text())").get()
title = products.xpath("normalize-space(.//span[@class='product-pod__title__product']/text())").get()
link = products.xpath(".//div//a//@href").get()
model = products.xpath("normalize-space(.//div[@class='product-pod__model'][2]/text())").get()
review_count = products.xpath("normalize-space(.//span[@class='product-pod__ratings-count']/text())").get()
price = products.xpath("normalize-space(.//div[@class='price-format__main-price']//span[2]/text())").get()
yield {
'Date scraped' : date,
'Brand' : brand,
'Title' : title,
'Product Link' : "https://www.homedepot.com" + remove_tags(link),
'Price' : "$" + price,
'Model #' : model,
'Review Count' : review_count
}
# click button `>` to load next page
try:
driver.find_element_by_xpath('//a[@aria-label="Next"]').click()
except:
break
# --- run without project and save in `output.csv` ---
from scrapy.crawler import CrawlerProcess
c = CrawlerProcess({
'USER_AGENT': 'Mozilla/5.0',
# save in file CSV, JSON or XML
'FEEDS': {'output.csv': {'format': 'csv'}}, # new in 2.1
})
c.crawl(HdSpider)
c.start() | unknown | |
d1892 | train | Don't use jQuery ... use css and media=print. Here is an article for reference, and here.
Basically, create a new stylesheet for what you want to show when you print, and set the media to print:
<link rel="stylesheet" type"text/css" href="print.css" media="print">
A: You could probably put the content in an iframe and call print() on that window.
A quick google gave me http://www.eggheadcafe.com/PrintSearchContent.asp?LINKID=449 which mentions you must focus() before you print(). Note that that page is a few years old.
Also see How do I print an IFrame from javascript in Safari/Chrome.
A: Styling html for printing is commonly achieved using a different style sheet, e.g. in your head element:
<head>
...
<link rel="stylesheet" type="text/css" media="screen" href="style.css">
<link rel="stylesheet" type="text/css" media="print" href="print.css">
...
</head>
The style sheet style.css is used to style your html on screen, while print.css is used to style your html for print. By providing the appropriate styling in print.css you can easily show or hide html elements to achieve the output you are looking for. | unknown | |
d1893 | train | If someone stumbles across this we solved this now with using a simple TCP Listener which listens for a connection:
TcpListener srv = new TcpListener(IPAddress.Any, 51530);
srv.Start(1);
client = srv.AcceptTcpClient();
Then we changed the Kinectpicture into a Bitmap and on every new picture we send the bitmap to the connected device:
NetworkStream ns = client.GetStream();
Graphics g = Graphics.FromImage(bitmap);
MemoryStream imageStream = new MemoryStream();
using (var ms = new MemoryStream())
{
Bitmap bmp = new Bitmap(bitmap);
bmp.Save(imageStream, ImageFormat.Bmp);
}
// bitmap.Save(imageStream, ImageFormat.Bmp);
Console.WriteLine("Bild wird über Socket geschickt");
//reset the memory stream to start of stream
imageStream.Position = 0;
//copy memory stream to network stream
imageStream.CopyTo(ns);
//make sure copy is completed
imageStream.Flush();
imageStream.Close();
//Makes sure everything is sent before closing it
ns.Flush();
on the other side there is an android device which gets the network stream and translates it into a bitmap and shows it in an imageview.
Feel free to ask additional questions for needed clarification. | unknown | |
d1894 | train | It looks to me that
*
*your paths configuration (in the CDT settings) has problems (some executables cannot be located)
*your actual build doesn't need these (e.g. you're just using a Makefile based project)
It appears that whenever you invoke an external tool (make, rm, ...) Eclipse is doing a sanity check on the configuration settings, just to be more userfriendly.
If you don't like the warnings, fix the missing configuration entries, or you can accept the warnings (and keep it in mind in case you start a different type of C++ project) | unknown | |
d1895 | train | I think you should persevere with using Thread.interrupt(). But what you need to do to make it work is to change the methodA code to do something like this:
public void methodA() throws InterruptedException {
for (int n=0; n < 100; n++) {
if (Thread.interrupted) {
throw new InterruptedException();
}
//Do something recursive
}
// and so on.
}
This is equivalent declaring and using your own "kill switch" variable, except that:
*
*many synchronization APIs, and some I/O APIs pay attention to the interrupted state, and
*a well-behaved 3rd-party library will pay attention to the interrupted state.
Now it is true that a lot of code out there mishandles InterruptedException; e.g. by squashing it. (The correct way to deal with an InterruptedException is to either to allow it to propagate, or call Thread.interrupt() to set the flag again.) However, the flip side is that that same code would not be aware of your kill switch. So you've got a problem either way.
A: Thread.interrupt will not stop your thread (unless it is in the sleep, in which case the InterruptedException will be thrown). Interrupting basically sends a message to the thread indicating it has been interrupted but it doesn't cause a thread to stop immediately.
When you have long looping operations, using a flag to check if the thread has been cancelled is a standard approach. Your methodA can be modified to add that flag, so something like:
// this is a new instance variable in `A`
private volatile boolean cancelled = false;
// this is part of your methodA
for (int n=0;n<100;n++) {
if ( cancelled ) {
return; // or handle this however you want
}
}
// each of your other loops should work the same way
Then a cancel method can be added to set that flag
public void cancel() {
cancelled = true;
}
Then if someone calls runEverything on B, B can then just call cancel on A (you will have to extract the A variable so B has a reference to it even after runEverything is called.
A: You can check the status of the run flag as part of the looping or recursion. If there's a kill signal (i.e. run flag is set false), just return (after whatever cleanup you need to do).
A: There are some other possible approaches:
1) Don't stop it - signal it to stop with the Interrupted flag, set its priority to lowest possible and 'orphan' the thread and any data objects it is working on. If you need the operation that is performed by this thread again, make another one.
2) Null out, corrupt, rename, close or otherwise destroy the data it is working on to force the thread to segfault/AV or except in some other way. The thread can catch the throw and check the Interrupted flag.
No guarantees, sold as seen...
A: From main thread letsvsay someTask() is called and t1.interrput is being called..
t1.interrupt();
}
private static Runnable someTask(){
return ()->{
while(running){
try {
if(Thread.interrupted()){
throw new InterruptedException( );
}
// System.out.println(i + " the current thread is "+Thread.currentThread().getName());
// Thread.sleep( 2000 );
} catch (Exception e) {
System.out.println(" the thread is interrputed "+Thread.currentThread().getName());
e.printStackTrace();
break;
}
}
o/P:
java.lang.InterruptedException
at com.barcap.test.Threading.interrupt.ThreadT2Interrupt.lambda$someTask$0(ThreadT2Interrupt.java:32)
at java.lang.Thread.run(Thread.java:748)
the thread is interrputed Thread-0
Only t1.interuuption will not be enough .this need check the status of Thread.interrupted() in child thread. | unknown | |
d1896 | train | as you mentioned in the comment here you go.
Create a file app.js with the following:
const express = require('express')
const app = express()
const port = 8000
app.get('/', (req, res) => {
console.log('getting request')
res.sendFile('website/y.html',{root:__dirname})
})
app.use(express.static(__dirname + '/website'))
app.use((req, res)=>{
res.redirect('/')
})
app.listen(port, () => {
console.log(`app listening at http://localhost:${port}`)
})
Here my website files exist at website folder and my entry point is y.html.
Set the static file directory (your website page) and then serve the .html for the root request
example project: https://github.com/ondbyte/website
Finally, to run it open terminal and move to the root folder. Then do
npm init
npm install express --no-save
node app.js
A: Here is the more simpler way. NO NEED to setup server
open your Build/web folder in vscode.
install Live server Plugin in vscode.
hit Golive Button
Here you go your flutter web app would be running locally without android studio. | unknown | |
d1897 | train | I would attach an event handler to the one control (radio button), which affects/changes the options in the select control:
$('#myRadioButtonInput').click(function() { $('#theSelectToAffect option.Conditional').hide(); });
Just attach the 'Conditional' class to the conditional options when you make the drop down/select. | unknown | |
d1898 | train | DispatchTouchEvent is called with a MotionEvent parameter. Method getAction within MotionEvent can return
*
*ACTION_DOWN
*ACTION_MOVE
*ACTION_UP
*ACTION_CANCEL
Then set on ACTION_DOWN flag isClick. If there is ACTION_MOVE clear isClick flag.
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
isClick = true;
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (isClick) {
//TODO Click action
}
break;
case MotionEvent.ACTION_MOVE:
isClick = false;
break;
default:
break;
}
return true;
}
A: set up a threshold limit.When you move the pointer within a small range make it recognized as a click or else a movement | unknown | |
d1899 | train | When listening with addEventListener, you listen for the change event which is just "change", not "onchange". Listening for "onchange" will never fire because there is never a matching event fired (unless you create a custom one yourself). | unknown | |
d1900 | train | There's a known error with the expo-google-signin library where idToken and sometimes accessToken are returned as undefined.
It might stretch over to expo Google as well. | unknown |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.