id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23528700
|
|batch|index|loss|
8 0 0.6232748031616211
..
8 23 0.6030591726303101
9 0 0.5626393556594849
9 1 0.6434788703918457
..
9 20 0.6232720017433167
I think it means that it doesn't learn on anything new. I do not know how to fix it, though. Doesn't matter if the no. epochs is 10 or 100. Loss is always ~0.6. Here is a code fragment without the model:
xy = np.loadtxt('diabetes.csv', delimiter=',', dtype=np.float32)
x_data = (torch.from_numpy(xy[:, 0:-1]))
y_data = (torch.from_numpy(xy[:, [-1]]))
class DiabetesDataset(Dataset):
def __init__(self):
xy = np.loadtxt('diabetes.csv', delimiter=',', dtype=np.float32)
self.len = (xy.shape[0])
self.x_data = (torch.from_numpy(xy[:, 0:-1]))
self.y_data = (torch.from_numpy(xy[:, [-1]]))
def __getitem__(self, index):
return self.x_data[index], self.y_data[index]
def __len__(self):
return self.len
dataset = DiabetesDataset()
train_loader = DataLoader(dataset=dataset,
batch_size=32,
shuffle=True,
num_workers=0)
model = Model()
criterion = torch.nn.BCELoss(reduction='mean')
optimizer = torch.optim.Rprop(model.parameters(), lr=0.01)
for epoch in range(10):
for i, data in enumerate(train_loader, 0):
inputs, labels = data
inputs, labels = Variable(inputs), Variable(labels)
y_pred = model(inputs)
loss = criterion(y_pred, labels)
print(epoch, i, float(loss.data))
optimizer.zero_grad()
loss.backward()
optimizer.step()
What might be the cause? Thanks!
| |
doc_23528701
|
if (e.keyCode == 27) { ... }
});
The previous code is a code I found that determines if the escape key is pressed and released; however, I've never used code like this before.
*
*I was wanting to find out if this was an okay code to use as far as security and performance?
*I wanted to find out how to make this change the page url? Basically, when they press the esc key and let go, it changes to the login page.
*Is there a better way to do this?
A: You can change the current url when pressing the esc button like so:
window.onkeyup = function(e) {
var event = e.which || e.keyCode || 0; // .which with fallback
if (event == 27) { // ESC Key
window.location.href = 'YOURURL'; // Navigate to URL
}
}
Alternatively, you could use jQuery's $(window).keyup() the same way.
Here we add an event listener to onkeyup to check for user interaction with the keyboard. When the user presses down and then releases a key the event will fire.
We then check if the key is the ESC key (27). Key code 27 (when using .which) is supported by the most popular browsers (Chrome, Safari, Firefox, Opera, IE).
On a final note. To prevent any default action you can return false; on keydown or keypress; as explained here.
A: $(document).keyup(function (e) {
if (e.keyCode == 27) { window.location.href = 'http://example.com'; }
});
| |
doc_23528702
|
<iframe
src="https://www.roomle.com/t/cp/?id=<ID>&configuratorId=<CONFIGURATOR_ID>&api=false"
frameborder="0"
width="100%"
height="500"
/>
By default the configurator always uses the default browser language. Is it possible to change that?
A: It's possible to use the locale url param to set the language.
<iframe
src="https://www.roomle.com/t/cp/?id=<ID>&configuratorId=<CONFIGURATOR_ID>&api=false&locale=en"
frameborder="0"
width="100%"
height="500"
/>
Here is a list with all available languages: https://www.roomle.com/en/documentation/configurator-languages
| |
doc_23528703
|
I could create a sprite with an ascii spritesheet but because I want the text (in my case the sprites) to change colour, that solution wouldn't be optimal.
In phaser2 I could create an empty bitmapdata object and use it as the graphic for my sprite, but in phaser3 there is no such a thing.
Should I create a sprite with a transparent png as the graphic and then add the text to it? Is this a good solution or would it be an overkill, as in my game I want everything to be ascii characters?
Any help would be appreciated.
Thank you
A: Your original solution of using a Sprite with an ASCII spritesheet will work fine. You can have white lettering and use the setTint(), clearTint(), and isTinted property to change the color while also being able to Sprite-related stuff.
*
*Tinting Demo
*Source Code
*Phaser 3 Sprite Doc
| |
doc_23528704
|
var image = UIImage()
var imageView = UIImageView(frame: CGRectMake(0, 0, view.frame.size.height * 0.22, view.frame.size.height * 0.22))
imageView.center = CGPointMake(self.view.center.x, view.frame.size.height * 0.414)
imageView.image = self.image
imageView.layer.cornerRadius = imageView.frame.size.width / 2
imageView.layer.borderWidth = 2.0
imageView.layer.borderColor = UIColor(red: 254.0/255, green: 216.0/255, blue: 0/255, alpha: 1.0).CGColor
imageView.clipsToBounds = true
imageView.layer.contentsRect = CGRectMake(0, 20, imageView.frame.size.width, imageView.frame.size.height) //This is where I have being trying to do it but no success.
imageView.contentMode = .ScaleAspectFill
view.addSubview(imageView)
A: Short answer: You don't.
What you would do is add the image view as a subview of another view. The trivial way to do this would be to put the image view in a scroll view, constrained so that the only place it can scroll is down, and only slightly. Then you could achieve the scrolling with zero code.
EDIT:
This isn't really a coding problem - it's more of an Interface Builder problem. You need to set up a scroll view.
A scroll view is a view that lets you look at a portion of a larger view.
You can think of a scroll view like a piece of paper with a rectangular hole in it. You put a bigger piece of paper under it (The scroll view's content view) and you can slide the bigger piece of paper around and view different parts of it through the hole.
Here's how you would set it up.
Drag a scroll view onto your view controller. Size it and add constraints to it to position it where you want. If you want your image view to be 300x300 points in size, for example, and want to be able to drag it up or down by 20 points, then make the scroll view 20 points taller. (w: 300, h: 320)
Select the view inside the scrollview and set it's width to the same width as it's scrollview, but 20 points taller than the scroll view. (w: 300, h: 340). Add constraints to lock it's height and width.
Now you have a scroll view that's big enough for a 300x300 point image, with 20 points of total white space at the top and bottom.
You've created a content view that's 20 points bigger than that, so it can slide up or down by 20 points in the scroll view.
Drag your 300x300 point image view into the view inside the scroll view, assign an image to it, and add constraints to lock it's size and center it horizontally and vertically in it's superview.
The final step is to set the content size of the scroll view. Normally you just set a scroll view's content size to the size of it's content view. You can do that by adding this bit of code to your view controller's viewDidLoad:
(Assuming you've connected an outlet to your scrollview that's called theScrollView)
//Get the first (and only) subview of the scrollView.
let subview = theScrollView.subviews[0] as! UIView;
//Make the scroll view's contentSize the same size as the content view.
theScrollView!.contentSize = subview.bounds.size;
It's also possible to set the content size of the scroll view without any code at all. You'd use a feature of IB (Interface Builder) called "User Defined Runtime Attributes". Here's how you'd do that: (If you use this approach don't add the code above to viewDidLoad)
Select the scroll view in IB.
Press command-option 3 to select the "identity inspector".
In the section headed "User Defined Runtime Attributes", tap the plus sign on the left. Edit the Key Path to "contentSize" (all lower case except the "S" in "Size". That's very important.) Press enter to change the key path. Then tap on the "type" column and select "size". The value field will show "{0,0}". Enter your desired content size: ("{300,340}" in the example above.)
What this does is tell IB "At runtime, look for a property called "contentSize" in the selected object (the scroll view.) Set that property to the specified value of type CGSize.
Once you're done your IB "identity inspector" should look like this:
Note that if you get a key name wrong when using "User Defined Runtime Attributes" then the app crashes when you display that view controller, with a very cryptic message.
By default scrollviews let you "overshoot" when dragging their contents around, and then bounce back into place when you let go. You can turn that feature off by unchecking the "Bounce" checkbox in the IB "Attributes Inspector" (command option 4)
A: You shouldn't do that. But if you want to you can play with anchorPoint property of backing layer of UImageView. link
Note: Keep in mind any layout process may alter this property later.
| |
doc_23528705
|
This question in particular has to do with the + & = operators. I've done a couple of programs already in class that involved both of these overloads, and I didn't seem to have any difficulty making the program function properly; however, there must be some distinct differences from these prior programs and my current one that I'm failing to see that goes beyond my understanding of how each operator overload works.
The error messages themselves make the issue seem almost too easy to fix as it's just an operand matching issue apparently, but I still have been unable to find the correct syntax to correct these errors. They are as follows:
"1>...\grademain.cpp(19): error C2679: binary '=' : no operator found which takes a right-hand 1>operand of type 'const char [12]' (or there is no acceptable conversion)
1>...\grade.h(39): could be 'Grade &Grade::operator =(const Grade &)'
1> while trying to match the argument list '(Grade, const char [12])' "
and
"1>...\grademain.cpp(26): error C2679: binary '+' : no operator found which takes a right-hand 1>operand of type 'int' (or there is no acceptable conversion)
1>...\grade.h(40): could be 'Grade Grade::operator +(const Grade &)'
1>\grade.h(16): or 'int operator +(const Grade &)'
1> while trying to match the argument list '(Grade, int)' "
The code is as follows:
GradeMain.cpp:
#include <iostream>
#include <string>
#include "Grade.h"
using namespace std;
int main(void)
{
Grade student1("Tom Smith", 90); //declare initialized object
cout << "First: " << student1 << endl;
Grade student2;
student2 = "Bill Miller"; //uses conversion constructor // ERROR # 1
cout << "Second: " << student2 << endl;
Grade student3;
student3 = student1;
cout << "Third: " << student3 << endl;
int adjusted_grade = student1 + 4; // ERROR # 2
cout << "adjusted grade of first by 4 points gives " << adjusted_grade << endl;
//test equality operator
if (student1 == student2)
cout << "\nerror - students should not be equal\n";
else
cout << "\nstudent 1 is not equal to student 2\n";
if (student1 == student3)
cout << "\nstudent 1 is equal to student 3\n";
else
cout << "\nerror - student 1 should be equal to student 3\n";
system("pause");
return 0;
}
Grade.cpp:
#include <iostream>
#include <string>
#include "Grade.h"
// Copy Assignment
Grade &Grade::operator=(const Grade &temp)
{
name = temp.name;
grade = temp.grade;
return *this;
}
// Addition Operator Overload
Grade Grade::operator+(const Grade &temp)
{
Grade temp1;
temp1.grade = grade + temp.grade;
return *this;
}
// Output Operator Overload
ostream& operator<<(ostream &os, const Grade &p)
{
os << p.name << " " << p.grade;
return os;
}
// Input Operator Overload
istream& operator>>(istream &in, const Grade &p)
{
// No purpose for program -- User does not input anything
return in;
}
// Comparison Operator Overload
bool Grade::operator==(const Grade &temp)
{
if(grade == temp.grade)
return true;
else
return false;
}
Grade.h:
using namespace std;
class Grade
{
// Friend Function Prototypes
friend ostream& operator<<(ostream& , const Grade&);
friend istream& operator>>(istream& , const Grade&); // Not necessary -- deleting
friend bool operator==(const Grade&, const Grade&);
friend int operator+(const Grade&);
private:
string name;
int grade;
public:
// Default Constructor
Grade();
// Constructor
Grade(string studentName, int studentGrade)
{
name = studentName;
grade = studentGrade;
}
// Copy Constructor
Grade(const Grade &obj)
{
name = obj.name;
grade = obj.grade;
}
// Operator Overloads
Grade& operator=(const Grade &); // Copy Assignment
Grade operator+(const Grade &);
Grade& operator<<(const Grade &);
Grade& operator>>(const Grade &);
bool operator==(const Grade &);
};
Part of my confusion with the operator= issue is that when I assigned student3 to student1, there was no problem, yet when I simply assign student2 = "Bill Miller", it experiences an operand issue. I had thought this would just create the object of student2("Bill Miller", 0) essentially, but I must be wrong somewhere. I can only imagine that whatever rectifies this would then also rectify the operand issue with updating student1's grade when assigning a new variable based off its current assigned grade. Something tells me it could possibly just be how the function is structured at the moment, where perhaps the operator+ overload would need to be something similar to "int Grade::operator+(const Grade &)" rather than "Grade Grade:operator+(const Grade &)", but all of my efforts to find the proper syntax so far have been futile.
Any direction you could point me in to better understand how to get out of the situation I am in would be absolutely excellent, just don't give me the answer straight out(of course)!! Seeing as this is an assignment for class, any suggestions should only pertain to Grade.cpp and Grade.h due to GradeMain being supplied by the instructor.
Many thanks for reading :)
A: When you say
student2 = "Bill Miller";
this would involve two user-defined conversions: one from a const char * to a std::string, and the other from a std::string to a Grade. However, C++ only allows one automatic user-defined conversion to take place.
Moreover, you have a constructor that takes a std::string, but it also takes an extra parameter, so it can't be used automatically to convert a std::string to a Grade. Only constructors that can be called with a single argument can be used for conversion.
For the other error
int adjusted_grade = student1 + 4;
there is no operator+ that takes a Grade and an int, and there is no way to convert the 4 to a Grade and no way to convert a Grade to another type that could be used with adding an int.
| |
doc_23528706
|
*
*Left-click on the blue box, will activate them.
*Box can only be activated if, it is connected to Starting Point (The red box).
*Right-click on the activated box will deactivate that box, and every other boxes that are connected to the Starting Point through it.
Current Status & Problem
I have finish writing code for activating the box. Now I'm stuck with the deactivation part. As for now, right click will only deactivate the target box alone.
My goal is to make sure all the box that have lost connection to the *Starting Point* (as a result of this box deactivation) will be deactivated as well.
Fiddle & Recreate Problem
http://jsfiddle.net/8wj48bv5/3/
*
*In that fiddle, activate all 'I' and 'O' boxes.
*When we deactivate the 'I' boxes, the 'O' boxes will lost the route to the Starting Point, and they should be deactivated as well.
Part that needs to be done:
function deactivateBox(a, b) {
var r, c; // Row, Column
if (typeof a == "string") {
var coor = a.split(',');
r = parseInt(coor[0]);
c = parseInt(coor[1]);
} else {
r = parseInt(a);
c = parseInt(b);
}
var cur = $('.talent-list a[data-col-coor="' + r + ',' + c + '"]');
if (!cur.hasClass('active')) {
console.log('Not yet actived.');
return;
} else {
cur.removeClass('active');
skill_point++;
// Check and deactivate disconnected box.
removeDisconnected(r, c);
console.info('Deactivate : ', r, ',', c, skill_point, ' Talent Point left.')
}
}
function removeDisconnected(r, c) {
// Check and deactivate disconnected box.
}
Thanks!
A: I have found the solution somewhere else. For those who are interested, here's the fiddle :
http://jsfiddle.net/jd1htegL/1/
fiddle
| |
doc_23528707
|
We send OTP upon each register request and now we have hundreds of spam requests costing a lot of money due to the SMS service fee.
Rate limiting on Ip is applied.
Rate limiting on device id is also applied.
The register request is secured by adding a signature to the header using the HMAC SHA-256 algorithm, the key used to generate the signature stored in mobile code.
But it turns out that this is not enough to secure the process.
Is there any other practice we should do to solve the spam issue?
We are using Flutter for the mobile app
A: Your Problem
We have a live mobile application supporting registering with the user's mobile number. We send OTP upon each register request and now we have hundreds of spam requests costing a lot of money due to the SMS service fee.
Registering with the mobile phone number to deter spam isn't enough because a lot of services exist in the internet to provide anyone with free mobile phone numbers, that are often used to workaround registrations or any other services that require you to provide a number.
Rate limiting on Ip is applied.
Malicious users can rotate their IP address when they use a script (bot) or run your app in an emulator. Also IP addresses in mobile are very dynamic, its not like in residential broadband where they stay stable for long periods.
Rate limiting on device id is also applied.
The malicious user will rotate the device id when using a bot, an emulator or a rooted device.
Reverse Engineering
The register request is secured by adding a signature to the header using the HMAC SHA-256 algorithm, the key used to generate the signature stored in mobile code.
The malicious user will reverse engineer you mobile app statically to see how the HMAC signature is done and then replicate it on its script. In a series of articles around Mobile API Security I wrote an article about statically reverse engineering an app, while in the context of extracting an API Key the principles remain to extract the logic for the HMAC signature. You can learn how to it by yourself on your own app by applying the same basic technics I used on the article How to Extract an API key from a Mobile App with Static Binary Analysis:
The range of open source tools available for reverse engineering is huge, and we really can't scratch the surface of this topic in this article, but instead we will focus in using the Mobile Security Framework(MobSF) to demonstrate how to reverse engineer the APK of our mobile app. MobSF is a collection of open source tools that present their results in an attractive dashboard, but the same tools used under the hood within MobSF and elsewhere can be used individually to achieve the same results.
During this article we will use the Android Hide Secrets research repository that is a dummy mobile app with API keys hidden using several different techniques.
The malicious user may also reverse engineer dynamically your app to understand how it communicates with your API server in order to do exactly the same on its bot.
This is usually done with a MitM attack on a device that the malicious user controls and a lot of open-source tools exist to help with the task, being the most known ones mitmproxy and Frida. Turns out that I also wrote an article on how to use this tools, not to extract the HMAC signature, but to bypass certificate pinning, but the basic mechanics to perform the dynamic analysis are the same, therefore I invite you to try this techniques against your own app. Learn the basics of MitM attack with Frida and mitmproxy on the article Bypassing Certificate Pinning:
In this article you will learn how to repackage a mobile app in order to disable certificate pinning and in the process you will also learn how to create an Android emulator with a writable system to allow for adding the custom certificate authority for the proxy server into the Android operating system trust store. This will allow us to bypass certificate pinning and intercept the requests between the mobile and its backend with a MitM attack.
The Difference Between WHO and WHAT is Accessing the API Server
But it turns out that this is not enough to secure the process.
No, its not enough because its not that hard to bypass with the several techniques I shown above.
In order for you to improve your security posture when developing an application you first need to understand the difference between who and what is doing the request to the API server.
In the article Why Does Your Mobile App Need An Api Key? you can read in detail the difference between who and what is accessing your API server, but I will extract here the main takes from it:
The what is the thing making the request to the API server. Is it really a genuine instance of your mobile app, or is it a bot, an automated script or an attacker manually poking around your API server with a tool like Postman?
The who is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.
So think about the who as the user your API server will be able to Authenticate and Authorize access to the data, and think about the what as the software making that request in behalf of the user.
When you grasp this idea and it's ingrained in your mindset, then you will look into mobile API security with another perspective and be able to see attack surfaces that you never though they existed before.
Possible Solutions
Security must be always seen as a layered approach, where you add as many layers as needed to deter the opponent from even trying to break them, or if in the case they try they will need a lot of resources, knowledge and time. This not new to software development, its being done for centuries, like in the medieval castles and prisons.
Is there any other practice we should do to solve the spam issue?
I recommend you to read this answer I gave to the question How to secure an API REST for mobile app?, especially the sections Hardening and Shielding the Mobile App, Securing the API Server and A Possible Better Solution.
From this answer the Mobile App Attestation would be the most suitable for you to employ in order to give a very high degree of confidence to your API backend that the request is indeed from what it expects, a genuine and unmodified version of your mobile app, not from a bot, an emulator, a jail broken device or whatever other technique being used by the malicious user.
Do You Want To Go The Extra Mile?
In any response to a security question I always like to reference the excellent work from the OWASP foundation.
For APIS
OWASP API Security Top 10
The OWASP API Security Project seeks to provide value to software developers and security assessors by underscoring the potential risks in insecure APIs, and illustrating how these risks may be mitigated. In order to facilitate this goal, the OWASP API Security Project will create and maintain a Top 10 API Security Risks document, as well as a documentation portal for best practices when creating or assessing APIs.
For Mobile Apps
OWASP Mobile Security Project - Top 10 risks
The OWASP Mobile Security Project is a centralized resource intended to give developers and security teams the resources they need to build and maintain secure mobile applications. Through the project, our goal is to classify mobile security risks and provide developmental controls to reduce their impact or likelihood of exploitation.
OWASP - Mobile Security Testing Guide:
The Mobile Security Testing Guide (MSTG) is a comprehensive manual for mobile app security development, testing and reverse engineering.
| |
doc_23528708
|
Here's my pubxml
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<WebPublishMethod>MSDeploy</WebPublishMethod>
<LastUsedBuildConfiguration>XXX</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<SiteUrlToLaunchAfterPublish />
<LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
<ExcludeApp_Data>True</ExcludeApp_Data>
<MSDeployServiceURL>http://XXX</MSDeployServiceURL>
<DeployIisAppPath>XXX</DeployIisAppPath>
<RemoteSitePhysicalPath />
<SkipExtraFilesOnServer>True</SkipExtraFilesOnServer>
<MSDeployPublishMethod>RemoteAgent</MSDeployPublishMethod>
<EnableMSDeployBackup>True</EnableMSDeployBackup>
<UserName>ifinformatica\administrator</UserName>
<_SavePWD>True</_SavePWD>
<PublishDatabaseSettings>
<Objects xmlns="">
<ObjectGroup Name="default" Order="1" Enabled="False">
<Destination Path="" />
<Object Type="DbDacFx">
<PreSource Path="Data Source=XXX ;Initial Catalog=XXX ;User ID=XXX ;Password=XXX ;Application Name=XXX includeData="False" />
<Source Path="$(IntermediateOutputPath)AutoScripts\default_IncrementalSchemaOnly.dacpac" dacpacAction="Deploy" />
</Object>
<UpdateFrom Type="Web.Config">
<Source MatchValue="Data Source=XXX;Initial Catalog=XXX;User ID=XXX;Password=XXX;Application Name=XXX" MatchAttributes="$(UpdateFromConnectionStringAttributes)" />
</UpdateFrom>
</ObjectGroup>
</Objects>
</PublishDatabaseSettings>
<ADUsesOwinOrOpenIdConnect>False</ADUsesOwinOrOpenIdConnect>
<_CustomFiles Include="..\Modules***" />
%(RecursiveDir)%(Filename)%(Extension)
CustomCollectFiles;
$(CopyAllFilesToSingleFolderForPackageDependsOn);
<CopyAllFilesToSingleFolderForMsdeployDependsOn>
CustomCollectFiles;
$(CopyAllFilesToSingleFolderForPackageDependsOn);
</CopyAllFilesToSingleFolderForMsdeployDependsOn>
I'm using VS2015, and my Modules folder is correct (..\Modules)
Do you see any particular relevant error?
A: Unless I'm misunderstanding the question all you need to is set the Copy to Output Directory property to Always.
To add files that are not part of your project you can extend WebDeploy to include additional files via MSBuild by adding them to the CopyAllFilesToSingleFolderForPackageDependsOn property in VS2010. this property name changed for VS2012 to CopyAllFilesToSingleFolderForMsdeployDependsOn.
| |
doc_23528709
|
python -m nuitka --standalone --enable-plugin=tk-inter --enable-plugin=numpy --enable-plugin=librosa --enable-plugin=matplotlib program.py
| |
doc_23528710
|
AS '-1', $$
Some extra lines 1
some extra lines 2
AS '24:-1', $$
Some extra lines 3
some extra lines 4
AS 'abc-1', $$
Some extra lines 5
some extra lines 6
The output should be
AS $$
Some extra lines 1
some extra lines 2
AS $$
Some extra lines 3
some extra lines 4
AS $$
Some extra lines 5
some extra lines 6
A: You can read the lines and use split to get the first and last element from each line to determine if you want to write 'AS $$' or the original line in the new file:
with open("test.txt","r") as input_file:
lines = input_file.readlines()
with open("out.txt","w") as output_file:
for line lines:
line = line.strip() #remove newline character
values = line.split() #break up line by spaces, so AS '-1', $$ becomes ['AS', '-1,', '$$]
if values[0] == 'AS' and values[-1] == '$$':
output_file.write('AS $$\n')
else:
output_file.write(line + '\n')
A: You can read the lines and store them in a list:
with open('file.txt', 'r') as f:
text = [line for line in f]
Then you can check whether the line contains 'AS' and '$$' and if it does you can write out 'AS $$', otherwise you write out the original line:
with open('txt.txt', 'w') as f:
for t in text:
if 'AS' in t and '$$' in t:
f.write('AS $$\n')
else:
f.write(t)
A: If you don't care for what's between the 2 words you should just read how much lines you have and write "AA $$" for the number of lines x)
No need to complexify the problem !
| |
doc_23528711
|
I'm aware of KeQuerySystemTime (but this is 1601 based).
i found this solution.
LONGLONG FileTime_to_POSIX(FILETIME ft)
{
// takes the last modified date
LARGE_INTEGER date, adjust;
date.HighPart = ft.dwHighDateTime;
date.LowPart = ft.dwLowDateTime;
// 100-nanoseconds = milliseconds * 10000
adjust.QuadPart = 11644473600000 * 10000;
// removes the diff between 1970 and 1601
date.QuadPart -= adjust.QuadPart;
// converts back from 100-nanoseconds to seconds
return date.QuadPart / 10000000;
}
but this seems to be wrong, i tested it and it was round about 10 seconds wrong
| |
doc_23528712
|
So, I don't want to invent the wheel and I think that it's not very good to reimplement the follow_page functionality by hand.
A: Well, it might looks as something like that (follow PTE from an virtual address):
void follow_pte(struct mm_struct * mm, unsigned long address, pte_t * entry)
{
pgd_t * pgd = pgd_offset(mm, address);
printk("follow_pte() for %lx\n", address);
entry->pte = 0;
if (!pgd_none(*pgd) && !pgd_bad(*pgd)) {
pud_t * pud = pud_offset(pgd, address);
struct vm_area_struct * vma = find_vma(mm, address);
printk(" pgd = %lx\n", pgd_val(*pgd));
if (pud_none(*pud)) {
printk(" pud = empty\n");
return;
}
if (pud_huge(*pud) && vma->vm_flags & VM_HUGETLB) {
entry->pte = pud_val(*pud);
printk(" pud = huge\n");
return;
}
if (!pud_bad(*pud)) {
pmd_t * pmd = pmd_offset(pud, address);
printk(" pud = %lx\n", pud_val(*pud));
if (pmd_none(*pmd)) {
printk(" pmd = empty\n");
return;
}
if (pmd_huge(*pmd) && vma->vm_flags & VM_HUGETLB) {
entry->pte = pmd_val(*pmd);
printk(" pmd = huge\n");
return;
}
if (pmd_trans_huge(*pmd)) {
entry->pte = pmd_val(*pmd);
printk(" pmd = trans_huge\n");
return;
}
if (!pmd_bad(*pmd)) {
pte_t * pte = pte_offset_map(pmd, address);
printk(" pmd = %lx\n", pmd_val(*pmd));
if (!pte_none(*pte)) {
entry->pte = pte_val(*pte);
printk(" pte = %lx\n", pte_val(*pte));
} else {
printk(" pte = empty\n");
}
pte_unmap(pte);
}
}
}
}
A: I think you can achieve virtual->physical translation through an indirect method by a combination of /proc/[pid]/maps ( gives the virtual mapping for a process ) and /proc/[pid]/pagemap( Gives Virtual Page to Physical Page mapping for every addressable page ). First, find out the mapping of virtual addresses of your process from maps ( This is done so that you don't search every byte in pagemap ) Then check for the physical mapping of the desired virtual address in pagemap ( pagemap is not in text format. Here is a detailed explantion of the format Pagemap )
This should give you the exact virtual-->physical mapping
A: It sounds like you're looking for virt_to_phys.
| |
doc_23528713
|
I'm trying to make a simple little thing which will display two images side by side, as large as the window will allow.
In theory what happening is:
*
*We get an imageIcon, in this case 001.jpg.
*We figure out the ratio of width/height of the imageIcon.
*We turn the imageIcon into an image.
*We turn that image into a new correctly sized image.
*We turn that image back into an image icon.
This all breaks down because the only way I've found to get the window size is size, but that keeps returning 0s.
This is the code I have right now:
class UI extends MainFrame {
title = "Matt's window header"
preferredSize = new Dimension(1920, 1080)
var imageIcon = new ImageIcon("001.jpg")
val imgRatio = imageIcon.getIconWidth.toDouble / imageIcon.getIconHeight.toDouble
println(size)
pack()
println(imgRatio)
val image = imageIcon.getImage()
val newimg = image.getScaledInstance(size.width, (size.width * imgRatio.toInt), java.awt.Image.SCALE_SMOOTH)
imageIcon = new ImageIcon(newimg)
contents = new Label {
icon = imageIcon
}
}
As an aside, it would be great if someone could give me info about how to load a different image, instead of just 001.jpg.
A: sizeis not determined at the point you are accessing it.
However, preferredSizeis. If you add println(preferredSize) you will get the Dimensions you just set.
| |
doc_23528714
|
code
Sub RefreshSalesData()
Dim Location9 As String
Dim Archive9 As String
Dim Location9Archive9 As String
Sheets("Data").Select
Range("Q1048576").Select
Selection.End(xlUp).Select
ActiveCell.Offset(1, 0).Select
ActiveCell.Value = Now()
Location9 = "C:\Users\fred\Documents\data_to_refresh"
Archive9 = "SalesData.xlsx"
Location9Archive9 = Location9 & Archive9
A: 1048576 is a hard-coded last row number in Q column. It is rather bad practice, because it is not compatible with older .xls format (.xlsx has exactly 1048576 rows, .xls about 65k) and would cause run-time error, because 1048576 row doesn't exists in .xls files. But even worse is using select for no purpose How to avoid select.
Change this fragment:
Sheets("Data").Select
Range("Q1048576").Select
Selection.End(xlUp).Select
ActiveCell.Offset(1, 0).Select
ActiveCell.Value = Now()
To:
With ThisWorkbook.Sheets("Data")
.Cells(.Rows.Count, "Q").End(xlUp).Offset(1, 0).Value = Now()
End With
Also remeber to fully qualify your ranges. For example:
Sheets("Data")
is implicite the same as:
ActiveWorkbook.Sheets("Data")
which can be dangerous probably if you have few workbooks open. If you want to make changes in current workbook (which contains the macro code), you can use:
ThisWorkbook.Sheets("Data")
| |
doc_23528715
|
NOTE: the current web address used will likely change week to week so it may not be a valid address in the future.
Current Code:
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wait
driver = webdriver.Chrome()
driver.get("https://sports.yahoo.com/dailyfantasy/contest/5416455/setlineup")
response = wait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME,"data-tst-player-id")))
driver.quit
soup = BeautifulSoup(response, 'lxml')
with open('test.txt','w', encoding='utf-8') as f_out:
f_out.write(soup.prettify())
A: There is no element with the class-name or id that you are providing in the line
response = wait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME,"data-tst-player-id")))
there is however, some tags with the attribute 'data-tst', so you can use that to make sure your page has loaded, and on this line
driver.quit
you are doing nothing, you have to call the function driver.quit().
working code:
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait as wait
driver = webdriver.Chrome()
driver.get("https://sports.yahoo.com/dailyfantasy/contest/5416455/setlineup")
wait(driver, 1).until(EC.presence_of_element_located((By.CSS_SELECTOR,"[data-tst]")))
response=driver.page_source
driver.quit()
soup = BeautifulSoup(response, 'lxml')
with open('test.txt','w', encoding='utf-8') as f_out:
f_out.write(soup.prettify())
| |
doc_23528716
|
Let's assume that I have a batch of one single channel 5x5 matrix called M and that I want to extract a 3x3 matrix of it.
When I call extract_glimpse([M], [3,3], [[1,1]], centered=False, normalized=False), it returns the result I am expecting: the 3x3 matrix centered at the position (1,1) in M.
But when I call extract_glimpse([M], [3,3], [[2,1]], centered=False, normalized=False), it doesn't return the 3x3 matrix centered at the position (2,1) in M but it returns the same as in the first call.
What is the point that I don't get?
A: The pixel coordinates actually have a range of 2 times the size (not documented - so it is a bug indeed). This is at least true in the case of centered=True and normalized=False. With those settings, the offsets range from minus the size to plus the size of the tensor. I therefore wrote a wrapper that is more intuitive to numpy users, using pixel coordinates starting at (0,0). This wrapper and more details about the problem are available on the tensorflow GitHub page.
For your particular case, I would try something like:
offsets1 = [-5 + 3,
-5 + 3]
extract_glimpse([M], [3,3], [offsets1], centered=True, normalized=False)
offsets2 = [-5 + 3 + 2,
-5 + 3]
extract_glimpse([M], [3,3], [offsets2], centered=True, normalized=False)
| |
doc_23528717
|
char **words = (char **)malloc(sizeof(char*)*lines_allocated);
...
words = (char **)realloc(words,sizeof(char*)*new_size);
...
Please could you help me understand them?
A: char **words = (char **)malloc(sizeof(char*)*lines_allocated);
Allocates lines_allocated pointers. When you use pointer to pointers you need to allocate space for the pointers, and them for each of those pointers you allocate space for you data, in this case, a char *.
words = (char **)realloc(words,sizeof(char*)*new_size);
This changes the size of the buffer, as the number of lines is unknown before you read the file, then you need to increase the number of pointers you allocate.
words points to a block that will store lines_allocated pointers at first moment and then it will be increased to new_size when needed.
In your code you also have a line like this:
/* Allocate space for the next line */
words[i] = malloc(max_line_len);
Which will allocate each string separately.
Also, don't cast the result of malloc:
*
*Do I cast the result of malloc?
A: The first line allocates a pointer to a pointer to character. A pointer to something in C is equivalent to a pointer to an array of that same something, so this is equivalent to saying that it allocates a pointer to an array of pointers to char.
sizeof(char*) is the size of a pointer, and multiplying it by lines_allocated means that the number of pointers in the allocated array will be lines_allocated.
The second line reallocates the array of pointers so that it may now contain new_size pointers instead of lines_allocated pointers. If new_size is larger, the new pointers will be undefined, and must be initialized before being used.
A: The first line allocates a chunk of dynamic memory (creates space for an array of pointers to char); the second line resizes that chunk.
A better way to write both lines is
char **words = malloc( sizeof *words * lines_allocated); // no cast, operand of sizeof
char **tmp = realloc( words, sizeof *words * new_size );
if ( tmp )
words = tmp;
In C, you don't need to cast the result of either call, and it's considered bad practice to do so. Also, note the operand to sizeof; if you ever change the base type of words (from char to wchar_t, for example), you won't have to change the malloc or realloc calls.
realloc will return NULL if it can't extend the buffer, so it's safer to assign the result to a temporary variable first, otherwise you risk losing your reference to that memory, meaning you won't be able to access or release it.
| |
doc_23528718
|
Container1 is created using a docker-compose-file and creates a file in his local file-system. Then it starts another container Container2 as a sibling. The created file in Container1 should be passed to Container2 for further processing.
I've tried using a volume, but without any success. The shared volume contains the files when I execute ls inside Container1, but if I execute the same command in Container2, the mounted volume is empty.
What am I missing?
A: Dear Mamen the best way of sharing data between containerized apps/services is not file-sharing.
There are some best practices that I can point below:
*
*Share your file using HTTP-based api between containers. (In your case share your file privately with Nginx is through a bridge network between docker containers.
*Share your data/blob using Queue Management services like Active|Rabbit|Zero MQ.
*POST your file to the receiver container using HTTP api (through a bridge between docker containers
Anyway, you can share data through volumes created and located in Host. To be clarified you can see this sample.
| |
doc_23528719
|
- (IBAction)linkedin:(id)sender {
A0Lock *lock = [MyApplication sharedInstance].lock;
A0APIClient *client = [lock apiClient];
A0APIClientAuthenticationSuccess success = ^(A0UserProfile *profile, A0Token *token) {
NSLog(@"We did it!. Logged in with Auth0.");
};
A0APIClientError failure = ^(NSError *error){
NSLog(@"Oops something went wrong: %@", error);
};
A0AuthParameters *params = [A0AuthParameters newDefaultParams];
params[A0ParameterConnection] = @"linkedin"; // Or your configured DB connection
[client authenticateWithSocialConnectionName:@"linkedin"credentials:@"token" parameters:nil success:success failure:failure];
My aim is simple, i try to create social login connection via using auth0. In the quickstart documentation of auth0 there is a sample which is using controller, and i also add custom connections.
- (IBAction)signUp:(id)sender {
A0Lock *lock = [[MyApplication sharedInstance] lock];
A0LockViewController *controller = [lock newLockViewController];
controller.connections=@[@"facebook", @"linkedin"];
controller.useWebView=YES;
controller.onAuthenticationBlock = ^(A0UserProfile *profile, A0Token *token) {
// Do something with token & profile. e.g.: save them.
// And dismiss the ViewController
[self dismissViewControllerAnimated:YES completion:nil];
};
[self presentViewController:controller animated:YES completion:nil];}}
But i cant use this because i need custom UI, i want to do this without controller. Can you please help me, what i m doing wrong in "authenticateWithSocialConnectionName" part. Thank you very much.
| |
doc_23528720
|
In my Asp.net MVC 4 app, I'm trying to register a new user this way:
var transactionOptions = new TransactionOptions
{
IsolationLevel = IsolationLevel.ReadCommitted,
Timeout = TransactionManager.MaximumTimeout
};
using (var transactionScope = new TransactionScope(TransactionScopeOption.Required, transactionOptions))
{
var confirmationToken = WebSecurity.CreateUserAndAccount(
vm.Email,
vm.Password,
new
{
AccountCreationDate = DateTime.Now,
City = vm.City,
(...)
},
true);
Roles.AddUserToRole(vm.Email, "Client");
// Some other job on DbContext in Repository
var userRepository = new UserRepository();
userRepository.AssignData(vm.Email);
transactionScope.Complete();
}
As you can see, I'm trying to create both an user account and membership entry, assign a role and then do some additional stuff on EF5 DbContext via repository.
This code is wrapped within a try-catch block, which I don't include here for brevity.
And here comes my question: is it possible to wrap all this 3 hits to the Database (respectively through WebSecurity, Roles and Repository) with one transaction WITHOUT letting it to escalate to DTC?
I'm using SQL Server 2012, one DB and the same connection string if it helps.
| |
doc_23528721
|
123,00
212,11
1.212,00
With
SELECT MIN(FIELD) FROM XYZ
I get "1.212,00". This is wrong for me, but not wrong for MySQL.
I need the following: 123,00.
How can I do this without changing the field type?
TIA Matt
A: You should cast your char value to numeric value.
select min(
CAST( replace(
replace ( FIELD, '.', '' ),
',', '.'
)
AS DECIMAL(5,2))
) ...
A: Use Cast or Convert:
The CONVERT() and CAST() functions take a value of one type and produce a value of another type.
SELECT MIN(CAST(Field AS DECIMAL(10,2))) FROM XYZ
http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html#function_cast
| |
doc_23528722
|
-(void)viewDidLoad {
UINib *cellNib = [UINib nibWithNibName:@"NibCell" bundle:nil];
[self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"cvCell"];
self.collectionView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"shelves.png"]];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
NSLog(@"1");
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [_allEntries count];
NSLog(@"2");
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
static NSString *cellIdentifier = @"cvCell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
UIImageView *titleLabel = (UIImageView *)[cell viewWithTag:100];
UILabel *titleLabel2 = (UILabel *)[cell viewWithTag:200];
NSString *thearticleImage = entry.articleImage;
[titleLabel setImageWithURL:[NSURL URLWithString:entry.articleImage] placeholderImage:[UIImage imageNamed:@"icon@2x.png"]];
// [titleLabel2 setText:entry.articleTitle];
return cell;
}
I am using an XIB to create the collectionView cell.
When there are only 2 issues, it looks fine, but as more and more issues get added and you begin to have to scroll, they get quite off:
A: Your calculation of your UICollectionViewCell with paddings between cells could be kind a wrong. You can either play with size of images or set the size of cell programmatically:
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(192.f, 192.f);
}
You can also play with paddings in Interface Builder.
You can also do this programmatically:
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setItemSize:CGSizeMake(100, 200)];
[flowLayout setMinimumInteritemSpacing:10];
[flowLayout setMinimumLineSpacing:10];
| |
doc_23528723
|
I want to display only the elements that I have access to instead of displaying all the code in the classes that I am not authorized to edit. What can I do ? I am using Visual Studio 2022.
A: From your question, you are using (CTRL + mouse click) to open the source code to display all the source code, you should probably select Enable Navigation to Decompiled Source Code in the settings, you can cancel this option.
It is possible to change the source code that cannot be defined for a member to display its metadata. Can view declarations of types and members, but not implementations
To do this: Select "Tools" > "Options" from the menu bar. Then, expand Text Editor > C# > Advanced and uncheck "Enable Navigation to Decompiled Source"
| |
doc_23528724
|
A first chance exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error in INSERT INTO statement.
If there is a handler for this exception, the program may be safely continued.
I used the following code.please see if there is any error..please help me out for it..
The Code is:
Private Sub frmGive_Load(sender As Object, e As EventArgs) Handles Me.Load
con = New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;Data Source=C:\Users\AntivirUS Vandry\Documents\Visual Studio 2013\Projects\Give And Get\dbaseMain.mdb")
Dim sql As String = "Select * from tblGive"
Dim dbcmd As OleDbCommand = New OleDbCommand(sql, con)
con.Open()
Dim dbadapter As OleDbDataAdapter = New OleDbDataAdapter(sql, con)
Dim db As DataSet = New DataSet("TABLE")
dbadapter.Fill(db, "TABLE")
'create new instance of table so that row can be accessed
Dim dt As New DataTable
dt = db.Tables("TABLE")
CmbGenre.Text = dt.Rows(0)(0)
CmbLanguage.Text = dt.Rows(0)(1)
txtNMovie.Text = dt.Rows(0)(2)
txtFName.Text = dt.Rows(0)(3)
txtLname.Text = dt.Rows(0)(4)
CmbClass.Text = dt.Rows(0)(5)
txtnull.Text = dt.Rows(0)(6)
End Sub
There are some codes in between them.Including textboxes and combo boxes.
Public Sub submit()
con = New OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;Data Source=C:\Users\AntivirUS Vandry\Documents\Visual Studio 2013\Projects\Give And Get\dbaseMain.mdb")
con.Open()
Dim sql As String
sql = "Insert into tblGive (Genre,Language,NMovie,FName,LName,Class,SaveDate)" + "VALUES (" & CmbGenre.Text & "','" & CmbLanguage.Text & "','" & txtNMovie.Text & "','" & txtFName.Text & "','" & txtLname.Text & "','" & CmbClass.Text & "','" & txtnull.Text & "')"
MsgBox(sql)
Dim dbcmd As OleDbCommand
dbcmd = New OleDbCommand(sql, con)
dbcmd.ExecuteNonQuery()
MsgBox("Saved")
End Sub
A: You are missing a single quote at the beginning of the values keyword.
In other words,
VALUES (" & CmbGenre.Text & "','" & CmbLanguage.Text &
should be
VALUES ('" & CmbGenre.Text & "','" & CmbLanguage.Text &
| |
doc_23528725
|
So, is it possible to compile a Phonegap project directly on the iDevice? In other words, I need to "convert" a web app in Phonegap format into an iOS application, like it is done in XCode.
P.S. The SDK I have installed is of version 3.2
Progress Report: Following the suggestion by user hatunike (here) I tried to link the PhoneGap framework into a dummy project on my iPod to see if it works. It does not. Looks like PhoneGap uses some features that were only introduced in iOS 4. The developers say it is possible to compile a PhoneGap application for an older iOS by weak-linking UIKit, AVFoundation and CoreMedia. Problem is, weak-linking those frameworks requires a newer iOS SDK than the target SDK.
A: try this:
http://build.phonegap.com/
you still need to have a developer key from Apple but your jailbroken iPod should allow you to put the built file on your device. its free for 1 private app.
| |
doc_23528726
|
Here is a sample code
async function initGatewayForOrg1() {
console.log(`${GREEN}--> Fabric client user & Gateway init: Using Org1 identity to Org1 Peer${RESET}`);
const ccpOrg1 = buildCCPOrg1();
const caOrg1Client = buildCAClient(FabricCAServices, ccpOrg1, 'ca.org1.example.com');
const walletPathOrg1 = path.join(__dirname, 'wallet', 'org1');
const walletOrg1 = await buildWallet(Wallets, walletPathOrg1);
await enrollAdmin(caOrg1Client, walletOrg1, org1);
await registerAndEnrollUser(caOrg1Client, walletOrg1, org1, Org1UserId, 'org1.department1');
try {
const gatewayOrg1 = new Gateway();
await gatewayOrg1.connect(ccpOrg1,
{ wallet: walletOrg1, identity: Org1UserId, discovery: { enabled: true, asLocalhost: true } });
return gatewayOrg1;
} catch (error) {
console.error(`Error in connecting to gateway for Org1: ${error}`);
process.exit(1);
}
}
async function main() {
console.log(`${GREEN} **** START ****${RESET}`);
try {
const gatewayOrg1 = await initGatewayForOrg1();
const networkOrg1 = await gatewayOrg1.getNetwork(channelName);
const channelOrgs = networkOrg1.getOrganizations();
} catch (error) {
console.error(`Error in setup: ${error}`);
if (error.stack) {
console.error(error.stack);
}
process.exit(1);
}
console.log(` **** END ****`);
}
main();
But the output is:
Error in setup: TypeError: networkOrg1.getOrganizations is not a function
TypeError: networkOrg1.getOrganizations is not a function
Does anybody what is the error? Or any other solution?
A: You don't say which version of the node-sdk you are using so
The error is saying that there is no getOrganizations method on networkOrg1 which is correct, that method does not exist on the network object in either node-sdk 1.4 or node-sdk 2.2
That method only exists on the channel object in node-sdk 1.4 (ie not in node-sdk 2.2). In node-sdk 1.4 you can get the channel object from the network object using the getChannel method.
| |
doc_23528727
|
Here is flutter doctor result
[√] Flutter (Channel stable, 2.10.2, on Microsoft Windows [Version 10.0.19043.1526], locale en-US)
• Flutter version 2.10.2 at D:\flutter_windows_2.2.3-stable\flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision 097d3313d8 (4 days ago), 2022-02-18 19:33:08 -0600
• Engine revision a83ed0e5e3
• Dart version 2.16.1
• DevTools version 2.9.2
[√] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
• Android SDK at C:\Users\dangm\AppData\Local\Android\sdk
• Platform android-31, build-tools 31.0.0
• Java binary at: C:\Program Files\Android\Android Studio1\jre\bin\java
• Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)
• All Android licenses accepted.
[√] Chrome - develop for the web
• Chrome at C:\Program Files\Google\Chrome\Application\chrome.exe
[√] Visual Studio - develop for Windows (Visual Studio Build Tools 2019 16.11.3)
• Visual Studio at C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools
• Visual Studio Build Tools 2019 version 16.11.31702.278
• Windows 10 SDK version 10.0.19041.0
[√] Android Studio (version 2020.3)
• Android Studio at C:\Program Files\Android\Android Studio1
• Flutter plugin can be installed from:
https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)
[√] VS Code (version 1.63.2)
• VS Code at C:\Users\dangm\AppData\Local\Programs\Microsoft VS Code
• Flutter extension can be installed from:
https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter
[√] Connected device (4 available)
• SM G977N (mobile) • R3CM70DLX9F • android-arm64 • Android 11 (API 30)
• Windows (desktop) • windows • windows-x64 • Microsoft Windows [Version 10.0.19043.1526]
• Chrome (web) • chrome • web-javascript • Google Chrome 98.0.4758.102
• Edge (web) • edge • web-javascript • Microsoft Edge 97.0.1072.62
[√] HTTP Host Availability
• All required HTTP hosts are available
• No issues found!
A: I think the main problem was using the old version of flutter (as Zorrilla mentioned), upgrading Flutter speed it up a lot. At the same time, the build() function is triggered repeatedly, so we need to control it more carefully
| |
doc_23528728
|
package main
import (
. "fmt"
"runtime"
)
func Goroutine1(i_chan chan int, done chan bool) {
for x := 0; x < 1000000; x++ {
i := <-i_chan
i++
i_chan <- i
}
done <- true
}
func Goroutine2(i_chan chan int, done chan bool) {
for x := 0; x < 1000000; x++ {
i := <-i_chan
i--
i_chan <- i
}
done <- true
}
func main() {
i_chan := make(chan int, 1)
done := make(chan bool, 2)
i_chan <- 0
runtime.GOMAXPROCS(runtime.NumCPU())
go Goroutine1(i_chan, done)
go Goroutine2(i_chan)
<-done
<-done
Printf("This is the value of i:%d\n", <-i_chan)
}
However when I try to run it with out any synchronisation. Using a wait statement and no channel to specify when it's done so no synchronisation.
const MAX = 1000000
func Goroutine1(i_chan chan int) {
for x := 0; x < MAX-23; x++ {
i := <-i_chan
i++
i_chan <- i
}
}
func main() {
i_chan := make(chan int, 1)
i_chan <- 0
runtime.GOMAXPROCS(runtime.NumCPU())
go Goroutine1(i_chan)
go Goroutine2(i_chan)
time.Sleep(100 * time.Millisecond)
Printf("This is the value of i:%d\n", <-i_chan)
}
It'll print out the wrong value of i. If you extend the wait for let say 1 sec it'll finish and print out the correct statement. I kind of understand that it has something with both thread not being finished before you print what's on the i_chan I'm just a bit curious about how this works.
A: Note that your first example would deadlock, since it never calls GoRoutine2 (the OP since edited the question).
If it calls GoRoutine2, then the expected i value is indeed 0.
Without synchronization, (as in this example), there is no guarantee that the main() doesn't exit before the completion of Goroutine1() and Goroutine2().
For a 1000000 loop, a 1 millisecond wait seems enough, but again, no guarantee.
func main() {
i_chan := make(chan int, 1)
i_chan <- 0
runtime.GOMAXPROCS(runtime.NumCPU())
go Goroutine2(i_chan)
go Goroutine1(i_chan)
time.Sleep(1 * time.Millisecond)
Printf("This is the value of i:%d\n", <-i_chan)
}
see more at "How to Wait for All Goroutines to Finish Executing Before Continuing", where the canonical way is to use the sync package’s WaitGroup structure, as in this runnable example.
| |
doc_23528729
|
how can i used wsdl's as service reference in C# application they import as reference but not create endpoint and binding in app.confg file because complexTyple same in both file how can Microsoft handle this issue.
<xs:complexType name="EventOutKeysType">
<xs:sequence>
<xs:element minOccurs="0" name="evsysseq" nillable="true"
type="cmn:StringType"/>
</xs:sequence>
<xs:attribute name="query" type="xs:string" use="optional"/>
<xs:attribute name="updatecounter" type="xs:long" use="optional"/>
</xs:complexType>
<xs:complexType name="EventOutInstanceType">
----------------
<xs:complexType name="EventOutKeysType">
<xs:sequence>
<xs:element minOccurs="0" name="evsysseq" nillable="true"
type="cmn:StringType"/>
</xs:sequence>
<xs:attribute name="query" type="xs:string" use="optional"/>
<xs:attribute name="updatecounter" type="xs:long" use="optional"/>
</xs:complexType>
<xs:complexType name="EventOutInstanceType">
you see they have different links but same xml,
like
..../SM/EventOut.wsdl
..../SM/EventManagement.wsdl
please advice
| |
doc_23528730
|
I have a a main table, Projects, with a o2m relationship to a second table Changes. This second table is quite wide so I would like to be able to segment the information across several subforms on different tabs.
I've created a main form, the tabs and the subforms on each tab and the presentation is fine. The problem comes when I create a new record. On the first tab (containing subform1), I create a new record and fill in some values. When I click on the second tab (subform2), the new record is not there. My question is how can I keep the different subforms all in sync?
I've tried to do a Requery of subform 2 using the OnClick event on the second tab but to no avail. I could be just doing that incorrectly.
Any ideas please?
Thanks,
Jon C
| |
doc_23528731
|
While I am trying to automate the same in UFT I am getting steps in single quotes in query as comments. How to execute the procedure successfully and get the output?
my procedure
my planned UFT code
Set cm = CreateObject(”ADODB.Command”)
cm.ActiveConnection = str
' Set the command type to Stored Procedures'
cm.CommandType = 4
' Stored Procedures'
cm.CommandText = strProc
' Define Parameters for the stored procedure'
cm.Execute()
| |
doc_23528732
|
I've been trying to design a table whose first row (header) contains input fields for each of the columns displayed, but I can't seem to find a way to distribute said fields on their own columns. They all get crammed into the first column of the table.
<table>
<thead>
<tr>
<th scope="col">
{/* TODO: Fix this form as it currently loads into a single column */}
<Formik
initialValues={hobbyInitialValues}
onSubmit={SubmitHobby}
validationSchema={ValidateHobby}
>
<Form>
<Field className="selectField" as="select" name="passion">
<option value="" label="Select Passion" />
<option value="Low" label="Low" />
<option value="Medium" label="Medium" />
<option value="High" label="High" />
</Field>
<Field
className="inputField"
id="inputHobbyName"
name="name"
placeholder="Enter User Hobby"
/>
<Field
className="inputField"
id="inputYear"
name="year"
placeholder="Enter Year"
/>
<button className="submitButton" type="submit">
Add
</button>
</Form>
</Formik>
</th>
</tr>
</thead>
<tbody>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
</tr>
</tbody>
</table>
Attempting to surround a single field within a results in this error, as both Formik and React Tables restrict what children can a component have:
Warning: validateDOMNesting(...): <form> cannot appear as a child of <tr>.
How can I achieve the intended result?
EDIT: my issue was solved thanks to Wraithy's answer. Code is now as follows:
<Formik
initialValues={hobbyInitialValues}
onSubmit={SubmitHobby}
validationSchema={ValidateHobby}
>
<Form>
<table>
<thead>
<tr>
<th scope="col">
<Field className="selectField" as="select" name="passion">
<option value="" label="Select Passion" />
<option value="Low" label="Low" />
<option value="Medium" label="Medium" />
<option value="High" label="High" />
</Field>
</th>
<th scope="col">
<Field
className="inputField"
id="inputHobbyName"
name="name"
placeholder="Enter User Hobby"
/>
</th>
<th scope="col">
<Field
className="inputField"
id="inputYear"
name="year"
placeholder="Enter Year"
/>
</th>
<th scope="col">
<button className="submitButton" type="submit">
Add
</button>
</th>
</tr>
</thead>
<tbody>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
</tr>
</tbody>
</table>
</Form>
</Formik>
A: You can just wrap your whole Table in <Formik>
<Formik
initialValues={hobbyInitialValues}
onSubmit={SubmitHobby}
validationSchema={ValidateHobby}
>
<table>
<!-- table with more columns go there -->
</table>
</Formik>
| |
doc_23528733
|
'apple', '#apple', ' apple', ' apple ', '#orange#apple'
Here is my python regex:
r"\b#?apple\b"
My feeble attempt at converting this to javascript was :
/\b#?apple\b/i
But it doesn't seem to work. Can anyone help?
A: Put the word boundary \b after the # char:
/#?\bapple\b/
| |
doc_23528734
|
My question is: Assuming a server has an endpoint that serves up json, are there any modifications necessary on the server to make use of jsonp in the client?
I think no, but want to be sure....
A: Yes, JSONP is slightly different when it renders, so your server needs to support it.
JSON looks like this:
{ "name": "value" }
Whereas JSONP looks like this:
functionName({ "name": "value" });
If whatever you're using supports it you're covered, but it's not the same as supporting just JSON. When the server gets a request, for example: http://example.com/json?callback=functionName, the above is what you should render, because how it looks in the page is this:
<script type="text/javascript" src="http://example.com/json?callback=functionName"></script>
This means something that runs needs to be returned, as an illustration, this is valid:
<script type="text/javascript">
functionName({ "name": "value" });
</script>
If your server didn't support JSONP it would effectively be this:
<script type="text/javascript">
{ "name": "value" }
</script>
...and you'll get syntax errors, since that's not valid JavaScript.
| |
doc_23528735
|
http://www.sitecrafting.com/blog/php-patterns-part-ii/
And i was wondering where should it be placed the domain logic. (methods to deal only with the object data, algoritms etc.)
Should it be at the VO classes? Or i should create another package for the domain logic classes?
It is not related with the DB so i assume it won't be placed on the DAO classes.
Thanks.
A: Logic that deals with data should go into the model, after the data has been extracted by your DAO and "processed" or "formatted" by your VO, following the pattern you reference in your question.
Here's a possible structure that could work in your scenario:
----- DAO -----------> VO -------> Model ----> Controller --------> View
UsersDatabase ----> UsersVO ----> User ----> UserProfile ---> UserProfilePage
Hopefully the class names are self-explanatory. In this example, any logic related with an user that doesn't deal with the interface would fit right into the User model.
And IMHO, but this just my opinion, unless your models are extremely large or you have a number of unrelated models that rely on the same data "processing/formatting" logic, you will want to skip the VO altogether and have the DAO communicate with your model directly.
| |
doc_23528736
|
findpos is used for finding position of an element
let delete x l =
let pos = findpos x l in
let rec remove_at pos l = function
[] -> []
| h :: t ->
if pos = 1 then n t else h :: remove_at pos t
;;
A: Every let in OCaml (except at the top level of a module) requires a matching in. Your first let is at the top level of a module. Your second let has a matching in. Your third let doesn't have an in. I suspect that's the error you're asking about.
| |
doc_23528737
|
http://i.stack.imgur.com/ZZfEg.jpg
And I don't know how to resize a text of the width of the view.
Without the ScrollView I can do a good structured view but when I use ScrollView I cannot get a good view, how to do ?
Code here: http://pastebin.com/LN5FySku
A: I think this task is very easy if you use code rather than storyboard.
Use this code..
You can do this in Storyboard as well but i prefer using code for such tasks. Hope that helped.
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 520)]; // little less than 568 to accommodate the tabBar
[scrollView setContentSize:CGSizeMake(320, 1500)];
UIView *largeView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 320, 100)];
[scrollView addSubview:largeView];
[self.view addSubview:scrollView];
for further more information check this link.
A: My problem is solved, the reasons:
UIImageView: I think my view have lost the images when i did a copy past of the view, so click on your UIImageView and set the image field.
UILabel: For the cropped text you have to create the Equal Width Constraint between the ContentView and the View, select the ContentView on the view hierarchy and Control + Drag to the View – you should get a pop-up that gives you the “Equal Widths” option.
| |
doc_23528738
|
Strange thing is that it actually creates correct files and folders by the given patterns, so it definitely do something with the config file. Besides that, loggers and appenders aren't working at all.
I also tried to use various other configuration files I found on examples - not even one worked, so I'm suspicious that there is some collision between used libraries and logback. I tried to google it, but found nothing relevant or working.
Have anyone of you came around ( or hopefully through ) such a problem? Or please point at the wrong line...
Thx in advance...
Kamil
Next code shows initialization:
public static final String LOGGER_CONFIG_FILE = "hacs.logger.conf";
public static final String LOGGER_CONFIG_FILE_DEFAULT = "./conf/logconf.xml";
public static void main( String[] args ) {
File configurationFile = new File(HACSProperties.instance().getProperty(LOGGER_CONFIG_FILE, LOGGER_CONFIG_FILE_DEFAULT));
if( configurationFile.exists() ){
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
context.reset(); // When this is commented, logback works in some default configuration
try {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
configurator.doConfigure( LOGGER_CONFIG_FILE_DEFAULT );
System.out.println("Logger successfully configured..");
Logger log = LoggerFactory.getLogger("analytics");
log.info( "Please appear in file" );
} catch (JoranException je) {
System.out.println("Error - failed to configure logger. Please check configuration.");
je.printStackTrace();
System.exit( 1 );
}
} else {
System.out.println("Error - failed to configure logger - configuration file does not exist. Please check configuration.");
System.exit( 2 );
}
}
Config file itself:
<configuration>
<timestamp key="bySecond" datePattern="dd.MM.yyyy'_T'HH.mm.ss" timeReference="contextBirth" />
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>./logs/HACS_LAST_RUN.log</file>
<append>false</append>
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n
</Pattern>
</layout>
</appender>
<appender name="FILE_PER_MINUTE" class="ch.qos.logback.core.FileAppender">
<file>./logs/PER_MINUTE/HACS-RUN-${bySecond}.log</file>
<append>false</append>
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n
</Pattern>
</layout>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>%d{HH:mm:ss.SSS} %level [%file:%line] %msg%n</Pattern>
</layout>
</appender>
<logger name="org.hibernate" additivity="false">
<level value="warn" />
<appender-ref ref="FILE" />
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE_PER_MINUTE" />
</logger>
<logger name="FILE_ONLY" additivity="false">
<level value="INFO" />
<appender-ref ref="FILE_PER_MINUTE" />
<appender-ref ref="FILE" />
</logger>
<root>
<level value="INFO" />
<appender-ref ref="FILE" />
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE_PER_MINUTE" />
</root>
</configuration>
List of libraries:
*antlr-2.7.7.jar
*aopalliance-1.0.jar
*asm-3.3.jar
*bcprov-jdk15-1.43.jar
*cglib-2.2.jar
*chronicle.jar
*commons-collections-3.2.1.jar
*commons-lang-2.5.jar
*commons-logging-1.1.1.jar
*commons-pool-1.5.2.jar
*cxf-2.3.0.jar
*cxf-manifest.jar
*cxf-xjc-boolean-2.3.0.jar
*cxf-xjc-bug671-2.3.0.jar
*cxf-xjc-dv-2.3.0.jar
*cxf-xjc-ts-2.3.0.jar
*dom4j-1.6.1.jar
*FastInfoset-1.2.8.jar
*felix.jar
*geronimo-activation_1.1_spec-1.1.jar
*geronimo-annotation_1.0_spec-1.1.1.jar
*geronimo-javamail_1.4_spec-1.7.1.jar
*geronimo-jaxws_2.2_spec-1.0.jar
*geronimo-jms_1.1_spec-1.1.1.jar
*geronimo-servlet_3.0_spec-1.0.jar
*geronimo-stax-api_1.0_spec-1.0.1.jar
*geronimo-ws-metadata_2.0_spec-1.1.3.jar
*groovy-all-1.8.5.jar
*h2-1.3.154.jar
*hibernate-jpa-2.0-api-1.0.0.Final.jar
*hibernate3.jar
*javassist-3.12.0.GA.jar
*jaxb-api-2.2.1.jar
*jaxb-impl-2.2.1.1.jar
*jaxb-xjc-2.2.1.1.jar
*jettison-1.2.jar
*jetty-continuation-7.1.6.v20100715.jar
*jetty-http-7.1.6.v20100715.jar
*jetty-io-7.1.6.v20100715.jar
*jetty-server-7.1.6.v20100715.jar
*jetty-util-7.1.6.v20100715.jar
*jmdns.jar
*jra-1.0-alpha-4.jar
*js-1.7R1.jar
*jsr311-api-1.1.1.jar
*jta-1.1.jar
*logback-access-1.0.1.jar
*logback-classic-1.0.1.jar
*logback-core-1.0.1.jar
*neethi-2.0.4.jar
*oro-2.0.8.jar
*saaj-api-1.3.jar
*saaj-impl-1.3.2.jar
*serializer-2.7.1.jar
*slf4j-api-1.6.4.jar
*spring-aop-3.0.4.RELEASE.jar
*spring-asm-3.0.4.RELEASE.jar
*spring-beans-3.0.4.RELEASE.jar
*spring-context-3.0.4.RELEASE.jar
*spring-core-3.0.4.RELEASE.jar
*spring-expression-3.0.4.RELEASE.jar
*spring-jms-3.0.4.RELEASE.jar
*spring-tx-3.0.4.RELEASE.jar
*spring-web-3.0.4.RELEASE.jar
*stax2-api-3.0.2.jar
*velocity-1.6.4.jar
*waiter-dns.jar
*woodstox-core-asl-4.0.8.jar
*wsdl4j-1.6.2.jar
*wss4j-1.5.9.jar
*xalan-2.7.1.jar
*xml-resolver-1.2.jar
*xmlbeans-2.4.0.jar
*XmlSchema-1.4.7.jar
*xmlsec-1.4.3.jar
| |
doc_23528739
|
Exception in thread "main" org.hibernate.HibernateException: Could not parse configuration: hibernate.cfg.xml
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1491)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1425)
at com.main.StoreData.main(StoreData.java:15)
Caused by: org.dom4j.DocumentException: Connection refused: connect Nested exception: Connection refused: connect
at org.dom4j.io.SAXReader.read(SAXReader.java:484)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1481)
... 2 more
my conf file.
employee.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.pojo.Employee" table="employee">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="firstName" column="first_name" type="string"></property>
<property name="lastName" column="last_name" type="string"></property>
</class>
</hibernate-mapping>
Hibernate config file
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="connection.url">jdbc:sqlserver://localhost;databaseName=sampleDB</property>
<property name="connection.username">sa</property>
<property name="connection.password">sa123</property>
<property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
A: You have to close all open tags, like this one:
<property name="connection.password"sa123</property>
Should be changed to:
<property name="connection.password">sa123</property>
| |
doc_23528740
|
I was able to get around this on a button by changing the button's z-index to be above the dynamic overlay's z-index. However, this doesn't seem to work on an element that's inside a table.
See my stackblitz example where if you hover over the button works, but if you hover over the span inside the table below the button, it goes into the loop as described above. My question is how do I resolve this or if there's a better way to fix the issue not using z-indexes? As far as I can see there's no way to remove the overlay in the control.
A: If you don't need the modal overlay, you can set the modal flag to false in your dialog configuration.
Like in this stackblitz example.
| |
doc_23528741
|
if test $1 -ge 1
then
/usr/bin/systemctl restart mongod >/dev/null 2>&1 || :
fi
This is an inconvenient and dangerous behaviour, especially when you use configuration management tools to set up your servers. For example, I'd like to run a full Ansible playbook to set up my servers first, and then restart MongoDB manually one by one to have full control of the situation.
Is there any way to alter or disable this? Alternative MongoDB packages, maybe? Or some obscure yum/rpm command option to disable scriptlets?
I'm aware that I can switch to simple .tar.gz installation, but this is the last resort.
A: If you first download the rpm and install it manually using rpm; you can use the --nopostun option:
rpm -Uvh mongodb***rpm --nopostun
from the rpm man page:
--noscripts
--nopre
--nopost
--nopreun
--nopostun
--nopretrans
--noposttrans
Don't execute the scriptlet of the same name. The --noscripts option is equivalent to
--nopre --nopost --nopreun --nopostun --nopretrans --oposttrans
and turns off the execution of the corresponding %pre, %post, %preun, %postun %pretrans, and %posttrans scriptlet(s).
afaik yumcannot handle the --nopostun and other flags.
| |
doc_23528742
|
From the other hand, I am receiving a JSON that has an attribute that will be part of the name of the file.
On the evaluateJsonPath the configuration is the next (I am receiving it correctly the value):
And finally I am trying to merge the values in the UpdateAttribute processor (here is where it doesn't work properly):
The response I am getting is _filename.csv
A: You have quotes around name inside your Expression Language expression, try
${name}_${filename} or
${name:append('_'):append(${filename})}
| |
doc_23528743
|
Basic pattern of ViewModel -> Repository -> Rertofit API
The user logs in and is issued a token, this token is then used on all subsequent API calls. Eventually this token expires or can be expired in the backend.
I am trying to figure out how to handle the expired token in a clean manner at a low level and not pollute all my fragments with logic on handling an expired token.
If the token expires I want the user to be taken to the login page/fragment.
A: Here is how I think it could be done. First, define an interface that provides a contract for logout. For example:
interface LogOutOwner {
fun logout(): Observable<Unit>
}
Implement this interface, here I am using an interceptor as an implementation since it gives enough information to deduce if logout is needed:
class ErrorInterceptor : Interceptor, LogOutOwner {
private val publishLogOutSubject: PublishSubject<Unit> = PublishSubject.create()
override fun intercept(chain: Interceptor.Chain): Response {
val response = chain.proceed(chain.request())
if (response.code == 401) { // check if a logout is needed
publishLogOutSubject.onNext(Unit)
}
return response
}
override fun logout(): Observable<Unit> {
return publishLogOutSubject
}
}
In order for this to work your interceptor and LogOutOwner should be singletons, so they handle all your network requests. One of the ways you can achieve this is by using a dependency injection framework. Here as an example, I show manual dependency injection:
object Injection {
private val errorInterceptor = ErrorInterceptor()
fun provideLogOutOwner(): LogOutOwner = errorInterceptor
private fun provideOkHttpClient(): OkHttpClient {
val httpClient = OkHttpClient.Builder()
httpClient.addInterceptor(errorInterceptor)
return httpClient.build()
}
fun provideRetrofit() = Retrofit.Builder()
.baseUrl("")
.addConverterFactory(GsonConverterFactory.create())
.client(provideOkHttpClient())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
}
Since Kotlin's object has only one instance, errorInterceptor is also instantiated only once in the scope of Injection.
Finally, now you need to subscribe to LogOutOwner to listen for logout events. Since you have only one activity you can subscribe there and open whatever fragment you need. But by doing so you eventually need to handle canceling the logout subscription and whenever you want to handle logout on a different activity or a fragment you would need to implement the same canceling logic. To make it more universal, without introducing the same boilerplate whenever you need to handle a logout consider using lifecycle-aware components. Here is an example:
class LogOutObserver(
private val logOutOwner: LogOutOwner,
private val logoutAction: () -> Unit
) :
LifecycleObserver {
private var disposable: Disposable? = null
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart() {
disposable = logOutOwner.logout()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { logoutAction.invoke() }
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() {
disposable?.dispose()
}
}
When you need to handle logout, just use this observer as here:
lifecycle.addObserver(LogOutObserver(Injection.provideLogOutOwner()) {
// do logout
})
So by introducing all the code above we reduced the amount of logic an activity or fragment should implement. Basically, activity or fragment now need only to concern themselves with the navigation logic without worrying about what causes the logout or any lifecycle events.
I used RxJava here but I imagine it's not that hard to implement it with Kotlin Coroutines if needed.
P.S. If you need it to use with multiple fragments/activities you need to change LogOutObserver so that it subscribes/cancels subscription in onResume() and onPause() to prevent from calling logout action from multiple activities/fragments at the same time.
| |
doc_23528744
|
my actionMethod code is :
public ActionResult getEmployeesInfo(JQueryDataTableParams param) {
EmployeeBL obj_EmployeeBL = new EmployeeBL();
var result = obj_EmployeeBL.getEmployeesData(param);
return Json(result, JsonRequestBehavior.AllowGet);
// return PartialView("_EmployeesList", Json( result,
// JsonRequestBehavior.AllowGet));
}
BL and DAL is:
public string getEmployeesData(JQueryDataTableParams param) {
using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conne"].ConnectionString)) {
List < EmployeeDataViewModel > lst_Employees = new List < EmployeeDataViewModel > ();
int filteredCount = 0;
using(SqlCommand command = new SqlCommand("spGetEmployees", conn)) {
command.CommandType = CommandType.StoredProcedure;
// command.Parameters.AddWithValue("@CurrentCulture", currentCultuer);
command.Parameters.AddWithValue("@DisplayLength", param.iDisplayLength);
command.Parameters.AddWithValue("@DisplayStart", param.iDisplayStart);
command.Parameters.AddWithValue("@SortCol", param.iSortCol_0);
command.Parameters.AddWithValue("@SortDir", param.sSortDir_0);
command.Parameters.AddWithValue("@Search", param.sSearch);
conn.Open();
command.CommandTimeout = 500;
SqlDataReader rdr = command.ExecuteReader();
while (rdr.Read()) {
EmployeeDataViewModel emp = new EmployeeDataViewModel();
filteredCount = Convert.ToInt32(rdr["TotalCount"]);
emp.EmployeeId = Convert.ToInt32(rdr["EmployeeId"]);
emp.Name = rdr["Name"].ToString();
emp.Level_1Name = rdr["level1"].ToString();
emp.Level_2Name = rdr["level2"].ToString();
emp.Level_3Name = rdr["level3"].ToString();
emp.Level_4Name = rdr["level4"].ToString();
emp.Level_5Name = rdr["level5"].ToString();
emp.RankName = rdr["RankNO"].ToString();
if (rdr["Rank"] != DBNull.Value) {
emp.Rank = Convert.ToInt32(rdr["Rank"]);
}
emp.EmployeeTypeName = (rdr["EmployeeType"] != DBNull.Value) ? rdr["EmployeeType"].ToString() : "-";
lst_Employees.Add(emp);
}
var result = new {
// sEcho = param.sEcho,
iTotalRecords = GetEmployeeTotalCount(),
iTotalDisplayRecords = filteredCount,
data = lst_Employees
};
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(result);
}
}
}
$(document).ready(function () {
$('#EmployeesDataTable').dataTable({
"bProcessing": true,
"columns": [
{ 'data': 'EmployeeId' },
{ 'data': 'Name' },
{ 'data': 'Level_1Name' },
{ 'data': 'Level_2Name' },
{ 'data': 'Level_3Name' },
{ 'data': 'Level_4Name' },
{ 'data': 'Level_5Name' },
{ 'data': 'RankName' },
{ 'data': 'Rank' },
{ 'data': 'EmployeeTypeName' }
],
"bServerSide": true,
"ajax": {
"url":'@Url.Action("getEmployeesInfo","Emp_Employee")',
"dataSrc": ""
}
});
});
<div class="table-responsive">
<table class="table table-hover" id="EmployeesDataTable">
<thead>
<tr class="">
<th>@Resource.ID</th>
<th>@Resource.EmployeeName</th>
<th>@Resource.FirstLevel</th>
<th>@Resource.SecondLevel</th>
<th>@Resource.ThirdLevel</th>
<th>@Resource.FourthLevel</th>
<th>@Resource.FifthLevel</th>
<th>@Resource.RankNumber</th>
<th>@Resource.Rank</th>
<th>@Resource.EmpType</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
the problem is my code does not go to the url inside ajax. and then the following alert box is appear
DataTables warning (table id = 'EmployeesDataTable'): DataTables warning: JSON data from server could not be parsed. This is caused by a JSON formatting error.
I think my dataTable did not understand what is ajax mean.
A: Here a string is passed to Json() method instead return result as anonymous object
public ActionResult getEmployeesInfo(JQueryDataTableParams param) {
EmployeeBL obj_EmployeeBL = new EmployeeBL();
var result = obj_EmployeeBL.getEmployeesData(param);
return Json(result, JsonRequestBehavior.AllowGet);
}
I changed the code to work with object
public object getEmployeesData(JQueryDataTableParams param) {
using(SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conne"].ConnectionString)) {
List < EmployeeDataViewModel > lst_Employees = new List < EmployeeDataViewModel > ();
int filteredCount = 0;
using(SqlCommand command = new SqlCommand("spGetEmployees", conn)) {
command.CommandType = CommandType.StoredProcedure;
// command.Parameters.AddWithValue("@CurrentCulture", currentCultuer);
command.Parameters.AddWithValue("@DisplayLength", param.iDisplayLength);
command.Parameters.AddWithValue("@DisplayStart", param.iDisplayStart);
command.Parameters.AddWithValue("@SortCol", param.iSortCol_0);
command.Parameters.AddWithValue("@SortDir", param.sSortDir_0);
command.Parameters.AddWithValue("@Search", param.sSearch);
conn.Open();
command.CommandTimeout = 500;
SqlDataReader rdr = command.ExecuteReader();
while (rdr.Read()) {
EmployeeDataViewModel emp = new EmployeeDataViewModel();
filteredCount = Convert.ToInt32(rdr["TotalCount"]);
emp.EmployeeId = Convert.ToInt32(rdr["EmployeeId"]);
emp.Name = rdr["Name"].ToString();
emp.Level_1Name = rdr["level1"].ToString();
emp.Level_2Name = rdr["level2"].ToString();
emp.Level_3Name = rdr["level3"].ToString();
emp.Level_4Name = rdr["level4"].ToString();
emp.Level_5Name = rdr["level5"].ToString();
emp.RankName = rdr["RankNO"].ToString();
if (rdr["Rank"] != DBNull.Value) {
emp.Rank = Convert.ToInt32(rdr["Rank"]);
}
emp.EmployeeTypeName = (rdr["EmployeeType"] != DBNull.Value) ? rdr["EmployeeType"].ToString() : "-";
lst_Employees.Add(emp);
}
var result = new {
// sEcho = param.sEcho,
iTotalRecords = GetEmployeeTotalCount(),
iTotalDisplayRecords = filteredCount,
data = lst_Employees
};
return result;
}
}
}
A: The solution for this problem is:
1. update jquery.dataTables.min.js to a new version so that my datatable understood what "ajax" means. By inserting the following to the LayOut.cshtml:
<script src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css"
href="//cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" />
*modify "getEmployeesInfo" Action to the following:
public ActionResult getEmployeesInfo()
{
string search = Request.Form.GetValues("search[value]")[0];
string draw = Request.Form.GetValues("draw")[0];
string order = Request.Form.GetValues("order[0][column]")[0];
string orderDir = Request.Form.GetValues("order[0][dir]")[0];
int startRec = Convert.ToInt32(Request.Form.GetValues("start")[0]);
int pageSize = Convert.ToInt32(Request.Form.GetValues("length")[0]);
EmployeeBL obj_EmployeeBL = new EmployeeBL();
var employeeDataViewModel = obj_EmployeeBL.getEmployeesData(draw,search, order,orderDir, startRec, pageSize);
int recordsTotal = employeeDataViewModel.TotalCount;
int recordsFiltered = employeeDataViewModel.filteredCount;
var data = employeeDataViewModel.lst_employeeData;
var result = this.Json(new { draw = Convert.ToInt32(draw), recordsTotal = recordsTotal, recordsFiltered = recordsFiltered, data = data }, JsonRequestBehavior.AllowGet);
return result;
}
*Modify "getEmployeesData" function as following:
public EmployeeDataViewModel getEmployeesData(string draw,string search, string order, string orderDir,int startRec, int pageSize)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ATASSqlCon"].ConnectionString))
{
EmployeeDataViewModel obj_EmployeeDataViewModel = new EmployeeDataViewModel();
obj_EmployeeDataViewModel.lst_employeeData = new List();
int filteredCount = 0;
using (SqlCommand command = new SqlCommand("spGetEmployees", conn))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@DisplayLength",pageSize);
command.Parameters.AddWithValue("@DisplayStart",startRec);
command.Parameters.AddWithValue("@SortCol",Convert.ToInt32(order));
command.Parameters.AddWithValue("@SortDir", orderDir);
command.Parameters.AddWithValue("@Search", search);
conn.Open();
command.CommandTimeout = 500;
SqlDataReader rdr = command.ExecuteReader();
while (rdr.Read())
{
EmployeeDataModel emp = new EmployeeDataModel();
filteredCount = Convert.ToInt32(rdr["TotalCount"]);
emp.EmployeeId = Convert.ToInt64(rdr["EmployeeId"]);
emp.Name = rdr["Name"].ToString();
emp.Level_1Name = rdr["level1"].ToString();
emp.Level_2Name = rdr["level2"].ToString();
emp.Level_3Name = rdr["level3"].ToString();
emp.Level_4Name = rdr["level4"].ToString();
emp.Level_5Name = rdr["level5"].ToString();
emp.RankName = rdr["RankNO"].ToString();
if (rdr["Rank"] != DBNull.Value)
{
emp.Rank = Convert.ToInt32(rdr["Rank"]);
}
emp.EmployeeTypeName = (rdr["EmployeeType"] != DBNull.Value) ? rdr["EmployeeType"].ToString() : "-";
obj_EmployeeDataViewModel.lst_employeeData.Add(emp);
}
obj_EmployeeDataViewModel.TotalCount = GetEmployeeTotalCount();
obj_EmployeeDataViewModel.filteredCount = filteredCount;
return obj_EmployeeDataViewModel;
}
}
}
*Modify Script as following:
$(document).ready(function () {
$('#EmployeesDataTable').DataTable({
"columnDefs": [
{
"width": "5%",
"targets": [0]
},
{
"className": "text-center custom-middle-align",
"targets": [0, 1, 2, 3, 4, 5, 6]
}, ],
"processing": true,
"serverSide": true,
"ajax":
{
"url": "/Emp_Employee/getEmployeesInfo",
"type": "POST",
"dataType": "JSON"
},
"columns": [
{
"data": "EmployeeId"
},
{
"data": "Name"
},
{
"data": "Level_1Name"
},
{
"data": "Level_2Name"
},
{
"data": "Level_3Name"
},
{
"data": "Level_4Name"
},
{
"data": "Level_5Name"
},
{
"data": "RankName"
},
{
"data": "Rank"
},
{
"data": "EmployeeTypeName"
}]
});
});
| |
doc_23528745
|
The documentation.
The code I used:
client = boto3.client('comprehend')
The exception I'm being thrown:
UnknownServiceError: Unknown service: 'comprehend'.
Valid service names are: acm,...
I'm guessing there has to be something going on that I'm not aware of
A: I am using boto3(v.1.5.22) and it works well in it. So, if you don't have problem working on higher version you can try it. Amazon comprehend was released recently so that have support for higher version of boto3 only
| |
doc_23528746
|
I begin by calling an API using retrofit to show cinemas near a users location.
I then use the cinema id which the user clicks on to display showtimes for this cinema i.e...
public interface ListingApiService
{
@GET("/get/times/cinema/{id}")
Call<ListingResponse> getShowtimes (@Path("id") String id);
}
Then using the interface....
public void connectAndGetApiData(String id)
{
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
ListingApiService listingApiService = retrofit.create(ListingApiService.class);
Call<ListingResponse> call = listingApiService.getShowtimes(id);
call.enqueue(new Callback<ListingResponse>() {
@Override
public void onResponse(Call<ListingResponse> call, Response<ListingResponse> response)
{
List<Listing> listings = response.body().getListings()
getAndDisplayImage(listings.get(0).getTitle());
recyclerView.setAdapter(new ListingAdapter(listings,R.layout.list_item_listing,getApplicationContext()));
}
@Override
public void onFailure(Call<ListingResponse> call, Throwable t)
{
Log.e(TAG,t.toString());
}
});
}
I then want to call a different API (contextual web search) to display an image of a relevant movie poster (just for a nice visual effect) for each movie listing. I know how to call the API for a single image, but I don't know how to make multiple calls. I've tried using RxJava code found elsewhere on the internet but none of it seems to work as I don't have prior knowledge of how many calls I will be making or what the search term will be. The code i'm using for a single call is:
public interface ListingImageApiService
{
//https://contextualwebsearch-websearch-v1.p.mashape.com/api/Search/ImageSearchAPI?count=1&autoCorrect=false&q=Donald+Trump
@Headers("X-Mashape-Key: apikey")
@GET("/api/Search/ImageSearchAPI?count=5&autoCorrect=false")
Call<ListingImageResponse> getListingImages (@Query("q") String term);
}
public void getAndDisplayImage(String search)
{
if (retrofit2 == null)
{
retrofit2 = new Retrofit.Builder()
.baseUrl(BASE_URL2)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
search = search + " poster";
ListingImageApiService listingImageApiService = retrofit2.create(ListingImageApiService.class);
Call<ListingImageResponse> call = listingImageApiService.getListingImages(search);
call.enqueue(new Callback<ListingImageResponse>() {
@Override
public void onResponse(Call<ListingImageResponse> call, Response<ListingImageResponse> response)
{
System.out.println(response.body().toString());
ListingImage a = new ListingImage();
List<ListingImage> listingImages = response.body().getListingImage();
System.out.println(listingImages.get(0).getUrl());
}
@Override
public void onFailure(Call<ListingImageResponse> call, Throwable t)
{
}
});
}
My question is, how would I use RxJava to make multiple calls using data for the list of movie titles of unknown size (which I can pass to getAndDisplayImage instead of a single string)? I have made several attempts but none seem to work for my use case. Thank you.
A: This design should solve your problem.
This interface contains the endpoints used in the application.
public interface ListingApiService
{
@GET("/get/times/cinema/{id}")
Observable<List<MovieResponse>> getShowtimes (@Path("id") String id);
@Headers("X-Mashape-Key: apikey")
@GET("/api/Search/ImageSearchAPI?count=5&autoCorrect=false")
Observable<ListingImageResponse> getListingImages (@Query("q") String term);
}
Method which provides the retrofit object to make the call
private API getAPI() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("<your API endpoint address")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
return retrofit.create(API.class);
}
Make the call to get the List<MovieResponse>. This method also converts the List into a individual observable MovieResponse object.
private void getMovieListingsWithImages() {
Observer<MovieResponse> observer = new Observer<MovieResponse>() {
@Override
public void onSubscribe(Disposable d) {
Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT).show();
}
@Override
public void onNext(MovieResponse movieResponse) {
//for each movie response make a call to the API which provides the image for the movie
}
@Override
public void onError(Throwable e) {
Toast.makeText(getApplicationContext(), "Error getting image for the movie", Toast.LENGTH_SHORT).show();
}
@Override
public void onComplete() {
Toast.makeText(getApplicationContext(), "Finished getting images for all the movies in the stream", Toast.LENGTH_SHORT).show();
}
};
getAPI().getShowtimes()
.flatMapIterable(movieResponseList -> movieResponseList) // converts your list of movieResponse into and observable which emits one movieResponse object at a time.
.flatMap(this::getObservableFromString) // method converts the each movie response object into an observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(observer);
}
method which converts the MovieResponse object into an Observable.
private Observable<MovieResponse> getObservableFromString(MovieResponse movieResponse) {
return Observable.just(movieResponse);
}
| |
doc_23528747
|
Using VBA is there any way when the front-end opens, I can determine if the user has come via VPN and then give them a message and automatically shut down the front-end database?
Never had to solve this one before and online searches have not given me anything useful so far. So if anyone has a solution for this that would be much appreciated.
A: I think you are taking wrong approach here. This should be done on a network level. The back-end access db should not be accessible on the network and the front end should just check if the e.g. mapped network drive is accessible.
An example:
Sub Testing_Mapped_Drive()
If (Len(Dir("M:\"))) Then
MsgBox "Mapped drive connected."
Else
MsgBox "Mapped drive not available!"
End If
End Sub
| |
doc_23528748
|
The examples I found on the Internet show me how to send data to the server, but they do not teach how to send them back to the client.
To demonstrate, my program does the following:
My client program creates a socket on the 4444 port, like this:
con, err := net.Dial("udp", "127.0.0.1:4444")
I sent a string and the local address to the server, so it could print the string and send an OK message. I am using gob for this:
enc := gob.NewEncoder(con)
enc.Encode(Data{"test", con.LocalAddr().String()})
My Data struct looks like this:
type Data struct{
Msg string
Addr string
}
My server listens to the 4444 port and decodes the Gob correctly, but how can I send the OK message back? I'm using the client address to do so (on the server .go file):
con, err := net.Dial("udp", data.Addr)
Then, I get an error code:
write udp 127.0.0.1:35290: connection refused
When the client tries to connect to the Server's port 4444, the client creates a port with a random number (in this case, 35290) so they can communicate. I know I shouldn't be passing the client's address to the server, but conn.RemoteAddress() does not work. A solution that discovers the client's address would be most appreciated.
Obs.: I know there is ReadFromUDP, so I can read the package. Should I read it, discover the client's address, and send the data to Gob so it can decode it?
A: Check the below samples for client/server communication over UDP. The sendResponse routine is for sending response back to client.
udpclient.go
package main
import (
"fmt"
"net"
"bufio"
)
func main() {
p := make([]byte, 2048)
conn, err := net.Dial("udp", "127.0.0.1:1234")
if err != nil {
fmt.Printf("Some error %v", err)
return
}
fmt.Fprintf(conn, "Hi UDP Server, How are you doing?")
_, err = bufio.NewReader(conn).Read(p)
if err == nil {
fmt.Printf("%s\n", p)
} else {
fmt.Printf("Some error %v\n", err)
}
conn.Close()
}
udpserver.go
package main
import (
"fmt"
"net"
)
func sendResponse(conn *net.UDPConn, addr *net.UDPAddr) {
_,err := conn.WriteToUDP([]byte("From server: Hello I got your message "), addr)
if err != nil {
fmt.Printf("Couldn't send response %v", err)
}
}
func main() {
p := make([]byte, 2048)
addr := net.UDPAddr{
Port: 1234,
IP: net.ParseIP("127.0.0.1"),
}
ser, err := net.ListenUDP("udp", &addr)
if err != nil {
fmt.Printf("Some error %v\n", err)
return
}
for {
_,remoteaddr,err := ser.ReadFromUDP(p)
fmt.Printf("Read a message from %v %s \n", remoteaddr, p)
if err != nil {
fmt.Printf("Some error %v", err)
continue
}
go sendResponse(ser, remoteaddr)
}
}
A: hello_echo.go
package main
import (
"bufio"
"fmt"
"net"
"time"
)
const proto, addr = "udp", ":8888"
func main() {
go func() {
conn, _ := net.ListenPacket(proto, addr)
buf := make([]byte, 1024)
n, dst, _ := conn.ReadFrom(buf)
fmt.Println("serv recv", string(buf[:n]))
conn.WriteTo(buf, dst)
}()
time.Sleep(1 * time.Second)
conn, _ := net.Dial(proto, addr)
conn.Write([]byte("hello\n"))
buf, _, _ := bufio.NewReader(conn).ReadLine()
fmt.Println("clnt recv", string(buf))
}
A: The gist is here:
https://gist.github.com/winlinvip/e8665ba888e2fd489ccd5a449fadfa73
server.go
/*
Usage:
go run server.go
See https://gist.github.com/winlinvip/e8665ba888e2fd489ccd5a449fadfa73
See https://stackoverflow.com/a/70576851/17679565
See https://github.com/ossrs/srs/issues/2843
*/
package main
import (
"fmt"
"net"
"os"
"strconv"
)
func main() {
serverPort := 8000
if len(os.Args) > 1 {
if v,err := strconv.Atoi(os.Args[1]); err != nil {
fmt.Printf("Invalid port %v, err %v", os.Args[1], err)
os.Exit(-1)
} else {
serverPort = v
}
}
addr := net.UDPAddr{
Port: serverPort,
IP: net.ParseIP("0.0.0.0"),
}
server, err := net.ListenUDP("udp", &addr)
if err != nil {
fmt.Printf("Listen err %v\n", err)
os.Exit(-1)
}
fmt.Printf("Listen at %v\n", addr.String())
for {
p := make([]byte, 1024)
nn, raddr, err := server.ReadFromUDP(p)
if err != nil {
fmt.Printf("Read err %v", err)
continue
}
msg := p[:nn]
fmt.Printf("Received %v %s\n", raddr, msg)
go func(conn *net.UDPConn, raddr *net.UDPAddr, msg []byte) {
_, err := conn.WriteToUDP([]byte(fmt.Sprintf("Pong: %s", msg)), raddr)
if err != nil {
fmt.Printf("Response err %v", err)
}
}(server, raddr, msg)
}
}
client.go
/*
Usage:
go run client.go
go run client.go 101.201.77.240
See https://gist.github.com/winlinvip/e8665ba888e2fd489ccd5a449fadfa73
See https://stackoverflow.com/a/70576851/17679565
See https://github.com/ossrs/srs/issues/2843
*/
package main
import (
"fmt"
"net"
"os"
"strings"
)
func main() {
serverEP := "127.0.0.1"
if len(os.Args) > 1 {
serverEP = os.Args[1]
}
if !strings.Contains(serverEP, ":") {
serverEP = fmt.Sprintf("%v:8000", serverEP)
}
conn, err := net.Dial("udp", serverEP)
if err != nil {
fmt.Printf("Dial err %v", err)
os.Exit(-1)
}
defer conn.Close()
msg := "Hello, UDP server"
fmt.Printf("Ping: %v\n", msg)
if _, err = conn.Write([]byte(msg)); err != nil {
fmt.Printf("Write err %v", err)
os.Exit(-1)
}
p := make([]byte, 1024)
nn, err := conn.Read(p)
if err != nil {
fmt.Printf("Read err %v\n", err)
os.Exit(-1)
}
fmt.Printf("%v\n", string(p[:nn]))
}
| |
doc_23528749
|
data1 = open('data1.txt', 'a+')
data2 = open('data2.txt', 'a+')
data3 = open('data3.txt', 'a+')
data4 = open('data4.txt', 'a+')
for i in range(0,100000): #range this big since close encounters don't happen every iteration
def P_dist(p1, p2):
#function calculating distances between planets
init_SMA = [sim.particles[1].a,sim.particles[2].a,sim.particles[3].a,sim.particles[4].a,sim.particles[5].a]
try:
sim.integrate(10e+9*2*np.pi)
except rebound.Encounter as error:
print(error)
for j in range(len(init_SMA)-1):
distance = P_dist(j, j+1)
if distance <= .01:
count+=1
if count > 4570:
break
elif(init_SMA[j] == init_SMA[0] and init_SMA[j+1] == init_SMA[1])
#write stuff to data1
elif(init_SMA[j] == init_SMA[1] and init_SMA[j+1] == init_SMA[2])
#write stuff to data2
elif(init_SMA[j] == init_SMA[2] and init_SMA[j+1] == init_SMA[3])
#write stuff to data3
elif(init_SMA[j] == init_SMA[3] and init_SMA[j+1] == init_SMA[4])
#write stuff to data4
#close files
Everyone, I apologize. I left out lots of the code that shows the creation of the planetary system. The main for loop is responsible for creating a planetary system, catching a close encounter, writing it to the files, and repeating until 4570 close encounters have occurred.
A: It isn't ideal to keep four different files open in a running script. What's more, you haven't opened those files using Python's convenient with context manager, which takes care of cleanly closing opened files among other things. You're also performing open operations every loop iteration - files usually should be opened and closed once as there is a lot of consequential I/O overhead.
As for a cleaner approach, I would conditionally accumulate items/lines in Python data storage objects, then just do a one-off open and write at the end of the script. That way, if something goes awry during the main logic, you don't have files that have been partially written to.
This would be something along the lines of:
create 4 empty lists
for loop
logic to conditionally append lines to be written to the text files to those lists
with open('data1.txt', 'a+') as f:
write contents of list1 to f
... copy paste for remaining 3
A: I'd probably put the four data files in a list, so you can just do:
filesArray = [data1,data2,data3,data4]
#insider your for loop:
if(count > 4750):
break
if(distance <= 0.01):
count += 1
filesArray[j].write(data)#for whatever your data is
else:
break
It would be even better to do
fileNamesArray = ["data1.txt", "data2.txt", "data3.txt", "data4.txt"]
#inside your for loop:
if(count > 4750):
break
if(distance <= 0.01):
count += 1
with open(fileNamesArray[j], "a") as dataFile:
dataFile.write(data)#for whatever your data is
This helps avoid data corruption in case your program crashes for another reason
This also avoids storing every result you get into a list in memory, which I'd guess could be expensive for complex simulations
It does bind your performance to disk speed though, so I guess it's a tradeoff
| |
doc_23528750
|
I followed the steps given in Pyq Installation for installing in a licensed Kdb+.
I created a virtual environment.
pip install virtualenv
mkdir python-virtual-environments && cd python-virtual-environments
pyvenv env
source env/bin/activate
Unzipped the kdb+ 64 bit file
mkdir -p ${VIRTUAL_ENV}/q && unzip path/to/m64.zip -d ${VIRTUAL_ENV}/q
copied the license and installed pyq
git clone https://github.com/enlnt/pyq.git
pip install <path to the source>
I have also done the same process by creating a virtual environment using Conda.
In both cases, when I run pyq in the Terminal, I am getting the following error:
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named pyq
'2017.10.11T06:10:31.641 python
Please help.
Also when I try to install pyq using
pip install -i https://pyq.enlnt.com --no-binary pyq pyq`
I get
Requirement already satisfied: pyq in /usr/local/lib/python2.7/dist-packages
A: First, uninstall pyq by running
pip uninstall pyq
Make a copy of the list of paths that this command displays as being removed. You will need it to troubleshoot later.
Make sure you have python shared libraries installed. See Installing PyQ on Ubuntu 16.04
Run
pip install pyq
Recently published versions don't require the extra pip options.
If this does not give you a working pyq executable, look at the list of paths that you saved during uninstall find the full path to the parent directory of the pyq package. Set the PYTHONPATH environment variable to that path.
BTW, the message that you reported,
Requirement already satisfied: pyq in /usr/local/lib/python2.7/dist-packages
suggests that you (or someone else) installed pyq directly into local python installation, not into a virtual environment. Also the /usr/local prefix indicates that you have a custom python installation which may be the cause of your problem.
| |
doc_23528751
|
ORIGINAL HASH
a = {:a=>1, :b=>2, :c=>3, :d=>4}
EDIT: Adding answer here from below for quick reference. See below for a better explanation.
SOME CODE HERE TO SLICE INTO SAY 2 EQUAL SLICES
a.each_slice(2).map{|slice| Hash[slice]}
RESULT
a = [{:a=>1, :b=>2}, {:c=>3, :d=>4}]
A: h = {:a=>1, :b=>2, :c=>3, :d=>4}
p h.each_slice(2).map{|slice| Hash[slice]} # => [{:a=>1, :b=>2}, {:c=>3, :d=>4}]
A: One way to do it:
arr = []
a.each_slice(2) {|s| arr << Hash[s]}
Choose whatever value you want for the 2 above.
As a method:
def slice( a, n )
arr = []
a.each_slice(n) {|s| arr << Hash[s]}
arr
end
Or simpler:
def slice( a, n )
a.each_slice(n).inject([]) {|a, p| a << Hash[p]}
end
| |
doc_23528752
|
// 2:11pm 2-20-2012
$opendate = '2012-02-20T14:11:03-05:00';
// 6:22pm 2-20-2012
$closedate = '2012-02-20T18:22:50-05:00';
$diff_date = $closedate - $opendate
I would like $diff_date to return in hours::minutes format, such as '4 hrs 11 min'.
If it would be beneficial for this, another alternative to the times formatted above is:
$removeT = "T";
$replaceSPACE = " ";
//returns datetime like '2012-02-20 14:11:03'
$r = str_replace($removeT, $replaceSPACE, $opendate[$i]);
$r = substr($r, 0, 19);
//returns datetime like '2012-02-20 18:22:50'
$s = str_replace($removeT, $replaceSPACE, $closedate[$i]);
$s = substr($s, 0, 19);
A: Convert both to UNIX-timestamp, then subtract one from the other. You can convert to result to hours and minutes very easy.
$secondsDiff = strtotime($closedate) - strtotime($opendate);
| |
doc_23528753
|
So here is my code:
try {
// UDP data-in settings
DatagramChannel inChannel = DatagramChannel.open();
SocketAddress inAddress = new InetSocketAddress(FMBuffer.IN_PORT);
inChannel.bind(inAddress);
// UDP data-out settings
DatagramChannel outChannel = DatagramChannel.open();
SocketAddress outAddress = new InetSocketAddress(FMBuffer.OUT_PORT);
outChannel.bind(outAddress);
LinkedList<ByteBuffer> buffer = new LinkedList<ByteBuffer>();
ByteBuffer b = ByteBuffer
.allocateDirect(FMBuffer.UDP_MAX_PACKET_SIZE);
while (true) {
if (inChannel.receive(b) != null) { // Receive data and put into b
b.flip();
// Save b into the buffer
buffer.addLast(b);
System.out.print("In(" + buffer.size() + "): ");
while (buffer.getLast().hasRemaining()) {
System.out.write(buffer.getLast().get());
}
System.out.println();
// If the buffer reaches the set limit
if (buffer.size() > FMBuffer.BUFFER_LIST_SIZE) {
// Send the first b out, then remove it
System.out.print("Out(" + buffer.size() + "): ");
while (buffer.getFirst().hasRemaining()) {
System.out.write(buffer.getFirst().get());
outChannel.send(buffer.getFirst(), outAddress);
}
System.out.println();
buffer.removeFirst();
}
b.clear();
} else { // Receive no data
if (buffer.size() > 0) {
// Send the first b out, then remove it
System.out.print("Out remaining(" + buffer.size() + "): ");
while (buffer.getFirst().hasRemaining()) {
System.out.write(buffer.getFirst().get());
outChannel.send(buffer.getFirst(), outAddress);
}
System.out.println();
buffer.removeFirst();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
There are several problems...
*
*I tried to use a program to read from 127.0.0.1:OUT_PORT. The program said that the port is in use. What shall I do?
*Say BUFFER_LIST_SIZE = 5 and outChannel.send(...) is commented.
The output data is always blank, not the input one.
Also, if I stop sending data to it, it will not output the remaining data from its buffer.
With inputs like "* UDP Flood. Server stress test ****", it will output:
In(1): ***** UDP Flood. Server stress test ****
In(2): ***** UDP Flood. Server stress test ****
In(3): ***** UDP Flood. Server stress test ****
In(4): ***** UDP Flood. Server stress test ****
In(5): ***** UDP Flood. Server stress test ****
In(6): ***** UDP Flood. Server stress test ****
Out(6):
In(6): ***** UDP Flood. Server stress test ****
Out(6):
In(6): ***** UDP Flood. Server stress test ****
Out(6):
In(6): ***** UDP Flood. Server stress test ****
Out(6):
| |
doc_23528754
|
When that happens, the entire application is not able to access the locked tables, and no matter how long I wait, those locks does not get freed up. I need to sign into the database from the rds query editor and manually kill the threads.
This has not happened when I was running my own MySQL server installation, only on Aurora Serverless.
There are no database transactions used in the system, and the database is set to auto commit after every queries.
Is there something I can do about this to stop this from happening?
| |
doc_23528755
|
I created a Java project based on the sonar-xoo-plugin.
Then I added a simple rule which inherits BaseTreeVisitor and always raises an issue in visitMethod(MethodTree). I annotated the class with @Rule(key = "x1") and used the same key in the class MyRulesDefinition when creating a new rule in the repository.
I built the project, put the jar file into the plugins folder and started the sonar server. The plugin was loaded and the rule existed. I activated it for the selected quality profile and ran an analysis but no issues were found by the rule.
What am I doing wrong? How is the rule template in MyRulesDefinition mapped to the logic of the rule?
Do any other examples exist for SonarQube plugins using the latest API?
A:
Do any other examples exist for SonarQube plugins using the latest API?
No, I faced exactly the same issue today and couldn't find any. But here is the solution :
*
*Create a class implementing RulesDefinition -> it is a ServerExtension whose sole purpose is to make your custom rules appear in SonarQube's UI if you've explicitly provided a definition (programatically, or in a XML file, or through annotations). This extension is loaded at server startup.
*Create a class implementing BatchExtension and JavaFileScannersFactory -> its purpose is to make all your custom java rules available during batch analysis by returning instances of your rules. This extension is loaded during analysis.
*Create a class extending SonarPlugin which returns Extensions created in points 1 and 2 above.
Your custom rules will then be both available in UI and during analysis. If you don't do 1. you won't be able to activate / configure them. If you forget 2, they will be activable / configurable, but will never be executed (and no error will be raised neither)
It's a slight difference with RulesRepository : your CustomRulesRepository extending RulesRepository could directly implement BatchExtension and JavaFilesScanner.
A: I exposed sample example (based on gradle) on github: https://github.com/misak69/misak69-sonar-custom. All important facts are based on previous answer from @kraal. Feel free to look for https://github.com/misak69/misak69-sonar-custom/blob/master/README.md
A: You can take a look at the Java Custom Rules example plugin. This one should give you all the answers you need.
| |
doc_23528756
| ||
doc_23528757
|
class FizzBuzz
def initialize(int_num, str_fb, value)
self.int_num = int_num
self.str_fb = str_fb
self.value = value
end
def int_num
@int_num
end
def int_num=(num)
raise TypeError if not num.is_a? Integer
@num = int_num
end
def str_fb
@str_fb
end
def str_fb=(name)
if int_num % 3 == 0
int_num = "Fizz"
elsif int_num % 5 == 0
int_num = "Buzz"
elsif int_num % 5 == 0 and int_num % 3 == 0
int_num = "FizzBuzz"
else
str_fb = int_num.to_s #Also needs to be stored in an array in main function
end
def main
ary =array.new
end
end
How do I store the newly converted int_num (now a string) into the array in main? Also, the code above is only one method of the class, but does it appear correct? Thanks, I am a full blown Ruby noob and appreciate all the help.
**Added full code. Still incomplete, as I need to create a getter and setter for value that loops 1-50.
A: You can add items to an array using push method or << (shovel) operator. I prefer the latter.
Here is my take on your assignment:
module MyModule
class FizzBuzz
attr_reader :main
def initialize(range)
raise TypeError unless range.is_a? Range
@main = []
range.to_a.each do |i|
main << process(i)
end
end
private
def process(num)
if num % 5 == 0 && num % 3 == 0
"FizzBuzz"
elsif num % 3 == 0
"Fizz"
elsif num % 5 == 0
"Buzz"
else
num
end
end
end
end
Note that I don't have any getter and setter methods. This is for two reasons:
*
*The by calling the attr_reader class method, I am setting up a public getter method for main in a much more elegant way
*I don't see a need for any setter methods as passing in the range when I initialise the class would is sufficient
If you save this module in a file named my_module.rb and run the irb command you can interact with your class as follows:
➜ Code irb
irb(main):001:0> require "#{absolute_path_to_file}/my_module"
=> true
irb(main):004:0> include MyModule
=> Object
irb(main):005:0> FizzBuzz.new(1..15).main
=> [1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz"]
irb(main):006:0> FizzBuzz.new('abc').main
TypeError: TypeError
from /Users/username/Code/my_module.rb:6:in `initialize'
from (irb):6:in `new'
from (irb):6
from /Users/alexveldtman/.rbenv/versions/2.3.1/bin/irb:11:in `<main>'
UPDATE: After looking at the code again, I thought it would be cool to refactor the class a bit to get rid of those boring if statements.
module MyModule
class FizzBuzz
attr_reader :main
def initialize(range)
raise TypeError, 'not a Range' unless range.is_a? Range
@main = []
range.to_a.each do |i|
main << fizzbuzzerize(i){|fizzy_string, k| string_or_num(fizzy_string, k) }
end
end
private
def fizzbuzzerize(num)
yield [divisible_by_3?(num), divisible_by_5?(num)].compact.join, num
end
def string_or_num(string, num)
(string.length > 0 ? string : nil) || num
end
def divisible_by_3?(num)
num % 3 == 0 ? "Fizz" : nil
end
def divisible_by_5?(num)
num % 5 == 0 ? "Buzz" : nil
end
end
end
Note: the fizzbuzzerize method yields to a block in stead of returning a value
A: To answer the original question, just put the variable you want to return inside an array into brackets:
def main
[str_fb]
end
Lots of other Ruby-specific improvements could be made here. For starters, you can replace the int_num and int_num= methods with a single line: attr_accessor :int_num. (You would need to move your raise to the constructor.)
You can replace the str_fb method with another single line: attr_reader :str_fb.
In the constructor, it is more common in Ruby to use instance variables to store input parameters. Consider which methods you want to leave public and which to make private. You can make instance methods (including attr_accessor and attr_reader private by adding a single line private and moving those methods below it.
So your code might look like this:
class FizzBuzz
attr_accessor :int_num
attr_reader :str_fb, :value
def initialize(int_num, str_fb, value)
raise TypeError unless int_num.is_a?(Integer)
@int_num = int_num
@str_fb = str_fb
@value = value
end
<public instance methods here>
private
<private instance methods here>
end
| |
doc_23528758
|
I thought there might be some Outlook API or Office.js method for it but didn't manage to find one.
What I need is a possibility to parse entities in an email, show some basic information in a contextual add-in with some buttons on it.
Then what I want to do is to show detailed information about some entity's part in a sidebar by clicking a corresponding button in a contextual add-in.
A: I am assuming by sidebar you mean TaskPane add-ins.
No, all web-based add-ins get activated by user action (either clicking on add-in button / add-in link (in case of contextual add-ins))
It is not possible to launch an add-in from another add-in.
But you can show a dialog, if you want more real estate to show the content.
| |
doc_23528759
|
I've done some research and reading up on the theories behind them doesn't really give me a solid understanding between the two. I read that in Prolog, pattern matching is different because it has the ability to unify variables and thus be able to deduce through resolution and spit out the possible answer
eg ?- [a,b] = [a,X]
X = b
Now I'm not sure how to display pattern matching in Haskell. I know that the same query above shown in Prolog will not work in Haskell because Haskell cannot unify like Prolog. I remember somewhere that to get the same answer in Haskell, you have to explicitly tell it through guards.
I know that I am pretty close to understanding it, but I need someone to break it down Barney style for me so I can FULLY understand it and explain it to a 12 year old. This has been bugging me for quite some time and I can't seem to find a solid explanation.
By the way the example shown above was just to display to you guys what I've learned so far and that I'm actually trying to find an answer. My main question does not relate to the examples above but rather a complete understanding on the difference between the two.
A: Nobody mentioned the following very important difference. Pattern matching in Prolog is tried for every clause of a predicate, even if one of the previous matches has succeeded (unless stopped short by a cut). But in Haskell pattern matching on clauses is attempted only until the first success. No other alternatives are tried (unless the match was rejected by a guard).
Prolog's pattern matching establishes an equality constraint in most general sense (see answer by @false for details). Sharing is explicit: A=B, A=5 sets B=5 as well. This is possible because Prolog's logvar can be in not-yet-set (i.e. uninstantiated) state. This makes tying-a-knot easy (a basic programming technique actually, viz. difference lists).
In Haskell, any variable is allowed to be defined only once at the syntax level. In Prolog a logvar is set only once too (sans backtracking), but it is allowed to point at an incomplete structure (data), where holes are represented by other not-yet-instantiated logvars which can be set at any later point in time.
In Haskell, a given structure defined with guarded recursion is progressively fleshed out as demanded by access. In Prolog, after the initial instantiation of a variable, any subsequent unification is turned into verification of terms' compatibility and possible further (perhaps partial yet again) instantiation ("filling up" the holes explicitly).
A: Adding to the answer of LeleDumbo, we could say that Prolog unification builds terms as well as deconstructs them, while in Haskell the build phase is conveniently demanded to returned value.
Of course such feature is what allows in pure Prolog so called 'bidirectional' predicates, exploited for instance in DCGs, that with some restriction, can be used for both parse and generation.
A: Here is an example I find interesting in Prolog to support @chac (+1 btw) mention about how Prolog's unification "builds" terms that we ran into in the prolog tag yesterday:
swapPairs([], []).
swapPairs([X], [X]).
swapPairs([X, Y|T], [Y, X|R]) :- swapPairs(T, R).
This predicate has almost no "body". It only uses unification of its arguments in its head and recursion.
As pointed out by both @chac and @LeleDumbo, that's because Prolog's unification is "both-way".
Here is what A gentle Introduction to Haskell says about it:
Pattern matching in Haskell is different from that found in logic
programming languages such as Prolog; in particular, it can be viewed
as "one-way" matching, whereas Prolog allows "two-way" matching (via
unification), along with implicit backtracking in its evaluation
mechanism.
A: Prolog pattern matching is based on unification, specifically the Martelli-Montanari Algorithm (minus the occurs check, by default). This algorithm matches values of the same position, binding variables on one side to a value at corresponding position on the other side. This kind of pattern matching could work both ways, therefore in Prolog you could use arguments as both input and output. A simple example, the length/2 predicate. We could use this to (comment explains the query):
?- length([],0). % is the length of empty list zero?
?- length([a,b,c],X). % what's the length of list consisting of a,b and c?
?- length(L,5). % give me all lists that have length of 5
Haskell pattern matching is a one way matching, to bind variables to different parts of given value. Once bound, it carries out the corresponding action (the right hand side). For example, in a function call, pattern matching may decide which function to call. e.g.:
sum [] = 0
sum (x:xs) = x + sum xs
the first sum binds empty list, while the second binds a list of at least 1 element. Based on this, given sum <a list>, the result could be either 0 or x + sum xs depending on whether sum <a list> matches sum [] or sum (x:xs).
A: The difference between pattern matching as in Haskell and Prolog's unification stems from the fundamentally different rôle of variables in both languages.
In Haskell, variables hold values. Concrete values. Such a value might not have been computed yet, and it might even be ⊥, but otherwise it is one concrete value. In Haskell you cannot take a variable and only state some properties of its value first.
So pattern matching always means that a concrete value is matched against a pattern which contains some variables. The outcome of such a matching is either failure or a binding of the variables to concrete values. In Haskell this is further restricted to avoid the need of general comparison, which would imply that class Eq is defined for the terms being matched.
In Prolog, however, variables may refer to a set of possible solutions. Variables may occur anywhere - also somewhere between other values. Unification now ensures that the stated equalities still hold and the result is represented optimally, i.e. the most general unifier is computed.
?- length(L,5).
L = [_A,_B,_C,_D,_E].
?- length(L,5), maplist(=(E),L).
L = [E,E,E,E,E].
So Prolog does not answer here with concrete values like L = [1,1,1,1,1] or L = [[],[],[],[],[]] but gives the most general unifier as an answer which contains all those concrete values.
| |
doc_23528760
|
On the other hand, I would like to allow vehicles to pickup / deliver shipments slightly out of time window (let’s say, they can arrive and deliver shipment in 5 minutes after time window ends). While searching for possible solutions, I’ve looked through SoftActivityConstraint class and thought about applying a soft constraint on each inserted job in route to have 0 cost if vehicle is late for less than 5 minutes.
Can I influence vehicles’ arrival and finish times? Can it be implemented using SoftActivityConstraint?
Thanks in advance.
| |
doc_23528761
|
The first if statement works on my other pages and I am unsure of how to properly code this as I am a beginner to PHP.
<?php
session_start();
if($_SESSION['loggedin'] != 'true') {
header("location:login.php");
}
if ($_SESSION['admin']=='N') {
header("location:errorpage.php");
}
?>
A: What is true in your conditions? It can be bool type or string type.
If You set like this:
$_SESSION['loggedin'] = TRUE;
$_SESSION['loggedin'] = 'true';
You have got two different variable sets.
You can compare it using == or === to include variable type.
For example:
$_SESSION['test_1'] = TRUE;
$_SESSION['test_2'] = 'true';
var_dump( $_SESSION );
array(2) { ["test_1"]=> bool(true) ["test_2"]=> string(4) "true" }
A: $_SESSION['loggedin']?
Why don't just clear every SESSION var on logout and if the SESSION vars are set => the user is logged in.
And use after the header(); an exit();
Try var_dump($_SESSION['loggedin']) and edit your question.
Or maybe your loggedin var is not a string but a boolean so you could do if(!$_SESSION['loggedin'])
A:
Try using Boolean values rather than strings. I would also use a const for the admin variables. I would do the following;
$_SESSION['loggedin'] = true/false;
$_SESSION['admin'] = true/false;
public class Priviledges
{
public CONST Admin = 0;
public CONST User = 1;
public CONST Contributor = 3;
//change this to however you want to do it :)
public static function isAdmin($val)
{
if ($val == Priviledges::Admin)
{
return true;
}
else
{
return false;
}
}
}
then when you set the admin session variable you can go;
$_SESSION['admin'] = Priviledges::Admin;
if(!$_SESSION['loggedin'])
{
header("location:login.php");
exit()
}
else if (!Priviledges::isAdmin($_SESSION['admin']))
{
header("location:errorpage.php");
exit()
}
else
{ //do your stuff if none of these conditions are met.. }
A: Always add an exit() or die() after sending a "Location" HTTP header:
<?php
session_start();
if($_SESSION['loggedin'] !== 'true') {
header("location:login.php");
exit();
}
if ($_SESSION['admin'] === 'N') {
header("location:errorpage.php");
exit();
}
Check: php - Should I call exit() after calling Location: header?.
From aaronsaray blog:
Remember, just because the browser is smart enough not to show the
content, doesn’t mean that this isn’t dangerous. So, it’s a little
less dangerous say if this page is just showing a user search option
or some information. It is much more dangerous if this is a page that
executes an action. This is because the entire PHP page will execute
if you don’t put a die() statement.
On other cases, if you want a condition to be evaluated only when a previous condition is false, you may use a "else if".
| |
doc_23528762
|
I'm wondering if there's a way to script this so we don't have to manually drag the directories into Xcode each time. Adding a "Copy Files" build phase only seems to work if I choose "Create folder references". When I choose "Create groups", the "Copy Files" section remains empty. Is this a bug in Xcode or am I doing something wrong? I'm using Xcode 9.1.
I know Apple recommends creating a framework rather than copying in a directory of source files. The reason we can't do that is because we're relying on the Unity build process which gives us a bunch of C source files.
A: In Xcode, you can manage your build process under the "Build Phases" tab when you select your app target. These tasks are executed on each build of your app, unless specified otherwise by some phases (for example: you can choose to run a phase only when the app installs for the first time).
Click the + button and you can add a "Copy files phase" that will copy your selected files into the app. When adding the files you'll be able to select if added folders will create groups or folder references.
You can also add a custom "Run script phase" and write some bash code to do whatever you like, or even run an external script that will do more complex work.
A: Xcode makes it possible to script adding resource files such as images to the project file using the "Build Phases" tab however this does not work for source code files that need to be recognized at compile time. Luckily I managed to come across a nice community-developed Python script which does allow us to do this.
https://github.com/kronenthaler/mod-pbxproj
With this script we can make all sorts of modifications to the project file including adding or deleting files.
See this link for a full list of available operations:
https://github.com/kronenthaler/mod-pbxproj/wiki
A: xcode->Build Phases-> click (+) button -> New Copy Files Phase / New Run Script Phase
| |
doc_23528763
|
Individually I understand rel="author", rel="me" and rel="publisher", however I am wondering if I can mix and match attribute values.
Example 1: On my website, I have a link in the footer which links to my domain. Do I add rel="me", rel="author" or rel="me author"?
Example 2: On my website I have a link to my twitter account. Do I add rel="me" or rel="me publisher"?
A: You can't add more than one rel attribute into one HTML element, but you can insert more than one argument into one rel attribute value - just delimit them with a space:
<a rel="me author" href="my_page">
<a rel="me publisher" href="twitter_link">
A: Last time I looked the Google rich snippet tool complained if you had both author and publisher mark-up on the same page.
If I remember correctly, author beats publisher
| |
doc_23528764
|
* element When I try and fire an event on a listview <li> item it seems that the whole element is not considered, but only the elements inside it:
<ul data-role='listview' data-filter='true' data-filter-placeholder='Search Your Trucks..' data-inset='true' data-mini='true'>
<li id=tg_1><a id=tg_2 href=#divdet>ONE</a> TEST </li>
<li id=tg_2><a id=tg_2 href=#divdet>TWO</a> FOO </li>
</ul>
The function handling touchstart (which handles touchstart of multiple elements):
document.addEventListener('touchstart', function (e) {
switch(e.target.id) {
case ...
..other elements...
break;
default:
if(e.target.id.substr(0,3) == "tg_")
$.ajax({
... do request ....
})
$("#divdet").html(from_ajax_data);
}
}
}
The issue is that it is working, but only when clicking on specific parts of the <li> element. I'd like it to work every time a <li> is clicked.
The concept is that with the href i can move to the next page of the app using effect such as slide, whilst with the touch event I load data into the div.
A: You can move to the next page with transition using script as well:
http://api.jquerymobile.com/pagecontainer/#method-change
<ul data-role='listview' data-filter='true' data-filter-placeholder='Search Your Trucks..' data-inset='true' data-mini='true'>
<li id="tg_1"><a id="tg_1a" href="#">ONE</a> TEST </li>
<li id="tg_2"><a id="tg_2a" href="#">TWO</a> FOO </li>
</ul>
$(document).on("click", "li", function(e){
var id = $(this).prop("id");
if(id && id.substr(0,3) == "tg_") {
var from_ajax_data = "from ajax html"; //ajax call here
$("#divdet").html(from_ajax_data);
$( ":mobile-pagecontainer" ).pagecontainer( "change", "#divdet", { transition: "slide" } );
}
});
Working DEMO
| |
doc_23528765
|
I want to use ubuntu:latest instead of official tensorflow image.
How can I do it?
A: You could simply clone the tensorflow/tensorflow repo, go to the tensorflow/tensorflow/tools/docker folder, and:
*
*change the Dockerfile in order to:
*
*use ubuntu:16.04
*install python3 (before python-numpy)
*build your own tensorflow image based on those modification.
| |
doc_23528766
|
*
*https://blog.keras.io/building-autoencoders-in-keras.html
Following the examples I built the autoencoder like that:
inputs = Input(shape=(timesteps, 50))
encoded1 = Dense(30, activation="relu")(inputs)
encoded2 = Dense(15, activation="relu")(encoded1)
encoded3 = Dense(5, activation="relu")(encoded2)
decoded1 = Dense(15, activation="relu")(encoded3)
decoded2 = Dense(30, activation="relu")(decoded1)
decoded = Dense(50, activation="sigmoid")(decoded2)
autoencoder = Model(inputs=inputs, outputs=decoded)
encoder = Model(inputs, encoded3)
autoencoder.compile(loss='mse', optimizer='rmsprop')
autoencoder.fit(trainX,
trainX,
epochs=epochs,
batch_size=512,
callbacks=callbacks,
validation_data=(trainX, trainX))
On the examples there is mostly a model with the encoder and a seperate model with the decoder. I always see that only the decoder model get's trained. The encoder is not trained. But for my usecase I only need the encoder model to denoise the data. Why does the encoder need no training?
A: Your interpretation about encoder-decoder is wrong. Encoder encodes your input data into some high dimensional representation which is abstract but it's very powerful if you want use that as features for further prediction. To make sure encoded output is as close to your actual input, you have decoder which decodes your encoded high-dimensional input back to original input. During training, both encoder and decoder are involved i.e. the weights of the encoder layers and decoder layers both are updated. If the encoder is not trained how it's going to learn the encoding mechanism. During inference, you use only the encoder module as you want to encode the input.
| |
doc_23528767
|
the module is called "test" and it had 1 model called "room"
when i click on the menu i get this error
Traceback (most recent call last):
File "/home/blink22/Desktop/odoo-nada/odoo/odoo/http.py", line 656, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/home/blink22/Desktop/odoo-nada/odoo/odoo/http.py", line 314, in _handle_exception
raise pycompat.reraise(type(exception), exception, sys.exc_info()[2])
File "/home/blink22/Desktop/odoo-nada/odoo/odoo/tools/pycompat.py", line 87, in reraise
raise value
File "/home/blink22/Desktop/odoo-nada/odoo/odoo/http.py", line 698, in dispatch
result = self._call_function(**self.params)
File "/home/blink22/Desktop/odoo-nada/odoo/odoo/http.py", line 346, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/home/blink22/Desktop/odoo-nada/odoo/odoo/service/model.py", line 97, in wrapper
return f(dbname, *args, **kwargs)
File "/home/blink22/Desktop/odoo-nada/odoo/odoo/http.py", line 339, in checked_call
result = self.endpoint(*a, **kw)
File "/home/blink22/Desktop/odoo-nada/odoo/odoo/http.py", line 941, in __call__
return self.method(*args, **kw)
File "/home/blink22/Desktop/odoo-nada/odoo/odoo/http.py", line 519, in response_wrap
response = f(*args, **kw)
File "/home/blink22/Desktop/odoo-nada/odoo/addons/web/controllers/main.py", line 1262, in load
action = request.env[action_type].browse([action_id]).read()
File "/home/blink22/Desktop/odoo-nada/odoo/odoo/addons/base/models/ir_actions.py", line 210, in read
result = super(IrActionsActWindow, self).read(fields, load=load)
File "/home/blink22/Desktop/odoo-nada/odoo/odoo/models.py", line 2797, in read
vals[name] = convert(record[name], record, use_name_get)
File "/home/blink22/Desktop/odoo-nada/odoo/odoo/models.py", line 5123, in __getitem__
return self._fields[key].__get__(self, type(self))
File "/home/blink22/Desktop/odoo-nada/odoo/odoo/fields.py", line 985, in __get__
self.determine_value(record)
File "/home/blink22/Desktop/odoo-nada/odoo/odoo/fields.py", line 1098, in determine_value
self.compute_value(recs)
File "/home/blink22/Desktop/odoo-nada/odoo/odoo/fields.py", line 1052, in compute_value
self._compute_value(records)
File "/home/blink22/Desktop/odoo-nada/odoo/odoo/fields.py", line 1043, in _compute_value
getattr(records, self.compute)()
File "/home/blink22/Desktop/odoo-nada/odoo/odoo/addons/base/models/ir_actions.py", line 170, in _compute_search_view
fvg = self.env[act.res_model].fields_view_get(act.search_view_id.id, 'search')
File "/home/blink22/Desktop/odoo-nada/odoo/odoo/models.py", line 1455, in fields_view_get
result = self._fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu)
File "/home/blink22/Desktop/odoo-nada/odoo/odoo/models.py", line 1428, in _fields_view_get
arch_etree = getattr(self, '_get_default_%s_view' % view_type)()
File "/home/blink22/Desktop/odoo-nada/odoo/odoo/models.py", line 1258, in _get_default_search_view
return E.search(element, string=self._description)
File "/usr/local/lib/python3.6/dist-packages/lxml/builder.py", line 218, in __call__
get(dict)(elem, attrib)
File "/usr/local/lib/python3.6/dist-packages/lxml/builder.py", line 205, in add_dict
attrib[k] = typemap[type(v)](None, v)
KeyError: <class 'bool'>
here is my XML file:
<odoo>
<data>
<record model="ir.ui.view" id="test.listtt">
<field name="name">room list</field>
<field name="model">test.room</field>
<field name="arch" type="xml">
<tree>
<field name="name"/>
<field name="rating"/>
</tree>
</field>
</record>
<record model="ir.actions.act_window" id="test.action_window">
<field name="name">room window</field>
<field name="res_model">test.room</field>
<field name="view_mode">tree,form</field>
<field name="view_type">form</field>
</record>
<menuitem name="test" id="test.menu_root" action="test.action_window"/>
</data>
</odoo>
it seems that the action is not properly linked to my model view
i guess maybe the ids i provided are wrong or something
| |
doc_23528768
|
I know docx-merger, but it has problems.
It causes problems when there is a header.
and then, I want to merge into the next line, not the next page.
Is there a related library or code?.
I think it's impossible in NodeJs , so considering using Spire in Java api server.
but, I want to avoid make a api server.
Is there any way Nodejs can handle it?
| |
doc_23528769
|
What does it mean if I define functions or variables inside a context like the one just below?
(source: http://tutorialzine.com/2010/12/better-confirm-box-jquery-css3/)
(function($) {
$.confirm = function() {
...
}
$.confirm.hide = function() {
...
}
})(jQuery);
Also, what the $. mean in the function $.confirm? Also, with $.confirm.hide, I feel that there is some jQuery object involved.
A:
What does it mean if I define functions or variables inside a context like the one just below?
It means that you've defined a function, and ideally prevented global pollution (unfortunately, it wont actually help against global warming). There's a lot going on, so I'll try to split it out into a few parts:
(function($) {
$.confirm = function() {
...
}
$.confirm.hide = function() {
...
}
})(jQuery);
Part 1 - Closure
JavaScript is not like most other C-style languages, blocks1 do not get a new variable scope. In many C-style languages, a variable defined within a block will only exist within that block:
Some other C-style pseudo-code
function foo() {
var a = 1;
if (somecondition) {
var b = 2;
output(a, b); //1, 2
}
output(a, b); //throws some sort of exception because 'b' isn't defined.
}
JavaScript:
function foo() {
var a = 1;
if (somecondition) {
var b = 2;
output(a, b); //1, 2
}
output(a, b); //1, 2 due to variable hoisting
}
In JavaScript, variables don't have block scope, instead they have functional scope. Any defined variable is owned by it's first function ancestor. The instantiation of the variable is moved to the top of the function when the script is analyzed (this is called "variable hoisting"), so although you may have written foo (as seen above), what it's actually interpreted as is as follows:
function foo() {
var a, b;
a = 1;
if (somecondition) {
b = 2;
output(a, b);
}
output(a, b);
}
If there is no parent function of the variable, it's added to the global object, which in web browsers is window:
<script>
var a = 1;
output(window.a); //1 - set because there's no parent function
</script>
functions declared using function [some name]() {...} are treated similarly.
<script>
function foo() {return 1;}
output(window.foo()); //1
</script>
If you work on a large project and all variables are defined without a parent function, multiple programmers might use var foo, and would overwrite window.foo, which would lead to buggy and unstable code.
JavaScript allows for the creation of self-executing anonymous functions:
( function (){} )();
-or-
( function () {}() );
This is useful because it creates a new function context with which variables and functions can be defined without polluting the global namespace2. Functions like this that close over a set of variables/functions are called closures.
Parameters can be defined just like any other function, and they are passed to the function in the last set of parens. This explains your first and last lines of code:
(function ($) {
...
}(jQuery));
A new function context is created, and jQuery is being passed into the context into the variable $. This is used for aliasing jQuery to the shortcut $, which is a valid character for variable and function names.
Part 2 - Everything's an Object
Everything in JavaScript is an object, except for null and undefined. Mutable objects can have properties and methods set on them. Object literals ({}), array literals ([]), functions (function(){}), and objects created using constructors (new String('foo')) are all mutable objects.
var a = {};
a.foo = 'bar';
function b() {}
b.fizz = 'buzz';
This means that the jQuery object, which is a function, and has been aliased to $, can have new properties added to it:
$.confirm = function () {...};
And after the new $.confirm function is created, $.confirm is an object that can have properties added to it:
$.confirm.hide = function () {...};
If you wanted to call the confirm function outside of the closure, you'd write:
jQuery.confirm();
If you wanted to call the hide function outside of the closure, you'd write:
jQuery.confirm.hide();
1: a block is a section of code contained within {} characters, such as if (...) {/* block region */}, switch() {}, function () {}, while () {}, etc. Don't confuse object literals, which instantiate new objects, with blocks.
2: global namespace pollution is simply adding too many new variables on the global object, which is typically window
A: By wrapping a function in parens then executed using to more parents (function() {])(); is a n immediately invoked function. By passing in jQuery within the 2nd set of parens you pass in a paramter which you are you passing in as $.
$.confirm is just a method of the jQuery object
(function($) { // $ = jQuery
$.confirm = function() { // <-- set method of jQuery
...
}
$.confirm.hide = function() { // <-- set method of confirm
...
}
// usage
$.confirm();
// or
jQuery.confirm();
})(jQuery); // pass in the jQuery object to the function via immediate invocation
Many libraries, like jQuery, use $ as a shortcut variable because it stands out from typical variables used in javascript.
A: The code creates an anonymous function and calls it with jQuery as the argument. It's the same as
function addProperties($) {
$.confirm = function() {
...
}
$.confirm.hide = function() {
...
}
}
addProperties(jQuery);
$ is a valid variable name in javascript, and the function is adding properties to it. It's the same as:
function addProperties(j) {
j.confirm = function() {
...
}
j.confirm.hide = function() {
...
}
}
addProperties(jQuery);
jQuery is an object, and using the dot operator accesses its properties. For example, an object of apple might look like:
var apple = {
color: 'red',
height: 55,
foodType: 'fruit'
};
alert(apple.foodType); // alerts 'fruit'
You might have some misconceptions about jQuery based on your question. jQuery isn't a feature of javascript, it's a library of code that creates a large object called jQuery, though it can also be accessed as $.
A: The $ is the name of the parameter to the function that is used to create the scope, and because it's called with the jQuery object, $ will be equal to jQuery inside the scope. (By default the global name $ is also assigned jQuery, but this way of using a scope enables you to use $ inside it even if jQUery is used in compatibility mode, where the global $ identifier is not set.)
So, assigning a function to $.confirm will in effect assign it to jQuery.confirm.
As functions are objects in Javascript, you can add properties to them. That's why you can assign a function to $.confirm.hide, which is of course jQuery.confirm.hide.
After that code has run, you can call the jQuery.confirm function, and the jQuery.confirm.hide function.
| |
doc_23528770
|
Here's my xml.
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<LinearLayout
android:id="@+id/main_content_fragments"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<android.support.v7.widget.Toolbar
android:id="@+id/main_app_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<fragment
android:id="@+id/activity_fragment_main_event_list"
class="com.torneyo.torneyoadmin.fragments.EventListFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="@+id/activity_fragment_main_event_detail"
class="com.torneyo.torneyoadmin.fragments.EventDetailFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
android:background="?android:attr/detailsElementBackground" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="@+id/main_drawer"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:itemIconTint="@color/colorAccent"
app:itemTextColor="@color/colorTextSecondary"
app:menu="@menu/menu_drawer" />
</android.support.v4.widget.DrawerLayout>
Thoughts? I need to have the fragments show up. I'm not sure I'm using the layouts correctly.
Thanks!
A: Hello I see your layout file. I think the problem in it. It should inside the relative layout. kindly see the below modified layout version. Apply it let me know if you have any question in it.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="@+id/main_app_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="@color/colorPrimary"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<LinearLayout
android:id="@+id/main_content_fragments"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/main_app_toolbar"
android:orientation="horizontal">
<fragment
android:id="@+id/activity_fragment_main_event_list"
class="com.torneyo.torneyoadmin.fragments.EventListFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="@+id/activity_fragment_main_event_detail"
class="com.torneyo.torneyoadmin.fragments.EventDetailFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="3"
android:background="?android:attr/detailsElementBackground" />
</LinearLayout>
</RelativeLayout>
<android.support.design.widget.NavigationView
android:id="@+id/main_drawer"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/drawer_header"
app:itemIconTint="@color/colorAccent"
app:itemTextColor="@color/colorTextSecondary"
app:menu="@menu/menu_drawer" />
</android.support.v4.widget.DrawerLayout>
| |
doc_23528771
|
Possible Duplicate:
In xcode 4.5.1 , about ios ARC
here is my code(arc)
self.string1=@"aaa";
__weak NSString *temp= self.string1;
NSLog(@"string1 %@",self.string1);
NSLog(@"temp %@",temp);
self.string1=nil;
NSLog(@"---after self.string1 = nil----");
NSLog(@"string1 %@",self.string1);
NSLog(@"temp %@",temp);
I think the output should be as below:
string1 aaa
temp aaa
---after self.string1 = nil----
string1 (null)
temp (null)
However, when I run it in xcode4.5.1, it makes me confused
string1 aaa
temp aaa
---after self.string1 = nil----
string1 (null)
temp aaa
can anyone help me ,and tell me why temp=@"aaa" (it is __weak, and it should be nil after the string1=nil)
Edit:
hi,everyone. will we discuss in a wrong direction?
maybe the NSLog is defined in core Foundation Functions Reference. ARC has some rules for parameter of core foundation functions Just as NSLog ? we pass _weak object into NSLog as parameter, it will change _weak into _autorelease?
A: @"aaa" is a compile-time constant, and will never be released. So, even if your weak pointer is the only thing you have, it will still be a valid object.
Try the experiment again with run-time created string, using alloc / initWithFormat: or similar, and you should see the results you expect.
UPDATE
Having tested this myself now it still doesn't seem to work as expected. There is further discussion of this issue here
| |
doc_23528772
|
its working in almost all browser but not in opera mini.
My code is:
<pre>
<script type="text/javascript">
function doCheck(field) {
if (isNaN(document.getElementById(field).value)) {
alert('This is not a number! Please enter a valid number before submitting the form.');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}else {
return true;
}
}
function abc(){
var a;
a = document.getElementById('inp').value;
if(isNaN(a)){
alert("you can write only numbers");
document.getElementById('inp').value = "";
}
}
</script>
</pre>
A: as far as i know, Opera Mini only has limited JS support (and onKeyPress isn't one of them)
| |
doc_23528773
|
private DataSet BindGridView(List<int> userids)
{ DataSet ds = new DataSet();
string MysqlStatement = "SELECT OrganisationID, OrganisationName FROM tbl_organisation WHERE OrganisationID=@OrganisationID";
MySqlParameter[] param = new MySqlParameter[1];
foreach (var OrgID in userids)
{
param[0] = new MySqlParameter("@OrganisationID", MySqlDbType.Int32);
param[0].Value = OrgID;
ds = server.ExecuteQuery(CommandType.Text, MysqlStatement, param);
ds.Merge(ds);
}
Grid_Organisationtable.DataSource = ds;
Grid_Organisationtable.Columns[0].Visible = false;
Grid_Organisationtable.DataBind();
return ds;
}
I pass a list of values to the databinding method. I pass a list with organistionID. how should I do the databinding. It is returning an empty dataset. I am passing the list with values like 60,61,62. The error I am getting is
Unable to cast object of type 'System.Collections.Generic.List`1[System.Int32]' to type 'System.IConvertible'.
A: You can't pass in a list of id's into an SQL query in this way. Your SELECT statement as it stands is expecting the parameter passed in to be a single value to be used by the WHERE clause.
If you were to stick with this query you will need to loop through your list and pass in each value one at a time and make a seperate database call, for example:
string MysqlStatement = "SELECT OrganisationID, OrganisationName FROM tbl_organisation WHERE OrganisationID=@OrganisationID";
foreach(var id in userids)
{
MySqlParameter[] param = new MySqlParameter[1];
param[0] = new MySqlParameter("@OrganisationID", MySqlDbType.Int32);
param[0].Value = id;
ds = server.ExecuteQuery(CommandType.Text, MysqlStatement, param);
... add result to another list which is used to databind to your grid
}
A better alternative would be to use a WHERE...IN... clause and pass all your id's in one go as this will only fire one database call and there is not need to pass in parameters:
string MysqlStatement = string.Format("SELECT OrganisationID, OrganisationName FROM tbl_organisation WHERE OrganisationID IN ({0})", String.Join(",", userIds));
ds = server.ExecuteQuery(CommandType.Text, MysqlStatement, null);
Your third option would to write a stored procedure that accepted an xml string representation of your list and used this to query the database although this is somewhat more complicated. This way allows you to stick to using a parameter.
Note: it is usually very bad practice to not pass in dynamic data as parameters as this can leave you open to Sql injection attacks but in this case as the data is coming from a List parameter passed into your method you can be fairly sure that it isn't going to mess with your database.
A: In your code, you are setting the parameter in a for loop. As you have a single parameter and setting the same time and agian in the for loop, the last value in the list will be set effectively to the parameter in the last iteration of the loop.
If you need to pass a list and need to get a set of records that meet the list in the where condition, the alternate is to use where .. in clause.
So your effective code can be something like:
private DataSet BindGridView(List<int> userids)
{ DataSet ds = new DataSet();
string MysqlStatement = string.format("SELECT OrganisationID, OrganisationName FROM tbl_organisation WHERE OrganisationID in ({0})", String.Join(",", userIds));
MySqlParameter[] param = new MySqlParameter[1];
ds = server.ExecuteQuery(CommandType.Text, MysqlStatement, null);
Grid_Organisationtable.DataSource = ds;
Grid_Organisationtable.Columns[0].Visible = false;
Grid_Organisationtable.DataBind();
return ds;
}
| |
doc_23528774
|
<?php
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\MessageBag;
use App\account;
?>
<?php echo Form::open(['url' => '/formcontroller','enctype'=>'multipart/form-data','files'=>true,'method' => 'post',
'autocomplete'=>'off','id'=>'request_form']);?>
<div>account
<?php
$types=account::pluck('name','id')->all();
// echo Form::select('account_name', [''=>'Select']+$types,null,['class'=>'selectpicker default']);
?>
</div>
<?php echo Form::close(); ?>
A: I think the issue is here:
use App\account;
class name first character must be in Capital case. So it must be like:
use App\Account;
And its not a good practice to use model functionality inside view, it must be called in controller and the result is passed on to view.
Eloquent Model Conventions
Now, let's look at an example Flight model, which we will use to retrieve and store information from our flights database table:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
//
}
Note that we did not tell Eloquent which table to use for our Flight model. By convention, the "snake case", plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the Flight model stores records in the flights table.
Edit:
As you have mentioned in comment that you have no model with the specified name, in that case either make the model or use the query builder methods like:
DB::table('table')->where()->get();
A: $types= DB::table('account')->pluck('name','id')->all();
| |
doc_23528775
|
This build is using a beta version of Xcode and can’t be submitted.
Make sure you’re using the latest version of Xcode or the latest seed
release found on the releases tab in News and Updates
I am using Xcode Version 14.2 (14C18), I am not sure if its beta, but it is the latest one available in the app store.
Do I need to downgrade to some previous version or there is some other issue? Thanks.
A: After hours of debugging I found the issue. My Info.plist file was missing several metadata info like -
<key>DTXcode</key>
<string>1331</string>
<key>DTXcodeBuild</key>
<string>13E500a</string>
After adding those testflight accepted the build.
| |
doc_23528776
|
The table being updated has over 600000 records. The select statement in the sql runs fast when tested alone so it has to be the update part.
UPDATE tblPackage
SET IsUpdated = 1,
ShippingCost = (
SELECT SUM(SC.ShippingCost)
FROM tblShippingCost SC
WHERE SC.PackageID = P.PackageID)
FROM tblShippingCost SC
INNER JOIN tblPackage P ON P.PackageID = SC.PackageID
INNER JOIN tblRunPackage RP ON RP.PackageID = P.PackageID
INNER JOIN tblRun R ON R.RunID = RP.RunID
INNER JOIN tblOrderItem OI ON OI.OrderItemID = R.OrderItemID
INNER JOIN tblOrder O ON O.OrderID = OI.OrderID
WHERE
O.InvoiceID IS NULL
AND SC.PackageID = P.PackageID
I welcome any and all suggestions.
Thanks!
A: You have joined tblshippingcost an extra time, this will not give the wrong result. But it will take more time joining and calculating. Try removing that part from your update like this:
UPDATE tblPackage
SET
IsUpdated = 1,
ShippingCost = (
SELECT SUM(SC.ShippingCost)
FROM tblShippingCost SC
WHERE SC.PackageID = P.PackageID
)
FROM
tblPackage P
INNER JOIN
tblRunPackage RP ON RP.PackageID = P.PackageID
INNER JOIN
tblRun R ON R.RunID = RP.RunID
INNER JOIN
tblOrderItem OI ON OI.OrderItemID = R.OrderItemID
INNER JOIN
tblOrder O ON O.OrderID = OI.OrderID
WHERE
O.InvoiceID IS NULL
A: try this
UPDATE tblPackage
SET IsUpdated = 1,
ShippingCost = SUM(SC.ShippingCost)
FROM tblShippingCost SC
INNER JOIN tblPackage P ON P.PackageID = SC.PackageID
INNER JOIN tblRunPackage RP ON RP.PackageID = P.PackageID
INNER JOIN tblRun R ON R.RunID = RP.RunID
INNER JOIN tblOrderItem OI ON OI.OrderItemID = R.OrderItemID
INNER JOIN tblOrder O ON O.OrderID = OI.OrderID
WHERE
O.InvoiceID IS NULL
AND SC.PackageID = P.PackageID
| |
doc_23528777
|
package com.amalwa.hadoop.MapReduce;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import com.google.gson.Gson;
public class ETL{
public static void main(String[] args) throws Exception{
if (args.length < 2) {
System.err.println("Usage: ETL <input path> <output path>");
System.exit(-1);
}
Configuration conf = new Configuration();
Job job = new Job(conf, "etl");
job.setJarByClass(ETL.class);
job.setMapperClass(JsonParserMapper.class);
job.setReducerClass(JsonParserReducer.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(Text.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(TweetArray.class);
FileInputFormat.addInputPath(job, new Path(args[1]));
FileOutputFormat.setOutputPath(job, new Path(args[2]));
job.waitForCompletion(true);
}
public static class JsonParserMapper extends Mapper<LongWritable, Text, Text, Text>{
private Text mapperKey = null;
private Text mapperValue = null;
Date filterDate = getDate("Sun Apr 20 00:00:00 +0000 2014");
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String jsonString = value.toString();
if(!jsonString.isEmpty()){
@SuppressWarnings("unchecked")
Map<String, Object> tweetData = new Gson().fromJson(jsonString, HashMap.class);
Date timeStamp = getDate(tweetData.get("created_at").toString());
if(timeStamp.after(filterDate)){
@SuppressWarnings("unchecked")
com.google.gson.internal.LinkedTreeMap<String, Object> userData = (com.google.gson.internal.LinkedTreeMap<String, Object>) tweetData.get("user");
mapperKey = new Text(userData.get("id_str") + "~" + tweetData.get("created_at").toString());
mapperValue = new Text(tweetData.get("text").toString() + " tweetId = " + tweetData.get("id_str"));
context.write(mapperKey, mapperValue);
}
}
}
public Date getDate(String timeStamp){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = null;
try {
date = simpleDateFormat.parse(timeStamp);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
public static class JsonParserReducer extends Reducer<Text, Text, Text, TweetArray> {
private ArrayList<Text> tweetList = new ArrayList<Text>();
public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
for (Text val : values) {
tweetList.add(new Text(val.toString()));
}
context.write(key, new TweetArray(Text.class, tweetList.toArray(new Text[tweetList.size()])));
}
}
}
please if someone can clarify this problem, it would be really nice. I have deployed this jar on my local machine on which I installed hadoop and it works fine, but when I set up my cluster using AWS and provide the streaming job with all the parameters it doesn't work. Here is a screen shot of my configuration:
The Mapper textbox is set to: java -classpath MapReduce-0.0.1-SNAPSHOT-jar-with-dependencies.jar com.amalwa.hadoop.MapReduce.JsonParserMapper
The Reducer textbox is set to: java -classpath MapReduce-0.0.1-SNAPSHOT-jar-with-dependencies.jar com.amalwa.hadoop.MapReduce.JsonParserReducer
Thanks and regards.
A: You need to select custom jar step instead of streaming program.
A: When you make the jar file (I usually do it using Eclipse or a custom gradle build), check if your main class is set to ETL. Apparently, that does not happen by default. Also check the Java version you are using on ur system. I think the aws emr works with upto java 7.
| |
doc_23528778
|
sh.enableSharding('vsm');
sh.shardCollection('vsm.pricelist', {maker_id:1});
Ok, we enabled sharding for Database (vsm) and collection in this database (pricelist).
We trying to write about 80 million documents to 'pricelist' collection.
And we have about 2000 distributed uniformly different maker_ids.
We have three shards. And Shard002 is PRIMARY for 'vsm' database.
We write to 'pricelist' collection from four application nodes with started mongos on each.
And during write data to 'pricelist' collection we see CPU Usage 100% ONLY on Shard002 !
We see rebalancing process. And data migrate to Shard000 and Shard003. But Shard002 has hight CPU Usage and Load Average!
Shards deployed on c4.xlarge EBS Optimized instances. dbdata stored on io1 with 2000 IOPS EBS Volumes.
It is looks like MongoDB write data only to one Shard :( What we do wrong?
A:
Is MongoDB always write to primary Shard and then rebalance?
Yes, if you are relying on auto balancer. And loading huge amounts of data into an empty collection
In your situation, you are relying on the autobalancer to do all the sharding / balancing stuff. I assume what you require is, as your data gets loaded it goes to each shard during load hence having less CPU usage etc.
This how sharding / autobalancing will take place on a high level.
*
*Create chunks of data using split http://docs.mongodb.org/manual/reference/command/split/
*Move the chunks to other shards http://docs.mongodb.org/manual/reference/command/moveChunk/#dbcmd.moveChunk
Now, when autobalancer is ON these two steps occur when your data is already loaded or loading.
Solution
*
*Create empty collection. Execute the shard command on it. The collection where your data is going to get loaded.
*Turn off the auto balancer http://docs.mongodb.org/manual/tutorial/manage-sharded-cluster-balancer/#disable-the-balancer
*Manually create empty chunks using split. http://docs.mongodb.org/manual/tutorial/create-chunks-in-sharded-cluster/
*Move those empty chunks to different shards. http://docs.mongodb.org/manual/tutorial/migrate-chunks-in-sharded-cluster/
*Start the load, This time all your data should go directly to their respective shards.
*Turn ON the balancer. (Once the load is complete) http://docs.mongodb.org/manual/tutorial/manage-sharded-cluster-balancer/#enable-the-balancer
You will have to test this approach using a small data set first. But I guess I have got enough information for you to get started.
A: The problem
What you describe is usually the indication that you have chosen a poor shard key with makerid, most likely monotonically increasing.
What usually happens is that one shard is assigned the key range from x to infinity (shard002 in your case). Now all new documents get written to that shard, until that shards holds more chunks in excess of the current migration threshold. Now the balancer kicks in and moves some chunks. Problem is that new documents still get written to said shard.
The solution
An easy solution for that problem is to use hashed keys for sharding
Now here comes the serious problem: you can not change the shard key.
So what you have to do is to make a backup of the sharded collection, drop it, reshard the collection using the hashed makerId and restore the backup into the new collection.
| |
doc_23528779
|
Here is the code I use:
public void paint(Graphics g)
{
if(this.background != null)
{
int bounds_top = getHeight() / 2;
int bounds_left = getWidth() / 2;
int half_height = this.background.getHeight(null) / 2;
int half_width = this.background.getWidth(null) / 2;
g.drawImage(this.background, bounds_left - half_width, bounds_top - half_height, this.background.getWidth(null), this.background.getHeight(null), this);
this.setBackground(Color.black);
//this.setOpaque(false);
}
}
If I set the frame to be opaqe, my image is displayed but the background is gray.
If I set opaque to false, my frame is just black, no image is displayed.
So here is my question, how can I display my image and have a back background?
A: If you are doing this in a JPanel child, call setBackground(Color.black); in the constructor, and implement the code in paintComponent first calling super.paintComponent(g); for the black background.
A: You are drawing the image to the background, and then setting the background color to black. Try setting the background color to black first, and then draw the image to it. Otherwise it looks like you are drawing black over the image.
A: I found a litle trick to solve it:
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(Color.BLACK);
g2.fill(new Rectangle2D.Double(0, 0, getWidth(), getHeight()));
g.drawImage(this.background, bounds_left - half_width, bounds_top - half_height, this.background.getWidth(null), this.background.getHeight(null), this);
This works well.
| |
doc_23528780
|
Does anyone know how this can be achieved?
A: I was able to get around this by promoting the missing file to the stream, resolving the merge, and then defuncting it again afterwards.
A: You will need to run the merge, once complete, just defunct the file and promote.
| |
doc_23528781
|
...
<GridView AllowsColumnReorder="True" ColumnHeaderToolTip="Info test">
<GridViewColumn Header="Number" Width="120">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Path=extensions}" Width="105" IsEditable="True" HorizontalAlignment="Center" Margin="0,0,0,0" BorderThickness="0">
<ComboBox.Resources>
<sys:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">15</sys:Double>
</ComboBox.Resources>
</ComboBox>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
...
In the code behind, "extensions" is an ObserverableCollection<string> that is 100% getting initialized and populated (this is in the class constructor):
public partial class MyForm : Window
{
...
public ObservableCollection<string> extensions;
...
public MyForm()
{
...
Initialize();
}
private Initialize()
{
extensions = new ObservableCollection<string>();
extensions.Add("x100");
extensions.Add("x101");
}
}
But when the application runs while the comboboxes appear, the binding never happens. What additional step(s) are required for this to be complete/correct?
A: First do not use public field, use properties instead. As far as I know public fields doesn't work with binding.
public ObservableCollection<string> extensions {get; private set;}
Second, probably the datacontext of the combobox is not set to the MyForm instance.
Try this
<ComboBox ItemsSource="{Binding Path=extensions, RelativeSource={RelativeSource AncestorType={x:Type MyForm}}}" ... >
| |
doc_23528782
|
producer.on('delivery-report', function (err, report) {
console.log("delivery report received");
console.log('delivery-report: ' + JSON.stringify(report));
});
A: For delivery-report event there is a once binding which delivers only one delivery report for each message.
producer.once('delivery-report', function (err, report) {
console.log("delivery report received");
console.log('delivery-report: ' + JSON.stringify(report));
});
| |
doc_23528783
|
java.lang.LinkageError: loader constraint violation: when resolving method "org.slf4j.impl.StaticLoggerBinder.getLoggerFactory()Lorg/slf4j/ILoggerFactory;" the class loader (instance of org/eclipse/jetty/webapp/WebAppClassLoader) of the current class, org/slf4j/LoggerFactory, and the class loader (instance of sun/misc/Launcher$AppClassLoader) for the method's defining class, org/slf4j/impl/StaticLoggerBinder, have different Class objects for the type org/slf4j/ILoggerFactory used in the signature
Problem is, the war file already contains slf4j. Any suggestions?
I tried to change my maven pom to "provider, which didn't help.
A: Use WebAppContext's (which it seems like from your error, and the mention of WebAppClassLoader).
Don't modify the Server or System classes lists on the WebAppContext or the WebAppClassLoader.
Don't set the WebAppContext.setParentLoaderPriority(boolean) field.
That's it.
Now you have the ClassLoader Isolation you are looking for.
| |
doc_23528784
|
public IQueryable<ClassA> search(IQueryable<ClassA> query,string name,string number)
{
if (name!= null )
query = query.Where( a =>a.name.Contains(name) );
if (number!= null )
query = query.Where( a =>a.number.ToString().Contains(numbr) );
return query;
}
and
public IQueryable<ClassB> search(IQueryable<ClassB> query,string address, string email)
{
if (address!= null )
query = query.Where( a =>a.name.Contains(address) );
if (email!= null )
query = query.Where( a =>a.email.Contains(email) );
return query;
}
Since the implementation is same but ClassA and ClassB has different attributes involving different checks to search the value.
How to make a single generic function where I can perform searching with both of these classes?
A: Possible solution, using object reflection. Parameter has two strings in pair. First is the name of property, second is the value of it.
public IQueryable<T> search(IQueryable<T> query, params Tuple<string, string>[] parameters)
{
Type type = typeof(T);
PropertyInfo[] properties = type.GetProperties();
foreach(var parameter in parameters)
{
PropertyInfo pi = properties.Where(a => a.Name == parameter.Item1).FirstOrDefault();
if (pi != null)
{
query = query.Where(a => pi.GetValue(a).ToString().Contains(parameter.Item2));
}
}
return query;
}
A: You can make both clases of the same interface IPropertyWalker for example. It should have thestring indexer.
public string this[string key]
{
switch(key)
{
case "Name"
return Name;
//list all you need for your class
}
}
And then pass property names to compare data.
A: Improving on @wannadreams response, you can lookup property information only if member type of the target is a property. Here is a full example.
class ClassA
{
// Will work
public string Name { get; set; }
// Will not work
public string Name;
}
public static async Task Main(string[] args)
{
IQueryable<ClassA> query = ...
search(query, Tuple.Create(nameof(ClassA.Name), "myName"));
}
public static IQueryable<T> search<T>(
IQueryable<T> query,
params Tuple<string, string>[] parameters)
where T : class
{
foreach(var criteria in parameters) {
var property = typeof(T).GetProperty(criteria.Item1);
if (property == null) continue;
// you also need to verify the property was retrievable from the instance.
query = query.Where(item => property.GetValue(item) != null)
.Where(item => property.GetValue(item).ToString().Contains(criteria.Item2));
}
return query;
}
| |
doc_23528785
|
order_products:
order_id,product_id,add_to_cart_order,reordered
2,33120,1,1
2,28985,2,1
2,9327,3,0
2,45918,4,1
3,17668,1,1
3,46667,2,1
3,17461,4,1
3,32665,3,1
4,46842,1,0
products:
product_id,product_name,aisle_id,department_id
9327,Garlic Powder,104,13
17461,Air Chilled Organic Boneless Skinless Chicken Breasts,35,12
17668,Unsweetened Chocolate Almond Breeze Almond Milk,91,16
28985,Michigan Organic Kale,83,4
32665,Organic Ezekiel 49 Bread Cinnamon Raisin,112,3
33120,Organic Egg Whites,86,16
45918,Coconut Butter,19,13
46667,Organic Ginger Root,83,4
46842,Plain Pre-Sliced Bagels,93,3
I'm to then create a new table that lists for each department, the number of orders created for this department, the number of first orders, and the ratio of (number of first orders / number of orders) for that department
So the resulting table would look like:
department_id,number_of_orders,number_of_first_orders,percentage
3,2,1,0.50
4,2,0,0.00
12,1,0,0.00
13,2,1,0.50
16,2,0,0.00
My solution involving Pandas:
orders = pd.read_csv("../insight_testsuite/tests/test_1/input/order_products.csv")
products = pd.read_csv("../insight_testsuite/tests/test_1/input/products.csv")
orders.drop(['add_to_cart_order'], axis=1, inplace=True)
products.drop(['aisle_id', 'product_name'], axis=1, inplace=True)
dep = pd.merge(orders, products)
dep = (dep.groupby('department_id')['reordered']
.agg([('number_of_orders','size'),
('number_of_first_orders', lambda x: x.eq(0).sum())
])
.reset_index())
dep['percentage'] = ("%.2f" %
round((dep['number_of_first_orders'] / dep['number_of_orders']), 2))
But with regular Python, AFAIK, you can only go through the CSV file line by line and evaluate from there. So I'm not sure how you can perform that kind of analysis without using Pandas.
A: Well, you can. It just takes a lot of work:
from collections import defaultdict
import pandas as pd
s1 = '''order_id,product_id,add_to_cart_order,reordered
2,33120,1,1
2,28985,2,1
2,9327,3,0
2,45918,4,1
3,17668,1,1
3,46667,2,1
3,17461,4,1
3,32665,3,1
4,46842,1,0'''
s2 = '''product_id,product_name,aisle_id,department_id
9327,Garlic Powder,104,13
17461,Air Chilled Organic Boneless Skinless Chicken Breasts,35,12
17668,Unsweetened Chocolate Almond Breeze Almond Milk,91,16
28985,Michigan Organic Kale,83,4
32665,Organic Ezekiel 49 Bread Cinnamon Raisin,112,3
33120,Organic Egg Whites,86,16
45918,Coconut Butter,19,13
46667,Organic Ginger Root,83,4
46842,Plain Pre-Sliced Bagels,93,3'''
result = '''department_id,number_of_orders,number_of_first_orders,percentage
3,2,1,0.50
4,2,0,0.00
12,1,0,0.00
13,2,1,0.50
16,2,0,0.00'''
lines = s1.split('\n')
# lines
# ['order_id,product_id,add_to_cart_order,reordered', '2,33120,1,1', '2,28985,2,1', '2,9327,3,0', '2,45918,4,1',
# '3,17668,1,1', '3,46667,2,1', '3,17461,4,1', '3,32665,3,1', '4,46842,1,0']
splitlines = [x.split(',') for x in lines]
# splitlines
# [['order_id', 'product_id', 'add_to_cart_order', 'reordered'], ['2', '33120', '1', '1'], ['2', '28985', '2', '1'],
# ['2', '9327', '3', '0'], ['2', '45918', '4', '1'], ['3', '17668', '1', '1'], ['3', '46667', '2', '1'],
# ['3', '17461', '4', '1'], ['3', '32665', '3', '1'], ['4', '46842', '1', '0']]
orders = {}
for j, k in enumerate(splitlines[0]):
orders[k] = [int(splitlines[i][j]) for i in range(1, len(splitlines))]
# orders
# {'order_id': [2, 2, 2, 2, 3, 3, 3, 3, 4], 'product_id': [33120, 28985, 9327, 45918, 17668, 46667, 17461, 32665, 46842],
# 'add_to_cart_order': [1, 2, 3, 4, 1, 2, 4, 3, 1], 'reordered': [1, 1, 0, 1, 1, 1, 1, 1, 0]}
lines = s2.split('\n')
# lines
# ['product_id,product_name,aisle_id,department_id', '9327,Garlic Powder,104,13',
# '17461,Air Chilled Organic Boneless Skinless Chicken Breasts,35,12',
# '17668,Unsweetened Chocolate Almond Breeze Almond Milk,91,16', '28985,Michigan Organic Kale,83,4',
# '32665,Organic Ezekiel 49 Bread Cinnamon Raisin,112,3', '33120,Organic Egg Whites,86,16', '45918,Coconut Butter,19,13',
# '46667,Organic Ginger Root,83,4', '46842,Plain Pre-Sliced Bagels,93,3']
splitlines = [x.split(',') for x in lines]
# splitlines
# [['product_id', 'product_name', 'aisle_id', 'department_id'], ['9327', 'Garlic Powder', '104', '13'],
# ['17461', 'Air Chilled Organic Boneless Skinless Chicken Breasts', '35', '12'],
# ['17668', 'Unsweetened Chocolate Almond Breeze Almond Milk', '91', '16'],
# ['28985', 'Michigan Organic Kale', '83', '4'], ['32665', 'Organic Ezekiel 49 Bread Cinnamon Raisin', '112', '3'],
# ['33120', 'Organic Egg Whites', '86', '16'], ['45918', 'Coconut Butter', '19', '13'],
# ['46667', 'Organic Ginger Root', '83', '4'], ['46842', 'Plain Pre-Sliced Bagels', '93', '3']]
products = {}
for j, k in enumerate(splitlines[0]):
products[k] = [splitlines[i][j] for i in range(1, len(splitlines))]
# products
# {'product_id': ['9327', '17461', '17668', '28985', '32665', '33120', '45918', '46667', '46842'],
# 'product_name': ['Garlic Powder', 'Air Chilled Organic Boneless Skinless Chicken Breasts',
# 'Unsweetened Chocolate Almond Breeze Almond Milk', 'Michigan Organic Kale',
# 'Organic Ezekiel 49 Bread Cinnamon Raisin', 'Organic Egg Whites', 'Coconut Butter',
# 'Organic Ginger Root', 'Plain Pre-Sliced Bagels'],
# 'aisle_id': ['104', '35', '91', '83', '112', '86', '19', '83', '93'],
# 'department_id': ['13', '12', '16', '4', '3', '16', '13', '4', '3']}
departments = list(set(products['department_id']))
# departments
# ['13', '16', '12', '3', '4']
order_counts = defaultdict(int)
for thing in products['department_id']:
order_counts[thing] += 1
# order_counts
# defaultdict( < class 'int'>, {'13': 2, '12': 1, '16': 2, '4': 2, '3': 2})
report = {}
departments.sort(key=lambda x: int(x))
# departments
# ['3', '4', '12', '13', '16']
report['department_id'] = departments
report['number_of_orders'] = [order_counts[dep] for dep in report['department_id']]
# report
# {'department_id': ['3', '4', '12', '13', '16'], 'number_of_orders': [2, 2, 1, 2, 2]}
first_order_count = defaultdict(int)
department_product = defaultdict(list)
for i in range(len(products['product_id'])):
if products['department_id'][i] in departments:
department_product[products['department_id'][i]].append(products['product_id'][i])
# department_product
# defaultdict( <class 'list'>, {'13': ['9327', '45918'], '12': ['17461'], '16': ['17668', '33120'], '4': ['28985', '46667'], '3': ['32665', '46842']})
order_first_counts = defaultdict(int)
product_department = {}
for dep, prodlist in department_product.items():
for prod in prodlist:
product_department[prod] = dep
# product_department
# {'9327': '13', '45918': '13', '17461': '12', '17668': '16', '33120': '16', '28985': '4', '46667': '4', '32665': '3',
# '46842': '3'}
first_order_count = defaultdict(int)
for prod, reordered in zip(orders['product_id'], orders['reordered']):
if product_department[str(prod)] in departments and int(reordered) == 0:
first_order_count[product_department[str(prod)]] += 1
# first_order_count
# defaultdict(<class 'int'>, {'13': 1, '3': 1})
report['number_of_first_orders'] = [first_order_count[dep] for dep in report['department_id']]
report['first_order_ratio'] = [q[0] / q[1] for q in zip(report['number_of_first_orders'], report['number_of_orders'])]
# report
# {'department_id': ['3', '4', '12', '13', '16'], 'number_of_orders': [2, 2, 1, 2, 2],
# 'number_of_first_orders': [1, 0, 0, 1, 0], 'first_order_ratio': [0.5, 0.0, 0.0, 0.5, 0.0]}
reportdf = pd.DataFrame.from_dict(report)
# department_id number_of_orders number_of_first_orders first_order_ratio
# 0 3 2 1 0.5
# 1 4 2 0 0.0
# 2 12 1 0 0.0
# 3 13 2 1 0.5
# 4 16 2 0 0.0
Presented for your amusement. I may come back and put some strategic comments in where I built dictionaries to represent FKeys and so on
Cheers!
| |
doc_23528786
|
Please find my the screenshots below:
*
*pom.xml file:
*External Library
*Dependencies added after successful maven build :
Tried to create a new project to check whether the above issues persist there as well,but there its working as expected as i am able to get the required java files.So the issue is only relevant to the above project.
I even tried to do the steps mentioned from the below links apart from the maven life cycle steps,but that also did not work out
link
| |
doc_23528787
|
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
if (!string.IsNullOrEmpty(result))
{
byte[] byteArray = Encoding.UTF8.GetBytes(result);
File.WriteAllBytes(Environment.CurrentDirectory + @"\label.pdf", byteArray);
}
}
A: Don't use a StreamReader. A StreamReader is for turning a stream of bytes into a stream of characters. However, PDFs are binary files, and you shouldn't turn them into text.
Simply copy the bytes that you are downloading directly into a file, without turning them into characters:
using (var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())
using (var responseStream = httpResponse.GetResponseStream())
using (var fileStream = File.Create(Path.Combine(Environment.CurrentDirectory, "label.pdf")))
{
responseStream.CopyTo(fileStream);
}
A: PDF is bytes, not text - it looks like you're fetching the PDF from an http request, in which case you don't want to use StreamReader, string or Encoding here - you just want the raw bytes. You can probably just use httpResponse.GetResponseStream().CopyTo(someOtherStream) where someOtherStream is a FileStream to the location, i.e.
using (var target = File.Create(path))
using (var source = httpResponse.GetResponseStream())
{
source.CopyTo(target);
}
| |
doc_23528788
|
function: getRuntime
I have a sample python script, in the script after some functionality check, it require's some input from the user, this script I want to execute using getRuntime().exec() method. I know we can give command line arguments to the script through getRuntime().exec() method, but I'm not sure if the above scenario is possible using getRuntime().exec() method.
Is it possible to do it, please let me know?
A: Runtime.exec() gives you a Process. you can read and write to that Process (using getOutputStream() and getInputStream(), which allows you to get what's output by your script and send it more information afterwards. See for example this other thread.
| |
doc_23528789
|
If multiple threads detect a cache miss at about the same time.They might attempt to load data simultaneously.In conclusion , data will be the same...
Is it true ?
public class Worker
{
private static object someLock;
public static object CacheMethod()
{
var results = HttpContext.Current.Cache["Common"];
if (results == null)
{
lock (someLock)
{
results = HttpContext.Current.Cache["Common"];
if (results == null)
{
results = GetResultsFromSomewhere();
HttpContext.Current.Cache.Insert("Common", results, null,
DateTime.Now.AddHours(1), Cache.NoSlidingExpiration);
}
}
}
return results;
}``
A: This lock is used to prevent cache stampeding. If the cache is empty and takes a while to fill then all incoming requests will start to fill the cache. Depending on how the numbers work out that can be a catastrophic loss of performance.
If GetResultsFromSomewhere was Thread.Sleep(10000) then this could easily happen.
The bad thing about that particular code is that it's one lock for all cache keys. Usually you want one lock per key.
A: This is called a double-checked locking pattern. Yes, it is true that if you have many requests and the data takes longer to retrieve than the time between requests, you could have multiple requests for the same data.
Without the locking, each additional thread is receiving the same data so the amount of CPU/Network Activity/RAM used by the additional threads is just wasted. Whether or not this is a problem depends on how much traffic your site has and the available server/network resources.
However, it is much more important to ensure that your results object itself is thread-safe, because you are guaranteed to have multiple threads interacting with its state. The simplest way is just to make all of its properties read-only, but if you need writable properties you could use a ReaderWriterLockSlim in conjunction with methods that ensure atomic actions (see the examples in the link).
| |
doc_23528790
|
I uninstalled and installed two other versions of python and I got the same error whenever I want to install modules..Any idea on how to solve the problem?
A: Uninstall Python and remove all Python directories from the "User PATH" Environment Variable (And if there are only Python directories, then delete the variable):
Then reinstall Python, and don't forget to check "Add Python to PATH" (Important).
| |
doc_23528791
|
I have a process running, let's call it Process1. Process1 creates a new process, Process2, and saves its id.
Now, at some point Process1 wants Process2 to do something, so it first needs to make sure that Process2 is still alive and that the user has not not killed it.
How can I check that this process is still running?
Since I created it, I have the Process ID, I would think there is some library function along the lines of IsProcessIDValid( id ) but I can't find it on MSDN
A: You can use GetExitCodeProcess. It will return STILL_ACTIVE (259) if the process is still running (or if it happened to exit with that exit code :( ).
A: I found this today, it is from 2003. It finds a process by name, you don't even need the pid.
\#include windows.h
\#include tlhelp32.h
\#include iostream.h
int FIND_PROC_BY_NAME(const char *);
int main(int argc, char *argv[])
{
// Check whether a process is currently running, or not
char szName[100]="notepad.exe"; // Name of process to find
int isRunning;
isRunning=FIND_PROC_BY_NAME(szName);
// Note: isRunning=0 means process not found, =1 means yes, it is found in memor
return isRunning;
}
int FIND_PROC_BY_NAME(const char *szToFind)
// Created: 12/29/2000 (RK)
// Last modified: 6/16/2003 (RK)
// Please report any problems or bugs to kochhar@physiology.wisc.edu
// The latest version of this routine can be found at:
// http://www.neurophys.wisc.edu/ravi/software/killproc/
// Check whether the process "szToFind" is currently running in memory
// This works for Win/95/98/ME and also Win/NT/2000/XP
// The process name is case-insensitive, i.e. "notepad.exe" and "NOTEPAD.EXE"
// will both work (for szToFind)
// Return codes are as follows:
// 0 = Process was not found
// 1 = Process was found
// 605 = Unable to search for process
// 606 = Unable to identify system type
// 607 = Unsupported OS
// 632 = Process name is invalid
// Change history:
// 3/10/2002 - Fixed memory leak in some cases (hSnapShot and
// and hSnapShotm were not being closed sometimes)
// 6/13/2003 - Removed iFound (was not being used, as pointed out
// by John Emmas)
{
BOOL bResult,bResultm;
DWORD aiPID[1000],iCb=1000,iNumProc,iV2000=0;
DWORD iCbneeded,i;
char szName[MAX_PATH],szToFindUpper[MAX_PATH];
HANDLE hProc,hSnapShot,hSnapShotm;
OSVERSIONINFO osvi;
HINSTANCE hInstLib;
int iLen,iLenP,indx;
HMODULE hMod;
PROCESSENTRY32 procentry;
MODULEENTRY32 modentry;
// PSAPI Function Pointers.
BOOL (WINAPI *lpfEnumProcesses)( DWORD *, DWORD cb, DWORD * );
BOOL (WINAPI *lpfEnumProcessModules)( HANDLE, HMODULE *,
DWORD, LPDWORD );
DWORD (WINAPI *lpfGetModuleBaseName)( HANDLE, HMODULE,
LPTSTR, DWORD );
// ToolHelp Function Pointers.
HANDLE (WINAPI *lpfCreateToolhelp32Snapshot)(DWORD,DWORD) ;
BOOL (WINAPI *lpfProcess32First)(HANDLE,LPPROCESSENTRY32) ;
BOOL (WINAPI *lpfProcess32Next)(HANDLE,LPPROCESSENTRY32) ;
BOOL (WINAPI *lpfModule32First)(HANDLE,LPMODULEENTRY32) ;
BOOL (WINAPI *lpfModule32Next)(HANDLE,LPMODULEENTRY32) ;
// Transfer Process name into "szToFindUpper" and
// convert it to upper case
iLenP=strlen(szToFind);
if(iLenP<1 || iLenP>MAX_PATH) return 632;
for(indx=0;indx<iLenP;indx++)
szToFindUpper[indx]=toupper(szToFind[indx]);
szToFindUpper[iLenP]=0;
// First check what version of Windows we're in
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
bResult=GetVersionEx(&osvi);
if(!bResult) // Unable to identify system version
return 606;
// At Present we only support Win/NT/2000 or Win/9x/ME
if((osvi.dwPlatformId != VER_PLATFORM_WIN32_NT) &&
(osvi.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS))
return 607;
if(osvi.dwPlatformId==VER_PLATFORM_WIN32_NT)
{
// Win/NT or 2000 or XP
// Load library and get the procedures explicitly. We do
// this so that we don't have to worry about modules using
// this code failing to load under Windows 95, because
// it can't resolve references to the PSAPI.DLL.
hInstLib = LoadLibraryA("PSAPI.DLL");
if(hInstLib == NULL)
return 605;
// Get procedure addresses.
lpfEnumProcesses = (BOOL(WINAPI *)(DWORD *,DWORD,DWORD*))
GetProcAddress( hInstLib, "EnumProcesses" ) ;
lpfEnumProcessModules = (BOOL(WINAPI *)(HANDLE, HMODULE *,
DWORD, LPDWORD)) GetProcAddress( hInstLib,
"EnumProcessModules" ) ;
lpfGetModuleBaseName =(DWORD (WINAPI *)(HANDLE, HMODULE,
LPTSTR, DWORD )) GetProcAddress( hInstLib,
"GetModuleBaseNameA" ) ;
if( lpfEnumProcesses == NULL ||
lpfEnumProcessModules == NULL ||
lpfGetModuleBaseName == NULL)
{
FreeLibrary(hInstLib);
return 605;
}
bResult=lpfEnumProcesses(aiPID,iCb,&iCbneeded);
if(!bResult)
{
// Unable to get process list, EnumProcesses failed
FreeLibrary(hInstLib);
return 605;
}
// How many processes are there?
iNumProc=iCbneeded/sizeof(DWORD);
// Get and match the name of each process
for(i=0;i<iNumProc;i++)
{
// Get the (module) name for this process
strcpy(szName,"Unknown");
// First, get a handle to the process
hProc=OpenProcess(PROCESS_QUERY_INFORMATION|PROCESS_VM_READ,FALSE,
aiPID[i]);
// Now, get the process name
if(hProc)
{
if(lpfEnumProcessModules(hProc,&hMod,sizeof(hMod),&iCbneeded) )
{
iLen=lpfGetModuleBaseName(hProc,hMod,szName,MAX_PATH);
}
}
CloseHandle(hProc);
// Match regardless of lower or upper case
if(strcmp(_strupr(szName),szToFindUpper)==0)
{
// Process found
FreeLibrary(hInstLib);
return 1;
}
}
}
if(osvi.dwPlatformId==VER_PLATFORM_WIN32_WINDOWS)
{
// Win/95 or 98 or ME
hInstLib = LoadLibraryA("Kernel32.DLL");
if( hInstLib == NULL )
return FALSE ;
// Get procedure addresses.
// We are linking to these functions of Kernel32
// explicitly, because otherwise a module using
// this code would fail to load under Windows NT,
// which does not have the Toolhelp32
// functions in the Kernel 32.
lpfCreateToolhelp32Snapshot=
(HANDLE(WINAPI *)(DWORD,DWORD))
GetProcAddress( hInstLib,
"CreateToolhelp32Snapshot" ) ;
lpfProcess32First=
(BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))
GetProcAddress( hInstLib, "Process32First" ) ;
lpfProcess32Next=
(BOOL(WINAPI *)(HANDLE,LPPROCESSENTRY32))
GetProcAddress( hInstLib, "Process32Next" ) ;
lpfModule32First=
(BOOL(WINAPI *)(HANDLE,LPMODULEENTRY32))
GetProcAddress( hInstLib, "Module32First" ) ;
lpfModule32Next=
(BOOL(WINAPI *)(HANDLE,LPMODULEENTRY32))
GetProcAddress( hInstLib, "Module32Next" ) ;
if( lpfProcess32Next == NULL ||
lpfProcess32First == NULL ||
lpfModule32Next == NULL ||
lpfModule32First == NULL ||
lpfCreateToolhelp32Snapshot == NULL )
{
FreeLibrary(hInstLib);
return 605;
}
// The Process32.. and Module32.. routines return names in all uppercase
// Get a handle to a Toolhelp snapshot of all the systems processes.
hSnapShot = lpfCreateToolhelp32Snapshot(
TH32CS_SNAPPROCESS, 0 ) ;
if( hSnapShot == INVALID_HANDLE_VALUE )
{
FreeLibrary(hInstLib);
return 605;
}
// Get the first process' information.
procentry.dwSize = sizeof(PROCESSENTRY32);
bResult=lpfProcess32First(hSnapShot,&procentry);
// While there are processes, keep looping and checking.
while(bResult)
{
// Get a handle to a Toolhelp snapshot of this process.
hSnapShotm = lpfCreateToolhelp32Snapshot(
TH32CS_SNAPMODULE, procentry.th32ProcessID) ;
if( hSnapShotm == INVALID_HANDLE_VALUE )
{
CloseHandle(hSnapShot);
FreeLibrary(hInstLib);
return 605;
}
// Get the module list for this process
modentry.dwSize=sizeof(MODULEENTRY32);
bResultm=lpfModule32First(hSnapShotm,&modentry);
// While there are modules, keep looping and checking
while(bResultm)
{
if(strcmp(modentry.szModule,szToFindUpper)==0)
{
// Process found
CloseHandle(hSnapShotm);
CloseHandle(hSnapShot);
FreeLibrary(hInstLib);
return 1;
}
else
{ // Look for next modules for this process
modentry.dwSize=sizeof(MODULEENTRY32);
bResultm=lpfModule32Next(hSnapShotm,&modentry);
}
}
//Keep looking
CloseHandle(hSnapShotm);
procentry.dwSize = sizeof(PROCESSENTRY32);
bResult = lpfProcess32Next(hSnapShot,&procentry);
}
CloseHandle(hSnapShot);
}
FreeLibrary(hInstLib);
return 0;
}
A: Another way of monitoring a child-process is to create a worker thread that will :
*
*call CreateProcess()
*call WaitForSingleObject() // the worker thread will now wait till the child-process finishes execution. it's possible to grab the return code (from the main() function) too.
A: The process handle will be signaled if it exits.
So the following will work (error handling removed for brevity):
BOOL IsProcessRunning(DWORD pid)
{
HANDLE process = OpenProcess(SYNCHRONIZE, FALSE, pid);
DWORD ret = WaitForSingleObject(process, 0);
CloseHandle(process);
return ret == WAIT_TIMEOUT;
}
Note that process ID's can be recycled - it's better to cache the handle that is returned from the CreateProcess call.
You can also use the threadpool API's (SetThreadpoolWait on Vista+, RegisterWaitForSingleObject on older platforms) to receive a callback when the process exits.
EDIT: I missed the "want to do something to the process" part of the original question. You can use this technique if it is ok to have potentially stale data for some small window or if you want to fail an operation without even attempting it. You will still have to handle the case where the action fails because the process has exited.
A: #include <cstdio>
#include <windows.h>
#include <tlhelp32.h>
/*!
\brief Check if a process is running
\param [in] processName Name of process to check if is running
\returns \c True if the process is running, or \c False if the process is not running
*/
bool IsProcessRunning(const wchar_t *processName)
{
bool exists = false;
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(snapshot, &entry))
while (Process32Next(snapshot, &entry))
if (!wcsicmp(entry.szExeFile, processName))
exists = true;
CloseHandle(snapshot);
return exists;
}
A: The solution provided by @user152949, as it was noted in commentaries, skips the first process and doesn't break when "exists" is set to true. Let me provide a fixed version:
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
bool IsProcessRunning(const TCHAR* const executableName) {
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
const auto snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (!Process32First(snapshot, &entry)) {
CloseHandle(snapshot);
return false;
}
do {
if (!_tcsicmp(entry.szExeFile, executableName)) {
CloseHandle(snapshot);
return true;
}
} while (Process32Next(snapshot, &entry));
CloseHandle(snapshot);
return false;
}
A: You can never check and see if a process is running, you can only check to see if a process was running at some point in the recent past. A process is an entity that is not controlled by your application and can exit at any moment in time. There is no way to guaranteed that a process will not exit in between the check to see if it's running and the corresponding action.
The best approach is to just do the action required and catch the exception that would be thrown if the process was not running.
A: call EnumProcesses() and check if the PID is in the list.
http://msdn.microsoft.com/en-us/library/ms682629%28VS.85%29.aspx
A: JaredPar is right in that you can't know if the process is running. You can only know if the process was running at the moment you checked. It might have died in the mean time.
You also have to be aware the PIDs can be recycled pretty quickly. So just because there's a process out there with your PID, it doesn't mean that it's your process.
Have the processes share a GUID. (Process 1 could generate the GUID and pass it to Process 2 on the command line.) Process 2 should create a named mutex with that GUID. When Process 1 wants to check, it can do a WaitForSingleObject on the mutex with a 0 timeout. If Process 2 is gone, the return code will tell you that the mutex was abandoned, otherwise you'll get a timeout.
A: You may find if a process (given its name or PID) is running or not by iterating over the running processes simply by taking a snapshot of running processes via CreateToolhelp32Snapshot, and by using Process32First and Process32Next calls on that snapshot.
Then you may use th32ProcessID field or szExeFile field of the resulting PROCESSENTRY32 struct depending on whether you want to search by PID or executable name. A simple implementation can be found here.
A: While writing a monitoring tool, i took a slightly different approach.
It felt a bit wasteful to spin up an extra thread just to use WaitForSingleObject or even the RegisterWaitForSingleObject (which does that for you). Since in my case i don't need to know the exact instant a process has closed, just that it indeed HAS closed.
I'm using the GetProcessTimes() instead:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms683223(v=vs.85).aspx
GetProcessTimes() will return a FILETIME struct for the process's ExitTime only if the process has actually exited. So is just a matter of checking if the ExitTime struct is populated and if the time isn't 0;
This solution SHOULD account the case where a process has been killed but it's PID was reused by another process. GetProcessTimes needs a handle to the process, not the PID. So the OS should know that the handle is to a process that was running at some point, but not any more, and give you the exit time.
Relying on the ExitCode felt dirty :/
A: This is a solution that I've used in the past. Although the example here is in VB.net - I've used this technique with c and c++. It bypasses all the issues with Process IDs & Process handles, and return codes. Windows is very faithful in releasing the mutex no matter how Process2 is terminated. I hope it is helpful to someone...
**PROCESS1 :-**
Randomize()
mutexname = "myprocess" & Mid(Format(CDbl(Long.MaxValue) * Rnd(), "00000000000000000000"), 1, 16)
hnd = CreateMutex(0, False, mutexname)
' pass this name to Process2
File.WriteAllText("mutexname.txt", mutexname)
<start Process2>
<wait for Process2 to start>
pr = WaitForSingleObject(hnd, 0)
ReleaseMutex(hnd)
If pr = WAIT_OBJECT_0 Then
<Process2 not running>
Else
<Process2 is running>
End If
...
CloseHandle(hnd)
EXIT
**PROCESS2 :-**
mutexname = File.ReadAllText("mutexname.txt")
hnd = OpenMutex(MUTEX_ALL_ACCESS Or SYNCHRONIZE, True, mutexname)
...
ReleaseMutex(hnd)
CloseHandle(hnd)
EXIT
A: char tmp[200] = "taskkill /f /im chrome.exe && \"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe\"
while (1)
{
FILE* f;
f = _popen("tasklist", "r");
char b[512];
bzero(b, 512);
while (fgets(b, 512, f) != NULL)
{
if (strncmp(b, "chrome.exe", 8) == 0)
{
printf("Chrome running!\n");
system(tmp);
}
else
{
printf("Chrome NOT running!\n");
}
}
Sleep(1000);
}
| |
doc_23528792
|
made the directories as below .
in folder named website and in a subfoder named templates make a file init_.py and outside the website folder ,main.py is there
code in init.py
from flask import Flask
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY']='madkrish'
return app
code in main.py
from website import create_app
app = create_app()
if __name__== '__main__':
app.run(debug=True)
When i run the main function the following errors comes:
No Module named 'website'
given above
Can someone please correct me where i am wrong i need to go further in the tutorial to the next step.
A: From your folder structure, you need to import from templates, so:
from templates import create_app
It should works.
VSCode will still marks it as error, you need to configure it to inlcude your templates folder in the Python Path
| |
doc_23528793
|
I have two pages in the left A and B panel and two pages C and D in the right panel.
Initially I render page A and C in left and right panel respectively. Now on click on a link I want to change the left panel from A to B and in right panel C to D
Change is not working completely its only changing the left panel not the page in right panel where the above anchor is placed.
Note that the link or button above is present in the right pane always. If I use
A: do a .refresh() after link click/anything that triggers the change in the splitview.
A: there is a context loading option in splitview. Why not use this?
I can't find the sample page anymore, but I'm using the same logic in my script, so... if you can't find it, try something like this:
1) give your links context attributes:
<a href="#some" data-panel="menu" data-context="#otherPage" data-context-panel="main">click me</a>
2) Listen for clicks on these context links like so:
$(document).bind( "click", function( event ) {
console.log("click registered");
var link = $( self.findClosestLink(event.target) );
if ( !link || event.which > 1) {
return;
}
console.log( link );
console.log( link.jqmData('context') );
// context routine fires with context links
if ( link.length === 1 && link.jqmData('context') ) {
// fire your context function, RENAME THIS
console.log("firing context routine");
self.context( link );
}
3) Put a context function somewhere:
context: function( object ) {
var self = this,
$context = object,
$targetPanelID = $context.jqmData('context-panel');
console.log("contextpage="+$context.href+" contextPanel="+targetPanelID);
// make sure the pageContainer is correctly set for the 2nd transition
$.mobile.pageContainer = $('div:jqmData(panel="'+$targetPanelID+'")');
// context changePage
$.mobile.changePage( $( $context.jqmData('context') ), { transition:'slide', changeHash:true, fromHashChange: false, pageContainer: $.mobile.pageContainer });
};
4) Add the JQM findclosestLink function (I forgot)
findClosestLink: function (ele) {
var self = this;
while (ele){
if (ele.nodeName.toLowerCase() == "a"){
break;
}
ele = ele.parentNode;
return ele;
}
Your link will fire the first changePage, your context function will fire the second changePage. Depending on where you use this, your context changePage call will also trigger another hashChange event, which JQM may not block (every changePage also fires a hashChange which is blocked by JQM using ignoreNextHashChange - check the source).
So you may have to do something like this after making your second call to ensure the hashChange is blocked:
$.mobile.ignoreNextHashChange = true;
The whole thing is working inside my multiview plugin, BUT the plugin is not finished, buggy and I haven't had the time to work on it lately. Context is working though, so you might just pull it out and use it as you need.
Cheers!
| |
doc_23528794
|
a b
0 3.0 10.0
1 2.0 9.0
2 NaN 8.0
For each row, I need to drop (and replace with NaN) all values, excluding the first non-null one.
This is the expected output:
a b
0 3.0 NaN
1 2.0 NaN
2 NaN 8.0
I know that using the justify function I can identify the first n non-null values, but I need to keep the same structure of the original dataframe.
A: One way to go, would be:
import pandas as pd
data = {'a': {0: 3.0, 1: 2.0, 2: None}, 'b': {0: 10.0, 1: 9.0, 2: 8.0}}
df = pd.DataFrame(data)
def keep_first_valid(x):
first_valid = x.first_valid_index()
return x.mask(x.index!=first_valid)
df = df.apply(lambda x: keep_first_valid(x), axis=1)
df
a b
0 3.0 NaN
1 2.0 NaN
2 NaN 8.0
*
*So, the first x passed to the function would consist of pd.Series([3.0, 10.0],index=['a','b']).
*Inside the function first_valid = x.first_valid_index() will store 'a'; see df.first_valid_index.
*Finally, we apply s.mask to get pd.Series([3.0, None],index=['a','b']), which we assign back to the df.
A: try this:
f = df.copy()
f[:] = f.columns
fv_idx = df.apply(pd.Series.first_valid_index, axis=1).values[:, None]
res = df.where(f == fv_idx)
print(res)
>>>
a b
0 3.0 NaN
1 2.0 NaN
2 NaN 8.0
| |
doc_23528795
|
*
*Website link
*Image of that slider:
How can I let my script slide that button to the right?
I've tried with:
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def sign_in():
driver.get("https://login.aliexpress.com/")
wait.until(EC.frame_to_be_available_and_switch_to_it(wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#alibaba-login-box")))))
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "input#fm-login-id"))).send_keys("someEmail")
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "input#fm-login-password"))).send_keys("somePassword")
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "button[class$='password-login']"))).click()
#the following line is for handling the slider but it doesn't do anything
item = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, ".nc_wrapper .btn_slide")))
ActionChains(driver).move_to_element(item).perform()
if __name__ == '__main__':
driver = webdriver.Chrome()
wait = WebDriverWait(driver,10)
sign_in()
Html elements connected to that slider:
<div id="nc_1_n1t" class="nc_scale">
<div id="nc_1__bg" class="nc_bg" style="width: 0px;"></div>
<span id="nc_1_n1z" class="nc_iconfont btn_slide" data-spm-anchor-id="0.0.0.i1.3f9579f4qCwuHp" style="left: 0px;"></span>
<div id="nc_1__scale_text" class="scale_text slidetounlock"><span class="nc-lang-cnt" data-nc-lang="_startTEXT">Please slide to verify</span></div>
<div id="nc_1_clickCaptcha" class="clickCaptcha" style="top: -118px; height: 235px;">
<div class="clickCaptcha_text">
<b id="nc_1__captcha_text" class="nc_captch_text"></b>
<i id="nc_1__btn_2" class="nc_iconfont nc_btn_2 btn_refresh"></i>
</div>
<div class="clickCaptcha_img"></div>
<div class="clickCaptcha_btn"></div>
</div>
<div id="nc_1_imgCaptcha" class="imgCaptcha" style="top: -118px; min-height: 290px; height: 189px;">
<div class="imgCaptcha_text"><input id="nc_1_captcha_input" maxlength="6" type="text" style="ime-mode:disabled"></div>
<div class="imgCaptcha_img" id="nc_1__imgCaptcha_img"></div>
<i id="nc_1__btn_1" class="nc_iconfont nc_btn_1 btn_refresh" onclick="document.getElementById('nc_1__imgCaptcha_img').children[0].click()"></i>
<div class="imgCaptcha_btn">
<div id="nc_1__captcha_img_text" class="nc_captcha_img_text"></div>
<div id="nc_1_scale_submit" class="nc_scale_submit"></div>
</div>
</div>
<div id="nc_1_cc" class="nc-cc"></div>
<i id="nc_1__voicebtn" tabindex="0" role="button" class="nc_voicebtn nc_iconfont" style="display:none"></i>
<b id="nc_1__helpbtn" class="nc_helpbtn"><span class="nc-lang-cnt" data-nc-lang="_learning">help</span></b>
</div>
A: I'm unable to get the slider to display on the website linked in the question, so I have provided a solution using another site that has a slider element (I'm assuming the functionality is similar to the one on the aliexpress website).
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
# Instantiate objects
driver = webdriver.Chrome()
actions = ActionChains(driver)
# Load page and fill in input elements
driver.get("http://kthornbloom.com/slidetosubmit/")
driver.find_element(By.NAME, "name").send_keys("Fred")
driver.find_element(By.NAME, "email").send_keys("fred@example.com")
# Find slider elements
slider_container = driver.find_element(By.CSS_SELECTOR, ".slide-submit")
slider = driver.find_element(By.CSS_SELECTOR, ".slide-submit-thumb")
# Perform sliding action
actions.move_to_element(slider).click_and_hold().move_by_offset(slider_container.size['width'], 0).release().perform()
# Browser intentionally left open so that you can see what happened when the test was run!
The key part here, is the Perform sliding action line. We have to identify two specific elements:
*
*The element that we are going to slide
*The container that holds this element
Once we have found both of these elements, we use the actions class to click and hold the element we need to slide and then we slide it the width of the containing element along the x axis (as shown using slider_container.size['width']), without changing the y axis.
This should fix your sliding problem, however you will have another problem, you need to work out if the slider was displayed, or you were logged into the website. To do that you are going to need an Expected condition that checks for the existence of 2 elements:
*
*The slider.
*An element you would expect to see when you have successfully logged in.
If the element you would expect to see when you log in is shown, you don't need to do anything. If the slider is shown, you will need to perform the above logic to slide the bar across.
*Edit*
To improve on this a bit more you can put the sliding code into an ExpectedCondition like so:
class wait_for_element_while_verifying_slider(object):
def __init__(self, locator, slider_container_locator, slider_locator):
self.locator = locator
self.slider_container_locator = slider_container_locator
self.slider_locator = slider_locator
def __call__(self, _driver):
try:
return _driver.find_element(*self.locator)
except (NoSuchElementException, StaleElementReferenceException):
container = _driver.find_elements(*self.slider_container_locator)
slider = _driver.find_elements(*self.slider_locator)
if len(container) > 0 and len(slider) > 0:
actions = ActionChains(_driver)
actions.move_to_element(slider[0]).click_and_hold().move_by_offset(container[0].size['width'], 0).release().perform()
return False
This will search for an element that you expect to be shown when you log in. If the element that you would expect to see when you have successfully logged in is not shown, it will then try and locate the slider elements and interact with them to process the slide verification. Note that once it tries to perform the slide verification the Expected Condition will return False which will force it to check to see if the expected logged in element is displayed again.
You can use it in your code like this:
# Instantiate objects
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
# Load page and fill in input elements
driver.get("http://kthornbloom.com/slidetosubmit/")
driver.find_element(By.NAME, "name").send_keys("Fred")
driver.find_element(By.NAME, "email").send_keys("fred@example.com")
# Define slider elements and element that will be shown when you successfully log in
SLIDER_CONTAINER = (By.CSS_SELECTOR, ".slide-submit")
SLIDER = (By.CSS_SELECTOR, ".slide-submit-thumb")
ELEMENT_TO_FIND = (By.XPATH, "//div[.=\"Looks Like You're Human!\"]")
# Invoke the explicit wait that will deal with the slider if it is displayed
wait.until(wait_for_element_while_verifying_slider(ELEMENT_TO_FIND, SLIDER_CONTAINER, SLIDER))
The example above uses the same example website as above. To make it timeout you can change ELEMENT_TO_FIND to something that doesn't exist. To make it pass without sliding you can modify ELEMENT_TO_FIND to be:
ELEMENT_TO_FIND = (By.XPATH, "//div[.=\"Slide To Submit\"]")
Using the code you have provided in your comment I would expect the following to work on the aliexpress website:
# Define slider elements and element that will be shown when you successfully log in
SLIDER_CONTAINER = (By.CSS_SELECTOR, ".nc-lang-cnt")
SLIDER = (By.CSS_SELECTOR, ".nc_wrapper .btn_slide")
ELEMENT_TO_FIND = (By.ID, "search-key")
# Invoke the explicit wait that will deal with the slider if it is displayed
wait.until(wait_for_element_while_verifying_slider(ELEMENT_TO_FIND, SLIDER_CONTAINER, SLIDER))
A: Try using Actions Below is c# code for reference
//following code will click and hold the slider
string Xpath=""; //set xpath for desired element to be click and hold
Actions clickHold = new Actions(driver);
IWebElement element = driver.FindElement(By.XPath(Xpath));
clickHold.ClickAndHold(element).Perform();
once you have held on slider try to move it to the desired offset value
int x = 100;
int y = 100;
Actions moveOffset = new Actions(driver);
moveOffset.MoveByOffset(x,y).Perform(); //set your suitable (x,y) offset value
A: The sample code (in java) for slider operation from left to right is below.
Actions slider=new Actions(driver);
slider.clickAndHold("xpath of slider");
slider.movebyoffset(x,y).build.perform();
in place of 'x' &'y' you can give actual offset value as per your application.
| |
doc_23528796
|
I have found jQuery examples online but I can't find any for Vue.js. The jQuery ones deal with dynamically added grids rather than one specified as HTML format.
I know that this is possible as I have done it before but unfortunately I can't remember how, and that code is no longer available.
For example:
<kendo-grid :dataBound="dataBound" :selectable="'multiple row'" height="580" id="dataGrid" ref="grid" :resizable="true" :data-source="dataContent" :filterable="true" :sortable="true" :change="onChange" @filterChange="saveFilter()">
<kendo-grid-column :field="'Code'" :title="'Code'" :width="150" :attributes="{ 'class': 'text-nowrap'}"></kendo-grid-column>
<kendo-grid-column :field="'Name'" :title="'Name'" :width="200" :attributes="{ 'class': 'text-nowrap'}"></kendo-grid-column>
<kendo-grid-column :field="'Balance'" :title="'Balance'" :width="150" format="{0:c}" :aggregates="['sum']" :footer-template="balanceFooterTemplate" :attributes="{ 'class': 'currency-right red-if-minus' }" :header-attributes="{ 'class': 'header-right-align'}"></kendo-grid-column>
</kendo-grid>
What code do I need to read the filter (if any) and re-apply it?
Test saveFilter event:
saveFilter: function () {
console.log('saveFilter called');
}
A: I just found a Vue example of saving/loading grid state.
It uses buttons to save and load state of the grid, however, I would think you could save your state on each filter change.
Code:
<template>
<kendo-datasource ref="datasource1"
:type="'odata'"
:transport-read-url="'https://demos.telerik.com/kendo-ui/service/Northwind.svc/Customers'"
:page-size='20'>
</kendo-datasource>
<a href="#" class="k-button" v-on:click="saveState">Save State</a>
<a href="#" class="k-button" v-on:click="loadState">Load State</a>
<kendo-grid ref="grid"
:height="600"
:data-source-ref="'datasource1'"
:groupable="true"
:sortable="true"
:reorderable="true"
:resizable="true"
:column-menu="true"
:filterable-mode="'row'"
:pageable-refresh="true"
:pageable-page-sizes="true"
:pageable-button-count="5">
<kendo-grid-column :field="'ContactName'"
:title="'Contact Name'"
:width="250"
:locked="true"></kendo-grid-column>
<kendo-grid-column :field="'ContactTitle'"
:title="'Contact Title'"
:width="350"></kendo-grid-column>
<kendo-grid-column :field="'CompanyName'"
:title="'Company Name'"
:width="350"></kendo-grid-column>
<kendo-grid-column :field="'Country'"
:width="450"></kendo-grid-column>
</kendo-grid>
</template>
<script>
import { Grid, GridColumn } from '@progress/kendo-grid-vue-wrapper';
import { KendoDataSource } from '@progress/kendo-datasource-vue-wrapper';
export default {
components: {
'kendo-grid': Grid,
'kendo-grid-column': GridColumn,
'kendo-datasource': KendoDataSource
},
data () {
return {
schemaModelFields: {
UnitsInStock: { type: "number" },
ProductName: { type: "string" },
UnitPrice: { type: "number" },
UnitsOnOrder: { type: "number" },
UnitsInStock: { type: "number" }
},
groupDefinition: {
field: "UnitsInStock",
aggregates: [
{ field: "ProductName", aggregate: "count" },
{ field: "UnitPrice", aggregate: "sum"},
{ field: "UnitsOnOrder", aggregate: "average" },
{ field: "UnitsInStock", aggregate: "count" }
]
},
aggregateDefinition: [
{ field: "ProductName", aggregate: "count" },
{ field: "UnitPrice", aggregate: "sum" },
{ field: "UnitsOnOrder", aggregate: "average" },
{ field: "UnitsInStock", aggregate: "min" },
{ field: "UnitsInStock", aggregate: "max" }
]
}
},
methods: {
saveState: function(e) {
e.preventDefault();
var grid = this.$refs.grid.kendoWidget();
localStorage["kendo-grid-options"] = kendo.stringify(grid.getOptions());
},
loadState: function(e) {
e.preventDefault();
var options = localStorage["kendo-grid-options"];
var grid = this.$refs.grid.kendoWidget();
if (options) {
grid.setOptions(JSON.parse(options));
}
}
}
}
</script>
| |
doc_23528797
|
I tried this as input
<input type="checkbox" name="all" value="1"
onclick='
<%
xox=0
while xox<count
xox=xox+1
%>
Radio1_<%=xox%>.checked=true;
<%wend%>
'
>ApplyAll
<td class="style13" style="width: 75">
<input class="style15" name="Radio1_<%=count%>" type="radio" value="0"
onclick='
AdminDet<%=count%>.disabled=true;
AdminDet<%=count%>.value="";
if (Radio1_<%=count%>.checked==true)
Radio1_<%=count%>.checked=false;
else
Radio1_<%=count%>.checked=true;
'><span class="style16">Accept</span></td>
A: <%
I= record count of total radio
%>
<FORM class=niceform method="GET" action="anketilet.asp" name="anketform" onsubmit="return z();">
<script type="text/javascript">
function z()
{
var de='<%=I%>';
var z=0;
for (i=0;i<anketform.elements.length ; i++ ) {
if (anketform.elements[i].type == 'radio'/* && anketform.elements[i].checked*/)
{
if(anketform.elements[i].checked)
{
z++;
}
}
}
if (z!=de)
{
alert("Lütfen cevapları eksiksiz doldurduğunuzdan emin olunuz!...");
return (false);
}
else return (true);
}
</script>
</table>
</fieldset><br>
<fieldset class="action" style="width: 800px;">
<input type="submit" name="submit" id="submit" value="GÖNDER">
</fieldset></FORM>
| |
doc_23528798
|
this is done by the following code:
NSArray* windows = [[UIApplication sharedApplication] windows];
int count = [windows count];
UIWindow* topWindow = [windows objectAtIndex:count - 1];
[topWindow addSubview:_storeView];
When I'm purchasing a product, in some cases (not sure exactly when and why) the in app purchase alerts, where the user needs to enter his app id credentials and approve the transaction are covered by my view and are not visible to the user.
Only when i dismiss my view i can see them and completing the purchase flow.
How can i make sure that those alerts will appear on top of all other views. and why is it not consistently, on some cases it is visible to the user and on some cases it isn't…
Appreciate any help.
A: Why you are adding your view directly to the window ? i advise you to read the Apple documentation UIViewController programming guide.
The problem can be this lines of code :
NSArray* windows = [[UIApplication sharedApplication] windows];
int count = [windows count];
UIWindow* topWindow = [windows objectAtIndex:count - 1];
[topWindow addSubview:_storeView];
What is the root controller of your application ? are you using a container controller ( UINavigationController, UITabBarController,...). can you please show your AppDelegate code ?
A: found a solution.
instead of using current window I'm creating a new window which is floating above other UI elements (like the system keyboard).
I'm setting its window level property to UIWindowLevelStatusBar for displaying above status bar but underneath uialertviews
| |
doc_23528799
|
enum Action: String {
case doThing
case doOtherThing
}
This enum is used this way:
func run(action: Action, block: () -> Void)
Now, I unit test the run method so I need to pass an Action this way:
func testActionRun() {
let expect = expectation(description: #function)
let sut = ActionRunner()
sut.run(action: .doThing) {
expect.fulfill()
// Assert something
}
waitForExpectations(timeout: 0.1, handler: nil)
}
As I need to test other situations on ActionRunner, I ended with a lot of .doThing spread over the whole test suite.
The problem is: if I make a change in production code and change case doThing to case doThatThing now all my test suite fails because there is no a case doThing.
The perfect thing would be to declare a dummy case in test code to allow something like
sut.run(action: .dummyAction) {
}
but enum does not allow that as it doesn't allows inheritance nor a extension to add a case.
The first option that came to my mind was to convert Action into a protocol, but that change is unnecessary in production and its only purpose is to accomplish something in test code.
So, is it there another option to achieve this?
A: The question of how to avoid coupling when using enums is a tricky one. I bumped into that myself a few times with no solid answer :/
One point you raise is the one of using a protocol, and that feels unnecessary in production. I sort of agree with that, but most time it's the necessary evil.
In the example you showed though I think maybe a tweak in the design might solve part of the problem.
In particular when looking at this code
func run(action: Action, block: () -> Void) {
// ...
}
func testActionRun() {
let expect = expectation(description: #function)
let sut = ActionRunner()
sut.run(action: .doThing) {
expect.fulfill()
// Assert something
}
waitForExpectations(timeout: 0.1, handler: nil)
}
What comes to mind to me is that your Action specifies a certain behaviour. That is when you test the run method passing .doThing you expect a different behaviour than when passing .doOtherThing.
If that's right, is there any reason why you need to pass the action enum instance and an action block to the run function?
You could separate the code that defines the behaviour from the one performs the actual action even more that what you've done already. For example:
protocol Actionable {
var action: () -> () { get }
}
enum Action: Actionable {
case doThing
case doOtherThing
var action {
switch self {
case .doThing: return ...
case .doOtherThing: return ...
}
}
class ActionRunner {
func run(actionable: Actionable) {
actionable.action()
}
}
func testActionRun() {
let expect = expectation(description: #function)
let sut = ActionRunner()
sut.run(actionable: FakeActionable()) {
expectation.fulfill()
}
waitForExpectations(timeout: 0.1, handler: nil)
}
class FakeActionable: Actionable {
let action = { }
}
func testDoThing() {
let sut = Action.doThing
sut.action()
// XCTAssert for the expected effect of the action
}
Note: I haven't actually compiled that code, so bear with me if it has some mistakes. It should give the idea though.
This way you have ActionRunner which only purpose is to properly run a given Actionable, and the Action enum which only purpose is to describe what different actions should do.
This example code is rather restrict in what it can do, only run () -> () actions, but you could build on top of it to achieve more advanced behaviours.
A: If you change your production code you have to change your test code too in order to test those new changes.
Maybe you can set the value on an Action variable in the setUp func of your XCTestCase class
import XCTest
class SharingKitTests: XCTestCase {
var theAction: Action!
override func setUp() {
super.setUp()
self.theAction = .doThing
}
}
Then you will be able to use this theAction var in all your test methods, and if you need to change the value you only need to change it in one place.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.