text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Can a Lipschitz continuous function be linear almost everywhere but not linear everywhere?
Can a Lipschitz continuous function be linear almost everywhere but not linear everywhere?
(:sorry for ambiguity) The almost everywhere here is defined as:
Let $f:\mathbb R^k\to\mathbb R$. $\nabla f(x)=v$ almost surely where $v$ is a constant.
That is $\nexists$ open set $U\subseteq dom(x)$ s.t. $\nabla f(x)\neq v \ \forall x\in U.$
My intuition is "no" but I don't know how to prove it. It is not a homework.
A:
Let $S\subset [0,1]$ such that $S$ is closed and nowhere dense in $\Bbb R$ and such that the Lebesgue measure $m( S)$ is positive. (E.g. $S$ can be a "fat Cantor set".) Let $f(x)=x$ for $x<0$ and let $f(x)=\int_0^x(1-\chi_S(t))dt$ for $x\geq 0.$ So for $x\geq 0$ we have $f(x)=m([0,x] \setminus S).$
| {
"pile_set_name": "StackExchange"
} |
Q:
(.OFX/.QFX/.QIF/.QBO/.OFC) file converter
We are building an application that reads files (.OFX/.QFX/.QIF/.QBO/.OFC) and place the data read in the file in a grid.
Does anyone know of a utility or 3rd party tool to convert the file types (.OFX/.QFX/.QIF/.QBO/.OFC) to something more conventional like XML or CSV. Any help will be greatly appreciated!
We are using c#/ASP.NET for developing out web application. The app is hosted on a Windows server if it makes any difference...
A:
fixofx was open sourced from Wesabe. It converts various types of financial files including OFX 1.0 and QIF files to OFX 2.0, which is an XML-based format and so is easily parsed.
A:
I wrote a Python script ofx2csv.py that converts OFX/QFX files to CSV, if anyone needs to do this programmatically.
A:
I found a solution to this problem.
Bank2CSV Pro converts various bank, credit card and investment files (QIF, OFX, QFX, QBO, OFC) into CSV format (the file will become a table like a regular spreadsheet with rows as transactions. It supports command line mode:
bank2csv_pro.exe input.ofx output.csv
See http://www.propersoft.net/
| {
"pile_set_name": "StackExchange"
} |
Q:
pdo_mysql unable to create mysqld.sock file
I'm adding PHP (php-fpm) to an existing Nginx Ubuntu 10.04 server and can't get pdo_mysql to work. I'm trying to connect to a MySQL server someplace else, but all the Googling answers I found are in regards to MySQL not working on the local server, so I'm not sure how to proceed.
I don't have mysqld installed, so I'm not sure if I need it, or if there's a way around this? Also I'm wondering if it can't create mysqld.sock because there is mysql user on the server?
Error:
SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) Fatal error: Call to a member function query() on a non-object
My PHP connection code:
$this->PDO = new PDO('mysql:host=' . $this->config->getValue('db_host') .
';dbname=' . $this->config->getValue('db_name'),
$this->config->getValue('db_user'),
$this->config->getValue('db_pass'));
My Query line it fails on:
$PDOStatement = $this->PDO->query($query);
Appreciate any help, thanks.
A:
Couple of things you should check
D you have mysql-client installed? if you are connecting to remote machine. you don't need mysql running on your box but I think you will still need the client.
Make sure the host value is correct. Double & triple check
Lastly, Try connecting manually using command line, by the following command.
$ mysql -u <INSERT_USER_HERE> -p -h <INSERT_IP_OF_REMOTE_MACHINE_HERE> <INSERT_DB_NAME_HERE>
If it does not work. come back with exact error message.
| {
"pile_set_name": "StackExchange"
} |
Q:
Windows batch file to minimize all open windows
I would like to have a batch file in Windows where when it is executed it minimizes all the open windows on the desktop?
Essentially, I would like this batch file to clear the screen clutter so when I launch an app it is the 'only window' on the desktop.
Although I've seen 'Show Desktop.scf' in several posts, I can't seem to incorporate that into a batch file so it runs - I must be missing something so any assistance would be much appreciated.
I have a mixed Win7 and Win10 environment.
Thanks in advance.
A:
The easiest method would be to not use a .cmd or .bat file, but create a .vbs file instead.
Writing that script for this task is fairly simple and can be run as well by a simple double-click too.
But a .vbs can do much more in case you want to actually go that route in the future.
Here's an example script that minimizes all windows, then runs a Command Prompt.
set oShellApp = CreateObject("Shell.Application")
oShellApp.MinimizeAll
oShellApp.ShellExecute "cmd.exe"
See also: VBScript Shell.Application
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does passing a KinectJS object from Client to NodeJS through a function cause loss of class?
I'm using KinectJS to create a Kinect.Rect object. I'm trying to pass this object from the client to the server. On the client side (just before passing as an argument the output of the object in console is:
box_284
Kinetic.Rect
alpha: 1
centerOffset: Object
className: "Shape"
drag: Object
drawFunc: function (){
eventListeners: Object
fill: "00D2FF"
height: 25
isListening: true
name: undefined
rotation: 0
scale: Object
stroke: "black"
strokeWidth: 4
visible: true
width: 25
x: 100
y: 100
__proto__: Object
After send it is:
box
Object
alpha: 1
centerOffset: Object
className: "Shape"
drag: Object
eventListeners: Object
fill: "00D2FF"
height: 25
isListening: true
rotation: 0
scale: Object
stroke: "black"
strokeWidth: 4
visible: true
width: 25
x: 100
y: 100
__proto__: Object
The KinectJS library is available to the client, is this an issue of 'deep cloning' and how objects get passed? Is it a problem of not having the library available to the server? Not sure what to think of this.. fairly new to Javascript.
===============
Update
I'm sending the argument as follows:
socket.emit('add_box', eval("box_" + id));
Where the object is something like: box_523
A:
First off, I'd recommend you have your objects accessible through an array or dictionary of some sort instead of using eval("box_" + id). Putting aside any potential security concerns, indexing into an array will give you much better performance than eval.
To get to the heart of your question, the issue is that socket.emit serializes and transfers data. Since drawFunc is a function and not data, it does not get transferred.
If you think about it, this is fairly straightforward behavior. What would the expected behavior be if you moved a function across the wire? Where would it execute? Would you transfer the actual JavaScript and then eval it on the server?
While these are all questions you could potentially answer and develop your own solution for, it's not something that's available out of the box anywhere.
That said, you might want to look into function calling with nowjs. It might fit your requirements. But again, it doesn't transfer any code across the wire:
Note: Code is only ever executed on the side on which it is created,
this means the body of the function isn't actually being transferred
from client to server or server to client, rather there is just a shim
for the remote function call when it is synced. This is hugely
important for security as it means there is never arbitrary code
execution in NowJS
| {
"pile_set_name": "StackExchange"
} |
Q:
Does an uppercase property auto-create a lowercase private property in C#?
Take this code:
public int Foo {get;set;}
As opposed to this more complete manually written code:
private int x;
public int X
{
get { return x; }
set { x = value; }
}
In the first example, does the compiler automatically create a private foo property?
I am not sure if this convention I have seen of having a lowercase private property masked by a public-facing uppercase one is just that, convention, or if it's actually part of the language/compiler, and you can either write it out or let it be done for you.
A:
Why not just have a look what's going on?
public class Test {
// private int myProp;
public int MyProp {
get;
set;
}
}
...
string report = String.Join(Environment.NewLine, typeof(Test)
.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
.Select(field => field.Name));
Console.Write(report);
And you'll get quite a weird name
<MyProp>k__BackingField
however this strange backing field name ensures that there'll be no name conflict (you can't declare any field, property, method etc. starting with <).
Edit: if you uncomment // private int myProp; line you'll have
myProp
<MyProp>k__BackingField
please, notice that myProp is not a backing field for the MyProp property.
A:
The casing has nothing to do with it.
Writing a property like below
public int x { get; set; }
will always create and use an anonymous private field which it manipulates via get/set.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Mock FileSystem function
I do not know how to mock the section where I'm changing the file's owner from line Path path = newFile.toPath(); to the end.
Here's my function :
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String uploadEndpoint(@RequestParam("file") MultipartFile file,
@RequestParam("usernameSession") String usernameSession,
@RequestHeader("current-folder") String folder) throws IOException {
String[] pathArray = file.getOriginalFilename().split("[\\\\\\/]");
String originalName = pathArray[pathArray.length-1];
LOGGER.info("Upload triggerred with : {} , filename : {}", originalName, file.getName());
String workingDir = URLDecoder.decode(folder.replace("!", "."),
StandardCharsets.UTF_8.name())
.replace("|", File.separator);
LOGGER.info("The file will be moved to : {}", workingDir);
File newFile = new File(workingDir + File.separator + originalName);
//UserPrincipal owner = Files.getOwner(newFile.toPath());
file.transferTo(newFile);
Path path = newFile.toPath();
FileOwnerAttributeView foav = Files.getFileAttributeView(path, FileOwnerAttributeView.class);
UserPrincipal owner = foav.getOwner();
System.out.format("Original owner of %s is %s%n", path, owner.getName());
FileSystem fs = FileSystems.getDefault();
UserPrincipalLookupService upls = fs.getUserPrincipalLookupService();
UserPrincipal newOwner = upls.lookupPrincipalByName(usernameSession);
foav.setOwner(newOwner);
UserPrincipal changedOwner = foav.getOwner();
System.out.format("New owner of %s is %s%n", path,
changedOwner.getName());
return "ok";
}
And here's the test :
@Test
public void uploadEndpointTest() throws Exception {
PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(file);
Mockito.when(multipartFile.getOriginalFilename()).thenReturn("src/test/resources/download/test.txt");
assertEquals("ok", fileExplorerController.uploadEndpoint(multipartFile, "userName", "src/test/resources/download"));
}
I got an exception because "userName" is not a user. I'd like to mock the call where it looks for a match in windows's users. It works when I set my window's username instead of "userName", but I can't let my window's username.
I tried to mock fs.getUserPrincipalLookupService(); and upls.lookupPrincipalByName(usernameSession); but I do not know what to return to mock the call.
Many thanks !
A:
First of all, you should consider the Single Responsibility principle and further dissect your code.
Meaning: create a helper class that abstracts all these low level file system accesses for you. Then you provide a mocked instance of that helper class here, and you simply ensure that the helper method gets called with the expected parameters. That will make your service method uploadEndpoint() much easier to test.
And then, your new helper class could simply expect a File object. And that enables you to pass a mocked File object to it, and all of a sudden you are in control of what thatMockedFileObject.newPath() will return.
In other words: your first goal should be to write code that doesn't make use of static or new() in a way that prevents simple mocking using Mockito. Whenever you encounter situations where you think "I need PowerMock(ito) to test my production code", then the very first impulse should be: "I should avoid that, and improve my design".
Same for FileSystem fs = FileSystems.getDefault(); ... instead of trying to get into the "mock that static call business", you make sure that your helper classes accept some FileSystem instance. And all of a sudden you can pass a simple Mockito mock object, and you are in full control over it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Not sure on Left Join, Outer Join, Unions or Minus?
Current work requires my to have a complex level of SQL syntax including these examples.
What in short is a left Join and where would you use it?
A:
What ever you have written is a JOIN clause that is used to combine rows from two or more tables, based on a related column between them.
Including outer join or left join depends on the table structure and the requirement to pull data from those tables.
IF you are looking for what is left join ,
Left join returns everything from the left table and the matching records from the right table and if there is no match in right table the result is null for the right table
Let us know what are you looking for
| {
"pile_set_name": "StackExchange"
} |
Q:
Theorem $8.12$ Apostol's Analytic Number Theory?
The below texts are from the book Introduction to Analytic Number Theory by Apostol:
Suppose $k=7$. Then for $n=7$, $q= \gcd(7,7)=7>1$. So for any $a<7$, $a \equiv 1 \mod 1$ holds since $a-1$ is a multiple of $1$ for any $a$. But $\chi(a) \ne 1$ for any $a>1$ as the following table shows:
So how the theorem is true?
Added; The following is the proof of the above Theorem. I can't find any mistake in it but still don't know how/why $\chi(a)=1$ is inconsistent with the values for $\chi_i(n)$'s.
A:
In the case of your supposed counterexample $n=k=7$, if $\chi$ is the trivial character, then certainly $\chi(a)=1$ for all $a=1,\dots,6$, and if $\chi$ is a nontrivial character, then we have
$$
G(n,\chi)=\sum_{m=0}^6\chi(m)e^{2\pi i 7m/7}=\sum_{m=1}^6\chi(m)=0,
$$
so the hypothesis that $G(n,\chi)\neq 0$ does not hold, and thus the theorem does not apply.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to position a component in the bottom center of a div without knowing its size in Css
which is the style to apply on a div to make component (button) centered in the botton without knowing the size of the remaining space that will take the div and the size of the button because this style will be generic.
I used this style but it didn't work for me:
<div location="buttonLayout" style="display:flex; justify-content:center; align-items:flex-end ;"></div>
The button is centered but not placed in the bottom of the remainig space of the parent div.
A:
You could use absolute positioning to get button at the bottom middle:
.parent {
background: gold;
position: relative;
width: 300px;
height: 400px;
box-sizing: border-box;
padding-bottom: 48px; // Padding + button height
}
.parent button {
background: grey;
border: none;
height: 32px;
color: #fff;
position: absolute;
bottom: 8px;
left: 50%;
transform: translateX(-50%);
}
<div class="parent">
<button>Button any size</button>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
No Certificates Found on Chrome Android with Comodo Positive SSL and IIS
For software testing reason, I have registered a domain name, set its A record to point to 192.168.1.30 (local PC on my network).
I have installed Comodo Positive SSL for this domain on IIS on Windows 10 on this IP.
I can access mydomain.com under SSL from any external PC browser, within my interal network (I only care for my internal network). The SSL chain is as follows:
However, when I navigate from an Android's Chrome browser, I am getting "No Certificates Found":
If I hit cancel, the page loads as expected with green padlock, and the certificate info is as follows:
The other problem that I am having which I think is connected to this problem is that I have a native Android app that is trying to connect to the website, it is working on port 80 but failing connection on SSL (port 443).
I have tried accessing the domain on SSL from an iPhone but connection times out but it is connecting fine on non-secure.
My questions are:
1 - What is the cause of this problem?
2 - How can I solve it? Please note that I don't want to solve it for a particular Android (I probably could solve this by installing the certificate manually), I want to solve it to all potential users.
I tried navigating to another website ( https://lifetanstic.co.ke/ ) that uses the same certificate chain, I wasn't asked to install any certificate, the padlock appears and the certificate details are the same. So, everything worked fine for that site.
Please note that my host name is pointing to an IP in my network, which means it is only accessible from my local network (and the Android is on my local network). So, could that be a factor to this problem?
A:
It appears that you enabled "Require Client Certificate" option in IIS.
Open IIS Manager, select your website, click SSL Settings and switch radiobutton to "Ignore":
| {
"pile_set_name": "StackExchange"
} |
Q:
LibGDX Animation doesn't work with >6 frames
I have a file called spritesheet.png, which has 7 frames of my sprite lined up side by side.
I am using this code:
TextureRegion[] reg = TextureRegion.split(new Texture("spritesheet.png"), 677, 1503)[0];
To get my TextureRegion array, and to start my animation:
animation = new Animation(1/12f, reg);
To render it, I do:
batch.begin();
batch.draw(animation.getKeyFrame(elapsedTime, true), 0, 0);
batch.end();
However, this just renders a black box.
Although, when I change my spritesheet.png file to only have 6 frames side by side, the animation works fine, and my sprite is shown.
How do I animate my sprite properly with more than 6 frames?
A:
You are probably exceeding the maximum supported texture size for the device you're running on. If you intend to support Android, your Texture dimensions shouldn't be bigger than 2048 to support the vast majority of devices. For desktop, I think 4096 is safe.
| {
"pile_set_name": "StackExchange"
} |
Q:
Spring Boot Kafka: Consume same message with all instances for specific topic
I have a spring boot application (let's say it's called app-1) that is connected to a kafka cluster and that consumes from a specific topic, let's say the topic is called "foo". Topic foo always receives a message when another application (let's say it's called app-2) has imported a new foo-item into the database.
The topic is primarily meant to be used in a third application (let's say it's called app-3) which sends out some e-Mail notification to people that may be interested in this new foo-item. App-3 is clustered, meaning there are multiple instances of it running at the same time. Kafka automatically balances the foo-topic messages between all these instances because they use the same consumer-id. This is good and in the case of app-3 it is actually desired.
In the case of app-2, however, the messages from the foo-topic are used for cache eviction. The logic is, basically, that if there is a new foo-item then the currently existing caches should probably be cleared, because their content depends on the foo-items. The issue is that app-2 is also clustered, which means that by default kafka-logic, every instance will only receive some of the messages sent to the foo-topic. This does not work correctly for this specific app tho, because whenever there is a new foo-item, all of the instances need to know about it because all of them need their clear their local caches.
From what I understand I have these two options if I want to keep the current logic:
Introduce a distributed cache for all instances of app-2 so that they all share the same cache. Then it does not matter if only one instance receives a foo-item, because the cache eviction will also affect the cache of the other instances; even though they never learned about the foo-item. I would like to avoid this solution, as a distributed cache would add a noticeable amount of complexity and also overhead.
Somehow manage to use a different consumer-id for each instance of app-2. Then they would be considered different consumers by kafka and they all would get each foo-topic message. However, I don't even know how to programmatically do this. The code of the application is not aware of replicated instances, there is no way to access any information about what node it is. If I use a randomly generated string on startup, then each time such instance restarts it would be considered a new consumer and would have to re-process all previous messages. That would be incorrect behavior as well.
Here is my bottom line question: Is it possible to make all instances of app-2 receive all messages from the foo-topic without completely breaking the way kafka is supposed to work? I know that it is probably very unconventional to use kafka-messages for cache eviction and I am entirely able to find an alternative mechanism for the cache eviction logic that does not depend on kafka-topic messages. However, the applications are for demonstration purposes and I thought it would be cool if more than one app read from this topic. But if I end up having to hack a dirty workaround to make it work then it's also bad for demonstration purposes and I would rather implement an alternative way of cache eviction.
A:
As you mentioned, you could use different consumer ids with random strings.
If notifications are being read from the beginning, then you probably have ConsumerConfig.AUTO_OFFSET_RESET_CONFIG set to "earliest" somewhere in your consumer configuration. If this is the case, removing it will probably solve your problems - when the app will start it will only receive notification sent after the consumer started listening.
| {
"pile_set_name": "StackExchange"
} |
Q:
Django display images in model form formset on validation error
I'm building an app where users can create projects; within each project, they can create 'locations', to which photos can be associated. Photo is a generic content model which can be associated with many other types of models. In this case the photos have already been uploaded and are associated to the project. The user can choose them to be associated with the location via a javascript modal window, then add a 'note' to them.
Originally I built this entirely manually and accessed the photos in the view via request.POST; however I had some trouble with the text values from the notes and so decided it would be easier/better to do it properly and build an actual model formset.
The photos are displayed in the template by accessing the .instance attribute of the form
This is working fine - I can add the photos and notes, and also remove them from a location if they have previously been added.
The problem is, however - that if the form has any validation errors and the user is returned to the template to deal with them, the image itself is not shown. This seems to be because the form does not have an instance attribute attached to it. The photo is displayed without any problem via the tag <img src="{{MEDIA_URL}}{{ photo.instance.photo.small.url }}">(using easy thumbnails) on the photos that are already saved to the location, but not for those that have just been added/edited.
My question is - how can I display the nice pretty picture in this situation?
Here's my model form:
class PhotoDisplayForm(ModelForm):
class Meta:
model = Photo
fields = {'id', 'note', }
widgets = {
'note': Textarea(attrs={'rows': 3}),
'photo': HiddenInput(),
'id': HiddenInput(),
}
views.py
def location_form(request, project_id, location_id=None):
project = Project.objects.get(id=project_id)
photos_formset = []
if location_id is None: #creates unbound forms
locPhotoFS = formset_factory(PhotoDisplayForm, max_num=0, can_delete=True)
photos_formset = locPhotoFS(prefix='loc_photos')
use_type = 'create' #this variable is passed to the template to display appropriate text
location_form = QuadratForm(request.POST or None, project_id=project_id)
else: ### edit an existing form ####
use_type = 'edit'
location = get_object_or_404(Location, pk=location_id)
location_form = QuadratForm(request.POST or None, project_id=project_id)
location_photos = Photo.objects.filter(location = location)
locPhotoFS = modelformset_factory(Photo, PhotoDisplayForm, max_num=0, can_delete=True)
photos_formset = locPhotoFS(queryset = location_photos, prefix='loc_photos')
if request.method == 'POST':
photos_formset = locPhotoFS(request.POST, prefix='loc_photos')
if location_form.is_valid() and photos_formset.is_valid():
location_instance = location_form.save(commit=False)
location_instance.project = get_object_or_404(Project, pk=project_id)
location_instance.save()
for form in photos_formset:
p = form.cleaned_data['id']
if form.cleaned_data['DELETE']:
p.content_object = project #reassociate the photo with the project
p.save()
else:
p.content_object = location_instance
p.note = form.cleaned_data['note'].strip()
print p.note
p.save()
return HttpResponseRedirect(reverse('core.views.location', args=(project_id, location_instance.id)))
else:
print 'there are errors'
context = {'location_type': location_type, 'use_type': use_type,'location_form': location_form,'project_photos': project.photos.all()}
if photos_formset:
context['photos_formset'] = photos_formset
return render(request, 'location_form.html', context)
Template
{% if photos_formset %}
{% if location_form.non_field_errors %}{{ location_form.non_field_errors }}{% endif %}
{{ photos_formset.management_form }}
{% for photo in photos_formset %}
{% if photo.non_field_errors %}{{ photo.non_field_errors }}{% endif %}
<div class="photo-details original" id="{{photo.instance.id}}_photo-details">
<button type="button" photo="{{photo.instance.id}}" class="close pull-right photo-delete" aria-hidden="true">×</button>
<div class="photo-notes">{{ photo.note.label_tag }}{{ photo.note|attr:"class:photo_notes_input" }}{{ photo.errors }}</div>
{{ photo.id }}
{{ photo.DELETE|attr:"class:delete-photo" }}
<div class="thumbnail-caption">
<img src="{{MEDIA_URL}}{{ photo.instance.photo.small.url }}">
<br>{{ photo.instance.title }}
</div>
</div>
{% endfor %}
{% endif %}
Here's the photo model itself, if that's useful:
class Photo(models.Model):
title = models.CharField(max_length=30)
photo = ThumbnailerImageField(upload_to=imagePath)
object_id = models.PositiveIntegerField()
content_type = models.ForeignKey(ContentType)
content_object = generic.GenericForeignKey('content_type', 'object_id')
note = models.TextField(max_length=200, blank=True)
def __unicode__(self):
return self.title
A:
I've figured out a (somewhat hacky) solution.
Because I already have a queryset called project_photos which is being passed to the template (this creates the javascript modal list where photos can be selected to add to the location), I simply loop through these in the template and find one where the id matches (the variable photo is the current form within the formset loop):
<div class="thumbnail-caption">
{% if photo.instance.title %}
<img src="{{MEDIA_URL}}{{ photo.instance.photo.small.url }}">
<br>{{ photo.instance.title }}
{% else %}
{% with p=photo.id.value %}
{% for pp in project_photos %}
{% ifequal p|stringformat:"s" pp.id|stringformat:"s" %}
<img src="{{MEDIA_URL}}{{ pp.photo.small.url }}">
<br>{{ pp.title }}
{% endifequal %}
{% endfor %}
{% endwith %}
{% endif %}
</div>
It was necessary to use the stringformat template filter - that got me stuck for a while.
This is not a perfect solution - because those photos are still displaying in the original javascript window (obviously I could work around that) - and also the template has to loop through a potentially large list of objects for each one which could slow things down.
Any suggestions for improvement gratefully accepted.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why aren't my onclick events working?
Here is a snippet of my code on jsfiddle.
I want the "+ Create Forum" button to show the form, "Cancel" button to reset the form and hide it, and if you want to see the form, delete "style="display: none".
I used a lot of examples out of w3schools and I have tried to use all its examples of writing a show and hide, one of the resets worked but it was a onclick="this.reset()" which wasn't what I wanted because I wanted it to hide too.
<html>
<body>
<button class="btn btn-default" type="submit" id="createform">+ Create Forum</button>
<div class="form-group" id="createForum">
<form action="forums.php" method="get" id="forumForm" style="display: none">
<label>Forum name:</label>
<input type="text" class="form-control" id="forumName">
<label>Description:</label>
<textarea class="form-control" rows="5" id="description"></textarea>
<button class="btn btn-danger" type="submit" name="create">Crear</button>
<input type="button" value="Reset Form" onclick="clearing()">
</form>
</div>
</body>
<script type="text/javascript">
$("#createform").click(function() {
$("#forumForm").show();
});
function clearing() {
document.getElementById("forumForm").reset();
}
</script>
A:
Try this:
$(document).ready(function(){
$("#createform").click(function() {
$("#forumForm").show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<html>
<body>
<button class="btn btn-default" type="submit" id="createform">+ Create Forum</button>
<div class="form-group" id="createForum">
<form action="forums.php" method="get" id="forumForm" style="display: none">
<label>Forum name:</label>
<input type="text" class="form-control" id="forumName">
<label>Description:</label>
<textarea class="form-control" rows="5" id="description"></textarea>
<button class="btn btn-danger" type="submit" name="create">Crear</button>
<input type="button" value="Reset Form" onclick="clearing()">
</form>
</div>
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
Exception-safety of C++ implicitly generated assignment operator
My understanding is that C++ implicitly generated assignment operator does a member-wise copy (this seems confirmed also by this answer). But, if during a member copy an exception is thrown (e.g. because a resource for that member can't be allocated), will the object being copied be stuck in an invalid state?
In other words, does the implicitly generated assignment operator achieve only the basic guarantee, but not the strong guarantee?
If we want the strong guarantee for our class copies, must we implement the assignment operator manually with the copy-and-swap idiom?
A:
If you want to offer an exception guarantee, and the default assignment operator is not nothrow then normally you need to write one.
The default copy assignment doesn't necessarily achieve even the basic guarantee, which is that no resources are leaked and the class invariants are preserved. Assigning some of the data members but not all might leave the target in a state where class invariants are not satisfied, depending on the particular class.
So you have to assess the default operator for your class -- if it can throw, and by throwing leave the object in an "invalid" state, then you have to suppress it. Or weaken the defined class invariants, but that's not very helpful to users.
There is (at least) one special case. If all the data members except for one have nothrow assignment, and the special one has strongly exception-safe assignment, and is the first data member in the class, then the default assignment operator would also be strongly safe. You might want to comment that quite carefully if you're relying on it, though, it could prove to be quite fragile!
| {
"pile_set_name": "StackExchange"
} |
Q:
How to move CCSprite
I need to move sprite from side to side. I use:
CCSprite *man;
id actionMove = [CCMoveTo actionWithDuration:1 position:ccp(20,300)];
[man runAction:actionMove];
When it's moved to (20,300) I need to move sprite to (20,0) and then move it to (20,300) and back.
How can I do that? Thanks.
A:
CCMoveTo *move = [CCMoveTo actionWithDuration:1 position:ccp(20,300)];
CCCallFuncN *move_done = [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished)];
[man runAction:[CCSequence actions:move1,move_done1,nil]];
-(void)spriteMoveFinished
{
CCMoveTo *move1 = [CCMoveTo actionWithDuration:1 position:ccp(20,0)];
[man runAction:[CCSequence actions:move1,nil]];
}
A:
Not sure if I got you right, but this should move your man 300 px on the y axis up and then back to 0 px on that same axis again in 2 seconds.
Not depending where is was before the man will move +300 on y and then -300 on y.
This is with CCMoveBy:
CCAction *moveOne = [CCMoveBy actionWithDuration:1 position:ccp(0, 300)];
CCAction *moveTwo = [CCMoveBy actionWithDuration:1 position:ccp(0, -300)];
CCSequence *manMoving = [CCSequence moveOne, moveTwo, nil];
[man runAction:manMoving];
This is with CCMoveTo:
CCAction *moveOne = [CCMoveTo actionWithDuration:1 position:ccp(20, 300)];
CCAction *moveTwo = [CCMoveTo actionWithDuration:1 position:ccp(20, 0)];
CCSequence *manMoving = [CCSequence moveOne, moveTwo, nil];
[man runAction:manMoving];
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery Basic Portlet
I am listing students at my web page. I want to list their information something like:
http://nettuts.s3.amazonaws.com/127_iNETTUTS/demo/index.html
However the portlets will be same size, no need for edit close buttons. I just want to show their names at every title of portlets. Also no need to be draggable or sortable. I just want to have good ui effect at my divs and wants that title for every portlet(I don't know well designing a CSS, so a library will be better for me instead of trying to get good colors)Also putting a minimize button may be good.
Is there any plugin like that at Jquery?
A:
You can use a jQuery UI theme CSS file along with properly formatted html.
http://jsfiddle.net/P9K3F/
| {
"pile_set_name": "StackExchange"
} |
Q:
Oracle - selected records between two dates (inclusive) when converting from date string
I have the following Oracle query
SELECT *
FROM table
WHERE date_opened
BETWEEN ((TO_DATE('2011-08-01', 'yyyy-mm-dd') - to_date('01-JAN-1970','DD-MON-YYYY')) * (86400))
AND ((TO_DATE('2011-08-31', 'yyyy-mm-dd') - to_date('01-JAN-1970','DD-MON-YYYY')) * (86400))
that nearly works but it doesn't include the dates records that are dated 2011-08-31. Any ideas? It has probably got something to do with how I am converting my date strings...
UPDATE: I really should have said that the date is actually a UNIX timestamp. That is why I am using the 86400 and 01-JAN-1970
Thank you :)
A:
If the upper bound of an interval is not included in your results, then it's likely that you're building an "exclusive" filter with respect to the upper bound. So just add one day to the upper bound. I.e.
AND ((TO_DATE(...) - to_date(...) + 1) * (86400)) - 1
In Oracle, +1 will add one day when used in date time arithmetic.
Note: BETWEEN .. AND creates an inclusive filter, as Ollie stated, but your arithmetic may change that behaviour by transforming things to seconds
A:
You don't include anything that happened after midnight the last day.
try:
AND ((TO_DATE('2011-09-01', 'yyyy-mm-dd') - to_date('01-JAN-1970','DD-MON-YYYY')) * (86400) - 1)
| {
"pile_set_name": "StackExchange"
} |
Q:
mysql_connect connection lifetime
What happes when the script that made @mysql_connect($server, $user, $password) dies?
How long does it live?
Thank you!
A:
Connections opened by mysql_connect()
are closed at script exit, unless
closed earlier by calls to
mysql_close().
http://www.phpdig.net/ref/rn41re774.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Print text file every three line start at 2nd line
I have done it with simple loop to count and print through.. How can I do it in bash scripting with program such as sed,awk ?
A:
Something like this:
awk 'NR % 3 == 2'
Test
sh-3.2$ more test
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Result
sh-3.2$ awk 'NR % 3 == 2' < test
2
5
8
11
14
A:
You can do it like this with GNU sed:
seq 20 | sed -n '2~3p'
Output:
2
5
8
11
14
17
20
| {
"pile_set_name": "StackExchange"
} |
Q:
plot a function in the positive semi axes
Good morning,
I would like to plot the following function: x=60-(1/6)*y. This function I'd like to be presented only in the positive side of both axes. How can I achive this? Is there a package or any order on how can I have any function plotted? I have tried many things seen both in this site and in others but I haven't succeded yet in making a good looking figure.
Thanks in advance
A:
As stated in the comments before, you can use the great package pgfplots for this.
\documentclass{minimal}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
\begin{axis}[xmin=0,xmax=360,ymin=0]
\addplot [domain=0:360,blue] {60-x/6};
\end{axis}
\end{tikzpicture}
\end{document}
But I can't really recomend plotting a simple function like this. It is easy enough to read, the ink to information ratio is not to well. If you want further information on ink to information ratio I suggest reading something written by Edward Tufte. Alternatively I would recommend the TikZ manual. pgfplots is build on TikZ.
If there is a good reason to still do it: Happy TeXing!
| {
"pile_set_name": "StackExchange"
} |
Q:
How to write JSON string value in code?
I want to store the following string in a String variable
{"Id":"123","DateOfRegistration":"2012-10-21T00:00:00+05:30","Status":0}
This is the code I use ..
String str="{"Id":"123","DateOfRegistration":"2012-10-21T00:00:00+05:30","Status":0}";
.. but it's showing error ..
A:
You have to do this
String str="{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}";
Please see this for referenceAlso from msdn :)
Short Notation UTF-16 character Description
\' \u0027 allow to enter a ' in a character literal, e.g. '\''
\" \u0022 allow to enter a " in a string literal, e.g. "this is the double quote (\") character"
\\ \u005c allow to enter a \ character in a character or string literal, e.g. '\\' or "this is the backslash (\\) character"
\0 \u0000 allow to enter the character with code 0
\a \u0007 alarm (usually the HW beep)
\b \u0008 back-space
\f \u000c form-feed (next page)
\n \u000a line-feed (next line)
\r \u000d carriage-return (move to the beginning of the line)
\t \u0009 (horizontal-) tab
\v \u000b vertical-tab
A:
I prefer this, just make sure you don't have single quote in the string
string str = "{'Id':'123','DateOfRegistration':'2012 - 10 - 21T00: 00:00 + 05:30','Status':0}"
.Replace("'", "\"");
A:
There is an alternate way to write these complex JSON using Expando object or XElement and then serialize.
https://blogs.msdn.microsoft.com/csharpfaq/2009/09/30/dynamic-in-c-4-0-introducing-the-expandoobject/
dynamic contact = new ExpandoObject
{
Name = "Patrick Hines",
Phone = "206-555-0144",
Address = new ExpandoObject
{
Street = "123 Main St",
City = "Mercer Island",
State = "WA",
Postal = "68402"
}
};
//Serialize to get Json string using NewtonSoft.JSON
string Json = JsonConvert.SerializeObject(contact);
| {
"pile_set_name": "StackExchange"
} |
Q:
Web based SIP Softphone app with open source api
I am planning to build a web based softphone which can be used with any SIP server (now need to support Genesys). Can you please suggest any C# based open source solution?
I was exploring these option and heard about Lync client SDK for SIP interaction. Can I use Lync Client SDK to build SIP softphone which can register work with 3rd party SIP server like Genesys etc?
A:
Not unless you have a Lync environment (hosted, on-premises, etc.) that is integrated via SIP with your Genesys platform - using a Session Border Controller or similar mechanism.
Unfortunately you can not communicate using the Lync Client SDK directly with a non-Lync platform.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I get a stuck screw filter off of my lens?
There is a UV-filter screwed on my Canon 16-35mm. For some reason, I'm not able to get it off the lens.
Does anyone has a simple but safe trick?
A:
I carry a jar lid gripper around in my kit which has always done the trick for me when I need a little extra, well, grip.
The other 'trick' that I have learned over the years is that most people's default reaction to a stuck filter is to get a really good grip on the filter and just try to torque it off. The problem with this approach is that the filter glass is rarely a snug fit inside the metal filter rim. Because of this, gripping the filter firmly often results in the metal filter rim flexing ever-so slightly... Which binds it to the lens even more tightly. With such tiny threads a flexed filter might as well have lock-tite in there!
So it seems paradoxical, but often I've found that by loosening my grip and very gently turning the filter mostly using pressure on the top of the filter, rather than on the sides (which can cause it to flex) I can get it to turn.
A:
If you're out and about and this happens then carry a couple of elastic bands! These allow you to get a proper grip on the slim sides of the filter so you can remove it. Often they are stuck not because they are jammed on but because you cannot get enough of a grip to apply enough pressure to start turning them.
A very simply, cheap, and more importantly small, solution that works quite well :)
A:
You can buy lens filter wrenches -- if you don't think they'd be something you'd use all the time (and thus, buy), you might find that your local camera shop has one you could use.
| {
"pile_set_name": "StackExchange"
} |
Q:
Flask/NGINX 404s on only some POST requests
I have a Flask app served by Gunicorn using NGINX as a webserver. I only have two endpoints that have POST requests, a login and a submit post. The login works flawlessly however whenever I attempt to POST using the submit post endpoint, I receive a 404. My code works running on localhost without NGINX or Gunicorn and in order to detect that the request is POST vs GET I am using WTForms validate_on_submit method. The NGINX error and access logs don't show anything out of the ordinary.
Edit: Here is the code for the endpoints with post requests
New Post:
@app.route('/newpost', methods=['GET', 'POST'])
@login_required
def new_post():
form = BlogForm()
if form.validate_on_submit():
#Omitted code for getting form data and creating form object
try:
#Omitted code for database actions
return redirect(url_for('index', _external=True))
except IntegrityError:
flash("Error inserting into database")
return('', 203)
else:
#Omitted some code for template rendering
return render_template('new_post.html')
Login:
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
userAuth = current_user.is_authenticated
if form.validate_on_submit():
flash("Login attempt logged")
user = User.query.filter_by(username=form.userID.data).first()
if user:
checkPass = form.password.data.encode('utf-8')
if bcrypt.checkpw(checkPass, user.password):
user.authenticated = True
login_user(user, remember=form.remember_me.data)
return redirect(url_for('index', _external=True))
else:
form.errors['password'] = 'false'
else:
form.errors['username'] = 'false'
else:
return render_template('login.html',
title='Log In',
loggedIn=userAuth,
form=form)
A:
The problem ended up being with NGINX after all, I fixed it by changing the ownership of /var/lib/nginx from the nginx user to the user running the Flask application. Prior to doing this AWS wasn't letting me upload files from my form in new_post.
| {
"pile_set_name": "StackExchange"
} |
Q:
Voltage regulating without current drop
How can I get 8V 30A power supply from a 12V 30A DC supply? I would be glad if you could illustrate on your point since i don't know much about this yet.
A:
How can I get 8V 30A power supply from a 12V 30A DC supply?
In principle, a linear regulator would allow you to do this. Typically they only consume a few micro or milliamps themselves and pass the vast majority of input current to their load.
In practice, 30 A through a linear regulator is a horrible idea due to the power inefficiency. 12 V x 30 A is 360 W while 8 V x 30 A is 240 W. So if you use a linear regulator that takes 360 W from the supply, and delivers 240 W to the load, where does the extra 120 W go? The linear regulator turns it into heat. Which means you need a truly massive heat sink, and a lot of careful design to avoid the regulator burning itself up.
This can be overcome by using a switching regulator. A switching regulator would be able to deliver 30 A to an 8 V load, while only drawing about 20 A (maybe 22-24 A in reality) from the 12 V input.
But designing a 240 W switching regulator is not a trivial job, and not a good choice for a first design project. If your goal is to learn, start with something smaller like mentioned in the comments, and try this design later. If your goal is just to provide power to some device you want to use, you'd probably be best off just buying an off-the-shelf 8 V 30 A mains-powered supply.
| {
"pile_set_name": "StackExchange"
} |
Q:
getIntent().getSerializableExtra is null
I have a POJO class implements Serializable
and I want to transfer an object of this class to another activity with a help Intent and Bundle.
I checked the object before the transfer, it is not null. (Correctly get one of attributes)
put:
private void onFriendClick(FriendHolder holder, int position) {
Intent intent = new Intent(context, ProfileActivity.class);
Bundle extra = new Bundle();
extra.putSerializable(Consts.KEY_USER_JSON, friendList.get(position));
intent.putExtra(Consts.KEY_USER_JSON, extra);
Log.e("onFriendClick", String.valueOf(friendList.get(position).getName()));
context.startActivity(intent);
}
get from another activity:
private void setupProfile() {
Bundle extras = getIntent().getExtras();
if (extras != null) {
profile = (ProfileDTO) getIntent().getSerializableExtra(Consts.KEY_USER_JSON);
Log.e("onFriendClick", String.valueOf(profile.getName()));//NPE this
} else profile = user.getProfile();
}
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'java.lang.String
ru.techmas.getmeet.api.models.ProfileDTO.getName()' on a null object
reference
at ru.techmas.getmeet.activities.ProfileActivity.setupJsonProfile(ProfileActivity.java:103)
A:
You don't need to create a Bundle.
Try doing:
private void onFriendClick(FriendHolder holder, int position) {
Intent intent = new Intent(context, ProfileActivity.class);
intent.putExtra(Consts.KEY_USER_JSON, friendList.get(position));
Log.e("onFriendClick", String.valueOf(friendList.get(position).getName()));
context.startActivity(intent);
}
private void setupProfile() {
if (getIntent().getSerializableExtra(Consts.KEY_USER_JSON) != null) {
profile = (ProfileDTO) getIntent().getSerializableExtra(Consts.KEY_USER_JSON);
Log.e("onFriendClick", String.valueOf(profile.getName()));//NPE this
} else {
profile = user.getProfile();
}
}
But if still want to use the Bundle, you should replace in the code that you posted:
profile = (ProfileDTO) getIntent().getSerializableExtra(Consts.KEY_USER_JSON);
By:
profile = (ProfileDTO) extras.getSerializableExtra(Consts.KEY_USER_JSON);
| {
"pile_set_name": "StackExchange"
} |
Q:
How to remotely run a Python script in an existing Blender instance?
I don't want to use /Application.../blender -P my_script.py but I want to tell a running Blender process to execute a script.
Is there an existing method to tell a running Blender process to execute a python script?
For example using http://localhost:123/run_script=myscript.py
A:
This can be done with sockets,
using the following examples you can run from the command line:
From the first terminal:
blender --python blender_server.py
From a second terminal:
python blender_client.py /path/to/myscript.py
This will execute /path/to/myscript.py in the first Blender instance.
You can send multiple scripts or run the client multiple times.
Note that this is a simple example, to get return codes in the client or make the port configurable... etc, this would have to be extended.
It could even be made to sent the entire script, or compressed Python byte-code over a network, none of this is especially hard. It just depends what you're after.
blender_server.py
# Script to run from blender:
# blender --python blender_server.py
PORT = 8081
HOST = "localhost"
PATH_MAX = 4096
def execfile(filepath):
import os
global_namespace = {
"__file__": filepath,
"__name__": "__main__",
}
with open(filepath, 'rb') as file:
exec(compile(file.read(), filepath, 'exec'), global_namespace)
def main():
import socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind((HOST, PORT))
serversocket.listen(1)
print("Listening on %s:%s" % (HOST, PORT))
while True:
connection, address = serversocket.accept()
buf = connection.recv(PATH_MAX)
for filepath in buf.split(b'\x00'):
if filepath:
print("Executing:", filepath)
try:
execfile(filepath)
except:
import traceback
traceback.print_exc()
if __name__ == "__main__":
main()
blender_client.py
#!/usr/bin/env python
# Script to send paths to run in blender:
# blender_client.py script1.py script2.py
PORT = 8081
HOST = "localhost"
def main():
import sys
import socket
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect((HOST, PORT))
for arg in sys.argv[1:]:
clientsocket.sendall(arg.encode("utf-8") + b'\x00')
if __name__ == "__main__":
main()
A:
I think this is a simple solution and avoids dependencies entirely.
https://github.com/zeffii/bpy_externall
Blender (Server)
Here's a small modal operator addon that works like this:
Adds a panel to the TextEditor, with a start / end button
when Start is pressed it
reads a file located at /path/whatever.io every n seconds.
If the file is empty we do nothing,
If the file contains a filepath (for instance to a python file)
then the filepath is executed with Blender's python (as if it was running from the TextEditor). Once completed the operator will erase the contents of the file to indicate that it executed the path.
When End is pressed the modal operator stops reading that file location.
External Text Editor (Client)
The add-on includes an example of a SublimeText3 plugin that acts as a Client. All this 'Sender' plugin needs to do is write the filepath of the python file you want Blender to execute to /path/whatever.io
A:
I did ask a similar question, but as this one is way more popular so I guess that answer should be here. Question on command port
This usually is done with command port that listens for commands, but there's apparently no such thing in Blender. I've created an addon that implements this functionality.
It can be found on github:
Sources
Release
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ : What are the purpose of captures in lambda expressions?
How are captures different than passing parameters into a lambda expression? When would I use a capture as opposed to just passing some variables?
for reference: http://en.cppreference.com/w/cpp/language/lambda#Lambda_capture
The reference only defines it as a "list of comma separated values" but not what they're for or why I'd use them.
To add: This is not the same question as "what is a lambda expression" because I'm not asking what a lambda expression is or when to use it. I'm asking what the purpose of a capture is. A capture is a component of a lambda expression, and can take values, but it's not well explained elsewhere on the internet what these values' intended purpose is, and how that is different from the passed values that follow the capture.
A:
You may want to pass your lambda to a function that calls it with a specific number of arguments (e.g., std::find_if passes a single argument to your function). Capturing variables permits you to effectively have more inputs (or outputs, if you capture by reference).
| {
"pile_set_name": "StackExchange"
} |
Q:
ΠΡΠ»ΠΎΠ² Π½Π°ΠΆΠ°ΡΠΈΡ ΠΊΠ»Π°Π²ΠΈΡΠΈ Π±Π΅Π· ΠΎΠΆΠΈΠ΄Π°Π½ΠΈΡ golang
package main
import (
"fmt"
"github.com/eiannone/keyboard"
)
func main() {
char, _, err := keyboard.GetSingleKey()
if (err != nil) {
panic(err)
}
fmt.Printf("You pressed: %q\r\n", char)
}
ΠΡΠΏΠΎΠ»ΡΠ·ΡΡ Π² ΠΊΠΎΠ΄Π΅ ΡΡΠ½ΠΊΡΠΈΡ Π½Π°ΠΏΠΎΠ΄ΠΎΠ±ΠΈΠ΅ ΡΡΠΎΠΉ. ΠΡΠΎΠ±Π»Π΅ΠΌΠ° Π² ΡΠΎΠΌ,ΡΡΠΎ keyboard.GetSingleKey() ΠΆΠ΄ΡΡ Π½Π°ΠΆΠ°ΡΠΈΡ ΠΊΠ»Π°Π²ΠΈΡΠΈ. Π§ΡΠΎ Π½ΡΠΆΠ½ΠΎ ΡΠ΄Π΅Π»Π°ΡΡ,ΡΡΠΎΠ±Ρ ΠΏΠΎ ΠΈΡΡΠ΅ΡΠ΅Π½ΠΈΠΈ ΠΊΠ°ΠΊΠΎΠ³ΠΎ-ΡΠΎ Π²ΡΠ΅ΠΌΠ΅Π½ΠΈ(Π½Π°ΠΏΡΠΈΠΌΠ΅Ρ 10ΠΌΡ) ΠΏΡΠΎΠ³ΡΠ°ΠΌΠΌΠ° ΠΏΡΠ΅ΡΡΠ²Π°Π»Π° ΠΎΠΆΠΈΠ΄Π°Π½ΠΈΠ΅ ΠΈ Π²ΠΎΠ·Π²ΡΠ°ΡΠ°Π»Π° nil?
A:
ΠΠΎΠ΄ΠΎΠ±Π½ΡΠ΅ Π±Π»ΠΎΠΊΠΈΡΡΡΡΠΈΠ΅ ΠΎΠΏΠ΅ΡΠ°ΡΠΈΠΈ Π² ΡΠ°ΠΊΠΈΡ
ΡΠ»ΡΡΠ°ΡΡ
ΡΡΠΎΠΈΡ Π²ΡΠ½ΠΎΡΠΈΡΡ Π² ΠΎΡΠ΄Π΅Π»ΡΠ½ΡΠ΅ Π³ΠΎΡΡΡΠΈΠ½Ρ. ΠΠ°ΠΏΡΠΈΠΌΠ΅Ρ, Π²ΠΎΡ ΡΠ°ΠΊ:
func getKeyTimeout(tm time.Duration) (ch rune, err error) {
if err = keyboard.Open(); err != nil {
return
}
defer keyboard.Close()
var (
chChan = make(chan rune, 1)
errChan = make(chan error, 1)
timer = time.NewTimer(tm)
)
defer timer.Stop()
go func(chChan chan<- rune, errChan chan<- error) {
ch, _, err := keyboard.GetSingleKey()
if err != nil {
errChan <- err
return
}
chChan <- ch
}(chChan, errChan)
select {
case <-timer.C:
return 0, errTimeout
case ch = <-chChan:
case err = <-errChan:
}
return
}
Π Π·Π°Π²Π΅ΡΡΠ°ΡΡ ΠΏΠΎ ΡΠ°ΠΉΠΌΠ΅ΡΡ. ΠΠΎΡ ΠΈ Π²ΡΡ. ΠΠΎΠ»Π½ΡΠΉ ΠΏΡΠΈΠΌΠ΅Ρ https://play.golang.org/p/HQ_gUsFW-io
Π ΡΡΠΎΠΌ ΠΏΡΠΈΠΌΠ΅ΡΠ΅ Π²ΠΎΠ·Π²ΡΠ°ΡΠ°Π΅ΡΡΡ errTimeout, Π½ΠΎ ΠΎΠ½ ΠΌΠΎΠΆΠ΅Ρ Π±ΡΡΡ Π»Π΅Π³ΠΊΠΎ ΠΏΠ΅ΡΠ΅Ρ
Π²Π°ΡΠ΅Π½ ΠΈΠ»ΠΈ Π·Π°ΠΌΠ΅Π½ΡΠ½ Π½Π° Π΄ΡΡΠ³ΠΎΠ΅ Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅, Π² ΡΠΎΠΌ ΡΠΈΡΠ»Π΅ ΠΈ Π½Π° nil, Π΅ΡΠ»ΠΈ ΡΠ°ΠΊ ΡΠ³ΠΎΠ΄Π½ΠΎ. ΠΠΎ, Π΄ΡΠΌΠ°Π΅ΡΡΡ ΠΌΠ½Π΅, Π»ΡΡΡΠ΅ ΠΏΡΠΎΡΡΠΎ
if err != nil && err != errTimeout {
// ΠΎΠ±ΡΠ°Π±ΠΎΡΠΊΠ° ΠΎΡΠΈΠ±ΠΊΠΈ
}
ΠΡ ΠΈΠ»ΠΈ ΠΊΠ°ΠΊ-ΡΠΎ ΡΠ°ΠΊ.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error code: 1364 Field doesnt have a default value in MySQL
I have a database in which there exist two tables campaign_details and product_details.
campaign_details
product_details
The column pr_name in campaign_details references pr_name in product_details.
Due to the vast size of the campaign_details table I decided to make a smaller table named campaign_info to increase speed of data access.
campaign_info
Here cmp_name corresponds to cmp_name in campaign_details and pr_id corresponds to pr_id of the associated pr_name in product_details.
Hence now I want to remove the columns cmp_name and pr_name from campaign_details and add a new column cmp_info_id
I am using this query to add the values to cmp_info_id
Insert into nredb.campaign_details(cmp_info_id) (Select ci.cmp_info_id from nredb.campaign_info ci, nredb.campaign_details cd,nredb.product_details pd
where ci.cmp_name=cd.cmp_name and ci.pr_id in (select pd1.pr_id from nredb.product_details pd1,nredb.campaign_details cd1 where cd1.pr_name=pd1.pr_name));
But it gives this error Error Code: 1364. Field 'pr_name' doesn't have a default value
Any help with what could be going wrong with the query?
A:
You're trying to insert into your campaign_details table, but you're not specifying a value for pr_name in your query, because that's not being picked up by the nested Select query.
You have two options:
Modify your Select query so that it also returns a pr_name;
Set a default value for pr_name on your campaign_details table so that it still gets populated with something if you don't specify a value in the Insert query.
It is also possible that you're not trying to add a new row to the table at all, but trying to modify the cmp_info_id field of an existing row. If that's the case, then you don't want an Insert query, you want an Update:
UPDATE nredb.campaign_details SET cmp_info_id=(SELECT ...) WHERE <condition to select row to update>
| {
"pile_set_name": "StackExchange"
} |
Q:
Solving the simultaneous equations
I need to solve the following simultaneous equations for the constants $A$ and $B$:
$$zA + (1-z)B = 1$$
$$\hspace{1.8cm} z^2A + (1-z)B = z^2 - z + 1$$
where$z$ is just a variable. What I did was this:
$$zA = 1 - (1-z)B \implies z^2A = z - (z - z^2)B$$
and so subbing this into the second equation gives me
$$z - (z - z^2)B + (1-z)B = z^2 -z + 1$$
Rearanging gives me
$$(z^2 - 2z + 1) = (1 - z)^2 = \{(1-z) - z(1 - z)\}B $$
which can then be simplified to get
$$(1 - z) = (1 - z)B \implies B = 1$$
which is wrong beacuse in my answers it says $B = \frac{1-z}{1 - 2z}$. I think I will get $A$ once I have $B$ but I can't see my mistake right now.
A:
Hints:
From eq. (1):
$$(1-z)B=1-Az$$
From eq. (2):
$$(1-z)B=(1-A)z^2-z+1$$
so
$$ (1)=(2)\implies (1-A)z^2-(1-A)z=0\implies A=1\;\; \text {or} \;\,\,z(z-1)=0\;\;\ldots$$
| {
"pile_set_name": "StackExchange"
} |
Q:
How to aggregate dataframe by minimum daily value
I am trying to extract values in a large data frame (with per minute data) where I want a subset of the data frame when x variable is at its daily minimum and maximum.
For an example data set see below. The example I have given has daily values to reduce the complexity - so in this case how would I get the monthly data frame values when temperature is at its minimum and maximum.
I do not have a great deal of experience in aggregate but I have been able to extract the monthly min and max temp values:
a <- as.data.frame(aggregate(df$Temp, df[4], function(x) {
c(max = max(x), min = min(x)) }))
But I am not sure how to do this without losing the information from the original data frame - it would almost be a subset based on a minimum and maximum argument? But I am not sure how to write that.
Any help would be appreciated - and apologies for the large dput example.
Thanks
df <- structure(list(Group.1 = c(1628, 1629, 1630, 1631, 1632, 1633,
1634, 1635, 1636, 1637, 1638, 1639, 1640, 1641, 1642, 1643, 1644,
1645, 1646, 1647, 1648, 1649, 1650, 1651, 1652, 1653, 1654, 1655,
1656, 1657, 1658, 1659, 1660, 1661, 1662, 1663, 1664, 1665, 1666,
1667, 1668, 1669, 1670, 1671, 1672, 1673, 1674, 1675, 1676),
datetime = structure(c(1466078376.13352, 1466164800, 1466251194.49235,
1466337600, 1466423992.99026, 1466510400, 1466596853.49096,
1466683185.13551, 1466769600, 1466856000.06254, 1466942345.50765,
1467028800, 1467115179.92356, 1467201600, 1467288000, 1467374400,
1467460801.81376, 1467547200, 1467633604.67316, 1467720000,
1467806423.20361, 1467892800, 1467979255.99444, 1468065552.68428,
1468152000, 1468238400, 1468324827.121, 1468411200, 1468497619.36762,
1468584000, 1468670456.74548, 1468756798.41446, 1468843200,
1468928779.09091, 1469016500.50633, 1469102400, 1469188805.17385,
1469275200, 1469361564.70097, 1469448000, 1469534423.82046,
1469620800, 1469707247.98331, 1469793556.6064, 1469880000,
1469966391.40473, 1470041370, 1470178341.25, 1470217984.93671
), class = c("POSIXct", "POSIXt")), year = c(2016, 2016,
2016, 2016, 2016, 2016, 2016, 2016, 2016, 2016, 2016, 2016,
2016, 2016, 2016, 2016, 2016, 2016, 2016, 2016, 2016, 2016,
2016, 2016, 2016, 2016, 2016, 2016, 2016, 2016, 2016, 2016,
2016, 2016, 2016, 2016, 2016, 2016, 2016, 2016, 2016, 2016,
2016, 2016, 2016, 2016, 2016, 2016, 2016), month = c(6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 8, 8, 8), day = c(16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 26, 27, 28, 29, 30, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 30, 31, 1, 2, 3), hour = c(11.4937413073713,
11.5, 11.4979137691238, 11.5, 11.4979137691238, 11.5, 11.5146036161335,
11.4961779013204, 11.5, 11.5003474635163, 11.4853963838665,
11.5, 11.4940931202224, 11.5, 11.5, 11.5, 11.5003474635163,
11.5, 11.5006954102921, 11.5, 11.5066018068103, 11.5, 11.5159944367177,
11.4867872044506, 11.5, 11.5, 11.5076495132128, 11.5, 11.505211952745,
11.5, 11.5159944367177, 11.4993045897079, 11.5, 11.2755681818182,
11.6385372714487, 11.5, 11.5020862308762, 11.5, 11.4895688456189,
11.5, 11.5066109951287, 11.5, 11.5132127955494, 11.4881780250348,
11.5, 11.4979137691238, 8.3314447592068, 22.3854166666667,
9.38818565400844), min = c(29.4777468706537, 29.5, 29.5333796940195,
29.5, 29.5083449235049, 29.5, 29.5152990264256, 29.4815844336345,
29.5, 29.4801945795691, 29.4680111265647, 29.5, 29.5198054204309,
29.5, 29.5, 29.5, 29.5093815149409, 29.5, 29.5361613351878,
29.5, 29.4906184850591, 29.5, 29.4735744089013, 29.5041724617524,
29.5, 29.5, 29.4930458970793, 29.5, 29.5100764419736, 29.5,
29.4860917941586, 29.5152990264256, 29.5, 29.2840909090909,
29.5295358649789, 29.5, 29.4610570236439, 29.5, 29.5375521557719,
29.5, 29.500347947112, 29.5, 29.5069541029207, 29.4860917941586,
29.5, 29.4819193324061, 29.1133144475921, 28.7291666666667,
29.2911392405063), sec = c(30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30), DOY = c(167.499723767578,
168.5, 169.499936254057, 170.5, 171.499918868799, 172.5,
173.500619108329, 174.499827957301, 175.5, 176.500000723882,
177.499369301499, 178.5, 179.499767633773, 180.5, 181.5,
182.5, 183.500020992587, 184.5, 185.500054087467, 186.5,
187.500268560343, 188.5, 189.500648083758, 190.499452364395,
191.5, 192.5, 193.500313900479, 194.5, 195.500224162227,
196.5, 197.500656776387, 198.499981648895, 199.5, 200.490498737374,
201.505792897328, 202.5, 203.500059882553, 204.5, 205.499591446453,
206.5, 207.50027569976, 208.5, 209.500555362386, 210.499497759233,
211.5, 212.499900517694, 213.367708333333, 214.953023726852,
215.41186269339), Day = c(1628.49972376758, 1629.5, 1630.49993625406,
1631.5, 1632.4999188688, 1633.5, 1634.50061910833, 1635.4998279573,
1636.5, 1637.50000072388, 1638.4993693015, 1639.5, 1640.49976763377,
1641.5, 1642.5, 1643.5, 1644.50002099259, 1645.5, 1646.50005408747,
1647.5, 1648.50026856034, 1649.5, 1650.50064808376, 1651.49945236439,
1652.5, 1653.5, 1654.50031390048, 1655.5, 1656.50022416223,
1657.5, 1658.50065677639, 1659.4999816489, 1660.5, 1661.49049873737,
1662.50579289733, 1663.5, 1664.50005988255, 1665.5, 1666.49959144645,
1667.5, 1668.50027569976, 1669.5, 1670.50055536239, 1671.49949775923,
1672.5, 1673.49990051769, 1674.36770833333, 1675.95302372685,
1676.41186269339), DayH = c(1628.47890588781, 1629.47916666667,
1630.47907974038, 1631.47916666667, 1632.47907974038, 1633.47916666667,
1634.47977515067, 1635.47900741256, 1636.47916666667, 1637.47918114431,
1638.47855818266, 1639.47916666667, 1640.47892054668, 1641.47916666667,
1642.47916666667, 1643.47916666667, 1644.47918114431, 1645.47916666667,
1646.4791956421, 1647.47916666667, 1648.47944174195, 1649.47916666667,
1650.47983310153, 1651.47861613352, 1652.47916666667, 1653.47916666667,
1654.47948539638, 1655.47916666667, 1656.47938383136, 1657.47916666667,
1658.47983310153, 1659.47913769124, 1660.47916666667, 1661.46981534091,
1662.48493905298, 1663.47916666667, 1664.47925359295, 1665.47916666667,
1666.47873203523, 1667.47916666667, 1668.4794421248, 1669.47916666667,
1670.47971719981, 1671.47867408438, 1672.47916666667, 1673.47907974038,
1674.34714353163, 1675.93272569444, 1676.39117440225), DayD = c(1628,
1629, 1630, 1631, 1632, 1633, 1634, 1635, 1636, 1637, 1638,
1639, 1640, 1641, 1642, 1643, 1644, 1645, 1646, 1647, 1648,
1649, 1650, 1651, 1652, 1653, 1654, 1655, 1656, 1657, 1658,
1659, 1660, 1661, 1662, 1663, 1664, 1665, 1666, 1667, 1668,
1669, 1670, 1671, 1672, 1673, 1674, 1675, 1676), Sal = c(29.0488087045063,
29.0242089236389, 28.9704142552782, 28.9337236612778, 28.9124731267455,
28.8621913531181, 28.7694603506606, 28.6800432876789, 28.6368648858889,
28.5239238692008, 28.6274684358136, 28.6899766423333, 28.7094982390063,
28.6427974009653, 28.6540963996528, 28.5762126331528, 28.5617631359555,
28.6364940399097, 28.6458543031711, 28.603713066875, 28.65796586713,
28.6926140346389, 28.6470827340195, 28.5985220503964, 28.6620416165972,
28.6305870582222, 28.7001961730876, 28.6916165265, 28.6656868092356,
28.8356597378472, 29.266969874235, 28.418354432114, 28.3670879136597,
28.7002130192898, 28.1320816093038, 27.4618531637569, 27.5341382380668,
27.4453546479236, 28.2270356746662, 28.3642271282222, 27.9785534427697,
28.1165695540903, 28.6652365165229, 28.4222878245758, 28.4388172580139,
28.0149544998192, 28.4748151350047, 28.0933474488542, 27.8804163691308
), Temp = c(-0.902727819368567, -0.824054421545139, -0.720653055488178,
-0.64214159655, -0.557226600257997, -0.438045884220833, -0.395580348047288,
-0.295740618513551, -0.262320095793056, -0.160162734756081,
-0.20336842434701, -0.197846770197222, -0.133355481749131,
-0.0565102243486111, -0.0215979124673611, 0.125483112529167,
0.238572840179291, 0.272823149654167, 0.311757436682198,
0.392257187272917, 0.396628769779013, 0.475891600833333,
0.607289245171071, 0.644559951482615, 0.665206005440278,
0.727629137738889, 0.696052211995828, 0.752315860946528,
0.832433359182071, 0.471555079075, -0.187290608750348, 1.12906111324131,
1.24940833146181, 0.780415736372869, 2.0088144469993, 2.93373915290972,
3.19907420429903, 3.16430728506875, 1.87296632160014, 1.74067924683403,
2.50500692939318, 2.26088904221181, 1.20761122894784, 1.64661297725591,
1.68971783634167, 2.8011089384096, 1.70051260145987, 2.9201268373125,
3.38838510550127), Den = c(1023.3705136356, 1023.34875807153,
1023.30254908484, 1023.27139922778, 1023.25147035396, 1023.20777893194,
1023.13225399791, 1023.05719108895, 1023.02118660833, 1022.92671791522,
1023.01148932893, 1023.06187513264, 1023.07546443363, 1023.01910884861,
1023.02718869861, 1022.95948791944, 1022.94312314663, 1023.00176208264,
1023.00818908971, 1022.97111798194, 1023.01464410354, 1023.03946157917,
1022.99742747636, 1022.95676902782, 1023.00684491736, 1022.97892510208,
1023.03639020376, 1023.02648772361, 1023.00193750904, 1023.15208127222,
1023.5269599694, 1022.78984692211, 1022.74222825486, 1023.03256159162,
1022.51158633193, 1021.90175907847, 1021.95317423018, 1021.88198156806,
1022.59607175591, 1022.71358182847, 1022.35521831037, 1022.47925275556,
1022.98340138456, 1022.76567206815, 1022.77633019236, 1022.36132367177,
1022.80426542115, 1022.42016046875, 1022.21591253502), Chl = c(0.426618683276773,
0.415201663443056, 0.385096423775383, 0.363738871729861,
0.409404512937413, 0.434480798338889, 0.491604291206537,
0.464091430292564, 0.519904672929861, 0.549126851486449,
0.552805036465925, 0.557850158557639, 0.466429236588603,
0.510509837531944, 0.488934344839583, 0.3889341805625, 0.423089474131341,
0.499932285390278, 0.459906828269124, 0.365046922974306,
0.275903841463516, 0.249863925111806, 0.234845544844924,
0.225590052227399, 0.230629094999306, 0.214579363215278,
0.166625286886648, 0.171862695222222, 0.188135247756776,
0.2714899376625, 0.249608510288595, 0.234688186765647, 0.263209856711111,
0.223578790403409, 0.196086601016174, 0.300936248076389,
0.198270502905424, 0.254613127958333, 0.211631943366481,
0.194650132228472, 0.221967901366736, 0.287470503101389,
0.346767555667594, 0.272033042223922, 0.261851759145139,
0.30292882953338, 0.354326095381492, 0.139364686395833, 0.25231837455865
), O2 = c(8.40147872631572, 8.38937171346181, 8.41514077121905,
8.42152294330694, 8.47538879331154, 8.49880474437986, 8.47472190401391,
8.57655982897498, 8.61944234794514, 8.61577329576095, 8.69213896446314,
8.68921609862778, 8.69141974274149, 8.70994810763125, 8.68851865927569,
8.67396664622847, 8.76928090276998, 8.80177919844583, 8.80529066242629,
8.7617663811118, 8.70471848277554, 8.73156013737708, 8.76644351992003,
8.7618030795612, 8.79754675150208, 8.79138352644236, 8.75052502651043,
8.71269655839444, 8.68668315413829, 8.60423627197361, 8.6258442449847,
8.54381038276356, 8.66501514202014, 8.70410267486577, 8.4057585319121,
8.04968271129722, 7.92461467095619, 7.9134090372875, 8.41306227992907,
8.53320737933681, 8.33820448514335, 8.38417834865208, 8.62405400836439,
8.42477547407102, NaN, 8.40141680898052, 8.48576496565722,
8.28582430035417, 7.96892147137215), ID = c(1.21133857408067,
1.16902903935, 1.11473135400904, 1.07275230797986, 1.03223155043115,
0.995775405476389, 0.962935072082058, 0.91925791728214, 0.844455992659028,
0.791515976553162, 0.751516800569541, 0.702131858139583,
0.707145974122307, 0.599273624570139, 0.502570098100694,
0.347712868368056, 0.335673459499653, 0.152877532414716,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), PAR = c(23.0673615360132,
32.1793662073708, 6.5780126555751, 26.73609441565, 48.6703905053255,
31.0519168669979, 32.4282362099165, 62.9277536311577, 42.349564172909,
36.1037009880507, 36.4754793940695, 41.2935785894486, 56.3411955151001,
32.0717618120021, 68.055826105709, 83.7724642720521, 92.4702250095455,
63.3510742622049, 123.118356252679, 127.241395072853, 134.184346299723,
144.712733899262, 152.801023269344, 145.640278660995, 149.976623338179,
159.125758044126, 185.67869649515, 154.650267769035, 118.350412925882,
97.6856430502583, 120.50500187914, 114.336144557309, 113.572030429865,
164.301402493774, 129.582420528291, 116.032838587456, 129.230413097896,
74.3598830959583, 156.888302579191, 146.709144185685, 170.418761938188,
109.206260157938, 107.575876383898, 116.456387998532, 101.787857506992,
138.683838377278, 59.2571219263966, 301.257992689583, 132.693163343932
), CO2 = c(313.287072418802, 316.458148259666, 311.875193224513,
310.725188107302, 307.113608999861, 305.345432183449, 306.866938424095,
296.338500576548, 301.685137467594, 301.496499046973, 292.31953961727,
288.615012611822, 290.213867048504, 285.695949347705, 287.207517193185,
288.916130984771, 284.025547924356, 280.331734920028, 276.455368840947,
283.035881080528, 288.114431753027, 281.591903017038, 277.471364486351,
275.133554284401, 272.650852387413, 276.396523718707, 279.08769762117,
282.910516518289, 287.561712111621, 298.595955828581, 290.299065880292,
280.221814783983, 271.902607398331, 267.655275534974, 187.578839181691,
295.344229054242, 294.793103994916, 299.124436790682, 275.716171689137,
271.748266282198, 274.022120842021, 276.591247188178, 268.405941518524,
267.118504699234, 265.624798023783, 275.240563041295, 266.857200690445,
79.6423144553947, 283.663994869992), IR = c(94.888329799096,
168.205345239028, 43.6012952622392, 155.376871086389, 249.315080590056,
188.485805169097, 140.05749463426, 327.30331523419, 317.749437070833,
335.839690080959, 288.73672165751, 315.9134794, 342.093960744267,
147.913321086785, 265.198319784722, 299.562780926042, 349.640961553857,
170.956328942361, 328.451052432198, 347.751372498958, 334.37511897533,
334.446311627778, 329.363355990612, 326.623001649513, 322.837199274444,
322.997446772569, 325.385474717316, 280.920902051319, 190.673680428353,
126.069364682462, 163.4228148, 153.172728333727, 166.565107412222,
251.82414954041, 241.950038763854, 186.326751968743, 252.239057356328,
114.703921665806, 231.317110343331, 217.123805467431, 263.428218097425,
150.468188479832, 152.846154624771, 164.441859235949, 149.983140035384,
190.64123323394, 86.6026193321907, 449.640322291667, 216.572470091966
), Wind = c(1.98109184856853, 4.53879830464599, 8.70032103138219,
6.59899662613967, 2.86950158330462, 1.91094036908824, 2.49644956157983,
4.51135762214745, 2.42873628334266, 1.82804668840925, 2.79143010703083,
2.16237533031289, 2.15848082990616, 2.82829126926611, 3.04592042806289,
4.43295455205038, 3.64900015248738, 5.93927428289323, 4.568747849922,
4.15613471303208, 2.91637168187178, 2.52179220100977, 1.44870759127444,
1.39712269197199, 2.07052311200698, 3.19886056692388, 4.59176673645728,
4.23987138922819, 6.5241126458074, 7.15729601227273, 5.78232411651958,
4.8622789499446, 4.40757803569404, 6.01049680807786, 4.37623822535244,
5.64634072332915, 6.9869768911053, 6.16325833892184, 4.01858391688531,
5.13520196430042, 4.98398472755042, 5.54085930760014, 6.1472408154439,
2.8608028792402, 3.73845798467388, 4.77812324101398, 2.78512103174882,
3.31994465129167, 2.24169682706943), AirTemp = c(4.40810744394993,
4.83240431381944, 2.53433683929068, 3.31246568041667, 3.30829270725313,
5.59009755125, 5.59340448650904, 7.34151981681723, 7.95149346486111,
6.35076665670605, 9.06164061349096, 10.7704471338194, 10.8565160628214,
7.49149095395833, 8.37798674340278, 6.50827215368056, 5.0225399762335,
7.40747958826389, 9.64073649255911, 9.69248163631944, 12.3917031494788,
14.0608254371528, 15.2186511161335, 17.322914922114, 17.6249810152778,
17.0803095690972, 15.2016485305981, 13.1528769309028, 12.8485860753996,
9.93430037097222, 8.49772086689847, 9.2253200445758, 7.55898443965278,
7.24284858572443, 6.94021240464135, 5.91370547875, 4.38009589235049,
5.42976892055556, 7.28829746376912, 6.63289298236111, 6.79095412268615,
9.45812934520833, 9.2179658081363, 10.4900065421419, 9.56056064826389,
10.5006926291377, 9.92910989490085, 11.8657420520833, 11.0606573877637
), Press = c(1010.94713220445, 1000.91298554167, 987.981428212796,
1003.31839191667, 1010.80608631433, 1010.70622420833, 1014.20480271905,
1018.25909922168, 1017.2977571875, 1017.2116500139, 1014.43729111961,
1016.86667607639, 1017.77638776233, 1017.73254004861, 1017.58831039583,
1023.96083316667, 1023.37822454482, 1018.61740789583, 1017.69460385953,
1019.06393609722, 1019.70283468381, 1021.57185751389, 1022.54906664812,
1019.93420589013, 1015.60680218056, 1013.92687847222, 1018.10282961752,
1017.75759179861, 1011.06972191105, 1000.6753998125, 1006.33157139777,
1010.47605901252, 1004.2360214375, 1003.47128640625, 1005.9544021519,
1002.94591790972, 998.129144311544, 994.845405819444, 996.572536383866,
1007.62132047917, 1015.58149314544, 1015.31391086806, 1014.80282973574,
1014.86646130737, 1011.12184847917, 1007.64412461752, 1008.94791512748,
1016.38731552083, 1014.23599833755), Ts = c(0.0939091805522304,
0.0933571324389885, 0.0926315816934272, 0.0920807064972713,
0.0914849244286843, 0.0906487390808381, 0.0903508008513881,
0.0896503398391888, 0.0894158788365697, 0.0886992027701387,
0.089002314704399, 0.0889635640417059, 0.0885111330762104,
0.0879720536464657, 0.0877271381692247, 0.0866953766257083,
0.0859020961040837, 0.0856618525704464, 0.0853887527876392,
0.0848241204226848, 0.0847934498305695, 0.0842374892345861,
0.0833158824031102, 0.0830544806008765, 0.0829096777186984,
0.0824718703347108, 0.0826933403725865, 0.0822988121621235,
0.0817369399215142, 0.0842685237873781, 0.0888896196011912,
0.079656634577284, 0.0788127760214962, 0.0821017792323535,
0.0734881871639127, 0.0670067820465301, 0.065144627947714,
0.0653888659545473, 0.0744405166847922, 0.0753679790243025,
0.0700098285152706, 0.0717215346483428, 0.0791058326941815,
0.0760274126969679, 0.0757251777215326, 0.0679345115120072,
0.0756495928144236, 0.0670994071000443, 0.0638174503450037
), C = c(8.94065543989075, 8.91870846791228, 8.89129215782166,
8.87041424509199, 8.84686764433126, 8.81516998854457, 8.8084814071784,
8.78498979939825, 8.77801254243485, 8.75556135353215, 8.76169863848835,
8.75623839427317, 8.73659381953759, 8.71875839369915, 8.7081454153551,
8.67125827547341, 8.64042586696951, 8.62643884773293, 8.61505698749588,
8.59531077426103, 8.59085475620887, 8.56693513415321, 8.53362826949292,
8.5263455666875, 8.51701535738585, 8.50192437544613, 8.50643587795999,
8.49224025025525, 8.47229959883608, 8.56396191736222, 8.71907216880554,
8.40708575426135, 8.37898781319225, 8.48450883536676, 8.19834292777621,
8.02742642860397, 7.94335742141408, 7.96038019864108, 8.22636890956846,
8.25191633282365, 8.08596024446269, 8.14084822127661, 8.37247267374788,
8.27175018847621, 8.25980001007453, 8.01532360653014, 8.25581090260999,
7.97597778883369, 7.87850954070042), deltaO = c(-0.539176713575035,
-0.529336754450473, -0.476151386602607, -0.448891301785048,
-0.371478851019715, -0.316365244164706, -0.333759503164495,
-0.20842997042327, -0.158570194489716, -0.139788057771207,
-0.0695596740252039, -0.0670222956453951, -0.0451740767961,
-0.00881028606789499, -0.0196267560794031, 0.00270837075506498,
0.12885503580047, 0.1753403507129, 0.190233674930407, 0.166455606850779,
0.11386372656667, 0.164625003223876, 0.23281525042711, 0.235457512873693,
0.280531394116234, 0.289459150996232, 0.244089148550445,
0.22045630813919, 0.214383555302208, 0.0402743546113934,
-0.0932279238208418, 0.136724628502207, 0.286027328827889,
0.219593839499005, 0.207415604135885, 0.0222562826932507,
-0.0187427504578891, -0.0469711613535759, 0.18669337036061,
0.281291046513154, 0.25224424068066, 0.243330127375477, 0.251581334616514,
0.153326651891512, NaN, 0.285793738567012, 0.229954063047229,
0.30984651152048, 0.0904119306717343), k = c(1.3843960648632,
6.67024147531018, 21.4898676969447, 12.6511158639218, 2.86455163396347,
1.18964832218751, 2.48536575543307, 6.11457188358869, 2.22117060425211,
1.39709711243724, 3.15681260593466, 1.69087035092879, 1.96031515063071,
3.05646023068449, 3.88091903012736, 5.89522588325253, 4.61191456284459,
9.9876497231258, 5.87859816406069, 5.25567516554151, 2.66410131584561,
1.91750845984603, 0.912508517423828, 0.788437993630362, 1.51297375451523,
4.1010391646833, 6.69386108760172, 6.60202002300452, 15.3120378300758,
17.0865393002387, 10.0683520284002, 7.04605349774694, 7.06555793241213,
11.2155892631143, 6.95932652757971, 10.5460039186381, 14.4457642190408,
11.1713965641408, 5.13491665227681, 9.17952853060783, 7.55395359942885,
9.93963153178716, 10.7556273136677, 2.74976182917367, 4.24852415082047,
7.44862825836769, 2.51232305022297, 3.16831051334729, 1.58255842462718
), NCP = c(-6555.51823916664, -30259.5423200574, -93284.1485540249,
-52785.5627897263, -9203.47328702618, -3474.14113092716,
-6643.58632076862, -11084.7222504768, -2779.86321684949,
-1481.582285219, -1974.24446012626, -1018.46398725869, -689.919166266737,
1680.8563208385, -442.391803921574, -180.816469873293, 5330.66701930139,
16192.8444708129, 10544.1353158852, 8370.10647897766, 2991.63246971473,
2741.5747232174, 1716.98452107368, 1723.27625157814, 3806.41762190115,
10674.6146528716, 15783.1240720338, 14337.3594334794, 30669.7204136871,
3257.08033198347, -8574.53718630027, 10409.6993939132, 17974.5471722579,
22284.8034527993, 11849.079774671, 7706.03700970845, 2652.66574996729,
-10421.7431381603, 8448.71926418016, 24212.1390873852, 18754.1407791307,
21358.338661014, 22616.1137584938, 3695.2416322836, NaN,
18437.8290676373, 4903.94862723591, 8770.18358118303, 1206.37283774814
)), .Names = c("Group.1", "datetime", "year", "month", "day",
"hour", "min", "sec", "DOY", "Day", "DayH", "DayD", "Sal", "Temp",
"Den", "Chl", "O2", "ID", "PAR", "CO2", "IR", "Wind", "AirTemp",
"Press", "Ts", "C", "deltaO", "k", "NCP"), row.names = 1324:1372, class
= "data.frame")
A:
If the output you are looking for is that subset of df rows having maximum or minimum Temp among all rows with the same month value then:
subset(df, ave(Temp, month, FUN = function(x) x %in% range(x)) == 1)
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular2. ΠΠ΅ Π·Π°ΠΏΡΡΠΊΠ°Π΅ΡΡΡ ΠΌΠ΅ΡΠΎΠ΄ Π² app.component.ts
Π’ΠΎΠ»ΡΠΊΠΎ Π½Π°ΡΠΈΠ½Π°Ρ ΡΠ°Π·Π±ΠΈΡΠ°ΡΡΡΡ Π² TypeScript ΠΈ Angular2. ΠΠΈΡΡ ΠΏΠ΅ΡΠ²ΡΠΉ ΠΊΠΎΠΌΠΏΠΎΠ½Π΅Π½Ρ ΠΈ Π½Π°ΡΠΊΠ½ΡΠ»ΡΡ Π½Π° ΠΏΡΠΎΠ±Π»Π΅ΠΌΡ, ΠΊΠΎΡΠΎΡΡΡ Π½Π΅ ΡΠ΄Π°Π»ΠΎΡΡ ΡΠ΅ΡΠΈΡΡ Π³ΡΠ³Π»Π΅Π½ΠΈΠ΅ΠΌ.
ΠΡΠΈΠ±ΠΊΡ ΡΠΎΠ·Π΄Π°ΡΡ Π²ΡΠ·ΠΎΠ² ΠΌΠ΅ΡΠΎΠ΄Π° setDateArray. ΠΠ΅Π· Π½Π΅Π³ΠΎ Π²ΡΡ ΠΎΡΡΠ°Π±Π°ΡΡΠ²Π°Π΅Ρ Π½ΠΎΡΠΌΠ°Π»ΡΠ½ΠΎ. ΠΡΠ·ΡΠ²Π°Ρ Π΅Π³ΠΎ Π² ngOnInit, Π½ΠΎ ΠΏΡΠΎΠ±ΠΎΠ²Π°Π» ΠΈ Π² constructor. ΠΡΠΈΠ±ΠΊΠ° Π² ΠΊΠΎΠ½ΡΠΎΠ»ΠΈ ΡΠ°ΠΊΠ°Ρ:
Uncaught Error: Unexpected value 'AppComponent' declared by the module
'AppModule'.
Please add a @Pipe/@Directive/@Component annotation.
at syntaxError (compiler.js:485)
at eval (compiler.js:15282)
at Array.forEach (<anonymous>)
at CompileMetadataResolver.getNgModuleMetadata (compiler.js:15264)
at JitCompiler._loadModules (compiler.js:34398)
at JitCompiler._compileModuleAndComponents (compiler.js:34359)
at JitCompiler.compileModuleAsync (compiler.js:34253)
at CompilerImpl.compileModuleAsync (platform-browser-dynamic.js:239)
at PlatformRef.bootstrapModule (core.js:5561)
at eval (main.ts:11)
ΠΡΠΈΠ²ΠΎΠΆΡ ΠΊΠΎΠ΄. ΠΡΡΠ΅Π·Π°Π» Π²ΡΡ, Π½Π΅ ΠΎΡΠ½ΠΎΡΡΡΠ΅Π΅ΡΡ ΠΊ Π²ΠΎΠΏΡΠΎΡΡ:
app.component.ts:
import { Component, OnInit } from '@angular/core';
import { CanvasSettings } from './canvas-settings';
import { Rate } from './rate';
import { RateService } from './rates.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [RateService]
})
export class DatePoint() {
X: number;
Y: number;
cost: number;
diff: number;
}
export class AppComponent implements OnInit {
title = 'Exchange Rate via Canvas';
bgrdCanvas = new CanvasSettings("bgrdCanvas");
interactiveCanvas = new CanvasSettings("iaCanvas");
rates: Rate[];
dateArray: DatePoint[][][];
sampleProperty: number;
constructor(private _rateService: RateService){}
ngOnInit() {
this.getRates();
this.setDateArray();
console.log(this.dateArray);
console.log(this.rates);
}
getRates() {
this._rateService.getRates().then(rates => this.rates = rates);
}
setDateArray() {
this.sampleProperty = 8;
}
}
A:
Π ΡΠ°ΠΉΠ»Π΅ Π΅ΡΡΡ ΠΎΠ±ΡΡΠ²Π»Π΅Π½ΠΈΠ΅ Π΄Π²ΡΡ
ΠΊΠ»Π°ΡΡΠΎΠ², DatePoint:
export class DatePoint() {
ΠΈ AppComponent:
export class AppComponent implements OnInit {
ΠΈ Π΅ΡΡ Π΅ΡΡΡ Π°Π½Π½ΠΎΡΠ°ΡΠΈΡ @Component:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [RateService]
})
ΠΠΎΡ ΡΠΎΠ»ΡΠΊΠΎ Π°Π½Π½ΠΎΡΠ°ΡΠΈΡ ΠΏΡΠΈΠΌΠ΅Π½ΡΠ΅ΡΡΡ ΠΊ ΠΊΠ»Π°ΡΡΡ, ΠΊΠΎΡΠΎΡΡΠΉ Π½Π΅ΠΏΠΎΡΡΠ΅Π΄ΡΡΠ²Π΅Π½Π½ΠΎ ΡΠ»Π΅Π΄ΡΠ΅Ρ Π·Π° Π°Π½Π½ΠΎΡΠ°ΡΠΈΠ΅ΠΉ, ΠΏΠΎΡΡΠΎΠΌΡ, ΠΊΠ°ΠΊ ΠΌΠΈΠ½ΠΈΠΌΡΠΌ, Π½Π°Π΄ΠΎ ΠΏΠ΅ΡΠ΅Π½Π΅ΡΡΠΈ Π°Π½Π½ΠΎΡΠ°ΡΠΈΠΈ ΠΊ ΡΠΎΠΌΡ ΠΊΠ»Π°ΡΡΡ, Π΄Π»Ρ ΠΊΠΎΡΠΎΡΠΎΠ³ΠΎ ΠΎΠ½Π° ΠΏΡΠ΅Π΄Π½Π°Π·Π½Π°ΡΠ΅Π½Π°:
export class DatePoint() {
...
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [RateService]
})
export class AppComponent implements OnInit {
...
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to follow users who sign in with twitter on my website?
require("twitteroauth/twitteroauth.php");
session_start();
//Site Account
$siteauth = new TwitterOAuth('{Consumer key}', '{Consumer secret}', '{Access token}', '{Access token secret}');
$access_token = $siteauth->getAccessToken($_GET['oauth_verifier']);
$_SESSION['access_token'] = $access_token;
$site_info = $siteauth->get('account/verify_credentials');
var_dump($site_info);
I'm trying to create a $twitteroauth object in order to use the next code:
$follows_faelazo = $siteauth->get('friendships/exists', 'MY-VISTOTR-ACCOUNT', 'user_b' => 'MY-SITE_ACCOUNT'));
if(!$follows_faelazo){
echo 'You are NOT following @faelazo!';
$siteauth->post('friendships/create', array('screen_name' => 'MY-VISTOR'));
}
What I'm trying to do is to follow users who log in to my site using twitter, any idea what's wrong? I'm kind of new with the twitter API.
A:
please go to twitter dev - > My app - > Your App -> settings -> Application type set to Read, Write and Access direct messages.
First you are checking if you have already followed the person. to do this 2 parameters are required ,.
// uname
1.) USER_FOLLOWING
2.) USER_FOLLOWED
Now the 2nd call will be to follow method so you could follow, for this 1 param is req.
//this can be uid/uname
1.) USER_T0_BE_FOLLOWED
For above mentioned please make sure you are calling methods with appropriate param.
e.g.) in the first you need to pass 4 param, client_id, client_secret , outhid, outhsecret
initially before this user needs to authenticate the app.
everything else lloks fine hope you passing proper param thats just one concern.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can you specify which svn branches with git svn?
I think my question is somewhat similar to CaptainPicard's but dissimilar enough that I feel compelled to ask so here goes.
I have an old SVN repository with around 7500 revisions and part of those 7500 revisions are some pretty large .fla files. And these .fla files exist in a number of the branches which have been created. As a result of this my .git directory after import is pretty large, something like 3.5 GB if I get the whole trunk, all the branches and all the tags. In an effort to pair this down some I did another svn clone of just the directory in trunk I wanted to work with but including all branches obviously pulls down all the history and objects for those.
So my question is this, is there some way to tell git to only fetch certain branches. For example only fetch branches starting with some identifier (e.g. mybranch)?
Update for clarity: I know I can point git svn init/clone at a single specific branch. What I want to be able to do is point it at a set of branches. For example, instead of matching branches/* only branches matching mybranchset*
A:
In git svn commands, you can only use the asterisk wildcard to specify all members of a directory (directoryname/*) and not filename variations (fileprefix*). That may change in the future if git svn is revised to make use of SVN's new merge tracking.
Because Git only stores a pointer to a commit for each branch (rather than a duplicate directory of the relevant files), your Git repo will be substantially smaller once you have repacked it, as the anonymous answer says. Unfortuately, Git can't store changesets for your Flash files like it does for text file commits, so they will be duplicated when they change.
I suggest you use
$ git gc --aggressive
to repack your repo. It prunes duplicates and handles more optimizations than git repack.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to force VBA to add new line in XML body?
I am looking for some assistance. I am currently in the middle of building an XML file via VBA.Β IΒ get to the point where I need to add multiple records but the thing is, every record has a different name. It doesn't make sense to me to create it in Excel, column by column because it can be a hundred records or none of them. I don't have an API to that either.
How to force in VBA to create extra line like mentioned in example below?
I downloaded XML directly from the website, and this is how it looks like this:
My code looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<dpiva version="05" xmlns="http://www.at.gov.pt/schemas/dpiva">
<rosto>
<apuramento>
<btBensUELiquidadoDeclarante></btBensUELiquidadoDeclarante>
<btBensUETotal></btBensUETotal>
<btImportDeclarante></btImportDeclarante>
<btOperacoesIsentasComDeducao></btOperacoesIsentasComDeducao>
<btOperacoesIsentasSemDeducao></btOperacoesIsentasSemDeducao>
<btServicosUE></btServicosUE>
<btTaxaNormal></btTaxaNormal>
<btTotal></btTotal>
<btTransmissoesUEIsentas></btTransmissoesUEIsentas>
<ivaARecuperar></ivaARecuperar>
<ivaBensUELiquidadoDeclarante></ivaBensUELiquidadoDeclarante>
<ivaBensUETotal></ivaBensUETotal>
<ivaDedutivelExistenciasTaxaNormal></ivaDedutivelExistenciasTaxaNormal>
<ivaDedutivelImobilizado></ivaDedutivelImobilizado>
<ivaDedutivelOutros></ivaDedutivelOutros>
<ivaDedutivelTotal></ivaDedutivelTotal>
<ivaFavorEstadoTotal></ivaFavorEstadoTotal>
<ivaFavorSujPassivoTotal></ivaFavorSujPassivoTotal>
<ivaImportDeclarante></ivaImportDeclarante>
<ivaServicosUE></ivaServicosUE>
<ivaTaxaNormal></ivaTaxaNormal>
<regularizacoesFavorEstado></regularizacoesFavorEstado>
<regularizacoesFavorSujPassivoNaoComunicadasCobranca></regularizacoesFavorSujPassivoNaoComunicadasCobranca>
<temOperacoesAdquirenteComLiqImposto></temOperacoesAdquirenteComLiqImposto>
<temOperacoesComLiqImposto></temOperacoesComLiqImposto>
<temOperacoesDedutiveis></temOperacoesDedutiveis>
<temOperacoesSemLiqImposto></temOperacoesSemLiqImposto>
</apuramento>
</rosto>
<anexoCampo40R>
<regularizacoes>
<campo40Total></campo40Total>
<listaNum2E3E6>
</listaNum2E3E6>
</regularizacoes>
</anexoCampo40R>
</dpiva>
A:
Using a 'string-based' approach, you can achieve it by simply building a string having the desired xml structure:
Public Sub Create_listaNum2E3E6()
Dim i As Integer
Dim artigoValue As String
Dim s As String
artigoValue = "01"
s = "<listaNum2E3E6>" & vbNewLine
For i = 1 To 10
s = s & " <listaNum2E3E6Item row=" & Chr(34) & i & Chr(34) & ">" & vbNewLine
s = s & " <artigo>" & artigoValue & CStr(i) & "</artigo>" & vbNewLine
s = s & " </listaNum2E3E6Item>" & vbNewLine
Next i
s = s & "<listaNum2E3E6>"
Debug.Print s
End Sub
You can replicate the code to get the <listaNum7Antes2013> tag as well.
The i variable will increment the row attribute, you also need to take care of the data (values of <artigo> tags, in the code there is a dummy value given). You can pass them to the procedure/function body in an array and use LBound and UBound as your iterator (instead of i).
| {
"pile_set_name": "StackExchange"
} |
Q:
In return methods for Arrays, is having the index as an argument bad practice?
So for example :
public static JButton[] getBtnScore(){
return btnScore;
}
public JButton getBtnScore(int i) { /// Is this bad practice?
return btnScore[i];
}
I started doing this before I realised getBtnScore()[i] would work and now I assume it is bad practice, but I haven't had it confirmed anywhere.
A:
No, it's not a bad practice. The problem may lie inside this method.
There are a variety of methods in Java that shows there is no problem passing the index:
java.util.List#get(int index)
java.util.Arrays
binarySearch
copyOfRange
fill
sort
If your question were:
Is this a good design?
It cannot be answerable with the provided info. You would need to explain your problem in depth to help you decide that.
| {
"pile_set_name": "StackExchange"
} |
Q:
Warning "format not a string literal and no format arguments" not appearing on latest gcc version
In my code I use the following line to print a char readbuffer[1]; array (char array with size 1):
printf(readbuffer);
This compiles and works without an issue on my pc (Arch Linux, gcc version 7.3.1+20180406-1). However, when I submitted my assignment containing this code to my instructor, he in fact got a compiler warning compiling my code:
shell.c:89:20: warning: format not a string literal and no format arguments [-Wformat-security]
printf(readbuffer);
He is using the gcc/clang version from 16.04 LTS release. We both used the same compiler flags.
Why is this? Is this suddenly not an issue anymore in the new gcc version? If so, why not?
Just a note: I don't want to know how to solve this issue, but just want to know why the warning is inconsistent over gcc versions.
A:
This is not caused by a difference in GCC versions. Rather, Ubuntu has modified GCC to enable -Wformat -Wformat-security by default. If you pass those options on Arch Linux, you should see the same behaviour there.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a way to disable blinking of cmd Echo command when re-echoing?
I was doing some stuff with .bat files. I also tried some things with echo
commands. One of them was repeatingly echoing and clearing some text. It started blinking. Is there a way to prevent that?
The code:
@echo off
:a
echo @
echo @
echo @
echo @
echo @
cls
goto a
A:
It's blinking because the computer is running through the script too fast that the terminal cannot refresh in time. It'll loop back to a and start again before all the text fully displays, then it also does a clear. You can prevent it by adding wait times.
Here's one that makes your code slowly display nicely:
@echo off
:a
echo @
PING 1.1.1.1 -n 1 -w 1.0 >NUL
echo @
PING 1.1.1.1 -n 1 -w 1.0 >NUL
echo @
PING 1.1.1.1 -n 1 -w 1.0 >NUL
echo @
PING 1.1.1.1 -n 1 -w 1.0 >NUL
echo @
PING 1.1.1.1 -n 1 -w 1.0 >NUL
cls
goto a
Removing all the PINGs between the echos and only have it right after the last echo and before the cls will display them in blocks. Basically the ping forces the script to wait for 1.0 milliseconds. I tried 0.5 but it still blinked. This is where I found the method.
WikiHow also has an article on how to slow down the batch file, I tried some of them but they display some text, which might not be acceptable for you. Which is why I felt ping was the best in this case. 'Sleep' doesn't work on Windows 7 though, looks like it's deprecated.
| {
"pile_set_name": "StackExchange"
} |
Q:
Parse JSON Object within Object
I am using nodejs script to parse one of the json string but not able to figure out how to parse data from onject within object.
Here is JSON Object:
{
"Item":{
"job_change_request":"task0020764",
"id":"a156fc4e-e8d4-424f-a792-0c8cf8e3ca46",
"job_data":{
"location":"sdqa03",
"id":"8f6087cb-b33d-41c4-9a71-e865fd444a1d",
"customer_id":"cust01291",
"change_request":"task0020764"},
"job_requested_time":"2019-08-09T20:54:20.237536",
"job_type":"create_subnet",
"job_status":"completed"},
"ResponseMetadata":{
"RequestId":"3TVF1M3UH7EIHUFJ0KA97F551NVV4KQNSO5AEMVJF66Q9ASUAAJG",
"HTTPStatusCode":200,
"HTTPHeaders":{
"server":"Server",
"date":"Fri, 09 Aug 2019 20:57:23 GMT",
"content-type":"application/x-amz-json-1.0",
"content-length":"385",
"connection":"keep-alive",
"x-amzn-requestid":"3TVF1M3UH7EIHUFJ0KA97F551NVV4KQNSO5AEMVJF66Q9ASUAAJG",
"x-amz-crc32":"1811639896"},
"RetryAttempts":0
}
}
I need to access job_type, job_status and id within job_data.
Anyone can please help me here.
A:
Do you mean like this? You just want to read the values of those three fields?
Using Destructuring
const data = { statuscode: 200, statustext: "OK", responseBody: { Item: { job_change_request: "task0020764", id: "a156fc4e-e8d4-424f-a792-0c8cf8e3ca46", job_data: { location: "sdqa03", id: "8f6087cb-b33d-41c4-9a71-e865fd444a1d", customer_id: "cust01291", change_request: "task0020764" }, job_requested_time: "2019-08-09T20:54:20.237536", job_type: "create_subnet", job_status: "completed" }, ResponseMetadata: { RequestId: "3TVF1M3UH7EIHUFJ0KA97F551NVV4KQNSO5AEMVJF66Q9ASUAAJG", HTTPStatusCode: 200, HTTPHeaders: { server: "Server", date: "Fri, 09 Aug 2019 20:57:23 GMT", "content-type": "application/x-amz-json-1.0", "content-length": "385", connection: "keep-alive", "x-amzn-requestid": "3TVF1M3UH7EIHUFJ0KA97F551NVV4KQNSO5AEMVJF66Q9ASUAAJG", "x-amz-crc32": "1811639896" }, RetryAttempts: 0 } }};
const {
job_type,
job_status,
job_data: { id }
} = data.responseBody.Item;
console.log(job_type, job_status, id);
| {
"pile_set_name": "StackExchange"
} |
Q:
How do you say (adjective) you are wearing cold clothes?
In portuguese there is the word:
Agasalhado
which is used for people who are wearing clothes for cold seasons.
I would like to know if there is an equivalent word.
"Clothed" seemed to be right, although not sure about meaning it is wearing cold clothes or just opposite of naked.
A:
There are many expressions for this. In the UK, we often use the phrase wrap (sb) up:
wrap (sb) up β phrasal verb with wrap
β
to dress in warm clothes, or to dress someone in warm clothes:
Wrap up well - it's cold outside.
Cambridge Dictionary
You can also use:
Make sure that you are wrapped up well.
Make sure that you are well wrapped up.
Stand still while I wrap you up properly.
Needless to say, it is children who are usually "wrapped up". Husbands come a poor second. Wives have to do it themselves.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I determine the type of object an ArrayList iterator will return next?
I have an ArrayList and I am using an iterator to run through it. I need to find out what type of object is next:
Iterator vehicleIterator = vehicleArrayList.iterator();
while(vehicleIterator.hasNext())
{
//How do I find the type of object in the arraylist at this point
// for example, is it a car, bus etc...
}
Thanks
A:
Object o = vehicleIterator.next();
if (o instanceof Car) // Is a car
if (o instanceof Bus) // ...
A:
Firstly, get some generics in there. They have been in Java since 2004. Even the version of Java SE that introduced them has completed its End of Service Life period.
(As @finnw points out, I was forgetting about poor old Java ME. If you have to use Java ME then you will need to eschew generics and cast (but not instanceof often) until it (including deployed devices) makes it into 2004.)
Using instanceof and casting tends to indicate poor design. It would probably better to place into the list an object with an interface the client code can use without tests, and implementations that map to different behaviour for each "real" target of the list. "Every problem in computer science can be solved by adding another level of indirection" ["... except too many levels of indirection."]
A:
One way is to use the getClass() method.
Object obj = vehicleIterator.next();
Class type = obj.getClass();
System.out.println("The type is: " + type.getName());
However, if you're explicitly checking class type there's almost always a better way to write your code using polymorphism or some other OO principle. Code that checks type like this, or using instanceof, would certainly have to be changed if additional types of cars are added.
Without having more information about what you're doing with the type, I'd suggest you have a base type Vehicle that Car, Bus, etc. all inherit from. Give your vehicles the methods they need (override the ones you need to) then just call those methods in your loop.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I somwhow manipulate the character displayed after the user edited an input field
Am I able to manipulate the input mechanism with simple event handlers? Imagine I have a simple textarea
<textarea id='t'></textarea>
Is there a way to change the value of the character which displayed after the user hitted a key?
document.getElementById('t').addEventListener("change", function(ev) {
var ev = ev || window.event;
// something like ev.return("X" + ev.key + "X") ?
});
So that always two X will surround the character at the actual caret position, no matter which key the user originally hit? I know, there is a ev.preventDefault() function, but this does just return nothing.
Every idea and every experience is welcome!
A:
There is still some stuff to polish, e.g. backspace or enter but you get the idea.
document.getElementById('t').addEventListener("keydown", function(ev) {
ev.preventDefault();
let textarea = document.getElementById('t');
let cursorPos = textarea.selectionStart;
let oldText = textarea.value;
let insertText = 'x' + ev.key + 'x';
let newText = [oldText.slice(0, cursorPos), insertText, oldText.slice(cursorPos)].join('');
textarea.value = newText;
});
<textarea id='t'></textarea>
| {
"pile_set_name": "StackExchange"
} |
Q:
Run non-blocking series of jobs
A certain number of jobs needs to be executed in a sequence, such that result of one job is input to another. There's also a loop in one part of job chain. Currently, I'm running this sequency using wait for completition, but I'm going to start this sequence from web service, so I don't want to get stuck waiting for response. I wan't to start the sequence and return.
How can I do that, considering that job's depend on each other?
A:
The typical approach I follow is to use Oozie work flow to chain the sequence of jobs with passing the dependent inputs to them accordingly.
I used a shell script to invoke the oozie job .
I am not sure about the loops within the oozie workflow. but the below link speaks about the way to implement loops within the workflow.Hope it might help you.
http://zapone.org/bernadette/2015/01/05/how-to-loop-in-oozie-using-sub-workflow/
Apart from this the JobControl class is also a good option if the jobs need to be in sequence and it requires less efforts to implement.It would be easy to do loop since it would be fully done with Java code.
http://gandhigeet.blogspot.com/2012/12/hadoop-mapreduce-chaining.html
https://cloudcelebrity.wordpress.com/2012/03/30/how-to-chain-multiple-mapreduce-jobs-in-hadoop/
| {
"pile_set_name": "StackExchange"
} |
Q:
Loop for calculating mean of subset of data frame in r
I have the following data.frame:
> test
a b c
1 1 4 10
2 1 5 11
3 2 6 12
4 2 7 14
5 2 8 15
6 8 9 15
I'd like to write a for loop which will calculate the mean of vector b for each value in vector a. I'd therefore like the following output:
> average
1 2 8
[1] 4.5 7.0 9.0
My attemp so far
subset<-data.frame()
average<-vector(mode="numeric")
for (i in 1:length(test$a)) {
subset<-subset(test,test$a==test$a[i])
average[i]<-mean(subset$b)
}
However, I get the following result
> average
[1] 4.5 4.5 7.0 7.0 7.0 9.0
This should be fairly easy but I unfortunately do not seem to manage it.
Could you please help me out?
Thank you very much in advance.
A:
One line in base R...
tapply(test$b,test$a,mean)
1 2 8
4.5 7.0 9.0
By the way, your code does not work because you are looping over each element of test$a, even duplicated values, rather than just over elements of unique(test$a).
| {
"pile_set_name": "StackExchange"
} |
Q:
Load a form without showing it
Short version: I want to trigger the Form_Load() event without making the form visible. This doesn't work because Show() ignores the current value of the Visible property:
tasksForm.Visible = false;
tasksForm.Show();
Long version: I have a WinForms application with two forms: main and tasks. The main form is always displayed. The user can either click a button to open the tasks form, or click some buttons that just run a task directly without opening the tasks form.
When a user asks to run a task directly, I'd like to just call some public methods on the tasks form without showing it. Unfortunately, the task logic depends on stuff that happens in the Form_Load() event. The only way I can find to trigger Form_Load() is to call Show(). The best I've been able to do is to show the form in the minimized state:
tasksForm.WindowState = FormWindowState.Minimized;
tasksForm.Show();
I suppose the cleanest solution would be to pull the tasks logic out of the tasks form and into a controller class. Then I can use that class from the main form and from the tasks form, and only load the tasks form when I need it visible for the user. However, if it's an easy thing to load the form without displaying it, that would be a smaller change.
A:
Perhaps it should be noted here that you can cause the form's window to be created without showing the form. I think there could be legitimate situations for wanting to do this.
Anyway, good design or not, you can do that like this:
MyForm f = new MyForm();
IntPtr dummy = f.Handle; // forces the form Control to be created
I don't think this will cause Form_Load() to be called, but you will be able to call f.Invoke() at this point (which is what I was trying to do when I stumbled upon this SO question).
A:
It sounds to me like you need to sit down and re-think your approach here. I cannot imagine a single reason your public methods need to be in a form if you are not going to show it. Just make a new class.
A:
I totally agree with Rich B, you need to look at where you are placing your application logic rather than trying to cludge the WinForms mechanisms. All of those operations and data that your Tasks form is exposing should really be in a separate class say some kind of Application Controller or something held by your main form and then used by your tasks form to read and display data when needed but doesn't need a form to be instantiated to exist.
It probably seems a pain to rework it, but you'll be improving the structure of the app and making it more maintainable etc.
| {
"pile_set_name": "StackExchange"
} |
Q:
Maven - Install an artifact to the Nexus repository
I have a problem currently when i run the command mvn install, the artifact is installed in my local repository (i.e. in %HOME/.m2 folder) but not in the Nexus repository.
I know with Nexus i can add an artifact manually using the GUI but is there a way to do install the artifact as part of the mvn command?
A:
What you're seeing is normal behavior in the standard maven lifecycle. The install phase is only supposed to install the artifact locally. You need to run deploy, which comes after install. That's when maven uploads artifacts to a remote repository. The remote repo for deployment is configured in the distribution management section of the pom.
| {
"pile_set_name": "StackExchange"
} |
Q:
MSBuild error: "Could not resolve this reference. Could not locate the assembly..."
I am aware that there is already a question here asking about the exact same error message, but unfortunately the accepted answer doesn't work for me.
I was able to build my current solution successfully earlier this morning, but the build suddenly started failing ~15 minutes ago, with the following error message:
C:\Program Files
(x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(1820,5):
warning MSB3245: Could not resolve this reference. Could not locate
the assembly "MyAssembly.dll". Check to make sure the assembly exists
on disk. If this reference is required by your code, you may get
compilation errors.
Unfortunately for me, this DLL is required by my code. Because it cannot be located, my solution won't compile.
I have tried cleaning and then building my solution again, but that was useless.
I noticed that there was a yellow icon next to this reference, so I removed the reference and then added it again from the exact same location specified inside the <HintPath> tag in my .csproj file. (The location was the \bin\Debug folder.) The yellow icon then disappeared.
However, immediately after I clicked on "Build solution" (in Debug mode), the yellow icon appeared again, and once more I saw the same MSBuild error message, informing me that the DLL could not be located.
How can I resolve this issue?
A:
Add a project reference to the MyAssembly project, not a reference to the compiled output. Right click on the References node of the project which needs MyAssembly.dll, go to "Add Reference", then choose "Solution":
Say you have two projects (X and Y) with Y depending on X. Visual Studio will build X first, then Y.
You can add a reference to X in Y in one of two ways:
Reference the project in the solution
Reference the compiled output in the \bin\Debug folder
If the reference is to the project in the solution, then Visual Studio will know which order to compile your projects (X, then Y in our example).
If the reference is to the output in \bin\Debug, then Visual Studio won't know which order to compile the assemblies, and could try to compile Y before X, not find the file in \bin\Debug, and not compile.
| {
"pile_set_name": "StackExchange"
} |
Q:
dojox.grid.DataGrid Data display.
I have this JSP page. When i run it i don't get any errors. But don't get the data either using Data Grid.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="MyPackage.PopulateTextbox" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
@import "http://localhost:8080/2_8_2012/js/dojo/resources/dojo.css";
@import "http://localhost:8080/2_8_2012/js/dijit/themes/nihilo/nihilo.css";
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/dojo/1.4/dojo/dojo.xd.js" djConfig="isDebug: false, parseOnLoad: true"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript">
dojo.require("dojox.grid.DataGrid");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dojo.data.ItemFileWriteStore");
</script>
<%
String temp1;
PopulateTextbox obj = new PopulateTextbox();
temp1 = obj.method();
request.setAttribute("variable", temp1);
%>
<script type="text/javascript">
dojo.ready(function(){
var myVar = <%= request.getAttribute("variable") %>
var storedata={
identifier:"table1",
label:"name",
items: myVar
};
var store = new dojo.data.ItemFileReadStore({data: storedata});
var gridStructure =[[
{ field: "ID",
name: "ID_Emp",
width: "40%"
},
{
field: "Names",
name: "Name",
width: "40%"
}
]
];
var grid = new dojox.grid.DataGrid({
id: 'grid',
store: store,
structure: gridStructure,
});
//document.createElement('div'));
/*append the new grid to the div*/
//dojo.byId("gridDiv").appendChild(grid.domNode);
/*Call startup() to render the grid*/
grid.startup();
});
</script>
<title>Dojo Data</title>
</head>
<body>
<div jsid="grid" id="mygrid" dojoType="dojox.grid.DataGrid" title="Simple Grid" style="width: 500px; height: 150px;">
</div>
</body>
</html>
When i run this page. And go to View Source i get the following ::
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
@import "http://localhost:8080/2_8_2012/js/dojo/resources/dojo.css";
@import "http://localhost:8080/2_8_2012/js/dijit/themes/nihilo/nihilo.css";
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/dojo/1.4/dojo/dojo.xd.js" djConfig="isDebug: false, parseOnLoad: true"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript">
dojo.require("dojox.grid.DataGrid");
dojo.require("dojo.data.ItemFileReadStore");
</script>
<script type="text/javascript">
var myVar = [{"ID":1,"Names":"Shantanu"},{"ID":2,"Names":"Mayur"},{"ID":3,"Names":"Rohit"},{"ID":4,"Names":"Jasdeep"},{"ID":5,"Names":"Rakesh"}];
var storedata={
identifier:"table1",
label:"name",
items: myvar
};
var gridStructure =[{
cells:[
[
{ field: "ID",
name: "ID_Emp",
width: "40%", styles: 'text-align: right;'
},
{
field: "Names",
name: "Name",
width: "40%", styles: 'text-align: right;'
}
]
]
}];
</script>
<title>Dojo Data</title>
</head>
<body class=nihilo>
<div style="width: 400px; height: 300px;">
<div data-dojo-type="dojo.data.ItemFileReadStore" data-dojo-id="countryStoreForGrid" data-dojo-props="data:storedata"></div>
<div id="grid"
data-dojo-type="dojox.grid.DataGrid"
data-dojo-props="store:countryStoreForGrid,
structure:'gridStructure',
rowsPerPage:40">
</div>
</div>
</body>
</html>
I have got Data in myVar(used for ITEMS in JSP page) as it shows in View source page. But still nothing gets displayed on screen. Is there any error in my HTML BODY tag. ? Please help me with this. thanks.
A:
Try changing
var storedata={
identifier:"table1",
to
var storedata={
identifier:"ID",
Note that identifier specifies the attribute in the item to be used as the unique identifier in the data
see http://livedocs.dojotoolkit.org/dojo/data/ItemFileReadStore for details
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I safely use an un-initialized array in a UITableView and show an empty table
How to prevent crashes when an array is empty and you make a request from a UITableView or UIPickerView?
My current method is to always initialize my arrays before using them with dummy data but I'm not really happy with this method since sometimes the dummy data is not needed and even-worse, sometimes it doesn't even make sense to show the data, in fact most of the time what I want is to show an empty table if there is no data.
For instance if I will be retrieving an array from NSUserDefaults to be used in a UITableView I usually initialize it in the AppDelegate as follow...
AppDelegate.swift:
NSUserDefaults.standardUserDefaults().registerDefaults([
keyMyAarray:["Dummy Data"]// initializing array
])
SomeViewController:
var myArray = read content from NSUserDefaults...
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
fun tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()
cell.textLabel.text = myArray[indexPath.row]
return cell
}
Again, how can I safely use an un-initialized array in a UITableView and show an empty table?
A:
There is no need to put "dummy data" in your array. You can just initilize an empty array. like below
var myArray = [String]()
And in numberOfRowsInSection return myArray.count. If count is zero, cellForRowAtIndexPath will not be called and you are safe to go.
| {
"pile_set_name": "StackExchange"
} |
Q:
Open PDF in gwt frame with highlighted words
how can i open pdf with highlighted words on gwt frame using java or javascript?
i passed url link to the iframe and it loads the pdf but there is no highlight
gwt version 2.5.1
firefox portable v.24
A:
This problem can be solve by changing or installing pdf viewer plugin adobe acrobat reader to the browser.
The pdf viewer of the frame depends on the browsers pdf viewer
setup plugins for chrome
http://blogs.adobe.com/acrolaw/2011/12/get-reader-or-acrobat-to-work-in-chrome-compact-pdf-output-from-chrome/
to test, use this url example to the browser with adobe acrobat plugin
http://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf#search=word
It works on chrome 42 with adobe reader plugin...
| {
"pile_set_name": "StackExchange"
} |
Q:
How to set contact name during Drupal's user registration?
During Drupal's normal user registration process (a user registering their own self, as opposed to an admin registering a user) a Civi contact record is created for that user. That works fine but the only data set for the contact record is the email address. How do I set it up so that the contact's First and Last Names are set during that process?
Currently I have fields on the user profile for first and last names. Is there a hook I can use to save these values to the contact record?
I don't see any configuration options for this sort of thing. I'm kind of mystified by the lack of info on this particular use case when I search the web, as it seems like a standard scenario.
A:
By default CiviCRM comes with a profile called 'Name and Address' which is set to be used for User Registration. First Name and Last Name fields in this profile are, again by default, set as required fields. So when a site visitor goes to user/register they need not only to provide a username/email address/password, but they also see the fields exposed in the Name and Address profile and must provide First/Last name. Maybe you've disabled or removed this profile? Or you can create a new profile that's used for user registration.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using watch with ssh
I have the below commands which is running properly on the local machine.
watch -t -n1 "echo `date '+%Y-%m-%d %H:%M:%S'` | tee -a Time.txt" &>/dev/null &
But when I run it from the remote machine I won't create the expected output i.e. Time.txt is not created and will not be running as a background process.
ssh ipaddress watch -t -n1 "echo `date '+%Y-%m-%d %H:%M:%S'` | tee -a Time.txt" &>/dev/null &
Please help me on this. I have tried multiple options like putting ', " for watch command but it did not helped me out.
A:
No need to use echo to output the result of a sub shell.
No need to use tee to append to a file.
No need to use watch to sleep for one second.
Try this instead.
ssh -t ipaddress 'while sleep 1; do date +%Y-%m-%d\ %H:%M:%S >> Time.txt; done &'
| {
"pile_set_name": "StackExchange"
} |
Q:
Is java Runtime.exec(String[]) platform independent?
I had some code that ran commands through Runtime.getRuntime.exec(String), and it worked on Windows. When I moved the code to Linux, it broke, and the only way of fixing it was to switch to the exec(String[]) version. If I leave things this way, will the code work the same on Windows and Linux, or should I use the exec(String) on Windows and exec(String[]) on Linux?
A:
Use String[] on both.
The answer I gave you before was the result of several miserable hours of debugging a production software running on windows.
After a lot of effort we ( I ) came to the solution posted before ( use String[] )
Since the problems you've got were on Linux, I guess using the array on both will be the best.
BTW. I tried that method with Java 1.4, Since then a new class is available: ProcessBuilder added on Java1.5. I'm not sure what is that all about, but there should be a good reason for it. Take a look at it and read what the difference between that an Runtime.exec is. Probably it will be a better option.
Finally some commands won't work on either platform because they are built in with the shell ( either Windows cmd or bash/sh/ etc ) such as dir or echo and some of those. So I would recommend do extra/extra test on each target platform and add exception handlers for the unsupported commands.
:)
| {
"pile_set_name": "StackExchange"
} |
Q:
AttributeError: module 'scipy.misc' has no attribute 'toimage'
While executing the below code:
scipy.misc.toimage(output * 255, high=255, low=0, cmin=0, cmax=255).save(
params.result_dir + 'final/%5d_00_%d_out.png' % (test_id, ratio))
I get the below error:
AttributeError: module 'scipy.misc' has no attribute 'toimage'
I tried installing Pillow as mentioned here: scipy.misc module has no attribute imread? But the same error persisted. Please help. Thanks.
A:
The scipy.misc.toimage() function was deprecated in Scipy 1.0.0, and was completely removed in version 1.3.0. From the 1.3.0 release notes:
Funtions from scipy.interpolate (spleval, spline, splmake, and spltopp) and functions from scipy.misc (bytescale, fromimage, imfilter, imread, imresize, imrotate, imsave, imshow, toimage) have been removed. The former set has been deprecated since v0.19.0 and the latter has been deprecated since v1.0.0.
The notes link to the v1.1.0 documentation that shows what to use instead; from the scipy.misc.toimage() documentation for v1.1.0:
Use Pillowβs Image.fromarray directly instead.
The function does more work than just Image.fromarray could do, however. You could port the original function:
import numpy as np
from PIL import Image
_errstr = "Mode is unknown or incompatible with input array shape."
def bytescale(data, cmin=None, cmax=None, high=255, low=0):
"""
Byte scales an array (image).
Byte scaling means converting the input image to uint8 dtype and scaling
the range to ``(low, high)`` (default 0-255).
If the input image already has dtype uint8, no scaling is done.
This function is only available if Python Imaging Library (PIL) is installed.
Parameters
----------
data : ndarray
PIL image data array.
cmin : scalar, optional
Bias scaling of small values. Default is ``data.min()``.
cmax : scalar, optional
Bias scaling of large values. Default is ``data.max()``.
high : scalar, optional
Scale max value to `high`. Default is 255.
low : scalar, optional
Scale min value to `low`. Default is 0.
Returns
-------
img_array : uint8 ndarray
The byte-scaled array.
Examples
--------
>>> from scipy.misc import bytescale
>>> img = np.array([[ 91.06794177, 3.39058326, 84.4221549 ],
... [ 73.88003259, 80.91433048, 4.88878881],
... [ 51.53875334, 34.45808177, 27.5873488 ]])
>>> bytescale(img)
array([[255, 0, 236],
[205, 225, 4],
[140, 90, 70]], dtype=uint8)
>>> bytescale(img, high=200, low=100)
array([[200, 100, 192],
[180, 188, 102],
[155, 135, 128]], dtype=uint8)
>>> bytescale(img, cmin=0, cmax=255)
array([[91, 3, 84],
[74, 81, 5],
[52, 34, 28]], dtype=uint8)
"""
if data.dtype == np.uint8:
return data
if high > 255:
raise ValueError("`high` should be less than or equal to 255.")
if low < 0:
raise ValueError("`low` should be greater than or equal to 0.")
if high < low:
raise ValueError("`high` should be greater than or equal to `low`.")
if cmin is None:
cmin = data.min()
if cmax is None:
cmax = data.max()
cscale = cmax - cmin
if cscale < 0:
raise ValueError("`cmax` should be larger than `cmin`.")
elif cscale == 0:
cscale = 1
scale = float(high - low) / cscale
bytedata = (data - cmin) * scale + low
return (bytedata.clip(low, high) + 0.5).astype(np.uint8)
def toimage(arr, high=255, low=0, cmin=None, cmax=None, pal=None,
mode=None, channel_axis=None):
"""Takes a numpy array and returns a PIL image.
This function is only available if Python Imaging Library (PIL) is installed.
The mode of the PIL image depends on the array shape and the `pal` and
`mode` keywords.
For 2-D arrays, if `pal` is a valid (N,3) byte-array giving the RGB values
(from 0 to 255) then ``mode='P'``, otherwise ``mode='L'``, unless mode
is given as 'F' or 'I' in which case a float and/or integer array is made.
.. warning::
This function uses `bytescale` under the hood to rescale images to use
the full (0, 255) range if ``mode`` is one of ``None, 'L', 'P', 'l'``.
It will also cast data for 2-D images to ``uint32`` for ``mode=None``
(which is the default).
Notes
-----
For 3-D arrays, the `channel_axis` argument tells which dimension of the
array holds the channel data.
For 3-D arrays if one of the dimensions is 3, the mode is 'RGB'
by default or 'YCbCr' if selected.
The numpy array must be either 2 dimensional or 3 dimensional.
"""
data = np.asarray(arr)
if np.iscomplexobj(data):
raise ValueError("Cannot convert a complex-valued array.")
shape = list(data.shape)
valid = len(shape) == 2 or ((len(shape) == 3) and
((3 in shape) or (4 in shape)))
if not valid:
raise ValueError("'arr' does not have a suitable array shape for "
"any mode.")
if len(shape) == 2:
shape = (shape[1], shape[0]) # columns show up first
if mode == 'F':
data32 = data.astype(np.float32)
image = Image.frombytes(mode, shape, data32.tostring())
return image
if mode in [None, 'L', 'P']:
bytedata = bytescale(data, high=high, low=low,
cmin=cmin, cmax=cmax)
image = Image.frombytes('L', shape, bytedata.tostring())
if pal is not None:
image.putpalette(np.asarray(pal, dtype=np.uint8).tostring())
# Becomes a mode='P' automagically.
elif mode == 'P': # default gray-scale
pal = (np.arange(0, 256, 1, dtype=np.uint8)[:, np.newaxis] *
np.ones((3,), dtype=np.uint8)[np.newaxis, :])
image.putpalette(np.asarray(pal, dtype=np.uint8).tostring())
return image
if mode == '1': # high input gives threshold for 1
bytedata = (data > high)
image = Image.frombytes('1', shape, bytedata.tostring())
return image
if cmin is None:
cmin = np.amin(np.ravel(data))
if cmax is None:
cmax = np.amax(np.ravel(data))
data = (data*1.0 - cmin)*(high - low)/(cmax - cmin) + low
if mode == 'I':
data32 = data.astype(np.uint32)
image = Image.frombytes(mode, shape, data32.tostring())
else:
raise ValueError(_errstr)
return image
# if here then 3-d array with a 3 or a 4 in the shape length.
# Check for 3 in datacube shape --- 'RGB' or 'YCbCr'
if channel_axis is None:
if (3 in shape):
ca = np.flatnonzero(np.asarray(shape) == 3)[0]
else:
ca = np.flatnonzero(np.asarray(shape) == 4)
if len(ca):
ca = ca[0]
else:
raise ValueError("Could not find channel dimension.")
else:
ca = channel_axis
numch = shape[ca]
if numch not in [3, 4]:
raise ValueError("Channel axis dimension is not valid.")
bytedata = bytescale(data, high=high, low=low, cmin=cmin, cmax=cmax)
if ca == 2:
strdata = bytedata.tostring()
shape = (shape[1], shape[0])
elif ca == 1:
strdata = np.transpose(bytedata, (0, 2, 1)).tostring()
shape = (shape[2], shape[0])
elif ca == 0:
strdata = np.transpose(bytedata, (1, 2, 0)).tostring()
shape = (shape[2], shape[1])
if mode is None:
if numch == 3:
mode = 'RGB'
else:
mode = 'RGBA'
if mode not in ['RGB', 'RGBA', 'YCbCr', 'CMYK']:
raise ValueError(_errstr)
if mode in ['RGB', 'YCbCr']:
if numch != 3:
raise ValueError("Invalid array shape for mode.")
if mode in ['RGBA', 'CMYK']:
if numch != 4:
raise ValueError("Invalid array shape for mode.")
# Here we know data and mode is correct
image = Image.frombytes(mode, shape, strdata)
return image
This could be further simplified based on the actual arguments used; your sample code doesn't use the pal argument, for example.
A:
Current scipy version 1.3.0 doesn't include toimage() 1.3.0 docs here
Try to install scipy 1.2.0 or 1.1.0 1.2.0 docs here with toimage() included.
A:
@Martijn Pieters worked for me but I also found another solution that may suit some people better. You can also use the code below that imports keras.preprocessing.image, array_to_img instead of scipy.misc.toimage which was deprecated in Scipy 1.0.0 as @Martijn Pieters has already mentioned.
So as an example of using keras API to handle converting images:
# example of converting an image with the Keras API
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import array_to_img
# load the image
img = load_img('image.jpg')
print(type(img))
# convert to numpy array
img_array = img_to_array(img)
print(img_array.dtype)
print(img_array.shape)
# convert back to image
img_pil = array_to_img(img_array)
print(type(img_pil))
# show image
fig = plt.figure()
ax = fig.add_subplot()
ax.imshow(img_pil)
and to save an image with keras:
from keras.preprocessing.image import save_img
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
# load image
img = load_img('image.jpg')
# convert image to a numpy array
img_array = img_to_array(img)
# save the image with a new filename
save_img('image_save.jpg', img_array)
# load the image to confirm it was saved correctly
img = load_img('image_save.jpg')
print(type(img))
print(img.format)
print(img.mode)
print(img.size)
| {
"pile_set_name": "StackExchange"
} |
Q:
Ubuntu16.04 install git failed
I used the fellow order to install git on my ubuntu16.04,but meet
the problem.
Can you help me?
A:
Adding this PPA to your system
This will solve the issue.
sudo add-apt-repository ppa:git-core/ppa
sudo apt-get update
sudo apt-get install git
| {
"pile_set_name": "StackExchange"
} |
Q:
Why Java infinite loop is possible? And what recommendations for this
I'm new to Java, but not so to JavaScript.
So, in JS you can't use code like this
while(true){/* do something */}
Because this way browser tab will just get stuck forever. Actually it will be hard to close this tab after infinite loop was invoked.
But in Java, as I saw, it is normal to use code like this
try {
while (true) {
try {
socket.println(data);
} finally {
socket.close();
}
}
} catch (IOException exception){
log(exception);
}
Q1. So, I'm wondering how infinite loop works in Java?
Q2. If I want to listen socket for data for hours, does my Thread will get stuck as browser tab with JavaScript?
Q3. (if Q2 == false) Why Java infinite loop don't consume all of the available resources of Thread as we see in JavaScript?
Q4. Whether this variant of code is more appropriate for socket reading or not because I can miss some important data while "sleeping"?
while(true){
readSocket();
Thread.sleep(10);
}
A:
Q1 - An infinite loop will repeat the code until interrupted somehow. In this case, it's actually not infinite - it uses a trick of a kind. It exists the loop when an exception in thrown.
Q2 - The thread does indeed get stuck in the loop. But in Java (and many other languages) you can just create another thread to run your UI or whatever you need to run at the same time.
Q3 - No, it uses the thread fully.
Q4 - Sleeping will not help you. When the thread is sleeping it just doesn't do anything, so it remains 'stuck'.
| {
"pile_set_name": "StackExchange"
} |
Q:
splitting an RGB image to R,G,B channels - python
I'm working on image processing, I want to know whether this code will split a color image into different channels, and give me the mean. Because when I tried its giving me the image what I'm reading, its giving me the blue, green, red values, and also the mean value. When i try to append it to a list, and try to print it, then the list contains only Zeros'.
This is my code:
b, g, r = cv2.split(re_img1)
ttl = re_img1.size
B = sum(b) / ttl
G = sum(g) / ttl
R = sum(r) / ttl
B_mean1.append(B)
G_mean1.append(G)
R_mean1.append(R)
re_img1 is the resized image(i.e 256x256). Image can be anything. And I'm using the same code in 2 different function, and I'm facing the same problem.
Any suggestions are welcome! Thanks in advance!
A:
If I understand you well, you are trying to calculate the mean of each RGB channel. There are 2 problems in your code:
ttl should be divided by 3 as below, because otherwise it's the number of pixels X channels (ex: for a 256X256 RGB, that would be 196608)
b, g, and r in your code are actually of the numpy.ndarray type, so you should use the appropriate methods to manipulate them, i.e ndarray.sum. Make the sum a float, otherwise you will lose decimals, since the quotient of 2 ints will give you an int.
import cv2
import numpy as np
re_img1 = cv2.imread('re_img1.png')
b, g, r = cv2.split(re_img1)
ttl = re_img1.size / 3 #divide by 3 to get the number of image PIXELS
"""b, g, and r are actually numpy.ndarray types,
so you need to use the appropriate method to sum
all array elements"""
B = float(np.sum(b)) / ttl #convert to float, as B, G, and R will otherwise be int
G = float(np.sum(g)) / ttl
R = float(np.sum(r)) / ttl
B_mean1 = list()
G_mean1 = list()
R_mean1 = list()
B_mean1.append(B)
G_mean1.append(G)
R_mean1.append(R)
Hope that's useful to you.
Cheers!
| {
"pile_set_name": "StackExchange"
} |
Q:
Regex for # and text between # and trailing whitespace
I am trying to get regex for:
Get "#" and all text between "#" and trail ending "\t"(whitespace).
So far I have:
/#[a-zA-Z0-9]\t/
This seems wrong? What can I do to fix it?
A:
If by whitespace you mean actual whitespace (that is spaces, tabs, etc), then this does it:
/#\S+/
(\S is equivalent to [^\s])
If you however meant tabs, when you wrote whitespace, then this:
/#[^\t]+/
| {
"pile_set_name": "StackExchange"
} |
Q:
How to embed base64 image in HTML using pytest-html?
I am using python-appium client and generating a HTML report after the tests are finished. I would like to add the embedded images of the failure tests in the HTML report. The reason to embed the image is that I can access it from the remote machine as well. Here is the code which I tried and doesn't work on another system but locally it works:
@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
pytest_html = item.config.pluginmanager.getplugin('html')
outcome = yield
report = outcome.get_result()
extra = getattr(report, 'extra', [])
if report.when == 'call' or report.when == 'setup':
xfail = hasattr(report, 'wasxfail')
if (report.skipped and xfail) or (report.failed and not xfail):
screenshot = driver.get_screenshot_as_base64()
extra.append(pytest_html.extras.image(screenshot, ''))
report.extra = extra
It seems to me that the encoded image is not generated properly as this is what I can see in the output HTML file:
<td class="extra" colspan="4">
<div class="image"><a href="assets/75870bcbdda50df90d4691fa21d5958b.png"><img src="assets/75870bcbdda50df90d4691fa21d5958b.png"/></a></div>
and I expect "src" to not to end with ".png" and it should be long string of characters. I have no idea how to resolve this.
A:
Your code is correct. However, the standard behaviour of pytest-html is that even if you pass the image as base64 string, it will still store a file in the assets directory. If you want to embed the assets in the report file, you need to pass the --self-contained-html option:
$ pytest --html=report.html --self-contained-html
Or store the option in the pytest.ini:
# pytest.ini (or tox.ini or setup.cfg)
[pytest]
addopts = --self-contained-html
For the sake of completeness, here's the relevant spot in pytest-html readme:
Creating a self-contained report
In order to respect the Content Security Policy (CSP), several assets such as CSS and images are stored separately by default. You can alternatively create a self-contained report, which can be more convenient when sharing your results. This can be done in the following way:
$ pytest --html=report.html --self-contained-html
Images added as files or links are going to be linked as external resources, meaning that the standalone report HTML-file may not display these images as expected.
The plugin will issue a warning when adding files or links to the standalone report.
| {
"pile_set_name": "StackExchange"
} |
Q:
python - order list of dict based on dict values
Lets consider the following list of dicts:
ins=[dict(rank=1, data="Pierre"),dict(rank=3, data="Paul"),dict(rank=2,data="Jacques")]
How can I convert it to the following list:
["Pierre", "Jacques", "Paul"]
that is reordering the items with the rank key and only keeping the data key items?
A:
You can do it fairly easily with comprehensions and the sorted() function's key parameter:
ranked_data = [d['data'] for d in sorted(ins, key=lambda x: x['rank'])]
(You can also use operators.itemgetter('rank') instead of the lambda function, but the lambda is easier to use as an example here.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Start service with crontab linux
I'm trying to create a shell to start a service, or have it be run by cron every time:
00 06 * * * sh /root/teste.sh
In the teste.sh file or in the following command:
service tomcat start
I've also tried with:
/usr/sbin/service tomcat_web start
Neither way worked. Could anyone tell me where I'm going wrong? In the cron logs there is no error. It executes, but I do not know if it is correct or not.
A:
Sorted out.
Test.sh adjusted file:
#!/bin/sh
PROGRAM_START="/orabin01/tomcat/bin/startup.sh"
DAEMON_USER="tomcat"
/bin/su $DAEMON_USER -c "$PROGRAM_START"
| {
"pile_set_name": "StackExchange"
} |
Q:
Alterar Icone JavaFx
Estou tentando alterar o icone mas nΓ£o estou conseguindo.
Codigo:
package olamundojavafx;
import com.sun.javafx.scene.SceneHelper;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
public class OlaMundoJavaFX extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setResizable(false);
stage.setTitle("Teste");
SceneHelper.getSceneAccessor();
stage.show();
Image image = new Image("/Icons/icon.png");
stage.getIcons().add(image);
}
public static void main(String[] args) {
launch(args);
}
}
Mensagem de erro:
Executing C:\Users\Lucas\Documents\NetBeansProjects\OlaMundoJavaFX\dist\run181984282\OlaMundoJavaFX.jar using platform C:\Program Files\Java\jdk1.8.0_111\jre/bin/java
jan 28, 2018 2:54:21 PM javafx.fxml.FXMLLoader$ValueElement processValue
WARNING: Loading FXML document with JavaFX API of version 9.0.1 by JavaFX runtime of version 8.0.111
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: Invalid URL: Invalid URL or resource not found
at javafx.scene.image.Image.validateUrl(Image.java:1118)
at javafx.scene.image.Image.<init>(Image.java:620)
at olamundojavafx.OlaMundoJavaFX.start(OlaMundoJavaFX.java:25)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
... 1 more
Caused by: java.lang.IllegalArgumentException: Invalid URL or resource not found
at javafx.scene.image.Image.validateUrl(Image.java:1110)
... 11 more
Exception running application olamundojavafx.OlaMundoJavaFX
Java Result: 1
A:
Tem duas coisas que chamam a atenΓ§Γ£o no seu stacktrace:
WARNING: Loading FXML document with JavaFX API of version 9.0.1 by
JavaFX runtime of version 8.0.111
Parece que seu cΓ³digo e seu compilador estΓ£o com versΓ΅es diferentes
Caused by: java.lang.IllegalArgumentException: Invalid URL: Invalid
URL or resource not found
Nesse caso ele nΓ£o estΓ‘ encontrando o recurso, vocΓͺ pode tentar desse jeito:
stage.getIcons().add(new Image(getClass().getResourceAsStream("/com/seuprograma/icons/icon.png")));
E confira se o caminho estΓ‘ escrito corretamente.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to retrieve data from the database without knowing the ID number?
I have a database with 3 values: id, credits, and name.
How can I get the credits of "some name" without knowing the id?
I only want to retrieve the users's credits in C#.
A:
You can use an exact match with =:
SELECT * FROM [MyTable] WHERE Name = 'some name'
Or you could use LIKE with % wildcards to do a contains:
SELECT * FROM [MyTable] WHERE Name LIKE '%some name%'
| {
"pile_set_name": "StackExchange"
} |
Q:
PHP SCRIPT - not updating database when executed
I have been playing for quite a few hours, but to no avail, I have been building a script that will allow me to edit info on a webpage in the admin by editing it in a table. I used some tutorials etc, but now it just doesnt want to update the database.
I have three elements:
FIRST ONE: Table of listings - works fine
require_once("models/config.php");
if (!securePage($_SERVER['PHP_SELF'])){die();}
require_once("models/header.php");
// Connects to your Database
mysql_connect("localhost", "cl52-abcdef","abcdef") or die(mysql_error());
mysql_select_db("cl52-abcdef") or die(mysql_error());
$tbl_name="DealOne";
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<table width="400" border="1" cellspacing="0" cellpadding="3">
<tr>
<td colspan="4"><strong>List data from mysql </strong> </td>
</tr>
<tr>
<td align="center"><strong>Desc</strong></td>
<td align="center"><strong>Dest</strong></td>
<td align="center"><strong>RRP</strong></td>
<td align="center"><strong>Price Entry</strong></td>
<td align="center"><strong>Entries Avail</strong></td>
<td align="center"><strong>Update</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><? echo $rows['holdesc1']; ?></td>
<td><? echo $rows['holdest1']; ?></td>
<td><? echo $rows['rrp1']; ?></td>
<td><? echo $rows['cpe1']; ?></td>
<td><? echo $rows['ea1']; ?></td>
<td align="center"><a href="update.php?id=<? echo $rows['id']; ?>">update</a></td>
</tr>
<?php
}
?>
</table>
</td>
</tr>
</table>
<?php
mysql_close();
?>
Second One: where the form is to update the data
require_once("models/config.php");
if (!securePage($_SERVER['PHP_SELF'])){die();}
require_once("models/header.php");
// Connects to your Database
mysql_connect("localhost", "cl52-abcdef","abcdef") or die(mysql_error());
mysql_select_db("cl52-abcdef") or die(mysql_error());
$tbl_name="DealOne";
// get value of id that sent from address bar
$id=$_GET['id'];
// Retrieve data from database
$sql="SELECT * FROM $tbl_name WHERE id='$id'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<form name="form1" method="post" action="update_ac.php">
<td>
<table width="100%" border="0" cellspacing="1" cellpadding="0">
<tr>
<td> </td>
<td colspan="3"><strong>Update data in mysql</strong> </td>
</tr>
<tr>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
</tr>
<tr>
<td align="center"> </td>
<td align="center"><strong>Desc</strong></td>
<td align="center"><strong>Dest</strong></td>
<td align="center"><strong>RRP</strong></td>
<td align="center"><strong>Price Entry</strong></td>
<td align="center"><strong>Entries Avail</strong></td>
</tr>
<tr>
<td> </td>
<td align="center"><input name="desc" type="text" id="holdesc1" value="<? echo $rows['holdesc1']; ?>" size="35">
</td>
<td align="center">
<input name="Destination" type="text" id="holdest1" value="<? echo $rows['holdest1']; ?>" size="35">
</td>
<td>
<input name="RRP" type="text" id="rrp1" value="<? echo $rows['rrp1']; ?>" size="8">
</td>
<td align="center">
<input name="Price per Entry" type="text" id="cpe1" value="<? echo $rows['cpe1']; ?>">
</td>
<td align="center">
<input name="Entries Available" type="text" id="ea1" value="<? echo $rows['ea1']; ?>" size="8">
</td>
</tr>
<tr>
<td> </td>
<td>
<input name="id" type="hidden" id="id" value="<? echo $rows['id']; ?>">
</td>
<td align="center">
<input type="submit" name="Submit" value="Submit">
</td>
<td> </td>
</tr>
</table>
</td>
</form>
</tr>
</table>
<?php
// close connection
mysql_close();
?>
And finally the third one, that I believed would update the database, but it doesnt:
require_once("models/config.php");
if (!securePage($_SERVER['PHP_SELF'])){die();}
require_once("models/header.php");
// Connects to your Database
mysql_connect("localhost", "cl52-abcdef","abcdef") or die(mysql_error());
mysql_select_db("cl52-abcdef") or die(mysql_error());
$tbl_name="DealOne";
// update data in mysql database
$sql="UPDATE $tbl_name SET holdesc1='$holdesc1', holdest1='$holdest1', rrp1='$rrp1', cpe1='$cpe1', ea1='$ea1' WHERE id='$id'";
$result=mysql_query($sql);
// if successfully updated.
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='view_posts.php'>View result</a>";
}
else {
echo "ERROR";
}
?>
Any ideas or suggestions on how to get this to work? Thanks in advance!!
A:
The issue here is that you're rendering a single form to update multiple entries, all of which share attributes with the same id HTML attribute. Your update script can't distinguish between DOM elements with the same id, therefore, your records won't be updated correctly β even if you're identifying each entry by passing the id as a hidden attribute.
A possible solution would be to pass the entry's unique ID as part of each of that entry's attributes' id:
<input name="Price per Entry" type="text" id="cpe1_<? echo $rows['id']; ?>" value="<? echo $rows['cpe1']; ?>">
This creates distinct id elements for each form field. Then, in you update script, you can append the entry's id to the element id attribute so that it correctly associates the entry's attribute with the correct form field.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get infomation of the media file when open an OPENFILENAME dialog
How do i get duration,album,singer,etc of a media file,not only mp3 format but including video file also in MFC, i have opened an OPENFILENAME dialog and want to retrieve the media file' infomation when select on a media file. please help me to get over it. Thank's so much!
A:
Use IShellFolder2::GetDetailsOf
Here is a discussion in a German forum but you can easily extract sample code there.
| {
"pile_set_name": "StackExchange"
} |
Q:
Multiple projects in CruiseControl.NET in the same queue running at the same time
I have multiple projects within CruiseControl.NET (version 1.4.4) that I have assigned to a single Queue...
<project name="Build - A" queue="Q1">
...
</project>
<project name="Build - B" queue="Q1">
...
</project>
<project name="Build - C" queue="Q1">
...
</project>
<project name="Build - D" queue="Q1">
...
</project>
All the projects are non-triggered projects - I (along with every other developer in the division) use CCTray to manually kick off each project. The problem is: If, while project A is running, another user uses Force Build to start another project, it runs concurrently with project A. Even though they are in the same queue. I would have thought that requests within the same queue would be... I don't know, queued and not executed at the same time. I am using the default queue implementation of "UseFirst".
Any idea how to make the projects within the queue behave a little more queue-like? I'd like to add the projects to a timed scheduler, but without any confidence that the projects will not all try to run concurrently and kill my woefully underpowered build machine, I dare not try it.
A:
Odd. I'm using the same configuration you mentioned and its queuing the force build requests.
Try updating ccnet version.
Following is (some of) my ccnet config style (its using preprocessor):
<cruisecontrol
xmlns:cb="urn:ccnet.config.builder" xmlns="http://thoughtworks.org/ccnet/1/5">
<!-- Queue to make sure one build at a time - to avoid same folder SVN locking issues-->
<queue name="Q_Synchronizer" duplicates="UseFirst" />
<!-- ************ Common defs (CC.net pre-processor tags)*********-->
<cb:define local_svn_root="C:\svn"/>
<cb:define remote_svn_root="http://SVN_SERVER:8888/svn/"/>
<cb:define svn_exe="C:\Program Files\Subversion\bin\svn.exe"/>
<cb:define svn_user="SVNUSER" svn_pw="PPPPPWWWW"/>
<cb:define server_url="http://CCNET_SERVER/ccnet"/>
<cb:define build_timeout="900"/>
<cb:define name="msbuild_task">
<msbuild>
<executable>C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe</executable>
<workingDirectory>$(local_svn_root)$(project_solution_path)</workingDirectory>
<projectFile>$(project_solution_file)</projectFile>
<buildArgs>/p:Configuration=$(project_solution_configuration) /p:VCBuildAdditionalOptions="/useenv" /v:diag /t:rebuild</buildArgs>
<timeout>$(build_timeout)</timeout>
</msbuild>
</cb:define>
<cb:define name="svn_dependency">
<svn>
<executable>$(svn_exe)</executable>
<workingDirectory>$(local_svn_root)$(internal_svn_path)</workingDirectory>
<trunkUrl>$(remote_svn_root)$(internal_svn_path)</trunkUrl>
<username>$(svn_user)</username>
<password>$(svn_pw)</password>
<timeout units="minutes">30</timeout>
</svn>
</cb:define>
<cb:define name="project_template" >
<project name="$(project_name)" queue="Q_Synchronizer" queuePriority="$(queuePriority)">
<workingDirectory>$(local_svn_root)$(project_solution_path)</workingDirectory>
<webURL>$(server_url)/server/local/project/$(project_name)/ViewLatestBuildReport.aspx</webURL>
<triggers>
<intervalTrigger seconds="30" name="continuous" buildCondition="IfModificationExists"/>
</triggers>
<sourcecontrol type="multi">
<sourceControls>
<cb:svn_dependency internal_svn_path="$(project_internal_svn_path)"/>
<cb:additional_svn_dependencies/>
</sourceControls>
</sourcecontrol>
<tasks>
<cb:msbuild_tasks/>
</tasks>
<publishers>
<xmllogger logDir="$(local_svn_root)$(project_solution_path)\BuildLogs" />
</publishers>
</project>
</cb:define>
<!-- ************* Projects definition ************-->
<cb:project_template
project_name="Proj A"
project_internal_svn_path="/code/"
project_solution_path="/code/Proj A"
project_solution_file="Proj A.sln"
queuePriority="1"
>
<cb:define name="msbuild_tasks">
<cb:msbuild_task project_solution_configuration="Debug"/>
<cb:msbuild_task project_solution_configuration="Release"/>
</cb:define>
<cb:define name="additional_svn_dependencies">
<cb:svn_dependency internal_svn_path="/bin"/>
</cb:define>
</cb:project_template>
<cb:project_template
project_name="Proj B"
project_internal_svn_path="/code/"
project_solution_path="/code/Proj B"
project_solution_file="Proj B.sln"
queuePriority="1"
>
<cb:define name="msbuild_tasks">
<cb:msbuild_task project_solution_configuration="Debug"/>
<cb:msbuild_task project_solution_configuration="Release"/>
</cb:define>
<cb:define name="additional_svn_dependencies">
<cb:svn_dependency internal_svn_path="/third-party"/>
</cb:define>
</cb:project_template>
</cruisecontrol>
| {
"pile_set_name": "StackExchange"
} |
Q:
Do level 3 crafting patterns drop in Looking For Raid difficulty?
I'm trying to complete my Leatherworking and Enchanting patterns. I've probably done Emerald Nightmare like a dozen times, on LFR, normal and Heroic, but I still am lacking most recipes from raids and dungeons.
Do these even drop on LFR difficulty?
A:
Looking at this enchanting guide, it shows beside each Rank 3 Enchantment that it is found by World Creatures.
But, looking at the actual boss drops for Xavius for example, the rank 3 enchanting options are no longer visible when switching between LFR and normal.
Therefor no, LFR cannot give rank 3 enchantments.
| {
"pile_set_name": "StackExchange"
} |
Q:
.NET Native and RCW overhead
I'm curious about how .NET Native works. Normally when using WinRT classes in managed code, they are invoked through RCW, incurring some overhead due to the interop between managed and unmanaged code. I wonder if there is theoretically the same overhead when the managed code is compiled using .NET Native?
A:
.NET Native interop with WinRT has the same structure as running with CoreCLR or full framework. This is because you have the unavoidable overhead of ensuring the memory for various objects is tracked properly as they are handed accross the boundary. There will always be come irreducible set of things that need to be tracked because of the GC in whichever .NET runtime you're targeting.
That said, the interop code generated for a .NET Native based application will have the benefit of being generated ahead-of-time. This means that it's able to be optimized by the same program optimizer that is part of our C++ compiler so you're going to get the best assembly codegen that Microsoft can offer.
(Disclosure: I work on the .NET Native runtime and compiler team)
| {
"pile_set_name": "StackExchange"
} |
Q:
SyndicationFeed class in Xamarin
I am trying to use the SyndicationFeed class in Xamarin to pull RSS feed data in to an iOS application.
I am using system.ServiceModel - but I cannot find this class. Is SyndicationFeed supported in Xamarin? And if so - where would I find it?
A:
System.ServiceModel.Syndication is not shipped with Xamarin. You can find a lists of shipped assemblies here.
| {
"pile_set_name": "StackExchange"
} |
Q:
html5 fillStyle does not work. shows black regardless of whatever value that i pass it into. What did I do wrong?
why fillStyle does not work in the code?
I console.log the variable that i passed in.
It shows correctly.
though, it still shows a black square instead of the color I would like to pass it into.
What did I do wrong?
const canvas = document.getElementById('tetris');
const draw2D = canvas.getContext("2d");
const ROW = 20;
const COL = 10;
//draw2D.fillStyle = '#000';
const strColor = "#FFFFFF";
const color = "#000000";
draw2D.scale(20, 20);
function drawSquare(x, y, bgColor, lineColor) {
console.log('bg color is: ' + bgColor);
draw2D.fillStyle = bgColor;
draw2D.fillRect(x, y, 1, 1);
console.log('line color is: ' + lineColor);
draw2D.strokeColor = lineColor;
draw2D.strokeRect(x, y, 1, 1);
};
drawSquare(0, 0, color, strColor);
<canvas id="tetris"></canvas>
A:
The issue is you're filling a rect 1 unit large and then stroking it with the default line width of 1 unit so the stroke is completely covering the fill
Also you wrote strokeColor instead of strokeStyle
const canvas = document.getElementById('tetris');
const draw2D = canvas.getContext("2d");
const ROW = 20;
const COL = 10;
//draw2D.fillStyle = '#000';
const strColor = "red";
const color = "green";
draw2D.scale(20, 20);
function drawSquare(x, y, bgColor, lineColor) {
console.log('bg color is: ' + bgColor);
draw2D.fillStyle = bgColor;
draw2D.fillRect(x, y, 1, 1);
console.log('line color is: ' + lineColor);
draw2D.lineWidth = 0.1;
draw2D.strokeStyle = lineColor;
draw2D.strokeRect(x, y, 1, 1);
};
drawSquare(0, 0, color, strColor);
<canvas id="tetris"></canvas>
| {
"pile_set_name": "StackExchange"
} |
Q:
Traefik v2 reverse proxy to a local server outside Docker
I have a simple server written in Python that listens on port 8000 inside a private network (HTTP communication). There is now a requirement to switch to HTTPS communications and every client that sends a request to the server should get authenticated with his own cert/key pair.
I have decided to use Traefik v2 for this job. Please see the block diagram.
Traefik runs as a Docker image on a host that has IP 192.168.56.101. First I wanted to simply forward a HTTP request from a client to Traefik and then to the Python server running outside Docker on port 8000. I would add the TLS functionality when the forwarding is running properly.
However, I can not figure out how to configure Traefik to reverse proxy from i.e. 192.168.56.101/notify?wrn=1 to the Python server 127.0.0.1:8000/notify?wrn=1.
When I try to send the above mentioned request to the server (curl "192.168.56.101/notify?wrn=1") I get "Bad Gateway" as an answer. What am I missing here? This is the first time that I am in contact with Docker and reverse proxy/Traefik. I believe it has something to do with ports but I can not figure it out.
Here is my Traefik configuration:
docker-compose.yml
version: "3.3"
services:
traefik:
image: "traefik:v2.1"
container_name: "traefik"
hostname: "traefik"
ports:
- "80:80"
- "8080:8080"
volumes:
- "/var/run/docker.sock:/var/run/docker.sock:ro"
- "./traefik.yml:/traefik.yml:ro"
traefik.yml
## STATIC CONFIGURATION
log:
level: INFO
api:
insecure: true
dashboard: true
entryPoints:
web:
address: ":80"
providers:
docker:
watch: true
endpoint: "unix:///var/run/docker.sock"
file:
filename: "traefik.yml"
## DYNAMIC CONFIGURATION
http:
routers:
to-local-ip:
rule: "Host(`192.168.56.101`)"
service: to-local-ip
entryPoints:
- web
services:
to-local-ip:
loadBalancer:
servers:
- url: "http://127.0.0.1:8000"
A:
First, 127.0.0.1 will resolve to the traefik container and not to the docker host. You need to provide a private IP of the node and it needs to be accessible form the traefik container.
| {
"pile_set_name": "StackExchange"
} |
Q:
Docker daemon config file on boot2docker / docker-machine / Docker Toolbox
Where can I find docker daemon config file on boot2docker machine?
According to this topic: Dockerfile: Docker build can't download packages: centos->yum, debian/ubuntu->apt-get behind intranet
I want to set '--dns' in DOCKER_OPTS, but I can't find this config file either at /etc/default or anywhere else.
A:
Inside boot2docker (boot2docker ssh) / docker-machine (docker-machine ssh default) , open or create the file /var/lib/boot2docker/profile and add the following line:
EXTRA_ARGS="--dns 192.168.1.145"
Also works for:
EXTRA_ARGS="--insecure-registry myinternaldocker"
After the change you need to restart the docker daemon:
sudo /etc/init.d/docker restart
Or leave boot2docker / docker-machine and restart the entire virtual machine:
boot2docker restart
# for docker machine
docker-machine restart default
Information taken from: https://groups.google.com/d/msg/docker-user/04pAX57WQ7g/_LI-z8iknxYJ
Regards
A:
It took me quite some time to figure this out. If you are using a mac you have to go to a fresh terminal and run:
boot2docker ssh
This will open a new terminal, from there you have to edit or create a file
sudo vi /var/lib/boot2docker/profile
and add the DNS that you would like to add, for example:
DOCKER_OPTS="-dns 8.8.8.8 -dns 8.8.4.4"
After that you need to restart boot2docker. Here I had some issues at the beginning so I close everything and run in a terminal:
boot2docker down
boot2docker up
you can also use:
boot2docker restart
I had to do it twice. After that I started again using the normal boot2docker icon and everything worked.
I hope this helps.
| {
"pile_set_name": "StackExchange"
} |
Q:
Select2 nΓ£o esta inserindo busca
Estou com um pequeno impasse. Apenas um Select2 no meu sistema nΓ£o esta funcionando o campo de busca. Ele faz a implementaΓ§Γ£o do plugin, todavia no campo de busca ele nΓ£o permite inserir os dados. Ele fica separado em um modal.Segue abaixo o trecho de cΓ³digo:
<div class="form-row">
<div class="form-group col-md-12">
<label>Advogado:</label><br/>
<select class="form-control selectDois" name="advogado"style="width: 300px; !important">
<option value="" selected="selected"></option>
@foreach($advogados as $advogado)
<option value="{{$advogado->id}}">{{$advogado->user->nome}}</option>
@endforeach
</select>
</div>
</div>
implemtacao do selectDois
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script>
<script>
//select 2
$(document).ready(function() {
$('.selectDois').select2();
});
</script>
A ideia Γ© essa...Quando eu clico no no botΓ£o, abre uma modal para vincular um advogado, todavia o select dois implementa, mas nao deixa inserir nada no campo de busca....
A:
Basta setar a propriedade dropdownParent com o id do seu dropdown. Coloquei um exemplo usando bootstrap 4 pra vc ter uma ideia de como fica.
$('.selectDois').select2({
width: '100%',
dropdownParent: $('#exampleModal')
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.min.js"></script>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<select class="form-control selectDois">
<option>Valor 1</option>
<option>Valor 2</option>
<option>Valor 3</option>
<option>Valor 4</option>
<option>Valor 5</option>
<option>Valor 6</option>
<option>Valor 7</option>
<option>Valor 8</option>
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Daily cron at specific time on Openshift
I'm trying to run this script at 08:28am everyday, but it didn't work.How do I configure a daily job with a specific time?
#!/bin/bash
time=$(date +%H%M)
if [ $time -eq "0825" ]; then
php /var/lib/openshift/55375281e0b8cdb702000011/app-root/runtime/repo/php/test.php
fi
A:
Put this in your minutely folder
#!/bin/bash
if [ `date +%H:%M` == "08:25" ]
then
######## do stuff here
fi
| {
"pile_set_name": "StackExchange"
} |
Q:
How to save HashMap to a file and load it
I got a major problem. I want to save a HashMap (I'll call it 'map' or 'hm') to a file on the android device the application is running on. I do want to save it on the internal storage.
I know questions like this were asked like 100 before and I tried about 25 of them, but none of them worked.
I got 3 classes, one main class which extends 'Activity' and two other classes, one called 'util'. I wanted to write two methods, to save and load the HashMap, and both of the methods should be in the 'util' class. In the main class I wrote several methods to load the HashMap, put something in it, and save it again.
Till here it shouldn't be difficult to solve my problem, but I want to use the 'save' and 'load' methods in other classes except of the main class too.
I don't know how to get the Context object in other classes as the main class, so I don't know how to call the openFileOutput() method.
In summary: I want to save and load a HashMap to / from a file which I want to create on the internal storage. The method I use should be located in the 'util' class and should be accessible for all other classes, preferred in the static way. I tried many different possibilities but I always get a 'FileNotFoundException'. I hope you can help me.
Some of the methods I used:
try {
FileOutputStream fos = c.openFileOutput(s, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(hm);
oos.flush();
oos.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
At this method I have to use the Context, and I don't know how to get it in other classes. I also get a 'FileNotFoundException'...
String file = The path where my file should be located (I don't know how it should be given, but "data/data/[packagename]/[file]" does not work)
try {
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(hm);
oos.flush();
oos.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
This method doesn't work either, I don't really know which exception I got.
Finally: If you want to help me, please describe how to get each Object you use (Well, except of basic stuff like strings, etc...) and paste your whole solution. I'm really sorry if exactly this question was asked before, I couldn't find it.
Edit
I tried to use the 'this.getApplicationContext().getFilesDir()' method but still getting a 'FileNotFoundException'... Don't know what to do.
A:
If you always call your Util-methods from classes with access to an Activity, just add the Context as a parameter in your method call.
Otherwise, you can create a global Application-object from which you can get a Context. This particular Context does not support creation of Views and other Activity-dependent options, but the openFileOutput()/openFileInput()-methods should be fine since the directory is on Application-level.
To do this you would create a subclass of Application with a static reference to itself:
//In the Application subclass:
static MyApplication instance;
onCreate(){
super.onCreate();
instance = this;
}
public static final MyApplication getInstance(){
return instance;
}
Then you can just call MyApplication.getInstance(); to get a Context.
You will also have to add your application-class in the manifest (With the name-attribute under the application-tag).
Related reading:
Singletons vs ApplicationContext in android
| {
"pile_set_name": "StackExchange"
} |
Q:
iOS8 unable to re-size the modal form sheet after changing the orientation
Actually what i am doing is on iPad i am presenting the modal form
sheet with my own size (520 X 400). It was working fine at first time.
Then when i do rotate (portrait to landscape or landscape to portrait)
my modal form sheet changed to ios default size. Also, i was not able
to change the modal form sheet size again by programatically. Since,
once the orientation changed ios making my (520X400) modal form sheet
to its default size. Any idea how to fix this?.
Note:
When i ran on ios7 device i not am seeing any issue with the
following code. If any thing wrong with my code then please indicate
me. Since i do not know what's wrong with ios8
Here is the code that was i used to change the modal form sheet size:
self.navigationController.view.superview.frame = CGRectMake(200, 220, 400, 605);
A:
finally i figure out a way how to resolve the above one.
Here my solution:
on ios8 just setting the following property to your modal view will resolve the issue
in view did load:
CGRect rect = self.navigationController.view.superview.bounds;
rect.size.width = 605;
rect.size.height = 350;
self.navigationController.view.superview.bounds = rect;
self.navigationController.preferredContentSize = CGSizeMake(605, 350);
before presenting your modal view
your_modal_view.preferredContentSize = CGSizeMake(540.0f, 620.0f) //what ever the size you want
I hope this helps
| {
"pile_set_name": "StackExchange"
} |
Q:
Elasticsearch: Expected field name but got START_OBJECT
I've been trying to run the following query, but every time I run it I receive the following error:
nested: ElasticsearchParseException[Expected field name but got START_OBJECT \"field_value_factor\"]; }]","status":400
Here is the query:
{
"query": {
"function_score": {
"query": {
"bool": {
"should": [{
"match": {
"thread_name": "parenting"
}
}, {
"nested": {
"path": "messages",
"query": {
"bool": {
"should": [{
"match": {
"messages.message_text": "parenting"
}
}]
}
},
"inner_hits": {}
}
}]
}
}
},
"field_value_factor": {
"field": "thread_view"
}
}
}
A:
Your field_value_factor function is misplaced. it should be nested within the functions property. Try this query instead
{
"query": {
"function_score": {
"functions": [
{
"field_value_factor": {
"field": "thread_view"
}
}
],
"query": {
"bool": {
"should": [
{
"match": {
"thread_name": "parenting"
}
},
{
"nested": {
"path": "messages",
"query": {
"bool": {
"should": [
{
"match": {
"messages.message_text": "parenting"
}
}
]
}
},
"inner_hits": {}
}
}
]
}
}
}
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
PosgtreSQL - Change multiple fields collation in one query
I have small database with few text fields with "default" collation. I don't want to recreate database. What is the query to alter all problematic fields at once?
To change the single one I can use
ALTER TABLE a_table_name ALTER a_column_name TYPE text COLLATE a_collate;
A:
There isn't a single SQL command that will do that for you. You can write a loop in a different language, using the results from
SELECT table_name, column_name
FROM information_schema.columns
WHERE table_schema IN ('your_schemas')
AND data_type = 'text'
AND collation_name IS NULL;
or similar.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get screenshot of current foreground app on Android having root priviliges
I'm developing an application that is installed on the system partition and I would like to know if it's possible to get a screenshot of the current foreground application from a service. Of course, the application being any third party app.
I'm not interested in security issues or anything related to that matter. I only want to get a snapshot of the current foreground third party app.
Note: I'm aware of the /system/bin/screencap solution but I'm looking for a more elegant alternative that does everything programmatically.
A:
Months have passed since I asked this question but just now had the time to add this feature. The way to do this is simply by calling screencap -p <file_name_absolute_path> and then grabbing the file. Next is the code I used:
private class WorkerTask extends AsyncTask<String, String, File> {
@Override
protected File doInBackground(String... params) {
File screenshotFile = new File(Environment.getExternalStorageDirectory().getPath(), SCREENSHOT_FILE_NAME);
try {
Process screencap = Runtime.getRuntime().exec("screencap -p " + screenshotFile.getAbsolutePath());
screencap.waitFor();
return screenshotFile;
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(File screenshot_file) {
// Do something with the file.
}
}
Remember to add the <uses-permission android:name="android.permission.READ_FRAME_BUFFER" /> permission to the manifest. Otherwise screenshot.png will be blank.
This is much simpler than what Goran stated and is what I finally used.
Note: It only worked for me when the app is installed on the system partition.
| {
"pile_set_name": "StackExchange"
} |
Q:
Settings for postgres: update existing db or create new
I have a local postgres db, and some query is executed ok on it, but the query does not work on production db. So I get the production db settings to reproduce the error. The settings looks like this:
INSERT INTO pg_settings
("name",setting,unit,category,short_desc,extra_desc,context,vartype,"source",min_val,max_val,enumvals,boot_val,reset_val,sourcefile,sourceline,pending_restart)
VALUES
('debug_assertions', 'off', NULL, 'Preset Options', 'Shows whether the running server has assertion checks enabled.' ,NULL, 'internal', 'bool', 'default', NULL, NULL, NULL, 'off' ,'off' ,NULL, NULL, false),
...
etc
When I'm trying to execute the script, I'm getting
SQL Error [55000]: ERROR: cannot insert into view "pg_settings"
Detail: Views that do not select from a single table or view are not automatically updatable.
Hint: To enable inserting into the view, provide an INSTEAD OF INSERT trigger or an unconditional ON INSERT DO INSTEAD rule.
What I need is either apply this settings to existing local db or create a new one using this settings. How can I do it? Sorry for lame question :(
A:
The documentation for pg_settings explains that
The view pg_settings provides access to run-time parameters of the
server. It is essentially an alternative interface to the SHOW and SET
commands. It also provides access to some facts about each parameter
that are not directly available from SHOW, such as minimum and maximum
values.
and
The pg_settings view cannot be inserted into or deleted from, but it
can be updated
I would use SHOW ALL on both servers and compare the results to see what is different if these settings are indeed relevant to your problem.
Alternatively, you can use this query on both servers:
SELECT * FROM pg_settings ORDER BY category, context, "name"
and then export as text and compare the results.
| {
"pile_set_name": "StackExchange"
} |
Q:
Validating User Input and Type
I have designed an input validation loop in C#, and I would like it to be able to check for the correct input format. I'm not sure, but I think my designed loop is not checking the type of input, just what char is entered. I know I could use a try-catch block, but shouldn't you only use exceptions for exceptional situations? This is not an exceptional situation, because I expect that the user would enter an incorrect value.
Question:
Is there a way I could redesign this loop so that it checks for valid input type as well?
Code:
do
{
Console.Write("Do you wish to enter another complex number?: (Y or N)");
response = char.Parse(Console.ReadLine());
response = char.ToUpper(response);
if (response != 'Y' && response != 'N')
Console.WriteLine("You must respond Y or N!");
} while (response != 'Y' && response != 'N');
A:
Well Console.Readline():
Reads the next line of characters from the standard input stream.
So your data will be of type System.String.
The only other checking you could do is to check that the returned string is of length 1, so you know you have input of the right format. You don't really need the char.Parse as the elements of a string are of type char.
| {
"pile_set_name": "StackExchange"
} |
Q:
Pictures of trigger point muscle fascia
Are there any pictures of an actual trigger point looks like? All I am able to find online are animations.
A:
You could have easily find these using a simple google search, however I will point several out:
See figure 1 of this article for an ultrasound image of a trigger point. Really interesting!
See figure 1 of this article for a schematic representation, and figure 2 for a real image. Although you did not ask for a deeper understanding of this topic, if you want to read more about it I would recommend reading this paper as it covers a lot of aspects (such as pain signals to the brain).
This article covers different imaging techniques and facilitates interpretation by using arrows to point out the trigger points.
If this is not what you are looking for please specify what you mean with "pictures"? (vibration sonoelastography, schematic, ultrasound, etc.) I cannot point you in a direction for real life images (if these even exist).
| {
"pile_set_name": "StackExchange"
} |
Q:
Stacked Bar And Scatter Alignment
I have a chart here: http://jsfiddle.net/wergeld/bx82z/
What I need is for the stacked bars and the scatter points to line up on each other based on the data X-element (county name in this case).
Getting the bars to stack was simple. But as you can see in the example the scatter points show up in the middle of the chart - not on the same x-value as the others.
I suppose I could create a category list (using the county names) but there may be cases where I do not have all 3 data elements for all counties - how to handle that scenario?
I did great the category axis and it is still doing the same thing: http://jsfiddle.net/wergeld/YckwW/
A:
You were not defining the series correctly to achieve what you were wanting. See updated jsfiddle for what I think you are looking for.
In the cases where you are missing a piece of data for one of the countries you could always use null, which simply means there is nothing to display for that data point. See Missing Data Sample for an example. It is case sensitive so make sure that null is all lower case.
| {
"pile_set_name": "StackExchange"
} |
Q:
$\land,\lor$ and $\lnot$ determinate a functionally complete basis
I read that a Boolean algebra is defined by the binary operations $\land$ and $\lor$ and the unary operation $\lnot$ on a set such that $$\varphi\land(\psi\land \chi)=(\varphi\land \psi)\land \chi,\quad \varphi\lor(\psi\lor \chi)=(\varphi\lor \psi)\lor \chi$$
$$\varphi\land \psi=\psi\land \varphi,\quad \varphi\lor \psi=\psi\lor \varphi$$
$$\varphi\lor (\psi\land \chi) = (\varphi\lor \psi) \land (\varphi \lor \chi) ,\quad \varphi \land (\psi\lor \chi) = (\varphi \land \psi) \lor (\varphi \land \chi) $$ $$\varphi \lor (\varphi \land \psi) = \varphi,\quad \varphi\land (\varphi\lor \psi) = \varphi$$ $$\varphi\land 0 =0,\quad \varphi\lor1=1$$ $$\varphi\lor\lnot \varphi=0,\quad \varphi\land\lnot \varphi=1$$
The text states that $\land,\lor$ and $\lnot$ determinates a functionally complete basis in the sense that any function $\{0,1\}^n\to\{0,1\}$ can be expressed by using such operations, and I would like to understand a proof of that.
I have verified that the statement is true for $n=2$. Moreover, I know that the number of all the functions mapping $\{0,1\}^n$ into $\{0,1\}$ are $2^{2^n}$ and I supposed I could verify by induction that we can write all the functions $\{0,1\}^n\to\{0,1\}$ with $\land,\lor$ and $\lnot$, but I am not able to prove it to myself. Could anybody prove it here or give a link to some on line resource? I heartily thank you!
A:
Let $\newcommand{\bbb}{\mathbb{B}}\bbb = \{0,1\}$, then you can express any function $f:\bbb^n\to \bbb$ as
$$f(x_0,x_1,\ldots,x_{n-1}) = \bigvee_{k=0}^{2^{n}-1} g(x_0,k_0)\land \ldots \land g(x_{n-1},k_{n-1}) \land f(k_0,k_1,\ldots,k_{n-1}) $$
where $k_i$ denotes the $i$-th bit of $k$ and
$$g(x_i,k_i) = (x_i \land k_i) \lor (\neg x_i \land \neg k_i) = \begin{cases}x_i & \text{ if }k_i = 1\\\neg x_i &\text{ if } k_i = 0\end{cases}$$
Too give you some intuition,
$k \in \{0,1,\ldots,2^{n}-1\}$ is a short way of iterating over $\bbb^n$.
$f(k_0, k_1, \ldots, k_{n-1})$ is a constant (either $0$ or $1$), because we know all the values of $k_i$.
$g(x_i, k_i)$ effectively encodes "if $x_i$ is equal to $k_i$".
$g(x_0, k_0)\land \ldots\land g(x_{n-1},k_{n-1})$ encodes "if the input is equal to some particular $k$" (remember that $k$ is an iterator, so we know it's value).
If a function $h$ takes only a finite number of inputs $i_1, i_2, \ldots, i_m$ for which returns non-zero values $v_1, v_2, \ldots, v_m$, then \begin{align}h(x) &= [\![x=i_1]\!]\cdot v_1 + \ldots+ [\![x=i_m]\!]\cdot v_m\\ &= [\![x=i_1]\!]\cdot h(i_1) + \ldots+ [\![x=i_m]\!]\cdot h(i_m)\end{align}
where $[\![b]\!]$ is equal to $1$ if $ b$ is true and $0$ otherwise.
Similarly $$f(x_0,\ldots,x_{n-1}) = \begin{cases}f(0,\ldots,0)&\text{ for }x_0=0,\ldots,x_{n-1}=0\\\vdots\\f(1,\ldots,1)&\text{ for }x_0=1,\ldots,x_{n-1}=1\end{cases}$$ that is $$f(x_0,\ldots,x_{n-1})=[\![x_0=0,\ldots,x_{n-1}=0]\!]\cdot f(0,\ldots,0) + \ldots + [\![x_0=1,\ldots,x_{n-1}=1]\!]\cdot f(1,\ldots,1)$$ only that we cannot use $+$, $\cdot$ or $[\![\bullet]\!]$, so instead we use $\lor$, $\land$ and $g$.
I hope this helps $\ddot\smile$
| {
"pile_set_name": "StackExchange"
} |
Q:
How to escape variable in js.erb on Rails 3
I want to alert my instance variable to inspect my variable by
alert('<%= j @user');
but I got error about FIXNUM
but the following code works.
$('#user_div').html('<%= j render(:partial=> 'found_user',
locals: { user: @user }, :formats => :html) %>');
Thanks :P
A:
Add the missing %>
alert('<%= j @user %>');
| {
"pile_set_name": "StackExchange"
} |
Q:
How to achieve this SQL Query ? Min(Date1) and Max(Date2)
This is how my table looks.I want to show only one row for each mcode.
The rule here would be
for AType =start Milestone we have to take MIN(StartDate) and for
AType =Finish Milestone consider the max(EndDate).
PID AId Mcode AType StartDate EndDate
1 ABC1 PM105 Start Milestone 2013-08-12 00:00:00.000 NULL
1 ABC2 PM200 Start Milestone 2015-06-22 00:00:00.000 NULL
1 ABC3 PM200 Start Milestone 2014-08-25 00:00:00.000 NULL
1 ABC4 PM200 Start Milestone 2014-09-29 00:00:00.000 NULL
1 ABC5 PM200 Start Milestone 2014-08-11 00:00:00.000 NULL
1 ABC6 PM200 Start Milestone 2014-08-11 00:00:00.000 NULL
1 ABC7 PM235 Finish Milestone NULL 2015-11-10 00:00:00.000
1 ABC8 PM235 Finish Milestone NULL 2015-11-18 00:00:00.000
1 ABC9 PM235 Finish Milestone NULL 2015-11-10 00:00:00.000
1 ABC10 PM235 Finish Milestone NULL 2015-09-03 00:00:00.000
1 ABC11 PM235 Finish Milestone NULL 2016-02-25 00:00:00.000
1 ABC12 WM310 Finish Milestone NULL 2017-09-29 00:00:00.000
My output should look like:
PID AId Mcode AType StartDate EndDate
1 ABC1 PM105 Start Milestone 2013-08-12 00:00:00.000 NULL
1 ABC6 PM200 Start Milestone 2014-08-11 00:00:00.000 NULL
1 ABC11 PM235 Finish Milestone NULL 2016-02-25 00:00:00.000
1 ABC12 WM310 Finish Milestone NULL 2017-09-29 00:00:00.000
You can use the below sql scripts:
Create table MilestoneData
(
ProjectID int,
ActivityId varchar(10),
MileStoneCode varchar(5),
ActivityType varchar(50),
StartDate datetime,
EndDate Datetime)
insert into MilestoneData values(1,'ABC1','PM105','Start Milestone','2013-08-12 00:00:00.000',NULL)
insert into MilestoneData values(1,'ABC2','PM200','Start Milestone','2015-06-22 00:00:00.000',NULL)
insert into MilestoneData values(1,'ABC3','PM200','Start Milestone','2014-08-25 00:00:00.000',NULL)
insert into MilestoneData values(1,'ABC4','PM200','Start Milestone','2014-09-29 00:00:00.000',NULL)
insert into MilestoneData values(1,'ABC5','PM200','Start Milestone','2014-08-11 00:00:00.000',NULL)
insert into MilestoneData values(1,'ABC6','PM200','Start Milestone','2014-08-11 00:00:00.000',NULL)
insert into MilestoneData values(1,'ABC7','PM235','Finish Milestone',NULL,'2015-11-10 00:00:00.000')
insert into MilestoneData values(1,'ABC8','PM235','Finish Milestone',NULL,'2015-11-18 00:00:00.000')
insert into MilestoneData values(1,'ABC9','PM235','Finish Milestone',NULL,'2015-11-10 00:00:00.000')
insert into MilestoneData values(1,'ABC10','PM235','Finish Milestone',NULL,'2015-09-03 00:00:00.000')
insert into MilestoneData values(1,'ABC11','PM235','Finish Milestone',NULL,'2016-02-25 00:00:00.000')
insert into MilestoneData values(1,'ABC12','WM310','Finish Milestone',NULL,'2017-09-29 00:00:00.000')
A:
Try it like this:
WITH DistinctMileStoneCodes AS
(
SELECT DISTINCT ProjectID,MileStoneCode
FROM MilestoneData
)
SELECT dms.ProjectID
,dms.MileStoneCode
,StartAndFinish.*
FROM DistinctMileStoneCodes AS dms
CROSS APPLY
(
SELECT TOP 1 x.ActivityId,x.ActivityType,x.StartDate,x.EndDate FROM MilestoneData AS x WHERE x.ProjectID=dms.ProjectID AND x.MileStoneCode=dms.MileStoneCode AND ActivityType='Start Milestone' ORDER BY StartDate ASC
UNION SELECT TOP 1 x.ActivityId,x.ActivityType,x.StartDate,x.EndDate FROM MilestoneData AS x WHERE x.ProjectID=dms.ProjectID AND x.MileStoneCode=dms.MileStoneCode AND ActivityType='Finish Milestone' ORDER BY EndDate DESC
) AS StartAndFinish
The result
ProjectID MileStoneCode ActivityID ActivityType StartDate EndDate
1 PM105 ABC1 Start Milestone 2013-08-12 NULL
1 PM200 ABC5 Start Milestone 2014-08-11 NULL
1 PM235 ABC11 Finish Milestone NULL 2016-02-25
1 WM310 ABC12 Finish Milestone NULL 2017-09-29
| {
"pile_set_name": "StackExchange"
} |
Q:
How to append struct into Array? Swift4
Function
import Foundation
struct Foods {
var fid: Int
var fname: String
var hits: Int?
var addr: String?
}
class Food {
func getFoodsById(_ fid: Int) -> [Foods]? {
var foods: Array<Foods>?
let URL_GET_TEAMS:String = "http://jsm0803.iptime.org:81/html/sufoo/getFoodById.php"
let requestURL = URL(string: URL_GET_TEAMS)
let request = NSMutableURLRequest(url: requestURL!)
request.httpMethod = "POST"
//request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let postParameters = "Fid=" + String(fid)
// "name="+teamName!+"&member="+memberCount!;
request.httpBody = postParameters.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest){data, response, error in
if error != nil{
print("error is \(error)")
return;
}
let dataString = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) // ν
μ€νΈμ©
//print(dataString!)
do{
var itemJSON: Dictionary<String, Any>!
itemJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? Dictionary
let items:Array<Dictionary<String, Any>> = itemJSON["Food"] as! Array
for i in 0 ..< items.count{
var food: Foods
let item = items[i]
let fid:Int = item["Fid"] as! Int
let fname: String = item["Fname"] as! String
let hits: Int? = item["Hits"] as? Int
let delegate_image:String? = item["Delegate_Image"]as? String
food = Foods(fid: fid, fname: fname, hits: hits, addr: delegate_image)
foods?.append(food)
print("fid ->", food.fid)
print("fname ->", food.fname)
if let f = food.hits {
print("hits ->", f)
}
else{
print("hits ->", food.hits as Any)
}
if let f = food.addr {
print("delegate_image -> ", f)
}
else {
print("delegate_image -> ", food.addr as Any)
}
print("==============")
print("")
print ("fid ==== ", foods?.first?.fid)
print ("fid ==== ", foods?.last?.fid)
}
}catch {
print(error)
}
}
task.resume()
if let result = foods{
for r in result{
print ("r.fname")
print (r.fname)
}
}
print ("000000")
return foods
}
}
If I run this code in Xcode, I get the result below:
000000
fid -> 140
fname -> λ° νλ°
hits -> nil
delegate_image -> ./pic_data/2309/20180423201954alj
==============
fid ==== nil
fid ==== nil
I want to return [var foods: Array?] value.
But although I made some values of Foods struct and used append function of Array in order to add Foods value into Array, it didn't works. There is no value in Array, only nil.(fid ==== nil)
Thus, it is useless to return that Array.
How can I get right results?
I need to get values like below:
fid ==== 140
fid ==== 140
Please help me to solve this problem.
I think I used Optional wrongly.
A:
You need to change your function implementation adding a completion handler, because your return is called before the for loop is ended:
func getFoodsById(_ fid: Int, completion: (([Foods]?, Error?) -> Void)?) {
//your precedent code
//then when you make the request call the completion
let task = URLSession.shared.dataTask(with: request as URLRequest){data, response, error in
guard error == nil else {
completion?(nil, error)
return
}
let dataString = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue)) // ν
μ€νΈμ©
//print(dataString!)
do{
var itemJSON: Dictionary<String, Any>!
itemJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? Dictionary
let items:Array<Dictionary<String, Any>> = itemJSON["Food"] as! Array
for i in 0 ..< items.count{
var food: Foods
let item = items[i]
let fid:Int = item["Fid"] as! Int
let fname: String = item["Fname"] as! String
let hits: Int? = item["Hits"] as? Int
let delegate_image:String? = item["Delegate_Image"]as? String
food = Foods(fid: fid, fname: fname, hits: hits, addr: delegate_image)
foods?.append(food)
print("fid ->", food.fid)
print("fname ->", food.fname)
if let f = food.hits {
print("hits ->", f)
}
else{
print("hits ->", food.hits as Any)
}
if let f = food.addr {
print("delegate_image -> ", f)
}
else {
print("delegate_image -> ", food.addr as Any)
}
print("==============")
print("")
print ("fid ==== ", foods?.first?.fid)
print ("fid ==== ", foods?.last?.fid)
}
completion?(foods, nil)
}catch {
print(error)
completion?(nil, error)
}
}
task.resume()
}
And you can use it in this way:
//where you have to make the call
self.getFoodsById(yourId) { (foodsArray, error) in
//here you can manage your foods array
}
| {
"pile_set_name": "StackExchange"
} |
Q:
What can be said about this family of functions?
$$\sqrt{a^2+x^2+\left(y-\frac{b}{2}\right)^2}-\sqrt{a^2+x^2+\left(y+\frac{b}{2}\right)^2} = \frac{(2n+1)\pi}{k} \space\space\space\space n \in \mathbb{Z}, \space\space a,b,k > 0$$ This has popped up in finding the locations of destructive interference on a screen for two spherical waves. $a,b,$ and $k$ are fixed, real constants, and $n$ depicts a specific member of the family. Additionally, $y$ is a function of $x$. Is there a convenient way to simplify the above expression to better show the behavior of these curves? The obvious route is to square both sides, isolate the remaining square root, and square again to eliminate all square roots, but I think this distorts a simpler, more enlightening route. Also, note that $a >> b$ can be used if needed.
A:
The equation can be solved for $y(x)$
Note that the solution has to be checked (by bringing it back into the original equation) in order to reject the parasitic solutions due to the squarings.
| {
"pile_set_name": "StackExchange"
} |
Q:
How would i check to see the number of key => value pairing differences in arrays that have similar orders?
For example, if I have two arrays:
$array1 = array('a', 'b', 'c', 'd');
$array2 = array('a', 'c', 'b', 'd');
Assuming that both arrays have similar orders (based on the last and first values), how would I check to see that are two differences in their key value pairings, in their defined orders?
As well as this, how could I return (possibly through another function), where exactly these differences are, by key?
A:
Using array_diff_assoc() with a callback will give you a result of the difference but only with the first arrays keys and values returned. If you want the second arrays differences, reverse the order of the parameters
$array1 = array('a', 'b', 'c', 'd');
$array2 = array('a', 'c', 'b', 'd');
function key_compare ($a, $b) {
if ($a === $b) {
return 0;
}
return ($a > $b)? 1:-1;
})
print_r(array_diff_uassoc($array1,$array2, "key_compare");
Result... Array ( [1] => b [2] => c )
Reversed...
print_r(array_diff_uassoc($array2,$array1, "key_compare");
Result... Array ( [1] => c [2] => b )
| {
"pile_set_name": "StackExchange"
} |
Q:
Changing the KeystoneJs List does not reflect in mongoDB collection
I explain the situation with a simple example and a pseudo code. This is my products schema in KeystoneJs:
ProductSchema.add({
title: { type : String}
})
After adding 1000 products, customer wants me to add a published field to products model, so I changed the code as follow :
ProductSchema.add({
title: { type : String},
published: {
type: Boolean,
default: true
}
})
Now when I want to find all published products I do this:
ProductModel.model.find({published: true});
But this query returns nothing, I know the reason is that when I added published field to productSchema this change is not reflected in the database, Now how to make keystone to add a published field to every document in MongoDB collection?
A:
Changing keystone schema does not affect database, this means next time you create entry, it will populate defaults. I am not sure if it also updates defaults on fetch from db (i remember seeing something similar in code but that may be for something else).
You have to run custom query, either standalone script or as part of your overall app.
| {
"pile_set_name": "StackExchange"
} |
Q:
Separate buttons to change password in user preferences web page
I'm designing a user preferences webpage and now I've placed two save buttons, one to save a new changed password, and other to save other kind of user preferences. My doubt is that I'm not sure if this is the more accessible and usable way to implement it.
I would hear opinions about what is the best option and why, because I haven't found any clear direction about this issue in the web.
A:
Ok so if you've got a form like so:
<form action="YOUR_PAGE" method="POST">
<label>Field 1: </label><input type="text" name="form_field_1" />
<label>Field 2: </label><input type="text" name="form_field_2" />
<input type="submit" name="submitFieldOneOnly" value="Submit field 1" />
<input type="submit" name="submitFieldTwoOnly" value="Submit field 2" />
</form>
You need to run different code depending on which button was pressed you can use the following PHP code on the page your form submits to:
<?php
if (isset($_POST['submitFieldOneOnly'])) {
//Submit button one was pressed
echo $_POST['form_field_1'];
}
if (isset($_POST['submitFieldTwoOnly'])) {
//Submit button two was pressed
echo $_POST['form_field_2'];
}
?>
This should be more than enough to do what you're after.
| {
"pile_set_name": "StackExchange"
} |
Q:
Re-adjusting a binary heap after removing the minimum element
After removing the minimum element in a binary heap, i.e. after removing the root, I understand that the heap must be adjusted in order to maintain the heap property.
But the preferred method for doing this appears to be to assign the last leaf to the root and sift it down.
I'm wondering why we don't take the lesser child of what used to be the root and just keep sifting up all the children? Isn't this the same amount of operations, so why is that "assign-the-last-leaf-to-the-root-and-sift-down" method preferred?
A:
Because you have to keep the tree filled from the left hand side on the last row. Sifting up from the top down, you can't guarantee that the last element you sift upwards will be the rightmost element.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I concatenate output without auto-escaping image_tag?
I have a column in my HTML table with negative and positive numbers. If the number is negative, I display a green arrow next to the number. If it's positive, I display a red arrow next to the number.
The neatest way I can think of doing this is to make a helper called show_with_arrow where I pass in the number. I'm trying to make the helper method pass back something like -6 β or 10 β, the arrows being images.
In my show view:
<td><%= show_with_arrow keyword.compare_to(7.day.ago) %></td>
In my helper class:
def show_with_arrow(position_change)
if position_change > 0
"#{position_change} #{image_tag('bad_arrow.gif')}"
elsif position_change < 0
"#{position_change} #{image_tag('good_arrow.gif')}"
else
position_change
end
end
And it's outputting:
-6 <img alt="Good_arrow" src="/images/good_arrow.gif?1295578152" />
instead of
-6 β
A:
I think you need to use raw() like so:
raw("#{position_change} #{image_tag('bad_arrow.gif')}")
You're on rails 3, right?
| {
"pile_set_name": "StackExchange"
} |
Q:
HTML Open link in New tab button
I am trying to make a button to lead to a page in HTML, except, the thing I use for hosting runs sites inside an iframe, I can make a button to lead to a page, but it will refuse to load because it is in an Iframe, so I need to find a way to make a button, that opens a link in a new tab. But I cannot find any information online on how to do it. My code is available here:https://www.w3schools.com/code/tryit.asp?filename=GFUY1Y8E6WB2. Thanks!
A:
Probabliy the easiest way is to use an <a> tag as follows
<a href="https://website.com" target="_blank"><button>Button Content</button></a>
The target attribute specifies where to open the linked document.
Using "_blank", the linked document in opened in a new window or tab.
More information is available here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why server returns me the Response Code 403 for a valid file in java?
I want to get the Content Length of this file by java:
https://www.subf2m.co/subtitles/farsi_persian-text/SImp4fRrRnBK6j-u2RiPdXSsHSuGVCDLz4XZQLh05FnYmw92n7DZP6KqbHhwp6gfvrxazMManmskHql6va6XEfasUDxGevFRmkWJLjCzsCK50w1lwNajPoMGPTy9ebCC0&name=Q2FwdGFpbiBNYXJ2ZWwgRmFyc2lQZXJzaWFuIGhlYXJpbmcgaW1wYWlyZWQgc3VidGl0bGUgLSBTdWJmMm0gW3N1YmYybS5jb10uemlw
When I insert this url in Firefox or Google Chrome, it downloads a file. but when i want to see that file's size by Java HttpsURlConnection, server returns me Response Code 403 and Content Length -1. why this happens? Thanks
try {
System.out.println("program started -----------------------------------------");
String str_url = "https://www.subf2m.co/subtitles/farsi_persian-text/SImp4fRrRnBK6j-u2RiPdXSsHSuGVCDLz4XZQLh05FnYmw92n7DZP6KqbHhwp6gfvrxazMManmskHql6va6XEfasUDxGevFRmkWJLjCzsCK50w1lwNajPoMGPTy9ebCC0&name=Q2FwdGFpbiBNYXJ2ZWwgRmFyc2lQZXJzaWFuIGhlYXJpbmcgaW1wYWlyZWQgc3VidGl0bGUgLSBTdWJmMm0gW3N1YmYybS5jb10uemlw";
URL url = new URL(str_url);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setConnectTimeout(150000);
con.setReadTimeout(150000);
con.setRequestMethod("HEAD");
con.setInstanceFollowRedirects(false);
con.setRequestProperty("Accept-Encoding", "identity");
con.setRequestProperty("connection", "close");
con.connect();
System.out.println("responseCode: " + con.getResponseCode());
System.out.println("contentLength: " + con.getContentLength());
} catch (IOException e) {
System.out.println("error | " + e.toString());
e.printStackTrace();
}
output:
program started -----------------------------------------
responseCode: 403
contentLength: -1
A:
The default Java user-agent is blocked by some online services (most notably, Cloudflare). You need to set the User-Agent header to something else.
con.setRequestProperty("User-Agent", "My-User-Agent");
In my experience, it doesn't matter what you set it to, as long as it's not the default one:
con.setRequestProperty("User-Agent", "aaa"); // works perfectly fine
EDIT: looks like this site uses Cloudflare with DDoS protection active - your code won't run the JavaScript challenge needed to actually get the content of the file.
| {
"pile_set_name": "StackExchange"
} |
Q:
Git - How to go back in history and create a commit between two commits
I have a question of how to go back to git and produce new versions from previous versions.
For example, let's say I have the following commit history in the main branch:
v1.0 - v1.1 - v1.2 - v2.0 - v3.0
Now let's suppose I have a client that is version v1.2 and need to fix a bug, however it is not yet able to go to version 2.0 onwards.
If I go back to version 1.2 using the git checkout command, create a branch and work on the fix as I do to commit to an old version?
I would like my sequence to look like this:
v1.0 - v1.1 - v1.2 - v1.3 - v2.0 - v3.0
Remembering that I am aware that the v1.3 fix will not be in v2.0 and v3.0
A:
Remembering that I am aware that the v1.3 fix will not be in v2.0 and v3.0
That's not what you drew, though. To draw that, let's re-draw this as a series of commitsβthe things that Git actually stores:
tag:v1.0
|
v tag:v1.1
...--β--β |
\ v tag:v1.2
β--...--β |
\ v tag:v2.0
β--β--...--β |
\ v tag:v3.0
β--...--β |
\ v
β--...--β
\
β--... <-- master
Here, master is a branch name, identifying the latest commit on branch master. Each of the various tag:... is a tag name, identifying the specific commit that constitutes the version released to someone.
You now want to go back and create a new branch name pointing to the same commit that tag:v1.2 points to. That's fine:
tag:v1.0
|
v tag:v1.1
...--β--β |
\ v tag:v1.2
β--...--β |
\ v tag:v2.0
β--β--...--β <------|------- release/1
\ v tag:v3.0
β--...--β |
\ v
β--...--β
\
β--... <-- master
Each solid β here stands in for a commit. Commits are real, actual, and very-concrete things in Git: each one has its own unique hash ID. Tag names and branch names are less-solid because they can be moved around. Tag names shouldn't be moved; moving one is kind of a violation of how they should be used. Branch names, however, move on their own. You might now git checkout release/1 to get the commit identified by both the names tag:v1.2 and release/1, and then make a new commit, which we'll represent as β here:
tag:v1.0
|
v tag:v1.1
...--β--β |
\ v tag:v1.2
β--...--β |
\ v tag:v2.0
β--β--...--β--β <---|------- release/1
\ v tag:v3.0
β--...--β |
\ v
β--...--β
\
β--... <-- master
Note how nothing else changed. Exactly two things did change:
you have a new commit β, and
your name release/1 identifies this new commit, because the branch name you have checked out moves automatically when you create a new commit.
This new commit is not part of the chain of commits that lead up to master. It stands on its own. You can make a new tag to remember its hash ID for the future, because hash IDs are big and ugly and not memorable to humans, if you like. You can make more new commits before you tag this one, if you like.
This is what version control is all about, in the end: it keeps every commit you ever made, so that you can go back to it, look at it, test out bugs on it, construct fixes to it if needed, and continue development.
If your question is "how", you've already answered it yourself: create a branch name pointing to the desired commit, then make new commits. For instance:
git checkout -b release/1 v1.2
and then begin working.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using a RouteCollectionProvider in Silex
I have a custom Silex\RouteCollection which I want to register...
class RouteCollectionProvider extends RouteCollection
{
public function __construct() {
$this->add(
'Index',
new Route('/', array(
'method' => 'get',
'controller' => 'index',
'action' => 'index'
)
));
}
}
...during the bootstrapping:
$app = new Silex\Application();
/** here **/
$app->run();
I could use:
$app = new Silex\Application();
$routes = new RouteCollectionProvider();
foreach ($routes->getIterator() as $route) {
$defaults = $route->getDefaults();
$pattern = $route->getPath();
$callback = 'Controller\\'
. ucfirst($defaults['controller'])
. 'Controller::'
. $defaults['action']
. 'Action';
$app->get($pattern, $callback);
}
$app->run();
I don't like having the initialization of those routes right in there.
Do you know any spot in Silex, where this does fit better?
I cannot use $app->register() because it's getting called too late and the routes won't get active in there.
Maybe there is an event I can use with
$app->on('beforeCompileRoutesOrSomething', function() use ($app) {
// initialize routes
}
Or a hook in the Dispatcher?
My aim is to not have a big collection of $app->get() or $app->post() in there. I also know I can ->mount() a controller but then still I have all my get definitions in my bootstrap and not in a Provider.
A:
This post solves the problem: Scaling Silex pt. 2.
$app = new Application;
$app->extend('routes', function (RouteCollection $routes, Application $app) {
$routes->addCollection(new MyCustomRouteCollection);
return $routes;
});
$app->run();
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.