source
list | text
stringlengths 99
98.5k
|
---|---|
[
"ru.stackoverflow",
"0000036086.txt"
] |
Q:
Как запретить доступ к файлам некоторых расширений в .htaccess?
Как запретить доступ к файлам некоторых расширений в .htaccess?
A:
<FilesMatch "config.php">
Order Deny,Allow
Deny from all
</FilesMatch>
запрещает доступ к файлу config.php
<FilesMatch ".(gif|jpe?g|png)$">
Order Deny,Allow
Deny from all
</Files>
запрет к картинкам
|
[
"scifi.stackexchange",
"0000172842.txt"
] |
Q:
Trying to identify story where aliens copied a machine without knowing about electricity
I read this story decades ago (probably between 1975 and 1990). I remember it only vaguely. If I recall correctly it involved humans exploring the galaxy with an alien contact policy reminiscent of Star Trek's Prime Directive.
In the story, aliens on one of these explored planets somehow acquired a piece of human equipment, or perhaps plans for the equipment, and attempted to make their own copy. They duplicated it with great care, complete with the cord that plugged into the wall. However, they knew nothing about electricity, so the socket in the wall wasn't wired to anything. They couldn't figure out why their machine didn't work.
The machine might have been a weapon, but again I'm not sure. I'm pretty certain it was large, as in a fixed installation, or at least too big for someone to carry.
I think it was a short story, but it's possible it was part of a novel. It was told from a human's point of view. Probably third person, but I can't remember for sure. If I recall correctly, the human was engaged by the aliens to help them figure out why the machine didn't work.
Can anyone identify this story for me? Please?
A:
A similar episode is found (if memory serves) in Gordon Dickson's
The Space Winners. A key component (vacuum tube?) was
completely misunderstood. It was electronics, though, not
electricity per se, that the aliens weren't aware of.
|
[
"stackoverflow",
"0009727256.txt"
] |
Q:
Seeded random number
Ive been wondering for some time. Is there a good (And fast) way to make an number random while its seeded?
is there a good algorithm to convert one number into a seemingly random number.
A little illustration:
specialrand(1) = 8
specialrand(2) = 5
specialrand(3) = 2
specialrand(4) = 5
specialrand(5) = 1
specialrand(1) = 8
specialrand(4) = 5
specialrand(1) = 8
It would be very nice if the output could also be huge numbers.
As a note: I don't want to fill a array and randomize the numbers because I want to be able to feed it huge difference of numbers because I want the same output whenever I restart the program
A:
You're not looking for a seeded random number. Instead what I think you're looking for is a hashing function. If you put in the same input and get the same output, that's not random.
If you're looking to generate a sequence of random numbers for a run, but have the same sequence generate from run to run, you can use a random number generator that generates the same sequence given the same seed value.
Thats how most basic pRNG's work. There are more cryptographically secure RNG's out there, but your standard Math.rand() should work to accomplish your needs.
|
[
"stackoverflow",
"0043620116.txt"
] |
Q:
css position pseudo elements stacking
Hello I use before & after in my element and it's work well, but the problem that when I set background-color for section the before & after will be disappear I know that this problem appear because of z-index: -1and I know that we can't stacking child element (before & after) above the parent element so what is the solution, I don't need to create any new elements to do this trick:
It's what I need:
section{
height:400px;
padding:50px 0;
background-color:#00fb8f;
}
.box-shadow-1{
height:200px;
background-color:#e8e8e8;
position:relative;
}
.box-shadow-1:before,
.box-shadow-1:after {
z-index: -1;
position: absolute;
content: "";
bottom: 25px;
left: 10px;
width: 50%;
top: 80%;
max-width: 300px;
background-color:#ff0000;
-moz-box-shadow: 0 20px 20px #777;
-webkit-box-shadow: 0 20px 20px #777;
box-shadow: 0 20px 20px #777;
-webkit-transform: rotate(-8deg);
-moz-transform: rotate(-8deg);
-o-transform: rotate(-8deg);
-ms-transform: rotate(-8deg);
transform: rotate(-8deg);
}
.box-shadow-1:after {
-webkit-transform: rotate(8deg);
-moz-transform: rotate(8deg);
-o-transform: rotate(8deg);
-ms-transform: rotate(8deg);
transform: rotate(8deg);
right: 10px;
left: auto;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<section>
<div class="container">
<div class="row">
<div class="col-lg-11 col-lg-offset-1">
<div class="box-shadow-1">
Hello World
</div>
</div>
</div>
</div>
</section>
A:
You need to give the box-shadow-1's parent a z-index, like this
.col-lg-11.col-lg-offset-1 {
position:relative;
z-index: 0;
}
I also adjusted your pseudo elements a little, so you get the shadow like the posted image
Stack snippet
section{
height:400px;
padding:30px 0;
background-color:#e8e8e8;
}
.col-lg-11.col-lg-offset-1 { /* added rule */
position:relative;
z-index: 0;
}
.box-shadow-1{
height:150px;
background-color:#00fb8f;
position:relative;
}
.box-shadow-1:before,
.box-shadow-1:after {
z-index: -1;
position: absolute;
content: "";
bottom: 25px;
left: 10px;
width: 50%;
height: 20px;
max-width: 300px;
background-color:#ff0000;
-moz-box-shadow: 0 30px 20px #777;
-webkit-box-shadow: 0 30px 20px #777;
box-shadow: 0 30px 20px #777;
-webkit-transform: rotate(-8deg);
-moz-transform: rotate(-8deg);
-o-transform: rotate(-8deg);
-ms-transform: rotate(-8deg);
transform: rotate(-8deg);
}
.box-shadow-1:after {
-webkit-transform: rotate(8deg);
-moz-transform: rotate(8deg);
-o-transform: rotate(8deg);
-ms-transform: rotate(8deg);
transform: rotate(8deg);
right: 10px;
left: auto;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<section>
<div class="container">
<div class="row">
<div class="col-lg-11 col-lg-offset-1">
<div class="box-shadow-1">
Hello World
</div>
</div>
</div>
</div>
</section>
|
[
"stackoverflow",
"0020286725.txt"
] |
Q:
Ajax Calender Extender issue
i have textbox in which i want to store the selected date of calender. for this purpose i have used ajax calender extender. and set the target control property to textbox id. but when i click on button of same page then i lost the seleted date (i mean i lost the textvalue) but i want to the selected date after clicking on button..
my code is as
<td>
<asp:TextBox ID="txtDate" runat="server" ReadOnly="true"></asp:TextBox>
</td>
<td>
<asp:ImageButton ID="imgCalender" runat="server" ImageUrl="~/Images/Calendar.png" ToolTip="Select a Date" />
<asp:CalendarExtender ID="calShow" runat="server" PopupButtonID="imgCalender" PopupPosition="BottomLeft" TargetControlID="txtDate" OnClientDateSelectionChanged="CheckForPastDate"></asp:CalendarExtender>
</td>
and also i want when user try to select a date which is greater than the current date+20 days then text box should be empty. means user have to select again a proper date.
Javascript
var selectedDate = new Date();
selectedDate = sender._selectedDate;
var todayDate = new Date();
if (selectedDate.getDateOnly() <= todayDate.getDateOnly())
{
alert('Date Cannot be in the past or current date');
sender._textbox.set_Value(null);
}
else if(selectedDate.getDateOnly() > todayDate.getDateOnly())
{
// why is this here?
}
A:
within the js method just do something like
var today = new Date();
var twentyDays = new Date();
twentyDays.setDate(today.getDate()+20);
if (selectedDate.getDateOnly() <= todayDate.getDateOnly())
{
alert('Date Cannot be in the past or current date');
sender._textbox.set_Value(null);
}
else if(selectedDate.getDateOnly() > twentyDays.getDateOnly())
{
alert('this is more than 20 days');
sender._textbox.set_Value(null);
return;
}
Update 02/12/2013
I am not sure what the getDateOnly() method is or does and that seemed to be causing me issues.
The script below is what I put together to test scenarios and works. simply adjust the daysModifier variable to test.
var daysModifier = 23;
var selectedDate = new Date();
selectedDate.setDate(selectedDate.getDate() + daysModifier);
var today = new Date();
var twentyDays = new Date();
twentyDays.setDate(today.getDate()+20);
document.write(today);
document.write("<br />");
document.write(selectedDate);
document.write("<br />");
document.write(twentyDays);
if (selectedDate <= today)
{
alert('Date cannot be in the past or current date');
}
else if(selectedDate > twentyDays)
{
alert('this is more than 20 days');
}
|
[
"stackoverflow",
"0025143226.txt"
] |
Q:
Replace delimiter in csv that is not between square brackets
I have a lot of csv files that I am having trouble reading since the delimiter is ',' and one of the fields is a list with comma separated values in square brackets. As an example:
first,last,list
John,Doe,['foo','234','&3bar']
Johnny,Does,['foofo','abc234','d%9lk','other']
I would like to change the delimiter to '|' (or whatever else) to get:
first|last|list
John|Doe|['foo','234','&3bar']
Johnny|Does|['foofo','abc234','d%9lk','other']
How can I do this? I'm trying to use sed right now, but anything that works is fine.
A:
I don't know it could be possible through sed or awk but you could do this easily through perl.
$ perl -pe 's/\[.*?\](*SKIP)(*F)|,/|/g' file
first|last|list
John|Doe|['foo','234','&3bar']
Johnny|Does|['foofo','abc234','d%9lk','other']
Run the below command to save the changes made to that file.
perl -i -pe 's/\[.*?\](*SKIP)(*F)|,/|/g' file
|
[
"blender.stackexchange",
"0000029248.txt"
] |
Q:
Creating a spherical array
Keep in mind that I am almost completely new to blender.
I was wondering how to create a spherical array. I have Googled and Googled, but I can only find ways to make circular arrays (two dimensional arrays).
Basically I want a way to make an array that simulates the proton and neutron structure of an atom. Atoms have both protons and neutrons in the nucleus, and I want a way to reproduce this using blender.
As you can see in this picture, the Uranium-235 atom has a heck-of-a-lot of protons and neutrons (ignore the one neutron shooting off due to nuclear fission). I do not need the disorganization of the actual protons and neutrons, I just want an array to simulate the structural look.
Thanks.
(Note: I am using the latest version of blender (2.74)
A:
Add a sphere, copy it, scale it down in edit mode
Select the big sphere, go to the Object panel, under Duplication select Verts
Select the small sphere, hold shift, then select the big sphere. Hit CTRL+P and set the paren to Vertex
Result should look like that
You can now go select the big sphere again and go to edit mode, select all vertices. Use the "Randomize" option, I used a setting of 0.06.
You can use the Object info -> Random input together with a Math node to give them different colors.
This isn't an accurate representation of an atom I guess, but you said it's about simplicity and the visualisation aspect.
P.S.: If you are worried about the top / bottom of the result, as there are more spheres, you can try another type of sphere for the big sphere, e.g. the icosphere, that has an even distribution of vertices.
A:
You are looking for a spherical array, but maybe you would settle for a set of points which are spread out evenly over the surface of a sphere?
If you are comfortable with the Math, you can easily script a vertex based object which can act as a 'donor of vectors/3d points' to place instances of smaller spheres (Neutrons, Protons).
import bpy
import random
import math
def fibonacci_sphere(samples, rseed):
# http://stackoverflow.com/a/26127012/1243487
rnd = 1.
random.seed(rseed)
rnd = random.random() * samples
points = []
offset = 2./samples
increment = math.pi * (3. - math.sqrt(5.));
for i in range(samples):
y = ((i * offset) - 1) + (offset / 2);
r = math.sqrt(1 - pow(y,2))
phi = ((i + rnd) % samples) * increment
x = math.cos(phi) * r
z = math.sin(phi) * r
points.append([x,y,z])
return points
verts = fibonacci_sphere(120, rseed=20)
mesh = bpy.data.meshes.new("mesh_name")
mesh.from_pydata(vertices=verts, edges=[], faces=[])
mesh.update()
obj = bpy.data.objects.new("obj_name", mesh)
scene = bpy.context.scene
scene.objects.link(obj)
This bit of code when Run from the Text Editor, will produce a sphere of points based on fibonacci. This might give you the approximation.
Mapping the spheres onto the points.
The script creates a points mesh named "obj_name" and adds it to the scene, in the object properties set duplication type to Verts,
Create the Neutron/Proton representative sphere on the same origin as the points mesh, (I like to use a Object->Surface->NURBS Sphere)
Set the Parent of the sphere to the points mesh.
This way you get a kind of Donor / Recipient relationship between the points mesh and the Neutron/Proton spheres.
When you render, the original NURBS sphere at the origin won't be visible, in contrast to when you are viewing in the 3d viewport, you'll see it all the time.
Sverchok
The Sverchok addon can be be used for this kind of visualization: https://blender.stackexchange.com/a/28792/47 . It's a Free and open source modular, node based geometry system built on Blender's custom Python Nodes API.
The same script as above exists inside Sverchok as a scripted node, meaning you can adjust a slider to increase or decrease the number of points (samples), and set a different Seed value (random starting point) without having to delete the object and run the script again. Then you connect other nodes to operate on the scale of the vectors it produces, then you can pick vectors by some logic gate and separate them into 2 different meshes, then assign the different spheres to represent Neutrons and Protons.
Within the space of 2 minutes I made this: (full disclosure I'm a contributor to Sverchok.. but with practice anyone can blaze through it)
The sphere of points is indexed, and i'm splitting them up by by the boolean result of index % 2. if that's 1 it goes into one mesh, else it goes into the other. The image above is just drawing openGL, there's no scene mesh yet.
We have nodes that do output meshes to the scene, called Bmesh Nodes
rather than every second vector, you can generate a random number for each vector and if it's larger than some value (between 0.0, 1.0), it goes into one mesh, else the other.
Here's the blend for that.
With a small modification you can even push the vectors away from the origin in a pulsating way.. drag the seed value or animate it
Though I imagine it behaves very differently, twisting and contorting..
|
[
"stackoverflow",
"0020519486.txt"
] |
Q:
How can i bind an extra click event to a hyperlink using jQuery 1.4?
I need to loop trough all email-links on a webpage. Then add GA tracking to each one of them. So below i have just been testing to get the binding to work, but that fails for some reason and tried to open the email client when i view the page.
var emails = $('a[href^="mailto:"]');
for (var i = 0; i < emails.length; i++){
var email = emails[i];
email.click(function(e) {
e.preventDefault();
alert('test');
//_gaq.push(['_trackEvent', 'Emails', $(this).pathname]);
});
}
Right now i want the popup to appear when i click the link, but it's not working.
A:
This would be more direct:
$('a[href^="mailto:"]').click(function(e){
e.preventDefault();
alert('test');
})
jQuery masquerades as an array of the elements its selector selects. By applying a handler to the jQuery object in this fashion, it actually attaches the handler to all elements that satisfy the selection criteria.
|
[
"stackoverflow",
"0023439070.txt"
] |
Q:
When using XElement Value, is it possible to get the non-concatenated text for a parent node?
Say you have an XElement that looks like this
<name>
TESTING
<given>GIVENNAME2</given>
<family>FAMILYNAME</family>
</name>
var descend = elements.ElementAt(i).DescendantsAndSelf();
foreach (XElement x in descend)
{
string g = x.Value;
}
Result for name element is
TESTING
GIVENNAME2FAMILYNAME
When I try to get the value of individual elements, it works for children nodes like given and family, but when I try to get the text contained in the parent element, Value returns that text, plus the concatenated text of all the child nodes. Does anyone know how to get just the text 'TESTING' as a discrete value form the parent node? And ignore the text of the child nodes?
Not only do I need to read, but I need to change the value as well, which is why I need it as a discrete value.
A:
You can use the Nodes method and look for nodes with a NodeType of XmlNodeType.Text.
var elements = XElement.Parse(@"<name>
TESTING
<given>GIVENNAME2</given>
<family>FAMILYNAME</family>
</name>");
// grab just the first text node for your specific case
// (since we know the structure of this example)
var text = elements.Nodes().OfType<XText>().First();
Console.WriteLine("Before: " + text.Value);
text.Value = "Hello, World!";
Console.WriteLine("After: " + text.Value);
// general approach to inspect all nodes
foreach (var node in elements.Nodes())
{
switch (node.NodeType)
{
case XmlNodeType.Text:
var xtext = (XText)node; // could just ToString() it
Console.WriteLine("{0} : {1}", node.NodeType, xtext.Value);
break;
case XmlNodeType.Element:
var xelement = (XElement)node;
Console.WriteLine("{0} : {1} : {2}", node.NodeType,
xelement.Name, xelement.Value);
break;
default:
Console.WriteLine(node);
break;
}
}
|
[
"stackoverflow",
"0027813976.txt"
] |
Q:
Geany editor "open explorer here" equivalent using nautilus
The intended functionality should be similar to what's seen in many windows editors e.g. "open explorer here". For those unfamiliar with windows, I just want to open nautilus to the directory of the active document.
I've tried two solutions so far, both which end up opening nautilus to the correct directory but without the window activating (not coming to the front with input focus).
Solution attempt 1 - Use the pre-existing "set build commands" and run the following command instead of make
nautilus %d; xdotools windowactivate $(xdotools search --name %d)
Solution attempt 2 - Use the Lua scripting plugin
dir = geany.dirname(geany.filename())
os.execute("nautilus " .. dir .. "; xdotools windowactivate $(xdotools search --name " .. dir .. ")")
I'm not worried about multiple windows having the same name, and I've tested the xdotools script in bash and it works fine. I'm really unsure what I'm missing here. I also don't want to use the explorer side-bar as a work-around.
A:
I did not resolve the bug using Nautilus. Thanks to frlan's help though using Thunar as an alternative works great. There are better guides exising on the internet, but all I did was install thunar[1]
sudo aptitude install thunar
then set it as my default via another package which I had to install in order to run exo-preferred-applications[2]
sudo aptitude install exo-utils
exo-preferred-applications
[1]
[2]
I'm not going to keep the links up to date - so if they are broken just do a quick google search. There are plenty of resources surrounding this topic.
|
[
"stackoverflow",
"0011514565.txt"
] |
Q:
Ninject Extension Factory with Moq
I've been using Ninject for dependency injection and inversion of control, and I have been using Moq for testing purposes quite successfully; however, I recently came into a position in which I needed to start using the factory extension of Ninject.
I have code along the lines of:
interface IBarFactory
{
Bar CreateBar();
}
class Bar : IBar
{
...
}
class BarModule
{
public override void Load()
{
Bind<IBarFactory>().ToFactory();
}
}
class Tests
{
[Fact]
public void TestMethod()
{
var bar = new Mock<IBar>();
bar.Setup(b => b.DoSomething())
.Verifiable();
var barFactory = new Mock<IBarFactory>();
cryptoKeyFactoryMock.Setup(f => f.CreateBar())
.Returns(bar.Object)
.Verifiable();
var someOtherClass = new SomeOtherClass(barFactory.Object);
}
}
When attempting to force the IBarFactory mock to return an IBar mocked object, I get an error due to the fact that the CreateBar() method expects a Bar typed object rather than an IBar typed one.
Has anyone had more success using Moq with Ninject Factory?
A:
I don't think the issue is Ninject specifically, but just that you seem to be declaring an Interface solely for testing. Is there a reason that the BarFactory shouldn't return IBar?
Moq can mock classes, not just interfaces. You can set up a Mock<Bar> instance for the mocked BarFactory call to return. The caveat is that any methods/properties you want to assert on the Mocked Bar instance must be declared as virtual. So in your example, if you declare DoSomething() as virtual then you can set up a mock of type Bar with your declaration instead of IBar.
|
[
"askubuntu",
"0001250444.txt"
] |
Q:
Can't download Ubuntu because the VM's screen is too zoom in. Help!
I am trying to download Ubuntu 16.04.6 on Virtual Box 6.1 and there is nothing else on there. I am currently using Windows 8.1.
I have tried going to devices >> Insert Guest Additions CD and nothing happen. I have guest additions downloaded on my laptop from a link.
I also tried to resize it but it doesn't let me.
I am in the middle of trying to download Ubuntu but the VM's screen is so zoomed in that I can't choose the options to continue.
Any help?
A:
You can move the window by right clicking on the header, hold down the right click and move the window.
You can also press tab to get focus on the continue button and then press enter.
|
[
"stackoverflow",
"0038419991.txt"
] |
Q:
yargs .check() error handling
I'm using yargs to validate cli arguments for a data-loading helper lib.
I want to be able to check that a file exists before allowing the script to run, which I do with fs.accessSync(filename, fs.R_OK);. However, if the file does not exist, the messaging simply shows the .check() function as the error, whereas I want to intercept, and state that the file does not exist (with read permissions).
So how to I send an error to be presented by .check() on a false return?
Here is the gist of my yargs:
var path = {
name: 'filepath',
options: {
alias: 'f',
describe: 'provide json array file',
demand: true,
},
};
function fileExists(filename) {
try {
fs.accessSync(filename, fs.R_OK);
return true;
} catch (e) {
return false;
}
}
var argv = require('yargs')
.usage('$0 [args]')
.option(path.name, path.options)
.check(function (argv) {
return fileExists(argv.f);
})
.strict()
.help('help')
.argv;
and the returned error if not a readable file:
Argument check failed: function (argv) {
return fileExists(argv.f);
}
I'd prefer to be able to specify something along the lines of:
Argument check failed: filepath is not a readable file
A:
So in yargs 5.0.0 when you return a non-truthy value it will print that entire output.
Argument check failed: function (argv) {
return fileExists(argv.f);
}
If you throw instead you can control the output message.
.check((argv) => {
if (fileExists(argv.f)) {
return true;
}
throw new Error('Argument check failed: filepath is not a readable file');
})
|
[
"stackoverflow",
"0006893670.txt"
] |
Q:
Import users to aspnet_membership table
I am trying to import 1000 users to aspnet_membership table using TSQL. Could anyone please point me to the right direction whether this is possible at all?
The requirement is to:
Create Users and Profiles.
Generate password.
Email password to end users.
Thank you.
A:
If you are going to use unencrypted password format then you can just call dbo.aspnet_Membership_CreateUser stored procedure from your SQL to create users. It takes a bunch of params;
@ApplicationName
@UserName
@Password
@PasswordSalt
@Email
@PasswordQuestion
@PasswordAnswer
@IsApproved
@CurrentTimeUtc
@CreateDate
@UniqueEmail
@PasswordFormat
@UserId (output)
You can generate password in TSQL and you can send emails from TSQL. This stored procedure: dbo.aspnet_Profile_SetProperties would set Profile properties.
If you need hashed or encrypted passwords .. then probably you have to write some admin code that uses Membership and Profile providers. It should be fairly easy to do so. Providers have all the methods that are needed to generate and encrypt passwords.
To create users you would just call:
CreateUser
( string username,
string password,
string email,
string passwordQuestion,
string passwordAnswer,
bool isApproved,
object providerUserKey,
out MembershipCreateStatus status )
method and pass the data in. The encryption will happen inside the method.
So TSQL could work if you do not need to encrypt or hash passwords. Otherwise it wouldbe some coding .. but really minimal.
|
[
"stackoverflow",
"0045185385.txt"
] |
Q:
matlab plot with multiple colormaps
I want to create a plot with pcolor plot with an contour plot on top. Both with different colormaps - pcolor with "hot", the contour with "gray".
I newer Matlab version multiple colormaps are possible.
The code works, however both axis do not overlap, even if the axes positions are in sync.
%% prepare Data
Data2D = peaks(100);
Data2D = Data2D -min(Data2D(:));
Data2D = Data2D/max(Data2D(:)) * 100;
steps = 0:05:100;
xAxis = 1:size(Data2D,2);
yAxis = 1:size(Data2D,1);
figure(1); clf
ax1 = axes;
hold on;
% 3D flat plot
caxis([0 100]);
cmap = fliplr(jet(1000));
colormap(ax1, cmap(1:800,:));
hplot = pcolor(ax1, xAxis, yAxis, Data2D);
shading flat; % do not interpolate pixels
set(ax1,'XLim',[xAxis(1) xAxis(end)]);
set(ax1,'YLim',[yAxis(1) yAxis(end)]);
% colorbar
hcb = colorbar('location','EastOutside');
set(hcb, 'Ylim', [0 100]);
%% contour plot
ax2 = axes; linkaxes([ax1,ax2])
colormap(ax2, flipud(gray(1000)));
[C,hfigc] = contour(ax2, xAxis, yAxis, Data2D,steps);
% Hide the top axes
ax2.Visible = 'off';
ax2.XTick = [];
ax2.YTick = [];
set(hfigc, 'LineWidth',1.0);
hold off;
drawnow
A:
If you didn't use ax2.Visible = 'off' you would probably see that the axes' positions are different, since the first axes are squashed to allow room for the colorbar which the second axes don't have.
TL;DR
You need to set the position properties to be equal
ax2.Position = ax1.Position
Demo
You can simulate this with a blank figure:
1.
% Create figure and first axes, which have a colorbar
figure(1)
ax1 = axes();
colorbar('location', 'eastoutside');
Output:
2.
% Add new axes
hold on;
ax2 = axes();
Output (notice the second axes fills the space of the first + colorbar):
3.
% Make the same, so that the second axes also allow for the colorbar
ax2.Position = ax1.Position;
Output (notice thicker numbers showing they are overlapping fully):
|
[
"stackoverflow",
"0013545754.txt"
] |
Q:
Creating View + Query (Combining columns + adding an extra attribute)
I managed to solve it using UNION between two querys, I belive my attempt was a little off and tried to do a mathematical add. This is problaby not the best way you can do it, but it worked and that's enough for me. Thank you for your help.
Working solution:
CREATE VIEW Registrations AS
(SELECT S.identificationnumber AS StudentId, S.name AS StudentName, C.code AS CourseCode, C.name AS CourseName, 'Waiting' AS Status
FROM Waitinglist W, Student S, Course C
WHERE S.identificationnumber = W.identificationnumber
AND W.code = C.code) UNION (SELECT S.identificationnumber AS StudentId, S.name AS StudentName, C.code AS CourseCode, C.name AS CourseName, 'Registered' AS Status
FROM Registeredat R, Student S, Course C
WHERE S.identificationnumber = R.identificationnumber
AND R.code = C.code);
Origianl Problem:
I'm a begginner at databases and SQL, so things might not look that professional.
What I'm trying to do in plain text:
I'm trying to create a view for all registerd and waiting students, for all courses. I also want to add a new "column" thats either "registerd" or "waiting".
How I want the view to look:
StudentID, StudentName, CourseCode, CourseName, Status
StudentID = Combined idenficationnumber for Table "RegisterdAt" and "Waitinglist"
StudentName = Based on StudentID find matching name in Table "Student"
CourseCode = Combined code for Table "RegisterdAt" and "Waitinglist"
CourseName = based on code find matching name in Table "Course"
Status = Either "registered" or "waiting"
depending on if we got the "row" from Table "RegisterdAt" or "Waitinglist"
The Created Tables(I have also added some examplery data into them, for easier testing):
CREATE TABLE Student(
identificationnumber VARCHAR(20),
name VARCHAR(50),
branchname VARCHAR(50),
programmename VARCHAR(50),
PRIMARY KEY(identificationnumber),
FOREIGN KEY(branchname, programmename) REFERENCES Branch(name, programmename)
);
CREATE TABLE Course(
code CHAR(6),
name VARCHAR(50),
credits VARCHAR(10),
departmentname VARCHAR(50),
PRIMARY KEY(code),
FOREIGN KEY(departmentname) REFERENCES Department(name)
);
CREATE TABLE Waitinglist(
identificationnumber VARCHAR(20),
code CHAR(6),
ddate VARCHAR(10),
PRIMARY KEY(identificationnumber, code),
FOREIGN KEY(identificationnumber) REFERENCES Student(identificationnumber),
FOREIGN KEY(code) REFERENCES Course_with_maxstudents(code)
);
CREATE TABLE Registeredat(
identificationnumber VARCHAR(20),
code CHAR(6),
PRIMARY KEY(identificationnumber,code),
FOREIGN KEY(identificationnumber) REFERENCES Student(identificationnumber),
FOREIGN KEY(code) REFERENCES Course(code)
);
An attempt to create a view(not working, and missing registerd/waiting attribute):
CREATE VIEW Registrations AS
SELECT (R.identificationnumber + W.identificationnumber) AS StudentId, S.name AS StudentName, (R.code + W.code) AS CourseCode, C.name as CourseName
FROM Registeredat R, Waitinglist W, Student S, Course C
WHERE S.identificationnumber = (R.identificationnumber + W.identificationnumber)
AND C.code = (R.code + W.code);
A:
The working solution you posted looks great. I would just make the plain UNION into a UNION ALL, for it seems unlikely for you to need to remove duplicates from between these 2 subqueries. The ALL will prevent the server from doing unnecessary work to resort the combined results and search for non-existant duplicates.
So it would become:
CREATE VIEW Registrations AS
(
SELECT S.identificationnumber AS StudentId, S.name AS StudentName, C.code AS CourseCode, C.name AS CourseName, 'Waiting' AS Status
FROM Waitinglist W, Student S, Course C
WHERE S.identificationnumber = W.identificationnumber
AND W.code = C.code
)
UNION ALL
(
SELECT S.identificationnumber AS StudentId, S.name AS StudentName, C.code AS CourseCode, C.name AS CourseName, 'Registered' AS Status
FROM Registeredat R, Student S, Course C
WHERE S.identificationnumber = R.identificationnumber
AND R.code = C.code
);
|
[
"stackoverflow",
"0060686073.txt"
] |
Q:
Uncaught TypeError when calling function from button
I'm making a form to record data from a group of people, and when pressing the button to add another person, the console spits out a TypeError, saying addPerson() is not a function.
HTML (body):
<form method="POST">
<h3> People </h3>
<div class="person">
<p>
<label>Name</label>
<input type="text" name="name" />
<br/>
</p>
<p>
<label>Gender</label>
<input type="radio" name="gender" value="male" />Male
<input type="radio" name="gender" value="female" />Female
<br />
</p>
<p>
<label>Date of Birth</label>
<input type="date" name="dob" />
<br/>
</p>
</div>
<br/>
<input type="button" value="Add another person" onclick="addPerson()" id="addPerson" />
</form>
<script src="client.js"></script>
Javascript:
function addPerson(){
let personForm = document.getElementsByClassName("person")[0];
let personFormCopy = personForm.cloneNode(true);
let buttonNode = document.getElementById("addPerson");
document.body.insertBefore(personFormCopy, buttonNode);
let br150 = document.createElement("br");
document.body.insertBefore(br150, buttonNode);
br150.style.lineHeight="150px";
}
Error:
Uncaught TypeError: addPerson is not a function at HTMLInputElement.onclick
A:
The name of your function and the button ID are the same. Ever since IE introduced this behavior, some browsers add DOM element IDs to the window scope, which is causing conflicts in your case.
This problem can be solved by changing the ID of the button to addPersonBtn, for example.
However, I would suggest not mixing HTML and JS. You could instead remove the onclick attribute in your HTML, and write your JS like so:
document.getElementById('addPersonBtn').addEventListener('click', addPerson);
function addPerson(){
console.log('It worked.');
}
<button id="addPersonBtn">Click me</button>
|
[
"stackoverflow",
"0003582390.txt"
] |
Q:
Get URL parameters in JS and embed into a JS function
I have a graph library that I use to plot some data.
This data comes passed as a GET paramater in the URL in the following format: plottedgraph.html?case_id=4&otherparam=blabla
Then I have my HTML page where I try to catch that GET param with the GUP function (below) and add it to my JS function as follows: "http://www.url.com/showgraph.do?case_id=" + gup('case_id') + "&status=weighted"
This is the whole HTML
<html>
<head>
<!--[if IE]>
<script type="text/javascript" src="js/excanvas.js"></script>
<![endif]-->
<script type="text/javascript" src="js/dygraph-combined.js"></script>
<script type="javascript">
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
</script>
</head>
<body>
<div id="graphdiv2" style="width:1800; height:900px;"></div>
<script type="text/javascript">
g2 = new Dygraph(
document.getElementById("graphdiv2"),
"http://www.url.com/showgraph.do?case_id=" + gup('case_id') + "&status=weighted", // path to CSV file
{
showRoller: true,
colors: ["rgb(255,100,100)",
"rgb(72,61,139)"]
} // options
);
</script>
</body>
</html>
Unfortunately the JS function doesn't recognize that case_id=4 in this case...
Could you please let me know what am I doing wrong?
A:
It's a bit hard to debug you gup() function, could you try:
var params={};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
params[decode(arguments[1])] = decode(arguments[2]);
});
You can now find your parameters in the params object, so params['case_id'] will hold the value you're looking for.
|
[
"stackoverflow",
"0046946478.txt"
] |
Q:
Rails 5.1 Trying to pass an attribute to a form using a link
I am trying to pass an attribute to an object that is being created by a link. I am on the show view of another object and I want to have two links available one that will make the :attribute false and the other to make the :attribute true. I have it set up so the default value of the this attribute is false and I tried using something like below, but it just saves it as nil in the database:
<%= link_to "Yes", new_building_listing_appointment_rented_unit_path(@building, @listing, @appointment, @rented_unit, leased: true) %>>
controller
class RentedUnitsController < ApplicationController
before_action :building
before_action :listing
before_action :appointment
before_action :set_rented_unit, only: [:show, :edit, :update, :destroy]
# GET /rented_units
# GET /rented_units.json
def index
@rented_units = appointment.rented_units
end
# GET /rented_units/1
# GET /rented_units/1.json
def show
end
# GET /rented_units/new
def new
@rented_unit = appointment.rented_units.new
end
# GET /rented_units/1/edit
def edit
end
# POST /rented_units
# POST /rented_units.json
def create
@rented_unit = appointment.rented_units.new(rented_unit_params)
respond_to do |format|
if @rented_unit.save
format.html { redirect_to [building, listing, appointment, @rented_unit], notice: 'Rented unit was successfully created.' }
format.json { render :show, status: :created, location: @rented_unit }
else
format.html { render :new }
format.json { render json: @rented_unit.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /rented_units/1
# PATCH/PUT /rented_units/1.json
def update
respond_to do |format|
if @rented_unit.update(rented_unit_params)
format.html { redirect_to [building, listing, appointment, @rented_unit], notice: 'Rented unit was successfully updated.' }
format.json { render :show, status: :ok, location: @rented_unit }
else
format.html { render :edit }
format.json { render json: @rented_unit.errors, status: :unprocessable_entity }
end
end
end
# DELETE /rented_units/1
# DELETE /rented_units/1.json
def destroy
@rented_unit.destroy
respond_to do |format|
format.html { redirect_to building_listing_appointment_rented_units_path(@building, @listing, @appointment), notice: 'Rented unit was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_rented_unit
@rented_unit = appointment.rented_units.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def rented_unit_params
params.require(:rented_unit).permit(:unit_no, :unit_model, :price, :bedrooms, :bathrooms, :half_baths, :square_footage, :leased, :appointment_id)
end
def building
@building ||= Building.find(params[:building_id])
end
def listing
@listing ||= Listing.find(params[:listing_id])
end
def appointment
@appointment ||= Appointment.find(params[:appointment_id])
end
end
A:
From what I understand you are looking to populate leased attribute auto when you open a new from from the link.
You need to give the param param to the link.
<%= link_to "Yes", new_building_listing_appointment_rented_unit_path(@building, @listing, @appointment, @rented_unit, rented_unit: { leased: true } ) %>>
In the controller then you can do some thing like
# GET /rented_units/new
def new
@rented_unit = appointment.rented_units.new(rented_unit_params)
end
Then, in the new form you will see the checkbox (or other control) selected.
|
[
"stackoverflow",
"0001303302.txt"
] |
Q:
Centering Text in IE 7 / Conditional CSS
i'm really banging my head on this one.
The site looks great in everything but IE7 and I've tried everything I know to make it center.
http://talentforceinc.com/Employer_Home.html
I've got conditional CSS for IE declared, and have added inline text-align:center tags, but for an unknown reason the text in the multi-colored bar on the left isn't centering.
Any thoughts?
Yes, I know the code is ugly right now - but it's all mucked up in my attempts to center things up.
Thanks in advance for any input.
IE Developer Tools are not the same as Firebug....
A:
For reference, the page being referred to is located here: http://talentforceinc.com/Employers_Home.html.
The specific code referred to is here: http://www.i-simplyrecruit.com/isrjobs/talentforce/ShowJobColors.asp and also shown below for reference.
The first problem is (as you mentioned), the code is ugly. So ugly in fact that it is very hard to see that:
There are unfinished HTML space entities ( ) in the "Cementing Service..." and "Document Layout Specialist" cells. This is causing portions of the ending tags that follow to be ignored.
HTML attributes for width and height are integer values only. Do not specify "px". ex. 450 instead of 450px.
The closing <div> tag in each cell (with a class of "sidebar") is placed after the ending <td> and <tr>.
After fixing these errors, I also notice that you have a table width set at 185 and each table cell width is set at 100. This is keeping the table cells from taking up the entire width of the table, making the text within them not able to be centered within the width of the table. Removing the cell width fixes this problem.
I have uploaded a test page with the original unmodified code and the results of my changes: http://demo.raleighbuckner.com/so/1303302/
Original HTML for reference:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://demo.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Latest Jobs</title>
<link href="http://www.talentforceinc.com/talentforce.css" rel="stylesheet" type="text/css" />
<!--[if LTE IE 7]>
<link href="http://www.talentforceinc.com/talentforce_IE.css" rel="stylesheet" type="text/css" />
<![endif]-->
<style type="text/css">
<!--
td {
text-align: center;
align: center;
}
-->
</style>
<script type="text/javascript">
<!--
function MM_openBrWindow(theURL,winName,features) { //v2.0
window.open(theURL,winName,features);
}
function ShowMore(pID)
{
var pParm = "Candidates_jobSearch3.asp?id=" + pID;
MM_openBrWindow(pParm,"jobDetail","scrollbars=yes,width=600,height=600 resizable=no");
}
//-->
</script>
</head>
<body>
<table width=185px bgcolor=white border=0 cellpadding=0 cellspacing=0 style='text-align:center'><tr><td height=40 width=100px align=center style='text-align:center' valign=middle bgcolor='#00AADD'><div class='sidebar'><div align='center'><a style='text-align:center' href='#' onclick='javascript:ShowMore("P0006008-0032");'>Contractor Engineer Specialist</a></div></td></tr></div><tr><td height=40 width=100px align=center style='text-align:center' valign=middle bgcolor='#AADDEE'><div class='sidebar'><div align='center'><a style='text-align:center' href='#' onclick='javascript:ShowMore("N0003008-0077");'>.Net & Sql server An</a></div></td></tr></div><tr><td height=40 width=100px align=center style='text-align:center' valign=middle bgcolor='#FFCC55'><div class='sidebar'><div align='center'><a style='text-align:center' href='#' onclick='javascript:ShowMore("S5696007-0004");'>Cementing Service Sup/Deep&nbs</a></div></td></tr></div><tr><td height=40 width=100px align=center style='text-align:center' valign=middle bgcolor='#22AA55'><div class='sidebar'><div align='center'><a style='text-align:center' href='#' onclick='javascript:ShowMore("S4082007-0012");'>Coil Tubing Operator/Equipment</a></div></td></tr></div><tr><td height=40 width=100px align=center style='text-align:center' valign=middle bgcolor='#9999AA'><div class='sidebar'><div align='center'><a style='text-align:center' href='#' onclick='javascript:ShowMore("L0008004-0157");'>Loads Analysis </a></div></td></tr></div><tr><td height=40 width=100px align=center style='text-align:center' valign=middle bgcolor='#EE9922'><div class='sidebar'><div align='center'><a style='text-align:center' href='#' onclick='javascript:ShowMore("D6452009-0448");'>Document Layout Specialist&nbs</a></div></td></tr></div><tr><td height=40 width=100px align=center style='text-align:center' valign=middle bgcolor='#CCCCCC'><div class='sidebar'><div align='center'><a style='text-align:center' href='#' onclick='javascript:ShowMore("L0008004-0161");'>Technical Trainer </a></div></td></tr></div><tr><td height=40 width=100px align=center style='text-align:center' valign=middle bgcolor='#00AAAA'><div class='sidebar'><div align='center'><a style='text-align:center' href='#' onclick='javascript:ShowMore("A0029005-0025");'>Q.A. Engineer </a></div></td></tr></div><tr><td height=40 width=100px align=center style='text-align:center' valign=middle bgcolor='#888888'><div class='sidebar'><div align='center'><a style='text-align:center' href='#' onclick='javascript:ShowMore("E0001008-0090");'>Clerk Secret Clearance</a></div></td></tr></div></table>
</body>
</html>
|
[
"gis.stackexchange",
"0000302091.txt"
] |
Q:
Performing Supervised Classification on Sentinel Image using ArcGIS Desktop?
Is it possible to perform supervised classification on Sentinel Satellite Image with the minimum error. I compared two raster, one being the manual classification of an area using Photoshop CS6 and the other being Supervised Classification with Interactive Supervised Classification (ArcGIS). The pixels that didn't match represented more than 70% (Confusion Matrix). So, this is the farthest I've gone. I need to know if there is more that I can do with only ArcGIS Desktop.
This is the Manual Classified Image with Photoshop CS6.
This is the raster using Interactive Supervised Classification (This tool uses training polygons)
As you see there is a big space that should be colored with violet in the second image. Obviously in the future using CS6 should not be what we always use but this is only used by compare and see if Interactive supervised classification works.
A:
You are likely observing the difference between pixel based classification and object oriented classification. The Photoshop algorithm likely incorporates some form of image segmentation (i.e. a type of object oriented image analysis), whereas the ArcGIS pixel based classifier uses the Maximum Likelihood classification algorithm. Esri defines the difference between the two methods as follows (Source):
Pixel-based is a traditional approach that decides what class each
pixel belongs in on an individual basis. It does not take into account
any of the information from neighboring pixels. It can lead to a salt
and pepper effect in your classification results.
The object-based approach groups neighboring pixels together based on
how similar they are in a process known as segmentation. Segmentation
takes into account color and the shape characteristics when deciding
how pixels are grouped. Because this approach essentially averages the
values of pixels and takes geographic information into account, the
objects that are created from segmentation more closely resemble
real-world features in your imagery and produces cleaner
classification results.
Generally speaking, image segmentation based classification approaches achieve much higher accuracy than pixel based approaches. In fact, ArcGIS has a Mean Shift segmentation algorithm which works pretty well. Note that you will need to select a classifier such as Random Trees to classify your image objects created during the segmentation.
|
[
"mathoverflow",
"0000242438.txt"
] |
Q:
Existentially closed partial orders
Existentially closed linear orders are dense linear orders without endpoints, which are finitely axiomatizable, and occur as order-types of natural mathematical structures such as the rationals or reals.
What about existentially closed partial orders? Is the theory finitely axiomatizable, and are there natural mathematical structures with an existentially closed partial order structure?
A:
A model $M$ of a theory $T$ is existentially closed with respect
to that theory, if for any quantifier-free formula $\varphi$ and
any objects $\vec a$ in $M$, if there is model $N$ of the theory
$T$ extending $M$ in which there is an object $z$ for which
$N\models \varphi(z,\vec a)$, then there is already such an object
$z$ inside $M$.
For the theory of linear orders, this property implies density,
since if $a<b$, then there is a larger linear order with some $z$
in between them, so there must already be something between.
Similarly, it implies that there is no largest element and no
smallest element, since you can always add a new element above or
below.
In a partial order, what you get is that any finite partial order
can be extended by adding points of any type that can occur in any
particular partial order.
Theorem. There is a unique countable existentially closed
partial order, and it has a computable presentation.
Proof. (Existence) Start with a single point; then add a point
above, below, and to the side. Continuing in stages, at every
stage you have finitely many points. Add points in all possible
ways that can be realized in any partial order extending what you
have so far. The result will be existentially closed, since for
any finitely many elements, if a point realizes some pattern in a
partial order extending it, you've already added a point just like
that. This process gives a computable presentation of the order.
(Uniqueness) This follows from a back-and-forth argument. Every
finite partial isomorphism can be extended one more step, since
whatever type is realized by the next point in one of the models,
the other model will also have a point realizing the corresponding
type.
QED
This partial order is the unique homogeneous countable partial order that is universal for all countable partial orders. It is also the Fraïssé limit of all finite partial orders.
The slides for my talk on the Hypnagogic digraph at the JMM 2016 special session on the surreal numbers (slides)
contain an elucidation of the countable universal homogeneous
partial order---look at the section on universality to see an partial animation of the countable existentially closed partial order being constructed.
|
[
"ru.stackoverflow",
"0000459709.txt"
] |
Q:
Vsftpd, позволить создавать каталоги в корне?
# /etc/vsftpd.conf:
# Запускаем как демон, а не из inetd.
listen=YES
background=YES
listen_address=10.200.79.220
#listen_port=2121
#
# Включаем возможность использования tcpwrapper, лимиты через /etc/hosts.allow
tcp_wrappers=YES
#
# Пускаем только пользователей имеющих валидный shell, присутствующий в /etc/shells
check_shell=YES
#
# Вместо реальных владельцев файлов всегда показываем ftp:ftp
hide_ids=YES
#
# Общее максиамльно допустимое число коннектов.
max_clients=100
#
# Разрешенное число коннектов с одного IP.
max_per_ip=10
#
# Таймаут при ожидании команды
idle_session_timeout=3000
#
# Таймаут при передаче данных
data_connection_timeout=6000
#
# Непривилегированный пользователь, для того чтобы делать под ним, что можно выполнить без root.
nopriv_user=ftp
#
# Запрещаем рекурсивный вызов "ls -R"
ls_recurse_enable=NO
#
# Ограничение скорости прокачки для анонимных и локальных пользователей (байт в сек.)
# ====================anon_max_rate=50000
# ====================local_max_rate=100000
#
# Включаем ведение лога операций.
xferlog_enable=YES
vsftpd_log_file=/var/log/vsftpd.log
#
# Расширенные логи всех команд
log_ftp_protocol=YES
#
#
# ------------ Настрйоки для анонимного сервера
# Если сервер публичный, пускающий анонимных пользователей
anonymous_enable=YES
anon_umask=0022
# anon_umask=777
# anon_umask=055
# anon_umask=066
# anon_umask=044
# anon_umask=033
# anon_umask=022
# anon_umask=077
#
# Корень анонимного ftp архива
anon_root=/home/u0807/RecordsPolycom/
#
# Запрещаем анонимным пользователям запись данных, если нужно разрешить
# запись для локальных пользовтелей
write_enable=YES
anon_upload_enable=YES
#
# Запрещаем создавать директории.
anon_mkdir_write_enable=YES
#
# ====error======chown_upload_mode=0777================in v.2.0.6
#
# Запрещаем переименовывать и удалять
anon_other_write_enable=YES
# Разрешаем анонимам чтение и копирование не проверенной админом информации
anon_world_readable_only=NO
# YES
#
# Если нужно запретить доступ к определенным типам файлов по маске
# deny_file={*.mp3,*.mov, *.avi, .filelist}
#
# Если нужно скрыть определенные типы файлов при выводе списка,
# но дать скачать тем кто знает точное имя.
# hide_file={*.mp3,*.mov, *.avi}
# Если анонимную закачку необходимо разрешить, нужно дополнительно
# использовать
chown_uploads=YES
# chown_username=ftp_anon_user
chown_username=ftp
#
# Если нужно пускать анонимных пользователей только при правильном введении
# email (аналог паролей для ограничения доступа к публичному ftp), заданного в
# файле определенном директивой email_password_file, нужно установить
# secure_email_list_enable=YES
#
#
# ------------ Настрйоки для входа локальных пользователей
#
# Если сервер разрешает вход локальных пользователей, присутствующих в системе
local_enable=YES
#
# "-rw-r--r--"
# local_umask=0022
local_umask=022
# local_umask=077
# local_umask=777
# local_umask=033
# local_umask=044
# local_umask=066
# local_umask=055
# local_umask=222
#
#
#
# Разрешаем показ файлов начинающихся с точки (например, .htaccess) для кривых ftp-клиентов
force_dot_files=YES
#
# Разрешаем пользователям записывать/изменять свою информацию на сервер.
# если нужно запретить запись данных - write_enable=NO
# Более тонкий тюнинг через "cmds_allowed=PASV,RETR,QUIT"
write_enable=YES
#
# Для всех пользователей делаем chroot, делаем корнем их домашнюю директорию,
# Список логинов для которых не нужно делать chroot задаем в vsftpd.chroot_list
chroot_local_user=YES
# chroot_list_enable=YES
# chroot_list_file=/etc/vsftpd.chroot_list
#
# Активируем список пользователей которым запрещен вход по FTP (например, root)
# userlist_enable=YES
# userlist_file=/etc/ftpusers
file_open_mode=0777
guest_enable=YES
guest_username=ftp
tilde_user_enable=YES
Подскажите пожалуйста что нужно поправить.
Или с авторизацией можно, главное что-бы в корне можно было каталоги создавать.
A:
Это нормальное поведение vsftpd начиная с версии 2.3.5
Вариантов решения несколько, например можно указать local_root на директорию выше:
local_root=/home
либо (если версия vsftpd выше 3.0.0):
allow_writeable_chroot=YES
- Add new config setting "allow_writeable_chroot" to help people in a bit of
a spot with the v2.3.5 defensive change. Only applies to non-anonymous.
|
[
"stackoverflow",
"0023137867.txt"
] |
Q:
How to display panel control based on Listview ItemDataBound value
Using asp.net 4.0. I have a page with a listview. I am trying to display a certain pre-defined Panel within the listview itemtemplate based on the current ItemBound value but not on the itemBound event....
For example, if the dataItem.Item("DataGapDesc") value is equal to "A", display Panel pnlPanelA, which will have 2 textboxes. If the dataItem.Item("DataGapDesc") value is equal to "B", display Panel pnlPanelB, which will have 3 textboxes and a checkbox, and so on.
Here's my current listview in the aspx:
<asp:ListView ID="EmployeesGroupedByDataField" runat="server" DataSourceID="sqlDataGapsForSelectedemployees" OnItemBound="employeesGroupedByDataField_ItemDataBound">
<LayoutTemplate>
<table id="Table1" runat="server" class="table1">
<tr id="Tr1" runat="server">
<td id="Td1" runat="server">
<table ID="itemPlaceholderContainer" runat="server" >
<tr id="Tr2" runat="server">
<th id="Th1" runat="server" style="text-align:left"><u>
employee</u></th>
<th id="Th2" runat="server" style="width:5%;text-align:center"><u>
# Items Missing</u></th>
<th id="Th3" runat="server"><u>
employee DOB</u></th>
<th id="Th4" runat="server"><u>
Primary Physican</u></th>
<th id="Th6" runat="server" style="width:10%;text-align:center;border-right: thin solid #000000"><u>
Missing Data Item</u></th>
<th id="Th5" runat="server" style="text-align: center;"><u>
Last Known Visit/Service</u></th>
<th id="Th7" runat="server" style="text-align: center;"><u>
Data Entry</u></th>
</tr>
<tr ID="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr id="Tr3" runat="server">
<td id="Td2" runat="server" style="">
</td>
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<%# AddGroupingRowIfemployeeHasChanged()%>
<td style="text-align: right;border-right: thin solid #000000"><%# Eval("DataGapDesc")%> </td>
<td style="text-align: left;">
<%#Eval("ServiceDate")%>
 - 
<%# Eval("PlaceOfService")%>
</td>
<td>
<%# DisplaySpecificPanel()%>
</td>
</tr>
</ItemTemplate>
</asp:ListView>
Im calling the function DisplaySpecificPanel() and this is where I was "trying" to perform this behavior. That function in VB:
Public Function DisplaySpecificPanel() As String
Dim currentEmployeeNameValue As String = Trim(Eval("Employee").ToString().Substring(0, (Eval("Employee").ToString.Length) - 10).ToString())
If currentEmployeeNameValue = "DOE, JOHN" Then
'Panel1.Visible = True
Return String.Format("<asp:Button ID=""Button1"" runat=""server"" Text=""Button"" />")
Else
Return String.Format("<asp:TextBox ID=""TextBox1"" runat=""server""></asp:TextBox>")
End If
End Function
Right now, I'm just trying this functionality out by adding either a textbox or button based on the value but longer term, I wish to add the panels...
Well, my function is being called properly but the controls are not being placed on the rendered listview.
Any ideas? I'm I going about this correct? Many thanks...
A:
Found this from another source. Makes sense but I wasn't completely versed in the lifecycle or behavior of the aspx page.
You will not be able to render server side controls using string
representation of the control. That approach works for plain HTML
controls. But, server side controls need to go through a rendering
mechanism which will not be invoked when you just set text property of
a control. Better alternative would be keeping just one panel in the
item template and adding controls dynamically in the itemdatabound
event based on conditions. Then, You can check if some condition is
true and then add textbox or a button accordingly. If there are too
many controls, you can also use UserControls. But, dynamic controls
will not be retained across page postbacks and you would need to add
them back with the same ID. If you do not want to handle all this
creation mechanism, you could just keep two independent panels and
update the visibility based on some conditions.
within Listview :
<td>
<asp:Panel runat="server" ID="pnlOne" Visible='<%# CanShowFirstPanel()%>'>
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Panel>
<asp:Panel runat="server" ID="pnlTwo" Visible='<%# CanShowSecondPanel()%>'>
<asp:TextBox runat="server" ID="TextBox1" />
</asp:Panel>
</td>
Code-behind:
Public Function CanShowFirstPanel() As Boolean
'condition to check
Return True
End Function
Public Function CanShowSecondPanel() As Boolean
'condition to check
Return False
End Function
|
[
"stackoverflow",
"0007212086.txt"
] |
Q:
Put self.editbuttonitem into segmentedcontrol as barbuttonitem?
I want to make a NavBar similar to the one in sample 3 of the NavBar sample code, except I want to use the self.editbuttonItem as one of the two buttons in the SegmentedControl. (The other will be a custom add button.) Basically - the end result will be a leftBarButtonItem that's just one button, bringing up a modal view, and a rightBarButtonItem that's a segmented control with both edit and add buttons.
Thing is, it looks like setting up the SegmentedControl needs an array of Strings or Images, but not BarButtonItems. Is there a workaround?
This is the relevant bit from Apple's sample:
// "Segmented" control to the right
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:
[NSArray arrayWithObjects:
[UIImage imageNamed:@"up.png"],
[UIImage imageNamed:@"down.png"],
nil]];
[segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
segmentedControl.frame = CGRectMake(0, 0, 90, kCustomButtonHeight);
segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
segmentedControl.momentary = YES;
defaultTintColor = [segmentedControl.tintColor retain]; // keep track of this for later
UIBarButtonItem *segmentBarItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
[segmentedControl release];
self.navigationItem.rightBarButtonItem = segmentBarItem;
[segmentBarItem release];
Instead of the images, I want to put BarButtonItems...
A:
If self.editbuttonitem is a UIBarButtonItem with title "Edit", I think you can do with the following code
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:
[NSArray arrayWithObjects:
@"Edit", @"AnotherButtonName"
nil]];
edit based on Charles Bandes's comment
Add an action to the segmentedControl, like the Apple's sample:
[segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
//...
then in segmentAction:, do
- (void)segmentAction:(UISegmentedControl*)sender
{
//if the "edit" item in segmentedControl is selected
if (sender.selectedSegmentIndex == 0)
{
//I assume self is a UITableView instance
//start editing
[self setEditing:YES animated:YES];
}
}
I wrote those code on my PC. However it should work.
You may take a look at [UITableView setEditing:animated:]
|
[
"stackoverflow",
"0051084316.txt"
] |
Q:
str to time object in python 3
Given a pair of str objects representing an ISO 8601 time and time zone:
time_str = '09:30'
time_zone_str = 'America/New_York'
How can these 2 strings be parsed into a time (not datetime) object?
Note: It's obviously possible to split the time_str by ':' and use the time constructor but then the parsing would be a little tricky to count the number of elements in the resulting list to know the resolution (minute, second, microsecond) of the str. This is because ISO 8601 allows for different representations:
time_str_short = '09:30'
time_str_long = '09:30:00'
Thank you in advance for your consideration and response.
A:
A timezone without a date is meaningless, so no, you can't use both to produce a time object. While the standard library time object does support having a tzinfo attribute, the 'timezone' object is not really a timezone, but merely a time offset.
A timezone is more than just an offset from UTC. Timezone offsets are date-dependent, and because such details as the Daylight Savings winter / summer time distinction is partly the result of political decisions, what dates the timezone offset changes is also dependent on the year.
To be explicit, America/New_York is a timezone, not a time offset. The exact offset from UTC depends on the date; it'll be minus 4 hours in summer, 5 hours in winter!
So for a timezone such as America/New_York, you need to pick a date too. If you don't care about the date, pick a fixed date so your offset is at least consistent. If you are converting a lot of time stamps, store the timezone offset once as a timedelta(), then use that timedelta to shift time() objects to the right offset.
To parse just a timestring, pretend there is a date attached by using the datetime.strptime() method, then extract the time object:
from datetime import datetime
try:
timeobject = datetime.strptime(time_str, '%H:%M').time()
except ValueError:
# input includes seconds, perhaps
timeobject = datetime.strptime(time_str, '%H:%M:%S').time()
To update the time given a timezone, get a timezone database that supports your timezone string first; the pytz library is regularly updated.
from pytz import timezone
timezone = pytz.timezone(time_zone_str)
How you use it depends on what you are trying to do. If the input time is not in UTC, you can simply attach the timezone to a datetime() object with the datetime.combine()method, after which you can move it to the UTC timezone:
dt_in_timezone = datetime.combine(datetime.now(), timeobject, timezone)
utc_timeobject = dt_in_timezone.astimezone(pytz.UTC).time()
This assumes that 'today' is good enough to determine the correct offset.
If your time is a UTC timestamp, combine it with the UTC timezone, then use the pytz timezone; effectively the reverse:
dt_in_utc = datetime.combine(datetime.now(), timeobject, pytz.UTC)
timeobject_in_timezone = dt_in_timezone.astimezone(timezone).time()
To store just the offset for bulk application, pass in a reference date to the timezone.utcoffset() method:
utc_offset = timezone.utcoffset(datetime.now())
after which you can add this to any datetime object as needed to move from UTC to local time, or subtract it to go from local to UTC. Note that I said datetime, as time objects also don't support timedelta arithmetic; a timedelta can be larger than the number of seconds left in the day or the number of seconds since midnight, after all, so adding or subtracting could shift days as well as the time:
# new time after shifting
(datetime.combine(datetime.now(), timeobject) + utc_offset).time()
For completion sake, you can't pass in a pytz timezone to a time object; it just doesn't have any effect on the time. The timezone object returns None for the UTC offset in that case, because it can't give any meaningful answer without a date:
>>> from datetime import time
>>> from pytz import timezone
>>> tz = timezone('America/New_York')
>>> time_with_zone = time(12, 34, tzinfo=tz)
>>> time_with_zone
datetime.time(12, 34, tzinfo=<DstTzInfo 'America/New_York' LMT-1 day, 19:04:00 STD>)
>>> time_with_zone.utcoffset()
>>> time_with_zone.utcoffset() is None
True
>>> tz.utcoffset(None) is None # what time_with_zone.utcoffset() does under the hood
None
So for all intents an purposes, time_with_zone is just another naive time object as the tzinfo object attached doesn't actually have any effect.
Moreover, because there is no date to determine the correct timezone information, pytz selects the earliest known 'New York' timezone, and that's not exactly a recent one; look closely at that tzinfo representation:
tzinfo=<DstTzInfo 'America/New_York' LMT-1 day, 19:04:00 STD>
^^^^^^^^^^^^^^^^^^^^^^^
That's the timezone introduced in 1883 by the railroads; the 'modern' EST timezone was not introduced until the 20th century. This is why timezone objects are usually passed in a date when determining the offset:
>>> tz.utcoffset(datetime(1883, 6, 28))
datetime.timedelta(-1, 68640)
>>> tz.utcoffset(datetime(1918, 6, 28))
datetime.timedelta(-1, 72000)
|
[
"stackoverflow",
"0027530945.txt"
] |
Q:
subprocess cp destination file empty
I'm writing a script which writes it's output to a system directory. Rather than run the entire script using root permissions, I'm writing the output to a temporary file and only using elevated privileges when copying the temporary file to the output.
print(tempfile.read())
return_code = suprocess.call(['/usr/bin/sudo', 'cp', tmpfile.name, outfile])
if return_code != 0:
print('Copy failed')
sys.exit(1)
return_code = subprocess.call(['/usr/bin/sudo', 'chmod', '664', outfile])
with open(outfile) as f2:
print(f2.read())
The first debug prints out the expected contents of the generated file, but the second dprint is empty. In addition, inspecting the file in the filesystem says the file is 0 bytes in length and owned by root.
I've tried the following and it doesn't seem to make a difference:
using shell=True
using a tempfile.NamedTempfile or creating a temporary file myself and cleaning up
A:
Solved the problem. tempfile was still open for writing when cp was called and the write hadn't flushed to disk when the copy was attempted.
|
[
"stackoverflow",
"0039469358.txt"
] |
Q:
Swift: Cocoa Bindings on button raises unrecognized selector
My goal is to create a MacOS app that will run some security tests and display the result in a TableView. For each failing test, I want the user to be able to click on a "Fix!" button.
I tried to do this using Cocoa Bindings and Swift 3 on Xcode 8. It seems to work, but I cannot set the button to perform the selector I want.
I followed this example that I tried to adapt to swift: https://developer.apple.com/library/mac/samplecode/BoundButton/Introduction/Intro.html#//apple_ref/doc/uid/DTS10004366-I…
I can get everything working, but when I click on the button I get the following error:
2016-09-13 13:23:20.978223 SampleCocoaBinding[31429:1142008]
-[SampleCocoaBinding.TestController MyClassAction:]: unrecognized selector sent to instance 0x600000029ea0
I use this function as the action:
func MyClassAction(sender: AnyObject) -> Void {
debugPrint(sender)
}
I created a test project and pushed it on github: https://github.com/ftiff/SampleCocoaBinding/tree/master/SampleCocoaBinding
Could someone have a look? Either it's a bug or I didn't understand something key.
A:
The default signature of an IBAction in Swift 3 is
func MyClassAction(_ sender: AnyObject)
|
[
"stackoverflow",
"0034118084.txt"
] |
Q:
Web Platform and IIS CAN'T FIND MANAGEMENT SERVER
I'm trying to have the management service in the IIS Manager. I know that to do that I need to add and install it in the web platform installer.
I'm having a difficulty finding it. I've even installed IIS: Management Scripts and Tools and IIS: Management Tools hoping that Management service will show up but it won't. I've also installed Web Deploy 3.5.
Question is, where can I find the management service?
I'm using web platform 5.0.
A:
That management service icon only appears if you are managing a Windows Server.
|
[
"stackoverflow",
"0046019212.txt"
] |
Q:
Items are not appearing in Listview
I apologize if I'm missing something simple, I'm still learning. This is my first attempt at recursion. this program is supposed to do the following, First I open my FileBrowserDialog, then the listview Populates with the file names within the folder selected. However, when I select the folder it fills the listview but I cannot see any names and my listview freezes. the reason I know it fills is the scroll bar adjusts. this is my code:
#region FileHandlers
void FolderSearch(string sFol)
{
try
{
foreach (string d in Directory.GetDirectories(sFol))
{
foreach (string f in Directory.GetFiles(d))
{
listView1.Items.Add(f);
}
FolderSearch(d);
}
}
catch (System.Exception excpt)
{
MessageBox.Show(excpt.Message);
}
}
public void ChooseFolder()
{
string pPath;
if(folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
pPath = folderBrowserDialog1.SelectedPath;
FolderSearch(pPath);
}
}
#endregion
void Button1Click(object sender, EventArgs e)
{
ChooseFolder();
}
A:
Your code skips the selected folder and it will only get files from subfolders within selected folder, because you are first calling GetDirectories method, if you don't have subfolders within selected folder or your subfolders dont have files, it will get nothing.
Try this
void FolderSearch(string sFol)
{
try
{
foreach (string f in Directory.GetFiles(sFol))
{
listView1.Items.Add(f);
}
foreach (string d in Directory.GetDirectories(sFol))
{
FolderSearch(d);
}
}
catch (System.Exception excpt)
{
MessageBox.Show(excpt.Message);
}
}
and also if you want only file name use GetFileName method from System.IO.Path class. listView1.Items.Add(Path.GetFileName(f));
|
[
"stackoverflow",
"0026127919.txt"
] |
Q:
Clojure - how to build up a data structure, possibly incrementally
New to Clojure.
I am trying to build up a data structure programmatically for insertion into a database. I actually have something that works just fine, but it does an insert for each record, and I'd like to generate the whole record, and then insert the whole thing at once with one insert.
Here is what I have working so far:
(doseq [record-data1 [:one :two :three]
(doseq [record-data2 [1 2 3]]
(insert {record-data1 record-data2})
Any suggestions on how to generate the entire bulk structure first before insert? Have tried variations on map, walk, etc. but haven't been able to come up with anything yet.
Thanks.
A:
I'm not sure I understand what you mean by "entire bulk structure". You can't put the cross-product of record-data1 and record-data2 in the same dictionary. Maybe you're looking for this:
user=> (for [record-data1 [:a :b :c] record-data2 [1 2 3]] {record-data1 record-data2})
({:a 1} {:a 2} {:a 3} {:b 1} {:b 2} {:b 3} {:c 1} {:c 2} {:c 3})
|
[
"stackoverflow",
"0033973562.txt"
] |
Q:
Permute a list using Python
I have a list with the following elements: A,B,C,D,E,F,G.
They are either suppose to true or false hence represented by 1 and 0 respectively.
I am supposed to get a combinations but the following restrictions stay:
Element C and Fare to be true in all cases, ie,1`.
When element A is true, element E, and G can be false.
When element B is true, element D can be false.
A:
What you want is not permutations, but product. Also, I interpret restrictions as:
C and F cannot be false
If A is false, E and G cannot be false
If B is false, D cannot be false
With that, the code is as followed:
import pprint
from itertools import product
def myproduct():
keys = 'abcdefg'
values = [(0, 1) for k in keys]
for value in product(*values):
d = dict(zip(keys, value))
# Skip: C and F that are 0 (False)
if d['c'] == 0 or d['f'] == 0:
continue
# Skip: When A is false, E and G cannot be false
if d['a'] == 0 and (d['e'] == 0 or d['g'] == 0):
continue
# Skip: When B is false, D cannot be false
if d['b'] == 0 and d['d'] == 0:
continue
yield d # This 'permutation' is good
for d in myproduct():
pprint.pprint(d)
Output:
{'a': 0, 'b': 0, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1}
{'a': 0, 'b': 1, 'c': 1, 'd': 0, 'e': 1, 'f': 1, 'g': 1}
{'a': 0, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1}
{'a': 1, 'b': 0, 'c': 1, 'd': 1, 'e': 0, 'f': 1, 'g': 0}
{'a': 1, 'b': 0, 'c': 1, 'd': 1, 'e': 0, 'f': 1, 'g': 1}
{'a': 1, 'b': 0, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 0}
{'a': 1, 'b': 0, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1}
{'a': 1, 'b': 1, 'c': 1, 'd': 0, 'e': 0, 'f': 1, 'g': 0}
{'a': 1, 'b': 1, 'c': 1, 'd': 0, 'e': 0, 'f': 1, 'g': 1}
{'a': 1, 'b': 1, 'c': 1, 'd': 0, 'e': 1, 'f': 1, 'g': 0}
{'a': 1, 'b': 1, 'c': 1, 'd': 0, 'e': 1, 'f': 1, 'g': 1}
{'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 0, 'f': 1, 'g': 0}
{'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 0, 'f': 1, 'g': 1}
{'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 0}
{'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1, 'f': 1, 'g': 1}
Notes:
values is a list of (0, 1):
[(0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1)]
Each value is a tuple of 7 numbers such as:
(1, 1, 1, 0, 0, 1, 0)
d is a dictionary in which the keys are a, b, ... and the values are 0 and 1
|
[
"stackoverflow",
"0019638025.txt"
] |
Q:
run time type information (why this code don't work)
I have a code similar to this (simplified to help present the problem)
class a
{
protected:
int m_x;
public:
a(int x):m_x(x){};
~a(){};
virtual int GetX()=0;
}
class b:public a
{
public:
b(int x):a:(x){};
~b(){};
virtual int GetX(){return m_x+2;};
}
class c:public a
{
public:
c(int x):a:(x){};
~c(){};
virtual int GetX(){return m_x+4;};
}
I also have these functions:
vector<a> GetData()
{
vector<a> data;
data.push_back(b(1));
data.push_back(c(1));
}
void printData()
{
vector<a> data=GetData();
for(int I=0;i<data.size();I++)
{
cout<< data[I].GetX()<<endl;
}
}
The above program did not compile by error that a class with virtual function can not be instantiated.
so I changed a to this one:
class a
{
protected:
int m_x;
public:
a(int x):m_x(x){};
~a(){};
virtual int GetX()={return m_x};
}
But I am not getting the correct result as I thought since I created objects of type b and c then when I call GetX, their function should be called and not of a. so I am getting this data:
1
1
instead of
3
5
How can I fix this problem?
Is there any switch in compiler that I should turn on to get this to work?
I am using visual studio 2012.
A:
You need to use a vector of pointers. Fortunately, since you are using VS2012, you have modern smart pointers (with some other C++11 goodness):
typedef std::vector<std::unique_ptr<a>> DataVector;
DataVector GetData() {
DataVector data;
data.push_back(std::unique_ptr<b>(new b(1)));
data.push_back(std::unique_ptr<c>(new c(1)));
return data;
}
void PrintData() {
for(const auto & datum : GetData())
std::cout << datum->GetX() << std::endl;
}
|
[
"stackoverflow",
"0026632474.txt"
] |
Q:
UITextView textContainer exclusion path fails if full width and positioned at top of textContainer
In iOS 8, I'm trying to add a UIImageView as a subview of a UITextView, similar to what's shown here - but with the text below the image.
I want to do it using an exclusion path because on other devices, I might position the image differently depending on the screen size.
However there's a problem where if the CGRect used to create the exclusion path has a Y origin of 0, and takes up the full width of the textView, the exclusion fails and the text appears within exclusion path (so that the text is shown behind the imageView, as you can see in that screenshot).
To test this I built a simple app using the "single view" Xcode template, with the following:
- (void)viewDidLoad {
[super viewDidLoad];
// set up the textView
CGRect frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
UITextView *textView = [[UITextView alloc] initWithFrame:frame];
[textView setFont:[UIFont systemFontOfSize:36.0]];
[self.view addSubview:textView];
textView.text = @"I wish this text appeared below the exclusion rect and not within it.";
// add the photo
CGFloat textViewWidth = textView.frame.size.width;
// uncomment if you want to see that the exclusion path DOES work when not taking up the full width:
// textViewWidth = textViewWidth / 2.0;
CGFloat originY = 0.0;
// uncomment if you want to see that the exclusion path DOES work if the Y origin isn't 0
// originY = 54.0;
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"photo_thumbnail"]];
imageView.frame = CGRectMake(0, originY, textViewWidth, textViewWidth);
imageView.alpha = 0.7; // just so you can see that the text is within the exclusion path (behind photo)
[textView addSubview:imageView];
// set the exclusion path (to the same rect as the imageView)
CGRect exclusionRect = [textView convertRect:imageView.bounds fromView:imageView];
UIBezierPath *exclusionPath = [UIBezierPath bezierPathWithRect:exclusionRect];
textView.textContainer.exclusionPaths = @[exclusionPath];
}
I also tried subclassing NSTextContainer and overriding the -lineFragmentRectForProposedRect method, but adjusting the Y origin there doesn't seem to help either.
To use the custom NSTextContainer, I set up the UITextView stack like this in viewDidLoad():
// set up the textView stack
NSTextStorage *textStorage = [[NSTextStorage alloc] init];
NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
[textStorage addLayoutManager:layoutManager];
CGSize containerSize = CGSizeMake(self.view.frame.size.width, CGFLOAT_MAX);
CustomTextContainer *textContainer = [[CustomTextContainer alloc] initWithSize:containerSize];
[layoutManager addTextContainer:textContainer];
CGRect frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
UITextView *textView = [[UITextView alloc] initWithFrame:frame textContainer:textContainer];
[textView setFont:[UIFont systemFontOfSize:36.0]];
[self.view addSubview:textView];
textView.text = @"I wish this text appeared below the exclusion rect and not within it.";
Then I adjust the Y origin in the CustomTextContainer like this... but this fails just as spectacularly:
- (CGRect)lineFragmentRectForProposedRect:(CGRect)proposedRect atIndex:(NSUInteger)characterIndex writingDirection:(NSWritingDirection)baseWritingDirection remainingRect:(CGRect *)remainingRect {
CGRect correctedRect = proposedRect;
if (correctedRect.origin.y == 0) {
correctedRect.origin.y += 414.0;
}
correctedRect = [super lineFragmentRectForProposedRect:correctedRect atIndex:characterIndex writingDirection:baseWritingDirection remainingRect:remainingRect];
NSLog(@"origin.y: %f | characterIndex: %lu", correctedRect.origin.y, (unsigned long)characterIndex);
return correctedRect;
}
I suppose this could be considered an Apple bug that I need to report (unless I'm missing something obvious), but if anybody has a workaround it would be much appreciated.
A:
This is an old bug.In the book Pushing the Limits iOS 7 Programming ,the author wrote this in page 377:
At the time of writing, Text Kit does not correctly handle some kinds of exclusion paths. In particular, if your exclusion paths would force some lines to be empty, the entire layout may fail. For example, if you attempt to lay out text in a circle this way, the top of the circle may be too small to include any text, and NSLayoutManager will silently fail. This limitation impacts all uses of NSTextContainer. Specifically, if lineFragmentRectForProposedRect:atIndex:writingDirection:remainingRect: ever returns an empty CGRect, the entire layout will fail.
Maybe you can override lineFragmentRectForProposedRect:atIndex:writingDirection:remainingRect:
of your custom NSTextContainer to workaround.
A:
I came across this problem as well. If you only need to exclude full width space at the top or bottom of the textView, you can use the textContainerInset.
|
[
"stackoverflow",
"0042963726.txt"
] |
Q:
Core Data crash: Collection was mutated while being enumerated
My app seems to be crashing when I try to perform a fetch. I'm using magical records. The error message is:
Collection <__NSCFSet: 0x17005a1f0> was mutated while being enumerated.
To me this indicates that we're changing objects in the context while performing the fetch, but I'm new to this so I might be wrong.
Here's the code it's pointing at:
- (void) buildAndFetchFRCsInContext:(NSManagedObjectContext*)context{
[context performBlock:^{
__unused NSDate* start = [NSDate date];
self.contactsFRC = [self buildFetchResultsControllerForClass:[Contact class] sortedBy:@"id" withPredicate:nil inContext:context];
self.callsFRC = [self buildFetchResultsControllerForClass:[Call class] sortedBy:@"id" withPredicate:nil inContext:context];
self.newsItemsFRC = [self buildFetchResultsControllerForClass:[NewsItem class] sortedBy:@"id" withPredicate:nil inContext:context];
NSError* error;
// Peform the fetches
[self.contactsFRC performFetch:&error];
[self.callsFRC performFetch:&error];
[self.newsItemsFRC performFetch:&error]; //Crash points to this line
NSLog(@"Spent [%@s] performing fetchs for counts!", @(fabs([start timeIntervalSinceNow])));
[self calculateAndBroadcastCounts];
}];
}
The context being passed in is:
- (instancetype) initWithUserSession:(BPDUserSession*)userSession{
self = [super init];
...
self.context = [NSManagedObjectContext MR_context];
[self buildAndFetchFRCsInContext:self.context];
...
}
What I think is that this class is being initialized in the main thread, but performBlock adds the block to a queue and then executes from a different thread. But I don't think this is true because the purpose of performBlock is to perform that block on another thread.
From what I've posted, can anyone tell what the issue is?
Update:
I tried moving the buildFetchResultsController call to outside of the perform block:
- (void) buildAndFetchFRCsInContext:(NSManagedObjectContext*)context{
self.contactsFRC = [self buildFetchResultsControllerForClass:[Contact class] sortedBy:@"id" withPredicate:nil inContext:context];
self.callsFRC = [self buildFetchResultsControllerForClass:[Call class] sortedBy:@"id" withPredicate:nil inContext:context];
self.newsItemsFRC = [self buildFetchResultsControllerForClass:[NewsItem class] sortedBy:@"id" withPredicate:nil inContext:context];
NSMutableArray *list = [[NSMutableArray alloc] initWithCapacity:100];
for (int i = 0; i < 100; i++) {
list[i] = [self buildFetchResultsControllerForClass:[NewsItem class] sortedBy:@"id" withPredicate:nil inContext:context];
}
[context performBlock:^{
__unused NSDate* start = [NSDate date];
NSError* error;
// Peform the fetches
[self.contactsFRC performFetch:&error];
[self.callsFRC performFetch:&error];
[self.newsItemsFRC performFetch:&error];
for (int i = 0; i < list.count; i++) {
[list[i] performFetch:&error]; // Generally error is thrown on i = 5 ~> 10
}
NSLog(@"Spent [%@s] performing fetchs for counts!", @(fabs([start timeIntervalSinceNow])));
[self calculateAndBroadcastCounts];
}];
}
but this still fails. I'm able to reproduce the failure with the loop shown above. I also tried creating a new context to use from within the actual performBlock closure with NSPrivateQueueConcurrencyType but this didn't work either, same issue.
Note: I'm using MagicalRecords, so for those of you who aren't familiar, [NSManagedObjectContext MR_context]; is equivalent to the context returned from:
NSManagedObjectContext *context = [[self alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; // Here self is NSManagedObjectContext
[context setParentContext:parentContext];
[context MR_obtainPermanentIDsBeforeSaving];
return context;
A:
My issue was I was performing a save on a context and that save had concurrency issues, I was trying to save objects created on the main thread from a thread that wasn't main. Moving that code to the main thread fixed the crash.
|
[
"stackoverflow",
"0021464503.txt"
] |
Q:
Practical use (and reuse) of the CONSTRUCT clause
When using CONSTRUCT in a sparql query, the output is a single RDF graph, aka a set of triples, which essentially new data. But in general, I've considered CONSTRUCT to be a way of manually creating a rule that in theory should be reusable.
In an example usage of CONSTRUCT, let's say I wanted to define something that wasn't already in the data. Here's a good example taken from an article about CONSTRUCT.
@prefix : <http://some.site.com/ont#> .
:jane :hasParent :gene .
:gene :hasParent :pat ;
:gender :female .
:joan :hasParent :pat ;
:gender :female .
:pat :gender :male .
:mike :hasParent :joan .
"The following CONSTRUCT statement creates new triples based on the ones above to specify who is who's grandfather:"
PREFIX : <http://some.site.com/ont#>
CONSTRUCT { ?p :hasGrandfather ?g . }
WHERE {?p :hasParent ?parent .
?parent :hasParent ?g .
?g :gender :male .
}
and the result:
@prefix : <http://some.site.com/ont#> .
:jane :hasGrandfather :pat .
:mike :hasGrandfather :pat .
Once I've generated the new triples as a result of CONSTRUCT queries, does that mean I have to take that data, and input it back into the database in order to start using/reusing :hasGrandfather? or can I reference the resulting RDF graph as if I would reference a dynamic table in SQL?
Are there other useful ways to interact with the triples that are generated as a result of using CONSTRUCT?
A:
If you're using SPARQL 1.1, and you're querying against a triplestore, you'd typically use INSERT to add those triples to the store (to the same graph or to a different graph). Have a look at section 3.1 from SPARQL 1.1 Update:
3.1 Graph Update
Graph update operations change existing graphs in the Graph Store but
do not explicitly delete nor create them. Non-empty inserts into
non-existing graphs will, however, implicitly create those graphs,
i.e., an implementation fulfilling an update request should silently
an automatically create graphs that do not exist before triples are
inserted into them, and must return with failure if it fails to do so
for any reason. (For example, the implementation may have insufficient
resources, or an implementation may only provide an update service
over a fixed set of graphs and the implicitly created graph is not
within this fixed set). An implementation may remove graphs that are
left empty after triples are removed from them.
SPARQL 1.1 Update provides these graph update operations: …
The fundamental pattern-based actions for graph updates are INSERT and DELETE (which can co-occur in a single DELETE/INSERT operation).
These actions consist of groups of triples to be deleted and groups of
triples to be added. The specification of the triples is based on
query patterns. The difference between INSERT / DELETE and INSERT DATA
/ DELETE DATA is that INSERT DATA and DELETE DATA do not substitute
bindings into a template from a pattern. The DATA forms require
concrete data (triple templates containing variables within DELETE
DATA and INSERT DATA operations are disallowed and blank nodes are
disallowed within DELETE DATA, see Notes 8+9 in the grammar). Having
specific operations for concrete data means that a request can be
streamed so that large, pure-data updates can be done.
Later in the same document:
Example 8:
This example copies triples from one named graph to another named
graph based on a pattern:
PREFIX dc: <http://purl.org/dc/elements/1.1/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
INSERT
{ GRAPH <http://example/bookStore2> { ?book ?p ?v } }
WHERE
{ GRAPH <http://example/bookStore>
{ ?book dc:date ?date .
FILTER ( ?date > "1970-01-01T00:00:00-02:00"^^xsd:dateTime )
?book ?p ?v
} }
|
[
"stackoverflow",
"0018103979.txt"
] |
Q:
Alternative to multiple if else statements in javascript
My question is very similar to Reduce multiple if else statements
I have multiple if else statements and I'd like to use the jquery each function to make the code more efficient, but I can't figure out how to do it.
I'm running jQuery in wordpress which I believe runs in noconflict mode, so I can't get a lot of the more (what I consider) advanced topics which give examples to work for me, as I can't understand the right function syntax to use.
If anyone could help and explain how to do it for me that would be amazing. Here is my code:
var $h6p = $("h6 + p");
var $h5p = $("h5 + p");
var $h4p = $("h4 + p");
var $h3p = $("h3 + p");
var $h2p = $("h2 + p");
var $h1p = $("h1 + p");
var $fullercolor_bg = "rgba(240,234,222,0.9)";
if($h1p.mouseIsOver()) {
$h1p.prev().css("background-color", $fullercolor_bg);
} else {
$h1p.prev().css("background-color", "");
}
if($h2p.mouseIsOver()) {
$h2p.prev().css("background-color", $fullercolor_bg);
} else {
$h2p.prev().css("background-color", "");
}
if($h3p.mouseIsOver()) {
$h3p.prev().css("background-color", $fullercolor_bg);
} else {
$h3p.prev().css("background-color", "");
}
if($h4p.mouseIsOver()) {
$h4p.prev().css("background-color", $fullercolor_bg);
} else {
$h4p.prev().css("background-color", "");
}
if($h5p.mouseIsOver()) {
$h5p.prev().css("background-color", $fullercolor_bg);
} else {
$h5p.prev().css("background-color", "");
}
if($h6p.mouseIsOver()) {
$h6p.prev().css("background-color", $fullercolor_bg);
} else {
$h6p.prev().css("background-color", "");
}
(If CSS had a previous adjacent siblings selector I would be over the moon at this point.)
Edit: Thanks for the help so far, one thing I should have mentioned is the empty setting of the else statement is deliberate. I have used CSS to target the sibling selector and the background-color is set in that, so I need that to be set. Not transparent.
A:
Maybe you can do something like this, by using the :header selector.
$(':header + p').each(function () {
var $this = $(this);
$this.prev().css({
backgroundColor: $this.mouseIsOver()? 'rgba(240,234,222,0.9)' : 'transparent'
});
});
A:
You could use an array:
var $hp = ["h6 + p", "h5 + p", "h4 + p", "h3 + p", "h2 + p", "h1 + p"],
$fullercolor_bg = "rgba(240,234,222,0.9)";
$hp.forEach(function(v) {
if($(v).mouseIsOver()) {
$(v).prev().css({
backgroundColor: $fullercolor_bg
});
} else {
$(v).prev().css({
backgroundColor: "transparent"
});
}
});
In your case I think it's simpler to use multiple CSS selectors within the variable. This may or may not work depending on the implementation of mouseIsOver:
var $hp = $("h6 + p, h5 + p, h4 + p, h3 + p, h2 + p, h1 + p"),
$fullercolor_bg = "rgba(240,234,222,0.9)";
if($hp.mouseIsOver()) {
$hp.prev().css({
backgroundColor: $fullercolor_bg
});
} else {
$hp.prev().css({
backgroundColor: "transparent"
});
}
|
[
"stackoverflow",
"0035963686.txt"
] |
Q:
Working around a very heavy encryption algorithm?
I'm in the progress of building an API in NodeJS. Our main API is built in Java in which all the ids are encrypted (one example being AA35794C728A440F).
The Node API needs to use the same encryption algorithm for compatibility.
During testing of the API, I was surprised to find that it was only able to handle somewhere in the region of 25 to 40 (depending on the AWS EC2 instance I tested with) requests per second, and that the CPU was maxing out.
Digging into it, I found the issue was with the algorithm being used, specifically that it was performing 1000 md5 operations per key per encrypt/decrypt.
Removing the encryption gave me a massive increase in throughput, up to 1200 requests per second.
I'm stuck with the algorithm - it won't be possible to change without impacting many consumers of the API, so I need to find a way to work around it.
I was wondering what the most efficient way to handle this would be, keeping in mind that I need to be able to 'encrypt' or 'decrypt'?
My question isn't so much how to make the algorithm more efficient, given that I would like to avoid the 1000 md5 ops per id, but rather, an efficient of bypassing the actual encryption itself.
I was thinking of storing all the keys (up to maybe 2 or 3 million) in a map or a tree and then doing a lookup, however that would be mean lugging around 30-50MB of ids in the repository, plus consuming a lot of memory.
A:
It sounds like, lacking any code, that a key derivation is being done on each invocation.
Key derivations are designed to be slow. Provide more information on what you are trying to accomplish and some code.
|
[
"stackoverflow",
"0025860516.txt"
] |
Q:
Varnish Cache Expiring Objects Too Quickly
I've been having a problem with my varnish (v3.0.2) cache where it keeps resetting the cache of an object after less than 60 seconds despite having a TTL of 24h, cookies stripped, content encoding normalized, non-critical headers unset, Cache-Control set to public, s-maxage=86400 etc.
For some reason, if you access the following URL repeatedly over a minute, you can see that the Age creeps up and then hits zero (with X-Cache returning MISS):
http://data.eyewire.org/volume/83329/chunk/0/1/0/1/tile/xz/32:64
There are no n_lru_nuked objects and the cache is over 60GB. I watched the varnishlog and may have seen something with ExpBan going on, but I can't for the life of me figure out why.
Here are some key parts to my vcl file:
sub vcl_recv {
set req.grace = 120s;
# normalize Accept-Encoding to reduce vary
if (req.http.Accept-Encoding) {
if (req.http.User-Agent ~ "MSIE 6") {
unset req.http.Accept-Encoding;
}
elsif (req.http.Accept-Encoding ~ "gzip") {
set req.http.Accept-Encoding = "gzip";
}
elsif (req.http.Accept-Encoding ~ "deflate") {
set req.http.Accept-Encoding = "deflate";
}
else {
unset req.http.Accept-Encoding;
}
}
# This uses the ACL action called "purge". Basically if a request to
# PURGE the cache comes from anywhere other than localhost, ignore it.
if (req.request == "PURGE")
{if (!client.ip ~ purge)
{error 405 "Not allowed.";}
return(lookup);}
if (req.http.Upgrade ~ "(?i)websocket") {
return (pipe);
}
# ....
if ( req.http.host ~ "data\.eyewire\.org" ) {
unset req.http.Cookie;
unset req.http.Accept-Language;
unset req.http.Expires;
unset req.http.Cache-Control;
unset req.http.User-Agent;
return(lookup);
}
# ....
}
sub vcl_fetch {
# ....
if ( req.http.host ~ "data.eyewire.org" ) {
if ( req.url ~ "^/volume" ) {
unset beresp.http.Set-Cookie;
set beresp.ttl = 24h;
set beresp.http.Cache-Control = "public, s-maxage=86400";
set beresp.http.X-TTL = beresp.ttl;
return(deliver);
}
elsif (req.url ~ "^/cell") {
set beresp.ttl = 1h;
return(hit_for_pass);
}
}
}
# from http://blog.bigdinosaur.org/adventures-in-varnish/
sub vcl_pass {
set bereq.http.connection = "close";
if (req.http.X-Forwarded-For) {
set bereq.http.X-Forwarded-For = req.http.X-Forwarded-For;
}
else {
set bereq.http.X-Forwarded-For = regsub(client.ip, ":.*", "");
}
}
# from http://blog.bigdinosaur.org/adventures-in-varnish/
sub vcl_pipe {
#we need to copy the upgrade header
if (req.http.upgrade) {
set bereq.http.upgrade = req.http.upgrade;
set bereq.http.connection = req.http.connection;
}
set bereq.http.connection = "close";
if (req.http.X-Forwarded-For) {
set bereq.http.X-Forwarded-For = req.http.X-Forwarded-For;
}
else {
set bereq.http.X-Forwarded-For = regsub(client.ip, ":.*", "");
}
}
# from http://blog.bigdinosaur.org/adventures-in-varnish/
sub vcl_hit {
if (req.request == "PURGE") {
purge;
error 200 "Purged.";
}
}
# from http://blog.bigdinosaur.org/adventures-in-varnish/
sub vcl_miss {
if (req.request == "PURGE") {
purge;
error 200 "Purged.";
}
}
sub vcl_deliver {
# Display hit/miss info
if (obj.hits > 0) {
set resp.http.X-Cache = "HIT";
set resp.http.X-Cache-Hits = obj.hits;
}
else {
set resp.http.X-Cache = "MISS";
}
# Security Non-Disclosure
remove resp.http.X-Varnish;
remove resp.http.X-Powered-By;
remove resp.http.Server;
return(deliver);
}
Thanks!
Edit: FYI: I had to revert some changes to my VCL to solve a problem in production, but the problem is still essentially the same.
A:
For what it's worth, I just upgraded to Varnish 4 and it seemed to solve the problem. During the upgrade we also removed the definition of vcl_hit and vcl_miss which included a purge directive that didn't seem like it was being hit but who knows.
|
[
"stackoverflow",
"0002975260.txt"
] |
Q:
bytes (1024) to string conversion (1 KB)?
I would like to know if there is a function in .NET which converts numeric bytes into the string with correct measurement?
Or we just need to follow old approach of dividing and holding the conversion units to get it done?
A:
No, there isn't.
You can write one like this:
public static string ToSizeString(this double bytes) {
var culture = CultureInfo.CurrentUICulture;
const string format = "#,0.0";
if (bytes < 1024)
return bytes.ToString("#,0", culture);
bytes /= 1024;
if (bytes < 1024)
return bytes.ToString(format, culture) + " KB";
bytes /= 1024;
if (bytes < 1024)
return bytes.ToString(format, culture) + " MB";
bytes /= 1024;
if (bytes < 1024)
return bytes.ToString(format, culture) + " GB";
bytes /= 1024;
return bytes.ToString(format, culture) + " TB";
}
|
[
"stackoverflow",
"0023194301.txt"
] |
Q:
AngularJS prevent modal open on Enter key
I have one problem with modal window.
I have couple section and in one section ( which is hidden ) I have button with ng-click='function()'.
<section class='hidden'>
<button class="mobileUpdate" ng-click="openMobileUpdateModal()">SMS</button>
</section>
openMobileUpdateModal() open modal dialog.
Problem is when I hit enter key on any input field in form it opens me modal window.
Any idea how to prevent this?
Thanks
A:
Quoting the docs on form/ngForm:
You can use one of the following two ways to specify what javascript method should be called when a form is submitted:
ngSubmit directive on the form element
ngClick directive on the first button or input field of type submit (input[type=submit])
[...]
...the following form submission rules in the HTML specification:
If a form has only one input field then hitting enter in this field triggers form submit (ngSubmit)
if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter doesn't trigger submit
if a form has one or more input fields and one or more buttons or input[type=submit] then hitting enter in any of the input fields will trigger the click handler on the first button or input[type=submit] (ngClick) and a submit handler on the enclosing form (ngSubmit)
So, depending on the rest of your setup, you could solve the problem by changing the order of buttons, by detecting and filtering key-events, by introducing additional form elements etc.
|
[
"stackoverflow",
"0044236321.txt"
] |
Q:
Git cleanup/garbage collection on remote VSO git repository
We are trying to clean up the history of a git repository hosted on VSO/team services.
Using bfg and git-filter-branch we removed about ~80% of stored objects by cleaning accidentally checken in packages folders etc.
After successfully rewriting the repository’s git history we force pushed to visualstudio.com but new clones of that repo seem to suggest that none of the objects were actually removed.
We found hints here and there indicating that TFS does not perform any garbage collection on git objects.
Is that (still) true for VSO as well?
Any improvements planned?
Deleting and recreating the repository would probably be a workaround but doesn’t seem that elegant.
A:
Yes, it’s still true for VSTS (VSO) now. But git gc on the server is in our backlog, so it will be improved in the future.
The option for now is recreating a new repo and push again (as you mentioned).
|
[
"stackoverflow",
"0023944974.txt"
] |
Q:
Unauthorized response when downloading file with Service Account in Google Drive API
I'm using the following code to get credentials from Google's Authentication server in order to access the Google drive API
public static Google.Apis.Services.BaseClientService.Initializer getCredentials()
{
String serviceAccountEmail = "[email protected]";
var certificate = new X509Certificate2(@"xxx.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { DriveService.Scope.Drive }
}.FromCertificate(certificate));
return new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "AppName",
};
}
then retrieving the Download url from the file metadata and attempting to download that file with the following code:
public static System.IO.Stream DownloadFile(Google.Apis.Drive.v2.Data.File file, Google.Apis.Drive.v2.DriveService service)
{
if (!String.IsNullOrEmpty(file.DownloadUrl))
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
new Uri(file.DownloadUrl));
// authenticator.ApplyAuthenticationToRequest(request);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
return response.GetResponseStream();
}
else
{
Console.WriteLine(
"An error occurred: " + response.StatusDescription);
return null;
}
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
}
else
{
// The file doesn't have any content stored on Drive.
return null;
}
}
However I'm receiving a 401 unauthorized response. I'm assuming I need to add an Authorization header in the request along the lines of Authorization: Bearer {ACCESS_TOKEN} but the HttpClientInitializer.Token property is null. Is it possible to authenticate this Request using the ServiceAccountCredential?
A:
I faced the same problem today. Using your approach to make a request no Authentication header is provided. I needed to construct the request a bit differently. Where you have:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
new Uri(file.DownloadUrl));
You should have:
HttpResponseMessage response = await service.HttpClient.GetAsync(new Uri(file.DownloadUrl));
This ensures that the request is properly authenticated.
|
[
"stackoverflow",
"0059706666.txt"
] |
Q:
Is there way to recover files ignored via .gitignore in the first commit?
I have a local repo. I made the mistake of adding a .gitignore file before the first commit with all the code. After adding the .gitignore file, the only files left in my repo are the ones that I wanted to ignore, that is the ones that matched my .gitignore file.
Tracing back the steps:
I had a folder.
I ran git init .
I added a regular Python .gitignore file.
I then commited adding the .gitignore file.
After this, the only files left in my directory are those who my .gitignore file was supposed to be ignoring. Confusing?
Is there a way to recover the files which were ignored in the first commit of my repo?
Below is a screenshot after running git reflog
Thanks in advance
A:
Based on the reflog output, my guess is that you ran git reset --hard, after a git add but before a git commit. This would remove all the files you had added. You may be able to recover their contents, but not their file names.
Here is an example:
$ mkdir treset
$ cd treset
$ git init
Initialized empty Git repository in ..
$ echo '*.pyc' > .gitignore
$ git add .gitignore
$ git commit -m initial
[master (root-commit) bca0228] initial
1 file changed, 1 insertion(+)
create mode 100644 .gitignore
$ echo precious data 1 > file1
$ echo precious data 2 > file2
$ git add .
$ git reset --hard
HEAD is now at bca0228 initial
$ ls
$
As you can see, the precious data files are gone!
Their data are in now-unreferenced Git blob objects, which we can have Git discover and place into its lost+found directory:
$ git fsck --lost-found
Checking object directories: 100% (256/256), done.
dangling blob 683416f292727f4659d5efa59d068189cf1b43bc
dangling blob f9d4c4040845bb7db25db33ec455d9a0c6703e68
Now, to get the content back, we look inside the appropriate directory (you can see here I forgot to include other/ in the initial cd), and inspect each file's content. The files' names are lost—they were in the index that we reset with git reset --hard, and are not saved anywhere else, but if we remember that precious data 1 means file1 and so on, we can mv the files back:
$ cd .git/lost-found/
$ ls
other
$ cd other/
$ ls
683416f292727f4659d5efa59d068189cf1b43bc
f9d4c4040845bb7db25db33ec455d9a0c6703e68
$ cat 683416f292727f4659d5efa59d068189cf1b43bc
precious data 1
$ cat f9d4c4040845bb7db25db33ec455d9a0c6703e68
precious data 2
hence:
$ mv 683416f292727f4659d5efa59d068189cf1b43bc ../../../file1
$ mv f9d4c4040845bb7db25db33ec455d9a0c6703e68 ../../../file2
gets the files back where we want them, in the work-tree of the new repository (path/to/treset in my case).
|
[
"stackoverflow",
"0048509419.txt"
] |
Q:
why I must reshape one image to [n,height,width,channel] in CNN
I try to apply a convolutional layer to a picture of shape [256,256,3]
a have an error when I user the tensor of the image directly
conv1 = conv2d(input,W_conv1) +b_conv1 #<=== error
error message:
ValueError: Shape must be rank 4 but is rank 3 for 'Conv2D' (op: 'Conv2D')
with input shapes: [256,256,3], [3,3,3,1].
but when I reshape the function conv2d work normally
x_image = tf.reshape(input,[-1,256,256,3])
conv1 = conv2d(x_image,W_conv1) +b_conv1
if I must reshape the tensor what the best value to reshape in my case and why?
import tensorflow as tf
import numpy as np
from PIL import Image
def img_to_tensor(img) :
return tf.convert_to_tensor(img, np.float32)
def weight_generater(shape):
return tf.Variable(tf.truncated_normal(shape,stddev=0.1))
def bias_generater(shape):
return tf.Variable(tf.constant(.1,shape=shape))
def conv2d(x,W):
return tf.nn.conv2d(x,W,[1,1,1,1],'SAME')
def pool_max_2x2(x):
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,1,1,1],padding='SAME')
#read image
img = Image.open("img.tif")
sess = tf.InteractiveSession()
#convetir image to tensor
input = img_to_tensor(img).eval()
#print(input)
# get img dimension
img_dimension = tf.shape(input).eval()
print(img_dimension)
height,width,channel=img_dimension
filter_size = 3
feature_map = 32
x = tf.placeholder(tf.float32,shape=[height*width*channel])
y = tf.placeholder(tf.float32,shape=21)
# generate weigh [kernal size, kernal size,channel,number of filters]
W_conv1 = weight_generater([filter_size,filter_size,channel,1])
#for each filter W has his specific bais
b_conv1 = bias_generater([feature_map])
""" I must reshape the picture
x_image = tf.reshape(input,[-1,256,256,3])
"""
conv1 = conv2d(input,W_conv1) +b_conv1 #<=== error
h_conv1 = tf.nn.relu(conv1)
h_pool1 = pool_max_2x2(h_conv1)
layer1_dimension = tf.shape(h_pool1).eval()
print(layer1_dimension)
A:
The first dimension is the batch size. If you are feeding 1 image at a time you can simply make the first dimension 1 and it doesn't change your data any, just changes the indexing to 4D:
x_image = tf.reshape(input, [1, 256, 256, 3])
If you reshape it with a -1 in the first dimension what you are doing is saying that you will feed in a 4D batch of images (shaped [batch_size, height, width, color_channels], and you are allowing the batch size to be dynamic (which is common to do).
|
[
"math.stackexchange",
"0001294653.txt"
] |
Q:
integrate $1/(x(x^2-1)^{1/2})$
$$\int\frac{1}{x (x^2-1)^{1/2}} \, dx=\text{ ?}$$
Hi! I'm new to the website and I didn't learn math in English so I may make mistakes with terminology. I have given a math homework and it says the answer is $\arccos(x^{-1})+c$
I used wolframalpha to check if the answer is true but it gave me a different result. However when I tried to derivative $\arccos(x^{-1})$ with wolfram alpha with gave me right the answer assuming x is positive. I'm a high school senior and I don't know advanced math, please try to use more simple math but all answers are welcomed.
A:
Notice that $$\int{\frac{dx}{x\sqrt{x^{2}-1}}}= \int{\frac{1}{\sqrt{1-(\frac{1}{x})^{2}}}\frac{dx}{x^{2}}}= \int{\frac{-d(\frac{1}{x})}{\sqrt{1-(\frac{1}{x})^{2}}}} = -\arcsin(\frac{1}{x}) + C$$ or if you prefer you can make the change of variable $y=\frac{1}{x}$
|
[
"parenting.stackexchange",
"0000024829.txt"
] |
Q:
My son is being hit by a friend, and we need to discuss the situation with his mom
I have two kids, an 8-year-old son and a 6-year-old daughter--second grade and first grade, respectively. They are both tiny. My son is only 46 pounds.
A child entered my daughter's first-grade class. Let's call the boy Joe. He's big, maybe 60 pounds. He's had behavioral problems his whole life, and his mom chose to homeschool him for kindergarten after he was removed from preschool.
Joe gets overstimulated easily and hits impulsively. He doesn't understand what he's doing is wrong. Dozens of teachers, social workers, and parents have urged the boy's mother to seek professional help, but she refuses. A petition to have Joe removed from the school was quashed in favor of an IEP (Individualized Education Program), which sometimes works.
We are (were) his only friends. As a family, we are compassionate and forgiving. Joe hit my daughter twice, but that was months ago, and she is willing to be his friend (they are in the same class). However, she is extremely sensitive to aggression; we don't even watch Disney movies.
A few weeks ago, Joe hit my son in the park and hurt him pretty bad. My son doesn't want to be friends anymore which I agree with. Joe's mom wants my daughter to still be his friend; he has no others.
The boy's mom asks if Joe and my daughter can have a play date at her house without my son present.
I have not responded to this request. Also, my daughter's birthday is coming up, and my son requests Joe not be invited. Joe is aggressive towards my son in almost every social setting, but we do better in small play date situations.
My questions:
1) What can I tell the mom about Joe and my daughter having a play date (without me? of course not). My instinct is to say when he gets professional help, we can try again, but that seems too pushy.
2) What is your feeling about my daughter's birthday party? My instinct is to not invite him because it would definitely harm my son's experience.
Edit: 4/20/17
The situation was resolved--mostly. We simply cut off contact. Joe's parents didn't object in any way; they've been through it before. He wasn't invited to my daughters party, but his mom and he briefly crashed to give a card. Joe invited us to his birthday. I dropped by with a card and $10 at the beginning without my kids. Nobody else came.
My son wants to do Scouts. Joe's in Scouts. Perfect. At the introductory meeting, I saw Joe hit 4 kids including my son, and I wasn't even paying attention to him for the most part. I'm going to ask his parents to keep Joe away from my son, or I'm just going to start calling the police. (His dad is one of the scout leaders.)
Update 8/2019
Joe has slowly gotten better with his aggression. However, I had to take a knife away from him at a Cub Scout event (in now the Pack leader). I talked with a classmate of his. I mentioned Joe seems to be hitting kids less. The boy responded, "Yeah, but he wants to." Great. Joe and my son actually shared a tent at a Scout campout, and it went fine. It was out of desperation in frigid conditions. (May and October are not safe for consistent weather in the US's Upper Midwest.) We invited Joe to my daughter's 10-yo birthday, but we haven't had any play dates.
A:
I'm not a professional, but my view is that you don't have any relationship whatsoever with a person who has harmed your children unless the wish for a relationship comes entirely from the child who was harmed, with no prompting or encouragement. Doing so delivers to your child a message that they're expected to accept abuse and allow abusive people to remain in their lives. This is not a good lesson for any child to hear.
To clarify: I'm not saying you should maintain a relationship even if the child wants to; that situation is more complicated and it's not the OP's situation anyway. In other words, "unless" above expresses a necessary, but not necessarily sufficient, condition.
A:
How you act in this situation depends a lot on how much you and your daughter want to see this friendship continue. Make sure to evaluate this from the perspective of how it affects your children, not Joe. I know this might come off as a bit heartless, but Joe isn't your responsibility. Your children are. As such you need to worry about what is best for them.
No matter what you decide, bring up your concerns with Joe's mother. Tell her you are worried about the physical and emotional well-being of both of your kids. As long as Joe is aggressive, you can't have him near your son (and possibly your daughter). Let her know that something needs to be done before you are willing to let Joe be with your kids. You don't need to specify what has to happen, but you can lay out a completely reasonable expectation that whatever happens needs to assure the safety of your children.
If she makes a reasonable effort to get Joe help, you can then decide if you are comfortable having him hang around your kids. If she doesn't, or what she does is insufficient, don't allow your kids to play with Joe (hopefully it doesn't come to this, but you can't control what others will do). Maybe this will help Joe and his mother to realize that something needs to be done and then Joe can get the help he really needs.
Good luck.
Addendum regarding the birthday party:
For the birthday specifically, that gets tricky in that your daughter may want Joe there but your son clearly does not. If Joe's mom or someone could keep an real close eye on him (or if he can get some help prior to the party) you could allow it if you are comfortable (you will have to work with your son to help him feel safe). But again it boils down to taking care of your kids first and then what you are comfortable with. Trying to weigh your children's opposing desires along with your responsibility to your kids is really only something you can do. Talk it out with your kids / partner.
A:
Your kids' need to feel safe is more important than this other kid's need to have friends, and you need to tell the other mother that.
|
[
"stackoverflow",
"0015943595.txt"
] |
Q:
Jquery Parsing json and get specific value
This is my response
["{\"id\":1,\"name\":\"JOHN\"}","{\"id\":2,\"name\":\"MICHEAL\"}"]
var json = JSON.parse(demp);
console.log(json[0].id); says undefined.
How to get id and name ?
Thank you
A:
My suggestion is to use a loop to iterate in array as you have suggested in the question.
To me your response is an array so you should JSON.parse() the array instead just var demp:
var DEMP = ["{\"id\":1,\"name\":\"JOHN\"}", "{\"id\":2,\"name\":\"MICHEAL\"}"];
for (var i = 0, syze = DEMP.length; i < syze; i++) {
var json = JSON.parse(DEMP[i]);
console.log('Response ID is --> '+json.id +
' Response name is --> ' + json.name);
}
Demo Fiddle
|
[
"stackoverflow",
"0010403419.txt"
] |
Q:
Some questions about AsyncTask
As far as I understand in an AsyncTask only doInBackground is executed in its own task. All other methods - e.g. onPostExecute - are executed in the Activity task.
Is it true, that onPostExecute and let's say onCofigurationChanged are in fact synchronized?
Does the system clean up a task, if it is finished or canceled and no longer referenced?
A:
Both onPostExecute and onConfigurationChanged are executed on the "UI thread" therefore executed one after another (in any order). There's a single UI Thread per application.
As with any Java object garbage collector eventually cleans up AsyncTask if it's no longer referenced.
|
[
"italian.stackexchange",
"0000006097.txt"
] |
Q:
Cos'è "l'inconsulto"?
Nel racconto Il cielo di pietra, di Italo Calvino, ho letto questa frase (il corsivo è mio):
Ma per Rdix, attratta come sempre dal raro e dall'inconsulto, c'era l'impazienza d'appropriarsi di qualcosa d'unico, buono o cattivo che fosse.
Ho letto la definizione dell'aggettivo "inconsulto" nel vocabolario Treccani. Comunque, non sono sicura di aver capito cosa sia "l'inconsulto" nella frase precedente. Significa che Rdix era attratta dal rischio in modo imprudente?
A:
Inconsulto è un aggettivo, usato some sostantivo nel testo di Calvino, che si riferisce ad atti, gesti o altre azioni fatte in maniera avventata, con imprudenza.
Fatto senza riflettere, in modo avventato, temerario, imprudente: atto, gesto inconsulto; un'impresa inconsulta.
Il significato sembra riferirsi al fatto che Rdix sia attratta dalle cose rare e dalle azioni fatte in maniera inconsulta.
|
[
"stackoverflow",
"0044472676.txt"
] |
Q:
Python + Selenium + Webscraping slow
print ('Page Loaded')
myelem = driver.find_elements_by_xpath(".//tr[contains(@class, 'inlineListRow')]")
with open("systext.csv","wb") as f:
writer = csv.writer(f)
for myinfo in myelem:
anotherlist = []
itemize = myinfo.find_elements_by_xpath(".//td[contains(@class, 'inlineListBodyCell')]")
for peritem in itemize:
anotherlist.append(peritem.text)
writer.writerows([anotherlist])
for peritem in itemize:
anotherlist.append(peritem.text)
writer.writerows([anotherlist])
Im trying to extract info from a website then, write it to a csv
i get all elements then get each element's sub element
the code i got works
Problem is that it takes 10+ mins to complete my loop is that normal or
is my code not efficient for the task
Data is 13 col by 1800 Rows total size is a 400kb
A:
I don't know whole code but it should be something like:
print('Page Loaded')
myelem = driver.find_elements_by_xpath(".//tr[contains(@class, 'inlineListRow')]")
async def iterate(w, info):
anotherlist = []
itemize = info.find_elements_by_xpath(".//td[contains(@class, 'inlineListBodyCell')]")
for peritem in itemize:
anotherlist.append(peritem.text)
# if in this nested loop by anotherlist you meant anotherlist2 otherwhise remove it
# anotherlist2.append(peritem.text)
# writer.writerows([anotherlist2])
w.writerows([anotherlist])
return
with open("systext.csv","wb") as f:
writer = csv.writer(f)
for myinfo in myelem:
iterate(writer, myinfo)
|
[
"latin.stackexchange",
"0000013922.txt"
] |
Q:
A Completed Action in the Mind OR Indirect Speech?
There are currently two theories (of which I am aware) to explain the use of the perfect subjunctive, in examples from the Latin Vulgate, included in brianpck's answer to Q: Memento quod <subjunctive>. One of these:
"memento quod et ipse servieris in Aegypto et eduxerit te inde Dominus Deus tuus." (Deut 5:15) =
"Remember both that you served as a slave, in Egypt, and that the Lord your God, himself, lead you out of there."
The theories:
(1) Given that the writer/ speaker is telling a second person what a third party (God) did--this would normally be expressed as indirect speech, "se eduxisse", as opposed to the perfect subjunctive, "eduxerit". Therefore, the perfect subjunctive, here, is an evolved form (4th. Century) of indirect speech, possibly unique to the Vulgate.
Thanks to Figulus: "...if you view attributed causes as an implicit case of indirect speech..."aufugit quod timebat" = "he ran away because, I say, he was afraid" and "aufugit quod timeret" = "he ran away because, he says, he was afraid" (Woodcock #240). Here, the switch to subjunctive, as always, indicates someone's mental state, and it indicates a switch to a point of view other than the speaker's. In "memento quod sumpseris" (9th. Century verse) it could be interpreted to mean "remember that you say you took up". This is obviously not an explicit case of indirect speech. the words "you say" do not appear explicitly, but may be present implicitly, as implied by the subjunctive."
(2) Figulus: "The subjunctive emphasises what is going on in someone's mind, whether true or not."
The corollary: here, a perfect subjunctive describes a completed action in the mind/ thoughts/ memory.
In the above example (Deut. 5:15) there are two perfect subjunctives. It could be argued that each is fulfilling the same role. The speaker tells the second person to remember (memento quod...) a completed action from his memory (Ben Kovitz: "The subjunctive emphasises the person doing the remembering..."). If correct, this must obviate the requirement to express the action of the third party (God) as indirect speech. The grammatical priority goes, not to the third party, but to the recollection from the memory of the second person.
Concluding, the perfect subjunctive, in the Vulgate examples is either a form of indirect speech; a completed thought in the mind; a hybrid of the two.
Any thoughts?
A:
I think that there is a third option, the generic subjunctive (Woodcock #155). "Remember that you were the kind of person who was a slave in Egypt, and that the Lord your God himself is the kind who led you out."
There are probably other possible type as well.
But I think your comment about the "hybrid" is a preceptive one. The subjunctive has so many uses that in any one particular case, it can be hard to decide which of many headings it might fall under. This is part of what one reviewer called the delightful vagueness of Latin.
|
[
"stackoverflow",
"0027030457.txt"
] |
Q:
Sprite Kit Remove SKSpriteNodes within Array within -Update method
I have an array of sprites in sprite kit and in my update method I check to see if these sprites fall off the bottom of the screen. If they do, I remove them from their parent and I remove them from their array..what I am wondering is if they way I am doing it if it is the best practice? Is it going to slow down performance? If so, what is the best way to go about accomplishing this?
Here's my code:
-(void)update:(CFTimeInterval)currentTime {
// Detect when animals fall off bottom of screen
NSMutableArray *animalsToDiscard = [NSMutableArray array];
for (SKSpriteNode* node in animalsArray) {
if (node.position.y < -node.size.height) {
NSLog(@"Remove Animal - Lose Life");
[node removeFromParent];
[animalsToDiscard addObject:node];
}
}
[animalsArray removeObjectsInArray:animalsToDiscard];
}
A:
You should use the built in physics world to help solve this task. Basically, you would build a "floor" and if your animal contacts it, remove the animal node.
https://stackoverflow.com/a/24195006/2494064
In this link, your "animal" would be the equivalent of "bubble". The code will work if you make that substitution.
|
[
"stackoverflow",
"0027681716.txt"
] |
Q:
Accessing config variables stored in maps by key
I have a variable in groovy like below:
project.Map
{
time.'1 1 * ?' = ['T1']
time.'2 1 * ?' = ['T2']
templates.'T1' = ['Z','X','Y']
templates.'T2' = ['Q']
}
Sorry but I am new to groovy ,when i try to access the individual
variable values in project.map how do i access them
i tried something like below
log.info(grailsApplication.config.project.Map.time[1])
log.info(grailsApplication.config.project.Map.get('time.'2 1 * ?'' ))
log.info(grailsApplication.config.project.Map.get('time[0]' ))
log.info(grailsApplication.config.project.Map.time.get('1 1 * ?'))
but they all print null value or object references.how do i access values for
time and templates both within a for loop and without it.
A:
please see http://grails.org/doc/latest/guide/conf.html#config for the ways the config is allowed to nest. your outer syntax is especially mentioned to not be allowed:
However, you can't nest after using the dot notation. In other words, this won't work:
// Won't work!
foo.bar {
hello = "world"
good = "bye"
}
You have to write it as
project { Map { ... } }
The inner dotted parts (with the assignment) are ok (according to the doc)
|
[
"stackoverflow",
"0061289162.txt"
] |
Q:
Getting ActionContext of an action from another
Can I get an ActionContext or ActionDescriptor or something that can describe a specific action based on a route name ?
Having the following controller.
public class Ctrl : ControllerBase
{
[HttpGet]
public ActionResult Get() { ... }
[HttpGet("{id}", Name = "GetUser")]
public ActionResult Get(int id) { ... }
}
What I want to do is when "Get" is invoked, to be able to have access to "GetUser" metadata like verb, route parameters , etc
Something like
ActionContext/Description/Metadata info = somerService.Get(routeName : "GetUser")
or
ActionContext/Description/Metadata info = somerService["GetUser"];
something in this idea.
A:
There is a nuget package, AspNetCore.RouteAnalyzer, that may provide what you want. It exposes strings for the HTTP verb, mvc area, path and invocation.
Internally it uses ActionDescriptorCollectionProvider to get at that information:
List<RouteInformation> ret = new List<RouteInformation>();
var routes = m_actionDescriptorCollectionProvider.ActionDescriptors.Items;
foreach (ActionDescriptor _e in routes)
{
RouteInformation info = new RouteInformation();
// Area
if (_e.RouteValues.ContainsKey("area"))
{
info.Area = _e.RouteValues["area"];
}
// Path and Invocation of Razor Pages
if (_e is PageActionDescriptor)
{
var e = _e as PageActionDescriptor;
info.Path = e.ViewEnginePath;
info.Invocation = e.RelativePath;
}
// Path of Route Attribute
if (_e.AttributeRouteInfo != null)
{
var e = _e;
info.Path = $"/{e.AttributeRouteInfo.Template}";
}
// Path and Invocation of Controller/Action
if (_e is ControllerActionDescriptor)
{
var e = _e as ControllerActionDescriptor;
if (info.Path == "")
{
info.Path = $"/{e.ControllerName}/{e.ActionName}";
}
info.Invocation = $"{e.ControllerName}Controller.{e.ActionName}";
}
// Extract HTTP Verb
if (_e.ActionConstraints != null && _e.ActionConstraints.Select(t => t.GetType()).Contains(typeof(HttpMethodActionConstraint)))
{
HttpMethodActionConstraint httpMethodAction =
_e.ActionConstraints.FirstOrDefault(a => a.GetType() == typeof(HttpMethodActionConstraint)) as HttpMethodActionConstraint;
if(httpMethodAction != null)
{
info.HttpMethod = string.Join(",", httpMethodAction.HttpMethods);
}
}
// Special controller path
if (info.Path == "/RouteAnalyzer_Main/ShowAllRoutes")
{
info.Path = RouteAnalyzerRouteBuilderExtensions.RouteAnalyzerUrlPath;
}
// Additional information of invocation
info.Invocation += $" ({_e.DisplayName})";
// Generating List
ret.Add(info);
}
// Result
return ret;
}
|
[
"meta.stackexchange",
"0000029405.txt"
] |
Q:
View Most Popular Questions by favorite count / views / votes
When can we expect to see a page or pages containing some of the most popular questions on Stack Overflow?
A:
Already exists.
Popularity by votes:
https://stackoverflow.com/questions?sort=votes
Popularity by views (here 250 views as minimum):
https://stackoverflow.com/search?q=views%3A250
A:
The Stack Exchange Data Explorer can be used to find the most viewed questions using this data query.
If you wish you can make a fork of the query to customise the results displayed to include more or less details regarding each question. (e.g. Comments, Answers, Favourites, Votes)
Change the last line:
ORDER BY ViewCount DESC
to
ORDER BY AnswerCount DESC
to sort by answers, or
ORDER BY FavoriteCount DESC
to sort by favorites, or
ORDER BY Score DESC
to sort by votes/score.
|
[
"stackoverflow",
"0010601370.txt"
] |
Q:
Preventing Time Zone values from host DB from overriding by client
Morning:
In a question I previously asked I picked up some helpful tips on managing the time zone value in a PL SQL query.
I misunderstood the issue, however.
We have a table where records are being written with dates and times that vary across time zone. These records are being queried by a C# assembly and being sent over to an AXIS service.
When the record gets to the AXIS service, which is hosted in India, the timezone changes to IST.
What I need to do is ensure that the time zone that was in the record is the time zone that is received when the data is queried from any other time zone.
How would I do this? I'm not sure this is so much an Oracle/PL SQL query issue, and if it isn't please set me straight.
Thanks for any insight.
A:
What data types are being passed around?
Based on your previous question, the data type you are using in Oracle is a DATE. An Oracle DATE does not have a time zone associated with it. Unless you are storing a time zone in a separate column that you're not mentioning, that implies that somewhere else in the stack, a DATE is being read from Oracle (or written to Oracle) with a time zone implied. Whatever component of the stack is implying a time zone would then be the culprit.
From an Oracle perspective, the best option is to use a TIMESTAMP WITH [LOCAL] TIME ZONE data type so that Oracle knows the time zone. You can then in PL/SQL convert a timestamp in one time zone to a timestamp in another time zone. So you could always get the data in IST or always in GMT/UTC or always in Us/Eastern.
|
[
"stackoverflow",
"0018224156.txt"
] |
Q:
Extjs Multi Slider
I am Using MutliSlider in My Application..
Is it possible to know which direction we are moving slider (left to right or right to left)
I tried many ways to find slider movement.. please suggest me solution is very appreciaeble
Thank You
A:
I got the answer of using thumb value which is index of slider
if(thumb.index==0) then left slider bar moved
else it is right
|
[
"askubuntu",
"0000652802.txt"
] |
Q:
How do I remove old kernels despite 100% inode use in /usr?
I was trying to update my packages today:
$ sudo apt-get upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these.
The following packages have unmet dependencies:
linux-headers-3.16.0-44-generic : Depends: linux-headers-3.16.0-44 but it is not installed
E: Unmet dependencies. Try using -f.
So, I went ahead and tried apt-get -f install:
$ sudo apt-get -f install
Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following extra packages will be installed:
linux-headers-3.16.0-44
The following NEW packages will be installed:
linux-headers-3.16.0-44
0 upgraded, 1 newly installed, 0 to remove and 3 not upgraded.
3 not fully installed or removed.
Need to get 0 B/9,101 kB of archives.
After this operation, 64.5 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
(Reading database ... 688666 files and directories currently installed.)
Preparing to unpack .../linux-headers-3.16.0-44_3.16.0-44.59_all.deb ...
Unpacking linux-headers-3.16.0-44 (3.16.0-44.59) ...
dpkg: error processing archive /var/cache/apt/archives/linux-headers-3.16.0-44_3.16.0-44.59_all.deb (--unpack):
unable to create `/usr/src/linux-headers-3.16.0-44/scripts/genksyms/Makefile.dpkg-new' (while processing `./usr/src/linux-headers-3.16.0-44/scripts/genksyms/Makefile'): No space left on device
dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Errors were encountered while processing:
/var/cache/apt/archives/linux-headers-3.16.0-44_3.16.0-44.59_all.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)
It's complaining saying No space left on device. df -Th tells me that there's sufficient space:
$ df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda6 3.3G 2.5G 571M 82% /
udev 2.0G 0 2.0G 0% /dev
tmpfs 395M 11M 384M 3% /run
tmpfs 2.0G 28M 1.9G 2% /dev/shm
tmpfs 2.0G 0 2.0G 0% /sys/fs/cgroup
tmpfs 100M 72K 100M 1% /run/user
tmpfs 5.0M 8.0K 5.0M 1% /run/lock
/dev/sda7 9.3G 7.6G 1.3G 87% /usr
/dev/sda8 188G 176G 3.0G 99% /home
/dev/sda1 945M 394M 487M 45% /boot
/dev/sda9 256G 9.6G 233G 4% /var
However, df -i tells me /usr has used up all the inodes.
These are the dirs and their inode usage:
/usr/bin = 2846
/usr/etc = 1
/usr/games = 8
/usr/include = 3204
/usr/lib = 42317
/usr/local = 105
/usr/lost+found = 1
/usr/sbin = 306
/usr/share = 228141
/usr/src = 348704
So, if I can clear out /usr/src (which contains the current and old kernels), I can probably resolve the issue. But, I keep running into the first error:
$ sudo apt-get purge linux-image-3.8.0-35-generic
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
linux-headers-3.16.0-44-generic : Depends: linux-headers-3.16.0-44 but it is not going to be installed
linux-image-extra-3.8.0-35-generic : Depends: linux-image-3.8.0-35-generic but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).
Any suggestions on how I can remove my old kernels?
Thanks!
A:
I was running out of options and time so I tried this and it worked:
I figured out what kernel I was using:
$ uname -r
3.16.0-44-generic
I decided to move the really old kernels to my external storage:
sudo mv linux-headers-3.8* /media/housni/linux-headers
df -i then showed that a significant amount of inodes have been freed so I quickly uninstalled the headers I knew I wouldn't need:
sudo apt-get purge linux-headers-3.8*
After which, I updated grub and rebooted
sudo update-grub2 && sudo shutdown now -r
I then did some extra clean up like cleaning up my cache (sudo apt-get clean) and running autoremove (sudo apt-get autoremove) just to be safe and now everything seems to be back to normal :)
|
[
"stackoverflow",
"0034186374.txt"
] |
Q:
what javascript codes can be used to highlight administrative territories on google maps, possibly with coordinates, similar to the image below?
Image of Microsoft MapPoint Territories
I want to highlight different territories with their actual boundaries in the Greater Toronto Area in Canada. I have done so using mapPoint and want to do same in Google Maps. what JavaScript codes can these be done with? Is there a code where you can add coordinates of a region and then select them
A:
This is simple example for google-developer. it's only a triangle but the rules are the same (only more coordinates)
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Simple Polygon</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
// This example creates a simple polygon representing the Bermuda Triangle.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {lat: 24.886, lng: -70.268},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
// Define the LatLng coordinates for the polygon's path.
var triangleCoords = [
{lat: 25.774, lng: -80.190},
{lat: 18.466, lng: -66.118},
{lat: 32.321, lng: -64.757},
{lat: 25.774, lng: -80.190}
];
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
bermudaTriangle.setMap(map);
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
</body>
</html>
as you can see here is create the polygon
the paths attribute contain the coordinates of the polygon, color stroke and fill, color and opacity are for the aspect of the polygon
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
|
[
"stackoverflow",
"0037716752.txt"
] |
Q:
Issues with inheritance when implementing Grails services
So, is it not recommended using an inheritance-approach when implementing Grails services? I went through a simple service specialization pattern understanding that all would work in a transparent way, but I started to go into trouble regarding transaction management under the spring/grails hood. Issues happen when a method from the specialized class calls a method from the inherited class (both concrete services themselves):
@Transactional
public class MammalService {
public mammalMethod() {
}
}
@Transactional
public class DogService extends MammalService {
public dogMethod() {
mammmalMethod()
}
}
It comes that when the inherited method is called from the specialized one, org.springframework.transaction.support.GrailsTransactionTemplate() constructor is fired (by the spring/grails transaction AOP) with a null transactionManager argument, which causes some NullPointerException moreover.
Has anyone used such approach with services? Am I missing something?
PS: Curiously, I tried changing the @grails.transaction.Transactional annotation by the @org.springframework.transaction.annotation.Transactional and the NullPointerException ceased from happening. (Nevertheless, it didn't point to a nice solution, since other side effects started to happen with my pool management).
UPDATE1: While debugging, I can see TWO variables with the same name transactionManager inside my specialized service (something that doesn't happen when inspecting the concrete superclass).
I'm opening a more specific issue at Duplicated transactionManager property in Grails service
A:
Solved by removing @Transaction from specialized service classes and
methods, keeping them only on the inherited service class and its methods.
@Transactional
public class MammalService {
@Transactional(readonly=true)
public mammalMethod() {
}
}
//Don't annotate with @Transactional - rely on the super class declaration
public class DogService extends MammalService {
//Don't annotate with @Transactional - rely on the super class transactional declaration
public dogMethod() {
mammmalMethod()
}
}
It seems that, for specialized service classes, the transaction routines try to re-inject the transactionManager attribute, resulting in two attributes with the same name and one of them null. Also, annotating overrided methods raises an StackOverflowException.
|
[
"stackoverflow",
"0000768602.txt"
] |
Q:
Need a simple way to show a map from an address on .NET Compact Framework
Are there any easy and free methods of showing a map of a location starting from an the address in .NET Compact Framework.
I'm fine with opening IE Mobile from my application.
A:
Google Map API, open the link in IE to show the location.
Note: This obviously requires internet access.
|
[
"stackoverflow",
"0033026373.txt"
] |
Q:
Pass String between two fragments without using an activity
I need to pass the string curDate between NewDateFragment and NewEventFrament, i see many peoples using Bundle, but using these i still having NullPointerException.
I transform the CalendarView to one string named curDate.
public class NewDateFragment extends Fragment {
public String curDate;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_newdate,
container, false);
CalendarView calendar = (CalendarView) view.findViewById(R.id.calendarView);
//sets the listener to be notified upon selected date change.
calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(CalendarView view, int year, int month, int day) {
curDate = day + "/" + month + "/" + year;
NewDateFragment fragment = new NewDateFragment();
Bundle bundle = new Bundle();
bundle.putString("date", curDate);
fragment.setArguments(bundle);
Log.d("Current Date:", curDate);
}
});
}
public class NewEventFragment extends Fragment {
// relative code inside onCreateView
Bundle b = getActivity().getIntent().getExtras();
final String dDate = b.getString("date");
}
My Logcat:
10-08 18:34:49.036 10293-10293/com.org.feedme.cisvmeeting.activities W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41640d88)
10-08 18:34:49.056 10293-10293/com.org.feedme.cisvmeeting.activities E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.org.feedme.cisvmeeting.activities, PID: 10293
java.lang.NullPointerException
at com.org.feedme.fragments.NewEventFragment.attemptCreate(NewEventFragment.java:116)
at com.org.feedme.fragments.NewEventFragment$1.onClick(NewEventFragment.java:61)
at android.view.View.performClick(View.java:4569)
at android.view.View$PerformClick.run(View.java:18570)
at android.os.Handler.handleCallback(Handler.java:743)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5212)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
at dalvik.system.NativeStart.main(Native Method)
Thanks for all the help!
A:
An alternative to the given answer would be to use Events. If you really want to avoid coupling your code - meaning getting rid of unnecessary dependence between classes, having a variable inside your Activity is not a good idea. Here is my suggestion:
Add EventBus library to your Gradle file:
compile 'de.greenrobot:eventbus:2.4.0'
Create a simple plain old java class to represent your event:
public class CalendarDateSelectedEvent{
private String currentDate;
public CalendarDateSelectedEvent(String date){
this.currentDate = date;
}
public String getCurrentDate(){
return currentDate;
}
}
Inside your first fragment where a date is picked, you can post an event to your second fragment as soon as the date is selected like this:
//somewhere when a date is selected
onSelectedDayChanged(String dateSelected){
EventBus.getDefault().post(new CalendarDateSelectedEvent(dateSelected));
}
Finally, inside your second fragment, do the following:
//could be inside onCreate(Bundle savedInstanceState) method
@Override
public void onCreate(Bundle saveInstanceState){
//......
EventBus.getDefault().register(this);
}
@Override
public void onDestroy(){
super.onDestroy();
EventBus.getDefault().unregister(this);
}
//very important piece here to complete the job
public void onEvent(CalenderDateSelectedEvent event){
String currentDate = event.getCurrentDate();
//you can now set this date to view.
}
At this point, you might be asking, why all the hussle to have all these code; but the answer is simple: the activity doesn't have to really know what is happening in either fragments. You have eliminated unnecessary coupling in your code.
If you ever change the activity to do something else, you won't have to change the fragment code.
I hope this helps you see the difference between the two approaches to communicating between fragments!
The first approach (the answer you accepted, involves 3 parties while the second approach involves only 2 parties). It is up to you to choose.
Enjoy!
|
[
"stackoverflow",
"0016914101.txt"
] |
Q:
Changing a programs process name in task manager?
Okay so I've been looking around and I can't find an answer anywhere.
What I want my program to do is every time I run it, the name that shows up in the task manager is randomized.
There is a program called 'Liberation' that when you run it, it will change the process name to some random characters like AeB4B3wf52.tmp or something. I'm not sure what it is coded in though, so that might be the issue.
Is this possible in C#?
Edit:
I made a sloppy work around, I created a separate program that will check if there is a file named 'pb.dat', it will copy it to the temp folder, rename it to a 'randomchars.tmp' and run it.
Code if anyone was interested:
private void Form1_Load(object sender, EventArgs e)
{
try
{
if (!Directory.Exists(Environment.CurrentDirectory + @"\temp")) // Create a temp directory.
Directory.CreateDirectory(Environment.CurrentDirectory + @"\temp");
DirectoryInfo di = new DirectoryInfo(Environment.CurrentDirectory + @"\temp");
foreach (FileInfo f in di.GetFiles()) // Cleaning old .tmp files
{
if (f.Name.EndsWith(".tmp"))
f.Delete();
}
string charList = "abcdefghijklmnopqrstuvwxyz1234567890";
char[] trueList = charList.ToCharArray();
string newProcName = "";
for (int i = 0; i < 8; i++) // Build the random name
newProcName += trueList[r.Next(0, charList.Length)];
newProcName += ".tmp";
if (File.Exists(Environment.CurrentDirectory + @"\pb.dat")) // Just renaming and running.
{
File.Copy(Environment.CurrentDirectory + @"\pb.dat", Environment.CurrentDirectory + @"\temp\" + newProcName);
ProcessStartInfo p = new ProcessStartInfo();
p.FileName = Environment.CurrentDirectory + @"\temp\" + newProcName;
p.UseShellExecute = false;
Process.Start(p);
}
}
catch (Exception ex)
{
MessageBox.Show("I caught an exception! This is a bad thing...\n\n" + ex.ToString(), "Exception caught!");
}
Environment.Exit(-1); // Close this program anyway.
}
A:
I would implement a host application to do this that simply runs and monitors a sub process (other executable). You may rename a file as such:
System.IO.File.Move("oldfilename", "newfilename");
and start the process like this:
Process.Start("newfilename");
This would mean that instead of one process you would have two, but the owner process only needs to be alive under startup - in order to change the name.
|
[
"cooking.stackexchange",
"0000028454.txt"
] |
Q:
What is the effect of adding alkaline or acidic substances to wheat flour?
What are the chemical reactions of adding alkaline substances to wheat flour dough and how does it change the properties and behavior? The same for acidic substances.
A:
I can think of adding alkali or acid substances mainly as means of changing the ph of the dough. And adding can be understood as in the dough, or on its surface.
Alkali/basic additives or ingredients
Gluten only works if PH is between 3 and 11. Outside those values it loses its stength.
Before reaching PH>11 it will make flour have a higher absorption.
It's a way to relax the dough, as the technic used to stretch noodles as it has previously been cited in this question (see @TFD and @Chad's answers), and also in this question. To make that kind of noodles, you add the alkali to the flour, resulting it to be in the dough.
Another way basic substances are used in dough is giving them a bath in caustic soda, as Germans do with their Laugengebäck (the most known ones outside Germany probably are the Brezels/Pretzels). The lye makes them have their characteristic crust: brown, and hard and thin, like a good sausage.
Acidic additives or ingredients
Acids can also weaken the gluten, but in bread making is not so strange to add certain acids, or wanting an acidic dough.
One of the reasons on wanting an acidic final loaf is it will help increasing the shelf life, as it will act as a preservative.
Besides that, there is a very common acid used in doughs: Citric acid / Ascorbic acid / E-300. It helps the dough to rise more and faster, and be more manageable and have a crumb that resembles like cotton candy. You can read more on Ascorbic acid at the page of the Real Bread Campaign, and in this YouTube video you can see its effect in dough.
Another reason for wanting a low PH dough is to avoid starch degradation. Flours have enzymes (amylase) that end up degrading it. But that enzymatic activity is stopped with a PH<4.5. This is well known with 100% rye breads:
I know the question states wheat flour, but this example is clarifier. Rye flour has low gluten, and it has a somehow "low quality" (if compared with "normal" wheat flour). Some recipes call for strong high gluten wheat flour to retain gas bubbles from the leavening that won't get trapped by rye's gluten. But in 100% rye breads gas can also be trapped. That is why usually rye breads are made with sourdough, which has acetic and lactic acids. They give the dough the right PH, and the starches in rye will get gelatinized and catch the gasses in a similar (although less effective way) than gluten. Sometimes, instead of sourdough, yeasts and acid are added as ingredients.
That was an specific example with rye, but wheat flour also has starches, and they can also be gelatinized, giving a distinctive sourdough touch to to 100% wheat breads.
Acidic and basic at the same time
(Thanks @ChrisSteinbach for reminding me it)
When mixing an acid and a base, a chemical reaction happens, neutralizing both and releasing CO2 gas:
NaHCO3 + H+ → Na+ + CO2 + H2O
That gas is employed to leaven the dough, as in a chemical leavener. I.E. in Irish bread or typical cakes.
Stuff that is not acidic nor basic... yet
As a chemical leaveners improvement, one would like the reaction wouldn't start as soon as acid, base and water are mixed, but a bit later. This woud let some more time to work on the dough. Some salts have the characteristic of degrading at high temperatures into acid, helping (usually in the oven) for a second rise.
A:
Alkaline solutions are added to wheat noodle dough when it is too be pulled by hand. The alkaline substance will break down the gluten connections to make a more pliable dough
See What flour and technique do I need for hand pulled noodles?
A:
A mixture of sodium bicarbonate (which is alkaline) and tartaric acid is commonly used as a chemical leavener in baking. If flour is mixed with small amounts of these substances, then carbon dioxide gas will form when water is added to the mixture creating small bubbles in the batter or dough. The mixture is typically cooked as soon as possible after the leavening agent is introduced so that the gas bubbles do not have time to escape and become baked-in.
|
[
"stackoverflow",
"0051914201.txt"
] |
Q:
pgsql query result separated with comma
My Database
Table // Name : accounts
id | login | password | macaddress
1 | ab | ex | 2X:D0:5X:5E:77:CX
2 | ac | example | 2X:D0:5X:5E:77:CX
3 | ad | example | 5X:Y0:GX:FE:27:G8
The query
$sql = pg_query("SELECT * FROM accounts where macaddress = '2X:D0:5X:5E:77:CX' ")
while( $row = pg_fetch_assoc($sql) )
echo "$row[id]";
The Result : 12
What result i want is : 1,2
I hope u can help me solve this.
Thx
A:
Put the values in an array first and join them.
$array = [];
$sql = pg_query("SELECT * FROM accounts where macaddress = '2X:D0:5X:5E:77:CX' ")
while( $row = pg_fetch_assoc($sql) )
$array[] = $row[id];
echo join(',', $array);
|
[
"superuser",
"0000736815.txt"
] |
Q:
How to make Excel chart axis start NOT at major unit?
Is it possible to have an Excel chart where the axis does NOT start at the major unit?
See the example below, where I want the x-axis to start at the year 2007, but have major unit 5 years and show 2010, 2015 and 2020.
I know you can move the vertical axis using the 'Vertical axis crosses'' setting, but in that case the x-axis is extended to the left of the vertical axis, which is not what I want.
This is what I want:
This is the best I can do (but not good enough, see the yellow marks):
A:
The quickest (and I think easiest) way to do this is:
Chart your data as-is (I prefer a scatter/XY chart for this type of chart).
Format your horizontal axis to use 2007 as your Minimum and set Axis Labels to None.
Add a helper column to your data called Labels, set all of your values to =NA(), then set the values you want to label on your axis (2010, 2015, 2020, etc...) to 0. The =NA() points won't plot, but the 0 points will plot on the minimum value, which is also the horizontal axis.
Add your Label data to the chart. You should have a point for each Label.
Format your series for Line and Marker to None (or marker to built-in cross if you want a tick).
Add data labels to your Label series, and format to X Value and position Below.
Here's a sample:
|
[
"matheducators.meta.stackexchange",
"0000000242.txt"
] |
Q:
Are questions about impacts of cultural, economical and political parameters on math education on-topic?
Math education as a social activity has an undeniable mutual interaction with almost all social parameters like cultural, economical and political changes in a society. For example John Smith's answer to my question "Mathematics Education in Africa" shows a direct relevance between political problems in African countries and problems in developing mathematical research.
Question. Are (historical, reference request, etc.) questions about the impacts of cultural, economical and political parameters on math education in different societies on-topic in MESE? If yes, what is a suitable tag for such questions?
Here is a (not too exact) example of such questions.
Example.
It seems Soviet Union scientific policies was really successful in improving math education.
Question. Is there any research to compare the status of math education and math research in Russia during communist regime and after that?
A:
Yes, in principle such questions can be on-topic. Of course, the usual restrictions regarding especially (but not limited too) 'opinion based' and 'too broad' apply.
Moreover, it should be noted that to ask such question in a way suitable for this site will typically need some pre-existing expertise on the asker's side, likely more so than for more hands-on questions. Too many broad and vague questions, possibly based on false or dubious premises, would in my opinion not be a good way to develop the site.
|
[
"stats.stackexchange",
"0000354051.txt"
] |
Q:
Gaussian Process UCB acquisition function: where do the constants come from?
I am trying to understand the GP-UCB acquisition function (Srinivas et al.) when applied to compact, convex spaces.
The GP-UCB acquisition function is:
$x_t = \mathrm{argmax}_{x \in D} \quad \mu_{t-1}(x) + \beta_t^{1/2} \sigma_{t-1}(x)$
Where $D \subset [0, r]^d$ for some positive integer $d$, and $r > 0$.
As I understand so far, the parameter $\beta_t$ controls the exploration-exploitation preference of the acquisition function, though I am confused as to how one chooses $\beta_t$:
The authors suggest one assumes a covariance kernel for which the derivatives of sample paths $f$ drawn from the GP satisfy:
$\mathrm{Pr}\{ \mathrm{sup}_{x \in D} |\partial f / \partial x_j| > L\} \leq ae^{-{L/b}^2} \quad j = 1 \dots d$
In which case one obtains $\beta_t$ by:
$\beta_t = 2 \mathrm{log}(t^2 2 \pi ^2 / (3 \delta)) + 2 d \mathrm{log}(t^2 dbr \sqrt{\mathrm{log}(4da / \delta)})$
for $\delta \in (0,1)$.
I understand this means GP-UCB applies (or at least, it's theoretical properties hold) only for "smooth" covariance functions. My lack of misunderstanding most likely comes from my lack of a mathematical background and inability to intuitively understand some of the constants. I can summarise my questions as follows:
Am I correct to understand $\delta$ represents the upper limit of the probability that the theoretical regret bounds outlined in the above paper do not hold?
For some arbitrary, sufficiently smooth kernel, how does one go about calculating $L$, $a$ and $b$ above?
A:
To answer your first point, I understand $\delta$ as you do. With one run of the GP-UCB algorithm, for $\delta = 0.05$, you have a 95 % chance for the regret to be bounded by the bound given in theorem 2.
|
[
"stackoverflow",
"0061172195.txt"
] |
Q:
Typeid() Check of Passing Paramaters of A Templated Function
I don't want to use function overload for a small change in a function. Instead, I want to use typeid() check of passing parameter of the templated function below. But, If I don't comment out the line in the code below, it gives the compile error of:
Severity Code Description Project File Line Suppression State
Error invalid operands to binary expression ('basic_ostream<char, std::char_traits<char> >' and 'std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >')
As I understand the compiler does not know how to behave. Is there a solution for this?
The code is :
#include <iostream>
#include <vector>
using namespace std;
template <class T>
void Test(T A)
{
if (typeid(T) == typeid(vector<string>)) {
cout << "The type of A is vector<string>" << endl << endl;
//cout << "First element of A is:" << A[0] << endl; // If I don't comment out this line, it gives the compiler error.
}
if (typeid(T) == typeid(vector<vector<string>>)) {
cout << "The type of A is vector<vector<string>>" << endl;
cout << "First row first element of A is:" << A[0][0] << endl;
}
}
int main()
{
Test(vector<string> {"1", "2", "3"});
Test(vector<vector<string>> { {"11", "12", "13"}, { "21", "22", "23" }});
return 0;
}
A:
The problem is in ordinary if, the statement-true (and statement-false if present) has to be valid statement at compile-time, no matter what's the result of the condition, for every instantiation of Test with the type T given.
You can use constexpr if since C++17 (with std::is_same).
In a constexpr if statement, the value of condition must be a
contextually converted constant expression of type bool. If the value
is true, then statement-false is discarded (if present), otherwise,
statement-true is discarded.
e.g.
if constexpr (std::is_same_v<T, vector<string>>) {
cout << "The type of A is vector<string>" << endl << endl;
cout << "First element of A is:" << A[0] << endl;
}
if constexpr (std::is_same_v<T, vector<vector<string>>>) {
cout << "The type of A is vector<vector<string>>" << endl;
cout << "First row first element of A is:" << A[0][0] << endl;
}
LIVE
Before C++17 you can go with SFINAE or specialization (with templates), or just overloading (even without templates).
|
[
"graphicdesign.stackexchange",
"0000131459.txt"
] |
Q:
Adobe Photoshop method to give results equivalent to 'Background Blur' in Adobe XD
I am searching for a way to make a blurred object in Adobe Photoshop like the image I've made in Adobe XD with the Background-Blur tool.
A:
Here's one simple method. There may be others . . .
Create a copy of the background layer, and apply some Gaussian blur to it.
Use the elliptical selection tool to make a circle, then add it as a layer mask
Add a layer above, fill it with white, reduce the layer opacity to something like 50%, then clip it to the blurred layer below
To move the circle around, select the Move Tool and switch off Auto-Select in the tool options along the top, select the layer mask, and unlink the mask from the image
Example:
|
[
"stackoverflow",
"0020918563.txt"
] |
Q:
AS3 setter and managing two levels of status
Let's say I have a setter which has the following possibilities:
The setter assigns the value to a local variable (common use).
The setter cannot assign the value to a local variable due to another condition which is determined at run time. The lack of assignment and the condition is considered normal operation for the application due to user decisions.
The setter experiences an application error.
I'm debating on two solutions, wondering if there are any better ideas:
A. Using a status class to hold the result of #1 or #2, with a try/catch to indicate #3.
B. Using a try/catch to indicate #2 or #3, with different classes indicating the difference between #2 and #3.
The problem I have with A is that every time there is a property assign, there needs to be a check of status.
The problem I have with B is that the try/catch seems as if it should be reserved for unexpected application errors, not an expected error due to user interaction.
I don't feel that there is a way to use the Proxy class.
Any opinions on A vs B, or other options? Also should mention I'm trying to avoid the use of event listeners.
A:
Not 100% sure what you're trying to do, but if you're trying to get the result of calling a setter (to see what, of any, kind of error occurred), you can:
1) use events or signals to indicate a problem:
foo.addEventListener(MyEvents.APP_ERROR, this._handleError);
foo.setter = bar;
2) change the setter to be a function with a return value:
public function setFoo( bar:Bar ):ErrorType;
3) make use of a lastError property that gets set when there's a problem:
foo.setter = bar;
if( foo.lastError != ErrorType.NONE )
// do something
|
[
"stackoverflow",
"0012930515.txt"
] |
Q:
Call show on array of jQuery objects
I have a little problem concerning performance of jQuery.show.
This problem occurs in IE8 (probably also versions below, but IE8 is of my interest).
I have an array of jQuery objects, lets call it elements.
I want to show them, so i did:
for (var i = elements.length - 1; i >= 0; i--) {
elements[i].show();
}
The bottleneck seems to be the call to show. The array is already generated, so that takes no time. looping through an array should not be a problem either.
I thought of reducing this to one call to show by creating a new jQuery element containing all my elements. but I was not sure how to do this. I tried by jQuery.add.
var $elements = elements[0];
for (var i = elements.length - 1; i >= 1; i--) {
$elements = $elements.add(elements[i]);
}
$elements.show();
Now, this time it seems to be a problem with jQuery.add. Probably because it always creates a new object.
So, I thought of three different approaches that could solve my problem. Maybe you can help me with one of them:
Is there a jQuery method like add that does not return a new object, but instead adds it to the current jQuery element?
Is there an easy and fast way to create a jQuery element by an array of jQuery elements?
Is there a way to show all jQuery objects in an array in a faster way?
Answering just one of the question would probably help me out here. My problem is, that jquery always expects an array of DOM elements and not an array of jQuery elements in its methods.
Thanks a lot in advance!
-- EDIT about the contents of elements
I have a jstree that dynamically creates nodes (that is, li elements). These elements have an attribute data-id to identify them.
Now, I could always query for something like $('li[data-id=xxx]'), but this would be very slow. So instead, when li elements are created, i cache them into a dictionary like object (key is the data-id, value is the node). Out of this object, i generate my array elements. This happens very fast.
The array can have a size of up to 4000 nodes. Every jQuery Element in the array only contains one DOM-Element (li).
A:
Edit
After reading your update, and the comments, this Very small one-liner is most likely going to be the answer:
elements.each($.fn.show);
Using the jQ each method to apply (well, internally: call is used) the show method to all elements.
The easiest, and fastest way to create a jQuery object from an array of jQuery objects would be this:
var objFromArr = $(jQarr);
I've just tested this in the console:
objFromArr = jQuery([jQuery('#wmd-input'),jQuery('#wmd-button-bar')]);
objFromArr.each(function()
{
console.log(this);//logs a jQ object
console.log(this[0]);//logs the DOMElement
});
But having said that: you say elements is an array of jQ objects, but if it's the return value of a selector ($('.someClass')) then really, it isn't: in that case, your loop is "broken":
elements = $('.someClass');
for (var i=0;i<elements.length;i++)
{
console.log(elements[i]);//logs a DOMElement, not a jQuery object
}
//It's the same as doing:
console.log(elements[0]);
//or even:
console.log($('.someClass').get(0));
But in the end, if you have an array of jQuery objects, and you want to invoke the show method on each and every one of them, I suspect this is the best take:
elements.each($.fn.show);//use the show method as callback
|
[
"stackoverflow",
"0047179029.txt"
] |
Q:
Angular ngbootstrap select tabs programmatically at page load
In my Angular 2 I'm implementing the navigation tabs from ngbootstrap. At loading time I want to change the active tab. So now by default the 'Offers' tab is set active. With the 'select' method I want to set the 'Orders' tab as active.
@ViewChild('tabs')
private tabs: NgbTabset;
With this.tabs.select("Orders"); in OnInit/AfterContentInit the tabset is not yet rendered and in OnAfterViewInit I got the error Expression has changed after it was checked. Previous value: 'true'. Current value: 'false', because the DOM element is already rendered and cannot be changed.
<ngb-tabset #tabs id="detailTab">
<ngb-tab id="Offers" title="Offers">
<ng-template ngbTabContent>
<br />
<div class="row">
<table class="table" *ngIf="_offers; else nooffers">
<tr>
<th></th>
<th>Offer number</th>
<th>When/who created</th>
<th>Price</th>
<th>#Del weeks</th>
</tr>
<tr *ngFor='let offer of _offers'>
<td style="padding: 10px"><button id="detail" (click)="clicked(offer)" [routerLink]="['/offers', offer.salnr]" title="Detail offers" class="glyphButton"><span class="glyphicon glyphicon-search"></span></button></td>
<td>{{ offer.salnr }}</td>
<td>{{ offer.WhenWhoCreated }}</td>
<td>{{ offer.price }} {{ offer.pricecurrency }}</td>
<td>{{ offer.delweeks }}</td>
</tr>
</table>
<ng-template #nooffers>No offers</ng-template>
</div>
</ng-template>
</ngb-tab>
<ngb-tab id="Orders" title="Orders">
<ng-template ngbTabContent>
<br />
<div class="row">
<table class="table" *ngIf="_orders; else noorders">
<tr>
<th></th>
<th>Order number</th>
<th>When/who created</th>
<th>Price</th>
<th>Backorder</th>
<th>Available</th>
<th>Partial delivery</th>
<th>Expected Del Date</th>
</tr>
<tr *ngFor='let order of _orders'>
<td style="padding: 10px"><button id="detail" (click)="clicked(order)" [routerLink]="['/orders', order.salnr]" title="Detail orders" class="glyphButton"><span class="glyphicon glyphicon-search"></span></button></td>
<td><a href='{{ _linkToOrder }}{{_clientNr}}'>{{ order.salnr }}</a></td>
<td>{{ order.WhenWhoCreated }}</td>
<td>{{ order.price }} {{ order.pricecurrency }}</td>
<td>{{ order.backorder }}</td>
<td>{{ order.isAVAIL }}</td>
<td>{{ order.partialdeliv }}</td>
<td>{{ order.expdeldate }}</td>
</tr>
</table>
<ng-template #noorders>No orders</ng-template>
</div>
</ng-template>
A:
Im not sure if this is the best practice or not but in order to get rid of that error you can inject ChangeDetectorRef in your constructor and call ChangeDetectorRef.detectChanges() in your ngAfterContentInit lifecycle hook.
constructor(private _cdRef: ChangeDetectorRef) {}
ngAfterViewInit() {
this._cdRef.detectChanges();
}
SOLUTION EDIT
Integrating this answer solved the problem.
The AfterViewInit now looks like this:
ngAfterViewInit()
{
if (sessionStorage.getItem("activeTab")) {
this.tabs.select(sessionStorage.getItem("activeTab"));
this.ref.detectChanges();
}
}
|
[
"stackoverflow",
"0027831568.txt"
] |
Q:
How can i run different functions depending on the value of a variable?
How do I run a function depending on a variables value without using tons of if or switch statements?
at the moment I'm repeating a lot of code and doing something like this
The 2 variables represent data i am reading from a socket.
i need to do something different depending on the data i recieve
//Class1.h
class Class1 {
public:
Class1();
virtual ~Class1();
unsigned char mode = 0x00;
unsigned char type = 0x00;
Interface* o;//in this case I’m creating an object not running a function
};
//Class1.cpp
#include "Class1.h"
Class1::Class1(){
switch(mode){
case 0x00:
switch(type){
case 0x00:
o = new Class2();
break;
case 0x01:
o = new Class3();
break;
case 0x02:
o = new Class4();
break;
}
//case 0x03
//case 0x04
//...
break;
//case 0x01
//case 0x02
//...
default:
break;
}
}
A:
I'd split the instance creation into its own factory class, something like this:
#include <map>
#include <cstdint>
#include <iostream>
class Interface
{
public:
virtual ~Interface() = 0;
};
Interface::~Interface() {}
class InterfaceFactory
{
public:
typedef Interface* (*InterfaceCreator)();
void registerInterface(unsigned char mode , unsigned char type, InterfaceCreator creator )
{
int16_t key = getKey(mode, type);
table[key] = creator;
}
Interface* createInterface(unsigned char mode, unsigned char type) const
{
int16_t key = getKey(mode, type);
Interface* iface = nullptr;
std::map<int16_t, InterfaceCreator>::const_iterator cit = table.find(key);
if (cit != table.end())
iface = (*(cit->second))();
return iface;
}
private:
int16_t getKey(unsigned char mode, unsigned char type) const
{
int16_t key = mode;
key <<= 8;
key += type;
return key;
}
std::map<int16_t, InterfaceCreator> table;
};
//StreamProcessor.h
class StreamProcessor {
public:
StreamProcessor(const InterfaceFactory& fact)
: factory(fact)
{}
virtual ~StreamProcessor();
bool initHandler(unsigned char mode = 0x00, unsigned char type = 0x00);
private:
const InterfaceFactory& factory;
Interface* o;//in this case I’m creating an object not running a function
};
//StreamProcessor.cpp
//#include "StreamProcessor.h"
bool StreamProcessor::initHandler(unsigned char mode , unsigned char type )
{
o = factory.createInterface(mode, type);
return o != 0;
}
class Class2 : public Interface
{
public:
static Interface* create()
{
return new Class2;
}
};
class Class3 : public Interface
{
public:
static Interface* create()
{
return new Class3;
}
};
int main()
{
InterfaceFactory factory;
factory.registerInterface(0x00, 0x00, &Class2::create);
factory.registerInterface(0x00, 0x01, &Class3::create);
StreamProcessor sp(factory);
if (!sp.initHandler(0x00, 0x01))
{
throw "Unknown interface type";
}
return 0;
}
|
[
"stackoverflow",
"0031558058.txt"
] |
Q:
Can I code for Windows Phone 8 on VS 2015 with Windows 7?
From this article , they said
If your computer meets the operating system requirements but does not meet the hardware requirements for the Windows Phone Emulators, the Windows Phone development tools will install and run. However, the Windows Phone 8.0 and 8.1 Emulators will not function and you must use a device to deploy or test Windows Phone apps.
So now I'm using win 7 64 bit , can I just use VS 2015 to code and then deploy to a real WP device for debug without using emulator Hyper-V ? Both WP8 app and "Windows 10 mobile" ?
Thanks.
A:
Windows Phone 8 SDK is not supported by Windows 7.
Therefore, you will not be able to develop windows phone 8 applications.
|
[
"stackoverflow",
"0014606712.txt"
] |
Q:
CSS: Apply style only to a combination of two classes but no other classes
Following is what i am using to inject a style which needs to be applied to a Div which has a combination of these two styles : .noindex and .ms-wpContentDivSpace
<script>
$(document).ready(function(){
$('.noindex, .ms-wpContentDivSpace')..css({
overflow: auto,
height : '150px'
});
});
</script>
<style>
.autoScrolListViewWP
{
HEIGHT: 150px;
OVERFLOW: auto
}
</style>
<script>
$(document).ready
(
function()
{
$('.noindex, .ms-wpContentDivSpace').addClass('autoScrolListViewWP');
}
);
</script>
Well but what I need is that above new CSS autoScrolListViewWP should get added to only those element where css combination is just for these two classes .noindex and .ms-wpContentDivSpace
But above script would apply style to any combination of css where those two class exists. E.g. .ms-WPBody , .noindex and ms-wpContentDivSpace autoScrolListViewWP
My question is how do i identify only a spcific combination of CSS classes ?
A:
A solution is to get all the elements with the two classes, then iterate through them and see if they have other classes. I.e:
$('.noindex.ms-wpContentDivSpace').each(function(i, elem) {
var classes = elem.className.split(/\s+/);
if (classes.length === 2) { // they should have only these two classes
$(elem).addClass('autoScrolListViewWP');
// alternatively elem.className += ' autoScrolListViewWP'; (untested)
}
});
|
[
"wordpress.stackexchange",
"0000215941.txt"
] |
Q:
Add the title attribute to links
I want to add a title attribute to my link like this:
<a href="#" title="here is the title">LINK</a>
I know how to do this in html but I can't expect this from my users.
I can't find anywhere in WordPress how to do this and there isn't a theme_support function for this.
I can't be the first to encounter this problem (I hope).
A:
Turns out you are not the only one: https://core.trac.wordpress.org/ticket/32095
It looks like this was removed in a recent update (4.2) and I can see why they did it. User interface can be confusing at times.
You can read more about the removal here: http://wptavern.com/how-to-restore-the-link-title-attribute-removed-in-wordpress-4-2
There is a WordPress plugin, however, that seems to add it back for you. I have not tested, but it should work:
https://wordpress.org/plugins/restore-link-title-field/
|
[
"stackoverflow",
"0020610263.txt"
] |
Q:
remove bounding boxes inside bounding boxes for number recognition
I am trying a number recognition. However after contour finding. I get bounding boxes inside the main bounding box for numbers 0,6,8 ... as shown in figure. Please help me with this initial step of image processing.
I have tried using group rectangles but they are not working. Please check the code below. Thank you.
Image: http://tinypic.com/r/1twx05/5
int main()
{
Mat inimage, gray;
inimage = imread("sample.jpg");
cvtColor(inimage, gray, COLOR_BGR2GRAY);
GaussianBlur(gray, gray, Size(5,5), 0);
adaptiveThreshold(gray, gray, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY_INV, 11, 0);
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours( gray, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );
vector<vector<Point> > contours_poly( contours.size() );
vector<Rect> boundRect( contours.size() );
for( int i = 0; i < contours.size(); i++ )
{
approxPolyDP( Mat(contours[i]), contours_poly[i], 3, true );
boundRect[i] = boundingRect( Mat(contours_poly[i]) );
}
//groupRectangles(boundRect, 1, 0.2);
Scalar color = Scalar(0,0,255);
for( int i = 0; i< contours.size(); i++ )
{
//drawContours( inimage, contours_poly, i, color, 1, 8, vector<Vec4i>(), 0, Point() );
rectangle( inimage, boundRect[i].tl(), boundRect[i].br(), color, 1, 8, 0 );
}
namedWindow( "Contours", CV_WINDOW_AUTOSIZE );
imshow( "Contours", inimage );
waitKey(0);
return 0;
}
A:
try to use the flag: CV_RETR_EXTERNAL instead of CV_RETR_TREE
as stated in the docs it tells to take only outer contours.
Or follow the tree hierarchy to drop nested contours (read the docs for how-to)
|
[
"stackoverflow",
"0044884852.txt"
] |
Q:
what is qsTr in PyQt/QT?
I'm new in the world of Qt/PyQt/QML.
I'm creating a simple calculator using PyQt5 and QML.
In QML title is assigned by like below instead of a string.
title : qsTr("PyQt5 Love QML")
I've no idea what is the use of qsTr and What is the advantage of it.
A:
qsTr is for localization purposes. Later it will help Qt to gather strings to be translated to different languages. It is a common and recommended practice to wrap all the gui-strings in your code in qsTr (or just tr in case of C++/Qt) since then special Qt's tools like lupdate and lrelease could prepare nice translation files for you.
So, even if you do not plan to localize your app, it is recommended to wrap any string that will be displayed to user in qsTr to get a usefull habit.
|
[
"stackoverflow",
"0054336083.txt"
] |
Q:
Incoming notifications are crashing my app Android
When using my Android app, everything works fine but as soon as I get an incoming notification (from other apps), my app just restarts.
It only does that when I have my camera active and during that time I am also drawing on the canvas view.
As I have understood, it is not possible to disable the notifications during certain processes (f.e recording) so I need to fix it somehow, but the only error log I get is the following:
--------- beginning of crash
2019-01-23 23:33:59.712 7469-7469/com.myApp.com E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myApp.com, PID: 7469
java.lang.RuntimeException: Canvas: trying to use a recycled bitmap android.graphics.Bitmap@cafcfb0
at android.graphics.Canvas.throwIfCannotDraw(Canvas.java:1271)
at android.graphics.Canvas.drawBitmap(Canvas.java:1368)
at android.graphics.Bitmap.createBitmap(Bitmap.java:973)
at com.author.myApp.Songplayer.Managers.CanvasDraw.getResizedBitmap(CanvasDraw.java:53)
at com.author.myApp.Songplayer.Managers.CanvasDraw.onDraw(CanvasDraw.java:38)
at android.view.View.draw(View.java:17236)
at android.view.View.updateDisplayListIfDirty(View.java:16201)
at android.view.View.draw(View.java:17002)
at android.view.ViewGroup.drawChild(ViewGroup.java:3777)
at android.support.design.widget.CoordinatorLayout.drawChild(CoordinatorLayout.java:1254)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3560)
at android.view.View.updateDisplayListIfDirty(View.java:16196)
at android.view.View.draw(View.java:17002)
at android.view.ViewGroup.drawChild(ViewGroup.java:3777)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3560)
at android.view.View.updateDisplayListIfDirty(View.java:16196)
at android.view.View.draw(View.java:17002)
at android.view.ViewGroup.drawChild(ViewGroup.java:3777)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3560)
at android.view.View.updateDisplayListIfDirty(View.java:16196)
at android.view.View.draw(View.java:17002)
at android.view.ViewGroup.drawChild(ViewGroup.java:3777)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3560)
at android.view.View.draw(View.java:17239)
at android.view.View.updateDisplayListIfDirty(View.java:16201)
at android.view.View.draw(View.java:17002)
at android.view.ViewGroup.drawChild(ViewGroup.java:3777)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3560)
at android.view.View.draw(View.java:17239)
at android.view.View.updateDisplayListIfDirty(View.java:16201)
at android.view.View.draw(View.java:17002)
at android.view.ViewGroup.drawChild(ViewGroup.java:3777)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3560)
at android.view.View.updateDisplayListIfDirty(View.java:16196)
at android.view.View.draw(View.java:17002)
at android.view.ViewGroup.drawChild(ViewGroup.java:3777)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3560)
at android.view.View.updateDisplayListIfDirty(View.java:16196)
at android.view.View.draw(View.java:17002)
at android.view.ViewGroup.drawChild(ViewGroup.java:3777)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3560)
at android.view.View.updateDisplayListIfDirty(View.java:16196)
at android.view.View.draw(View.java:17002)
at android.view.ViewGroup.drawChild(ViewGroup.java:3777)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3560)
at android.view.View.updateDisplayListIfDirty(View.java:16196)
at android.view.View.draw(View.java:17002)
at android.view.ViewGroup.drawChild(ViewGroup.java:3777)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:3560)
at android.view.View.draw(View.java:17239)
at com.android.internal.policy.DecorView.draw(DecorView.java:801)
at android.view.View.updateDisplayListIfDirty(View.java:16201)
at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:677)
at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:683)
at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:797)
at android.view.ViewRootImpl.draw(ViewRootImpl.java:2991)
at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2785)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2376)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1366)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6768)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:926)
at android.view.Choreographer.doCallbacks(Choreographer.java:735)
at android.view.Choreographer.doFrame(Choreographer.java:667)
2019-01-23 23:33:59.712 7469-7469/com.myApp.com E/AndroidRuntime: at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:912)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
2019-01-23 23:33:59.742 542-8728/? I/ImagingSystem: virtual TRetCode hw::CIMX219Spec::getOTPTestResult(): OTP module_id=0xc8,vendor_id=0x31,checksum=0x1
2019-01-23 23:33:59.746 542-8714/? I/ProjectName: Tornado: mrc_cv_ColorSaturationDetectionTOA:UISaturationLevel:0,saturationCompValid:0,outPutSaturationComp:256.
2019-01-23 23:33:59.775 542-8728/? I/ImagingSystem: virtual TRetCode hw::CIMX219Spec::getOTPTestResult(): OTP module_id=0xc8,vendor_id=0x31,checksum=0x1
2019-01-23 23:33:59.779 542-8714/? I/ProjectName: Tornado: mrc_cv_ColorSaturationDetectionTOA:UISaturationLevel:0,saturationCompValid:0,outPutSaturationComp:256.
2019-01-23 23:33:59.802 1218-4278/? E/ReportTools: This is not beta user build
Which basically tells me nothing.. only that it has failed to find the canvas after the notification.
I am not sure what I should do. When I checked how Android's camera does it then they disable the sound and vibration, so maybe that will help me? If yes then I have searched for quite some time but not have found a way to disable the vibration/sound of other notifications.
EDIT
Adding the onDraw class:
public class CanvasDraw extends View{
Bitmap voiceMeterChart;
Paint linePaint = new Paint();
public CanvasDraw(Context context) {
super(context);
voiceMeterChart = BitmapFactory.decodeResource(getResources(), R.drawable.voice_chart_meter);
voiceMeterChart = adjustOpacity(voiceMeterChart, 125);
linePaint.setColor(Color.RED);
linePaint.setStrokeWidth(1);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int canvasWidth = canvas.getWidth();
int canvasHeight = canvas.getHeight();
canvas.drawBitmap(getResizedBitmap(voiceMeterChart, (canvasWidth * 0.1), canvasHeight, canvasWidth), 25, 0, null);
}
public Bitmap getResizedBitmap(Bitmap bm, double newWidth, int newHeight, int canvasWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(
bm, 0, 0, width, height, matrix, false);
bm.recycle();
return resizedBitmap;
}
private Bitmap adjustOpacity(Bitmap bitmap, int opacity)
{
Bitmap mutableBitmap = bitmap.isMutable()
? bitmap
: bitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
int colour = (opacity & 0xFF) << 24;
canvas.drawColor(colour, PorterDuff.Mode.DST_IN);
return mutableBitmap;
}
}
And in the log it shows that it crashes on this line:
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
A:
The first onDraw call recycles the voiceMeterChart bitmap in getResizedBitmap.
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(
bm, 0, 0, width, height, matrix, false);
bm.recycle();
When onDraw is called again, it attempts to create another bitmap using the original, and it no longer exists.
|
[
"tex.stackexchange",
"0000120751.txt"
] |
Q:
Is there any opposite of newpage?
Is there any command which is the opposite of \newpage/\pagebreak/\clearpage, i.e. which goes back a page instead of going forward, similarly to the way you can use \vspace to move the current vertical position in a page?
A:
No, there is sampage but that isn't what you want I suspect. The whole memory model of TeX is to ship out pages as fast as you can and to free up the memory. That is why even on the machines of 1982 TeX could produce documents of hundreds of pages. Once a page has been shipped out it has gone.
What you can do is collect more than one page worth of material in a box and then handle the box in some way before shipping it out.
|
[
"craftcms.stackexchange",
"0000017840.txt"
] |
Q:
Getting Stripe to work with Commerce
We're using Stripe for an ecomm project that we're testing out right now and nothing is hitting Stripe. If we use a bad card number (per Stripe's docs) like 4000000000000002, the order still goes through.
The Stripe account is brand new (hasn't fully been activated yet) and in Test mode and the test secret and publishable keys are in Commerce's settings. I'm not sure what else to check.
EDIT:
I had forgotten stripe.js altogether but now I'm getting "Payment information submitted is invalid." which I think is a Craft/Commerce error. Here's a link to my checkout template code. The wrapper template (extended template) contains this javascript before the closing body tag.
A:
Issue was not RTFM. :) Basically I didn't include every part of the stripe.js setup
|
[
"stackoverflow",
"0004522733.txt"
] |
Q:
How do I generate (and label) a random integer with python 3.2?
Okay, so I'm admittedly a newbie to programming, but I can't determine how to get python v3.2 to generate a random positive integer between parameters I've given it. Just so you can understand the context, I'm trying to create a guessing-game where the user inputs parameters (say 1 to 50), and the computer generates a random number between the given numbers. The user would then have to guess the value that the computer has chosen. I've searched long and hard, but all of the solutions I can find only tell one how to get earlier versions of python to generate a random integer. As near as I can tell, v.3.2 changed how to generate and label a random integer. Anyone know how to do this?
A:
Use random.randrange or random.randint (Note the links are to the Python 3k docs).
In [67]: import random
In [69]: random.randrange(1,10)
Out[69]: 8
|
[
"stackoverflow",
"0058376052.txt"
] |
Q:
How to make my code thread-safe when my shared variable can change anytime?
Here is a question that has been asked many times, I have double-checked numerous issues that have been raised formerly but none gave me an answer element so I thought I would put it here.
The question is about making my code thread-safe in java knowing that there is only one shared variable but it can change anytime and actually I have the feeling that the code I am optimizing has not been thought for a multi-threading environment, so I might have to think it over...
Basically, I have one class which can be shared between, say, 5 threads. This class has a private property 'myProperty' which can take 5 different values (one for each thread). The problem is that, once it's instantiated by the constructor, that value should not be changed anymore for the rest of the thread's life.
I am pretty well aware of some techniques used to turn most of pieces of code "thead-safe" including locks, the "synchronized" keyword, volatile variables and atomic types but I have the feeling that these won't help in the current situation as they do not prevent the variable from being modified.
Here is the code :
// The thread that calls for the class containing the shared variable //
public class myThread implements Runnable {
@Autowired
private Shared myProperty;
//some code
}
// The class containing the shared variable //
public class Shared {
private String operator;
private Lock lock = new ReentrantLock();
public void inititiate(){
this.lock.lock()
try{
this.operator.initiate() // Gets a different value depending on the calling thread
} finally {
this.lock.unlock();
}
}
// some code
}
As it happens, the above code only guarantees that two threads won't change the variable at the same time, but the latter will still change. A "naive" workaround would consist in creating a table (operatorList) for instance (or a list, a map, etc. ) associating an operator with its calling thread's ID, this way each thread would just have to access its operator using its id in the table but doing this would make us change all the thread classes which access the shared variable and there are many. Any idea as to how I could store the different operator string values in an exclusive manner for each calling thread with minimal changes (without using magic) ?
A:
I'm not sure if I totally understand the situation, but if you want to ensure that each thread uses a thread-specific instance for a variable, the solution is use a variable of type ThreadLocal<T>.
A:
I'm not 100% sure I understood your question correctly, but I'll give it a shot anyway. Correct me if I'm wrong.
A "naive" workaround would consist in creating a table (operatorList)
for instance (or a list, a map, etc. ) associating an operator with
its calling thread's ID, this way each thread would just have to
access its operator using its id in the table but doing this would
make us change all the thread classes which access the shared variable
and there are many.
There's already something similar in Java - the ThreadLocal class?
You can create a thread-local copy of any object:
private static final ThreadLocal<MyObject> operator =
new ThreadLocal<MyObject>() {
@Override
protected MyObject initialValue() {
// return thread-local copy of the "MyObject"
}
};
Later in your code, when a specific thread needs to get its own local copy, all it needs to do is: operator.get(). In reality, the implementation of ThreadLocal is similar to what you've described - a Map of ThreadLocal values for each Thread. Only the Map is not static, and is actually tied to the specific thread. This way, when a thread dies, it takes its ThreadLocal variables with it.
|
[
"stackoverflow",
"0000588013.txt"
] |
Q:
Possible for Instruments to show Leaks on autoreleased objects?
I'm having a difficult time understanding where actual Leaks are happening and where they are not in my application using Instruments. I have objects which are autoreleased and not being retained afterwards.. that are showing up as leaks via Instruments. There's also a bunch of objects which are listed as leaking that don't point back to any code that I've written myself. Perhaps it's a domino effect where one of my real leaks is causing stuff within the Apple libraries to leak, but I'm reluctant to believe that is the case. What's the best way of differentiating where the real leaks are happening?
A:
In my experience Instruments does not give false-positives for auto-released items. (these are still referenced by an auto-release pool so there's no magic difference).
With memory leaks there can indeed by a domino effect in that one culprit results in many cascading leaks. Within instruments each leak will have a time based identity so I suggest you start with the first leaks.
|
[
"stackoverflow",
"0020693405.txt"
] |
Q:
User uploaded textures in three.js
Here you will find a jsFiddle adaptation of the problem.
I would like to create a 3d web application in which the user is able to select an image file on their local machine:
<input id="userImage" type="file"/>
When a file is selected, the image is loaded as a parameter in a THREE.ShaderMaterial object. A glsl shader is applied to the image and the result is rendered to a container in the browser:
$("#userImage").change(function(){
var texture = THREE.ImageUtils.loadTexture( $("#userImage").val() );
texture.image.crossOrigin = "anonymous";
shader.uniforms.input.value = texture;
shader.uniforms.input.needsUpdate = true;
});
Unfortunately, this results in the following error:
Cross-origin image load denied by Cross-Origin Resource Sharing policy.
I am aware there are issues with trying to access cross-origin resources in WebGL, but at the same time I see the following work around is offered in the official specification for WebGL:
The following ECMAScript example demonstrates how to issue a CORS request for an image coming from another domain. The image is fetched from the server without any credentials, i.e., cookies.
var gl = ...;
var image = new Image();
// The onload handler should be set to a function which uploads the HTMLImageElement
// using texImage2D or texSubImage2D.
image.onload = ...;
image.crossOrigin = "anonymous";
image.src = "http://other-domain.com/image.jpg";
In my code you see I've specified the crossOrigin parameter for the image object, but I still receive the error. Where does my example differ from the specification? Is it even possible to use local resources in WebGL as one would with resources hosted on another server? Barring that, are there any other work arounds I should consider to accomplish the task?
A:
The solution actually turns out to be commonly used to preview local images prior to, say, uploading them a server. The image you are trying to render is converted to a data url where restrictions about cross origin policies do not apply. The corrected code is located here. What follows is the meat of it:
userImage = $("#userImage")[0];
if (userImage.files && userImage.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
image.src = e.target.result;
};
reader.readAsDataURL(userImage.files[0]);
}
|
[
"stackoverflow",
"0006084037.txt"
] |
Q:
How to serialize a 3D array with boost?
Okay, I recently switched to boost and I partitialy understand serializing simple objects or simple classes (the boost tutorial confuses me), but how can I serialize a 3D array which contains class members?
I have an array (std::vector) called TileList, which contains objects which are of a class Tile and class Tile contains nothing else than two variables, int TileID and int TilePassability.
I tried doing it as the Serialization tutorial does in the non obtrusive method and the STL Container method, but I just get a stack of errors in return. Can somebody explain how to do it properly? Thank you.
A:
So I understand you have something like this (that's not really a 3D array, post the exact code you want to serialise if I misread you):
struct Tile {
int id, passability;
};
std::vector<Tile> tileList;
Because std::vector is already serialisable through standard Boost.Serialization facilities, you only need to make Tile serialisable. The easiest way is to add a serialize member that does both the loading and saving.
struct Tile {
int id, passability;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & id;
ar & passability;
}
};
Aand that's about it, your type is now serialisable. Special things to be considered include class members being private — you need to add friend declaration for Boost.Serialization in this case, i.e.
class Tile {
int id, passability;
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive& ar, const unsigned version) {
ar & id;
ar & passability;
}
public:
Tile(int, int);
};
serialize member have to be a template (well, not really; but until you know the library a bit better, it have to be), so its entire body must be included within the class declaration (unless you use explicit instantiation, but that's also not something for beginners).
You can also split it into save and load members, but that's not useful until you start using versioning. It would look like this:
struct Tile {
int id, passability;
BOOST_SERIALIZATION_SPLIT_MEMBER()
template <typename Archive>
void save(Archive& ar, const unsigned version) { ... }
template <typename Archive>
void load(Archive& ar, const unsigned version) { ... }
};
That makes the type held by the vector serialisable. Serialising a vector itself is just archive & tileList.
|
[
"math.meta.stackexchange",
"0000031790.txt"
] |
Q:
Using text and MathJax instead of screenshot.
I would suggest the community simply close questions containing screenshots of text. I can understand a screenshot of a figure, but if the text part of a question can be easily typeset with the built-in editor, there’s no place for a screenshot.
If anything, the time and effort going to typesetting makes it easier to justify that the OP has done some effort - at least a typesetting effort - in thinking about and posting the question.
Of course typesetting also means a question becomes searchable and all those advantages, but it seems to me that intolerance to screenshot questions (at least the textual part of the question) is enough of a deterrent to eliminate the most egregious cases.
Recently I've noticed a few people posting questions in rapid succession, each with a screenshot of a problem. If you look at the questions as a whole, it's obvious they've split their entire problem set or take-home exam into tiny pieces and asked us how to do the whole thing. However, since each question alone contains Lagrange multiplier, complex integrals, etc. , which is viewed as sophisticated, none of these questions are closed or even downvoted, and most have some answers or comments.
I think this kind of behaviour should not be encouraged. Here are few of them: Q.1, Q.2, Q.3, Q.4, Q.5.
A:
While I agree that images of text or formulae are undesirable, I do not believe use of images alone is a good reason to close a question - I view closure principally as a tool to deal with questions where further input from the OP is required to make the question possible to answer well. This is not such a case - the appropriate community response to posts that are of low quality solely because of their use of screenshots in place of typeset text and to leave comments pointing the OP towards the site's documentation on typesetting. While closure for this reason alone would serve the goal of eradicating posts with images better than any other tools, it would harm the goal of making the site more welcoming to new users - and while this tradeoff is worthwhile for closure of unanswerable questions, it is not a good trade-off in this case.
This is an issue where it will do less harm to put the responsibility of edits to those who answer such questions - and to view this as a particular case where the behavior of answerers (who overwhelmingly are familiar with MathJax - and who, one hopes, are also receptive to site policy) is a more promising avenue of change than the behavior of new users (who are particularly difficult to influence by policy decisions and might not know or easily adapt to typesetting). The usual tools for changing answerer behavior apply here - especially since I would consider an answer that leaves the question in a poor state to be itself of lower quality than if the question had been improved. This is obviously not a perfect filter against question-answer pairs in need of typesetting, but it avoids the use of closure against questions that may be posted in good faith and that can be improved by an essentially mechanical process.
This question is mostly theoretical though: it's rare to see a question that is of high quality except for using images in place of text. I've not seen any users who have made many such posts - it seems that people who consistently write good questions learn to typeset them correctly without the need for formal moderation tools. Expanding the compass of closure to catch these edge cases doesn't seem productive.
|
[
"stackoverflow",
"0026285451.txt"
] |
Q:
Controlling a rich text box control that is on form 1 from form 2
I'm sorry if this seems incredibly obvious or a very much commonly asked question, but I've been searching and looking over posts for a while now and i still can't seem to get it.
I'm just getting into learning C# and I set myself a little project, making a word processor around a richtextbox control with a few extra features.
I'm currently just adding in the ability to 'Find & Replace' text, and the below code is working when used on the same form as the rich text box control.
richTextBox1.Rtf = richTextBox1.Rtf.Replace("bob", "bill");
I don't want to use a dialog box or something similar, i'm coming direct from our old friend VB6 though, so i'm not sure if they still even exist as such, so i'm making an external form that acts sort of like a dialog box, where i'd like the user to be able to enter the text to look for and replace and then press okay, and be sent back to the main form, sounds simple huh, probably is, i'm not sure what i'm missing...
private void findReplaceToolStripMenuItem_Click(object sender, EventArgs e)
{
Form3 AboutBox = new Form3();
AboutBox.ShowDialog();
}
I've tried my best at implementing a few of the answers I've read over here, in one of them i managed to be able to control form1 but only if i opened a new instance of it with form1.show(); after the code, which is kind of useless in what i'm trying to achieve.
I've set the richTextBox1.Modifiers to Public, but I'm still scratching my head over this one.
A:
Instead of making the RichTextBox public, I'd add a property to the other form that returns the text from that control, like this:
public class SearchForm : Form
{
public string SearchTerm
{
get { return richTextBox1.Text; }
}
...
When the user closes the "search" form, you can get the search term by referencing the property:
private void findReplaceToolStripMenuItem_Click(object sender, EventArgs e)
{
string searchTerm;
using (var searchForm = new SearchForm()) // used 'using' to dispose the form
{
searchForm.ShowDialog();
searchTerm = searchForm.SearchTerm;
}
// do something with searchTerm
}
You'll find this makes maintenance more manageable too. Changing the names of controls in one form shouldn't require you to make changes in any other form that uses them.
|
[
"stackoverflow",
"0054193764.txt"
] |
Q:
Can Delphi 7 pass Int64 value through OLE Variant?
I know that in Delphi 5 it is impossible to write Int64 to Variant and OLEVariant and so, to use it in Type Library (TLB) file of COM Server.
Does anybody know or had experience with Delphi 7 regarding of usage int64 values in COM Server interfaces?
A:
No restriction on Int64 in Delphi 7 variants: it is supported, in the standard way:
There is indeed the OLE/COM compatible type definition
varInt64 = $0014; { vt_i8 20 }
in the System.pas unit, and all needed conversion in the Variants.pas unit.
I confirm it was not supported in Delphi 5.
|
[
"stackoverflow",
"0004028792.txt"
] |
Q:
basic c++ pointer question
if I have a function like that:
void doSomething(int& aVar)
{
// do something
}
and I have this:
int *aVar = new int;
*aVar = 10;
doSomething(*aVar);
Why should I call *aVar? isn't aVar already an address?
A:
No, a reference is not a pointer. References are guaranteed to not be null; you cannot say the same for a pointer. When you pass an int to a function that expects an int& the reference will be taken automatically.
P.S. Don't think of it as an address or a fancy pointer. It is a reference, or an alias to an existing object.
|
[
"stackoverflow",
"0010918870.txt"
] |
Q:
Script doesn't work unless executed in footer
This is a weird situation. Despite making sure that all of its dependencies are loaded before it (in my case it's only jQuery library), my script doesn't work when loaded in the head section (i.e. <head>), but does its job when loaded in the footer (somewhere above </body> tag).
Since that's not clear enough, let me give a live example. This is the web page. Now, view the source of the page, and in there, this is the code I am talking about.
<script type='text/javascript'>
/* <![CDATA[ */
var yjlSettings = {"gifUrl":"http:\/\/whatthenerd.com\/wp-content\/themes\/reddlec\/images\/ajax-loader.gif","autoGrow":"enable"};
/* ]]> */
</script>
<script type='text/javascript' src='http://whatthenerd.com/wp-content/themes/reddlec/js/no-reload-comments.js?ver=3.3.2'></script>
What it's supposed to do is allow users to post comments without reloading the page. (Please feel free to test comment on the page :) ) -- but it's doesn't. Why?
PS: Like I said earlier, everything works when the aforementioned scripts are loaded just before the </body> tag. I don't really see what could be causing the conflict.
A:
Your script goes immediately out to find elements in the DOM:
var $commentlist = jQuery('.commentlist');
var $respond = jQuery('#respond');
Two examples found within the script. These items don't exist at the time the header is being loaded, but they do exist by the time the end of your body is reached. If you want to load this from your header, you need to wrap this in a document ready block:
jQuery(document).ready(function($) {
// Code using $ as usual goes here.
});
This makes it safe to load at the top of your page by delaying the execution of your code until the document has fully loaded, and the DOM is constructed.
More about ready online at: http://api.jquery.com/ready/
|
[
"stackoverflow",
"0021288604.txt"
] |
Q:
Handling user settings with MVVM
Currently i'm developing an WPF application with the MVVM-light framework.
On this moment i'm setting my settings as shown in the next example code in my viewmodel:
private string _property
public string Property
{
get { return _property; }
set
{
if (_property != value)
{
_property = value;
Settings.Default.Property = value;
RaisePropertyChanged("Property");
}
}
}
I save my settings on application exit:
protected override void OnExit(ExitEventArgs e)
{
Settings.Default.Save();
}
Everything works as intended, but ...
Question: Is this a correct approach or is there a better way of handling settings in MVVM
A:
If you want to change your settings based on properties of your ViewModel, your approach would work. The only problem is that your ViewModel is tightly coupled with System.Configuration.ApplicationSettingsBase class.
I would create a Wrapper class that implements an interface (say IConfigProvider) that exposes all your settings as Properties and the Save method and inject that into your ViewModel. This way, you can pass a mock\stub when you unit test your ViewModel.
Another benefit is that if you ever decide to change the way you store your config values (say you want to store some settings in the database), you don't need to touch your ViewModels as all that job is done in your ConfigProvider class.
|
[
"stackoverflow",
"0016340922.txt"
] |
Q:
Array Concatenate text and variable
I would like to create an array as follows:
Dim vHdr As Variant
vHdr = Array("Jogo", "Sala", "Operadora", "Semana", "NSemana", "Acumulado Semana 3")
However, in "Acumulado Semana 3", the 3 is a variable called semana_atual.
I tried:
vHdr = Array("Jogo", "Sala", "Operadora", "Semana", "NSemana", ""Acumulado & "" - "" & " & semana_atual")
but it didn't work.
A:
What if you try this (for VBA):
vHdr = Array("Jogo", "Sala", "Operadora", "Semana", "NSemana", "Acumulado Semana " & semana_atual)
just you need some order with your quotation marks. (I added 'Semana' referring to what you need, not what you have tried).
|
[
"stackoverflow",
"0005893373.txt"
] |
Q:
C# : RowUpdating Method not called when Update is clicked in a gridView
I am having a gridView which has a Edit, Delete, Update and Cancel link buttons to perform the respected functionalities.
Edit, Delete and Cancel commands work fine.
But the problem is that the RowUpdating Event is not fired when I click Update Link Button on the gridView.
What could be wrong?
Here is my code:
<asp:GridView ID="gvCompanies" runat="server" AutoGenerateColumns="False" AllowPaging="True"
onpageindexchanging="gvCompanies_PageIndexChanging"
onrowediting="gvCompanies_RowEditing" PageSize="20"
onrowcancelingedit="gvCompanies_RowCancelingEdit"
onrowdeleting="gvCompanies_RowDeleting"
onrowupdating="gvCompanies_RowUpdating" >
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" ReadOnly="True" />
<asp:BoundField DataField="name" ItemStyle-Width="200px"
ItemStyle-HorizontalAlign="Left" HeaderText="Name" >
<ItemStyle HorizontalAlign="Left" Width="200px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="address" HeaderText="Address">
<ItemStyle HorizontalAlign="Left" Width="200px" />
</asp:BoundField>
<asp:BoundField DataField="city" ItemStyle-Width="200px"
ItemStyle-HorizontalAlign="Left" HeaderText="City" >
<ItemStyle HorizontalAlign="Left" Width="200px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="state" ItemStyle-Width="200px"
ItemStyle-HorizontalAlign="Left" HeaderText="State" >
<ItemStyle HorizontalAlign="Left" Width="200px" />
</asp:BoundField>
<asp:BoundField DataField="zipcode" HeaderText="Zip Code" />
<asp:BoundField DataField="telephone" HeaderText="Telephone" />
<asp:BoundField DataField="fax" HeaderText="Fax" />
<asp:BoundField DataField="mobile" HeaderText="Mobile" />
<asp:BoundField DataField="website" HeaderText="Website" />
<asp:BoundField DataField="email" HeaderText="Email" />
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
</Columns>
</asp:GridView>
In .cs file My RowUpdating Event is as below
protected void gvCompanies_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//My Code for Update
}
NOTE: I had checked out all the similar questions on Stackoverflow but none seem to work for me. So I had posted this question
A:
Got the answer.
Thanks to those who tried to help me with this.
Had to change CausesValidation property of my commandButton to false.
Hope this helps all.
|
[
"stackoverflow",
"0023753476.txt"
] |
Q:
Fill non-consecutive missings with consecutive numbers
For a given data frame...
data = pd.DataFrame([[1., 6.5], [1., np.nan],[5, 3], [6.5, 3.], [2, np.nan]])
that looks like this...
0 1
0 1.0 6.5
1 1.0 NaN
2 5.0 3.0
3 6.5 3.0
4 2.0 NaN
...I want to create a third column where all missings of the second column are replaced with consecutive numbers. So the result should look like this:
0 1 2
0 1.0 6.5 NaN
1 1.0 NaN 1
2 5.0 3.0 NaN
3 6.5 3.0 NaN
4 2.0 NaN 2
(my data frame has much more rows, so imagine 70 missings in the second column so that the last number in the 3rd column would be 70)
How can I create the 3rd column?
A:
You can do it this way, I took the liberty of renaming the columns to avoid the confusion of what I am selecting, you can do the same with your dataframe using:
data = data.rename(columns={0:'a',1:'b'})
In [41]:
data.merge(pd.DataFrame({'c':range(1,len(data[data.b.isnull()]) + 1)}, index=data[data.b.isnull()].index),how='left', left_index=True, right_index=True)
Out[41]:
a b c
0 1.0 6.5 NaN
1 1.0 NaN 1
2 5.0 3.0 NaN
3 6.5 3.0 NaN
4 2.0 NaN 2
[5 rows x 3 columns]
Some explanation here of the one liner:
# we want just the rows where column 'b' is null:
data[data.b.isnull()]
# now construct a dataset of the length of this dataframe starting from 1:
range(1,len(data[data.b.isnull()]) + 1) # note we have to add a 1 at the end
# construct a new dataframe from this and crucially use the index of the null values:
pd.DataFrame({'c':range(1,len(data[data.b.isnull()]) + 1)}, index=data[data.b.isnull()].index)
# now perform a merge and tell it we want to perform a left merge and use both sides indices, I've removed the verbose dataframe construction and replaced with new_df here but you get the point
data.merge(new_df,how='left', left_index=True, right_index=True)
Edit
You can also do it another way using @Karl.D's suggestion:
In [56]:
data['c'] = data['b'].isnull().cumsum().where(data['b'].isnull())
data
Out[56]:
a b c
0 1.0 6.5 NaN
1 1.0 NaN 1
2 5.0 3.0 NaN
3 6.5 3.0 NaN
4 2.0 NaN 2
[5 rows x 3 columns]
Timings also suggest that Karl's method would be faster for larger datasets but I would profile this:
In [57]:
%timeit data.merge(pd.DataFrame({'c':range(1,len(data[data.b.isnull()]) + 1)}, index=data[data.b.isnull()].index),how='left', left_index=True, right_index=True)
%timeit data['c'] = data['b'].isnull().cumsum().where(data['b'].isnull())
1000 loops, best of 3: 1.31 ms per loop
1000 loops, best of 3: 501 µs per loop
|
[
"stackoverflow",
"0056222347.txt"
] |
Q:
How to check if an element is contained in a list?
I have two lists list1 and list2.
list1 contains a variable amount of names. list2 contains three constant names.
When I loop over list1, how can I write my when condition to check if item is contained in list2 ?
This is what I have tried
---
- hosts: localhost
vars:
list1:
- user1
- user2
- user3
- userN
list2:
- user1
- user2
- user3
tasks:
- name: check
debug:
msg: the "{{item}}" name can be used
loop: "{{ list1 }}"
when: item != list2
Thanks.
A:
The intersect filter might be what you're looking for.
The play below
- hosts: localhost
vars:
list1:
- user1
- user2
- user3
- userN
list2:
- user1
- user2
- user3
tasks:
- debug:
msg: "the {{ item }} name can be used"
loop: "{{ list1 | intersect(list2) }}"
gives (grep msg):
"msg": "the user1 name can be used"
"msg": "the user2 name can be used"
"msg": "the user3 name can be used"
|
[
"stackoverflow",
"0015692133.txt"
] |
Q:
Replace CSS file if is specific subdomain, using preg_match
Regular Expressions are still a stone in my boot. Can you help me, guys?
I have this piece of code for a hook in a CMS. Actually it is the whole code enclosed in the function to be excecuted by the main code.
if (preg_match('#^/member/helpdesk/index.*#i', $_SERVER['REQUEST_URI'])) //do it only for specific url
{
$event->replace('#(<h1>Tickets.*</h1>)#i', '$1<div>Some content</div>');
}
But what I really want is to check if the pages belongs to subdomain member.site.com, find the <link rel="stylesheet" href="http://site.com/orange.css"/> and replace orange.css by blue.css
Thank you :)
A:
I mean, at the core I think you're trying to do this:
$str = '<html><head><link rel="stylesheet" href="http://site.com/style.css"/></head></html>'
if (preg_match('#member\.site\.com#i'), $_SERVER['HTTP_HOST'])){
$str = preg_replace('#http://site\.com/style\.css#', 'http://site.com/style-member.css', $str);
}
But perhaps you should consider how whatever it is you're trying to replace is being generated in the first place? Perhaps this is a check that could be placed at that location? Additionally, if you're going to be modifying an html document, I highly suggest using a parser of some kind. If you're going to do the first, maybe something like this:
$head = '<head><link rel="stylesheet" href="http://site.com/style';
if (preg_match('#member\.site\.com#i'), $_SERVER['HTTP_HOST'])){
$head .= '-member';
}
$head .= '.css"></head>';
But if you insist on parsing an html document:
$str = '<html><head><link rel="stylesheet" href="http://site.com/style.css"/></head></html>'
$dom = new DOMDocument();
$dom->loadHTML($str);
if (preg_match('#member\.site\.com#i'), $_SERVER['HTTP_HOST'])){
$links = $dom->getElementsByTagName('link');
foreach ($links as $link){
$attr = $link->attributes;
if ($attr
&& $attr->getNamedItem('rel')->nodeValue == 'stylesheet'
&& $attr->getNamedItem('href')->nodeValue == 'http://site.com/style.css'){
$attr->getNamedItem('href')->nodeValue = 'http://site.com/style-member.css'
}
}
}
$str = $dom->saveHTML();
|
[
"stackoverflow",
"0045368533.txt"
] |
Q:
How to make image asset with transparent background in Android studio? (with option add image asset)
I have image with transparent background.
When i add image to resource folder, my background changes to white.
(with android studio add image asset option)
If i put image directly to resource file, image background stays transparent.
A:
Select "Action Bar and Tab Icons" instead of "Launcher Icons" and you'll get the transparent background as required for all the images.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.