qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
1,244,621 | When I try to redirect to a new page after downloading a file it doesn't work. Do I have to remove or modify anything in this code? the debugger doesnt reach it
```
byte[] fileData = (byte[])sqlRead[3];
Response.Clear();
Response.AppendHeader("content-disposition", "attachment; filename=" + sqlRead[2]);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(fileData);
Response.Flush();
Response.End();
Response.Clear();
Response.Redirect("Questions.aspx");
``` | 2009/08/07 | [
"https://Stackoverflow.com/questions/1244621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132640/"
] | Take out
```
Response.End();
```
[`Response.End`](http://msdn.microsoft.com/en-us/library/ms524629.aspx) kills the entire response, nothing after that will run.
>
> The End method causes the Web server
> to stop processing the script and
> return the current result. The
> remaining contents of the file are not
> processed.
>
>
> | I'm not ASP guy, but you also need to move the Redirect call above any call that writes something to the body of the response.
Try to put the `Redirect()` call right after `Response.Clear()`
The redirect URL is transferred in header of HTTP response, thus calling it afterwards the body was generated (and thus the header was already generated and sent) would render in no effect or an error. |
25,627,953 | I have two fields of type `varchar` that contain numeric values or blank strings, the latter of which I have filtered out to avoid `Divide by Zero` errors.
I am attempting to determine the percentage value that num2 represents in relation to num1, i.e. (Num\_2 \* 1 / Num\_1). Relatively simple math.
The problem I am having is that I cannot seem to do the math and then cast it to a decimal value. I keep receiving `Arithmetic overflow error converting int to data type numeric` errors.
Can someone help me out with the casting issue? | 2014/09/02 | [
"https://Stackoverflow.com/questions/25627953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1059832/"
] | You didn't interpret the error correctly.
It is not about casting the result of your math to float, it is about implicit type casting **before** the equation is evaluated.
You have in your table some values that cannot be converted to numeric, because they are not valid numbers or numbers out of range. It is enough that one row contains invalid data to make fail the whole query. | you said that can be number or blank string.
son try something like this:
```
SELECT
(CASE WHEN NUM_2 = '' THEN 0 ELSE CAST(NUM_2 AS NUMERIC(15,4)) END)
/
(CASE WHEN NUM_1 = '' THEN 1 ELSE CAST(NUM_1 AS NUMERIC(15,4)) END)
```
you test if string is blank. if it is, you use 0 (or 1, to avoid division by zero) |
16,224,515 | I've found similar questions, but no clear answer for this question. I have this table:
```
CREATE DATABASE testDB DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
CREATE TABLE testTable
(
firstName binary(32) not null,
lastName binary(32) not null
/* Other non-binary fields omitted */
)
engine=INNODB DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
```
This statement executes just fine:
```
INSERT INTO testTable (firstName) VALUES (AES_ENCRYPT('Testname', 'test'));
```
But, this returns NULL:
```
SELECT AES_DECRYPT(firstName, 'test') FROM testTable;
```
Why does this return NULL?
Fwiw, this returns "testValue" as expected:
```
SELECT AES_DECRYPT(AES_ENCRYPT('testValue','thekey'), 'thekey');
``` | 2013/04/25 | [
"https://Stackoverflow.com/questions/16224515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1091949/"
] | The answer is that the columns are `binary` when they should be `varbinary`. [This article](http://thinkdiff.net/mysql/encrypt-mysql-data-using-aes-techniques/) explains it:
>
> Because if AES\_DECRYPT() detects invalid data or **incorrect
> padding**, it will return NULL.
>
>
>
With `binary` column types being fixed length, the length of the input value must be known to ensure correct padding. For unknown length values, use `varbinary` to avoid issues with incorrect padding resulting from differing value lengths. | Did you try different values other than 'Testname'?
Do other values work?
I ask because I had a situation while testing 2 test credit card numbers where one decrypted fine and the other returned null.
The answer was to hex and unhex as suggested by "abhinai raj" |
3,913,736 | I'm sorry if this is a duplicate, I've searched google and SO and couldn't find anything similar since it's a fairly generic set of words to search for!
What I want is to have the .git directory be outside of the working tree.
I need to do this because it's a 'stealth' git repository inside a project using other version control software, and unfortunately the way it is set up is with multiple projects (which I want to each be a git repository) inside one root directory, and with build scripts that like to purge files from the project directories. So far I've been versioning the root directory and ignoring all other project directories, so one of the projects was versioned, but I now want to version another project and clearly can't have multiple git repositories in the root directory (or can I? That would be a good alternative answer). Putting the .git directories elsewhere on disk would be a good solution, if it's possible. | 2010/10/12 | [
"https://Stackoverflow.com/questions/3913736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40834/"
] | You can specify the path to the git repository explicitly with the `--git-dir` global option for all git commands. When you use this option with `init` it usually creates a bare repository but if you supply `--work-tree` as well you can initialize a non-bare repository with a 'detached' working tree.
```
git --git-dir=/var/repo/one.git --work-tree=/var/work/one init
```
From then on, you still have to supply either the `--git-dir` option or set `GIT_DIR` environment variable so that git knows where the repository is as there is no git specific data at all inside the working tree, but the working tree will be determined appropriately from the git repository config. | You can link to a gitdir in an arbitrary location by creating a file called `.git` in the root of the work tree, containing the following:
```
gitdir: <path-to-gitdir>
```
Naturally you need to have first moved the original .git directory to its exterior location.
All well-behaved git tools will honour this, without relying on environment variables, or OS-specific mechanisms such as symlinks. You should also be able to place these links at arbitrary locations in your directory hierarchy, thereby linking to multiple repositories.
Of course, such `.git` files will still be visible in the work tree, so this approach may not be acceptable in your case. However, if such a file gets deleted it is trivial to restore (unlike a `.git` directory). |
21,565 | The massive Golems are nearly impervious to harm. Thanks to the New Golem Army, the nascent Dutch Republic's castles and forts are now safe from harm. The century-long external threat has been finally and permanently put to rest, as the bones of our enemies are bleaching in the sun by our castle's walls.
A decision has been recently made in the Staten-Generaal council that defense is to give way to offense. We will no longer be content to defend ourselves in our high castles, leaving the enemy to roam free, but instead, we will march out and take the fight to them, and bring them down for good.
This brings up obvious problems. The strings of wind- and river-mills on our mighty rivers and polders are currently providing the power elektrik to galvanize our Golem troops.
The question now is how do we handle this out in the field, far away from the castles and the galvanic stations? A young apprentice has suggested that given the frequent storms that batter the lands of our neighbors, we could **power our army from the lightning strikes themselves. Would that be plausible with our rough copper wiring? How much energy could we harness from these bolts?**
---
*Assume that golem insides are a black box, we don't care about that. Would capturing lightning be plausible with early renaissance technology? If so, how could it work and how much energy could we get?*
*For the sake of argument and specificity, let's assume that a fully charged golem can operate for 5-7 days on normal stress level, and for 1/2 day in intense combat. Before you ask, I didn't get the chance to run a voltampermeter by the golems, so I don't know their full capacity.*
*If lightning is deemed unfeasible, I'm willing to hear suggestions for alternative ways of charging up in field operations conditions.* | 2015/07/30 | [
"https://worldbuilding.stackexchange.com/questions/21565",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/3510/"
] | Lightning is quite conceivably a good source of power for the golems. An average bolt of negative lightning delivers 500MJ of energy, and a large negative bolt could deliver 35GJ of energy. Positive lightning bolts are very much rarer, but could deliver up to 3.5TJ. In terms of watt-hours, this equates to 138kWh for an average negative bolt, 9.72MWh for a large negative bolt, and 972MWh for a very rare positive bolt.
Assuming that a golem uses about a hundred times the energy per day of an average human male (11MJ or 3kWh), i.e 30kWh/d or 180kWh/charge (lasting an average of 6 days of non-combat operations), it might take two average lightning strikes to charge a golem, or one large one could charge up to 54 golems. You couldn't count on a positive bolt occurring all that often, but if it did occur - and polarity wasn't an issue - then it might charge up to 5400 golems in one strike.
Naturally, given that a lightning strike might more than charge a single golem, a golem force would be interconnected and charged as a unit, not as individuals.
We'd better hope that the golems can accept this fantastically high charging rate without exploding - Negative lightning can have currents of 30-120kA, and positive lightning 300kA, and if this energy was released over a very short period of time, might result in an explosion equivalent to nearly 12kg of TNT for an *average* lightning bolt.
The main problem with this is getting the lightning to strike where you want it to. Fortunately, the emerging field of rocketry can come to your rescue. A simple black-powder rocket (appropriately waterproofed for use in a thunderstorm) could drag a fine copper wire into the sky high enough to attract a lightning bolt, which will strike down the wire, incidentally turning it to plasma, but causing the bolt to strike right where it is needed.
Sure, you'd need a lot of copper wire and rockets to keep your golems charged, but war is expensive, and this is a minor cost. You just want to hope that thunderstorms in the area of operations are as frequent as people say they are. | I would not base my strategies on that.
Seeing how they power their golems, we can safely assume that they have some knowledge of electricity. Technology isn't too complex, you need metallic rods and connect them to some batteries or directly to the golems.
**However**, I would recommend to think about another alternative. Indeed, storms are very local phenomena, and lightening strikes are hard to predict (you can improve by changing the voltage of your rod, but you probably want to save on energy. And what would be the autonomy of the golems after a storm? Plus your enemies might now that, and hide after a storm before attacking once the autonomy is over.
It is hard to devise a strategic campaign on seemingly random and unpredictable elements.
**Alternative**
With the water mills, they have some alternator technology. A more flexible, based on the same technology are [windmills](https://en.wikipedia.org/wiki/Windmill). The Windwheels were known since antiquity. And it could be based on, e.g. the top of [siege towers](https://en.wikipedia.org/wiki/Siege_tower) for large production. And individual wheels could be placed on more transportable poles. With the autonomy they have, you could be sure to prepare well for field battles. |
48,414,782 | I've 2 tables
DeviceType Table
```
id Name
1 Device Type 1
2 Device Type 2
```
Device Table
```
id Name Device Type Id (fk)
1 Device1 1
2 Device2 1
3 Device3 2
```
What I want is to query the data from device table with device type name using `LINQ Methods`. I couldn't find the `Include` method to use here.
I'm trying to get this in result
```
id Name DeviceType Name
1 Device1 Device Type 1
2 Device2 Device Type 1
3 Device3 Device Type 2
``` | 2018/01/24 | [
"https://Stackoverflow.com/questions/48414782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2430556/"
] | You do not need to use `.Include` unless you want to get the related entities as well. You can do something like this:
```
context.Devices.Where(your conditions here)
.Select(d=>new {Id = d.id, Name = d.Name, DeviceTypeName = d.DeviceType.Name})
```
You do not need to do `join` since there's a FK relationship (looks like that from the question), EF should pick up the relationship | ```
List<DeviceType> deviceTypeList = new List<DeviceType>() {
new DeviceType { id = 1, Name = "Device Type 1" },
new DeviceType { id = 2, Name = "Device Type 2" } };
List<Device> deviceList = new List<Device>() {
new Device { id = 1, Name = "Device1", DeviceTypeId = 1 },
new Device { id = 2, Name = "Device2", DeviceTypeId = 1 },
new Device { id = 3, Name = "Device3", DeviceTypeId = 2 } };
//Linq
var query = from device in deviceList
join type in deviceTypeList
on device.DeviceTypeId equals type.id
select new { Id = device.id, Name = device.Name,
DeviceTypeName = type.Name };
//Or lambda expressions
var query = deviceList.Join(deviceTypeList,
device => device.DeviceTypeId,
type => type.id,
(device, type) => new { Id = device.id, Name = device.Name,
DeviceTypeName = type.Name });
``` |
54,850,318 | So this is more of a trivial problem of writing a clean Python3 code. Let's say I have a class `function` which can create many function types based on the user input.
```
import numpy as np
class functions(object):
def __init__(self, typeOfFunction, amplitude, omega, start = None, stop = None,
pulsewidth = None):
self.typeOfFunction = typeOfFunction
self.amplitude = amplitude
self.omega = omega
self.period = 2 * np.pi/omega
self.start = start
self.stop = stop
self.pulsewidth = pulsewidth
def sine_function(self, t):
func = self.amplitude * np.sin(self.omega*t)
return func
def cosine_function(self, t):
func = self.amplitude * np.cos(self.omega*t)
return func
def unit_step_function(self, t):
func = self.amplitude * np.where(t > self.start, 1, 0)
return func
```
Now my question is let us say we want to write 3 other functions:
* Differentiation
* Integration
* Evaluation at a given time.
Now my problem is that in each of these function I have to put conditions such as these:
```
def evaluate_function(self, time):
if(self.typeOfFunction == 'sine'):
funcValue = self.sine_function(time)
elif(self.typeOfFunction == 'cosine'):
funcValue = self.cosine_function(time)
elif(self.typeOfFunction == 'unit_step_function'):
funcValue = self.unit_step_function(time)
```
I want to do it only once in the `__init__` method and at subsequent steps just pass the arguments instead of writing `if-else`:
```
def __init__(self, typeOfFunction, amplitude, omega, start = None, stop = None,
pulsewidth = None):
self.typeOfFunction = typeOfFunction
self.amplitude = amplitude
self.omega = omega
self.period = 2 * np.pi/omega
self.start = start
self.stop = stop
self.pulsewidth = pulsewidth
#DO SOMETHING THAT MAKES THE TYPE OF FUNCTION EMBEDDED
IN THE CLASS IN A CLASS VARIABLE
```
And then:
```
def evaluate_function(self, time):
value = self.doSomething(time)
return value
```
How can this be done? If duplicate question exists please inform me in the comments. | 2019/02/24 | [
"https://Stackoverflow.com/questions/54850318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8560127/"
] | <https://dev.mysql.com/doc/refman/8.0/en/optimize-table.html> says:
>
> For InnoDB tables, `OPTIMIZE TABLE` is mapped to `ALTER TABLE ... FORCE`, which rebuilds the table to update index statistics and free unused space in the clustered index.
>
>
>
This does do some good in cases when you had too much fragmentation. Pages will be filled more efficiently, indexes will be rebuilt, and disk space occupied by the table will be reduced if you use `innodb_file_per_table` (which is the default in recent versions).
It does take time, depending on the size of your table. It will lock the table while it's running. It will require extra disk space while it's running, as it creates a copy of the table.
Doing optimize table on an InnoDB table is usually not necessary to do frequently, but only after you do a lot of insert/update/delete against the table in a way that could result in fragmentation.
`ANALYZE TABLE` is much less impact for InnoDB. This doesn't require building a copy of the table. It's a read-only action, it just reads a random sample of pages from the table and uses that to estimate the number of rows, average size of rows, and it update statistics about the indexes, to guide the query optimizer. This is safe to run anytime, it will lock that table for moment, but that won't be any greater regardless of the size of the table. | Don't bother. InnoDB almost never needs either `ANALYZE` or `OPTIMIZE`; don't waste your time unless you have identified a need.
An exception is a `FULLTEXT` index on an InnoDB table. Such can benefit from `DROP INDEX`, then `ADD INDEX`.
If you are "reloading" the table from new data, then the following avoids downtime:
```
CREATE TABLE new LIKE real;
load `new`
RENAME TABLE real TO old, new TO real; -- fast, atomic
DROP TABLE old;
```
(Caveat: The above technique probably has issues if there are `FOREIGN KEYS`.) |
28,751,783 | I am using digits by twitter for login through phone number.
<http://digits.com/>
How can I set the default country code? As I dont want users to scroll through all list of country codes as my major customers are from same geographical reason ? | 2015/02/26 | [
"https://Stackoverflow.com/questions/28751783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3196981/"
] | When you send object through an Intent's bundle (`i.putExtra("playersList", playersList);`), it is marshalled and then unmarshalled on the other side (the new activity). This mean you have 2 instances of ArrayList and its content (one in each activity). If you wish to share data between activity A and activity B, I suggest you store it on an Application instance or by using a singleton.
If your data is coming from a database, you can pass the id through the intent, and get the list of players and the special player with a database query. | Not sure if this is the best way to accomplish this but i'm going to share with you.
I move the `arrayList` with the players back and forth in between the activities.
Once the player is sent back it's removed from it and kept in an object `player1`,`player2`,`player3` etc etc.
So if the user clicks the button that has already a player assigned to it i simply add that player again into the list and pass the `arrayList` as i would do if it was empty. |
39,514,730 | I need to read spaces (present before string and after String) given as input using Scanner
Note : if there is no spaces given in input it should not add space in output
Please find the below code:
```
package practise;
import java.util.Scanner;
public class scanccls {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
String name= scan.nextLine();
name+=scan.nextLine();
scan.close();
System.out.println("Enter your name"+name);
}
}
```
I am expecting output like:
1. Input :Enter Your name:Chandu Aakash
Output:chandu Aakash
2. Input: Enter Your name: (Space..)Chandu Aakash(Space..)
Output: (space.. )chandu Aakash(Space..) | 2016/09/15 | [
"https://Stackoverflow.com/questions/39514730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5672019/"
] | Your code work fine. I just add little modification:
```
package practise;
import java.util.Scanner;
public class scanccls {
public static void main(String[] args) {
System.out.println("Enter your name:");
Scanner scan = new Scanner(System.in);
String name="";
name+=scan.nextLine();
scan.close();
System.out.println("Your name is :"+name);
}
}
``` | ```
package practise;
import java.util.Scanner;
public class scanccls
{
public static void main(String[] args)
{
System.out.println("Enter your name:");
Scanner scan = new Scanner(System.in);
String name = "";
name += scan.nextLine();
// Can also be done like
// String name=scan.next();
// name+=scan.nextLine();
// They Both Work as same
System.out.println("Your name is :" + name);
}
}
``` |
70,469,506 | hope you're doing good.
I'm working on an Advent / Chocolate Box Calendar in ReactJS and am trying to iterate over a for Loop for the number of days in December.
I have an issue understanding how to render it to my container in my return statement.
[Code Snapshot](https://i.stack.imgur.com/pYgmA.png)
Here is the code in actual text:
```
const Calendar = () => {
// For Loop Here for each Day in December (31 Days)
for (let days = 31; days < array.length; days++) {
// Grid Item to Be Rendered for each Day
<Grid item>
<Box
sx={{
width: 300,
height: 300,
backgroundColor: 'primary.dark',
'&:hover': {
backgroundColor: 'primary.main',
opacity: [0.9, 0.8, 0.7],
},
}}
/>
</Grid>;
}
};
return (
<Grid container spacing={1}>
{/* Want To Generate <Grid item> Here Through for Loop */}
</Grid>
);
```
I want to be iterated over 31 times to amount for the total of days in December and render it in my return statement below the Grid component. I've tried to use an array to push the Grid item into and render it but it didn't work.
Any thoughts on how I could do this?
Thanks in advance | 2021/12/24 | [
"https://Stackoverflow.com/questions/70469506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17752882/"
] | Thanks everyone for taking your time to help,
I found that this code below worked via @jspcal reference to this link for a more concise answer: [React render multiple buttons in for loop from given integer](https://stackoverflow.com/questions/64655265/react-render-multiple-buttons-in-for-loop-from-given-integer)
Here is the code I wrote to make it work:
```
// I added a constant 'box' and set an empty array
const box = [];
// I initiated days as 0 instead of 31 and if days are less than 31 then
// for loop iterates over it until it reaches that number.
for (let days = 0; days < 31; days++) {
// Then the code pushes each time it loops to the empty array I initiated.
box.push(
<Grid item>
<Box
sx={{
width: 300,
height: 300,
backgroundColor: 'primary.dark',
'&:hover': {
backgroundColor: 'primary.main',
opacity: [0.9, 0.8, 0.7],
},
}}
/>
</Grid>
);
}
return (
<Grid container spacing={1}>
{/* And here I render the box array */}
{box}
</Grid>
);
```
And here is a snapshot of my code for better visuals:
[](https://i.stack.imgur.com/UThns.png)
Thanks once again everyone! | In React, it is done using [map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map). Check out react docs on [rendering multiple components](https://reactjs.org/docs/lists-and-keys.html#rendering-multiple-components)
```
<Grid container spacing={1}>
{days.map((day) => {
return (<Grid item key={day}>
<Box
sx={{
width: 300,
height: 300,
backgroundColor: 'primary.dark',
'&:hover': {
backgroundColor: 'primary.main',
opacity: [0.9, 0.8, 0.7],
},
}}
/>
</Grid>)
})
</Grid>
``` |
10,070,027 | I have created a spring-batch job. My reader class reads the data from the DB and gives back the dataset object having the below structure.
```
@XmlRootElement
@XmlType(propOrder = { "start", "end", "users"})
public class DataSet implements Serializable {
/**
* Start datetime of this data set
*/
private Date start;
/**
* End datetime of this data set
*/
private Date end;
/**
* Providers involved in this data set
*/
private List<User> users;
}
```
etc...... and the writer wites the above data using StaxEventItemWriter.
The resulting xml contains two root tag elements.
```
<root> //added by the startDocument and endDocument methods from stax writer.
<DataSet>......</DataSet> // from the dataSet xsd annotation.
</root>
```
i need to eliminate the with out overriding the startDocument and endDocument methods.
is there a way to do it through the configuration. its urgent please.
my writer configuartion is given below.
```
<bean id="testrWriter" class="com.test.writer.TestWriter"
scope="step">
<property name="testXMLWriter" ref="testXMLWriter" />
<property name="baseDirectory" value"#{jobParameters['baseDirectory']}"></property>
</bean>
<bean id="testXMLWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter">
<property name="overwriteOutput" value="true" />
<property name="marshaller" ref="testJaxb2Marshaller" />
</bean>
<bean id="testJaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.test.service.dto.DataSet</value>
</list>
</property>
</bean
``` | 2012/04/09 | [
"https://Stackoverflow.com/questions/10070027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1320554/"
] | I set the root to `!-- --`
finally got a valid xml.
```
<bean id="delegateWriter" class="org.springframework.batch.item.xml.StaxEventItemWriter">
<property name="marshaller" ref="someMarshaller" />
<property name="overwriteOutput" value="true" />
<property name="RootTagName" value="!-- --"/>
</bean>
``` | I override the method endDocument(XMLEventWriter writer), when I set rootTagName = "!-- --" and then ignore the end root tag.
```
protected void endDocument(XMLEventWriter writer) throws XMLStreamException {
//
if(this.getRootTagName().equalsIgnoreCase("!-- --")){
return;
}
String nsPrefix = !StringUtils.hasText(getRootTagNamespacePrefix()) ? "" : getRootTagNamespacePrefix() + ":";
try {
bufferedWriter.write("</" + nsPrefix + getRootTagName() + ">");
}
catch (IOException ioe) {
throw new DataAccessResourceFailureException("Unable to close file resource: [" + resource + "]", ioe);
}
}
``` |
46,043,666 | as I described on the title, I want to write a trigger that defines to add a new staff by all giving attributes except ID, I want to trigger generate and insert it automatically. How can I do that?
I've written a code like below in PL/SQL, but it's including the sequence and I couldn't find how can I get the current max ID of my staff with using the sequence, so could you please help me, with or without using the sequence?
```
CREATE SEQUENCE BEFORE_INSERTING START WITH 1000 INCREMENT BY 1;
CREATE OR REPLACE TRIGGER NEW_ID_BEFORE_INSERTING
BEFORE INSERT ON STAFF
FOR EACH ROW
BEGIN
:NEW.STAFF_ID := BEFORE_INSERTING.nextval;
END;
/
```
By the way, this code works fine but as you see it's starting from 1000. | 2017/09/04 | [
"https://Stackoverflow.com/questions/46043666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5675275/"
] | Perhaps you can use something like the following to find the maximum value for STAFF\_ID and then redefine the sequence based on that value:
```
DECLARE
nMax_staff_id NUMBER;
BEGIN
SELECT MAX(STAFF_ID)
INTO nMax_staff_id
FROM STAFF;
EXECUTE IMMEDIATE 'DROP SEQUENCE BEFORE_INSERTING';
EXECUTE IMMEDIATE 'CREATE SEQUENCE BEFORE_INSERTING START WITH ' ||
nMax_staff_id + 1 || ' INCREMENT BY 1';
END;
```
You only need to run the above once, just to get the sequence reset. After that the trigger will use the sequence to obtain each STAFF\_ID value. Note that there are other ways to redefine a sequence's value, but here we'll do The Simplest Thing That Could Possibly Work, which is to drop the sequence and then recreate it with the new starting value.
Best of luck. | Using the sequence guarantees uniqueness of STAFF\_ID but does not guarantee no gaps in assigning STAFF\_ID. You might end up with STAFF\_ID like 100, 101, 103, 106..
First, get the max(STAFF\_ID) while the system is not running. Something like
```
select max(staff_id) from staff;
```
Then, create the sequence to start from the max staff\_id. Something like
```
create sequence staff_sequence start with <max_id> + 1 increment by 1 nocache;
```
"NOCACHE" minimizes the chance of having gaps in the staff\_id assigned
After, use the trigger that you created to get the nextval from the seuqnece
Note the following:
- Once a sequence is invoked for nextval, that number dispatched cannot be returned to the sequnece
- Any cached sequence values will be lost if oracle database was shutdown
If your requirement is not to have gaps between staff\_ids, then sequence might not be used. |
39,681,371 | Like the subject says, I've suddenly lost the ability to view class members (properties and methods, or any structure at all) from the Solution Explorer. I've looked in settings unsuccessfully (not that I changed anything), and have tried cleaning the solution, rebuilding, restarting Visual Studio, etc. to no avail. What could be causing this? Thank you. | 2016/09/24 | [
"https://Stackoverflow.com/questions/39681371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2346932/"
] | Is it website project or web application project? We couldn't see any class member hierarchy in website project. | You can find it in view dropdown menu! and if not then clear your question more please |
19,323,990 | I have the following models in file `listpull/models.py`:
```
from datetime import datetime
from listpull import db
class Job(db.Model):
id = db.Column(db.Integer, primary_key=True)
list_type_id = db.Column(db.Integer, db.ForeignKey('list_type.id'),
nullable=False)
list_type = db.relationship('ListType',
backref=db.backref('jobs', lazy='dynamic'))
record_count = db.Column(db.Integer, nullable=False)
status = db.Column(db.Integer, nullable=False)
sf_job_id = db.Column(db.Integer, nullable=False)
created_at = db.Column(db.DateTime, nullable=False)
compressed_csv = db.Column(db.LargeBinary)
def __init__(self, list_type, created_at=None):
self.list_type = list_type
if created_at is None:
created_at = datetime.utcnow()
self.created_at = created_at
def __repr__(self):
return '<Job {}>'.format(self.id)
class ListType(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable=False)
def __init__(self, name):
self.name = name
def __repr__(self):
return '<ListType {}>'.format(self.name)
```
I call `./run.py init` then `./run.py migrate` then `./run.py upgrade`, and I see the migration file generated, but its empty:
```
"""empty message
Revision ID: 5048d48b21de
Revises: None
Create Date: 2013-10-11 13:25:43.131937
"""
# revision identifiers, used by Alembic.
revision = '5048d48b21de'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
pass
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
pass
### end Alembic commands ###
```
**run.py**
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from listpull import manager
manager.run()
```
**listpull/\_\_init\_\_.py**
```
# -*- coding: utf-8 -*-
# pylint: disable-msg=C0103
""" listpull module """
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.script import Manager
from flask.ext.migrate import Migrate, MigrateCommand
from mom.client import SQLClient
from smartfocus.restclient import RESTClient
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
mom = SQLClient(app.config['MOM_HOST'],
app.config['MOM_USER'],
app.config['MOM_PASSWORD'],
app.config['MOM_DB'])
sf = RESTClient(app.config['SMARTFOCUS_URL'],
app.config['SMARTFOCUS_LOGIN'],
app.config['SMARTFOCUS_PASSWORD'],
app.config['SMARTFOCUS_KEY'])
import listpull.models
import listpull.views
```
**UPDATE**
If I run the shell via `./run.py shell` and then do `from listpull import *` and call `db.create_all()`, I get the schema:
```
mark.richman@MBP:~/code/nhs-listpull$ sqlite3 app.db
-- Loading resources from /Users/mark.richman/.sqliterc
SQLite version 3.7.12 2012-04-03 19:43:07
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .schema
CREATE TABLE job (
id INTEGER NOT NULL,
list_type_id INTEGER NOT NULL,
record_count INTEGER NOT NULL,
status INTEGER NOT NULL,
sf_job_id INTEGER NOT NULL,
created_at DATETIME NOT NULL,
compressed_csv BLOB,
PRIMARY KEY (id),
FOREIGN KEY(list_type_id) REFERENCES list_type (id)
);
CREATE TABLE list_type (
id INTEGER NOT NULL,
name VARCHAR(80) NOT NULL,
PRIMARY KEY (id),
UNIQUE (name)
);
sqlite>
```
Unfortunately, the migrations still do not work. | 2013/10/11 | [
"https://Stackoverflow.com/questions/19323990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/134484/"
] | When you call the `migrate` command Flask-Migrate (or actually Alembic underneath it) will look at your `models.py` and compare that to what's actually in your database.
The fact that you've got an empty migration script suggests you have updated your database to match your model through another method that is outside of Flask-Migrate's control, maybe by calling Flask-SQLAlchemy's `db.create_all()`.
If you don't have any valuable data in your database, then open a Python shell and call `db.drop_all()` to empty it, then try the auto migration again.
**UPDATE**: I installed your project here and confirmed that migrations are working fine for me:
```
(venv)[miguel@miguel-linux nhs-listpull]$ ./run.py db init
Creating directory /home/miguel/tmp/mark/nhs-listpull/migrations...done
Creating directory /home/miguel/tmp/mark/nhs-listpull/migrations/versions...done
Generating /home/miguel/tmp/mark/nhs-listpull/migrations/script.py.mako...done
Generating /home/miguel/tmp/mark/nhs-listpull/migrations/env.pyc...done
Generating /home/miguel/tmp/mark/nhs-listpull/migrations/env.py...done
Generating /home/miguel/tmp/mark/nhs-listpull/migrations/README...done
Generating /home/miguel/tmp/mark/nhs-listpull/migrations/alembic.ini...done
Please edit configuration/connection/logging settings in
'/home/miguel/tmp/mark/nhs-listpull/migrations/alembic.ini' before
proceeding.
(venv)[miguel@miguel-linux nhs-listpull]$ ./run.py db migrate
INFO [alembic.migration] Context impl SQLiteImpl.
INFO [alembic.migration] Will assume non-transactional DDL.
INFO [alembic.autogenerate] Detected added table 'list_type'
INFO [alembic.autogenerate] Detected added table 'job'
Generating /home/miguel/tmp/mark/nhs-
listpull/migrations/versions/48ff3456cfd3_.py...done
```
Try a fresh checkout, I think your setup is correct. | For anyone coming who comes across this, my problem was having
`db.create_all()`
in my main flask application file
which created the new table without the knowledge of alembic
Simply comment it out or delete it altogether so it doesn't mess with future migrations.
but unlike @Miguel's suggestion, instead of dropping the whole database (i had important information in it), i was able to fix it by deleting the new table created by Flask SQLAlchemy and then running the migration.
and this time alembic detected the new table and created a proper migration script |
58,514,008 | How can you get say a number `99123412341234` to `99-1234-1234-1234`?
* First two characters are in a group (`99`).
* The rest are separated into groups of 4 characters (`1234, 1234, 1234`).
* The groups are joined with a `-`.
My frankenstein version works (see below), but **there must be a more elegant solution.**
```
let myNumber = 99123412341234;
let parsedNumber = [
myNumber.slice(0,2),
myNumber.slice(2, scannedTicket.ticketId.length).match(/.{1,4}/g).join("-")
].join("-");
// Result: parsedNumber = "99-1234-1234-1234"
``` | 2019/10/23 | [
"https://Stackoverflow.com/questions/58514008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1903339/"
] | You can do this without a for-loop by reducing every character onto a sub-array and then joining the results.
```js
console.log(formatNumber(99123412341234, '-', 4, 2));
/**
* Formats
* @param {int} n - a number
* @param {String} d - delimiter
* @param {int} p - partition size
* @param {int} o - initial offset
*/
function formatNumber(n, d, p, o) {
return n.toString(10).split('').reduce((a, c, i) => {
if (i % p === o) a.push([c]);
else a[a.length - 1].push(c);
return a;
}, [[]]).map(e => e.join('')).join(d);
}
```
```css
.as-console-wrapper { top: 0; max-height: 100% !important; }
```
Of course, if you want a regular expression version you can try this...
```js
console.log(formatNumber(99123412341234, '-'));
function formatNumber(n, d) {
return n.toString(10).match(/^(\d{2})(\d{4})(\d{4})(\d{4})$/).slice(1).join(d);
}
```
```css
.as-console-wrapper { top: 0; max-height: 100% !important; }
``` | One approach is to use [slice()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice).
```js
let number = 99123412341234;
number = number.toString(); // Convert number to string.
let parsedNumber = number.slice(0, 2); // Get first two characters.
let length = number.slice(2).length;
for (let i = 2; i < length; i += 4) {
parsedNumber += "-" + number.slice(i, i + 4);
}
console.log(parsedNumber);
``` |
1,060,081 | I'm trying to allow my php pages to run inside a content page of the master page. I'd like to run php somehow inside a master page. Besides frames is there another way? I've read you can use a frame, but would prefer not to. If I have to go with frames to get it done, should I be using an asp.net frame class of some sort or the raw html type? | 2009/06/29 | [
"https://Stackoverflow.com/questions/1060081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/57883/"
] | Check out [Phalanger](http://www.codeproject.com/KB/cross-platform/phalanger-intro.aspx), a php compiler for the CLR | Unfortunately, you won't be able to get php to run within an ASP.NET page. You can run PHP on an IIS7 install, but it would have to be separate pages, and I don't think that things such as application or session state are transferrable (you would have to store all of that externally, in a DB for example). |
57,911,585 | I got a problem when I wanted to put my large-sized photos from my storage into small imageViews. I´m wondering how to put these kind of photos inside a small imageViews without decreasing app speed or crashing.
I have a RecyclerView that shows some pictures from storage in a list. Here is my recycler adapter code.
Thanks for your help.
```
class Adapter(files: ArrayList<File>):RecyclerView.Adapter<Adapter.myViewHolder>() {
val files: ArrayList<File> = files
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): myViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_complex_note_view , parent , false)
return myViewHolder(view)
}
override fun getItemCount(): Int {
return files.size
}
override fun onBindViewHolder(holder: myViewHolder, position: Int) {
holder.bind(files.get(position))
}
class myViewHolder(itemView: View):RecyclerView.ViewHolder(itemView){
lateinit var imageView: ImageView
init {
imageView = itemView.findViewById(R.id.complex_note_view_item_imageview)
}
fun bind(file: File) {
imageView.setImageURI(file.toUri())
}
}
}
``` | 2019/09/12 | [
"https://Stackoverflow.com/questions/57911585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10192418/"
] | The better way is using this code:
```
Glide.with(imageView.context)
.load(imageFile)
.apply(RequestOptions().centerCrop())
.into(imageView)
```
Glide class is faster and more optimized. | i suggest you using **[picasso](https://square.github.io/picasso/)** with resize methode ,it will avoid you the lack of speed and crashes
```
Picasso.get().load(new File(...)).resize(50, 50).centerCrop().into(imageView);
``` |
14,862,289 | I have read the documentation and various tutorials online but I'm still confused on how regex works in Java. What I am trying to do is create a function which takes in argument of type string. I then want to check if the passed string contains any characters other than
MDCLXVIivxlcdm. So for example, string "XMLVID" should return false and "ABXMLVA" should return true.
```
public boolean checkString(String arg)
{
Pattern p = Pattern.complile("[a-zA-z]&&[^MDCLXVIivxlcdm]");
Matcher m = p.matcher(arg);
if(m.matches())
return true;
else
return false;
}
```
When I pass, "XMLIVD", "ABXMLVA", and "XMLABCIX", all return false. What am I doing wrong? Any help will be greatly appreciated. | 2013/02/13 | [
"https://Stackoverflow.com/questions/14862289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2002059/"
] | You will need to use [Java's character class](http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#cc) intersection operator inside a character class, otherwise it literally matches `&&`. Btw, your first character class from `A` to (lowercase) `z` also includes `[\]^_`, which you certainly do not want; and you misspelled "Patter.complile".
Also, [`matches()`](http://docs.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html#matches%28%29)
>
> Attempts to match the *entire* region against the pattern.
>
>
>
So you either need to use `find()` instead or pad the expression with `.*`.
```
public boolean checkString(String arg) {
return Pattern.compile("[[a-zA-Z]&&[^MDCLXVIivxlcdm]]").matcher(arg).find();
}
``` | you can use a function like this, with two arguments, viz.,
* `origingalString` the original string to check
* `searchString` the string to be searched
the code exactly,
```
public boolean checkCompletelyExist(String origingalString,String searchString){
boolean found = false;
String regex = "";
try{
for(int i = 0; i < searchString.length();i++){
String temp = String.valueOf(searchString.charAt(i));
regex = "[\\x20-\\x7E]*"+"["+temp.toLowerCase()+"|"+temp.toUpperCase()+"]+[\\x20-\\x7E]*";
if(!origingalString.matches(regex)){
found = true;
break;
}
}
System.out.println("other character present : "+found);
} catch (Exception e) {
e.printStackTrace();
}
return found;
}
```
eg:
`checkCompletelyExist("MDCLXVIivxlcdm","XMLVID")` output will be `other character present : false`
and
`checkCompletelyExist("MDCLXVIivxlcdm","ABXMLVA")` output will be `other character present : true` |
30,523,370 | I'm trying to create a toggle content button that loads with the content already hidden.
This is the code I'm using but I'm not sure how to make the content appear as hidden (making the toggle button function more used for expanding content)
```js
$(function() {
var b = $("#button");
var w = $("#wrapper");
var l = $("#list");
w.height(l.outerHeight(true));
b.click(function() {
if(w.hasClass('open')) {
w.removeClass('open');
w.height(0);
} else {
w.addClass('open');
w.height(l.outerHeight(true));
}
});
});
```
```css
#wrapper {
background: #ccc;
overflow: hidden;
transition: height 200ms;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Toggle Expand/Collapse</button>
<div id="wrapper" class="open">
<ul id="list">
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ul>
</div>
``` | 2015/05/29 | [
"https://Stackoverflow.com/questions/30523370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4274897/"
] | jQuert toggle method will help you, if you want it hidden for the first time apply style like this -> style="display:none" If you want it visible then don't add this style
Basically what toggle function does is, if your component visible then hides it and if it is hidden then shows it...
```
$('#button').click(function(){
$('#wrapper').toggle();
})
```
below code will explain you better
<http://jsfiddle.net/31zfvm2u/> | using CSS
=========
You can accomplish this with just CSS:
```css
div#wrapper {
transition: max-height 1000ms;
overflow: hidden;
}
#toggle:not(:checked) ~ div#wrapper {
max-height: 0;
}
#toggle:checked ~ div#wrapper {
max-height: 200px;
}
#toggle:checked ~ label:after {
content: "hide"
}
#toggle:not(checked) ~ label:after {
content: "show"
}
```
```html
<input type="checkbox" id="toggle">
<label for="toggle"></label>
<div id="wrapper" class="open">
<ul id="list">
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ul>
</div>
```
---
using JavaScript
================
You're pretty much there. Just use [`$.hide`](http://api.jquery.com/hide/) and [`$.show`](http://api.jquery.com/show/) instead of [`$.height`](http://api.jquery.com/height/).
A more succinct method would be [`$.toggle`](http://api.jquery.com/toggle/), however, which does the same as the below code.
```js
$(function() {
var b = $("#button");
var w = $("#wrapper");
var l = $("#list");
w.height(l.outerHeight(true));
b.click(function() {
if(w.hasClass("open")) {
w.hide();
} else {
w.show()
}
w.toggleClass("open");
});
});
```
```css
#wrapper {
background: #ccc;
overflow: hidden;
transition: height 200ms;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Toggle Expand/Collapse</button>
<div id="wrapper" class="open">
<ul id="list">
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ul>
</div>
``` |
70,472,848 | I'm using [Swift Playgrounds App](https://www.apple.com/swift/playgrounds/) on Mac, which is different than Swift Playgrounds inside the Xcode.
I'm interested in using a UIKit-based Swift Package in my Playground, but couldn't find anything similar to Package.swift file or a menu item to add a package:
Is there an option to connect an external Swift Package stored in a git repository or are only local modules allowed?
[](https://i.stack.imgur.com/zCiZz.png) | 2021/12/24 | [
"https://Stackoverflow.com/questions/70472848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3667264/"
] | What I would try do is open the playground file in the finder.
You can open the playground book as a folder and see the contents of the playgrounds there and paste the swift package there. | I add the GitHub hosted packages by tapping the add file button and selecting package from the menu and pasting the GitHub link into the pop up. It will ask you to select the version you want to use.
I’m guessing in the Mac interface that will be in the File menu. |
51,352,655 | I can not get out of my application, I'm using the auth out of box login for laravel 5, but when I get out of my account, I'm not successful.
**EDIT:** the problem is that dropdown menu does not open for me to logout.
Can someone help me ?
this is my app.blade.php ->
```
@guest
<li><a href="{{ route('login') }}">Login</a></li>
<li><a href="{{ route('register') }}">Register</a></li>
@else
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" aria-haspopup="true" v-pre>
{{ Auth::user()->name }} <span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li>
<a href="{{ route('logout') }}"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
Logout
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
</li>
</ul>
</li>
@endguest
``` | 2018/07/15 | [
"https://Stackoverflow.com/questions/51352655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9796809/"
] | With the classes you have shown us here, there is nothing shorter than
```
Person p2 = Person()
..name = p1.name
..surname = p1.surname
..city = (City()..name = p1.city.name..state = p1.city.state);
```
If you add a `clone` method to `Person` and `City`, then you can obviously use that.
There is nothing built in to the language to allow you to copy the state of an object.
I would recommend changing the classes, at least by adding a constructor:
```
class Person {
String name;
String surname;
City city;
Person(this.name, this.surname, this.city);
}
class City {
String name;
String state;
City(this.name, this.state);
}
```
Then you can clone by just writing:
```
Person P2 = Person(p1.name, p1.surname, City(p1.city.name, p1.city.state));
```
(And [ob-link](https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/) about names)
I say that there is no language feature to copy objects, but there actually is, if you have access to the `dart:isolate` library: Sending the object over a isolate communication port. I cannot recommend using that feature, but it's here for completeness:
```
import "dart:isolate";
Future<T> clone<T>(T object) {
var c = Completer<T>();
var port = RawReceivePort();
port.handler = (Object o) {
port.close();
c.complete(o);
}
return c.future;
}
```
Again, I cannot recommend using this approach.
It would work for simple objects like this, but it doesn't work for all objects (not all objects can be sent over a communication port, e.g., first-class functions or any object containing a first class function).
Write your classes to support the operations you need on them, that includes copying. | Using a package like [freezed](https://pub.dev/packages/freezed#going-further-deep-copy), you could make deep copies of the complex objects.
Although one downside is that the objects are immutable and you cannot make shallow copies of it. But again, it depends on your use case and how you want your objects to be. |
177,126 | Playing on the 1.8 snapshots, I came across a very rare rabbit known as the Killer Rabbit of Caerbannog. He looked a little bit like this:

If I make him a cage, how can I catch him and get him into it? | 2014/07/16 | [
"https://gaming.stackexchange.com/questions/177126",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/77290/"
] | Although the other answers both work, I found it inconvenient to transport the rabbit to his cage after he was caught.
I ended up using a mine-cart to pick up my rabbit and transport him to his new home:

Leading my evil friend to his trap:

Got him!:

I then led tracks straight into his new home:

...and switched the tracks:

I finally closed off the cage where he sat quietly:

The Killer Rabbit of Caerbannog still is currently still in his cage, and I can roam about the world without worry. The killer rabbit is also worry free, as Holy Hand Grenades cannot breach his cell.
EDIT:
-----
Apparently forming a secret alliance with passing creepers, the killer rabbit was trying to escape. Luckily I had been forewarned of this uttermost danger and had the time to up the security near his cell:
 | The Killer Rabbit is hostile towards players so luring it around isn't tricky- it will try to move towards you and attack if it can. Just stand near enough that it can chase you (but keep enough distance that it doesn't hit you- it does more than twice the damage of a zombie).
Trapping it is not difficult. It doesn't have any special jumping abilities so an enclosure of fences or a 2 block deep pit should theoretically work. |
10,741,831 | I want to format selected text to a heading, the way I am doing it works fine in Firefox and Google Chrome but it doesn't work in IE9, here is how I do it:
```
document.execCommand('formatBlock',false,'h1');
```
Does anyone know how to achieve the same task in Internet Explorer 9? | 2012/05/24 | [
"https://Stackoverflow.com/questions/10741831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1117672/"
] | Internet Explorer supports only heading tags `H1` - `H6`, `ADDRESS`, and `PRE`, which must also include the tag delimiters `<` and `>`, such as in `<H1>`. | works perfect for me in IE9
your codes probably wrong, mines more like:
```
var contentWindow = editor.contentWindow;
contentWindow.focus();
contentWindow.document.execCommand('formatBlock', false, '<h1>');
contentWindow.focus();
``` |
225,968 | In [my answer](https://scifi.stackexchange.com/a/53787/19561) to a question on the SF & Fantasy stack, I assumed that "half a dozen" is imprecise enough to mean anywhere from 5 to 7. Another user challenged that assumption and stated that since a dozen is 12, a half dozen is necessarily 6 and nothing else.
In [the answer](https://english.stackexchange.com/a/28038/59244) to a similar question, it is said that
>
> *Dozen* is quite flexible when it is pluralized.
>
>
>
Does half count as a pluralisation? Can "half a dozen" mean anywhere from 5 to 7, or can it only be 6? | 2015/02/06 | [
"https://english.stackexchange.com/questions/225968",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/59244/"
] | A 'dozen' is absolute. It means **twelve**. No generalities apply. | A gross is always 144, a score is always 20, a bakers dozen is always 13, a dozen is always 12, and half a dozen is always six, and so on and so forth, but . . .
We do not always use numbers precisely, leaving aside errors (including fencepost errors like the mentioned supermarket line) there are three ways that numbers are used less precisely.
1. Measuring the count: discrete items can always be counted (I have five magic beans), but sometimes an exact count is not needed (put two and a half cups of beans in cold water and let soak). This leaves you with all the accuracy and precision issues of all measurement. Often you are only concerned with orders of magnitude, less than half a dozen, a little more than a dozen, about a gross, more than I wanted to count, More than I could count.
2. Symbolic numbers: A classic example is the three wise-men bearing gifts to Christ. There is no count given in the bible about how many there were. we only know fore sure that there was more than one. Most scholars speculate somewhere between six and twenty. So why three? It does make staging a play easier in that each has a unique prop corresponding to each gift, but the main reason is that three is considered a holy number and therefore appropriate for gifts to Christ. Also ponder the seven wonders of the world, top ten lists, and the seven deadly sins.
3. Place holders: Where a number is needed but the value is not known or does not matter. See also <http://www.catb.org/jargon/html/R/random-numbers.html> and <http://www.catb.org/jargon/html/F/for-values-of.html> |
16,346,632 | I have an asp.net application (created by a previous developer) that uses a RadGrid control to display data. However, the RadGrid does not show data if there is an on the page. The radGrid works fine soon as I remove the UpdatePanel. If I remove the Updatepanel, then RadCombobox makes a whole page submit (instead of using Ajax).
Is there anyway to make radGrid and work together?
```
<asp:UpdatePanel ID="upnlFilter" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<span class="subHeader">VTRIP Log Search: </span>
<asp:Panel ID="Panel1" runat="server" BorderColor="#E3B391" BorderStyle="Solid"
BorderWidth="1" Width="994px">
<div style="height:10px; width:994px">
</div>
<table style="width: 974px; margin: 10px" border="0">
<tr>
<td width="200px">
<telerik:RadComboBox ID="DriverDD" runat="server" Height="120px" Width="180px"
DropDownWidth="180px" EmptyMessage="Choose a Driver"
HighlightTemplatedItems="true" AutoPostBack="true"
AppendDataBoundItems="true"
onselectedindexchanged="DriverDD_SelectedIndexChanged" >
</telerik:RadComboBox>
</td>
<td width="220px">
<asp:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender1" runat="server" TargetControlID="txtDOS"
WatermarkText="Select today or any previous day" WatermarkCssClass="watermarked">
</asp:TextBoxWatermarkExtender>
<asp:TextBox ID="txtDOS" runat="server" Width="200px" EnableViewState="true" CssClass="SetTextbox"
Height="20px" BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px"></asp:TextBox>
<asp:CalendarExtender ID="txtDOS_CalendarExtender" runat="server" Enabled="True"
TargetControlID="txtDOS">
</asp:CalendarExtender>
</td>
<td style="width:350px"> </td>
</tr>
</table>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<br/>
<telerik:RadGrid ID="RadGrid1" OnSortCommand="RadGrid1_SortCommand"
OnPageIndexChanged="RadGrid1_PageIndexChanged"
Width="99%" Height="181px" OnPageSizeChanged="RadGrid1_PageSizeChanged" AllowSorting="True"
PageSize="5" AllowPaging="True" AllowMultiRowSelection="True" runat="server"
GridLines="None" AutoGenerateColumns="False">
<MasterTableView Height="100px" Width="100%" Summary="RadGrid table">
<CommandItemSettings ExportToPdfText="Export to PDF" />
<RowIndicatorColumn FilterControlAltText="Filter RowIndicator column"
Visible="True">
</RowIndicatorColumn>
<ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column"
Visible="True">
</ExpandCollapseColumn>
<Columns>
<telerik:GridBoundColumn DataField="TripId" HeaderText="Trip ID" SortExpression="TripID"
UniqueName="TripID"
SortAscImageUrl="SortAsc.gif" SortDescImageUrl="SortDesc.gif">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="MemberName" HeaderText="Member Name" SortExpression="MemberName"
UniqueName="MemberName"
SortAscImageUrl="SortAsc.gif" SortDescImageUrl="SortDesc.gif">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="VehicleType" HeaderText="Vehicle Type" SortExpression="VehicleType"
UniqueName="VehicleType"
SortAscImageUrl="SortAsc.gif" SortDescImageUrl="SortDesc.gif">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn DataField="Status" HeaderText="Status" SortExpression="Status"
UniqueName="Status"
SortAscImageUrl="SortAsc.gif" SortDescImageUrl="SortDesc.gif">
</telerik:GridBoundColumn>
</Columns>
<EditFormSettings>
<EditColumn FilterControlAltText="Filter EditCommandColumn column">
</EditColumn>
</EditFormSettings>
<PagerStyle PageSizeControlType="RadComboBox" />
</MasterTableView>
<PagerStyle Mode="NextPrevAndNumeric"></PagerStyle>
<FilterMenu EnableImageSprites="False">
</FilterMenu>
</telerik:RadGrid>
```
Code behind: (populate grid using [Grid - Simple Data Binding](http://demos.telerik.com/aspnet-ajax/grid/examples/programming/simplebinding/defaultcs.aspx))
```
private void LoadData()
{
if (Session["TripMaster"] != null)
{
RadGrid1.DataSource = Session["TripMaster"];
RadGrid1.DataBind();
}
}
``` | 2013/05/02 | [
"https://Stackoverflow.com/questions/16346632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/72324/"
] | You are generating the controls dynamically, so the compiler has no idea what `textBox4` is BEFORE it is even created. What you can do though is to search for that control by its name during runtime:
```
TextBox textbox4 = (TextBox)this.Controls.Find("textbox4", false).FirstOrDefault();
if (textbox4 == null)
{
throw new Exception("Could not find textbox4.");
}
```
This will search for `textbox4` in `Form.Controls` and will throw an exception if it doesn't exist. You can follow the same pattern for `labels` or any other control in the form. | you can find the textbox by name:
```
var textbox = this.Controls.OfType<TextBox>().Single(ctr => ctr.Name == "textboxname");
``` |
48,230,830 | I want to add a CSS dropdown menu to my header. It's works in part...
but when you mouse over it, this element escapes up. How to set it correctly?
It should stay in place and dropdown should be under the `<li>` element.
```css
* {
margin: 0px;
padding: 0px;
font-family: 'Advent Pro', sans-serif;
}
body {
display: flex;
-ms-flex-direction: column;
flex-direction: column;
min-height: 100vh;
}
.wrapper {
display: flex;
flex-direction: column;
}
.navbar-list,
.navbar-list a,
.navbar,
.logo {
display: flex;
align-items: center;
}
.navbar {
display: flex;
background: #008cf4;
padding: 0 20px;
flex-wrap: wrap;
border-bottom: 1px solid #d6d7dd;
font-size: 14px;
}
.navbar .navbar-list {
height: 80px;
list-style-type: none;
padding: 0;
margin: 0;
display: flex;
margin-left: auto;
flex-wrap: wrap;
flex-grow: 1;
justify-content: flex-end;
}
.navbar .navbar-list a {
color: #e9e9e9;
text-decoration: none;
margin: 0 10px;
padding: 0 10px;
text-transform: uppercase;
}
.navbar .navbar-list a:hover {
color: #fff;
}
.navbar .navbar-list i {
font-size: 14px;
color: inherit;
padding-bottom: 1px;
}
.navbar .navbar-list ul {
display: none;
flex-direction: column;
list-style-type: none;
}
.navbar .navbar-list ul li {
list-style-type: none;
justify-content: center;
align-items: flex-end;
align-content: flex-start;
height: auto !important;
opacity: 0.8;
background: black;
text-align: center;
}
.navbar .navbar-list ul li a {
height: 10px !important;
}
.navbar .navbar-list ul li a:hover {
background-color: #a4a4a4;
height: 10px;
}
.navbar .navbar-list li:hover ul {
display: block;
height: auto !important;
}
.navbar .logo {
margin-right: 15px;
}
.navbar .logo h1 {
font-family: 'Alegreya', sans-serif;
font-size: 35px;
}
```
```html
<link href="//fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href='//fonts.googleapis.com/css?family=Alegreya&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Advent+Pro&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<script src="//code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous">
</script>
<div class="wrapper">
<nav class="navbar">
<div class="logo">
<h1>Your logo</h1>
</div>
<ul class="navbar-list">
<li>
<a href="#">
<i class="material-icons">home</i> Dashboard
</a>
</li>
<li>
<a href="#">
<i class="material-icons">build</i> Account & settings
</a>
<ul>
<li>
<a href="#"> 1</a>
</li>
<li>
<a href="#"> 2</a>
</li>
<li>
<a href="#"> 3</a>
</li>
</ul>
</li>
</ul>
<div>avatar</div>
</nav>
</div>
```
[View on Codepen with SCSS](https://codepen.io/pottymouth/pen/ZvROjr) | 2018/01/12 | [
"https://Stackoverflow.com/questions/48230830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7839727/"
] | You need to set position:relative to the parent item, then position:absolute on the dropdown.
Without touching the HTML, that'd be
```
.navbar-list > li{
position:relative;
}
.navbar-list ul{
position:absolute;
width:100%;
}
```
The second rule sets any `<ul>` that's a descendant from the .navbar-list as absolute positioned, removing it from the flow so they won't "push" others, while the first makes the any `<li>` that's a direct child of the .navbar-list the point from which their child `<ul>` will be positioned. | try this
```css
* {
margin: 0px;
padding: 0px;
font-family: 'Advent Pro', sans-serif;
}
body {
display: flex;
-ms-flex-direction: column;
flex-direction: column;
min-height: 100vh;
}
.wrapper {
display: flex;
flex-direction: column;
}
.navbar-list,
.navbar-list a,
.navbar,
.logo {
display: flex;
align-items: center;
}
.navbar {
display: flex;
background: #008cf4;
padding: 0 20px;
flex-wrap: wrap;
border-bottom: 1px solid #d6d7dd;
font-size: 14px;
}
.navbar .navbar-list {
height: 80px;
list-style-type: none;
padding: 0;
margin: 0;
display: flex;
margin-left: auto;
flex-wrap: wrap;
flex-grow: 1;
justify-content: flex-end;
}
.navbar .navbar-list a {
color: #e9e9e9;
text-decoration: none;
margin: 0 10px;
padding: 0 10px;
text-transform: uppercase;
}
.navbar .navbar-list a:hover {
color: #fff;
}
.navbar .navbar-list i {
font-size: 14px;
color: inherit;
padding-bottom: 1px;
}
.navbar .navbar-list ul {
display: none;
flex-direction: column;
list-style-type: none;
position: absolute;
width: auto;
}
.navbar .navbar-list ul li {
list-style-type: none;
justify-content: center;
align-items: flex-end;
align-content: flex-start;
height: auto !important;
opacity: 0.8;
background: black;
text-align: center;
position: relative;
}
.navbar .navbar-list ul li a {
height: 10px !important;
}
.navbar .navbar-list ul li a:hover {
background-color: #a4a4a4;
height: 10px;
}
.navbar .navbar-list li:hover ul {
display: block;
height: auto !important;
}
.navbar .logo {
margin-right: 15px;
}
.navbar .logo h1 {
font-family: 'Alegreya', sans-serif;
font-size: 35px;
}
```
```html
<link href="//fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href='//fonts.googleapis.com/css?family=Alegreya&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Advent+Pro&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<script src="//code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous">
</script>
<div class="wrapper">
<nav class="navbar">
<div class="logo">
<h1>Your logo</h1>
</div>
<ul class="navbar-list">
<li>
<a href="#">
<i class="material-icons">home</i> Dashboard
</a>
</li>
<li>
<a href="#">
<i class="material-icons">build</i> Account & settings
</a>
<ul>
<li>
<a href="#"> 1</a>
</li>
<li>
<a href="#"> 2</a>
</li>
<li>
<a href="#"> 3</a>
</li>
</ul>
</li>
</ul>
<div>avatar</div>
</nav>
</div>
``` |
11,195,333 | I know documentation is lacking for this mysterious module, but Im running Strawberry Perl and would be happy just with being able to install it. I typically run something like the following from the command line to get a module:
```
cpan WWW::Selenium
```
To get WWW::Selenium, for example. Yet when I run
```
cpan Lucene
```
I get all this and, as I've never seen this before, I point the finger at Windows for lack of a better lead:
```
C:\Users\PHJohnson\Desktop>cpan Lucene
CPAN: CPAN::SQLite loaded ok (v0.202)
Database was generated on Mon, 25 Jun 2012 18:28:43 GMT
Running install for module 'Lucene'
Running make for T/TB/TBUSCH/Lucene-0.18.tar.gz
CPAN: Digest::SHA loaded ok (v5.63)
CPAN: Compress::Zlib loaded ok (v2.042)
Checksum for C:\strawberry\cpan\sources\authors\id\T\TB\TBUSCH\Lucene-0.18.tar.gz ok
CPAN: Archive::Tar loaded ok (v1.80)
CPAN: File::Temp loaded ok (v0.22)
CPAN: Parse::CPAN::Meta loaded ok (v1.4401)
CPAN: CPAN::Meta loaded ok (v2.112621)
CPAN.pm: Building T/TB/TBUSCH/Lucene-0.18.tar.gz
couldn't find clucene config file at Makefile.PL line 34.
Warning: No success on command[C:\strawberry\perl\bin\perl.exe Makefile.PL]
TBUSCH/Lucene-0.18.tar.gz
C:\strawberry\perl\bin\perl.exe Makefile.PL -- NOT OK
Running make test
Make had some problems, won't test
Running make install
Make had some problems, won't install
Could not read metadata file. Falling back to other methods to determine prerequisites
C:\Users\PHJohnson\Desktop>
```
I wonder, how can I remedy this - can I get the Lucene library on Windows? | 2012/06/25 | [
"https://Stackoverflow.com/questions/11195333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1222564/"
] | See, some Perl modules are just wrappers around some libraries and/or system tools, allowing to use them naturally within Perl program (using the familiar syntax constructs, etc.) [Lucene](https://metacpan.org/module/Lucene) is built the same way: it's a wrapper around CLucene indexing library.
So you have (as quite often with Perl) two options: either try to build CLucene [from the source](http://sourceforge.net/projects/clucene/) (I said 'try', because I really don't know whether it will work on Windows or not) - or look for similar solutions, like [KinoSearch](https://metacpan.org/module/KinoSearch) (or its fork, [KinoSearch1](https://metacpan.org/module/KinoSearch1) - both are rated quite nice by reviewers) and [Plucene](https://metacpan.org/module/Plucene). The latter is actually a Perl port of the Lucene search engine, not a wrapper of any kind. | Looking at the Makefile.PL, the module is not designed to work under Windows, if you look at the Makefile.PL under "C:\Strawberry\cpan\build\" (on my machine), you should see something like this on lines ~8:
```
## Hash that specifies for each OS all possible directories to look
## for CLucene/clucene-config.h
my $rh_include_dirs = {
"linux" => ["/usr/include", "/usr/lib"],
"freebsd" => ["/usr/local/include", "/usr/local/lib"],
"darwin" => ["/usr/local/include", "/usr/local/lib"],
};
```
you could try to add another entry with the path where you have Lucene installed in windows.
```
my $rh_include_dirs = {
"linux" => ["/usr/include", "/usr/lib"],
"freebsd" => ["/usr/local/include", "/usr/local/lib"],
"darwin" => ["/usr/local/include", "/usr/local/lib"],
"MSWin32" => ["path to your lucene install"],
};
```
After updating the file and saving it, you should be able to do a regular `perl Makefile.PL` and then the usual `make` and `make install` (or nmake on windows). The Makefile.PL script will generate the necessary files for `make` to build and install the package.
I don't have Lucene, so I can't try it out tho... |
7,056,472 | I'd like to use protocol buffer in my program to read data from a file. I also would like to be able to edit the data file with any text editor, for a start (I'll write a data editor later on, and switch to full binary).
Is there a way to parse a human-readable format ? (debug string provided by protobuf itself, or some other format). | 2011/08/14 | [
"https://Stackoverflow.com/questions/7056472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/893790/"
] | There is a text based format too, but support for this is implementation specific. For example, I don't support it *at all* in protobuf-net. But yes: such is defined, and discussed (for example) here: <http://code.google.com/apis/protocolbuffers/docs/reference/cpp/google.protobuf.text_format.html>
Personally, I'd rather use binary and write a UI around the model. | If you don't mind using command-line tools, the [Piqi project](http://piqi.org) includes [piqi convert](http://piqi.org/doc/tools/#piqiconvert) command for converting between 4 formats: binary Protocol Buffers, JSON, XML and [Piq](http://piqi.org/doc/piq). The Piq format is specially designed for viewing and editing data in a text editor. |
1,386,367 | I'm interested in the definite integral
\begin{align}
I\equiv\int\_{-\infty}^{\infty} \frac{1}{x^2-b^2}=\int\_{-\infty}^{\infty} \frac{1}{(x+b) (x-b)}.\tag{1}
\end{align}
Obviously, it has two poles ($x=b, x=-b$) on the real axes and is thus singular. I tried to apply the contour integration methods mentioned [here](https://math.stackexchange.com/questions/564952/complex-integration-poles-real-axis), where they discuss the integral
\begin{align}
\int\_{-\infty}^{\infty}\frac{e^{iax}}{x^2 - b^2}dx = -\frac{\pi}{b}\sin(ab),\tag{2}
\end{align}
where the r.h.s. is the solution derivable in multiple ways as shown in the above thread (e.g. circumventing the poles with infinitesimal arcs).
However, since in the seemingly more simple case (1) the nominator is symmetric in constrast to the situation in (2), I obtain
$$I=0,$$
as the residues equal up to different signs. E.g. consider the limit $a\rightarrow 0$ in (2) which gives $\sin(ab)\rightarrow 0$.
Based on some literature (in the context in which the integral is appearing) it seems that one *should* obtain
\begin{align}
I=-\frac{i\pi}{b}.
\end{align}
Of course, this can be realized by considering the modified integral
\begin{align}
I\_{mod}\equiv\lim\_{\eta\rightarrow 0^+} \int\_{-\infty}^{\infty} dx \frac{1}{x^2-b^2+i\eta},
\end{align}
and closing the contour (e.g. a box closed at infinity) in the lower half plane.
However, in this approach one seems to have some freedom (sign of the infinitesimal contribution, why shift one pole upwards and another pole downwards and not e.g. both upwards?)
So let me explicitly phrase my questions:
1. Is the value of the definite integral in (1) well-defined?
2. Is it equal to zero?
3. In any case, why would I include an infinitesimal shift as in (2) and not in another way?
Thank you very much in advance! | 2015/08/06 | [
"https://math.stackexchange.com/questions/1386367",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/259225/"
] | If $0 \neq 2$ in the field and $P^2=P$, then the minimal Polynomial of $P$ divides $f := x^2-x$, which means it is $f$, $x$, or $x-1$. If it is $x$, $P=0$, and if it is $x-1$, $P=1$. Those cases are clear.
So suppose it is $x^2-x$. Then $I+P$ has minimal polynomial $(x-1)(x-2)=x^2-3x+2$. This means that $I$ is $((I+P)^2-3(I+P))/(-2)$ and so
$(I+P)^{-1}$ is $(I+P-3I)/(-2)=(P-2I)/(-2)$ | Hint:
$$
(I+P)(P-2I)=P-2I+P-2P=-2I
$$ |
25,761,232 | I am trying to use sitefinity *Staging & Synchronization* feature.
I did exactly what is told in this youtube video <https://www.youtube.com/watch?v=O-mbXODZ0MI>
But receiving following error.
**You cannot sync the data, because the destination doesn't contain a site with name 'SFDev'.**

I am moving data from SFDev to SFStaging. So how could the destination name be **SFDev**.
SFDev - Running on Casini Web server
SFStaging - running on local IIS
Not able to find any information on this error. Any suggestions here please?
Product Version: **7.1.5200.0** | 2014/09/10 | [
"https://Stackoverflow.com/questions/25761232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2739418/"
] | The site names have to be the same. When you make the first move it is all "manual". The code and DBs must match from the beginning. The sync tool is NOT a database mover it only sync specific areas of it. Please reference these instructions.
<http://www.sitefinity.com/documentation/documentationarticles/installation-and-administration-guide/syncing-of-data> | I don't think the source or destination site can be running Casini Web server while executing a SiteSync.
Have a look here:
<http://www.sitefinity.com/documentation/documentationarticles/prerequisites-and-restrictions>
>
> All sites must be deployed on IIS.
>
>
> |
1,196,703 | We get into unnecessary coding arguments at my work all-the-time. Today I asked if conditional AND (&&) or OR (||) had higher precedence. One of my coworkers insisted that they had the same precedence, I had doubts, so I looked it up.
According to MSDN AND (&&) has higher precedence than OR (||). But, can you prove it to a skeptical coworker?
<http://msdn.microsoft.com/en-us/library/aa691323(VS.71).aspx>
```
bool result = false || true && false; // --> false
// is the same result as
bool result = (false || true) && false; // --> false
// even though I know that the first statement is evaluated as
bool result = false || (true && false); // --> false
```
So my question is how do you prove with code that AND (&&) has a higher precedence that OR (||)? If your answer is it doesn't matter, then why is it built that way in the language? | 2009/07/28 | [
"https://Stackoverflow.com/questions/1196703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39013/"
] | Wouldn't this get you what you're after? Or maybe I'm missing something...
```
bool result = true || false && false;
``` | You cannot just show the end result when your boolean expressions are being short-circuited. Here's a snippet that settles your case.
It relies on implementing & and | operators used by && and ||, as stated in [MSDN 7.11 Conditional logical operators](http://msdn.microsoft.com/en-us/library/aa691310(VS.71).aspx)
```
public static void Test()
{
B t = new B(true);
B f = new B(false);
B result = f || t && f;
Console.WriteLine("-----");
Console.WriteLine(result);
}
public class B {
bool val;
public B(bool val) { this.val = val; }
public static bool operator true(B b) { return b.val; }
public static bool operator false(B b) { return !b.val; }
public static B operator &(B lhs, B rhs) {
Console.WriteLine(lhs.ToString() + " & " + rhs.ToString());
return new B(lhs.val & rhs.val);
}
public static B operator |(B lhs, B rhs) {
Console.WriteLine(lhs.ToString() + " | " + rhs.ToString());
return new B(lhs.val | rhs.val);
}
public override string ToString() {
return val.ToString();
}
}
```
The output should show that && is evaluated first before ||.
```
True & False
False | False
-----
False
```
For extra fun, try it with result = t || t && f and see what happens with short-circuiting. |
8,132,074 | Here's the PowerShell script I am using to add "segment99" to the beginning of all the text files (one by one) within a folder:
```
Set Environmental Variables:
$PathData = '<<ESB_Data_Share_HSH>>\RwdPnP'
Go to each text file in the specified folder and add header to the file:
Get-ChildItem $PathData -filter 'test_export.txt'|%{
$content = '"segment99" ' + [io.file]::ReadAllText($_.FullName)
[io.file]::WriteAllText(($_.FullName -replace '\.txt$','_99.txt'),$content)
}
```
This is giving me the following error:
```
Error: Exception calling "ReadAllText" with "1" argument(s): "Exception of type 'Syste
Error: m.OutOfMemoryException' was thrown."
Error: At D:\apps\MVPSI\JAMS\Agent\Temp\JAMSTemp13142.ps1:17 char:51
Error: + $content = '"segment99" ' + [io.file]::ReadAllText <<<< ($_.FullName)
Error: + CategoryInfo : NotSpecified: (:) [], MethodInvocationException
Error: + FullyQualifiedErrorId : DotNetMethodException
Error:
```
I am running this code on a folder that has 20 files, each over 2 GB.
How can I fix this? | 2011/11/15 | [
"https://Stackoverflow.com/questions/8132074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1046901/"
] | Copying a header file + a large file to a new file will be less prone to outofmemory exceptions (for files of that size):
```
$header = '"segment99"'
$header | out-file header.txt -encoding ASCII
$pathdata = "."
Get-ChildItem $PathData -filter 'test_export.txt' | %{
$newName = "{0}{1}{2}" -f $_.basename,"_99",$_.extension
$newPath = join-path (split-path $_.fullname) $newname
cmd /c copy /b "header.txt"+"$($_.fullname)" "$newpath"
}
``` | This is not optimal code but it solves the task without reading all text to memory: it adds the header to the first line and then outputs other lines. Also, note that it does nothing if the input file is empty.
```
Get-ChildItem $PathData -Filter 'test_export.txt' | %{
$header = $true
Get-Content $_.FullName | .{process{
if ($header) {
'"segment99" ' + $_
$header = $false
}
else {
$_
}
}} | Set-Content ($_.FullName -replace '\.txt$', '_99.txt')
}
``` |
29,375,512 | I'm trying to build up some regular expressions to validate a textbox on c# wpf. I build the following to validate a number from 6 to 3600:
```
^([6-9]|[1-9][0-9]{1,2}|[12][0-9]{3}|3[0-5][0-9]{2}|3600)$
```
Now I need to validate from 15 to 250. I am new on regex and I am having a hard time getting it.
Thanks | 2015/03/31 | [
"https://Stackoverflow.com/questions/29375512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3614070/"
] | A direct translation would be:
```
^(1[5-9]|[2-9][0-9]|1[0-9]{2}|2[0-4][0-9]|250)$
```
Split up it is `1[5-9]` or 15-19, `[2-9][0-9]` or 20-99, `1[0-9]{2}` or 200-199, `2[0-4][0-9]` or 100-249, `250`. | The following RegEx should satisfy all numbers in the range 15-250. However, as I have cautioned you in the comments, a NumericUpDown is a far superior choice for this kind of stuff:
```
\b(2[0-4]\d)|(1\d\d)|(250)|([2-9]\d)|(1[5-9])\b
``` |
19,027,324 | I'm trying to install numpy using pip. When I type `pip install numpy` in the command prompt it goes to work but won't install the file and returns an error code `1`. I am using windows 8 64-Bit and python 2.7.This is the final bit of the error message
```
Cleaning up...
Removing temporary dir c:\users\pim\appdata\local\temp\pip_build_Pim...
Command python setup.py egg_info failed with error code 1 in c:\users\pim\appdata\local\temp\pip_build_Pim\numpy
Exception information:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\pip-1.4.1-py2.7.egg\pip\basecommand.py", line 134, in main
status = self.run(options, args)
File "C:\Python27\lib\site-packages\pip-1.4.1-py2.7.egg\pip\commands\install.py", line 236, in run
requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
File "C:\Python27\lib\site-packages\pip-1.4.1-py2.7.egg\pip\req.py", line 1134, in prepare_files
req_to_install.run_egg_info()
File "C:\Python27\lib\site-packages\pip-1.4.1-py2.7.egg\pip\req.py", line 259, in run_egg_info
command_desc='python setup.py egg_info')
File "C:\Python27\lib\site-packages\pip-1.4.1-py2.7.egg\pip\util.py", line 670, in call_subprocess
% (command_desc, proc.returncode, cwd))
InstallationError: Command python setup.py egg_info failed with error code 1 in c:\users\pim\appdata\local\temp\pip_build_Pim\numpy
``` | 2013/09/26 | [
"https://Stackoverflow.com/questions/19027324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2747359/"
] | Make sure you have python-dev installed (as you'll definitely see this same error if you don't).
```
dpkg -l python-dev
``` | I downloaded python 37, and I customized install location. Then I tried to install numpy using pip: failed error code 1.
Then I deleted python 37, downloaded python 36 without customizing install location. Then I installed numpy using pip: successful.
Perhaps customizing install location caused the error. |
2,647,999 | I have created a toolbar with some controls on it using ReBar within a window. Can anyone please tell me,
1. How to get the HWND of a **buttons/combobox/etc** (not normal buttons in a window) if I know (only) the Id of it ?
2. How to obtain the HBITMAP if I know the id of the resource ?
3. How to set the bitmap to the controller ?
SendDlgItemMessageW(hWnd, nId, BM\_SETIMAGE, IMAGE\_BITMAP, (LPARAM)hBitmap);
This isn't working for toolbars, isn't it ? I couldn't find a way to do it, please help me. Thank you...
Regards
EDIT:
Anyone please ? :(
EDIT:
Ok. it seems everyone is busy these days. :( Btw, is it a wrong question ? | 2010/04/15 | [
"https://Stackoverflow.com/questions/2647999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/134804/"
] | You could download [ControlSpy](http://msdn.microsoft.com/en-us/library/bb773165(VS.85).aspx) and try it in there to get a feel for it.
I checked the Rebar and saw that RB\_SETBANDINFO (under *Messages*) could be what you are looking for. | [GetDlgItem](http://msdn.microsoft.com/en-us/library/ms645481(VS.85).aspx) will work just as well with a Rebar as it does with a Dialog.
>
> You can use the GetDlgItem function with any parent-child window pair, not just with dialog boxes. As long as the hDlg parameter specifies a parent window and the child window has a unique identifier (as specified by the hMenu parameter in the CreateWindow or CreateWindowEx function that created the child window), GetDlgItem returns a valid handle to the child window.
>
>
>
You can use LoadImage to load a bitmap from a resource and return the HBITMAP.
Finally, `SendMessage(hWndButton, BM_SETIMAGE, (WPARAM) IMAGE_BITMAP, (LPARAM) hBitmap);` |
64,624,106 | I need to access the `fileHandler` object of my logger so I can flush the buffer to the file.
This is my program:
```
import * as log from "https://deno.land/std@0.75.0/log/mod.ts"
import { Application } from "https://deno.land/x/oak@v6.3.1/mod.ts";
const app = new Application()
const port = 7001
await log.setup({
handlers:{
file: new log.handlers.FileHandler("DEBUG",{
filename: "logger.log",
formatter: lr => {
return `${lr.datetime.toISOString()} [${lr.levelName}] ${lr.msg}`
}
})
},
loggers: {
default: {
level: "DEBUG",
handlers: ["file"]
}
}
})
const logger = log.getLogger()
logger.debug("hi there")
app.use((ctx) => {
ctx.response.body = 'Hi there'
})
console.log(`listening on port ${port}`)
app.listen({ port })
```
My problem is that the log message is never being written to file.
If I remove the last line ( app.listen() ) it Does write to the file because the process ends.
But if I leave it listening process never ends so the log buffer is never flushed.
If I interrupt the process with Ctrl-C it doesn't write it either
Documentation (<https://deno.land/std@0.75.0/log/README.md>) says I can force log flush using the flush method from FileHandler. But I don't know how to access the fileHandler object.
So I've tried this:
```
const logger = log.getLogger()
logger.debug("hi there")
logger.handlers[0].flush()
```
And it works! but only as javascript, NOT as typescript
As typescript I get this error:
```
error: TS2339 [ERROR]: Property 'flush' does not exist on type 'BaseHandler'.
logger.handlers[0].flush()
``` | 2020/10/31 | [
"https://Stackoverflow.com/questions/64624106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2432478/"
] | Well, I found a solution.
I just have to import the FileHandler class and cast my handler down from BaseHandler to FileHandler.
So I added this line among the imports:
```
import { FileHandler } from "https://deno.land/std@0.75.0/log/handlers.ts"
```
And then after creating the logger:
```
logger.debug("hi there")
const fileHandler = <FileHandler> logger.handlers[0]
fileHandler.flush()
```
Looks a little weird, I still guess there must be less quirky / more semantic solution for this. But it works ok. | Let us just recap with the help of Santi's answer.
In my experience logs in file work fine in an ending program. I mean a program which dies by itself or with Deno.exit(0). Problem occurs in a never ending loop. In this case logs don't append in their files. Below is how to overcome this situation :
```
// dev.js : "I want my logs" example
import {serve} from "https://deno.land/std@0.113.0/http/server_legacy.ts";
import * as log from "https://deno.land/std@0.113.0/log/mod.ts";
// very simple setup, adapted from the official standard lib https://deno.land/std@0.113.0/log
await log.setup({
handlers: {
file: new log.handlers.FileHandler("WARNING", {
filename: "./log.txt",
formatter: "{levelName} {msg}",
}),
},
loggers: {
default: {
level: "DEBUG",
handlers: ["file"],
},
},
});
// here we go
let logger;
logger = log.getLogger();
logger.warning('started');
const fileHandler = logger.handlers[0];
await fileHandler.flush(); // <---- the trick, need to flush ! Thanks Santi
// loop on requests
const srv = serve(`:4321`);
for await (const request of srv) {
request.respond({body: 'bonjour', status: 200});
logger.warning('hit !');
fileHandler.flush(); // <---- flush again
}
```
Run with
```
$ deno run -A dev.js
```
And check the file log.txt with the following trigger
```
$ curl localhost:4321
```
This is a very low tech, problably adding important delay to the process. The next level will be to fire a time event to flush every minute or so. |
56,893,911 | `hg bookmarks --delete` can be used to remove a bookmark.
Is there any way I can remove all bookmarks in a Mercurial repo through some bash script? I think that this may be possible using awk - but it's a bit beyond me.
The format of the `hg bookmarks` output is (for example):
```
2018.02.706 Customer App 5255:c1321f7f3903
2018.02.707 Customer App 5255:c1321f7f3902
```
I need to get just:
```
2018.02.706 Customer App
2018.02.707 Customer App
``` | 2019/07/04 | [
"https://Stackoverflow.com/questions/56893911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/448337/"
] | If you really just want to delete all bookmarks, just delete the `.hg/bookmarks` file from your repo's hidden `.hg` directory.
The bookmarks may come back if you pull them from a remote location, so you'd have to also do `hg book push -B 'your bookmark name'` to also remove the bookmark from the remote location, but this is a problem you would face with any other method for deleting bookmarks. | Assuming the spaces in your input are blank chars as it appears in your sample input, to do what you asked for in your question portably and robustly is:
```
$ sed 's/ [^ ]*$//' file
2018.02.706 Customer App
2018.02.707 Customer App
```
and to get the output the command line in [your answer](https://stackoverflow.com/a/56902098/1745001) would produce is:
```
$ sed 's/\(.*\) .*$/hg bookmarks --delete '\''\1'\''/' file
hg bookmarks --delete '2018.02.706 Customer App'
hg bookmarks --delete '2018.02.707 Customer App'
```
If you feel a burning desire to use awk then it'd be:
```
$ awk '{sub(/ [^ ]+$/,"")}1' file
2018.02.706 Customer App
2018.02.707 Customer App
$ awk '{sub(/ [^ ]+$/,""); print "hg bookmarks --delete \047" $0 "\047"}' file
hg bookmarks --delete '2018.02.706 Customer App'
hg bookmarks --delete '2018.02.707 Customer App'
```
Replace `/ [^ ]+$/` with `/[[:space:]]+[^[:space:]]+$/` if the white space in your example can be something other than a single blank char. |
39,552,333 | I'm new in Ethereum, so probably that's a silly question.
Now I'm trying to install serpent and pyethereum according to this [tutorial](https://github.com/ethereum/wiki/wiki/Serpent). Everything works well, but when I'm launching Python's code:
```
import serpent
import pyethereum
```
There is an error: `No module named pyethereum`
How can I solve it? | 2016/09/17 | [
"https://Stackoverflow.com/questions/39552333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6843935/"
] | The module's name is `ethereum`, not `pyethereum`. Using the following:
```
import serpent
import ethereum
```
should work just fine. | Follow the installation instructions from [Pytherium's Readme](https://github.com/ethereum/pyethereum), which read:
```
git clone https://github.com/ethereum/pyethereum/
cd pyethereum
python setup.py install
```
In the tutorial's instructions, `develop` branch is used, which seems to be failing according to the continuous integration badges. |
23,476,257 | Say I have an algorithm in Java where I want to do something on a monthly basis based off the time associated with each object.
So for example, if `Object a` has time `long t`, and `t` is in milliseconds since the epoch, how would I find out that `t` is a time in 03/2014?
As a secondary question, how can I iterate over months backwards in time - so if I'm starting on May 1, 2014, how can I accurately go back to April, March, Feb, etc, without worrying about the whole problem of having 28 - 31 days in a month? I was considering using the `Calendar` class, but wasn't sure if I can just update the `MONTH` variable and have it give me a correct millisecond value. Like, what if it's March 31, and I update the month to February, and then suddenly it thinks it's Feb 31? | 2014/05/05 | [
"https://Stackoverflow.com/questions/23476257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3475234/"
] | The easiest way to do this is to use the [`java.util.Calendar`](http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html) class as you mention in your question. You can easily get an instance by using
```
//use whatever time zone your milliseconds originiate from
//there is another getter that takes a Locale, which may be useful depending on your context
Calander c = Calendar.getInstance(TimeZone.getDefault());
```
You can then set the time using
```
c.setTimeInMillis(t);
```
In order to find out when this was, you can print out the result using a [`DateFormat`](http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html) object
```
DateFormat df = DateFormat.getInstance(DateFormat.SHORT);
System.out.println(df.format(c.getTime());
```
To move through the months (or any other unit of time), you would "add" to the calendar using the month field:
```
c.add(Calendar.MONTH, -2);
```
The good news is that you can use the `add()` method for any other time unit and the `Calendar` class will take care of properly adjusting the date as needed, in the way you expect (i.e., the culturally appropriate way defined by the `Locale` of the `Calendar`).
Lastly, you can get this turned back into milliseconds by using
```
long newTime = c.getTimeInMillis();
``` | Using the Java 8 API in `java.time` you could do the following:
```
import java.time.Instant;
import java.time.Month;
import java.time.MonthDay;
import java.time.OffsetDateTime;
public static void main(String[] args) {
long ms_since_epoch = 1_500_000_000_000L;
Instant instant = Instant.ofEpochMilli(ms_since_epoch);
// convert milliseconds in UTC to date
OffsetDateTime dateUTC = OffsetDateTime.ofInstant(instant, ZoneOffset.UTC);
// convert milliseconds in EST (UTC-0500) to date
OffsetDateTime dateEST = OffsetDateTime.ofInstant(instant, ZoneOffset.ofHours(-5));
// note: this is 2017-07-14 at 2:40
// create a MonthDay from the date in EST
MonthDay monthDay = MonthDay.of(dateEST.getMonth(), dateEST.getDayOfMonth());
// note: this is 2017-07-13 at 21:40
// loop over the next six months, after monthDay from dateEST
MonthDay md = monthDay;
for (int i = 0; i < 6; ++i) {
md = md.with(md.getMonth().plus(1));
System.out.println(md);
// prints 08-13 through 01-14 (August 2013 through January 2014)
}
// loop over the previous six months, including this month
md = monthDay;
for (int i = 0; i < 6; ++i) {
System.out.println(md);
md = md.with(md.getMonth().minus(1));
// prints 07-13 through 02-13 (July 2013 through February 2013)
}
}
```
Note that MonthDay is immutable, so calling `md.with(otherMonth)` returns a new instance with the month changed, and it only represents a month and a day, not a complete date with year, time, and time zone. Note also how converting the timestamp yields a different date and time depending on the time zone, which will also be true with `Calendar`. |
2,098,135 | I'd like to increase the height of an NSPathControl as well as make the font size larger. Is there any way to do it without subclassing the control as discussed [here](http://www.cocoabuilder.com/archive/cocoa/226871-design-advice-bread-crumbs-nspathcontrol.html)? | 2010/01/20 | [
"https://Stackoverflow.com/questions/2098135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512/"
] | To get a list of all model classes, you can use `ActiveRecord::Base.subclasses` e.g.
```
ActiveRecord::Base.subclasses.map { |cl| cl.name }
ActiveRecord::Base.subclasses.find { |cl| cl.name == "Foo" }
``` | You can use `rails dbconsole` to view the database that your rails application is using. It's alternative answer `rails db`. Both commands will direct you the command line interface and will allow you to use that database query syntax. |
11,462,768 | When seeing an instance variable's address in the debugger, how can one get the class by entering in the given memory address?
I know that the opposite (getting the address from an instance) is possible with `p someObjectInstance` in the debugger or `NSLog(@"%p", someObjectInstance);` from within the code. Is there a similar way to do this the other way around? | 2012/07/13 | [
"https://Stackoverflow.com/questions/11462768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/205926/"
] | What you are asking for is VERY unsafe. Accessing an unknown memory location is generally a bad idea, but since you asked:
EDIT: If inside `gdb` or `lldb`, you can do the following:
```
po [(id)(0xDEADBEEF) class]
```
If running from code, however, use the following;
```
NSString *input = @"0xFAFAFA";
unsigned address = UINT_MAX; // or UINT_MAX
[[NSScanner scannerWithString:input] scanHexInt:&address];
if (address == UINT_MAX)
{
// couldn't parse input...
NSLog(@"failed to parse input");
return 0;
}
void *asRawPointer = (void *) (intptr_t) address;
id value = (__bridge id) asRawPointer;
// now do something with 'value'
NSLog(@"%@", [value class]);
``` | In Swift, you can use `unsafeBitCast`
```
(lldb) e let $vc = unsafeBitCast(0x7fd0b3e22bc0, GooglyPuff.PhotoCollectionViewController.self)
(lldb) po $vc.navigationItem.prompt = "WOOT!"
```
Reading from [Grand Central Dispatch Tutorial for Swift: Part 2/2](http://www.raywenderlich.com/79150/grand-central-dispatch-tutorial-swift-part-2) |
18,353,830 | I am working on a Quiz Application where I need to get all the selected elements or the user answers . These elements can be radio input, check-box input or the text field. every element is assigned a question\_id attribute, answer\_id and a mark attribute with it. What I want to do is I have to get these all question\_id , answer\_id and mark attribute so that I can calculate marks, and send the both question\_id and answer\_id to DB so that i can store the related user answer under a particular question. i have rendered the quiz on template using this code.
```
$(data.quiztopics).each(function(index,element){
$(element.questions).each(function(index,question){
$(".quiz").append("<form name='question' class= question_"+question.id+"><input type='text' disabled value="+question.question_text+"/><br></form>");
if(question.question_type=='NUM'){
$(question.answers).each(function(index,answer){
$(".question_"+question.id).append("<input type='radio' question_id='+question.id+'answer_id='+answer.id +'name='answer' class=answer_"+answer.id+" mark="+answer.marks+"value="+answer.answer_text+">"+answer.answer_text+"</input>")
});
}
else if(question.question_type=='MCQ'){
$(question.answers).each(function(index,answer){
$(".question_"+question.id).append("<input type='checkbox' question_id='+question.id+'answer_id='+answer.id +' name='answer' class=answer_"+answer.id+">"+answer.answer_text+"</input>")
});
}
else if(question.question_type=='FIB'){
$(question.answers).each(function(index,answer){
$(".question_"+question.id).append("<input type='text' question_id='+question.id+'answer_id='+answer.id +' name='answer' class=answer_"+answer.id+">"+answer.answer_text+"</input>")
});
}
});
});
```
tell me how can i get the attributes of the selected elements for submitting the quiz. | 2013/08/21 | [
"https://Stackoverflow.com/questions/18353830",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765969/"
] | I have solved this problem by getting all the elements available in the DOM by their name, using getElementsByName('answer') method. It returns me a list then looping over this list i checked if the element is check or not if it is checked i get their attributes.
```
attributes_list=new Array()
var answers=document.getElementsByName('answer');
for(i=0;i<answers.length;i++){
if(answers[i].checked){
question_id=answers[i].attributes['question_id'].value
answer_id=answers[i].attributes['answer_id'].value
attributes_list.push({'que':question_id,'ans':answer_id});
}
}
``` | its very simple, you just have to use `element.attr( attributeName )` function
[JQuery documentation](http://api.jquery.com/attr/)
A little [JSFIddle](http://jsfiddle.net/Y8K9A/) to get you going
```
alert("Radio Mark " + $("#one").attr('mark') + ", Radio Value " + $("#one").attr('value'));
alert("check Mark " + $("#two").attr('mark') + ", check Value " + $("#two").attr('value'));
``` |
16,521,029 | Suppose I have some html like this -:
```
<div style="blah...blah">Hey Nice</div>
<a style="blah...blah">Great</a>
```
How do I remove all the inline styling applied to the above elements in my stylesheet considering I don't know what all inline styling exists.
Currently I am trying this, but in vain -:
```
div[style], a[style]{ !important }
``` | 2013/05/13 | [
"https://Stackoverflow.com/questions/16521029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1952015/"
] | You must reset **all** css properties for elements that have `style` attribute:
```
[style] {
position: static !important;
float: none !important;
border: 0 none !important;
margin: 0 !important;
padding: 0 !important;
outline: 0 none !important;
// and so on
}
``` | There are several determining factors determining which CSS property prevails in any situation. In order, these are:
1. Whether the property value has the `!important` flag or not.
2. If the style declaration is applied inline via the `style` attribute.
3. The strength of the CSS rule selector
* If the rule has any ID clauses, and if so how many
* If the rule has class, attribute or pseudo-class clauses, and if so how many
* If the rule has any tagname clauses, and if so how many
4. If the property is parsed later in the source than another property with a rule of the same strength
So the only way to override the properties is to make sure that all the properties applied via `style` are applied elsewhere in your stylesheet, and have the `!important` declaration. The most rational way to do this is still very awkward — it would involve applying a very specific reset stylesheet, and including `!important` on every property on every rule.
But even if this is done, you still couldn't override inline `style` declarations that have `!important` themselves.
You've told Mojtaba that there should be a better solution, but that better solution would involve designing CSS to break its own rules. Imagine if there was a simpler solution for overriding inline styles from stylesheets designed into the language of CSS — should there also be another solution for simply overriding the override from inline styles? Where does the cycle end? All in all, I'd recommend using Javascript or giving up. Or describing your specific problem in more detail — there may be another solution! |
33,442,951 | I built this code as a test to delete a range of records from an Access 2013 database based upon a range of dates. I'm getting a missing operator error in query expression 'START\_DATE >= .....etc. I have tried the select statement with apostrophes as well.
NOTE: the CALL line is all one line in the actual code. Also, if I run the CALL line with Between/AND instead of >= / <= , the code completes with no errors, but does not accomplish anything. It does not find and delete the rows.
```
Function Delete_Range()
Dim begdt As Date
Dim enddt As Date
'user inputs date range
begdt = InputBox("Enter beginning date as mm/01/yyyy", "BEGINNING DATE")
enddt = InputBox("Enter ending date as mm/01/yyyy", "ENDING DATE")
Dim objectrecordset As ADODB.Recordset
Set objectrecordset = New ADODB.Recordset
'initiate recordset object
objectrecordset.ActiveConnection = CurrentProject.Connection
Call objectrecordset.Open("select START_DATE
from TEMP_DATE_RANGE where START_DATE IS >= "
& begdt & " AND <= " & enddt, , , adLockBatchOptimistic)
While objectrecordset.EOF = False
'delete record
objectrecordset.Delete
objectrecordset.UpdateBatch
'move to next record
objectrecordset.MoveNext
Wend
End Function
```
Thank you everybody for your help. Here is the code that worked.
```
DoCmd.SetWarnings (warningsoff)
'Declare variables
Dim begdt As String
Dim enddt As String
'User inputs variables
begdt = InputBox("Enter beginning date as mm/01/yyyy", "BEGINNING DATE")
enddt = InputBox("Enter ending date as mm/01/yyyy", "ENDING DATE")
'Format variable as date and error handling
If Not (IsDate(begdt) And IsDate(enddt)) Then
MsgBox "Please enter a date using a the date format", vbOKOnly
GoTo Finished
Else
begdt = Format(begdt, "\#yyyy\/mm\/dd\#")
enddt = Format(enddt, "\#yyyy\/mm\/dd\#")
End If
'Delete records from tables based upon user input date range
Dim SQL As String
Dim SQL2 As String
Dim SQL3 As String
SQL = "DELETE * FROM TEST_TBL_1 WHERE START_DATE BETWEEN " & begdt & " AND " & enddt & ""
SQL2 = "DELETE * FROM TEST_TBL_2 WHERE START_DATE BETWEEN " & begdt & " AND " & enddt & ""
SQL3 = "DELETE * FROM TEST_TBL_3 WHERE START_DATE BETWEEN " & begdt & " AND " & enddt & ""
DoCmd.RunSQL SQL
DoCmd.RunSQL SQL2
DoCmd.RunSQL SQL3
'Close form and show process complete page
DoCmd.SetWarnings (warningson)
DoCmd.Close acForm, "DELETE HISTORY", acSaveNo
DoCmd.OpenForm "COMPLETE", acNormal, "", "", , acNormal
Finished:
End Function
``` | 2015/10/30 | [
"https://Stackoverflow.com/questions/33442951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4538449/"
] | First work out the query logic and syntax in the Access query designer. Assuming *START\_DATE* is Date/Time datatype, pick a couple static values for the start and end of your target date range:
```sql
SELECT START_DATE
FROM TEMP_DATE_RANGE
WHERE START_DATE BETWEEN #2015-1-1# AND #2015-10-30#
```
Adjust as needed.
Once you have the proper SQL statement, build the corresponding statement text in your VBA code.
```vb
Dim strSelect As String
strSelect = "SELECT START_DATE FROM TEMP_DATE_RANGE " & _
"WHERE START_DATE BETWEEN " & Format(begdt,"\#yyyy-m-d\#") & _
" AND " & Format(enddt,"\#yyyy-m-d\#")
Debug.Print strSelect '<- inspect this in Immediate window; Ctrl+g will take you there
```
Then you can use *strSelect* with `objectrecordset.Open`
However, since your goal is to delete those rows, you don't actually need a recordset. You can simply execute a `DELETE` statement instead.
```sql
DELETE FROM TEMP_DATE_RANGE
WHERE START_DATE BETWEEN #2015-1-1# AND #2015-10-30#
``` | Your date comparison syntax is a little off, remove `IS` in `IS >=` and remember to add `START_DATE <=` rather than just `<=`
With the corrections, it becomes:
```
Call objectrecordset.Open("select START_DATE
from TEMP_DATE_RANGE where START_DATE >= "
& begdt & " AND START_DATE <= " & enddt, , , adLockBatchOptimistic)
``` |
13,906 | If the time signature is 8/8 or 4/4 and let's say we have 8 eighth notes in a bar the picking should just be down up down up down up, etc. But what happens if we have 7/8? Particularly in the next bar. After we play the first bar the 7th eighth note was played downwards so should the first note of the next bar be played upwards? | 2013/11/29 | [
"https://music.stackexchange.com/questions/13906",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/8608/"
] | While, as said by the previous answers, such meters can normally be sudivided into little chunks, it is in my experience not a good idea to let this influence strumming patterns etc. to directly: this is prone to give exactly the experience that many people associate, dislikingly, with odd meters – a "jumpy" sound, as if something is just missing or artificially plunged into the rythm.
In my band (where we have *lots* of unusual time signatures), we tend to try avoiding the unevenness or spread it out across the bars and the intruments as much as possible.
Sometimes, the best thing is to just keep the "natural" pattern going as if it were a 4/4. The extreme application of this is the grooves Led Zeppelin preferred in odd meters: John Bonham would usually play extremely *even*, often actually staying with something that sounded like a very reduced rock rythm for most of the time. Listen to Black Dog. I quite like this approach; it preserves a powerful beat with no jarring jumps, while still giving some exciting quirkiness of the odd meter. But of course such an approach doesn't always work, it quite limits the ability to build in common syncopated accents etc..
Strumming
---------
Yet, for guitar, you can often keep to a simple alternating down/up pattern even when obeying an accent pattern of an odd meter. If a 7/8 is not to fast, the natural thing might be a down/up-pulse in 16th notes; that way you end up on a downstroke on each 1 without further ado. If that's too fast, simply reversing the direction on every other bar might be fine as well. Sure, you won't have the potentially more powerful downstrokes on the "classical" emphasised beats, but always accenting those beats with rythm guitar tends to sound a bit stupid anyway. It's often better to only "feel" the accents.
If you find none of this works satisfyingly and you need to build in some "switch", I'd normally try to place it somewhere *in the middle*, so the last stroke[s] are already coherent with the first ones of the next bar. For instance, in a 7/8 I might prefer `|↑↓↑↓↑↑↓|↑↓↑↓↑↑↓|` over `|↑↓↑↓↑↓↑|↑↓↑↓↑↓↑|`. Actually though, two strokes in the same direction mean there's necessarily an implicit 16th in between, so really this would read `|↑ ↓ ↑ ↓ ↑.↑ ↓ |`. I.e., you basically have to speed up to 16th in between anyway. I'd probably end up with something like `|↑ ↓ ↑ ↓ ↑..↓..|` (a stroke on `6+`), where the implicit 16ths aren't necessary anymore. Of course, it really depends on the piece. You generally will have some of the strokes silent anywhere, so you can also just omit one of those, that also results in a direction switch.
If you're not playing with a pick, there's another option that borrows from Flamenco strumming techniques: you can do e.g. two down strokes in a row, but both within one hand movement, using the fingers for the first stroke and the thumb for the second. I find this can give extremely smooth results and can be placed pretty much anywhere in the meter.
Picking
-------
This is quite another issue to begin with. In traditional folky finger picking, the thumb has a similar "steady beat" role as the down/up movement in strumming, but usually slower. It's quite difficult to incorparate this into an odd meter; I'd probably try do actually keep it going, possibly over multiple bars, until it's eventually in sync again. But I don't have much experience with that.
For less rythmic picking, perhaps just single-note arpeggio, there shouldn't be much of a problem: which string you pluck doesn't follow a fixed underlying beat anyway, so you can pretty much try anything you feel fits in the meter. What's ideal depends again on the musical context. | Watch any good rhythm player, and notice how the strumming arm flows with a regular motion. The up/down movements are not jerky. With some of the above answers, the strum pattern, whatever it is, will result in jerks.
By playing the main beats all with downstrokes, the 'ands' are with upstrokes. This will keep a steady flow going. When a rhythm player wants to change the pattern in the middle of a song, it is then so easy - the pattern of the strumming arm doesn't change, only the number of occasions the strings are sounded.
For example, in a song with 4 strong beats per bar, all will be downstrums.Changing the feel to say, reggae, with the same tempo, just miss the strings on all the downstrums, but flick them on the way up each time - reggae. Strum arm pattern - exactly the same.( I'm trying to keep it simple).
What I'm advocating is that in most rhythm patterns, including odd time sigs., is that EACH BAR needs the same motion with the strumming arm.Thus, subtle pattern changes are easy to do, and will sound smooth. A lot of the above suggestions will, I feel, cause the rhythm to sound jumpy - unless, of course, that's what is wanted or required for the song. Not usual, though. |
40,747,397 | I'm creating a pennies game, which has now already been created in C++, however I am having some trouble converting it to Python. It seems I can't figure out how to convert something such as this loop into Python.
```
void penniesLeftOver(int amountOfPenniesCurrent) //Displays the amount of Pennies left to the user.
{
cout << "Pennies Remaining: " << amountOfPenniesCurrent; //Displays the amount of Pennies remaining.
for (int i = 0; i < amountOfPenniesCurrent; i++)
{
cout << " o"; //Uses "o" to represent a Penny.
}
cout << "\n" << endl; //Starts a new line.
}
``` | 2016/11/22 | [
"https://Stackoverflow.com/questions/40747397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7195717/"
] | In python you can multiply a string by an int, it will create a new string which is the initial string repeated n times.
And you can `print()` multiples things at once. Which gives:
```
def penniesLeftOver(amountOfPenniesCurrent):
print("Pennies Remaining:", amountOfPenniesCurrent, " o"*amountOfPenniesCurrent)
``` | while it makes more sense to modify the string beforehand so you only make one call to `print` there are other ways to accomplish your task.
`sys.stdout.write(string)` will write the variable `string` to stdout (buffered) and calling `sys.stdout.flush()` will flush that buffer to write immediately. (you can also define the buffer size)
alternatively you can use the print function's keyword argument `end=''` (which normally defaults to `\n`) to prevent a newline from being added. in python2.7 this requires calling `from __future__ import print_function`
```
>>>for i in range(10):
... print('o', end='')
...
oooooooooo>>>
>>>for i in range(10):
... sys.stdout.write('o')
... sys.stdout.flush()
>>>
oooooooooo>>>
``` |
55,690,307 | I got some question and hopefully you can help me out. :)
What I have is a table like this:
```
ID Col1 Col2 ReverseID
1 Number 1 Number A
2 Number 2 Number B
3 Number 3 Number C
```
What I want to achieve is:
* Create duplicate of every record with switched columns and add them to original table
* Add the ID of the duplicate to ReverseID column of original record and vice-versa
So the new table should look like:
```
ID Col1 Col2 ReverseID
1 Number 1 Number A 4
2 Number 2 Number B 5
3 Number 3 Number C 6
4 Number A Number 1 1
5 Number B Number 2 2
6 Number C Number 3 3
```
What I've done so far was working with temporary table:
```
SELECT * INTO #tbl
FROM myTable
UPDATE #tbl
SET Col1 = Col2,
Col2 = Col1,
ReverseID = ID
INSERT INTO DUPLICATEtable(
Col1,
Col2,
ReverseID
)
SELECT Col1,
Col2,
ReverseID
FROM #tbl
```
In this example code I used a secondary table just for making sure I do not compromise the original data records.
I think I could skip the SET-part and change the columns in the last SELECT statement to achieve the same, but I am not sure.
Anyway - with this I am ending up at:
```
ID Col1 Col2 ReverseID
1 Number 1 Number A
2 Number 2 Number B
3 Number 3 Number C
4 Number A Number 1 1
5 Number B Number 2 2
6 Number C Number 3 3
```
So the question remains: How do I get the ReverseIDs correctly added to original records?
As my SQL knowledge is pretty low I am almost sure, this is not the simplest way of doing things, so I hope you guys & girls can enlighten me and lead me to a more elegant solution.
Thank you in advance!
br
mrt
### Edit:
I try to illustrate my initial problem, so this posting gets long. ;)
[](https://i.stack.imgur.com/4D5cC.png)
.
First of all: My frontend does not allow any SQL statements, I have to focus on classes, attributes, relations.
**First root cause:**
Instances of a class B (B1, B2, B3, ...) are linked together in class Relation, these are many-to-many relations of same class. My frontend does not allow join tables, so that's a workaround.
Stating a user adds a relation with B1 as first side (I just called it 'left') and B2 as second side (right):
Navigating from B1, there will be two relations showing up (FK\_Left, FK\_Right), but only one of them will contain a value (let's say FK\_Left).
Navigating from B2, the value will be only listed in the other relation (FK\_Right).
So from the users side, there are always two relations displayed, but it depends on how the record was entered, if one can find the data behind relation\_left or relation\_right.
That's no practicable usability.
If I had all records with vice-versa partners, I can just hide one of the relations and the user sees all information behind **one** relation, regardless how it was entered.
**Second root cause:**
The frontend provides some matrix view, which gets the relation class as input and displays left partners in columns and right partners in rows.
Let's say I want to see all instances of A in columns and their partners in rows, this is only possible, if all relations regarding the instances of A are entered the same way, e.g. all A-instances as left partner.
The matrix view shall be freely filterable regarding rows and columns, so if I had duplicate relations, I can filter on any of the partners in rows and columns.
sorry for the long text, I hope that made my situation a bit clearer. | 2019/04/15 | [
"https://Stackoverflow.com/questions/55690307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11363139/"
] | Currently `Wrapper<A>` and `Wrapper<B>` are structurally compatible. If you'll store the passed constructor as a field (for example) you'll get an error:
```
type Constructor<T> = new (...args: any[]) => T;
class Wrapper<T> {
constructor(private c: Constructor<T>){}
public static forConstructor<T>(construc: Constructor<T>): Wrapper<T> {
return new Wrapper<T>(construc);
}
}
class A {
private aaa: string = null;
}
class B {
private bbb: string = null;
}
const wrapper: Wrapper<A> = Wrapper.forConstructor(B); // error
```
[Playground](https://www.typescriptlang.org/play/index.html#src=type%20Constructor%3CT%3E%20%3D%20new%20(...args%3A%20any%5B%5D)%20%3D%3E%20T%3B%0D%0A%0D%0Aclass%20Wrapper%3CT%3E%20%7B%0D%0A%20%20constructor(private%20c%3A%20Constructor%3CT%3E)%7B%7D%0D%0A%0D%0A%20%20%20%20public%20static%20forConstructor%3CT%3E(construc%3A%20Constructor%3CT%3E)%3A%20Wrapper%3CT%3E%20%7B%0D%0A%20%20%20%20%20%20%20%20return%20new%20Wrapper%3CT%3E(construc)%3B%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Aclass%20A%20%7B%0D%0A%20%20%20%20private%20aaa%3A%20string%20%3D%20null%3B%0D%0A%7D%0D%0A%0D%0Aclass%20B%20%7B%0D%0A%20%20%20%20private%20bbb%3A%20string%20%3D%20null%3B%0D%0A%7D%0D%0A%0D%0Aconst%20wrapper%3A%20Wrapper%3CA%3E%20%3D%20Wrapper.forConstructor(B)%3B%20%2F%2F%20error) | A static method can not use the instance type argument `Wrapper<T>` since static is not instance bounded. Your method signature `<S extends Object` essentially means `any` Object. So there is no type safety at all. That's why the tscompiler does not complain at
```
const wrapper: Wrapper<A> = Wrapper.forConstructor(B);// LINE X
```
However if you actually use the instance type argument and make it non-static then it will complain e.g.
```
class Wrapper<S> {
public forConstructor(construc: { new (...args: any[]): S }): Wrapper<S> {
return new Wrapper<S>();
}
}
const wrapper: Wrapper<A> = new Wrapper();
wrapper.forConstructor(B); // will not work
``` |
4,087,325 | If $\sum a\_n$ is convergent then the power series $\sum a\_n z^n$ has a positive radius of convergence. Prove or disprove. I am unable to connect the convergence of the series and the corresponding power series. Help please. | 2021/04/02 | [
"https://math.stackexchange.com/questions/4087325",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/201051/"
] | There are
* $\binom{25}{0} = 1$ ways to toss the coin 25 times, obtaining zero "cross"s,
* $\binom{25}{1} = 25$ ways to toss the coin 25 times, obtaining one "cross", and
* $2^{25} = 33\,554\,432$ possible sequences of 25 coin tosses.
So the probability of getting $0$ or $1$ "cross"s is
$$ \frac{\binom{25}{0} + \binom{25}{1}}{2^{25}} = \frac{1 + 25}{33\,554\,432} = \frac{13}{16\,777\,216} \text{.} $$ | If I understand your question correctly...
Take cases on if $x=0,1$.
If $x=0$, then every flip must be head, so
$$\frac{1}{2^{25}}$$
chance.
If $x=1$ then there must be one cross and all others heads. This happens with chance
$$\frac{25}{2^{25}}.$$
Thus the answer is
$$\frac{26}{2^{25}}.$$ |
6,970,921 | I'm trying to set up a basic web page, and it has a small music player on it (niftyPlayer). The people I'm doing this for want the player in the footer, and to continue playing through a song when the user navigates to a different part of the site.
Is there anyway I can do this without using frames? There are some tutorials around on changing part of a page using ajax and innerHTML, but I'm having trouble wrapping my head aroung getting everything BUT the music player to reload.
Thank you in advance,
--Adam | 2011/08/07 | [
"https://Stackoverflow.com/questions/6970921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/882442/"
] | Wrap the content in a div, and wrap the player in a separate div. Load the content into the content div.
You'd have something like this:
```
<div id='content'>
</div>
<div id='player'>
</div>
```
If you're using a framework, this is easy: `$('#content').html(newContent)`.
EDIT:
This syntax works with jQuery and ender.js. I prefer ender, but to each his own. I think MooTools is similar, but it's been a while since I used it.
Code for the ajax:
```
$.ajax({
'method': 'get',
'url': '/newContentUrl',
'success': function (data) {
// do something with the data here
}
});
```
You might need to declare what type of data you're expecting. I usually send json and then create the DOM elements in the browser.
EDIT:
You didn't mention your webserver/server-side scripting language, so I can't give any code examples for the server-side stuff. It's pretty simple most of time. You just need to decide on a format (again, I highly recommend JSON, as it's native to JS). | What you're looking for is called the 'single page interface' pattern. It's pretty common among sites like Facebook, where things like chat are required to be persistent across various pages. To be honest, it's kind of hard to program something like this yourself - so I would recommend standing on top of an existing framework that does some of the leg work for you. I've had success using backbone.js with this pattern:
<http://andyet.net/blog/2010/oct/29/building-a-single-page-app-with-backbonejs-undersc/> |
24,249,320 | I have a table (Table1) that has an ID that is shared from multiple-inserts:
>
>
> ```
> ID | RefID | Field_Name | Field_Value | Type
> 1 | 1 | NumbAmt | 1111 | INT
> 2 | 1 | LocAdd | 123 Street | String
> 3 | 1 | LocDesc | Something | String
> 4 | 1 | LocHidden | Useless | Hidden
>
> ```
>
>
I can't use the ID since it is made from the inserts, the RefID is the main thing used to narrow down this data to all those with the **RefID = 1 AND Type != 'Hidden'**.
Whenever I do a case statement query:
```
SELECT
CASE WHEN Field_Name = 'NumbAmt' THEN Field_Value END Amt,
CASE WHEN Field_Name = 'LocAdd' THEN Field_Value END Address,
CASE WHEN Field_Name = 'LocDesc' THEN Field_Value END Description
FROM Table1
WHERE RefID = 1
AND Type IN ('INT','String')
```
It returns the results like:
>
>
> ```
> Amt | Address | Description
> 1111 | NULL | NULL
> NULL | 123 Street | NULL
> NULL | NULL | Something
>
> ```
>
>
My question is, how would I gather all the data but have it split into separate columns without all the NULLs showing? (My assumption leads me to believe a temp table)
Or show up like:
>
>
> ```
> Amt | Address | Description
> 1111 | 123 Street | Something
>
> ```
>
> | 2014/06/16 | [
"https://Stackoverflow.com/questions/24249320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368835/"
] | You have several options:
* Join the table to itself
* Use PIVOT
* Subquery all fields in the SELECT list
* Use OUTER APPLY for each field
* Use CTE
* **Consider to rethink your scheme!**
**JOINS**
```
SELECT
T1_RefID.RefID,
T1_NumbAmt.FieldValue AS NumbAmt,
T1_LocAdd.FieldValue AS LocAdd
FROM
(SELECT DISTINCT RefID FROM Table1) T1_RefID
LEFT JOIN Table1 T1_NumbAmt
ON T1_RefID.RefID = T1_NumbAmt.RefID AND T1_NumbAmt.FieldName = 'NumbAmt' AND T1_NumbAmt.Type != 'Hidden'
LEFT JOIN Table1 T1_LocAdd
ON T1_RefID.RefID = T1_LocAdd.RefID AND T1_LocAdd.FieldName = 'LocAdd' AND T1_LocAdd.Type != 'Hidden'
/* And so on*/
```
**PIVOT**
```
SELECT
*
FROM (
SELECT
RefID, FieldName, FieldValue
FROM
Table1
WHERE
Type != 'Hidden'
) AS src
PIVOT (
MAX(FieldValue)
FOR FieldName IN (NumbAmt, LocAdd, LocDesc)
) AS PVT
```
[SQL Fiddle](http://sqlfiddle.com/#!6/61335/8) | Use group by on the key field, and some aggregate function to promote the correct value over the nulls (I believe max will do, but cannot test this where I sit presently)
```
SELECT
RefID,
MAX( CASE WHEN Field_Name = 'NumbAmt' THEN Field_Value ELSE NULL END ) Amt,
MAX( CASE WHEN Field_Name = 'LocAdd' THEN Field_Value ELSE NULL END ) Address,
MAX( CASE WHEN Field_Name = 'LocDesc' THEN Field_Value ELSE NULL END ) Description
FROM Table1
GROUP BY RefID
``` |
337,449 | I need to declare an array of pointers to functions like so:
```
extern void function1(void);
extern void function2(void);
...
void (*MESSAGE_HANDLERS[])(void) = {
function1,
function2,
...
};
```
However, I want the the array to be declared as constant -- both the data in the array and the pointer to the data. Unfortunately, I do not recall where to place the const key-word(s).
I'm assuming the actual pointer, MESSAGE\_HANDLERS in this case, is already constant because it is declared as an array. On the otherhand, couldn't the function pointers within the array be change at runtime if it is declared as shown? | 2008/12/03 | [
"https://Stackoverflow.com/questions/337449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1491/"
] | `cdecl` says:
```
cdecl> explain void (* const foo[])(void)
declare foo as array of const pointer to function (void) returning void
```
Is it what you need? | I am not sure if this will work in 'C'. it does work in 'C++':
* First define MESSAGE\_HANDLERS as a type:
`typedef void (*MESSAGE_HANDLER)();`
* Then, use the type definition to declare your array a constant:
`MESSAGE_HANDLER const handlers[] = {function1, function2};`
The trick is in the `typedef`, if you can do the same semantically in 'C', it should work too. |
28,867,024 | I am using
```
void Update()
{`for (var i = 0; i < Input.touchCount; ++i)
{
if (Input.GetTouch(i).phase == TouchPhase.Began)
{
// Construct a ray from the current touch coordinates
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(i).position);
if (Physics.Raycast(ray))
Destroy();
}
}
```
}
I tested on my mobile phone (Windows Phone) to see if I can touch my object to destroy. This script is also attached to the object, so when touched it should get destroyed. Instead, if I touch anywhere in the screen, all the objects, which is multiple duplicates of one object, gets destroyed instead of the specific one I touch. This does not happen when I use OnMouseDown. Is there something I can do similar to MouseDown with touch control? | 2015/03/04 | [
"https://Stackoverflow.com/questions/28867024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4220797/"
] | An attribute has its own syntax. It uses the `name=value` form for named parameters.
For a normal method you can't use that form, you are stuck with the `name:value` form.
It would not be possible to use the `name=value` form for normal methods. The compiler would not be able to tell if you were trying to use a named parameter or if you were trying to assing a value to a variable and use the assignment as a parameter value. | Despite this syntax looking like a method call:
```
[Required(ErrorMessage="Something")]
```
An Attribute is a *class*, not a method. You aren't specifying an argument in the line above, you are initializing a property. See the example on the [Attribute base class documentation](https://msdn.microsoft.com/en-us/library/system.attribute%28v=vs.110%29.aspx) to see what I mean.
The Attribute-specifying syntax is therefore similar to C#'s class initialization syntax:
```
new RequiredAttribute { ErrorMessage = "Something" };
```
There is currently no equivalent syntax in C# for specifying a named argument to a method. |
51,848 | Whats the difference between using:
```
ENTITY MyDemo is
PORT(X: IN STD_LOGIC; F: OUT STD_LOGIC );
END MyDemo;
```
and
```
ENTITY MyDemo is
PORT(X: IN BIT; F: OUT BIT );
END MyDemo;
```
What are the limitations of using BIT over STD\_LOGIC and vice-versa? Are they completely interchange able? I understand that if I've define STD\_LOGIC I can't use it with a BIT\_Vector to access the elements in the array. But I can't seem to see the difference. | 2012/12/20 | [
"https://electronics.stackexchange.com/questions/51848",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/1623/"
] | **`std_logic` has a resolution function**
Not only does `std_logic` have more useful states besides `1` and `0`, it also has a resolution function defined.
A resolution function is a VHDL language concept. It is a function that is associated to a type, and it determines what happens when multiple values of that type are applied to a single signal. The syntax is:
```
SUBTYPE std_logic IS resolved std_ulogic;
```
where `std_ulogic` is the unresolved (and thus much less useful) version of `std_logic`.
In particular, this implies nice things like `0` and `1` leads to `X`:
```
library ieee;
use ieee.std_logic_1164.all;
entity std_logic_tb is
end std_logic_tb;
architecture behav of std_logic_tb is
signal s0 : std_logic;
begin
s0 <= '0';
s0 <= '1';
process
begin
wait for 1 ns;
assert s0 = 'X';
wait;
end process;
end behav;
```
This makes intuitive sense, as we understand `X` to be the state where multiple incompatible values are applied to a single wire.
`std_logic` also knows how to resolve every other possible pair of input signals according to a table present on the LRM.
`bit` on the other hand, does not have a resolution function, and if we had used it on the above example, it would lead to a simulation error on GHDL 0.34.
The possible values of `std_logic` are a good choice because they are standardized by [IEEE 1164](https://en.wikipedia.org/wiki/IEEE_1164) and deal with many common use cases.
Related: <https://stackoverflow.com/questions/12504884/what-is-the-purpose-of-the-std-logic-enumerated-type-in-vhdl> | *std\_logic* is richer than *bit*, and should basically be used most of the time.
There is also the *boolean* type, which, like *bit*, has two values. It is the result type of comparisons, the type expected after an IF *[bool]* or a WHEN *[bool]*, often used for selection constants : `constant ENABLE_DEBUG_INTERFACE : boolean := true;`
One place where *bit* can be preferred to *std\_logic* is for large arrays, memories. On optimizing simulators, bit occupies less area in the simulator's memory than *std\_logic*. And it may matter if your design instantiates one GB of RAM.
It can also be faster for very large designs, for example something automatically generated from post-synthesis gate-level netlist.
Of course, this performance aspect is not part of the language, and depends on the implementation of the VHDL simulator. |
58,534,956 | i am getting an error when i trying to run the app. please help. The error in cmd is below -
Error running Gradle:
ProcessException: Process "C:\Flutter projects\FlatApp-Firebase-Flutter-master\android\gradlew.bat" exited abnormally:
FAILURE: Build failed with an exception.
* Where:
Build file 'C:\Flutter projects\FlatApp-Firebase-Flutter-master\android\app\build.gradle' line: 14
* What went wrong:
A problem occurred evaluating project ':app'.
>
> ASCII
>
>
>
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with
--scan to get full insights.
* Get more help at <https://help.gradle.org>
BUILD FAILED in 14s
Command: C:\Flutter projects\FlatApp-Firebase-Flutter-master\android\gradlew.bat app:properties
Please review your Gradle project setup in the android/ folder.
---------------------------------------------------------------
line nine in app-build-gradle is below-
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
} | 2019/10/24 | [
"https://Stackoverflow.com/questions/58534956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12172062/"
] | The answer from [Mahmoud Ben Hassine](https://stackoverflow.com/a/58538544/6043279) and the comments pretty much covers all aspects of the solution and is the accepted answer.
Here is the implementation I used if anyone is interested :
```
public class JdbcCustomBatchSizeItemWriter<W> extends JdbcDaoSupport implements ItemWriter<W> {
private int batchSize;
private ParameterizedPreparedStatementSetter<W> preparedStatementSetter;
private String sqlFileLocation;
private String sql;
public void initReader() {
this.setSql(FileUtilties.getFileContent(sqlFileLocation));
}
public void write(List<? extends W> arg0) throws Exception {
getJdbcTemplate().batchUpdate(sql, Collections.unmodifiableList(arg0), batchSize, preparedStatementSetter);
}
public void setBatchSize(int batchSize) {
this.batchSize = batchSize;
}
public void setPreparedStatementSetter(ParameterizedPreparedStatementSetter<W> preparedStatementSetter) {
this.preparedStatementSetter = preparedStatementSetter;
}
public void setSqlFileLocation(String sqlFileLocation) {
this.sqlFileLocation = sqlFileLocation;
}
public void setSql(String sql) {
this.sql = sql;
}
}
```
**Note :**
1. The use of `Collections.unmodifiableList` prevents the need for any explicit casting.
2. I use `sqlFileLocation` to specify an external file that contains the sql and `FileUtilities.getfileContents` simply returns the contents of this sql file. This can be skipped and one can directly pass the `sql` to the class as well while creating the bean. | I wouldn't do this. It presents issues for restartability. Instead, modify your reader to produce individual items rather than having your processor take in an object and return a list. |
4,703,028 | I'm trying to get futures running for Mvc3 RTM. There is no .dll included after installing mvc3 from webPI.
I've downloaded the source and have tried to build it myself, but when I drop it into my solution and add the namespace to the web.config under the Views folder I get the following error on every page:
```
S0012: The type 'System.Web.Mvc.Controller' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=null'.
```
I guess it's because because of strong naming or something along those lines.
How can I get up and running with futures?
Edit:
1) I might be wrong, but from memory, when you downloaded and installed previous versions of MVC, it would give you a Microsoft.Web.Mvc .dll under Program File/Microsoft ASP.NET/Asp .net MVC2. With WebPI install, there is only System.Web.Mvc.dll in that location.
2) It is definitely not in the GAC... it's not the place for this assembly (I also checked just to make sure)
3) The project that is not working is the target project. I created a new 'Asp .net Mvc 3 Application' ran it to make sure it worked (it did). Then I added a reference to the assembly I built from the Mvc 3 Source Code and altered the web.config under the 'Views' folder.
```
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="Microsoft.Web.Mvc" />
</namespaces>
</pages>
```
4) As soon as I remove the namespace element and the dll, the project works again. | 2011/01/16 | [
"https://Stackoverflow.com/questions/4703028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/178211/"
] | It's been added to the MVC 3 RTM release now :
<http://aspnet.codeplex.com/releases/view/58781#DownloadId=211128>
The direct link is here :
<http://aspnet.codeplex.com/releases/view/58781#DownloadId=211128> | You need to include the assembly in the web.config as well as the namespace - if you started with an mvc2 project you probably have a line in there like
That will need to change to 3.0 of course, and you may also need to update the binding redirect.
When you say there is no dll included, have you checked the gac? If it is there you don't need a file locally for the system to find it based on strong name.
If you have built from source and therefore your version has a different strong name, you may have issues with third party components that reference an official build, but as long as the name in web config matches you should be ok for the core stuff. You'll want to add your own key so that the token isn't null though. |
271,110 | I would like to extract 2D mesh of outer surface of 3D meshed object.
Let's say I have 3D mesh data from [here](https://www.dropbox.com/sh/2ogwd26rk2daogu/AADiFuYQn0EG88kIgnWmg9JCa?dl=0) and I import the data into Mathematica.
```
Needs["NDSolve`FEM`"];
SetDirectory[NotebookDirectory[]];
nodes3Dmesh = Import["nodes_3D_mesh.txt", "Table"];
conn3Dmesh = Import["connection_3D_mesh.txt", "Table"] + 1;
mesh3D = ToElementMesh["Coordinates" -> nodes3Dmesh, "MeshElements" ->
{HexahedronElement[conn3Dmesh]}];(*3D hex mesh*)
Graphics3D[{ElementMeshToGraphicsComplex[mesh3D]}, Axes -> True,
AxesLabel -> {x, y, z}]
```
[](https://i.stack.imgur.com/BJp4z.png)
Now, I want to extract 2D mesh of surface lying in the *x*-*z* plane at ***y = 0*** (this reddish surface in the above picture).
My approach to this problem was:
```
PosNodesY0 = Flatten[Position[nodes3Dmesh, _?(#[[2]] == 0. &)]];(*positions of nodes which
have y coordinate equal to zero*)
conn2Dmesh = Select[Map[Select[#, MemberQ[PosNodesY0, #] &] &, conn3Dmesh],
UnsameQ[#, {}] &];(*computed connections for the 2D mesh*)
mesh2D = ToElementMesh["Coordinates" -> Drop[nodes3Dmesh, None, {2}],
"MeshElements" -> {QuadElement[conn2Dmesh]}];(*resulting 2D quad mesh*)
mesh2D["Wireframe"]
```
[](https://i.stack.imgur.com/AX5G2.png)
**Questions**:
1. My approach of extracting 2D mesh takes a long time for large 3D meshed object. Specifically the `conn2Dmesh` implementation. It is possible to make it faster?
2. My approach does not work for surface with more complicated geometry (e.g. white surface in the first picture). Would it be possible to generalize this for any outer surface of 3D object?
I would appreciate any help. | 2022/07/21 | [
"https://mathematica.stackexchange.com/questions/271110",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/38112/"
] | Here's the different approach (not sure how fast it will be though).
First, construct the mesh region and convert it to a boundary mesh:
```
mesh = MeshRegion[nodes3Dmesh, Hexahedron[conn3Dmesh]];
bmesh = BoundaryMesh[mesh];
```
Compute normal vectors of polygons:
```
enormal = Chop[Region`Mesh`MeshCellNormals[bmesh, 2]];
```
compare normals of adjacent polygons of lines and find corner edges:
```
mg = MeshConnectivityGraph[bmesh, {1, 2}];
edges = VertexList[mg, {1, _}];
adj = (AdjacencyList[mg, #] & /@ edges)[[All, All, 2]];
corneredges = Pick[edges, Dot @@ enormal[[#]] & /@ adj, x_ /; x < 1];
HighlightMesh[bmesh, corneredges]
```
[](https://i.stack.imgur.com/soMQY.jpg)
Partition the graph with corner edges and construct submeshes:
```
partition = WeaklyConnectedComponents[VertexDelete[mg, corneredges]];
meshes =
MeshRegion[MeshCoordinates[bmesh], MeshCells[bmesh, #]] & /@
partition;
```
then project resulting meshes onto 2d:
```
projMesh[mesh_] :=
Block[{coords, p, m},
coords = MeshPrimitives[mesh, {2, 1}][[1]];
p = First[coords];
m = Select[
Orthogonalize[Transpose[Transpose[Rest[coords]] - p], Dot],
AnyTrue[#, # != 0 &] &];
m = AffineTransform[{m, -Dot[m, p]}];
MeshRegion[m[MeshCoordinates[mesh]], MeshCells[mesh, 2]]
]
projMesh /@ meshes
```
[](https://i.stack.imgur.com/kjNsD.jpg) | Another possible approach. Use `ConvexHullMesh` to get the 7 surfaces and collect the polygons.
```
Clear[bmesh, chmesh, bmeshNormal, chmeshNormal, indexs, regs, meshs];
bmesh = BoundaryMeshRegion[mesh3D];
chmesh = ConvexHullMesh[bmesh];
bmeshNormal = Region`Mesh`MeshCellNormals[bmesh, 2];
chmeshNormal = Region`Mesh`MeshCellNormals[chmesh, 2];
indexs =
Table[Position[bmeshNormal,
x_?VectorQ /;
EuclideanDistance[x, chmeshNormal[[i]]] < .001], {i,
Length@chmeshNormal}][[;; , ;; , 1]];
regs = Table[
RegionUnion@MeshPrimitives[bmesh, 2][[indexs[[i]]]], {i,
Length@chmeshNormal}];
meshs =
Table[reg =
TransformedRegion[regs[[i]],
If[Norm@Cross[chmeshNormal[[i]], {0, 0, 1}] > 0,
RotationTransform[{chmeshNormal[[i]], {0, 0, 1}}], Identity]];
MeshRegion[
MeshCoordinates[reg] /. {x_Real, y_Real, z_Real} :> {x, y},
MeshCells[reg, 2]], {i, Length@chmeshNormal}]
```
[](https://i.stack.imgur.com/L81QS.png) |
17,252,076 | I am developing a feature that needs a variant of read/write lock that can allow concurrent multiple writers.
Standard read/write lock allows either multiple readers or single writer to run concurrently. I need a variant that can allow multiple readers or multiple writers concurrently. So, it should never allow a reader and a writer concurrently. But, its okay to allow multiple writers at the same time or multiple readers at the same time.
I hope I was clear. I couldn't find any existing algorithm so far. I can think of couple of ways to do this using some queues and etc. But, I dont want to take a risk of doing it myself unless none exists.
Do you guys know of any existing scheme?
Thanks, | 2013/06/22 | [
"https://Stackoverflow.com/questions/17252076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/972209/"
] | The concept you are looking for is a Reentrant lock. You need to be able to try to acquire the lock and not get blocked if the lock is already taken (this is known as reentrant lock). There is a native implementation of a reentrant lock in java so I will illustrate this example in Java. (<http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/locks/ReentrantLock.html>).
Because when using tryLock() you don't get blocked if the lock is not available your writer/reader can proceed. However, you only want to release the lock when you're sure that no one is reading/writing anymore, so you will need to keep the count of readers and writers. You will either need to synchronize this counter or use a native atomicInteger that allows atomic increment/decrement. For this example I used atomic integer.
```
Class ReadAndWrite {
private ReentrantLock readLock;
private ReentrantLock writeLock;
private AtomicInteger readers;
private AtomicInteger writers;
private File file;
public void write() {
if (!writeLock.isLocked()) {
readLock.tryLock();
writers.incrementAndGet(); // Increment the number of current writers
// ***** Write your stuff *****
writers.decrementAndGet(); // Decrement the number of current writers
if (readLock.isHeldByCurrentThread()) {
while(writers != 0); // Wait until all writers are finished to release the lock
readLock.unlock();
}
} else {
writeLock.lock();
write();
}
}
public void read() {
if (!readLock.isLocked()) {
writeLock.tryLock();
readers.incrementAndGet();
// ***** read your stuff *****
readers.decrementAndGet(); // Decrement the number of current read
if (writeLock.isHeldByCurrentThread()) {
while(readers != 0); // Wait until all writers are finished to release the lock
writeLock.unlock();
}
} else {
readLock.lock();
read();
}
}
```
**What's happening here:** First you check if your lock is locked to know if you can perform the action you're going to perform. If it's locked it means you can't read or write so you use lock to put yourself in wait state and re-call the same action when the lock is freed again.
If it's not locked, then you lock the other action (if you're going to read you lock writes and vice-versa) using tryLock. tryLock doesn't block if it's already locked, so several writers can write at the same time and several readers can read at the same time. When the number of threads doing the same thing as you reaches 0 it means that whoever held the lock in the first place can now release it. The only inconvenience with this solution is that the thread that holds the lock will have to stay alive until everyone is finished to be able to release it. | If you are using pthreads, take a look at the synchronization approach in [this question](https://stackoverflow.com/questions/2136169/synchronization-among-2-threads-in-linux-pthreads).
You could use a similar approach with two variables `readerCount` and `writerCount` and a mutex.
In a reader thread you would lock the mutex and wait for `writerCount == 0`. If this is condition is met, you increment the `readerCount` by 1 and release the lock. Then you do the reading. When you are done, you lock the mutex again, decrement the `readerCount`, signal the condition change and release the lock.
The writer thread follows the same logic but waits for the condition `readerCount == 0` and increments/decrements `writerCount` instead. |
9,867,005 | I recently read an article about `c#-5` and new & nice asynchronous programming features . I see it works greate in windows application. The question came to me is if this feature can increase ASP.Net performance?
consider this two psudo code:
```
public T GetData()
{
var d = GetSomeData();
return d;
}
```
and
```
public async T GetData2()
{
var d = await GetSomeData();
return d;
}
```
Has in an ASP.Net appication that two codes difference?
thanks | 2012/03/26 | [
"https://Stackoverflow.com/questions/9867005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/648723/"
] | Define 'performance'.
Ultimately the application is going to be doing the same amount of work as it would have done synchronously, it's just that the calling thread in the asynchronous version will wait for the operation to complete on another, whereas in the synchronous model it's the same thread performing the task.
Ultimately in both cases the client will wait the same amount of time before seeing a response from the web server and therefore won't notice any difference in performance.
If the web request is being handled via an asynchronous handler, then, again, the response will still take the same amount of time to return - however, you can decrease the pressure on the thread pool, making the webserver itself more responsive in *accepting* requests - [see this other SO](https://stackoverflow.com/questions/9453560/why-use-async-requests-instead-of-using-a-larger-threadpool) for more details on that. | It would only increase performance if you needed to do multiple things, that can all be done without the need for any other information. Otherwise you may as well just do them in sequence.
In terms of your example, the answer is no. The page needs to wait for each one regardless. |
28,287,021 | I have read somewhere that MongoDB and Redis server shouldn't be executed in the same host because the way that Redis manages the memory damages MongoDb. This is before Docker.io. But now thing seems are pretty different or not? Is is convenient running Redis server and MongoDB on two different containers on the same host machine? | 2015/02/02 | [
"https://Stackoverflow.com/questions/28287021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1055637/"
] | Would this work for you?
**XSLT 1.0**
```
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/SHOP">
<xsl:copy>
<xsl:copy-of select="SHOPITEM[YEAR=2015]"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
``` | You can nest predicates - try `//SHOPITEM[YEAR[text() = 2015]]` |
49,325 | I have been growing B16F10 Mouse Melanoma cells. I need to extract the genomic DNA and do PCR to amplify a specific region. However, no matter what temperature or magnesium concentration I use, I have no luck.
I obtained mouse DNA from someone who was genotyping mice. I tested the PCR oligos with that DNA, and the reaction worked, so it's not an oligo problem.
The genomic DNA had poor 260/230, about 0.6. I thought the EDTA levels may have been high, so I did an isopropanol precipitation to clean it up. This made the 260/230 ratios about 2.1. But the PCR still didn't work.
What I had noticed during the precipitation however was that the DNA pellets were gray to black. I assume this is melanin, because the cells are melanoma cells, and turn black.
Could this melanin be a problem in PCR? | 2016/08/01 | [
"https://biology.stackexchange.com/questions/49325",
"https://biology.stackexchange.com",
"https://biology.stackexchange.com/users/4747/"
] | Melanin is a potent inhibitor of PCR - when you use B16 cells (or any other cell line that produces melanin) you have to purify your sample from it. Unfortunately a simple Phenol-Chloroform extraction or an ethanol precipation won't do the magic, since melanin co-precipitates with the nucleic acids.
I recommend following the following paper: "[CTAB–Urea Method Purifies RNA from Melanin for cDNA Microarray Analysis](http://onlinelibrary.wiley.com/doi/10.1111/j.1600-0749.2004.00155.x/abstract)".
The protocol derived from the paper can also be found [here](http://1000.fungalgenomes.org/home/protocols/removal-of-melanin/). | There are many suggestions how to avoid melanin-caused PCR inhibition. Some we have found helpfull (like using smaller amount of DNA sample + increasing number of cycles or adding BSA to PCR reaction), other (like trying different DNA isolation and PCR kits, purification columns etc.) are good only for profits of biotech companies. The solution is in fact very simple: using proper procedure for DNA isolation.
Rutinely we prepare DNA using high-salt lysis buffer (250 mM EDTA, pH 8,5, 1% SDS and 100 ug/ml proteaseK) and, after incubating at 50°C, single extraction step with phenol/chloroform, followed by precipitation with 1 volume of EtOH (not more, otherwise you precipitate EDTA). Under these conditions melanin remains with DNA.
For samples containing melanin we include one extraction step with phenol only before phenol/chloroform extraction. Melanin gets extracted into water/phenol interphase and falls throught phenol during centrifugation; this does not happen when you extract with phenol/chlofoform mixture. For efficient melanin extraction the high salt is important. If you need to eliminate melanin from ready-made DNA samples, add LiCl to 2M concentration and extract with phenol. |
253,361 | Resources in MGS 5 shared between offline and online mode and most of resources are stored online. However offline funds spent first and dip into negative values.
Andswer on [How does Mother Base staff morale work?](https://gaming.stackexchange.com/a/234256/20757) states that negative GMP values hurt morale.
Will morale decrease when offline resources negative but shared GMP value positive? | 2016/01/27 | [
"https://gaming.stackexchange.com/questions/253361",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/20757/"
] | The online resources can be viewed as a sort of "savings fund".
It seems that you are given a set amount that you can keep offline at a time and once this set amount drops to zero it will transfer more to you the next time you connect to the servers or hit checkpoints in or between missions.
So when your offline resources drop and there is no more online resources to feed in, that is when the staff moral will drop.
If your offline resources are negative but your online positive, some online resources should get transferred over. | If the servers need maintenance before you can get resources transferred you're boned unless you sell some stuff at mother base or whatever. |
48,772,621 | I have opencv-python installed and the .pyd file is added in the site-packages and the DLLs. The code works with images. When I want to read, show, write an image it works. But I get a warning that the functions' references cannot be found in **init**.py . Due to this, I can not use the auto-complete feature. Could someone help me out? I am using opencv 3.4.0 and python 3.6.4 in pycharm. I downloaded opencv via pip in the command prompt. | 2018/02/13 | [
"https://Stackoverflow.com/questions/48772621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7515891/"
] | The problem is caused by CV2 and how `__init__.py` does the imports. Just ignore the warnings the program will work all the same, or you can do an import with an alias like:
```py
import cv2.cv2 as cv2
```
If you have a warning on it press `Alt`+`Enter` to install and fix it. Now you will have the [code completion](https://www.jetbrains.com/help/pycharm/auto-completing-code.html) and no other warnings (about that) on the project. | I was using Python 3.10.2288.0 and OpenCV 1.6.0.66.
I resolved the issue by rolling back the OpenCV version to 4.5.5.62. |
18,889,494 | I'm looking to create a new contact form for asking an offer on a Magento Eshop.
This "**Ask for an Offer**" form will provide the option to a visitor to fill some fields and just sent an email exactly like the default **contact form** does.
The only difference with the default contact form is that the visitor doesn't have to be loged in to send an email.
So my approach so far is to Dublicate the file **contacts/form.phtml** to **contacts/askforanoffer.phtml**
and ofcourse I created the new **xml** in folder **layout/askforanoffer.xml**
*The question is this.*
**Where should I change to code in order that the user not to has to be loged in in order to send an email with this ask for an offer form ?** | 2013/09/19 | [
"https://Stackoverflow.com/questions/18889494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2567702/"
] | You have to create separate module for this. I have also create and sharing code here. Form submitting is by ajax. May be I have missed something to remove or renaming. try to correct it.
app\etc\modules\namespace\_modulename.xml
```
<Namespace_Modulename>
<active>true</active>
<codePool>local</codePool>
</Namespace_Modulename>
```
app\code\local\Namespace\Modulename\Helper\Data.php
```
<?php class Namespace_Modulename_Helper_Data extends Mage_Core_Helper_Abstract
{
}
?>
```
app\code\local\Namespace\Modulename\etc\config.xml
```
<?xml version="1.0"?>
<config>
<modules>
<Namespace_Modulename>
<version>0.0.01</version>
</Namespace_Modulename>
</modules>
<frontend>
<routers>
<contacts>
<args>
<modules>
<Namespace_Modulename before="Mage_Contacts">Namespace_Modulename</Namespace_Modulename>
</modules>
</args>
</contacts>
</routers>
</frontend>
<global>
<helpers>
<Modulename>
<class>Namespace_Modulename_Helper</class>
</Modulename>
</helpers>
<template>
<email>
<havequestion_email_email_template translate="label" module="contacts">
<label>Have a Question Form</label>
<file>havequestion_form.html</file>
<type>text</type>
</havequestion_email_email_template>
</email>
</template>
</global>
</config>
```
app\code\local\Namespace\Modulename\controller\IndexController.php
```
public function havequestionpostAction()
{
$template_path = 'havequestion_email_email_template';
//$post = $this->getRequest()->getPost();
$post = array (
'name' => $this->getRequest()->getParam('name'),
'email' => $this->getRequest()->getParam('email'),
'comment' => $this->getRequest()->getParam('comment')
);
if ( $post ) {
$translate = Mage::getSingleton('core/translate');
/* @var $translate Mage_Core_Model_Translate */
$translate->setTranslateInline(false);
try {
$postObject = new Varien_Object();
$postObject->setData($post);
$error = false;
if (!Zend_Validate::is(trim($post['name']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['comment']) , 'NotEmpty')) {
$error = true;
}
if (!Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
$error = true;
}
if (Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
$error = true;
}
if ($error) {
throw new Exception();
}
$mailTemplate = Mage::getModel('core/email_template');
/* @var $mailTemplate Mage_Core_Model_Email_Template */
$senderDetail = Mage::getStoreConfig('trans_email/ident_'.Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER));
$senderDetail['name'] = $post['name'];
$mailTemplate->setDesignConfig(array('area' => 'frontend'))
->setReplyTo($post['email'])
->sendTransactional(
$template_path,
$senderDetail,
//Mage::getStoreConfig(self::XML_PATH_EMAIL_SENDER),
Mage::getStoreConfig(self::XML_PATH_EMAIL_RECIPIENT),
null,
array('data' => $postObject)
);
if (!$mailTemplate->getSentSuccess()) {
throw new Exception();
}
$translate->setTranslateInline(true);
//Mage::getSingleton('customer/session')->addSuccess(Mage::helper('contacts')->__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.'));
//$this->_redirectUrl($post['currentpage']);
echo 'SUCCESS';
return;
} catch (Exception $e) {
$translate->setTranslateInline(true);
//Mage::getSingleton('customer/session')->addError(Mage::helper('contacts')->__('Unable to submit your request. Please, try again later'));
//$this->_redirectUrl($post['currentpage']);
echo '<div class="error-msg">Unable to submit your request. Please, try again later.</div>';
return;
}
} else {
echo '<div class="error-msg">Unable to submit your request. Please, try again later.</div>';
//$this->_redirectUrl($post['currentpage']);
return;
}
}
}
```
app\design\frontend\default\YOUR\_TEMPLATE\_PATH\template\contacts\havequestionform.phtml
```
<div class="form-add">
<form action="<?php echo $this->getUrl('') ?>contacts/index/havequestionpost/" id="havequestionForm" method="post">
<div class="question-ajax-msg"></div>
<ul class="form-list">
<li class="fields">
<div class="field">
<label for="name" class="required"><em>*</em><?php echo Mage::helper('contacts')->__('Name') ?></label>
<div class="input-box">
<input name="name" id="name" title="<?php echo Mage::helper('contacts')->__('Name') ?>" value="<?php echo $this->htmlEscape($this->helper('contacts')->getUserName()) ?>" class="input-text required-entry" type="text" />
</div>
</div>
<div class="field">
<label for="email" class="required"><em>*</em><?php echo Mage::helper('contacts')->__('Email') ?></label>
<div class="input-box">
<input name="email" id="email" title="<?php echo Mage::helper('contacts')->__('Email') ?>" value="<?php echo $this->htmlEscape($this->helper('contacts')->getUserEmail()) ?>" class="input-text required-entry validate-email" type="text" />
</div>
</div>
</li>
<li class="wide">
<label for="comment" class="required"><em>*</em><?php echo Mage::helper('contacts')->__('Comment') ?></label>
<div class="input-box">
<textarea name="comment" id="comment" title="<?php echo Mage::helper('contacts')->__('Comment') ?>" class="required-entry input-text" cols="5" rows="3"></textarea>
</div>
</li>
</ul>
<div class="">
<p class="required" style="text-align:left"><?php echo Mage::helper('contacts')->__('* Required Fields') ?></p>
<button type="submit" title="<?php echo Mage::helper('contacts')->__('Submit') ?>" class="button"><span><span><?php echo Mage::helper('contacts')->__('Submit') ?></span></span></button>
<span class="question-ajax-loading"> </span>
</div>
</form>
<script type="text/javascript">
//<![CDATA[
var havequestionForm = new VarienForm('havequestionForm', true);
// submit have a question by ajax
jQuery('#havequestionForm').submit(function (e){
e.preventDefault();
jQuery(".question-ajax-loading").css('display','block');
var name = jQuery("#name").val();
var email = jQuery("#email").val();
var comment = jQuery("#comment").val();
var hideit = jQuery("#hideit").val();
var prosku = jQuery("#prosku").val();
var prostyle = jQuery("#prostyle").val();
var procolor = jQuery("#procolor").val();
var currentpage = jQuery("#currentpage").val();
var dataString = 'name='+ name + '&email=' + email + '&comment=' + comment + '&hideit=' + hideit + '&prosku=' + prosku + '&prostyle=' + prostyle + '&procolor=' + procolor + '¤tpage=' + currentpage;
url = jQuery('#havequestionForm').attr('action');
jQuery.ajax( {
url : url,
Type : "POST",
data: dataString,
success: function(data) {
jQuery(".question-ajax-msg").css('display','block');
if(data == 'SUCCESS'){
var successMsg = '<div class="success-msg">Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.</div>';
jQuery(".question-ajax-msg").html(successMsg);
jQuery("#comment").val('');
}
else {
jQuery(".question-ajax-msg").html(data);
jQuery("#comment").val('');
}
jQuery(".question-ajax-loading").css('display','none');
jQuery('.question-ajax-msg').delay(5000).fadeOut('slow');
}
});
return false;
});
//]]>
</script>
</div>
``` | you can use below documentation
Custom Module with Custom Database Table
<http://www.magentocommerce.com/wiki/5_-_modules_and_development/0_-_module_development_in_magento/custom_module_with_custom_database_table>
Front-End Editor Extension for Magento Commerce
<http://www.youtube.com/watch?v=ALgdsMCVuH4>
please see above the URL.
hope this will sure help you, |
12,571,852 | I have a textbox, where i want the written text to be added to a UIImage.
How can i draw NSString to a UIImage?
I´ve searched, and found lots of examples, but non of them works. Xcode just gives me lots of errors.
Simply put, i want to draw a NSString to a UIimage. The UIImage should be the same size as a predefined UIImageView, and be placed in center.
Any ideas? | 2012/09/24 | [
"https://Stackoverflow.com/questions/12571852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1686319/"
] | UIImage is not a subview of UIView, so you cant add a subview to it. Also NSString is not a subview of UIView. If you want to show things on the screen, they should inherit from UIView.
So try this:
Create a UIImageView - set its image property to be your UIImage instance.
Create a UILabel - set its text property to your NSString.
Add the UILabel as a subview of your UIImageView.
and finally add your UIImageView to your current view controllers view. | Emm, here is some thoughts.
I think that one simple way is like this :
1. Put aUIImageView on aView;
2. Add aUITextView on aView;
3. Get ScreenShot from aView;
This may works fine.
Also, this may come with a problem that screenshot may be not clear.
Then, After step1 and step2, we may get new image by UIGraphics.
(With here, we already know position where text should be on image and this should be ok.)
PS: Some image may not have some attribution like CGImage and CGImage is needed for this. So, transform it. |
9,094 | I have a requirment to have users be able to select button colors, I want that according to the background color they select, an appropriate, contrasted button text color will be determined automatically.
for that - I need some sort of formula, and I was wondering if anyone knows what such formula might be, I looked around, but haven't found anything substantial.
Here is an example of a visible text on button that I want to achieve:
 | 2012/08/22 | [
"https://graphicdesign.stackexchange.com/questions/9094",
"https://graphicdesign.stackexchange.com",
"https://graphicdesign.stackexchange.com/users/2282/"
] | OK, I finally got around to looking at the [example image](https://i.stack.imgur.com/c4m02.png), and the trick is pretty simple: gamma correction.
As others have noted, the image is composed of two interleaved pictures: out of every 2 × 2 pixel block, three pixels have RGB values in the range 0 to 210, and show the "red tabby kitten on bed" image, while one pixel has RGB values in the range 214 to 255 and shows a very heavily lightened version of the "batman cat" image.
Here's a small section of the image, scaled up by a factor of 8, with no gamma correction applied. This is what you'll see if you open the image in a program that *doesn't* understand PNG gamma correction and zoom in:

As you can see, the light pixels (which contain the "batman cat" image) just pretty much look white. At normal magnification, they blend in with the other image, which has much higher contrast, and just make it look somewhat lighter.
*However*, the PNG image also contains a `gAMA` chunk, which specifies a file gamma value of 0.023. This is an *extremely* small gamma value; more typical values would be between 1.0 and 0.45. When opened in a program that supports PNG gamma correction, this causes the image to be darkened so much that the "kitten on bed" image literally becomes invisible — all its colors are mapped to black — while the colors of the "batman cat" image are mapped to more ordinary values.
For example, here's the same zoomed-in section of the image after gamma correction:

So, to conclude, **the appearance of this image does *not* depend on the color of the background.** Rather, it depends on whether the program you use to view it supports PNG gamma correction (and is willing to apply such an extreme gamma value) or not.
By the way, the gamma correction value used in the image seems a little *too* extreme: at least on my screen, the "batman cat" image shows up a lot more nicely if you double the gamma. | The image is two images interlaced. Interlacing is, very basically, where two images are displayed simultaneously by showing a single line (or pixel) of each one in an alternating pattern.
Usually one finds this in TV and video broadcasting since the frame rates mask the interlacing effect.
If one were to take this image and use a deinterlace filter ("even fields"), the batman image would be gone. Also, the batman cat image becomes "primary" when zoomed to 50% or when using the scale feature of photoshop, probably becasue of interpolation/resampling. Curiously, when you commit the scaling change and photoshop re-renders at full quality (it uses a fast render method when manipulating transforms), the other cat becomes "primary" again. The same scaling to 25% eliminates the batman cat as well.
As far as "why" the display changes depending on software, that is most probably a function of the methods used by various software for rendering images. I checked the header for the file and it looks to be properly formed, but there may be some trick or hack implemented in one of the optional sections (it has 3 optional chunks IIRC) which exploits a rendering bug. Personally, I think it is just the method used interpolate based on the rescaling stuff I mentioned above. Also, there *is* a gamma section in the header and on my display the image is REALLY dark, so it may just exploit the fact that some pixels are lighter and the rest blend in with a dark background. |
17,367,192 | I have this snippet of code and want to know if exist way to make it much more readable?
My code:
```
public String getMonthName()
{
if (1 == this.monthNumber) {
monthName = "January";
} else if (2 == this.monthNumber) {
monthName = "February";
} else if (3 == this.monthNumber) {
monthName = "March";
} else if (4 == this.monthNumber) {
monthName = "April";
} else if (5 == this.monthNumber) {
monthName = "May";
} else if (6 == this.monthNumber) {
monthName = "June";
} else if (7 == this.monthNumber) {
monthName = "July";
} else if (8 == this.monthNumber) {
monthName = "August";
} else if (9 == this.monthNumber) {
monthName = "September";
} else if (10 == this.monthNumber) {
monthName = "Oktober";
} else if (11 == this.monthNumber) {
monthName = "November";
} else if (12 == this.monthNumber) {
monthName = "December";
}
return monthName;
}
/**
* Gets the number of days in this month
* @return the number of days in this month in a non-leap year
*/
public int getNumberOfDays()
{
int numberOfDays;
if (monthNumber == 1 || monthNumber == 3 || monthNumber == 5 || monthNumber == 7 || monthNumber == 9 || monthNumber == 11) {
numberOfDays = 31;
} else if (monthNumber == 4 || monthNumber == 6 || monthNumber == 8 || monthNumber == 10 || monthNumber == 12) {
numberOfDays = 30;
} else {
numberOfDays = 28;
}
return numberOfDays;
}
}
```
How better way to refactoring code? Make it much more readable. | 2013/06/28 | [
"https://Stackoverflow.com/questions/17367192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1498427/"
] | You should use the `Calendar` class, it was provided to save you from all this extra branching. You also won't have to determine if it is a Leap Year, the API will take of that for you.
```
final String[] months = new String[]{ "January", "February", ... };
public String getMonthName() {
return months[Calendar.getInstance().get(Calendar.MONTH)];
}
public int getNumberOfDays() {
return Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH);
}
``` | ```
String[] months = String[] {"Jan", "Feb", ... , "Dec"};
String monthName = months[monthNumber - 1];
``` |
10,186 | I'm thinking about the basic types of convergence for sequences of functions: convergence in measure, almost uniform convergence, convergence in Lp and point wise almost everywhere convergence. I'm looking for examples of sequences of functions that converge in one or more of these ways, but fail for others. I keep seeing the same examples over and over and I'd like to think about some new ones. Here are the examples I've seen:
$f\_n=\chi\_{[n, n+1]}$
$f\_n=\chi\_{A\_{n}}$ where $A\_1 = [0,1]$, $A\_2 = [0,1/2]$, $A\_3 = [1/2,1]$, $A\_4 = [0,1/4]$, $A\_5 = [1/4,1/2]$, $A\_6 = [1/2,3/4]$, $A\_7 = [3/4,1]$, $A\_8 = [0,1/8]$ ...
$f\_n= n\chi\_{[1/n,2/n]}$
These are a great set of examples since they let you give a counterexample for the relations between the types of convergence when needed, but I would like to know of some more.
(EDIT: I added a bit to the 2nd example to make it more clear.) | 2009/12/30 | [
"https://mathoverflow.net/questions/10186",
"https://mathoverflow.net",
"https://mathoverflow.net/users/2907/"
] | When it comes to complex analytic functions on open subsets of $\mathbb{C}$, it is hard to come up with examples of pointwise convergent sequences that do not converge uniformly on compact sets. That is partly because it doesn't take much for a family of analytic functions to be normal. There is much more to be said about the matter, and for an exposition including examples I recommend [this survey](http://www.jstor.org/pss/2975578) by Davidson.
[Edit: This post would be better if it included a description of such an example. I may add one when I have more time.] | On $[0,1]$: $ f\_n = a\_n\chi\_{[\alpha n,\alpha n + \varepsilon n^{-2}]\ {\rm mod}\ 1 } $ with $\alpha$ irrational, and $a\_n = 1 $ or $ a\_n = n^2 $.
This is, of course, also similar ...
Transferred from my comments below, and corrected (TeX was not shown, so I did not see that some of the code did not work):
Well, it was rather late (in my timezone). So I only typed in the $f\_n$.
$ \int |f\_n -0| $ is either $ = \varepsilon n^{-2} \to 0 $ or $ = \varepsilon \to \varepsilon $, respectively.
$ \int \bigcup\_{n\ge N} \lbrace x | \chi\_{[\alpha n,\alpha n + \varepsilon n^{-2}]\ {\rm mod}\ 1 } \ne 0 \rbrace \le \sum\_{n\ge N}\varepsilon n^{-2} \to 0 $,
i.e., $ f\_n \to 0 $ almost everywhere. |
12,878,012 | I have a singleton class:
```
public class Singleton {
private static Singleton istance = null;
private Singleton() {}
public synchronized static Singleton getSingleton() {
if (istance == null)
istance = new Singleton();
return istance;
}
public void work(){
for(int i=0; i<10000; i++){
Log.d("-----------", ""+i);
}
}
}
```
And multiple Threads are calling the work() function:
```
public class Main {
public static void main(String[] args) {
new Thread (new Runnable(){
public void run(){
Singleton s = Singleton.getSingleton();
s.work();}
}).start();
System.out.println("main thread");
new Thread(new Runnable() {
public void run() {
Singleton s = Singleton.getSingleton();
s.work();
}
}).start();
}
}
```
I noticed the two Threads are running concurrently, as if two work functions were instantiated at the same time.
I want the last thread to be run in place of the previous thread, rather then concurrently. Is it possible in java to make the second call override the memory space of the first call? | 2012/10/13 | [
"https://Stackoverflow.com/questions/12878012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1245466/"
] | As @amit stated in a comment your `getSingleton()` method should be `synchronized`. The reason for this is that it is possible for multiple threads to ask for an instance at the same time and the first thread will still be initializing the object and the reference will be null when the next thread checks. This will result in two instances being created.
```
public static synchronized Singleton getSingleton() {
if (istance == null)
istance = new Singleton();
return istance;
}
```
Marking your method as `synchronized` will cause it to block and only allow one thread at a time to call it. This should solve your problem. | You can use Locks around the shared resources. Use the `Reentrant` class. It prevents race conditions for multiple threads. |
111,231 | I think my question says it all.
I want to do a full server backup of the entire machine (Windows Server 2008) using the OS's built in "Windows Server Backup". My server runs the SQL for Sharepoint and is also the domain controller.
Do I need to stop Sharepoint Services first? | 2014/08/07 | [
"https://sharepoint.stackexchange.com/questions/111231",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/7452/"
] | Have you tried:
```
$("select [title='Option']".on('change', function(){
alert("yes");
});
``` | Try placing your code in "content place holder main" in editform.aspx |
19,010 | Were the Pharisees being sarcastic in John 7:52, when they claimed that "no prophet ever came out of Galilee"? It is written that Jonah came from Gath-hepher, in Galilee (2 Kings 14:25). | 2013/09/12 | [
"https://christianity.stackexchange.com/questions/19010",
"https://christianity.stackexchange.com",
"https://christianity.stackexchange.com/users/5525/"
] | Many commentators have enjoyed pointing out the Pharisees' mistake, which is just one of several errors they make in this chapter.
A "pure" sarcasm would mean that the Pharisees considered Galilee to be *the* place where prophets came from - a bit like associating Washington, DC with politicians. But the context is their rejection of Jesus (known to them as a Galilean) as a prophet, which makes that reading a bit tricky. It is more likely that they are being rude or sarcastic, but at the same time, incorrect to dismiss Galilee as a prophet-free zone.
[Thomas Aquinas](http://en.wikipedia.org/wiki/Thomas_Aquinas) in the [*Catena Aurea*](http://dhspriory.org/thomas/CAJohn.htm#7) collated some earlier discussion on this passage. This includes [John Chrysostom](http://en.wikipedia.org/wiki/John_Chrysostom) ([Homily 52 on the Gospel of John](http://www.newadvent.org/fathers/240152.htm)) characterizing the tone of the Pharisees as "rude" and "insulting" (*rudius*, *iniuriose*), which would cover sarcasm; and on the other hand [Alcuin of York](http://en.wikipedia.org/wiki/Alcuin)'s [*Commentary on the Gospel of John*](http://www.e-codices.unifr.ch/en/list/one/csg/0258), where the emphasis is on their ignorance. If it is sarcasm, then it is still misaimed sarcasm, because the Pharisees are incorrect.
But their mistake is significant. The story of Jonah prefigures that of Jesus in several important ways, and so it is interesting that the two prophets are, in a sense, rejected together.
N. T. Wright says of this verse:
>
> The Pharisees further show their ignorance of Scripture in that both the prophets Jonah and Hosea came from Galilee. And when John has them say that no prophet "rises up" or "arises" from Galilee, the word he uses is almost always used elsewhere in the book to refer to the resurrection. Jonah was proverbial for coming, so it seemed, "back from the dead" after three days in the belly of the fish; and Hosea contains the prophecy that God will "raise us up on the third day" (Hosea 6:2).1
>
>
>
The Greek verb in question is ἐγείρεται (ἐγείρω), which originally meant "to wake up" or "to arouse", and was later applied to rising from a sick-bed or death-bed, as well as from sleep. It can also mean rousing someone to activity from a previous state of torpor. The other instances in John's gospel are as follows:
* Jesus's resurrection / metaphor of raising the Temple: 2:19, 2:20, 2:22, 21:14
* Healing at the pool of Bethesda: 5:8
* Raising the dead in general: 5:21; and Lazarus specifically: 12:1, 12:9, 12:17
* Standing up / being called to action: 11:29, 13:4, 14:31
The "resurrection" sense is also strongly present elsewhere in the New Testament. So we could say that John's account has a certain level of *irony*, even if the Pharisees are not themselves being sarcastic.
Some versions of John 7:52 have the Pharisees talking about *the* prophet, rather than *a* prophet. They would then be arguing about whether *the* Messiah ought to be from Galilee, as opposed to whether prophets in general could come from there. If this is the reading then the Jonah question does not arise - but instead, we have to ask about the Pharisees' knowledge or interpretation of the Messianic prophecy in Isaiah 9 (or in the Hebrew, starting at 8:23). Here, "Galilee" is to be made glorious by a son who is to be called "Wonderful, Counsellor, the Mighty God, the Everlasting Father, the Prince of Peace". The application to Jesus hinges on him being "from" Nazareth as well as Bethlehem, and of the line of David - facts which were not generally known (John 7:42). As before, the tone of the argument could very well be sarcastic, with the Pharisees being wrong, but this time for a different reason.
1. N. T. Wright. *John: 26 studies for individuals and groups* (InterVarsity Press, 2009). Chapter 10, *Disputes about Jesus*, p. 60. | Their question is not just about whether a prophet *can* come from Galilee, but verse 42 gives more info about their reason for doubting Galilee as the source of the 'Christ'. The Christ should come from David's line and from Bethlehem (prophecy from [Micah 5:2](https://www.biblegateway.com/passage/?search=Micah%205%3A2&version=NRSV)). Herod ordered the murder of all the boys in Bethlehem, so there would not be any men from Bethlehem around Jesus' age. Even though Herod died before Mary & Joseph returned from Egypt, Joseph still feared Herod's son, who was then ruling in Judea, and God warned Joseph to go to Galilee instead ([Matthew 2:19-23](https://www.biblegateway.com/passage/?search=Matthew%202%3A19-23&version=NRSV)). Joseph and Mary probably didn't broadcast that Jesus was really from Bethlehem because of their fear (and because of God's warnings). |
9,949,302 | I have programmed a UIImageView that allows me to draw inside of it. It therefore tracks the users touches and records it. When used in a window it works great.
However, I have then added it as a subView of a UIScrollView which resides in a View Controller. When I try and use it now, the touch gestures inside of the UIImageView simply scroll the whole view rather than draw inside the UIImageView.
How do I refer gestures made to the UIScrollView which are also inside of the UIImageView to the UIImageView.
I hope that makes sense
Best regards
EDIT: I have set all the following properties: `canCancelContentTouches`, `exclusiveTouch` and `delaysContentTouches` to NO.
Now, when I touch inside the UIImageView it doesn't scroll but still won't call the methods: `touchesBegan:withEvent:`, `touchesMoved:withEvent:` or `touchesEnded:withEvent:` which each reside in the ViewController | 2012/03/30 | [
"https://Stackoverflow.com/questions/9949302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190768/"
] | Set the `exclusiveTouch` property of the UIImageView to `YES` (This means that, when the UIImageView is touched, that touch will not have effects on any other views) | How do you want the app to decide whether a touch is supposed to scroll the scroll view or draw in the image view?
Let's say you want one finger to draw and two fingers to scroll. If you're targetting iOS 5.0, it's easy:
```
self.scrollView.panGestureRecognizer.minimumNumberOfTouches = 2;
```
If you're targetting an earlier iOS, you can't use the `panGestureRecognizer` property. You have to dig through the scroll view's `gestureRecognizers` property to find the right recognizer. [Check out my answer here](https://stackoverflow.com/a/9318919/77567) for example code. |
3,137,674 | This is a followup to:
[MySQL - Is it possible to get all sub-items in a hierarchy?](https://stackoverflow.com/questions/3073614/mysql-is-it-possible-to-get-all-sub-items-in-a-hierarchy)
I have an arbitrary-depth **adjacency list model** table (I am at the point that I *can* convert it into a **nested set model**.
I read the MySQL data on how to use a nested set model, though it seemed to get increasingly complex and very complex to do basic functions such as inserting, updating and deleting.
Another blog showing how to use a trigger system with the adjacency list model to keep a table of ancestors that relates each object to its ancestors.
---
Right now I need to be able to return a list of all children of a given node, to change or delete them. This hierarchical structure won't be changing all the time once created, but there will be a mass amount of the hierarchical structures.
The three methods I see are:
1. **Created a Stored Procedure** which would do a recursive query that returns all children.
2. **Convert to Nested Set Model** which would require to get into the complexities and possibly create a stored procedure to add, edit and delete in that.
3. **Create the Ancestor Table** described above on insert/delete triggers to handle all of the data.
If there are other methods I'm not exploring, please let me know and I'll update this list. | 2010/06/29 | [
"https://Stackoverflow.com/questions/3137674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/344769/"
] | I would always go with the **Nested Set** for shear simplicity and convienience. I always suggest [this article](http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/). It shows excelent the queries that are needed for the work with such hierachrchical data. The only disadvantage I see here is that it can get slower with inserting/updateing new records when the hierachry reached a certain level of complexity, but the reading is faster than many other solutions I hae seen.
Just to give you an example from the article above:
```
SELECT t1.name AS lev1, t2.name as lev2, t3.name as lev3, t4.name as lev4
FROM category AS t1
LEFT JOIN category AS t2 ON t2.parent = t1.category_id
LEFT JOIN category AS t3 ON t3.parent = t2.category_id
LEFT JOIN category AS t4 ON t4.parent = t3.category_id
WHERE t1.name = 'ELECTRONICS';
+-------------+----------------------+--------------+-------+
| lev1 | lev2 | lev3 | lev4 |
+-------------+----------------------+--------------+-------+
| ELECTRONICS | TELEVISIONS | TUBE | NULL |
| ELECTRONICS | TELEVISIONS | LCD | NULL |
| ELECTRONICS | TELEVISIONS | PLASMA | NULL |
| ELECTRONICS | PORTABLE ELECTRONICS | MP3 PLAYERS | FLASH |
| ELECTRONICS | PORTABLE ELECTRONICS | CD PLAYERS | NULL |
| ELECTRONICS | PORTABLE ELECTRONICS | 2 WAY RADIOS | NULL |
+-------------+----------------------+--------------+-------+
6 rows in set (0.00 sec)
```
SQL wise, I don't think it can get any prettier and simpler ;)
I have no idea to the **Stored Procedure** way. But since it involces recursion (in your case), I don't know if it will be fast with many levels in the hierarchy. I assume you can give it a try. | I once had to store a complex hierarchical arbitrary-depth bill-of-material system in a SQL-like database manager that wasn't really up to the task, and it ended up forcing messy and tricky indicies, data definitions, queries, etc. After restarting from scratch, using the db manager to provide only an API for record reads and writes on simple indexed keys, and doing all of the actual input/manipulation/reporting in external code, the final result was quicker to implement, easier to understand, and simpler to maintain and enhance. The most complex query needed was essentially SELECT A FROM B.
So, instead of embedding logic and operations inside the restrictions of MySQL, consider banging out code to do what you want, and relying on MySQL only for the lowest-level gets/puts. |
31,005,242 | I have this code
```js
$('#fancybox-wrap .caption').appendTo('#fancybox-outer #fancybox-content');
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="fancybox-wrap">
<div id="fancybox-outer">
<div id="fancybox-content"></div>
</div>
<p class="caption">Hello world</p>
</div>
```
I want to put `.caption` into `#fancybox-content`.
I try to append this p but it does not work
Thanks for the help ! | 2015/06/23 | [
"https://Stackoverflow.com/questions/31005242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4875059/"
] | By writing it in [TryRoslyn](http://goo.gl/dmuV2i) it becomes quite evident that there is a difference based on where you put the property in the interface:
Given:
```
interface ISub1A: IBaseA
{
int Prop3 { get; set; }
}
interface IBaseA
{
int Prop1 { get; set; }
string Prop2 { get; set; }
}
interface ISub1B: IBaseB
{
int Prop3 { get; set; }
string Prop2 { get; set; }
}
interface IBaseB
{
int Prop1 { get; set; }
}
```
and
```
ISub1A a = null;
a.Prop2 = "Hello";
ISub1B b = null;
b.Prop2 = "Hello";
```
(note that in both cases I'm using the `ISub1*` interface in C# code)
The generated IL code is:
```
IL_0001: ldstr "Hello"
IL_0006: callvirt instance void IBaseA::set_Prop2(string)
IL_000b: ldnull
IL_000c: ldstr "Hello"
IL_0011: callvirt instance void ISub1B::set_Prop2(string)
```
so the IL code "correctly" resolves to the interface where the property is really defined. | First, you should hide `ISub2.Prop2` by [implementing it explicitly](https://msdn.microsoft.com/en-us/library/ms173157.aspx). Then, depending on why `ISub2` should not contain `Prop2`, you should either deprecate that implementation using the [ObsoleteAttribute](https://msdn.microsoft.com/en-us/library/system.obsoleteattribute(v=vs.110).aspx) attribute or throw an [InvalidOperationException](https://msdn.microsoft.com/en-us/library/system.invalidoperationexception(v=vs.110).aspx) from both accessors. |
34,627,561 | I am adding posts in database and against each post there will be an image. For example there is a product table and against each product I've its id, quanitity and price.
Now I store image like this in
```
if ( isset($_POST["uploadimg"]) ) {
$file_name =$_FILES["image"]["name"];
$file_type=$_FILES["image"]["type"];
$file_size=$_FILES["image"]["size"];
$tmp_name=$_FILES["image"]["tmp_name"];
if ( $file_name ) {
if ( move_uploaded_file($tmp_name,"images/$file_name") ) {
// something here
}
}
}
```
fetch it like this
```
$folder = "images";
if ( is_dir($folder) ) {
if ( $handle= opendir($folder) ) {
while (($file= readdir($handle))!=FALSE) {
if($file==='.' || $file==='..') continue;
echo '<img src="images/'.$file.'" width="100" height="100" >';
}
closedir($handle);
}
}
```
Now product image goes to folder and details about this product go to db, using insert query.
My question is that how do i relate this image with its product details while fetching products?
I mean how do i store reference to this image so that I may know which image is for which product details. | 2016/01/06 | [
"https://Stackoverflow.com/questions/34627561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1760937/"
] | Remove all your subviews before adding a new one as below
```
NSArray *viewsToRemove = [self.view subviews];
for (UIView *v in viewsToRemove) {
[v removeFromSuperview];
}
```
Above code should add before this below line,
```
[self.viewReview addSubview:titleLabel];
[self.viewReview addSubview:reviewLabel];
``` | ok - first create the arrays for your titles as members of your view controller
```
NSMutableArray *titleLabels = [NSMutableArray array];
NSMutableArray *reviewLabels = [NSMutableArray array];
```
and then update your function to look more like this
```
for(int i = 0;i <= titleArray.count-1;i = i + 1){
_noReview.hidden = YES;
UILabel * titleLabel;
UILabel * reviewLabel;
if (i >= [titleLabels count]) {
titleLabel = [[UILabel alloc] initWithFrame: CGRectMake(i*172, 0, 100, 50)];
reviewLabel = [[UILabel alloc] initWithFrame:CGRectMake(i * 172 , 30, 200, 50)];
[titleLabels addObject:titleLabel];
[reviewLabels addObject:reviewLabel];
}
else {
titleLabel = [titleLabels objectAtIndex:i];
reviewLabels = [reviewLabels objectAtIndex:i];
}
// do your other stuff here
```
each time you call the function, if there are more titles returned than you have labels for, it will create new instances, and add them to your array. As you step through the array, it will re-use the instances. |
7,648,515 | I'm trying to consume a WCF 4.0 service in my application. I built, tested, and deployed the service from the ground up. The service works in the WCF test client and can be consumed in any other test project I built. The problem is this one particular application... the only one that matters as it's the reason I built the service.
When I build the application after referencing the service I get an error. The error is "The type name 'AAA' does not exist in the type 'YYY.YYY' ".
The project consuming the service is named 'YYY.Web' and is in the 'YYY' namespace.
The service was initially created in the 'YYY.ReportingService' namespace. It has been changed to a different namespace once this problem started. Is now in the 'MMM' namespace.
I added a using directive 'YYY.Service1'. I also tried aliasing the using directive (using test = YYY.Service1)
To make sure something wasn't messed up with my service and its namespaces, I built a new service with a single method. It takes a string parameter and returns "Hello, " and whatever string is passed. This services also works in the WCF test client and the couple of test projects I created. This service is in the SimpleTestService namespace, BasicService class, with a methiod named GetGreeting. Naming was done intentionally to avoid any possible naming collisions. The error still occurs with this new service.
Any thoughts on this? Thanks! | 2011/10/04 | [
"https://Stackoverflow.com/questions/7648515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/978467/"
] | This one took me a while. Turned out, that `"The type name 'AAA' does not exist in the type 'YYY.YYY' "` was caused by the YYY.YYY - my consuming class sharing name with its containing namespace.
Solution: rename the consuming class to something that is not equal to the full name of its namespace, i.e. `YYY.XXX`. | I have another issue. Imagine two projects with different namespaces and following classes
Project 1
```
[DataContract(Namespace="SomeNamespace")]
public class A
{
[DataMember]
public class B { get; set; }
}
```
Project 2
```
// Here no DataContract attribute
public class B
{
//...
}
```
In this case you'll get same error as above. Hopefully this will help someone. |
43,450 | I've playing around with the google maps api and am puzzled at the following behavior. If I use `mPoint` as the LatLng for my marker, the marker is rendered on a different point on the map as opposed to putting the same value directly into the properties of the marker. Code chunk is as follows:
```
var mPoint = [new google.maps.LatLng(38.991300,-76.936165)];
// var GPoint = new google.maps.Marker({map:map,position:AVPoint});
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(38.991300,-76.936165),
//position: new google.maps.LatLng(mPoint),
draggable: true
});
```
Why would this happen? | 2012/12/07 | [
"https://gis.stackexchange.com/questions/43450",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/8964/"
] | In your code:
```
var mPoint = [new google.maps.LatLng(38.991300,-76.936165)];
```
You define an array as mPoint. And it absolutely makes no sense to pass this array to the marker object that you are creating since the position attribute expects a latlng object and not an array as argument.
In your case `var marker = new google.maps.Marker({map: map,position: mPoint[0], draggable: true});` would be the solution. | Google Maps Marker Example (with drop/drag animation)
reference: <https://developers.google.com/maps/documentation/javascript/examples/>
```
<script>
var mPoint = new google.maps.LatLng(38.991300,-76.936165);
var marker;
var map;
function initialize() {
var mapOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: mPoint
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
marker = new google.maps.Marker({
map:map,
draggable:true,
animation: google.maps.Animation.DROP,
position: mPoint
});
google.maps.event.addListener(marker, 'click', toggleBounce);
}
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
</script>
```
Source:
<https://google-developers.appspot.com/maps/documentation/javascript/examples/marker-animations> |
3,465,465 | In Java, the [`throws`](http://download.oracle.com/javase/tutorial/essential/exceptions/declaring.html) keyword allows for a method to declare that it will not handle an exception on its own, but rather throw it to the calling method.
Is there a similar keyword/attribute in C#?
If there is no equivalent, how can you accomplish the same (or a similar) effect? | 2010/08/12 | [
"https://Stackoverflow.com/questions/3465465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/385387/"
] | The op is asking about the **C# equivalent of Java's [`throws` clause](http://java.sun.com/docs/books/jls/third_edition/html/classes.html#41401)** - not the `throw` keyword. This is used in method signatures in Java to indicate a checked exception can be thrown.
In C#, there is no direct equivalent of a Java checked exception. C# has no equivalent method signature clause.
```
// Java - need to have throws clause if IOException not handled
public void readFile() throws java.io.IOException {
...not explicitly handling java.io.IOException...
}
```
translates to
```
// C# - no equivalent of throws clause exceptions are unchecked
public void ReadFile()
{
...not explicitly handling System.IO.IOException...
}
``` | Yes this is an old thread, however I frequently find old threads when I am googling answers so I figured I would add something useful that I have found.
If you are using Visual Studio 2012 there is a built in tool that can be used to allow for an IDE level "throws" equivalent.
If you use [XML Documentation Comments](http://msdn.microsoft.com/en-us/library/b2s063f7.aspx), as mentioned above, then you can use the [<exception>](http://msdn.microsoft.com/en-us/library/w1htk11d.aspx) tag to specify the type of exception thrown by the method or class as well as information on when or why it is thrown.
example:
```
/// <summary>This method throws an exception.</summary>
/// <param name="myPath">A path to a directory that will be zipped.</param>
/// <exception cref="IOException">This exception is thrown if the archive already exists</exception>
public void FooThrowsAnException (string myPath)
{
// This will throw an IO exception
ZipFile.CreateFromDirectory(myPath);
}
``` |
158,668 | Daily we have to fill timesheets and details on the project/task we have worked on upto hour level. Somedays I don't have any task that have been assigned to me. I have asked to my manager to assign task and he said ok he will do it. But it sometimes takes hours or he assigns the task next day or tells someone else to assign me task which makes it harder to write on the timesheets that I have worked on since obviously I didn't work on anything and I don't wanna lie. I try to attend internal trainings or do some trivial tasks but I get bored and it's creating problem for me as I am on probation and there will be performance review after 6 months of which 4 months have been passed already.
I am BA at IT MNC in India and I don't wanna lose this job atleast not in current times. Any help on what I could/should do to make it so I don't look like I am slacking would be helpful and appreciated. Or this is normal and I should take it lightly?
As far as previous task are concerned I've been completing that on time so there is no such issue of incompetency from my side. | 2020/05/28 | [
"https://workplace.stackexchange.com/questions/158668",
"https://workplace.stackexchange.com",
"https://workplace.stackexchange.com/users/43528/"
] | Some companies are struggling with a dissonance between theory and practice.
In theory, all hours on the timesheet must be billable, either on an external or an internal customer. But in practice, they just don't have enough billable tasks for everyone.
How is that problem solved in practice?
* In some organizations, people just cheat. Off-time gets distributed on all billable tasks they worked on during that time. If someone spent 8 hours at work, and during that time they spent 3 hours solving issue A, 1 hour solving issue B and 4 hours looking at meme pictures on Reddit, then they claim they spent 6 hours on issue A and 2 hours on issue B. This is of course very problematic, because customers get billed for hours they didn't need, the whole internal controlling gets thrown off and the management has no way to quantify how much free capacity they have. But nevertheless it is the status quo. It's usually the result of management ignoring the cognitive dissonance between expecting people to bill 100% of their time while not having any work for them to do.
* Some organizations have a formal and encouraged way to bill hours on "lack of work". But anyone who puts too many hours there admits that they might be reduntant, so in practice it often degenerates into the previous point: People cheat so they look busy.
* Some organizations have a formal and encouraged way to put hours on certain tasks people are expected to perform when they have nothing better to do. For example:
+ Education (which might be self-education or teaching your knowledge to colleagues)
+ Looking for ways to improve internal processes
+ Brainstorming proposals for new products or ways to acquire customers
+ Teambuilding
If you want to know which solution is the usual one in **your** organization, then you need to ask your colleagues how they deal with this issue. | Ask your manager directly. Ask what you should be doing between tasks and where to log that time. As a developer, you could be helping others in chat or via calls, reviewing code, answering emails. As a BA, you could be looking into project documentation to better understand what you are working on. Watching internal product training is another useful direction. But first - ask. Also it's better to send an email, so that you have a written response - if you ever need it later. |
18,822,890 | Question: How do I go about setting the ActionListener of my Shuffle button to do just what the button declares it does, and that is, to shuffle the 3 cards (out of 54 in an image folder) displayed on the screen? They appear randomly each time I run the program, and that's fine and all, but I'm needing to add a shuffle button that'll allow those changes to happen without having to restart the program.
Here is what I've got so far..
```
//Jeffrey Zachary
//Advanced Java: Sept 15 2013
//Display 3 cards, shuffle them when called to do so
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.*;
class DisplayCards extends JFrame implements ActionListener{
private JPanel cards;
private JButton shuffle;
private JLabel c1, c2, c3;
private Container contents;
private ImageIcon[] imIc;
int cardA = 1 + (int)(Math.random() * 54);
int cardB = 1 + (int)(Math.random() * 54);
int cardC = 1 + (int)(Math.random() * 54);
//create variables to store the random number for card
private ImageIcon firstCard = new ImageIcon("card/" + cardA + ".png");
private ImageIcon secondCard = new ImageIcon("card/" + cardB + ".png");
private ImageIcon thirdCard = new ImageIcon("card/" + cardC + ".png");
public DisplayCards(){
super("Display three cards");
contents = getContentPane();
contents.setLayout(new BorderLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Creating card labels
c1 = new JLabel(firstCard, JLabel.CENTER);
c2 = new JLabel(secondCard, JLabel.CENTER);
c3 = new JLabel(thirdCard, JLabel.CENTER);
//Creating panel
cards = new JPanel(new BorderLayout());
//Creating button
shuffle = new JButton("Shuffle");
shuffle.addActionListener(this);
//Adding buttons
cards.add(shuffle, BorderLayout.PAGE_END);
//Adding labels
cards.add(c1, BorderLayout.LINE_START);
cards.add(c2, BorderLayout.CENTER);
cards.add(c3, BorderLayout.LINE_END);
contents.add(cards, BorderLayout.CENTER);
setResizable(false);
setSize(255, 177);
setVisible(true);
}
public static void main(String[] args) {
DisplayCards dc = new DisplayCards();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == shuffle){
}
}
}
```
Can't create a new homework tag (hint hint) :) -No holding hands here- | 2013/09/16 | [
"https://Stackoverflow.com/questions/18822890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2770639/"
] | I suggest you to parse the HTML code ([How do you parse and process HTML/XML in PHP?](https://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php)), then extract the domains from the appropriate attributes. For example:
```
<?php
function getDomainFromEmbed($html, $all = false)
{
$result = array();
$doc = new DOMDocument;
@$doc->loadHTML($html);
$iframes = $doc->getElementsByTagName('iframe');
if (!empty($iframes)) {
foreach ($iframes as $iframe) {
if ($iframe->hasAttribute('src')) {
$url = parse_url($iframe->getAttribute('src'), PHP_URL_HOST);
if ($all) {
$result[] = $url;
} else {
return $url;
}
}
}
}
$objects = $doc->getElementsByTagName('object');
if (!empty($objects)) {
foreach ($objects as $object) {
if ($object->hasAttribute('data')) {
$url = parse_url($object->getAttribute('data'), PHP_URL_HOST);
if ($all) {
$result[] = $url;
} else {
return $url;
}
}
$params = $object->getElementsByTagName('param');
if (!empty($params)) {
foreach ($params as $param) {
if ($param->hasAttribute('name') && $param->hasAttribute('value') && 'movie' === $param->getAttribute('name')) {
$url = parse_url($param->getAttribute('value'), PHP_URL_HOST);
if ($all) {
$result[] = $url;
} else {
return $url;
}
}
}
}
}
}
$embeds = $doc->getElementsByTagName('embed');
if (!empty($embeds)) {
foreach ($embeds as $embed) {
if ($embed->hasAttribute('src')) {
$url = parse_url($embed->getAttribute('src'), PHP_URL_HOST);
if ($all) {
$result[] = $url;
} else {
return $url;
}
}
}
}
return $all ? $result : null;
}
echo '<pre>';
var_dump(getDomainFromEmbed('<iframe src="http://www.websites-test.com/video231/" frameborder=0 width=510 height=400 scrolling=no></iframe>'));
var_dump(getDomainFromEmbed('<object width="990" height="750"> <param name="movie" value="http://www.websites-test.com/video231/"></param><param name="AllowScriptAccess" value="always"></param><param name="wmode" value="transparent"></param><embed src="http://www.websites-test.com/video231/" type="application/x-shockwave-flash" wmode="transparent"` AllowScriptAccess="always" width="990" height="750"></embed></object>'));
echo '</pre>';
``` | Try this code:
```
function getDomain($html) {
preg_match('`<[^>]*src=["\'\s]?([^"^\'^\s]+)["\'\s][^>]*>`i', $html, $matches);
if(isset($matches[1]))
return parse_url($matches[1], PHP_URL_HOST);
return false;
}
$html = '<iframe src="http://www.websites-test.com/video231/" frameborder=0 width=510 height=400 scrolling=no></iframe>';
echo getDomain($html);
echo '<br />';
$html = '<object width="990" height="750"> <param name="movie" value="http://www.websites-test.com/video231/"></param><param name="AllowScriptAccess" value="always"></param><param name="wmode" value="transparent"></param><embed src="http://www.websites-test.com/video231/" type="application/x-shockwave-flash" wmode="transparent"` AllowScriptAccess="always" width="990" height="750"></embed></object>';
echo getDomain($html);
```
Of course instead of `echo getDomain($html)` you can put `$Domain_Embed = getDomain($html)` to assing it to your variable, just as you wanted. `$html` is the HTML code that contains these tags with `src` that you mentioned.
For multiple objects in the same `$html` you can change function to get array of results:
```
function getDomains($html) {
$results = array();
preg_match_all('`<[^>]*src=["\'\s]?([^"^\'^\s]+)["\'\s][^>]*>`i', $html, $matches);
if(isset($matches[1]) && is_array($matches[1]))
foreach($matches[1] as $match)
$results[] = parse_url($match, PHP_URL_HOST);
return empty($results) ? false : $results;
}
echo '<pre>' . print_r(getDomains($html), true) . '</pre>';
``` |
23,491,377 | How can I do that.
This is the scenario:
firstTextbox value: "firstString"
secondTextbox value: "/secondString"
Result I want to recive:
secondTextbox value: "firstString/secondString"
I've tried this solution:
```
<input id="A">
<input id="B">
A.onblur = function() {
B.value = this.value;
};
```
But it only replace the second textbox value width the first value. I want to join the | 2014/05/06 | [
"https://Stackoverflow.com/questions/23491377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3228992/"
] | This can even be done using HTML5 **[output tag](http://www.w3schools.com/tags/tag_output.asp)**
`***[js Fiddle](http://jsfiddle.net/wLy4E/)***`
*HTML*
```
<form oninput="x.value=a.value + b.value">
<input type="text" id="a" value="" />
<input type="text" id="b" value="" />
<output name="x" for="a b"></output>
</form>
``` | The code snippet looks so childish but if this is how you need it, then the possible solution may be out here <http://jsfiddle.net/e8vBj> .
HTML:
```
<input type="text" id="t1"/>
<input type="text" id="t2"/>
<br/>
<br/>
<input type="text" id="t3"/>
```
JS:
```
$('#t1,#t2').blur(function(){
var t1 = $('#t1').val();
if(t1 == ''){
$('#t2').val(t1);
}
//vice versa
var t2 = $('#t2').val();
t1 = (t1 == null)?'':t1;
t2 = (t1 == null)?'':t2;
$('#t3').val(t1+t2);
});
``` |
46,870,479 | I want to convert String variable 'true' or 'false' to int '1' or '0'.
To achieve this I'm trying like this
```
(int) (boolean) 'true' //gives 1
(int) (boolean) 'false' //gives 1 but i need 0 here
```
I now I can using array like `array('false','true');`
or using `if($myboolean=='true'){$int=1;}`
But this way is less efficient.
Is there another more efficient way like this `(int) (boolean) 'true'` ?
### I know this question has been asked. but I have not found the answer | 2017/10/22 | [
"https://Stackoverflow.com/questions/46870479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7228341/"
] | Strings always evaluate to boolean true unless they have a value that's considered "empty" by PHP.
Depending on your needs, you should consider using filter\_var() with the FILTER\_VALIDATE\_BOOLEAN flag.
```
(int)filter_var('true', FILTER_VALIDATE_BOOLEAN);
(int)filter_var('false', FILTER_VALIDATE_BOOLEAN);
``` | ```
$variable = true;
if ($variable) {
$convert = 1;
}
else {
$convert = 0;
}
echo $convert
``` |
5,127,166 | So, I am trying to make floated divs to hide in parent's div, but it isn't working...
My code:
css:
```
div.scrollarea {
overflow: scroll;
width: 400px;
float: left;
}
div.td {
float: left;
width: 100px;
height: 20px;
background-color: red;
}
```
html:
```
<div class="scrollarea">
<div class="td">x1</div>
<div class="td">x2</div>
<div class="td">x3</div>
<div class="td">x4</div>
<div class="td">x5</div>
</div>
```
So what I am getting is:
(couldn't upload images because of spam prevention, so here is link)
<http://i.stack.imgur.com/I0cH1.png>
And what I want to get is to get all of .td's in same row, where horizontal scroll would show up.
Thanks, | 2011/02/26 | [
"https://Stackoverflow.com/questions/5127166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/635538/"
] | Do you have the ability to install software on the computer you wish to run the executable on?
If so, you can create an Adobe AIR application that launches your file. Have the user install that AIR app on their computer. Next, create a small flash widget to sit on your web page. Have the flash widget invoke the AIR app.
Some API info:
<http://www.rogue-development.com/blog2/2008/03/interacting-with-an-air-app-from-a-browser-based-app/> | I do it by linking to a .bat file that runs the .exe itself. |
9,368,904 | I have a webpage where I have a header section and then some content. In the content, I have a grid and some of the views show many columns which (depending on the screen size) will create a horizontal scroll bar on the browser)
my html looks like sort of like this:
```
<head></head>
<body>
<div id="TopHeader"></div>
<div id="MainContent"></div>
</body>
```
so often the **content that is inside of "MainContent" is wider than the screen** . Right now I have my css for my div like this:
```
#TopHeader {
background-color: black;
}
```
but when I scroll over to the right, the background of this section is white. I tried to solve this by doing this:
```
#TopHeader {
min-width:1150px;
background-color: black;
}
```
which helps a little bit but this is a hard coded solution and if the width happens to be > 1150px, I run into the same problem.
The only other thing I can think of is to put TopHeader inside of main (which will fix this). something like this:
```
<head></head>
<body>
<div id="MainContent">
<div id="TopHeader"></div>
</div>
</body>
```
**but** the issue there is that I want padding around my content (what was the MainContent section and I don't want this padding around the top header so that doesn't seem to work. If i create a new div like this
```
<head></head>
<body>
<div id="MainContent">
<div id="TopHeader"></div>
<div id="InnerMainForPadding"></div>
</div>
</body>
```
I am back to the original problem listed above.
Any suggestions ? | 2012/02/20 | [
"https://Stackoverflow.com/questions/9368904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] | As others have pointed out, you're looking for `exists`. Keep in mind that using `exists` with names used by R's base packages would return true regardless of whether you defined the variable:
```
> exists("data")
[1] TRUE
```
To get around this (as pointed out by Bazz; see `?exists`), use the `inherits` argument:
```
> exists("data", inherits = FALSE)
[1] FALSE
foo <- TRUE
> exists("foo", inherits = FALSE)
[1] TRUE
```
Of course, if you wanted to search the name spaces of attached packages, this would also fall short:
```
> exists("data.table")
[1] FALSE
require(data.table)
> exists("data.table", inherits = FALSE)
[1] FALSE
> exists("data.table")
[1] TRUE
```
The only thing I can think of to get around this -- to search in attached packages but *not* in base packages -- is the following:
```
any(sapply(1:(which(search() == "tools:rstudio") - 1L),
function(pp) exists(_object_name_, where = pp, inherits = FALSE)))
```
Compare replacing `_object_name_` with `"data.table"` (`TRUE`) vs. `"var"` (`FALSE`)
(of course, if you're not on RStudio, I think the first automatically attached environment is `"package:stats"`) | If you don't mind using quotes, you can use:
>
> exists("x")
>
>
>
If you don't want to use quotes you can use:
>
> exists(deparse(substitute(x)))
>
>
> |
32,333,902 | Trying to capture an image from webcam and wanted save on a drive
Using Grails 2.3.7
**script code**
```
var video = document.querySelector("#videoElement");
var imageW;
//check for getUserMedia support
navigator.getUserMedia = navigator.getUserMedia
|| navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia
|| navigator.msGetUserMedia || navigator.oGetUserMedia;
if (navigator.getUserMedia) {
// get webcam feed if available
navigator.getUserMedia({
video : true
}, handleVideo, videoError);
}
function handleVideo(stream) {
video.src = window.URL.createObjectURL(stream);
}
function videoError(e) {
}
var v, canvas, context, w, h;
var imgtag = document.getElementById('imgtag');
var sel = document.getElementById('"avatar"');
document.addEventListener('DOMContentLoaded', function() {
v = document.getElementById('videoElement');
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
w = canvas.width;
h = canvas.height;
}, false);
function draw(v, c, w, h) {
if (v.paused || v.ended)
return false; // if no video, exit here
context.drawImage(v, 0, 0, w, h); // draw video feed to canvas
var uri = canvas.toDataURL("image/png"); // convert canvas to data URI
imageW = canvas.toDataURL("image/png");
imageW = imageW.replace('data:image/png;base64,', '');
imgtag.src = uri;
}
document.getElementById('save').addEventListener('click',
function(e) {
draw(v, context, w, h);
});
var fr;
sel.addEventListener('change', function(e) {
var f = sel.files[0];
fr = new FileReader();
fr.onload = receivedData;
fr.readAsDataURL(f);
})
function receivedData() {
imgtag.src = fr.result;
}
function webImageSubmit() {
alert(imageW);
var pars = "id=" + $('#id').val() + "&imageW=" + imageW;
$.ajax({
type : 'POST',
url : '/controller_name/saveWebCamImage',
data : pars,
error : function(request, status, error) {
document.getElementById('load').style.visibility = "hidden";
},
beforeSend : function() {
document.getElementById('load').style.visibility = "visible";
},
success : function(data) {
location.reload();
}
});
}
```
Controller Side :
```
def encodedData = javax.xml.bind.DatatypeConverter.parseBase64Binary(params.imageW.toString());
def defaultPath = "/images/userImages";
def webRootDir = servletContext.getRealPath("/");
def systemDir = new File(webRootDir, defaultPath);
if (!systemDir.exists()) {
systemDir.mkdirs();
}
String file_name = "webImage.jpg";
def csvFileDir = new File( systemDir, file_name);
new File(systemDir, file_name).withOutputStream {
it.write(encodedData);
};
```
But image is not saving on drive.
Please Help me..
Thank you.. | 2015/09/01 | [
"https://Stackoverflow.com/questions/32333902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2446714/"
] | This example sure helpful
```
export default class Setup extends Component {
_onPressButton() {
Alert.alert('You tapped the button!')
}
render() {
return (
<View style={styles.container}>
<View>
<Text h1>Login</Text>
</View>
<View>
<Button
onPress={this._onPressButton}
title="Learn More"
color="#841584"
accessibilityLabel="Learn more about this purple button"
/>
</View>
</View>
);
}
}
``` | You have to use the ES6 way of doing a function or it will not work, specially for higher version such as 0.59. The code below should work, when calling functions within class. You have got it right for calling the function by using this.\_onRegionChangeComplete,
```
constructor(props) {
super(props);
this.state = {sliderValue: 15,}
}
var Map = React.createClass({
render(){
return (
<View style={styles.container}>
<MapView style={styles.map}
showsUserLocation={true}
rotateEnabled={false}
onRegionChangeComplete={this._onRegionChangeComplete}
/>
</View>
);
},
_onRegionChangeComplete=()=>
{
//Your code here. you can use this.variable if you want to use variables from
//your constructor(props) { super(props); this.state = {sliderValue: 15,} }
//Example passing variable
let Myvalue = this.state.sliderValue;
}
``` |
27,610,404 | I am developing a Quiz game. I know about sqlite database creation and the use of DBhandler etc.. but, the problem is that I could not find how to **create a database file in assets folder** in my android project.
Kindly help me.
Thanks in advance | 2014/12/22 | [
"https://Stackoverflow.com/questions/27610404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3969131/"
] | Found the problem. when I did this:
```
echo strlen($hash)
```
it printed 90, which is strange because there were definitely no spaces at the end when I printed out the success/failure message, and the field has a varchar length of 255
I added this line:
```
$hash = substr( $hash, 0, 60 );
```
And now it works fine.
Its strange that no one else seems to have run into this issue. There are similar posts about password\_verify, but none of them required this type of conversion, or any conversion for that matter:
[php password\_verify not working](https://stackoverflow.com/questions/21741424/php-password-verify-not-working)
[password\_verify php not match](https://stackoverflow.com/questions/22374333/password-verify-php-not-match)
<http://forums.phpfreaks.com/topic/283407-need-help-with-password-verify/>
[Using PHP 5.5's password\_hash and password\_verify function](https://stackoverflow.com/questions/14992367/using-php-5-5s-password-hash-and-verify-function-am-i-doing-it-right)
One thing that bothers me is this prevents the code from being forward compatible. How will I know that the hash is 60 characters long when the default changes? | I had the same issue and it was still not working despite ensuring my database columns were varchar(255), that the hashes were 60 characters, and ensuring my encoding was UTF-8 all the way through. I'm pretty new to PHP and SQL so I won't pretend to understand exactly why it worked, but I managed to fix it so I hope this post will help other folks with the same problem.
It turned out that the underlying reason password\_verify() wasn't verifying my hashes was because I had made a prepared statement that used a stored procedure earlier in the script without fetching all the results from the query properly to clear the buffer, before closing and reopening the connection to perform the next query. Calling next\_result() on the mysqli\_link after closing the statement will make sure any results are consumed.
Additionally, I was then using another prepared statement with a stored procedure to make the insert for the password, but I still needed to make calls to store\_result() and free\_result() even though no result sets were returned from the insert. I'm assuming the combination of these things was corrupting my data somewhere along the line, resulting in password\_verify() returning false on seemingly identical hashes.
[This answer](https://stackoverflow.com/a/14561639/8679435) was for a different problem but I found it useful for learning how to properly close out prepared statements with stored procedures. |
29,893,631 | I successfully imported following file in database but my import method removes double quotes during saving process. but i want to export this file as it is , i.e add quotes to a string which contains delimiter so how to achieve this .
**here is my csv file with headers and 1 record.**
```
PTNAME,REGNO/ID,BLOOD GRP,WARD NAME,DOC NAME,XRAY,PATHO,MEDICATION,BLOOD GIVEN
Mr. GHULAVE VASANTRAO PANDURANG,SH1503/00847,,RECOVERY,SHELKE SAMEER,"X RAY PBH RT IT FEMUR FRACTURE POST OP XRAY -ACCEPTABLE WITH IMPLANT IN SITU 2D ECHO MILD CONC LVH GOOD LV SYSTOLIC FUN, ALTERED LV DIASTOLIC FUN.", HB-11.9gm% TLC-8700 PLT COUNT-195000 BSL-173 UREA -23 CREATININE -1.2 SR.ELECTROLYTES-WNR BLD GROUP-B + HIV-NEGATIVE HBsAG-NEGATIVE PT INR -15/15/1.0. ECG SINUS TACHYCARDIA ,IV TAXIMAX 1.5 GM 1-0-1 IV TRAMADOL DRIP 1-0-1 TAB NUSAID SP 1-0-1 TAB ARCOPAN D 1-0-1 CAP BONE C PLUS 1 -0-1 TAB ANXIT 0.5 MG 0-0-1 ANKLE TRACTION 3 KG RT LL ,NOT GIVEN
```
Here is my method of export:
```
public void DataExport(string SelectQuery, string fileName)
{
try
{
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(SelectQuery, con);
da.Fill(dt);
//Sets file path and print Headers
// string filepath = txtreceive.Text + "\\" + fileName;
string filepath = @"C:\Users\Priya\Desktop\R\z.csv";
StreamWriter sw = new StreamWriter(filepath);
int iColCount = dt.Columns.Count;
// First we will write the headers if IsFirstRowColumnNames is true: //
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(',');
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dt.Rows) // Now write all the rows.
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < iColCount - 1)
{
sw.Write(',');
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
catch { }
}
``` | 2015/04/27 | [
"https://Stackoverflow.com/questions/29893631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4696835/"
] | You can rely on base R structures and consider following approach based on building the hclust trees by yourself.
```
mtscaled = as.matrix(scale(mtcars))
row_order = hclust(dist(mtscaled))$order
column_order = hclust(dist(t(mtscaled)))$order
heatmap(mtscaled[row_order,column_order], Colv=NA, Rowv=NA, scale="none")
```
No need to install additional junk. | Do the dendrogram twice using the basic R heatmap function. Take the output of the first run, which clusters but has mandatory drawing of the dendrogram and feed it into the heatmap function again. This time, without clustering, and without drawing the dendrogram.
#generate a random symmetrical matrix with a little bit of structure, and make a heatmap
```
M100s<-matrix(runif(10000),nrow=100)
M100s[2,]<-runif(100,min=0.1,max=0.2)
M100s[4,]<-runif(100,min=0.1,max=0.2)
M100s[6,]<-runif(100,min=0.1,max=0.2)
M100s[99,]<-runif(100,min=0.1,max=0.2)
M100s[37,]<-runif(100,min=0.1,max=0.2)
M100s[lower.tri(M100s)] <- t(M100s)[lower.tri(M100s)]
heatmap(M100s)
```
#save the output
```
OutputH <- heatmap(M100s)
```
#run it again without clustering or the dendrogram
```
M100c <- M100s
M100c1 <- M100c[,OutputH$rowInd]
M100c2 <- M100c1[OutputH$colInd,]
heatmap(M100c2,Rowv = NA, Colv = NA, labRow = NA, labCol = NA)
``` |
67,813,167 | I have the following document structure
```
{
"_id": "60b7b7c784bd6c2a1ca57f29",
"user": "607c58578bac8c21acfeeae1",
"exercises": [
{
"executed_reps": [8,7],
"_id": "60b7b7c784bd6c2a1ca57f2a",
"exercise_name": "Push up"
},
{
"executed_reps": [5,5],
"_id": "60b7b7c784bd6c2a1ca57f2b",
"exercise_name": "Pull up"
}
],
}
```
In aggregation, I am trying to sum all the `executed_reps` so the end value in this example should be 25 (8+7+5+5).
Here is the code I have so far:
```
const exerciseStats = await UserWorkout.aggregate([
{
$match: {
user: { $eq: ObjectId(req.query.user) },
},
},
{ $unwind: '$exercises' },
{
$group: {
_id: null,
totalReps: {
$sum: {
$reduce: {
input: '$exercises.executed_reps',
initialValue: '',
in: { $add: '$$this' },
},
},
},
},
},
]);
```
This gives a result of 5 for `totalReps`. What am I doing wrong? | 2021/06/02 | [
"https://Stackoverflow.com/questions/67813167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6224201/"
] | So let's start with:
```
$ docker run --rm -it php:7.4-alpine -r 'var_dump($l = new Locale("en_CA"));'
Fatal error: Uncaught Error: Class 'Locale' not found in Command line code:1
Stack trace:
#0 {main}
thrown in Command line code on line 1
```
Yep, that tracks. So then:
```
FROM php:7.4-alpine
RUN apk add icu-dev
RUN docker-php-ext-configure intl
RUN docker-php-ext-install intl
RUN docker-php-ext-enable intl
```
and:
```
$ docker build -t php:intl-test ./
```
finally:
```
$ docker run --rm -it php:intl-test -r 'var_dump($l = new Locale("en_CA"));'
object(Locale)#1 (0) {
}
```
So either it's working, or you have a *completely different problem*. | Thank you @Ovinz
Just adding to my Dockerfile
```
RUN apk add --no-cache icu-libs
RUN apk add --no-cache icu-data-full
```
And everything goes well (twig intl in my case) |
40,626,410 | Trying to execute in SQLAssitant (v 15.x Teradata):
```
WITH TEMP1 (EMP_ID,E_NAME,E_SAL) AS (WITH TEMP (EMP_ID,E_NAME,E_SAL) AS (SELECT EMP_ID,E_NAME,E_SAL FROM EMP_TABLE_TEST)
SELECT EMP_ID,E_NAME,E_SAL FROM TEMP) SELECT EMP_ID,E_NAME,E_SAL FROM TEMP1
```
Error: SELECT Failed. 6926: definitions, views, triggers or stored procedure
```
WITH TEMP (EMP_ID,E_NAME,E_SAL) AS (SELECT EMP_ID,E_NAME,E_SAL FROM EMP_TABLE_TEST ) , TEMP1 (EMP_ID,E_NAME,E_SAL) AS (
SELECT EMP_ID,E_NAME,E_SAL FROM TEMP) SELECT EMP_ID,E_NAME,E_SAL FROM TEMP1
```
Error: SELECT Failed. 3807: Object 'TEMP' does not exist.
Does Teradata really support Multiple WITH clause or WITH within WITH clause?
I heard it is supported in 14.x higher version but it is not supporting for 15.x. | 2016/11/16 | [
"https://Stackoverflow.com/questions/40626410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6518278/"
] | The syntax is different (and is the same as in other databases)
`With t1 as (...),t2 as (...), t3 as (...) select ...`
---
Currently the reference order is upside-down -
t2 can refer t3 and t1 can refer t2 and t3.
The "right" order will be supported in TD16. | This has been fixed in Teradata 16. Please see the release summary chapter 2.
<http://www.info.teradata.com/doclist.cfm?RetainParams=Y&FilterCall=Y&selDocType=100>
>
> Previously, when a nonrecursive WITH clause defined multiple CTEs, a CTE could only reference a
> subsequent CTE in the WITH clause. Now, a CTE can reference a preceding or subsequent CTE in the
> WITH clause.
>
>
>
From Teradata Release Summary for version 16 |
8,277,979 | As per the instructions here:
<http://developer.apple.com/library/mac/#documentation/MusicAudio/Conceptual/CoreAudioOverview/WhatisCoreAudio/WhatisCoreAudio.html#//apple_ref/doc/uid/TP40003577-CH3-SW1>
It says:
The Core Audio SDK assumes you will use Xcode as your development environment.
You can download the latest SDK from <http://developer.apple.com/sdk/>. After installation, the SDK files are located in /Developer/Examples/CoreAudio.
I looked at all the SDKs and did a search for Core audio. Nothing shows up. Does anyone know where I can find the Core Audio SDKs? | 2011/11/26 | [
"https://Stackoverflow.com/questions/8277979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/129089/"
] | The documentation is out of date. Core Audio SDK is included with current Xcode 4.2. You need to link to it like this:

and of course include its header file. | It seems the CoreAudio SDK was renamed Core Audio Utility Classes, and can be found there:
<http://developer.apple.com/library/mac/#samplecode/CoreAudioUtilityClasses/Introduction/Intro.html> |
6,189,522 | Backbone configure url once for all when a Collection is created. Is there a way to change this url later?
The following sample shows 2 POST at `/product` and 2 `POST` at `/product/id/stock`. The last `POST` won't work, Backbone concatenate the id and try to `PUT` it, but I don't know why.
```
products.create({ name: 'American Pastoral', price: 8 });
products.create({ name: 'The Grapes of Wrath', price: 10 });
products.each(function(product) {
var id = parseInt(product.get('id'));
stocks.setId(id);
stocks.create({ id: id, quantity: 12 });
}
```
The stock collection:
```
Backbone.Collection.extend({
url: function() {
return this.url;
},
parse : function(resp) {
return resp.stock;
},
setProduct: function(id) {
this.url = '/product/'+id+'/stock';
}
});
```
This **won't** work. | 2011/05/31 | [
"https://Stackoverflow.com/questions/6189522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/535184/"
] | Backbone.js will use the url of the model when saving existing models. Its not quite clear what you are trying to do -- I don't know what stocks is, for instance. Anyway, your code probably needs to look similar to the below and you should not be dynamically changing the url:
```
Product = Backbone.Model.extend({
url: function() {
return '/product/' + id + '/stock';
}
});
ProductList = Backbone.Collection.extend({
model: Product,
url: '/product'
}):
```
Backbone.js will then use collection url for creates and the model url for saves. I think you need to leave the url alone and let backbone's default functionality handle it. | I have run into what is essentially the same problem. It seems that Backbone's pattern is to lock down relative URI's in models and collections and allow the framework to use these to build final the final URI for a given resource. This is great for Restful URI's templates that don't change. But in a pure RESTful service you would expect lists of relative URI's to come down as part of a given resource. There are many reasons why you might need to do this, obvious one is if the URI for a resource moves.
As far as I can tell Backbone has no way of easily cleanly handling this. In the question above my workaround is to essentially redefine the models url method using OLN. You would do this while fetching a collection or initializing it for the first time. Basically build the logic to handle URI lists yourself. |
34,614,579 | I'm trying to implement an AngularJS directive which has it own isolated scope in order to make it reusable in the same page. This directive is described by a template which is in another file so I use the templateUrl option.
```
app.directive('inputSettings', function () {
return {
restrict: 'E',
transclude: true,
templateUrl: 'templates/admin/inputSettingsTemplate.html',
controller: 'InputSettingsCtrl',
scope: {
settingkey: '=',
value: '=',
range: '=',
check: '=',
autosave: '='
}
};
});
```
In this template, I have a form named `form`.
```
<form name="form" class="settingForm" novalidate>
<div class="form-group" ng-class="{ 'has-error' : form.input.$invalid, 'has-success' : form.input.$valid }">
<input class="form-control" name="input" type="text" ng-model="valueInput" />
<p ng-show="form.input.$invalid && !form.input.$pristine" class="help-block" translate="{{ 'inputSettingErrorMessage' | translate:translationData }}"></p>
</div>
</form>
```
The problem I have is that I want to be able to set the validity of the input inside the template using a code like the following in the controller of my directive :
```
$scope.form.input.$setValidity("input", true);
```
But I have an error when I try to execute such a code. It seems that `$scope` does not know the form so I can't interact with my form within the controller of my directive.
Have you any idea? Is there anything I did wrong?
Thanks in advance ! | 2016/01/05 | [
"https://Stackoverflow.com/questions/34614579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3511736/"
] | Generally in a directive , to set the validity of a element we require ngModel for the directive and then we try to set the $validity of the element using the ngModelController | Use $rootScope. It`s global. It contains all $scopeS..
Like
```
$rootScope.data = data; $scope.data = $rootScope.data
``` |
242,713 | Make a program that outputs a sequence of integers so that every finite sequence of positive integers is a substring (continuous subsequence) of the output.
For example, the following sequence satisfies the rules:
`1,1,1,2,1,1,1,1,2,2,1,3,1,1,1,1,1,1,2,1,2,1,1,3,2,1,1,3,1,4,...`
To see the underlying pattern, let's format the sequence a bit differently:
```
1,
1,1, 2,
1,1,1, 1,2, 2,1, 3,
1,1,1,1, 1,1,2, 1,2,1, 1,3, 2,1,1, 2,2, 3,1, 4,
1,1,1,1,1, 1,1,1,2, 1,1,2,1, 1,1,3, 1,2,1,1, 1,2,2, 1,3,1, 1,4, 2,1,1,1, 2,1,2, 2,2,1, 2,3, 3,1,1, 3,2, 4,1, 5
...
```
Here you can see that every row contains every sequence of positive numbers that sum to the index of the row. For example, row 3 has all sequences whose sum is 3. This means that every sequence is included somewhere in the list.
Standard [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply. As stated before, your sequence may also contain 0 or negative numbers. These non-positive numbers are not ignored, meaning that your output must contain arbitrarily long substrings of only positive integers. | 2022/02/11 | [
"https://codegolf.stackexchange.com/questions/242713",
"https://codegolf.stackexchange.com",
"https://codegolf.stackexchange.com/users/84290/"
] | [Haskell](https://www.haskell.org/), 39 bytes
=============================================
```hs
do y<-[1..];q<-mapM id$[1..y]<$[1..y];q
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P902JV@h0kY32lBPL9a60EY3N7HAVyEzRQUkUBlrA6WtC//nJmbm2RYUZeaVqJQkZqcqGBoAgYKKQvp/AA "Haskell – Try It Online")
Start with the positive integers `[1..]`. Draw an integer `y`. Then take the cartesian product of `y` copies of `[1..y]`. This is just all the ways to choose `y` numbers less than or equal to `y`. | [Pari/GP](http://pari.math.u-bordeaux.fr/), 39 bytes
====================================================
```
for(i=1,oo,[print(p[2])|p<-factor(i)~])
```
[Try it online!](https://tio.run/##K0gsytRNL/j/Py2/SCPT1lAnP18nuqAoM69EoyDaKFazpsBGNy0xuQQkq1kXq/n/PwA "Pari/GP – Try It Online")
A port of [@Command Master's 05AB1E answer](https://codegolf.stackexchange.com/a/242757/9288).
---
[Pari/GP](http://pari.math.u-bordeaux.fr/), 44 bytes (@Polichinelle)
--------------------------------------------------------------------
```
for(i=9,oo,[print(d)|d<-digits(i,log(i)\1)])
```
[Try it online!](https://tio.run/##K0gsytRNL/j/Py2/SCPT1lInP18nuqAoM69EI0WzJsVGNyUzPbOkWCNTJyc/XSNTM8ZQM1bz/38A "Pari/GP – Try It Online")
---
[Pari/GP](http://pari.math.u-bordeaux.fr/), 47 bytes
----------------------------------------------------
```
for(i=9,oo,[print(d)|d<-digits(i,log(i)^.9\1)])
```
When \$i\$ is larger enough, \$b = \lfloor\log(i)^{0.9}\rfloor\$ will satisfy \$b^b < i\$. So the code will print the base-\$b\$ digits of a sequence of more than \$b^b\$ consecutive integers, which will contain all sequences of integers in \$1,\dots,b-1\$ with length \$<b\$.
[Try it online!](https://tio.run/##K0gsytRNL/j/Py2/SCPT1lInP18nuqAoM69EI0WzJsVGNyUzPbOkWCNTJyc/XSNTM07PMsZQM1bz/38A "Pari/GP – Try It Online")
---
[Pari/GP](http://pari.math.u-bordeaux.fr/), 50 bytes
----------------------------------------------------
```
for(i=2,oo,for(j=1,i^i,[print(d)|d<-digits(j,i)]))
```
[Try it online!](https://tio.run/##K0gsytRNL/j/Py2/SCPT1kgnP18HxMyyNdTJjMvUiS4oyswr0UjRrEmx0U3JTM8sKdbI0snUjNXU/P8fAA "Pari/GP – Try It Online") |
16,442,565 | So, I load a file at the start of a form. I have "Save button" in that form.When I click it, I want to overwrite the file with richtextbox.Savefile method. but I get "Access to path.. is denied"
I checked and got this:
1. Permissions for current user are all granted
2. The debug folder has "Read-Only" -- tried to remove, but they always come back
Now, I think that the program doesn't release the resource(the file) only when I close the form
Is there any method to force this? (I think the file remains loaded into the RAM memory)
One more thing: I must use SaveFile and LoadFile methods. I am working with RTF files and my code is in such a way that this methods do the best job.
```
public EditareArticol(string path,List<capitol>chapters,Object[,]lca)
{
this.richTextBoxEx1.LoadFile(path, RichTextBoxStreamType.RichText);
}
private void saveToolStripButton_Click(object sender, EventArgs e)
{
richTextBoxEx1.SaveFile("articles\\" +
textBox1.Text + ".dat",
RichTextBoxStreamType.RichText);
File.SetAttributes("articles\\" + textBox1.Text + ".dat", File.GetAttributes("articles\\" + textBox1.Text + ".dat") | FileAttributes.Hidden);
}
```
**EDIT:**
I think it's all about the handle for the specific file.
From the MSDN Documentations:
>
> The LoadFile method will not open a file until a handle is created for the RichTextBox. Ensure that the control's handle is created before calling the LoadFile method.
>
>
> | 2013/05/08 | [
"https://Stackoverflow.com/questions/16442565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1789415/"
] | Just a minor problem with your code my friend, you just need to add only one following line to your code, forget to `setUserInteractionEnabled:NO` to `UIView` it will allow you to click the button
```
UILabel *lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
[lbl1 setText:@"ONe"];
UILabel *lbl2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, 100, 30)];
[lbl2 setText:@"Two"];
UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 130)];
[view setUserInteractionEnabled:NO];
[view addSubview:lbl1];
[view addSubview:lbl2];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn addSubview:view];
[btn setFrame:CGRectMake(0, 0, 200, 130)];
[btn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
```
Click Method
```
-(void)click
{
NSLog(@"%s",__FUNCTION__);
}
``` | **Swift 4.2 Solution**
This is the solution of the problem (based on previous answers) with the last version of Swift:
```
func customButton() {
// Label Creation
let firstLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 30))
firstLabel.text = "first"
let secondLabel = UILabel(frame: CGRect(x: 0, y: 30, width: 100, height: 30))
secondLabel.text = "second"
// Custom View creation
let viewFrame = CGRect(x: 0, y: 0, width: 100, height: 60)
let customView = UIView(frame: viewFrame)
customView.addSubview(firstLabel)
customView.addSubview(secondLabel)
customView.isUserInteractionEnabled = false
// Custom button
let button = UIButton(type: .custom)
button.frame = viewFrame
button.addSubview(customView)
button.addTarget(self, action: #selector(click), for: .touchUpInside)
addSubview(button)
}
@objc
func click() {
print("Click")
}
```
*Notes*: Disabling the user interaction of the `customView` is definitely needed, since it is added on top and will eventually interfere with the tap gesture that we want to catch.
For seeing this more clearly, simply use the "Debug View Hierarchy" while debugging:
[](https://i.stack.imgur.com/72Y8n.png) |
16,721,157 | I have this map, as an answer of [this other question](https://stackoverflow.com/q/16346000/1546946). It uses geocodezip and works well, but it is not working in Internet Explorer. Can you suggest me any solution?
This is the link of the map:
<http://www.geocodezip.com/geoxml3_test/v3_geoxml3_kmltest_linktoB.html?filename=http://www.geocodezip.com/xmlProxy060215.asp?https%3A%2F%2Fmaps.google.com%2Fmaps%2Fms%3Fhl%3Den%26ie%3DUTF8%26oe%3DUTF8%26authuser%3D0%26msa%3D0%26output%3Dkml%26msid%3D216330649072490208011.0004daf6e6bfde8dd857d>
This is how it looks in other browsers

This is how it looks in intenet explorer

Thank you very much | 2013/05/23 | [
"https://Stackoverflow.com/questions/16721157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1546946/"
] | Your rewrite rules have two major problems:
* the order of them matters. Right now, your second and third will never match stuff
* two of them could be simplified into one.
Consider using this:
```
RewriteEngine on
RewriteBase /ansjc
# Remove file extension
RewriteRule images/album_id/(.+)/?$ images.php?album_id=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.+) $1.php [L]
```
The [L] flag signifies "last". In other words, if it matches, nothing else will be processed in terms of rewrites. So, if images/album\_id/etc/ gets matched, the second rewrite rule will not interfere.
This also solves the issue of the .php being appended to everything. Though I suspect your 500 might be from your code, not from rewrites. | Use this code
```
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]*)$ $1.php [NC,L]
RewriteRule ^images/(.*)$ images.php?album_id=$1 [L]
```
and try
```
http://localhost/images
http://localhost/images/
http://localhost/images/album_id
```
it will call images.php and inside images.php just print\_r($\_GET); to test. |
18,832 | `:scriptnames` outputs a (not convenient) list with more at the bottom.
I'd like to have all the output in a buffer so i can search, edit ...
How do i do that? | 2019/02/08 | [
"https://vi.stackexchange.com/questions/18832",
"https://vi.stackexchange.com",
"https://vi.stackexchange.com/users/19908/"
] | You can also directly paste it into the current buffer using
```
:put =execute(':scriptnames')
``` | You could redirect the output to a register like:
```
:redir @a | silent scriptnames | redir END
```
And then past the content of the register wherever you want with `"ap`.
The `silent` is used here, to prevent a "-- More --" prompt.
You could also redirect to file or a script variable. See `:help :redir`. |
30,619,221 | i am having the value in column Description , 'TRANSPORT' , in that particular table the same value has two times, i need to make it as a single value , in that i am using group by . but its not assigning.
my query
```
SELECT CONVERT(date, UC.USGDATE) as USGDATE, SG.DESCRIPTION, SG.SERVICEGRP
FROM APP_SYUTILITYCHARGES UC LEFT OUTER JOIN
TX_MYSERVICEITEM SI
ON SI.SERVICEITEMID = UC.SERVICEITEMID LEFT OUTER JOIN
TX_MYSERVICE MS
ON MS.SERVICEID = SI.SERVICEID LEFT OUTER JOIN
TX_SERVICEGROUP SG
ON SG.SERVICEGRP = MS.SERVICEGRP
WHERE UC.STAYID = @STAYID
GROUP BY SG.SERVICEGRP, UC.USGDATE, SG.DESCRIPTION
``` | 2015/06/03 | [
"https://Stackoverflow.com/questions/30619221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3643560/"
] | Updated details following release of .Net Core 1.0.0
startup.cs
```
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc(config =>
{
// Add XML Content Negotiation
config.RespectBrowserAcceptHeader = true;
config.InputFormatters.Add(new XmlSerializerInputFormatter());
config.OutputFormatters.Add(new XmlSerializerOutputFormatter());
});
```
project.json
```
"dependencies": {
"Microsoft.AspNetCore.Mvc": "1.0.0",
"Microsoft.AspNetCore.Mvc.Formatters.Xml": "1.0.0",
```
For more help see Shawn Wildermuths blog post on the subject: [Content Negotiation in ASP.NET Core](https://wildermuth.com/2016/03/16/Content_Negotiation_in_ASP_NET_Core) | Updated answer for ASP.NET Core 1.1:
Startup.cs:
```cs
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc(config => {
config.RespectBrowserAcceptHeader = true;
config.InputFormatters.Add(new XmlSerializerInputFormatter());
config.OutputFormatters.Add(new XmlSerializerOutputFormatter());
});
}
```
Csproj:
```
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.3" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Formatters.Xml" Version="1.1.3" />
``` |
94,226 | I have 4 versions of file A.txt in my subversion repository, say: A.txt.r1, A.txt.r2, A.txt.r3 and A.txt.r4. My working copy of the file is r4 and I want to switch back to r2. I don't want to use "*svn update -r 2 A.txt*" because this will delete all the revisions after r2, namely r3 and r4.
So is there any way that I update my working copy to r2 and still having the option to switch to r3 and r4 later? Put it another way, I want to still be able to see all 4 revisions by using "*svn log A.txt*" after doing the update. | 2008/09/18 | [
"https://Stackoverflow.com/questions/94226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8203/"
] | The command `svn up -r 4` only updates your *local* copy to revision 4.
The server still has all versions 1 through to whatever.
What you want to do, is create a *new* revision, revision number 5, which is identical to revision number 2.
```
cd /repo
svn up -r 2
cp /repo/file /tmp/file_2
svn up -r 4
cp /tmp/file_2 /repo/file
svn commit -m "Making 5 from 2"
```
If you ever change your mind and want 4 back, you can do so by creating revision 6 from revision 4.
```
cd /repo
svn up -r 4
cp /repo/file /tmp/file_4
svn up -r 5
cp /tmp/file_4 /repo/file
svn commit -m "Making 6 from 4"
```
Happy hacking.
( there is of course a way to do the above in only 2 commands i believe, but its been a while since I did it and it can be a little confusing ) | >
> "I don't want to use "svn update -r 2 A.txt" because this will delete all the revisions after r2, namely r3 and r4."
>
>
>
Uh... it won't, actually. Try it: do a regular svn update after the -r 2 one and you'll see the working copy updated back to r4. |
19,767,917 | In Asp.net Entity Framework I need to forward to another page and pass some data processed by the second page along.
In PHP I could do something like
```
<!-- page1.php -->
<form action="page2.php" method="POST">
<input type="hidden" name="id" />
<input type="submit" value="Go to page 2" />
</form>
<!-- page2.php -->
<?php
echo $_POST['id'];
?>
```
How can this be implemented in Asp.net?
**Edit**: There is a simple solution using Javascript and jQuery.
```
<!-- on page 1 -->
$('input[type=submit]').on('click', function (e) {
// Forward to browsing page and pass id in URL
e.preventDefault();
var id= $('input[name=id]').val();
if ("" == id)
return;
window.location.href = "@Request.Url.OriginalString/page2?id=" + id;
});
<!-- on page 2 -->
alert("@Request.QueryString["id"]");
``` | 2013/11/04 | [
"https://Stackoverflow.com/questions/19767917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2558051/"
] | There are, at least, two options:
1. Session state, like this:
Putting data into `Session` (your first page)
```
Session["Id"] = HiddenFieldId.Value;
```
Getting data out of `Session` (your second page)
```
// First check to see if value is still in session cache
if(Session["Id"] != null)
{
int id = Convert.ToInt32(Session["Id"]);
}
```
2. Query string, like this:
Putting the value into the URL for the second page as a query string
```
http://YOUR_APP/Page2.aspx?id=7
```
Reading the query string in the second page
```
int id = Request.QueryString["id"]; // value will be 7 in this example
``` | There's a lot of ways to do this, take a look at [`this link`](http://msdn.microsoft.com/en-us/library/6c3yckfw%28v=vs.100%29.aspx) for some guidance.
HTML page:
```
<form method="post" action="Page2.aspx" id="form1" name="form1">
<input id="id" name="id" type="hidden" value='test' />
<input type="submit" value="click" />
</form>
```
Code in Page2.aspx:
```
protected void Page_Load(object sender, EventArgs e)
{
string value = Request["id"];
}
```
**MVC** would look like...
```
@using (Html.BeginForm("page2", "controllername", FormMethod.Post))
{
@Html.Hidden(f => f.id)
<input type="submit" value="click" />
}
```
also, read through these [`MVC tutorials`](http://www.asp.net/mvc/tutorials), you shouldn't blindly translate what you know in PHP to ASP.NET MVC, since you need to learn the MVC pattern too. |
19,970,611 | I want to select first 4 letters of the address string ignoring the numbers or P.O. box.
For example, I have a database column "address" in "customers" table.
```
51 church st
```
In a query, I only want "chur" ignoring the numbers. It can be any number. I am not interested in number. Also, I don't want this for just one record. I want this to happen for every record
So for example I have these records:
```
51 church st
6178 fookeral ave
597537 state ct
```
In my 1 query i want results look like this
```
Chur
Fook
Stat
```
How can I get this in one query? | 2013/11/14 | [
"https://Stackoverflow.com/questions/19970611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2990687/"
] | Many correct answers here already, but since the OP still seems a little confused, I'd like to make this point as simple and clear as possible:
You should use `Nullable<something>` with a `something` that can not, on it's own, have a value of `Null`. Take `DateTime` for example - it has a default value of `DateTime.MinValue` (a constant representing 01.01.01), but can *never* have a value of `Null`. The same goes for `int`; it can never hold a value of `null`
Ie, you can't do:
```
DateTime invalidDate = null;
```
But you CAN do:
```
Nullable<DateTime> validDate = null;
```
**String, on the other hand, *can be null*, so you basically *don't need* Nullable:**
```
string justFine = null;
```
Trying to use `Nullable<string>` therefore makes little sense, and that is basically what you need to know to resolve this problem. | `decimal` is a ValueType. `string` is a Class. Null cannot be assigned to variables that are ValueTypes unless you wrap them in `Nullable<>`. Null can already be assigned to variables that are classes like `string`. |
7,943,220 | I am using ar.h for the defining the struct. I was wondering on how I would go about getting information about a file and putting it into those specified variables in the struct.
```
struct ar_hdr {
char ar_name[16]; /* name of this member */
char ar_date[12]; /* file mtime */
char ar_uid[6]; /* owner uid; printed as decimal */
char ar_gid[6]; /* owner gid; printed as decimal */
char ar_mode[8]; /* file mode, printed as octal */
char ar_size[10]; /* file size, printed as decimal */
char ar_fmag[2]; /* should contain ARFMAG */
};
```
Using the struct defined above, how would I put get the information from the file from `ls -la`
`-rw-rw----. 1 clean-unix upg40883 368 Oct 29 15:17 testar`
? | 2011/10/30 | [
"https://Stackoverflow.com/questions/7943220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/988728/"
] | You're looking for [`stat(2,3p)`](http://linux.die.net/man/2/stat). | For collecting data about a single file into an archive header entry, the primary answer is [`stat()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fstatat.html); in other contexts (such as `ls -la`), you might also need to use `lstat()` and [`readlink()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/readlink.html). (Beware: `readlink()` does not null terminate its return string!)
With `ls -la`, you would probably use the [`opendir()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/opendir.html) family of functions ([`readdir()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/readdir.html) and [`closedir()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/closedir.html) too) to read the contents of a directory.
If you needed to handle a recursive search, then you'd be looking at [`nftw()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/nftw.html). (There's also a less capable [`ftw()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/ftw.html), but you'd probably be better off using `nftw()`.) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.