qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
293,532 | People who don't understand Terminal are often afraid to use it for fear that they might mess up their command and crash their computer. Those who know Terminal better know that that's not the case - usually Terminal will just output an error. But are there actually commands that will crash your computer?
WARNING: you could lose data if you type these or copy paste, especially `sudo` and `rm` commands.
================================================================================================== | 2017/07/31 | [
"https://apple.stackexchange.com/questions/293532",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/234283/"
] | Not sure what you mean about 'crash'ing the computer - if you would re-phrase it to say 'render the computer unusable', then yes. Certainly all it takes is a single stray command - just a moment where you're not thinking clearly about what you're doing, similar to when you speak without thinking, and the damage can be immense and almost immediate. The classic example:
```
$ sudo rm -rf /
```
If you let that command run for even just one second, that can wipe out enough of your system to render it unbootable, and possibly cause irreversible data loss. Don't do it. | Yes, you can completely destroy your system. Accidentally doing something with `sudo` privileges is one example that has been posted, whether it's forgetting a few characters that instruct the terminal to do something completely different than you intended. `rm`ing `/` instead of `/tmp/\*` is only a 5 character difference. Putting a space in the wrong place could do something completely different as well. Other times, seemingly well meaning instructions could have malicious code obfuscated into it. Some people on the internet are very good at obfuscating code.
There are also commands that, using html, can be made font size zero, so something completely innocuous looking, when copied to the clipboard, could in fact be installing someone's git repo as a trusted source and downloading malware.
And there are commands that you can run that open you to exploit, or that could be perfectly well intended but removes important files or programs or corrupts your disk. In fact, using tools incorrectly could do something as basic as accidentally writing over your boot sector, or the head of your disk, or lots of other issues.
An example of something less destructive that hasn't been posted is opening binary files in `vi`. If you've ever tried it, you'll know that it can mess up your terminal to the point that it's unusable until it is `reset`.
Alternatively, there are commands that will bog down your machine, like:
```
yes >> /dev/null & yes >> /dev/null & yes >> /dev/null & yes >> /dev/null &
```
You can try that one, it's not going to do damage, but it will bog down your processor, and you'll have to kill each process you've spawned.
That being said, in computing it's generally taken that you can't make an omelette without breaking a few eggs. You should be cautious at the terminal, but the only way that one can become better at using the OS is by learning and practicing. |
293,532 | People who don't understand Terminal are often afraid to use it for fear that they might mess up their command and crash their computer. Those who know Terminal better know that that's not the case - usually Terminal will just output an error. But are there actually commands that will crash your computer?
WARNING: you could lose data if you type these or copy paste, especially `sudo` and `rm` commands.
================================================================================================== | 2017/07/31 | [
"https://apple.stackexchange.com/questions/293532",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/234283/"
] | Not sure what you mean about 'crash'ing the computer - if you would re-phrase it to say 'render the computer unusable', then yes. Certainly all it takes is a single stray command - just a moment where you're not thinking clearly about what you're doing, similar to when you speak without thinking, and the damage can be immense and almost immediate. The classic example:
```
$ sudo rm -rf /
```
If you let that command run for even just one second, that can wipe out enough of your system to render it unbootable, and possibly cause irreversible data loss. Don't do it. | Modern macOS makes it *really* hard to crash your machine as an unprivileged user (i.e. without using `sudo`), because UNIX systems are meant to handle thousands of users without letting any of them break the whole system. So, thankfully, you'll usually have to be prompted before you do something that destroys your machine.
Unfortunately, that protection only applies to the system itself. As xkcd illustrates, there's lots of stuff that *you* care about that isn't protected by System Integrity Protection, root privileges or password prompts:
[](https://imgs.xkcd.com/comics/authorization.png)
So, there's tons of stuff you can type in that will just wreck your user account and all your files if you aren't careful. A few examples:
* `rm -rf ${TEMPDIR}/*`. This seems totally reasonable, until you realize that the environment variable is spelt **`TMPDIR`**. `TEMPDIR` is usually undefined, which makes this `rm -rf /`. Even without `sudo`, this will happily remove anything you have delete permissions to, which will usually include your entire home folder. If you let this run long enough, it'll nuke any drive connected to your machine, too, since you usually have write permissions to those.
* `find ~ -name "TEMP*" -o -print | xargs rm`. `find` will normally locate files matching certain criteria and print them out. Without the `-o` this does what you'd expect and deletes every file starting with `TEMP*` (*as long as you don't have spaces in the path*). But, the `-o` means "or" (not "output" as it does for many other commands!), causing this command to actually delete all your files. Bummer.
* `ln -sf link_name /some/important/file`. I get the syntax for this command wrong occasionally, and it will rather happily overwrite your important file with a useless symbolic link.
* `kill -9 -1` will kill every one of your programs, logging you out rather quickly and possibly causing data loss. |
293,532 | People who don't understand Terminal are often afraid to use it for fear that they might mess up their command and crash their computer. Those who know Terminal better know that that's not the case - usually Terminal will just output an error. But are there actually commands that will crash your computer?
WARNING: you could lose data if you type these or copy paste, especially `sudo` and `rm` commands.
================================================================================================== | 2017/07/31 | [
"https://apple.stackexchange.com/questions/293532",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/234283/"
] | Modern macOS makes it *really* hard to crash your machine as an unprivileged user (i.e. without using `sudo`), because UNIX systems are meant to handle thousands of users without letting any of them break the whole system. So, thankfully, you'll usually have to be prompted before you do something that destroys your machine.
Unfortunately, that protection only applies to the system itself. As xkcd illustrates, there's lots of stuff that *you* care about that isn't protected by System Integrity Protection, root privileges or password prompts:
[](https://imgs.xkcd.com/comics/authorization.png)
So, there's tons of stuff you can type in that will just wreck your user account and all your files if you aren't careful. A few examples:
* `rm -rf ${TEMPDIR}/*`. This seems totally reasonable, until you realize that the environment variable is spelt **`TMPDIR`**. `TEMPDIR` is usually undefined, which makes this `rm -rf /`. Even without `sudo`, this will happily remove anything you have delete permissions to, which will usually include your entire home folder. If you let this run long enough, it'll nuke any drive connected to your machine, too, since you usually have write permissions to those.
* `find ~ -name "TEMP*" -o -print | xargs rm`. `find` will normally locate files matching certain criteria and print them out. Without the `-o` this does what you'd expect and deletes every file starting with `TEMP*` (*as long as you don't have spaces in the path*). But, the `-o` means "or" (not "output" as it does for many other commands!), causing this command to actually delete all your files. Bummer.
* `ln -sf link_name /some/important/file`. I get the syntax for this command wrong occasionally, and it will rather happily overwrite your important file with a useless symbolic link.
* `kill -9 -1` will kill every one of your programs, logging you out rather quickly and possibly causing data loss. | Answers that call `sudo` should be considered invalid. These already assume
administrative access to the system.
Try `perl -e 'exit if fork;for(;;){fork;}'`. OSX may have some safeguard against this now. If is presents an apple bubble asking if you want to terminate Terminal app and subprocesses, you're (almost) good.
`while true ; do cat /dev/zero > /dev/null & done` is also very handy, esp. if you don't have `perl`.
`for i in 1 2 3 4 ; do cat /dev/zero > /dev/null & done` will just do a funny little CPU load test. Very good for checking if your heatsink and fan are up to par. |
293,532 | People who don't understand Terminal are often afraid to use it for fear that they might mess up their command and crash their computer. Those who know Terminal better know that that's not the case - usually Terminal will just output an error. But are there actually commands that will crash your computer?
WARNING: you could lose data if you type these or copy paste, especially `sudo` and `rm` commands.
================================================================================================== | 2017/07/31 | [
"https://apple.stackexchange.com/questions/293532",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/234283/"
] | One way to crash a computer is to execute a so called [fork-bomb](https://en.wikipedia.org/wiki/Fork_bomb).
You can execute it on a unix-sytem by:
```
:(){ :|: & };:
```
It's a command that will recursively spawn processes till the OS is so busy it won't respond to any action anymore. | Suppose you don't know what your doing and attempting to do a backup of some hard drive
```
dd if=/dev/disk1 of=/dev/disk2
```
Well if you mix those up (switch if and of), it will overwrite the fresh data with old data, no questions asked.
Similar mix ups can happen with archive utils. And frankly with most command line utilities.
If you want an example of a one character mix up that will crash your system take a look at this scenario: You want to move all the files in the current directory to another one:
```
mv -f ./* /path/to/other/dir
```
Let's accept the fact that you learned to use `./` to denote the current directory. (I do)
Well if you omit the dot, it will start moving *all* your files. Including your system files. You are lucky you didn't sudo this. But if you read somewhere that with 'sudo -i' you will never again have to type in sudo you are logged in as root now. And now your system is eating itself in front of your very eyes.
But again I think stuff like overwriting my precious code files with garbage, because I messed up one character or because I mixed up the order of parameters, is more trouble.
Let's say I want to check out the assembler code that gcc is generating:
```
gcc -S program.c > program.s
```
Suppose I already had a program.s and I use TAB completion. I am in a hurry and forget to TAB twice:
```
gcc -S program.c > program.c
```
Now I have the assembler code in my program.c and no c code anymore.
Which is at least a real setback for some, but to others it's start-over-from-scratch-time.
I think these are the ones that will cause real "harm". I don't really care if my system crashes. I would care about my data being lost.
Unfortunately these are the mistakes that will have to be made until you learn to use the terminal with the proper precautions. |
293,532 | People who don't understand Terminal are often afraid to use it for fear that they might mess up their command and crash their computer. Those who know Terminal better know that that's not the case - usually Terminal will just output an error. But are there actually commands that will crash your computer?
WARNING: you could lose data if you type these or copy paste, especially `sudo` and `rm` commands.
================================================================================================== | 2017/07/31 | [
"https://apple.stackexchange.com/questions/293532",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/234283/"
] | Not sure what you mean about 'crash'ing the computer - if you would re-phrase it to say 'render the computer unusable', then yes. Certainly all it takes is a single stray command - just a moment where you're not thinking clearly about what you're doing, similar to when you speak without thinking, and the damage can be immense and almost immediate. The classic example:
```
$ sudo rm -rf /
```
If you let that command run for even just one second, that can wipe out enough of your system to render it unbootable, and possibly cause irreversible data loss. Don't do it. | I am only a bash beginner, but you could use something like this:
`while True; do COMMAND; done;`
Most people would try to use Ctrl+C to stop the command, not the external process (Ctrl+Z, which then need to be killed).
If the command in the `while True` loop is a resource-intensive operation (such as multiplying large number to its own power), that could mess with your system resources and bog down your processor. However, modern operating systems are usually protected against such catastrophes. |
38,842,591 | I have a mvc devexpress grid, i want to acheive a functionality which when on editing of the grid, one of the column has to be readonly while other changeable.And while adding a new row, all the columsn have to be changeable including the previously said readonly column.
This is my code for the grid
```
@{
var grid = Html.DevExpress().GridView(settings =>
{
settings.Name = "GridViewDuration";
settings.CallbackRouteValues = new { Controller = "DurationMaster", Action = "GridViewDurationPartial" };
settings.SettingsEditing.AddNewRowRouteValues = new { Controller = "MyController", Action = "MyControllerAction1" };
settings.SettingsEditing.UpdateRowRouteValues = new { Controller = "MyController", Action = "MyControllerAction2" };
settings.SettingsEditing.DeleteRowRouteValues = new { Controller = "MyController", Action = "MyControllerAction3" };
settings.SettingsEditing.Mode = GridViewEditingMode.EditFormAndDisplayRow;
settings.SettingsBehavior.ConfirmDelete = true;
settings.CommandColumn.Visible = true;
settings.CommandColumn.ShowNewButton = true;
settings.CommandColumn.ShowDeleteButton = true;
settings.CommandColumn.ShowEditButton = true;
settings.KeyFieldName = "DurationId";
settings.SettingsPager.Visible = true;
settings.SettingsPager.PageSize = 20;
settings.Settings.ShowGroupPanel = true;
settings.Settings.ShowFilterRow = true;
settings.SettingsBehavior.AllowSelectByRowClick = false;
settings.Columns.Add(column =>
{
column.FieldName = "Column1";
column.ReadOnly = true;
column.Width = 20;
});
settings.Columns.Add(column =>
{
column.FieldName = "Column2";
column.Caption = "xyz";
column.ColumnType = MVCxGridViewColumnType.ComboBox;
column.Width = 250;
var comboBoxProperties = column.PropertiesEdit as ComboBoxProperties;
comboBoxProperties.DataSource = PMC.Web.Controllers.DurationMasterController.getSelectList("0", "MyAction4");
comboBoxProperties.TextField = "Text";
comboBoxProperties.ValueField = "Value";
comboBoxProperties.ValueType = typeof(int);
comboBoxProperties.ValidationSettings.RequiredField.IsRequired = true;
});
settings.InitNewRow = (sender, e) =>
{
e.NewValues["ColumnId"] = 0;
};
settings.Columns.Add("ColumnName");
settings.Columns.Add("Description");
//settings.Columns.Add("DisplayName");
settings.Columns.Add(column =>
{
column.Caption = "FromDate";
column.FieldName = "FromDate";
column.ColumnType = MVCxGridViewColumnType.DateEdit;
column.ReadOnly = true;
var DateEditProperties = column.PropertiesEdit as DateEditProperties;
column.CellStyle.Wrap = DefaultBoolean.False;
});
settings.Columns.Add(column =>
{
column.Caption = "ToDate";
column.FieldName = "ToDate";
column.ColumnType = MVCxGridViewColumnType.DateEdit;
var DateEditProperties = column.PropertiesEdit as DateEditProperties;
column.CellStyle.Wrap = DefaultBoolean.False;
});
});
if (ViewData["EditError"] != null)
{
grid.SetEditErrorText((string)ViewData["EditError"]);
}
}
@grid.Bind(Model).GetHtml()
```
And this is what i tried
```
settings.CellEditorInitialize += (s, e) =>
{
var abc = s as ASPxGridView;
e.Editor.ReadOnly = !abc.IsNewRowEditing;
};
```
this sets the all the grid columns in read only, while i only need the `fromDate` column to be `readonly`
Any help would be appreciated. Thanks. | 2016/08/09 | [
"https://Stackoverflow.com/questions/38842591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2368862/"
] | Instead you can use CellEditorInitialize event on your desired column
```
settings.CellEditorInitialize += (s, e) =>
{
var abc = s as ASPxGridView;
if (e.Column.FieldName == "YourFieldName")
e.Editor.ReadOnly = !abc.IsNewRowEditing;
};
``` | I still think you should setup action **MVCxGridViewColumn.SetEditItemTemplateContent** on that specific column.
This is very similar issue to your previews one:
[Set ReadOnly property to a column of devexpress grid(MVC) only on edit click](https://stackoverflow.com/questions/38825706/set-readonly-property-to-a-column-of-devexpress-gridmvc-only-on-edit-click/38829191#38829191)
Please try following solution, it should works :
```
settings.Columns.Add(col =>
{
col.FieldName = "FromDate";
col.Caption = "From Date";
col.Width = Unit.Percentage(15);
col.ColumnType = MVCxGridViewColumnType.DateEdit;
col.SetEditItemTemplateContent(e =>
{
var fromDate = DateTime.Now;
ViewContext.Writer.Write(
Html.DevExpress().DateEdit(settingsDateEdit =>
{
settingsDateEdit.Name = "fromDate";
settingsDateEdit.Width = Unit.Percentage(100);
settingsDateEdit.ReadOnly = !e.Grid.IsNewRowEditing;
}).Bind(fromDate).GetHtml()
);
});
});
``` |
32,608,150 | I have the following string:
```
"Failed verification. \n Selected: First Name; Andrew; Last Name; Drew; correct options: First Name; Matt; Last Name; Darr;
```
I want to create array with data from this string that will look like this:
```
[ ["Andrew", "Matt"], ["Drew", "Darr"] ]
```
first key in array is selected option and the second one is correct option. Is there any way to do it with regex?
EDIT:
I was thinking about this a little bit and my string will look like this:
```
"Failed verification. \n Selected: First Name; Andrew; Last Name; Drew; School; selected school; correct options: First Name; Matt; Last Name; Darr; School; Correct school"
```
And the result I want to have is:
```
[ ["Andrew", "Matt"], ["Drew", "Darr"], ["selected school", "Correct school"] ]
``` | 2015/09/16 | [
"https://Stackoverflow.com/questions/32608150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2389501/"
] | spray-routing is build around the concept of [`Directive`](http://spray.io/documentation/1.2.3/spray-routing/key-concepts/directives/).
You can think of a `Directive` as a transformation over an HTTP request.
The cardinality associated with a directive is the number of arguments is passes down the transform chain after performing the transformation.
`Directive0` is a directive that doesn't provide (or extract) any argument.
`Directive1[A]` provides one argument of type `A`.
`Directive[A :: B :: HNil]` provides 2 arguments of types `A` and `B`, or - to be more precise - provides an heterogeneous list made of `A` and `B` (the implementation is a [shapeless's `HList`](https://github.com/milessabin/shapeless)).
Let's take the examples in your code
```
val twoIntParameters: Directive[Int :: Int :: HNil] =
parameters('a.as[Int], 'b.as[Int])
```
You're defining a new directive that extracts two integers from the HTTP request, i.e. has the type `Directive[Int :: Int :: HNil]`.
The implementation simply leverages a directive provided already by spray, i.e. `parameters`.
`parameters` is a directive that allows to extract the query parameters from a HTTP request and convert them to a specific type, in this case `Int` for both parameters.
```
val myDirective: Directive1[String] =
twoIntParameters.hmap {
case a :: b :: HNil => (a + b).toString
}
```
`myDirective` is a directive that extracts one parameter of type `String`.
Its implementation uses the previously defined `twoIntParameters` directive and maps over its result, applying a transformation to it.
In this case we're taking the two `Int`, summing them and turning the result into a `String`.
So, what's with the `hmap`? That's just a way provided by spray of working with Directives that return a shapeless `HList`. `hmap` requires a function that `HList` to anything, in this case a `String`.
`HList`s can be pattern matched over, just like a normal scala `List`, and that's what you're seeing in the example.
Finally, this is just an idea of how directives work from a functional point of view.
If you want to understand the fine details of the DSL syntax, you will have to dig a little further and read about the [Magnet Pattern](http://spray.io/blog/2012-12-13-the-magnet-pattern/). | Here I found a very good workshop.
<https://www.youtube.com/watch?v=XPuOlpWEvmw> |
4,397,600 | here is the example
```
<style>body{color:red;width:200px; }</style>
```
looking to strip the style tag and retrieve the data..but wanaa regx for strip tags and get data between them...someone plz help me... | 2010/12/09 | [
"https://Stackoverflow.com/questions/4397600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/516957/"
] | If this is your css:
```
<style>
body{
color:red;
width:200px;
}
</style>
```
Then you can *reliably* get the body's width like this:
```
$('body').css('width');
```
Try it: <http://jsfiddle.net/3SkY5/1/>
See <http://api.jquery.com/css/> | ```
$('style:first').html();
```
... for instance. Modify as needed.
I don't think regular expressions will be the best solution here. As somebody else will doubtlessly explain to you in a link, html is not regular. |
4,397,600 | here is the example
```
<style>body{color:red;width:200px; }</style>
```
looking to strip the style tag and retrieve the data..but wanaa regx for strip tags and get data between them...someone plz help me... | 2010/12/09 | [
"https://Stackoverflow.com/questions/4397600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/516957/"
] | If this is your css:
```
<style>
body{
color:red;
width:200px;
}
</style>
```
Then you can *reliably* get the body's width like this:
```
$('body').css('width');
```
Try it: <http://jsfiddle.net/3SkY5/1/>
See <http://api.jquery.com/css/> | Can you try this:
```
$('style').html();
``` |
29,647,529 | When I send email from my application using the default WildFly mail session, the auto-generated message ID gives away that my server is WildFly:
```
Message-ID: <524672585.11.1429091886393.JavaMail.wildfly@myserver.example.com>
```
For security reasons, I'd like to suppress or override the `wildfly` substring in the message ID.
Is there a configuration element or a system property to do that? | 2015/04/15 | [
"https://Stackoverflow.com/questions/29647529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338614/"
] | See [How do I specify the exit code of a console application in .NET?](https://stackoverflow.com/questions/155610/how-do-i-specify-the-exit-code-of-a-console-application-in-net), [MSDN: Main() Return Values (C# Programming Guide)](https://msdn.microsoft.com/en-us/library/0fwzzxz2.aspx) and [.NET Global exception handler in console application](https://stackoverflow.com/questions/3133199/net-global-exception-handler-in-console-application).
The dialog is shown because you don't catch an exception. You need to combine everything shown there, so:
```
class Program {
static void Main(string[] args) {
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
// Your code here
throw new Exception("Kaboom");
}
static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) {
Console.WriteLine(e.ExceptionObject.ToString());
Environment.Exit(1);
}
}
```
And:
```
@echo off
TestExceptionApp
@if "%ERRORLEVEL%" == "0" goto good
:fail
echo Execution Failed
echo return value = %ERRORLEVEL%
goto end
:good
echo Execution succeeded
echo Return value = %ERRORLEVEL%
goto end
:end
``` | You'll have to write a separate program that creates a new process that catches the error. When the catch is made you can send notification to yourself in the catch statement before the error handling notification.
It will likely need to run as a separate program called from the local user's system. |
1,241,265 | I am trying to use xdotool over ssh on Ubuntu 20.04 LTS. It works perfectly from within a terminal window when logged in locally, but over ssh it displays the following error from using any command:
```
$ xdotool click 1
Error: Can't open display: (null)
Failed creating new xdo instance
```
Looking up this error the [fix people suggest](https://askubuntu.com/questions/235126/simulate-media-keys-in-terminal/235181#235181) is exporting the DISPLAY variable before running it, but for me this only leads to a new line added to the error message:
```
$ export DISPLAY=:0.0 && xdotool click 1
No protocol specified
Error: Can't open display: (null)
Failed creating new xdo instance
```
Looking for "No protocol specified" errors for xdotool the [only other suggestion](https://unix.stackexchange.com/questions/391357/run-command-on-user-display-as-root-isnt-working-as-expected) I've been able to find is also adding `export XAUTHORITY=/home/[username]/.Xauthority` to the command as well but that makes no difference for me. It's probably worth noting that I don't have an .Xauthority file in my home directory either (and creating an empty one just to see if it made a difference did not help). I'm not really familiar with X server stuff so I don't know if these things have changed since the results I'm finding where written.
I would appreciate any advice in trying to get this to work.
---
Solved: As pointed out by N0rbert I was missing the -X option when connecting over SSH. That's all I needed to include. | 2020/05/19 | [
"https://askubuntu.com/questions/1241265",
"https://askubuntu.com",
"https://askubuntu.com/users/-1/"
] | You have to run `ssh` with `-X` option like below:
```
ssh -X user@hostname
```
and then execute "graphical" commands as usual. | The thing is this will control the system that is connected via SSH and not the Host you want to Control.
For a example I login with the ssh -X server@192.192.192.192 and then tell xdotool to move the mouse instead of moving the mouse on the Server it moves the mouse on the client that is connected. |
59,671,983 | I am trying to create a connection manager in Microsoft SQL Server Data Tools for Visual Studio 2017 (SSDT) for an integration services project.
In the **Connection Manager**:
1. The Provider is set to: **Native OLE DB\SQL Server Naive Client 11.0**
2. The Server name is set to: the name of the **local machine**
3. Log on to the server is set to: **Windows Authentication**
4. Connect to a database is set to: Select or enter a database name. However no database names appear in the drop down box - the drop down box is blank. I am expecting the name of the database i am working on, including the master database etc to be present.
5. When I Test Connection, I get an error message which says:
'*Test connection failed because of an error in initializing provider. Login timeout expired
A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online.
Named Pipes Provider: Could not open a connection to SQL Server [2]..*'
I am using SQL Server 2017 and Microsoft SQL Server Management Studio 18.
Allow remote connections has been ticked in SSMS.
The only thing i can see is the SQL Server Agent and SQL Server Browser has stopped / is not running and the TCP/IP Protocols for SQLEXPRESS is set to disabled - I am unable to enable it without a further Access is denied (0x80070005) error.
I have tried to follow all of the guides but cannot progress. Could somebody please offer some further guidance? | 2020/01/09 | [
"https://Stackoverflow.com/questions/59671983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12685290/"
] | I have resolved the issue. It was an extremely silly oversight! On installation, the server name in the Visual Studio 17 Connection Manager was listed as: *Local MachineName* only. In SQL Server, the Server Name was listed as: *LocalMachineName*\SQLEXPRESS. The Server Name in VS17 has to be exactly the same as SQL Server. As i said, this is a very silly oversight on my part but have documented for future reference. | SQL Server Configuration Manager ==> SQL Server Services(Left sidebar) ==> Right Click and Start all Stopped services |
3,680,022 | Prove that if $x$ is a real number such that $x(x + 1)>2$, then $x <−2$ or $x > 1$.
I think this is easy to prove by contrapositive, and thus,
if $x\ge -2$ and $x\le{1}$, then $x(x+1)\le 2$.
Notice that $ x(x+1)=x^2+x$ and that $x^2\ge{0}$ for all $x$ in the real numbers.
Since $-2\le{x}\le{1}$ implies $x^2\le 4$.
Now I am stuck. How can I show that this is always less than $2$? | 2020/05/18 | [
"https://math.stackexchange.com/questions/3680022",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/789642/"
] | The fact that the $D$ matrix is diagonal makes the problem much easier. The Lagrangian is:
$$L(x,y) = ||x-z||\_2^2 + y\left(x^TDx-1\right)$$
so the KKT conditions are:
$$(x\_i-z\_i) + yd\_i x\_i = 0 \quad \forall i$$
$$x^TDx = 1$$
The stationarity condition can also be expressed as:
$$x\_i = \frac{z\_i}{1+yd\_i}.$$
This simple expression is only possible because $D$ is diagonal, which gave rise to the term $yd\_ix\_i$. Due to symmetry, you know $x\_i^\*$ has the same sign as $z\_i$, so $y\geq -1/(\max\_i d\_i)$. Note that $y=0$ is impossible (it leads to $x^T D x = z^TDz <1$), and that $y>0$ implies $|x\_i| \leq |z\_i| \; \forall i$ which is also not possible, so $y<0$ All that's left is finding $y$ for which $-1/(\max\_i d\_i) \leq y < 0$ and
$$\sum\_i d\_i \left( \frac{z\_i}{1+y d\_i}\right)^2 = 1.$$
Since the left hand side is monotonously decreasing in $y$, you can use bisection search. | One way to look at this problem is from a bounding perspective, although it only gives insight into the optimal distance $\|x^\*-z\|\_2$, and not necessarily localization information of $x^\*$ itself in general.
In particular, note that we can define a lifted variable $X=xx^\top$. Then the left side of the constraint can be rewritten as
\begin{equation\*}
x^\top Dx = \text{tr}(x^\top Dx) = \text{tr}(Dxx^\top) = \text{tr}(DX).
\end{equation\*}
Similarly, the objective can be written as
\begin{equation\*}
\|x-z\|\_2^2 = x^\top x - 2z^\top x + z^\top z = \text{tr}(X)-2z^\top x + z^\top z.
\end{equation\*}
Therefore, the projection problem is equivalent to the following:
\begin{equation\*}
\begin{aligned}
&\underset{x\in\mathbb{R}^n,X\in\mathbb{S}^n}{\text{minimize}} && \text{tr}(X)-2z^\top x + z^\top \\
&\text{subject to} && \text{tr}(DX)=1, \\
&&& X=xx^\top.
\end{aligned}
\end{equation\*}
Under this reformulation, the objective is affine, and the old equality constraint is also affine. However, the nonconvexity has been absorbed into the new constraint $X=xx^\top$. If you relax this constraint to $X\succeq xx^\top$, the problem becomes convex, since $f\colon\mathbb{R}^n\to\mathbb{S}^n$ defined by $f(x,X)=xx^\top-X$ is cone-convex with respect to the positive semidefinite cone. Indeed, using Schur complements, we can further rewrite the condition that $X-xx^\top\succeq 0$ as
\begin{equation\*}
\begin{bmatrix}
1 & x^\top \\
x & X
\end{bmatrix} \succeq 0.
\end{equation\*}
Since we've introduced a relaxation of your original problem, we conclude that the following (convex) semidefinite programming problem lower bounds your original problem:
\begin{equation\*}
\begin{aligned}
&\underset{x\in\mathbb{R}^n,X\in\mathbb{S}^n}{\text{minimize}} && \text{tr}(X)-2z^\top x + z^\top \\
&\text{subject to} && \text{tr}(DX)=1, \\
&&& \begin{bmatrix}
1 & x^\top \\
x & X
\end{bmatrix} \succeq 0.
\end{aligned}
\end{equation\*}
Note that in the case the final constraint is active at optimum, i.e., $X^\*=x^\*x^{\*\top}$, you can conclude that $x^\*$ solves the original nonconvex problem.
For the other side of things, you can upper bound the optimal value by looking at the eigenvalues of $D$. In particular, the eigenvalues of $D$ are precisely the diagonal elements of $D$ (since it is a diagonal matrix per your assumption). Without loss of generality, let us assume $d\_1\ge d\_2\ge \cdots \ge d\_n$. Then the eigenvector associated with eigenvalue $d\_i$ is $e\_i$, the $i$th standard basis vector. Let $x=\frac{1}{\sqrt{d\_i}}e\_i$. Then we remark that $x$ is feasible for your original optimization problem, since
\begin{equation\*}
x^\top Dx = \frac{1}{d\_i}e\_i^\top De\_i = \frac{1}{d\_i}e\_i^\top (d\_i e\_i) = e\_i^\top e\_i = 1.
\end{equation\*}
The corresponding objective value is
\begin{equation\*}
\|x-z\|\_2^2 = \left\|\frac{1}{\sqrt{d\_i}}e\_i - z\right\|\_2^2.
\end{equation\*}
This value trivially upper bounds the optimal objective value of the minimization problem. Since this holds for all $i\in\{1,2,\dots,n\}$, we conclude that the following upper bounds the optimal value of the problem:
\begin{equation\*}
\min\_{i\in\{1,2,\dots,n\}}\left\|\frac{1}{\sqrt{d\_i}}e\_i - z\right\|\_2^2.
\end{equation\*}
With a bit more work, it may be possible to tighten these bounds, or even reformulate your problem differently so as to find an exact solution. I hope this helps give you some ideas. |
66,456 | My longtable exceeds the page length. Any help would be highly appreciated.
```
\documentclass[11pt,a4paper,oneside]{report}
\usepackage{fontenc}
\usepackage{setspace}
\usepackage{array}
\usepackage{covington}
\usepackage{pslatex}
\usepackage{float}
\usepackage{longtable}
\usepackage{booktabs}
\newcolumntype{R}{>{\raggedleft\arraybackslash}p{2cm}}
\usepackage{tocvsec2}
\setcounter{secnumdepth}{3}
\setcounter{tocdepth}{3}
\usepackage{colortbl}
\setlength{\evensidemargin}{1.96cm}
\setlength{\topmargin}{3.5 cm}
\setlength{\headheight}{1.36cm}
\setlength{\headsep}{1.00cm}
\setlength{\textheight}{20.84cm}
\setlength{\textwidth}{14.5cm}
\setlength{\marginparsep}{1mm}
\setlength{\marginparwidth}{3cm}
\setlength{\footskip}{2.36cm}
\usepackage{graphicx}
\usepackage{titlesec}
\usepackage[bottom,norule]{footmisc}
\usepackage[tableposition=t]{caption}
\usepackage[danish,english]{babel}
\usepackage{natbib}
\bibpunct{(}{)}{,}{a}{}{,}
\usepackage[a4paper]{geometry}
\geometry{top=4cm, bottom=3.5cm, left=5cm, right=3.5cm}
\footskip = 30pt
\renewcommand{\bibname}{References}
\usepackage[toc,page]{appendix}
\usepackage{longtable}
\usepackage[hidelinks]{hyperref}
\usepackage{bookmark}
\usepackage[bitstream-charter]{mathdesign}
\usepackage[T1]{fontenc}
\usepackage{multirow}
\usepackage{lscape}
\begin{document}
\newpage
\chapter{Data Collection}
\section{California Cities Selected and Represented in the Present Study}
\subsection{Cities Selection Method}
Northern California includes forty-eight counties, thirty-eight of which are represented in this study (see following sections for a complete list of included counties).
Alpine County, Colusa County, Inyo County, Mariposa County, Modoc County, Mono County, Napa County, Plumas County, Sierra County, and Sutter County are not represented in this study.
In fact, we could not find online newspapers based in those counties that were suitable for the present research.
\newpage
\subsection{The North Coast Region}
\begin{figure}
\centering
\rule{4.88in}{4in}\caption{Map of the North Coast Region.\label{fig:North Coast Region}}
\end{figure}
The North Coast of California is a rural area that stretches on the Pacific coast from San Francisco Bay north to the Oregon border and includes Del Norte, Humboldt, Trinity, and Mendocino counties. Within the region there is no city with a population of over 100,000.
According to Bright (1971), in 1870 the population of the North Coast region included eleven percent of immigrants from New York, nine percent from Missouri; three percent from Maine; and two percent from Ohio (see Appendix for details).
%(White \%, Black or African American \%, Hispanic or Latino \%, Asian \%, Other \%). The median age of the population in Del Norte County is - years old.
\begin{longtable}{l r l r r}
\caption{Description of the Counties in the The North Coast Region\label{Description of the Counties in the The North Coast Region}}\\
\toprule
\textsc{County}&\textsc{Founded}&\textsc{Seat}&\textsc{Area (sqm)}&\textsc{Pop 2010}\\
\midrule
\endfirsthead
\caption[]{(continued)}\\
\toprule
\textsc{County}&\textsc{Founded}&\textsc{Seat}&\textsc{Area (sqm)}&\textsc{Pop 2010}\\
\midrule
\endhead
\bottomrule
\endlastfoot
Del Norte&1857&Crescent City&1,008&7,643\\
Humboldt&1853&Eureka&3,573&27,191\\
Lake&1861&Lakeport&1,258&4,753\\
Mendocino&1850&Ukiah&3,509&16,075\\
Trinity&1850&Weaverville&3,179&3,600\\
\end{longtable}
\begin{longtable}{l l l}
\caption{Coverage for The North Coast Region\label{Coverage for The North Coast Region}}\\
\toprule
\textsc{County Name}&\textsc{City}&\textsc{Online Newspaper}\\
\midrule
\endfirsthead
\caption[]{(continued)}\\
\toprule
\textsc{County Name}&\textsc{City}&\textsc{Online Newspaper}\\
\toprule
\endhead
\bottomrule
\endlastfoot
Del Norte&Crescent City&Daily Triplicate\\
Humboldt&Eureka&Eureka Times-Standard\\
Lake&Lakeport&Lake County News\\
Mendocino&Ukiah&Ukiah Daily Journal\\
&Willits&Willits News\\
Trinity&Weaverville&Trinity Journal\\
\end{longtable}
\end{document}
``` | 2012/08/09 | [
"https://tex.stackexchange.com/questions/66456",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/17205/"
] | You should try to provide a minimum working example (MWE) instead of your full preamble and content. Also the comments of @hakaze above.
However, you should provide the placement options `[htbp]` to the `figure` environment so as to enable LaTeX to conveniently place your figure. With `\begin{figure}[htbp]`, your problem can be solved.
```
\documentclass[11pt,a4paper,oneside]{report}
\usepackage{fontenc}
\usepackage{setspace}
\usepackage{array}
\usepackage{longtable}
\usepackage{booktabs}
\newcolumntype{R}{>{\raggedleft\arraybackslash}p{2cm}}
\usepackage{graphicx}
\usepackage[a4paper]{geometry}
\geometry{top=4cm, bottom=3.5cm, left=5cm, right=3.5cm}
\footskip = 30pt
\begin{document}
\newpage
\chapter{Data Collection}
\section{California Cities Selected and Represented in the Present Study}
\subsection{Cities Selection Method}
Northern California includes forty-eight counties, thirty-eight of which are represented in this study (see following sections for a complete list of included counties).
Alpine County, Colusa County, Inyo County, Mariposa County, Modoc County, Mono County, Napa County, Plumas County, Sierra County, and Sutter County are not represented in this study.
In fact, we could not find online newspapers based in those counties that were suitable for the present research.
\newpage
\subsection{The North Coast Region}
\begin{figure}[htbp]
\centering
\rule{4.88in}{4in}\caption{Map of the North Coast Region.\label{fig:North Coast Region}}
\end{figure}
The North Coast of California is a rural area that stretches on the Pacific coast from San Francisco Bay north to the Oregon border and includes Del Norte, Humboldt, Trinity, and Mendocino counties. Within the region there is no city with a population of over 100,000.
According to Bright (1971), in 1870 the population of the North Coast region included eleven percent of immigrants from New York, nine percent from Missouri; three percent from Maine; and two percent from Ohio (see Appendix for details).
%(White \%, Black or African American \%, Hispanic or Latino \%, Asian \%, Other \%). The median age of the population in Del Norte County is - years old.
\begin{longtable}{l r l r r}
\caption{Description of the Counties in the The North Coast Region\label{Description of the Counties in the The North Coast Region}}\\
\toprule
\textsc{County}&\textsc{Founded}&\textsc{Seat}&\textsc{Area (sqm)}&\textsc{Pop 2010}\\
\midrule
\endfirsthead
\caption[]{(continued)}\\
\toprule
\textsc{County}&\textsc{Founded}&\textsc{Seat}&\textsc{Area (sqm)}&\textsc{Pop 2010}\\
\midrule
\endhead
\bottomrule
\endlastfoot
Del Norte&1857&Crescent City&1,008&7,643\\
Humboldt&1853&Eureka&3,573&27,191\\
Lake&1861&Lakeport&1,258&4,753\\
Mendocino&1850&Ukiah&3,509&16,075\\
Trinity&1850&Weaverville&3,179&3,600\\
\end{longtable}
\begin{longtable}{l l l}
\caption{Coverage for The North Coast Region\label{Coverage for The North Coast Region}}\\
\toprule
\textsc{County Name}&\textsc{City}&\textsc{Online Newspaper}\\
\midrule
\endfirsthead
\caption[]{(continued)}\\
\toprule
\textsc{County Name}&\textsc{City}&\textsc{Online Newspaper}\\
\toprule
\endhead
\bottomrule
\endlastfoot
Del Norte&Crescent City&Daily Triplicate\\
Humboldt&Eureka&Eureka Times-Standard\\
Lake&Lakeport&Lake County News\\
Mendocino&Ukiah&Ukiah Daily Journal\\
&Willits&Willits News\\
Trinity&Weaverville&Trinity Journal\\
\end{longtable}
\end{document}
``` | This answer is posted in response to some questions the OP posted to earlier comments. The main point of this posting is to demonstrate that it's possible to create the exact same layout of a "short" table, i.e., one that fits on a single page, using either the `longtable` environment or the `table`/`tabular` environments.
As you compare the differences in code, you'll notice that the each type has some advantages and some disadvantages in terms of "overhead" that's needed to get it going. For instance, a `longtable` requires you to be diligent about providing formats for the table's headers and footers for both the first (last) page and for the remaining pages. Of course, you only need to provide this information once for a `tabular` environment. However, for a `tabular` environment you need to remember to provide the `\centering` instruction in case you want the material centered, and you need to remember to provide a `[h]` placement specifier if you want to override LaTeX's float placement algorithm. In contrast, a `longtable` environment will always try to start "right here", i.e., a `[h]` specifier is built in.
In the end, I don't think differences in table-creating overhead should determine whether you use one form or the other. Rather, assuming the table fits on a single page, you should decide whether the material of the table should be allowed to be broken across pages or not. If it's supposed to be kept together, you should *not* use a `longtable` environment in any case.
```
\documentclass[11pt,a4paper,oneside]{report}
\usepackage[a4paper,margin=1in]{geometry}
\usepackage{longtable,booktabs}
\setlength\belowcaptionskip{1\baselineskip} % or whatever is required
\begin{document}
\begin{longtable}{l r l r r}
\caption{Description of Counties in North Coast Region} \label{tab:description1}\\
\toprule
\textsc{County}&\textsc{Founded}&\textsc{Seat}&\textsc{Area (sqm)}&\textsc{Pop 2010}\\
\midrule
\endfirsthead
\multicolumn{3}{l}{(continued)}\\
\toprule
\textsc{County}&\textsc{Founded}&\textsc{Seat}&\textsc{Area (sqm)}&\textsc{Pop 2010}\\
\midrule
\endhead
\bottomrule
\endlastfoot
Del Norte&1857&Crescent City&1,008&7,643\\
Humboldt&1853&Eureka&3,573&27,191\\
Lake&1861&Lakeport&1,258&4,753\\
Mendocino&1850&Ukiah&3,509&16,075\\
Trinity&1850&Weaverville&3,179&3,600\\
\end{longtable}
\begin{table}[h]
\caption{Description of Counties in North Coast Region} \label{tab:description2}
\centering
\begin{tabular}{l r l r r}
\toprule
\textsc{County}&\textsc{Founded}&\textsc{Seat}&\textsc{Area (sqm)}&\textsc{Pop 2010}\\
\midrule
Del Norte&1857&Crescent City&1,008&7,643\\
Humboldt&1853&Eureka&3,573&27,191\\
Lake&1861&Lakeport&1,258&4,753\\
Mendocino&1850&Ukiah&3,509&16,075\\
Trinity&1850&Weaverville&3,179&3,600\\
\bottomrule
\end{tabular}
\end{table}
%% second table
\begin{longtable}{l l l}
\caption{Coverage for the North Coast Region}
\label{tab:coverage1}\\
\toprule
\textsc{County Name}&\textsc{City}&\textsc{Online Newspaper}\\
\midrule
\endfirsthead
\multicolumn{3}{l}{(continued)}\\
\toprule
\textsc{County Name}&\textsc{City}&\textsc{Online Newspaper}\\
\toprule
\endhead
\bottomrule
\endlastfoot
Del Norte&Crescent City&Daily Triplicate\\
Humboldt&Eureka&Eureka Times-Standard\\
Lake&Lakeport&Lake County News\\
Mendocino&Ukiah&Ukiah Daily Journal\\
&Willits&Willits News\\
Trinity&Weaverville&Trinity Journal\\
\end{longtable}
\begin{table}[h]
\caption{Coverage for the North Coast Region}
\label{tab:coverage2}
\centering
\begin{tabular}{ l l l }
\toprule
\textsc{County Name}&\textsc{City}&\textsc{Online Newspaper}\\
\midrule
Del Norte&Crescent City&Daily Triplicate\\
Humboldt&Eureka&Eureka Times-Standard\\
Lake&Lakeport&Lake County News\\
Mendocino&Ukiah&Ukiah Daily Journal\\
&Willits&Willits News\\
Trinity&Weaverville&Trinity Journal\\
\bottomrule
\end{tabular}
\end{table}
\end{document}
```
 |
5,933,025 | The following yields 6000:
```
firstLabel.text = [[NSString alloc] initWithFormat:@"%f",(6*pow(10,3))];
```
How can this be made to display the number in scientific notation, like `6 x 10^3` or `6e3`? | 2011/05/09 | [
"https://Stackoverflow.com/questions/5933025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/744592/"
] | <http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html>
in short you want %e. | Look at [NSNumberFormatter](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNumberFormatter_Class/Reference/Reference.html) and NSNumberFormatterScientificStyle.
```
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterScientificStyle];
NSString *formattedNumber = [formatter stringFromNumber:someNSNumber];
```
And yes, release your formatter. |
2,821 | I met by chance one of the original/foundational SO developers at a bar the other day. He told me it had been a long day and he needed a beer. After talking I hopped on 'meta' later and saw the whole uproar over things related to moderators, community, etc. and understood a bit more about why it had been a long day for him.
What I saw was a lot of conflict about how SO is percieved as treating moderators. But in here it seems pretty quiet on the topic.
Does the topic at hand bother anyone? Maybe better as a chat topic, but meta is full of "chat topic" posts so I'm using it as my example a bit.
PS
If you don't know what I'm talking about, then that's fine - in fact it's a sign that the conflict going on in <https://meta.stackexchange.com/> has indeed not showed up on your radar. | 2019/10/07 | [
"https://gamedev.meta.stackexchange.com/questions/2821",
"https://gamedev.meta.stackexchange.com",
"https://gamedev.meta.stackexchange.com/users/3830/"
] | I'd say, the question you can ask yourself is, will others benefit by the changes? It's not only OP that people are helping by answering, but future readers as well.
I saw this answer when it was posted, and I was really confused about what it is trying to do. I agree with you that it could use a lot of work to make it readable, but if the OP is new on C# and wouldn't understand the changes, they would just ignore them.
I've seen answers before addressing this in a way to satisfy both the OP and other readers. Simply answer the question, being as straightforward as possible without altering the code a lot. After that, you can have some extra information, something like "It would be better if you did X and Y in your code, as it makes it better because of reasons A and B".
This way, the OP can read the new information, and possibly benefit from them, or just focus on the solution, which might be more time-critical for them. But future readers can see both the solution and possible ways of making the code even better.
In this specific case however, I think your code might look too complex for OP. On that question I left a comment because I'm still not sure what OP is trying to achieve.
Keep in mind there's always the [CodeReview StackExchange](https://codereview.stackexchange.com/), for people looking to improve their code. | My answer will go along the lines of [TomTsagk](https://gamedev.meta.stackexchange.com/a/2819/40264), but will end differently:
1. provide the straight answer to their question;
2. add an horizontal line (`blank line` + `---`);
3. tell them that you think of ways of making their code "more optimal";
4. describe what you think;
5. provide the code;
6. comment the code, explain what's going on.
Although they might not have a grasp of what you suggest *now*, your techniques and the code you use could get them intrigued and curious about new approaches. |
2,821 | I met by chance one of the original/foundational SO developers at a bar the other day. He told me it had been a long day and he needed a beer. After talking I hopped on 'meta' later and saw the whole uproar over things related to moderators, community, etc. and understood a bit more about why it had been a long day for him.
What I saw was a lot of conflict about how SO is percieved as treating moderators. But in here it seems pretty quiet on the topic.
Does the topic at hand bother anyone? Maybe better as a chat topic, but meta is full of "chat topic" posts so I'm using it as my example a bit.
PS
If you don't know what I'm talking about, then that's fine - in fact it's a sign that the conflict going on in <https://meta.stackexchange.com/> has indeed not showed up on your radar. | 2019/10/07 | [
"https://gamedev.meta.stackexchange.com/questions/2821",
"https://gamedev.meta.stackexchange.com",
"https://gamedev.meta.stackexchange.com/users/3830/"
] | I'd say, the question you can ask yourself is, will others benefit by the changes? It's not only OP that people are helping by answering, but future readers as well.
I saw this answer when it was posted, and I was really confused about what it is trying to do. I agree with you that it could use a lot of work to make it readable, but if the OP is new on C# and wouldn't understand the changes, they would just ignore them.
I've seen answers before addressing this in a way to satisfy both the OP and other readers. Simply answer the question, being as straightforward as possible without altering the code a lot. After that, you can have some extra information, something like "It would be better if you did X and Y in your code, as it makes it better because of reasons A and B".
This way, the OP can read the new information, and possibly benefit from them, or just focus on the solution, which might be more time-critical for them. But future readers can see both the solution and possible ways of making the code even better.
In this specific case however, I think your code might look too complex for OP. On that question I left a comment because I'm still not sure what OP is trying to achieve.
Keep in mind there's always the [CodeReview StackExchange](https://codereview.stackexchange.com/), for people looking to improve their code. | I've done this before, and typically the following applies:
* If the provided code is OK, barring that it might benefit from some refactoring, then I prefer to leave it be. The OP might be aware of this, or doing it this way for other reasons we don't immediately know about.
+ The classic example of this in a Gamedev context might be someone who posts code using OpenGL immediate mode; a reply that focusses on "don't use immediate mode, use buffer objects", although correct and good advice, is probably actually *not very helpful* in terms of solving the problem.
* If there are other things obviously wrong with the code that would prevent the OP from achieving what they wish to do, then it would be a disservice to the OP to not at least point it out.
+ It may be appropriate to encourage the OP to ask a bunch of extra questions about these hypothetical other wrong things, rather than going down too much of a rabbit hole in your answer to their original question.
Finally, one should always remember that one may not be seeing the *actual* code in a question. Remember that:
>
> Questions about debugging a problem must provide a *minimal, complete, verifiable example* of the issue...
>
>
>
The code that is posted may therefore be this example, with idiomatic correctness perhaps being of lower priority than illustrating the problem. |
2,821 | I met by chance one of the original/foundational SO developers at a bar the other day. He told me it had been a long day and he needed a beer. After talking I hopped on 'meta' later and saw the whole uproar over things related to moderators, community, etc. and understood a bit more about why it had been a long day for him.
What I saw was a lot of conflict about how SO is percieved as treating moderators. But in here it seems pretty quiet on the topic.
Does the topic at hand bother anyone? Maybe better as a chat topic, but meta is full of "chat topic" posts so I'm using it as my example a bit.
PS
If you don't know what I'm talking about, then that's fine - in fact it's a sign that the conflict going on in <https://meta.stackexchange.com/> has indeed not showed up on your radar. | 2019/10/07 | [
"https://gamedev.meta.stackexchange.com/questions/2821",
"https://gamedev.meta.stackexchange.com",
"https://gamedev.meta.stackexchange.com/users/3830/"
] | My answer will go along the lines of [TomTsagk](https://gamedev.meta.stackexchange.com/a/2819/40264), but will end differently:
1. provide the straight answer to their question;
2. add an horizontal line (`blank line` + `---`);
3. tell them that you think of ways of making their code "more optimal";
4. describe what you think;
5. provide the code;
6. comment the code, explain what's going on.
Although they might not have a grasp of what you suggest *now*, your techniques and the code you use could get them intrigued and curious about new approaches. | I've done this before, and typically the following applies:
* If the provided code is OK, barring that it might benefit from some refactoring, then I prefer to leave it be. The OP might be aware of this, or doing it this way for other reasons we don't immediately know about.
+ The classic example of this in a Gamedev context might be someone who posts code using OpenGL immediate mode; a reply that focusses on "don't use immediate mode, use buffer objects", although correct and good advice, is probably actually *not very helpful* in terms of solving the problem.
* If there are other things obviously wrong with the code that would prevent the OP from achieving what they wish to do, then it would be a disservice to the OP to not at least point it out.
+ It may be appropriate to encourage the OP to ask a bunch of extra questions about these hypothetical other wrong things, rather than going down too much of a rabbit hole in your answer to their original question.
Finally, one should always remember that one may not be seeing the *actual* code in a question. Remember that:
>
> Questions about debugging a problem must provide a *minimal, complete, verifiable example* of the issue...
>
>
>
The code that is posted may therefore be this example, with idiomatic correctness perhaps being of lower priority than illustrating the problem. |
18,066,847 | ```
DWORD baseAddress = (DWORD) GetModuleHandle(NULL);
```
If I put that code into a DLL and inject it to a process, that seems to equal the base address of the injected process.
How does that work exactly? How does the cast from HMODULE to DWORD work? Would it work if I cast it to void\* instead of DWORD? | 2013/08/05 | [
"https://Stackoverflow.com/questions/18066847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2654180/"
] | This is an implementation detail of the 32-bit and 64-bit version of Windows. HMODULE is older than that, in the 16-bit version of Windows they were true handles. That was not necessary anymore in win32, the virtual memory address at which a module is loaded uniquely identifies the module. So using the VM address was preferable, no need to keep it in a handle table.
This does mean that you can't cast to DWORD, not good enough to store a virtual memory address on the 64-bit version. You'll need to use DWORD\_PTR. | It works because Windows just happened to use the base address as an identifying handle, and because on a 32-bit system an address fits into a DWORD. Since Windows isn't required to do that, you shouldn't rely on it for anything. |
21,902,734 | I am developing on OS X. For testing I am using VirtualBox with windows VMs from <http://www.modern.ie/en-us/virtualization-tools#downloads>
When testing my web applications, should I be testing in IE10 on both Win7 *and* Win8, or can I safely assume that IE10 behaves identically on both platforms and only test on Win7? And the same question goes for IE11. | 2014/02/20 | [
"https://Stackoverflow.com/questions/21902734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/250605/"
] | No, they are not identical, but they should be the same for the common features that both support. IE10 and 11 on Windows 8 and 8.1 support a number of extra features that are not included on Windows 8. They mostly relate to touch and device hardware support. Windows 8.\* is a touch friendly OS while Win7 is a more traditional OS that does not include robust touch support.
Differences in IE10 for Windows 7:
* The "Touch" token is never included in the UA string
* Gesture DOM events are not fired.
* Scroll, Scrolling Snap Points, and Zooming CSS properties are not supported
* touch-action CSS property is not supported
* `msMaxTouchPoints` returns 0
More details can be found in the [IE10 developer guide](http://msdn.microsoft.com/en-us/library/ie/jj819730%28v=vs.85%29.aspx)
Additionally the following are not supported in IE10 for Xbox One:
* Geolocation API
* prompt() method
* Copy/Paste with JavaScript
* File API
More details can be found in the [Internet Explorer for Xbox One Developer Guide](http://msdn.microsoft.com/en-us/library/ie/dn532261%28v=vs.85%29.aspx)
Differences in IE11 for Windows 7:
* Device Orientation events are not supported
* Touch is not supported for HTML5 Drag and Drop
* Encrypted Media Extensions (DRM) is not supported
* High DPI is not supported (except the `devicePixelRatio` property)
* No Link highlighting
* No Media Source Extensions (media streaming, inc. MPEG Dash)
* Doesn’t support automatic phone number detection (converts phone like numbers into clickable link)
* No support for Screen Orientation API
* No support for SPDY protocol
More details can be found in the [IE11 developer guide](http://msdn.microsoft.com/en-us/library/ie/dn394063%28v=vs.85%29.aspx#unsupported_features) | [Please visit Microsoft IE 10 Dev Guide:](http://msdn.microsoft.com/en-us/library/ie/jj819730%28v=vs.85%29.aspx)
[IE Guide:](http://msdn.microsoft.com/en-us/library/ie/bg125382.aspx) |
44,277,771 | My UI asks for the inputs User\_ID and Supplier\_ID and I wanted a string validation accept inputs for Supplier\_ID like below:
```
1st scenario: 123456
2nd scenario: 123456,098765
3rd scenario: 123456,098765,345678
```
While it should not accept inputs like:
```
1st scenario: Any number less than 6 digits like 123
2nd scenario: Any number more than 6 digits 1234567
3rd scenario: Inputs with comma in the end or even at the beginning - 123456,098765,345678, or ,098765,345678
```
I will use the inputs for Supplier\_ID on this query below:
```
UPDATE ABC.Items
SET Crit_Limit = 'Y'
WHERE User_ID = 'userID'
AND Supplier_ID in (suppID)
```
Variable suppID will carry the inputs from the UI Supplier\_ID, so the query will look like this for example:
```
UPDATE ABC.Items
SET Crit_Limit = 'Y'
WHERE User_ID = '007'
AND Supplier_ID in (123456,098765,345678)
```
Anyway, the field Supplier\_ID has a length 6 and must be numeric.
Thanks in advance! | 2017/05/31 | [
"https://Stackoverflow.com/questions/44277771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8090072/"
] | This pattern matches your test cases, and for any number of 6 digit groups separated by a comma.
```
^\d{6}(,\d{6})*$
``` | this is the expresion you are looking for
```
^\d{6}(\,\d{6}){0,2}$
``` |
44,277,771 | My UI asks for the inputs User\_ID and Supplier\_ID and I wanted a string validation accept inputs for Supplier\_ID like below:
```
1st scenario: 123456
2nd scenario: 123456,098765
3rd scenario: 123456,098765,345678
```
While it should not accept inputs like:
```
1st scenario: Any number less than 6 digits like 123
2nd scenario: Any number more than 6 digits 1234567
3rd scenario: Inputs with comma in the end or even at the beginning - 123456,098765,345678, or ,098765,345678
```
I will use the inputs for Supplier\_ID on this query below:
```
UPDATE ABC.Items
SET Crit_Limit = 'Y'
WHERE User_ID = 'userID'
AND Supplier_ID in (suppID)
```
Variable suppID will carry the inputs from the UI Supplier\_ID, so the query will look like this for example:
```
UPDATE ABC.Items
SET Crit_Limit = 'Y'
WHERE User_ID = '007'
AND Supplier_ID in (123456,098765,345678)
```
Anyway, the field Supplier\_ID has a length 6 and must be numeric.
Thanks in advance! | 2017/05/31 | [
"https://Stackoverflow.com/questions/44277771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8090072/"
] | This pattern matches your test cases, and for any number of 6 digit groups separated by a comma.
```
^\d{6}(,\d{6})*$
``` | Create your regex as searchgroups and check first for a newline followed by 6 digits, and then for `,` followed by 6 digits groups.
```js
['123456',
'123456,098765',
'123456,098765,345678',
'123456,0987s65,345678',
'12345,098765,345678',
'123456/098765'
]
.forEach(function(line) {
if (line.toString().replace(/(^\d{6}(,\d{6})*)/gm, '').length < 1) {
console.log(line, "matches");
} else {
console.log(line, "does not match");
}
});
``` |
54,915,673 | I'm trying to run a Copy URL event using clipboard.js. I have it installed on my server and the reference to clipboard.js is there in my code. So I have this in my footer:
```
<script type="text/javascript">
var url = document.location.href;
new Clipboard('.btn', {
text: function() {
return url;
}
});
</script>
```
And this simply for my button:
```
<button class="btn">Copy</button>
```
Simple. And there's an example on SO that does work:
[Copy URL from browser using clipboard.js](https://stackoverflow.com/questions/37442706/copy-url-from-browser-using-clipboard-js)
But mine is throwing an Illegal Constructor error on my script and I'm really puzzled as to why. Am I forgetting something that's causing this error to appear?
Here's the Stack example: [Copy URL from browser using clipboard.js](https://stackoverflow.com/questions/37442706/copy-url-from-browser-using-clipboard-js)
Here's what I got: <https://dadventuresla.com/copy-link-test/> | 2019/02/27 | [
"https://Stackoverflow.com/questions/54915673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1070096/"
] | Because the value of `castChar` is the integer value `5`, while the value of `realChar` is the *integer encoding of the character value* `'5'` (ASCII 53). These are not the same values.
Casting has nothing to do with it. Or, more accurately, casting `nr` to `char` doesn't give you the *character value* `'5'`, it just assigns the integer value `5` to a narrower type.
If you expect the output `5`, then you need to print `realChar` with the `%c` specifier, not the `%d` specifier. | `(char)5` and `'5'` are not the same thing.
The literal `'5'` is an integer value that represents the character 5. Its value depends on the platform. Assuming ASCII representation for characters, this would be 53.
The literal `(char)5` is the integer value 5 that has been cast to type `char`. This means it retains the value of 5 after the cast. |
60,568,456 | I am using FusionPro to create a gift ask string for an appeal letter based on a donors last gift. The letter is mailed to an area that has a high Jewish population so if a donors last gift is a multiple of 18, the ask string need to be created accordingly and only use multiples of 18. Here is my current script to create ask amounts based off of last gift. How do I work in dealing with multiples of 18?
```
//$Ask2 Round to nearest 5//
function round5(x)
{
return Math.ceil(x/5)*5;
}
var Ask1 = Field("Last Gift ");
var round = (round5(Ask1));
var plus10 = parseInt(round) + StringToNumber("10")
var plus15 = parseInt(round) + StringToNumber("15")
var plus20 = parseInt(round) + StringToNumber("20")
var plus30 = parseInt(round) + StringToNumber("30")
var plus50 = parseInt(round) + StringToNumber("50")
var plus75 = parseInt(round) + StringToNumber("75")
var plus100 = parseInt(round) + StringToNumber("100")
var plus150 = parseInt(round) + StringToNumber("150")
var plus250 = parseInt(round) + StringToNumber("250")
var plus500 = parseInt(round) + StringToNumber("500")
if (StringToNumber(round) == StringToNumber(""))
{
return "250";
}
if (StringToNumber(round) <= StringToNumber("21"))
{
return "45";
}
if (StringToNumber(round) >= StringToNumber("24") && StringToNumber(round) <= StringToNumber("50"))
{
return FormatNumber("#,###", plus20);
}
if (StringToNumber(round) >= StringToNumber("49") && StringToNumber(round) <= StringToNumber("100"))
{
return FormatNumber("#,###", plus20);
}
if (StringToNumber(round) >= StringToNumber("99") && StringToNumber(round) <= StringToNumber("300"))
{
return FormatNumber("#,###", plus75);
}
if (StringToNumber(round) >= StringToNumber("299") && StringToNumber(round) <= StringToNumber("1000"))
{
return FormatNumber("#,###", plus150);
}
if (StringToNumber(round) >= StringToNumber("1000"))
{
return FormatNumber("#,###", plus250);
}
else
return "";
}
//End $Ask2 Rule//
``` | 2020/03/06 | [
"https://Stackoverflow.com/questions/60568456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13020086/"
] | The easiest way to find if any number is evenly divisible by another is to use the mod operator. In many languages, the operator is a % [Reference](https://www.w3schools.com/js/js_arithmetic.asp)
Basically the mod operator gives you the remainder after a division operation. For example
>
> 4 % 2 is 0 7 % 2 is 3 Remainder 1. The result provided would be "1"
> because that is the remainder
>
>
>
```js
var x = 7;
var y = 2;
var z = x % y;
console.log(z);
``` | to find if a number is a multiple of x use the % function
so
```
if (StringToNumber(round) % 18 === 0) {
// Number is a multiple of 18
}
``` |
8,761,665 | **Hello everybody,**
I have a small code in PHP that I would like to convert in Delphi and I have some troubles...
Here is the PHP code :
```
$from = "121.198.0.0";
$to = "121.198.255.255";
$arry1 = explode(".", $from);
$arry2 = explode(".", $to);
$a1 = $arry1[0];
$b1 = $arry1[1];
$c1 = $arry1[2];
$d1 = $arry1[3];
$a2 = $arry2[0];
$b2 = $arry2[1];
$c2 = $arry2[2];
$d2 = $arry2[3];
while ($d2 >= $d1 || $c2 > $c1 || $b2 > $b1 || $a2 > $a1) {
if ($d1 > 255) {
$d1 = 1;
$c1++;
}
if ($c1 > 255) {
$c1 = 1;
$b1++;
}
if ($b1 > 255) {
$b1 = 1;
$a1++;
}
echo "$a1.$b1.$c1.$d1<br>";
$d1++;
}
```
And in Delphi I started with that :
```
procedure TForm1.Button1Click(Sender: TObject);
var
Arry1, Arry2: TStringList;
RangeFrom, RangeTo: string;
a1, b1, c1, d1, a2, b2, c2, d2: string;
begin
RangeFrom := Edit1.Text;
RangeTo := Edit2.Text;
Arry1 := Explode('.', RangeFrom);
Arry2 := Explode('.', RangeTo);
a1 := Arry1[0];
b1 := Arry1[1];
c1 := Arry1[2];
d1 := Arry1[3];
a2 := Arry1[0];
b2 := Arry1[1];
c2 := Arry1[2];
d2 := Arry1[3];
while (StrToInt(d2) >= StrToInt(d1))
//and StrToInt(c2) > (StrToInt(c1)
//and StrToInt(b2) > (StrToInt(b1)
//and StrToInt(a2) > (StrToInt(a1)
do
begin
if (StrToInt(d1) > 255) then
begin
d1 := '1';
StrToInt(c1)+1;
end;
if (StrToInt(c1) > 255) then
begin
c1 := '1';
StrToInt(b1)+1;
end;
if (StrToInt(b1) > 255) then
begin
b1 := '1';
StrToInt(a1)+1;
end;
ListBox1.Items.Add(a1+'.'+b1+'.'+c1+'.'+d1);
StrToInt(d1)+1;
end;
end;
```
(For the Explode function, I use : <http://www.marcosdellantonio.net/2007/06/14/funcao-explode-do-php-em-delphi/>)
Someone can help me to make working this small code in Delphi ?
Thanks in advance :)
Beny | 2012/01/06 | [
"https://Stackoverflow.com/questions/8761665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/778642/"
] | Here's what I can see just by looking at the code:
If think you have the parameters to `Explode` in the wrong order. The separator is the second parameter in the function to which you linked. So you should write:
```
Arry1 := Explode(RangeFrom, '.');
Arry2 := Explode(RangeTo, '.');
```
---
You are leaking memory by not freeing the arrays returned by the `Explode` function. Delphi is different from PHP in that you often have to manage the memory of objects that you create.
---
```
a2 := Arry1[0];
b2 := Arry1[1];
c2 := Arry1[2];
d2 := Arry1[3];
```
These should be `Arry2` rather than `Arry1`.
---
You should convert the strings to integers up front. So declare them like this:
```
a1, b1, c1, d1, a2, b2, c2, d2: Integer;
```
and write the assignments like this:
```
a1 := StrToInt(Arry1[0]);
b1 := StrToInt(Arry1[1]);
//etc. etc.
```
---
```
while ($d2 >= $d1 || $c2 > $c1 || $b2 > $b1 || $a2 > $a1)
```
translates to:
```
while ((d2 >= d1) or (c2 > c1) or (b2 > b1) or (a2 > a1))
```
---
Inside the while loop you want code like this:
```
if d1 > 255 then
begin
d1 := 1;
inc(c1);
end;
```
---
Converting the 4 values back to an IP address is easiest with the `Format` function:
```
ListBox1.Items.Add(Format('%d.%d.%d.%d', [a1, b1, c1, d1]));
```
---
You have a mis-understanding of what `StrToInt` does it is a function that receives as input a string and returns an integer. When you write:
```
StrToInt(d1)+1
```
you are not modifying the variable `d1` which is just an input variable. That issue disappears when you make the other changes I describe, but I wanted to point it out for your future benefit.
---
You may also want to force a periodic repaint of the list box so that you can see what is happening.
---
Put it all together and you have this:
```
var
Arry1, Arry2: TStringList;
RangeFrom, RangeTo: string;
Count: Integer;
a1, b1, c1, d1, a2, b2, c2, d2: Integer;
begin
RangeFrom := Edit1.Text;
RangeTo := Edit2.Text;
Arry1 := Explode(RangeFrom, '.');
try
a1 := StrToInt(Arry1[0]);
b1 := StrToInt(Arry1[1]);
c1 := StrToInt(Arry1[2]);
d1 := StrToInt(Arry1[3]);
finally
Arry1.Free;
end;
Arry2 := Explode(RangeTo, '.');
try
a2 := StrToInt(Arry2[0]);
b2 := StrToInt(Arry2[1]);
c2 := StrToInt(Arry2[2]);
d2 := StrToInt(Arry2[3]);
finally
Arry2.Free;
end;
Count := 0;
while ((d2 >= d1) or (c2 > c1) or (b2 > b1) or (a2 > a1)) do
begin
if d1 > 255 then
begin
d1 := 1;
inc(c1);
end;
if c1 > 255 then
begin
c1 := 1;
inc(b1);
end;
if b1 > 255 then
begin
b1 := 1;
inc(a1);
end;
ListBox1.Items.Add(Format('%d.%d.%d.%d', [a1, b1, c1, d1]));
inc(Count);
if Count mod 1000=0 then begin
ListBox1.Repaint;
ListBox1.TopIndex := ListBox1.Items.Count-1;
end;
inc(d1);
end;
end;
``` | I think the reason it is not doing anything right now is you may not have any values in edit1.text or edit2.text.
For testing (before making this snippet a procedure or function) you could just assign some test data to RangeFrom and RangeTo.
Ex.
RangeFrom := '121.198.0.0';
RangeTo := '121.198.255.255'; |
8,761,665 | **Hello everybody,**
I have a small code in PHP that I would like to convert in Delphi and I have some troubles...
Here is the PHP code :
```
$from = "121.198.0.0";
$to = "121.198.255.255";
$arry1 = explode(".", $from);
$arry2 = explode(".", $to);
$a1 = $arry1[0];
$b1 = $arry1[1];
$c1 = $arry1[2];
$d1 = $arry1[3];
$a2 = $arry2[0];
$b2 = $arry2[1];
$c2 = $arry2[2];
$d2 = $arry2[3];
while ($d2 >= $d1 || $c2 > $c1 || $b2 > $b1 || $a2 > $a1) {
if ($d1 > 255) {
$d1 = 1;
$c1++;
}
if ($c1 > 255) {
$c1 = 1;
$b1++;
}
if ($b1 > 255) {
$b1 = 1;
$a1++;
}
echo "$a1.$b1.$c1.$d1<br>";
$d1++;
}
```
And in Delphi I started with that :
```
procedure TForm1.Button1Click(Sender: TObject);
var
Arry1, Arry2: TStringList;
RangeFrom, RangeTo: string;
a1, b1, c1, d1, a2, b2, c2, d2: string;
begin
RangeFrom := Edit1.Text;
RangeTo := Edit2.Text;
Arry1 := Explode('.', RangeFrom);
Arry2 := Explode('.', RangeTo);
a1 := Arry1[0];
b1 := Arry1[1];
c1 := Arry1[2];
d1 := Arry1[3];
a2 := Arry1[0];
b2 := Arry1[1];
c2 := Arry1[2];
d2 := Arry1[3];
while (StrToInt(d2) >= StrToInt(d1))
//and StrToInt(c2) > (StrToInt(c1)
//and StrToInt(b2) > (StrToInt(b1)
//and StrToInt(a2) > (StrToInt(a1)
do
begin
if (StrToInt(d1) > 255) then
begin
d1 := '1';
StrToInt(c1)+1;
end;
if (StrToInt(c1) > 255) then
begin
c1 := '1';
StrToInt(b1)+1;
end;
if (StrToInt(b1) > 255) then
begin
b1 := '1';
StrToInt(a1)+1;
end;
ListBox1.Items.Add(a1+'.'+b1+'.'+c1+'.'+d1);
StrToInt(d1)+1;
end;
end;
```
(For the Explode function, I use : <http://www.marcosdellantonio.net/2007/06/14/funcao-explode-do-php-em-delphi/>)
Someone can help me to make working this small code in Delphi ?
Thanks in advance :)
Beny | 2012/01/06 | [
"https://Stackoverflow.com/questions/8761665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/778642/"
] | Here's what I can see just by looking at the code:
If think you have the parameters to `Explode` in the wrong order. The separator is the second parameter in the function to which you linked. So you should write:
```
Arry1 := Explode(RangeFrom, '.');
Arry2 := Explode(RangeTo, '.');
```
---
You are leaking memory by not freeing the arrays returned by the `Explode` function. Delphi is different from PHP in that you often have to manage the memory of objects that you create.
---
```
a2 := Arry1[0];
b2 := Arry1[1];
c2 := Arry1[2];
d2 := Arry1[3];
```
These should be `Arry2` rather than `Arry1`.
---
You should convert the strings to integers up front. So declare them like this:
```
a1, b1, c1, d1, a2, b2, c2, d2: Integer;
```
and write the assignments like this:
```
a1 := StrToInt(Arry1[0]);
b1 := StrToInt(Arry1[1]);
//etc. etc.
```
---
```
while ($d2 >= $d1 || $c2 > $c1 || $b2 > $b1 || $a2 > $a1)
```
translates to:
```
while ((d2 >= d1) or (c2 > c1) or (b2 > b1) or (a2 > a1))
```
---
Inside the while loop you want code like this:
```
if d1 > 255 then
begin
d1 := 1;
inc(c1);
end;
```
---
Converting the 4 values back to an IP address is easiest with the `Format` function:
```
ListBox1.Items.Add(Format('%d.%d.%d.%d', [a1, b1, c1, d1]));
```
---
You have a mis-understanding of what `StrToInt` does it is a function that receives as input a string and returns an integer. When you write:
```
StrToInt(d1)+1
```
you are not modifying the variable `d1` which is just an input variable. That issue disappears when you make the other changes I describe, but I wanted to point it out for your future benefit.
---
You may also want to force a periodic repaint of the list box so that you can see what is happening.
---
Put it all together and you have this:
```
var
Arry1, Arry2: TStringList;
RangeFrom, RangeTo: string;
Count: Integer;
a1, b1, c1, d1, a2, b2, c2, d2: Integer;
begin
RangeFrom := Edit1.Text;
RangeTo := Edit2.Text;
Arry1 := Explode(RangeFrom, '.');
try
a1 := StrToInt(Arry1[0]);
b1 := StrToInt(Arry1[1]);
c1 := StrToInt(Arry1[2]);
d1 := StrToInt(Arry1[3]);
finally
Arry1.Free;
end;
Arry2 := Explode(RangeTo, '.');
try
a2 := StrToInt(Arry2[0]);
b2 := StrToInt(Arry2[1]);
c2 := StrToInt(Arry2[2]);
d2 := StrToInt(Arry2[3]);
finally
Arry2.Free;
end;
Count := 0;
while ((d2 >= d1) or (c2 > c1) or (b2 > b1) or (a2 > a1)) do
begin
if d1 > 255 then
begin
d1 := 1;
inc(c1);
end;
if c1 > 255 then
begin
c1 := 1;
inc(b1);
end;
if b1 > 255 then
begin
b1 := 1;
inc(a1);
end;
ListBox1.Items.Add(Format('%d.%d.%d.%d', [a1, b1, c1, d1]));
inc(Count);
if Count mod 1000=0 then begin
ListBox1.Repaint;
ListBox1.TopIndex := ListBox1.Items.Count-1;
end;
inc(d1);
end;
end;
``` | Testing the goal:
```
procedure TForm1.Button1Click(Sender: TObject);
var
AddrList: TStringList;
StartAddress,
EndAddress: Cardinal;
a, b, c, d: PByte;
x: Cardinal;
begin
AddrList := TStringList.Create;
AddrList.Delimiter := '.';
AddrList.DelimitedText := Edit1.Text;
StartAddress := (Cardinal(StrToInt(AddrList.Strings[0])) shl 24 ) +
(Cardinal(StrToInt(AddrList.Strings[1])) shl 16) +
(Cardinal(StrToInt(AddrList.Strings[2])) shl 8) +
StrToInt(AddrList.Strings[3]);
AddrList.DelimitedText := Edit2.Text;
EndAddress := (Cardinal(StrToInt(AddrList.Strings[0])) shl 24 ) +
(Cardinal(StrToInt(AddrList.Strings[1])) shl 16) +
(Cardinal(StrToInt(AddrList.Strings[2])) shl 8) +
StrToInt(AddrList.Strings[3]);
AddrList.Free;
for x := StartAddress to EndAddress do begin
a := @x;
b := a;
Inc(a);
c := a;
Inc(a);
d := a;
Inc(a);
Memo1.Lines.Add(Format('%d.%d.%d.%d', [a^,d^,c^,b^]));
end;
end;
``` |
67,509,234 | I was able to do it by looping accessing `list[i][j]`.
but wanted to do it without looping.
Any ideas how to do it
Example list :
Input: `["abc","def","ghi"]`
Output: `["$bc_","$ef_","$hi_"]` | 2021/05/12 | [
"https://Stackoverflow.com/questions/67509234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15146737/"
] | Use a list comprehension and concatenate or format the strings you want.
```
inlist = ['abc','def','ghi']
outlist = [f'${s[1:]}_' for s in inlist]
``` | You can use list comprehension:
```
lstIn = ['abc', 'def', 'ghi']
lstOut = [f'${i[1:]}_' for i in lstIn]
print(lstOut)
```
Prints:
```
['$bc_', '$ef_', '$hi_']
``` |
67,509,234 | I was able to do it by looping accessing `list[i][j]`.
but wanted to do it without looping.
Any ideas how to do it
Example list :
Input: `["abc","def","ghi"]`
Output: `["$bc_","$ef_","$hi_"]` | 2021/05/12 | [
"https://Stackoverflow.com/questions/67509234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15146737/"
] | Use a list comprehension and concatenate or format the strings you want.
```
inlist = ['abc','def','ghi']
outlist = [f'${s[1:]}_' for s in inlist]
``` | Try this
```
lst = ["abc","def","ghi"]
out = [ "".join(("$",s[1:],"_")) for s in lst ]
```
Output: `print(out)`
```
['$bc_', '$ef_', '$hi_']
``` |
63,483,417 | Say I have a dataframe
```
id category
1 A
2 A
3 B
4 C
5 A
```
And I want to create a new column with incremental values where `category == 'A'`. So it should be something like.
```
id category value
1 A 1
2 A 2
3 B NaN
4 C NaN
5 A 3
```
Currently I am able to do this with
```
df['value'] = pd.nan
df.loc[df.category == "A", ['value']] = range(1, len(df[df.category == "A"]) + 1)
```
Is there a better/pythonic way to do this (i.e. I don't have to initialize the value column with nan? And currently, this method assigns me a float type instead of integer which is what I want. | 2020/08/19 | [
"https://Stackoverflow.com/questions/63483417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1676881/"
] | The following code for GNU sed:
```
sed 's/EndHere/&\n/g; s/\(StartHere\)[^\n]*\(EndHere\|$\)/\1\2/g; s/\n//g' <<EOF
StartHere Word1 EndHere
StartHere Word2
StartHere Word2 EndHere something else
something else StartHere Word2 EndHere something else
EOF
```
outputs:
```
StartHereEndHere
StartHere
StartHereEndHere something else
something else StartHereEndHere something else
```
>
> I am sure here that the word that i am deleting after is there only once per line
>
>
>
Then you could:
```
sed 's/\(StartHere\).*\(EndHere\)/\1\2/; t; s/\(StartHere\).*$/\1/'
```
The `t` command will end processing of the current line if the last `s` command was successful. So... it will work. | Instead of using `sed`, you could do it with Perl, which supports [negative lookahead](http://www.regular-expressions.info/lookaround.html).
Using the example you gave in your comment:
```
$ echo "oooo StartHere=Yo9897 EndHereYo" \
| perl -pe 's/(StartHere) (?: .*(EndHere) | .*(?!EndHere) )/$1$2/x'
```
would output "oooo StartHereEndHereYo".
`(?!...)` is a "negative lookahead"
The Perl's `x` regex option allows using spaces in the regex to make it (slightly) more readable |
689,798 | Suppose $\mathcal F$ is a family of functions from $A$ to $A$, and $B\subseteq A$. Prove that the closure of $B$ under $\mathcal F$ exists.
Attempt: I defined a set $$\bigcup\_{n \in \mathbb N}B\_n$$
where $B\_1=B$ and for all $n \ge 1$, $$B\_{n+1}=\{f(x)\mid f \in \mathcal F \,\text{and x $\in$ $B\_n$}\}$$
I am not sure with my answer above, can anyone please check and explain if my answer is wrong? Thanks in advance. | 2014/02/25 | [
"https://math.stackexchange.com/questions/689798",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/82405/"
] | Write $\mathcal F = (f\_i)\_{i \in \mathbb{N}}$. Define $C\_0 := B$ and $C\_{i+1} := \cup\_{j \in \mathbb{N}} f\_j(C\_i)$ for $i \in \mathbb{N}^+$.
Case 1: $C\_1 \subseteq B$
Obviously $C\_{i+1} \subseteq C\_{i}$ for all $i \geq 1$. On the other hand, $|C\_i| \geq 1$ for every $i$ by the definition of a function. So $(C\_i)\_{i \in \mathbb{N}}$ is a monotonically decreasing bounded sequence, and therefore its limit exists.
Case 2: $C\_1 \supseteq B$
Analogous reasoning with $C\_{i+1} \supseteq C\_{i}$ for all $i \geq 1$, $|C\_i| \leq |A|$ for every $i$, and monotonically increasing sequences.
Let $L$ denote the limit set above.
The closure you are searching for then is $L \cup B$. | This answer is motivated by Enderton's "A Mathematical Introduction to Logic".
The closure of $B\subset A$ under family of functions $\mathcal{F}$ is defined as follows.
I will generalize to the case that $f\in \mathcal{F}$ has $f:\times^m A \to A$ for any $m\in \mathbb{N}$.
$C\subset A$ is said to be a closure of $B\subset A$ under $\mathcal{F}$ if $B\subset C$ and for all $f\in\mathcal{F}$, with $f:\times^m A \to A$ if $c\_1,\ldots, c\_m\in C$ then $f(c\_1,\ldots,c\_m)\in C$.
We prove that such a set exists.
Let $C\_0 = B$.
Let $[n] = \{m\in\mathbb{N}: m < n\} = \{0, 1, \ldots, n-1\}$. Recall that a finite sequence on $A$ is a function $x: [n] \to A$. We use $x\_m$ to denote $x(m)$. We say a sequence $x$ on $A$ is a construction sequence if for each $0\le i < n$ we have either
* $x\_i \in C\_0$
* There exists $f\in \mathcal{F}$ with $f:\times^m A\to A$ and there exists $j\_1,\ldots, j\_m < i$ such that $f(x\_{j\_1},\ldots, x\_{j\_m}) = x\_i$
Now let
$$
C\_n = \{c \in A: \text{There is a construction sequence } x:[n]\to A \text{ and } x\_{n-1}=c\}
$$
That is $C\_n$ is the collection of final elements of length-$n$ finite construction sequences.
Now let
$$
C = \bigcup\_{i\in\mathbb{N}} C\_i
$$
We now prove that $C$ is the closure of $B\subset A$ under $\mathcal{F}$.
Clearly $B=C\_0 \subset C$.
Now consider $f\in \mathcal{F}$ with $f:\times^m A \to A$. Let $c\_1, \ldots, c\_m\in C$.
We must prove $f(c\_1,\ldots, c\_m)\in C$.
Since $c\_i\in C$ that means there is some $n\_i$ such that $x^i:[n\_i]\to A$ with $x^i$ a construction sequence and $x^i\_{n\_i-1} = c\_i$.
We can define a new sequence $x$ which is the concatenation of $x^1, \ldots, x^m$.
Without getting into the details of the definition of a concatenation of sequences, it is the case that $x$ is a construction sequence which includes all of $c\_1, \ldots, c\_m$.
We now append $f(c\_1, \ldots, c\_m)$ to $x$ to make a new construction sequence $x^+$.
Since $x^+$ is a construction sequence ending in $f(c\_1, \ldots, c\_m)$ we have that $f(c\_1, \ldots, c\_m)\in C$. |
689,798 | Suppose $\mathcal F$ is a family of functions from $A$ to $A$, and $B\subseteq A$. Prove that the closure of $B$ under $\mathcal F$ exists.
Attempt: I defined a set $$\bigcup\_{n \in \mathbb N}B\_n$$
where $B\_1=B$ and for all $n \ge 1$, $$B\_{n+1}=\{f(x)\mid f \in \mathcal F \,\text{and x $\in$ $B\_n$}\}$$
I am not sure with my answer above, can anyone please check and explain if my answer is wrong? Thanks in advance. | 2014/02/25 | [
"https://math.stackexchange.com/questions/689798",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/82405/"
] | Write $\mathcal F = (f\_i)\_{i \in \mathbb{N}}$. Define $C\_0 := B$ and $C\_{i+1} := \cup\_{j \in \mathbb{N}} f\_j(C\_i)$ for $i \in \mathbb{N}^+$.
Case 1: $C\_1 \subseteq B$
Obviously $C\_{i+1} \subseteq C\_{i}$ for all $i \geq 1$. On the other hand, $|C\_i| \geq 1$ for every $i$ by the definition of a function. So $(C\_i)\_{i \in \mathbb{N}}$ is a monotonically decreasing bounded sequence, and therefore its limit exists.
Case 2: $C\_1 \supseteq B$
Analogous reasoning with $C\_{i+1} \supseteq C\_{i}$ for all $i \geq 1$, $|C\_i| \leq |A|$ for every $i$, and monotonically increasing sequences.
Let $L$ denote the limit set above.
The closure you are searching for then is $L \cup B$. | I'll add another answer using another approach. Let $B\subset A$ and $\mathcal{F}$ a family functions where $f\in \mathcal{F}$ means there exists $n\in \mathbb{N}$ such that $f:A^n \to A$.
A set $C$ is said to be $(A, B, \mathcal{F})$-inductive if
\begin{align\*}
&B \subset C\\
&\text{and}\\
&\forall f \in \mathcal{F}(\forall n \in \mathbb{N}(f:U^n \to U \implies \forall \tilde{c}\in C^n(f(\tilde{c})\in C)))
\end{align\*}
If we restrict $\mathcal{F}$ to contain functions $f:A\to A$ the second condition can be simplified as
$$
\forall f \in \mathcal{F}(\forall c\in C(f(c)\in C))
$$
Define
$$
\mathcal{C} = \{C\in \mathcal{P}(A): C \text{ is } (A, B, \mathcal{F})\text{-inductive}\}
$$
We define the closure of $B$ under $\mathcal{F}$ to be
$$
\mathbb{N}\_{(A, B, \mathcal{F})} = \bigcap \mathcal{C}
$$
We have that $A\in \mathcal{C}$ so $\mathcal{C}$ is non-empty so there are no worries with taking the intersection.
We can prove that $\mathbb{N}\_{(A, B, \mathcal{F})}$ is $(A, B, \mathcal{F})$-inductive. This is because for every $C\in \mathcal{C}$ we have $B\subset C$ so we must have $B\subset \mathbb{N}\_{(A, B, \mathcal{F})}$. For the second condition, consider $f\in \mathcal{F}$ with $f:A^n \to A$. Let $\tilde{c}\in \mathbb{N}\_{(A, B, \mathcal{F})}^n$. This means that $\tilde{c}\in C$ for each $C\in \mathcal{C}$. Because $C$ is $(A, B, \mathcal{F})$-inductive, this means $f(\tilde{c}) \in C$ for each $C\in \mathcal{C}$. But this means that $f(\tilde{c})$ is also in $\mathbb{N}\_{(A, B, \mathcal{F})}$.
These two conditions mean $\mathbb{N}\_{(A, B, \mathcal{F})}$ is $(A, B, \mathcal{F})$-inductive.
All of this proves the existence and inductiveness of $\mathbb{N}\_{(A, B, \mathcal{F})}$. From these definitions we can prove both induction theorems and the recursion theorem for $\mathbb{N}\_{(A, B, \mathcal{F})}$ as generalizations of the induction and recursion theorems over the natural numbers $\mathbb{N}$. |
9,449,627 | I have two URLs:
<http://s140452.gridserver.com/view-pullsheet/>
<https://s140452.gridserver.com/locations/>
When browsing through any properties on the locations page (as well as any single property, filtering properties using the sidebar, adding and removing properties from the "pullsheet") the jcart.js script works fine -- it is in control of adding and removing photos from the "pullsheet".
From this page however, <http://s140452.gridserver.com/view-pullsheet/> , I get the following error "Ajax error: Edit the path in jcart.js to fix".
The code in question is:
```
var path = 'https://s140452.gridserver.com/wp-content/themes/re/assets/functions/jcart',
container = $('#jcart'),
token = $('[name=jcartToken]').val(),
tip = $('#jcart-tooltip');
var config = (function() {
var config = null;
$.ajax({
url: path + '/config-loader.php',
data: {
"ajax": "true"
},
dataType: 'json',
async: false,
success: function(response) {
config = response;
},
error: function() {
alert('Ajax error: Edit the path in jcart.js to fix.');
}
});
return config;
}());
```
How can the script be working fine on the locations page but throw an error from a different URL? How can I fix this?
Thanks!
jcart.js is located @ <https://s140452.gridserver.com/wp-content/themes/re/assets/js/jcart.js> | 2012/02/26 | [
"https://Stackoverflow.com/questions/9449627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/220761/"
] | because you are running into the same origin problem. https vs http
```
var path = 'https://s140452.gridserver.com/wp-content/themes/re/assets/functions/jcart',
```
to
```
var path = '//s140452.gridserver.com/wp-content/themes/re/assets/functions/jcart',
``` | With your error function you are assuming that the error can only be the incorrect path. Why not implement the function as `error(jqXHR, textStatus, errorThrown)` (see [ajax](http://api.jquery.com/jQuery.ajax/)), put a breakpoint in that function and then find out the true error. |
39,679,005 | I recently wrote some code in java that is supposed to send a string to a php script and it works perfectly fine. However it refuses to work when i use it in an android program. thought someone could help me find out what the problem is!
>
>
> ```
> public static String main(String x, String y){
> if (android.os.Build.VERSION.SDK_INT > 9)
> {
> StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
> StrictMode.setThreadPolicy(policy);
>
> ```
>
>
```
}else{
try{
String username = x;
String password = y;
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
// LÄSER FRÅN HEMSIDAN
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine()) != null){
result += line;
}
//AVSLUTA CONNECTION
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
}catch(Exception e){
e.printStackTrace();
}
}
return null;
}
```
I did allow internet permission in the manifest by adding
```
<uses-permission android:name="android.permission.INTERNET" />
```
but it simply gives me no result. At first i thought that maybe there was something missing in the php script but it works perfectly fine when being tested in eclipse, so there must be something wrong or missing from the android part, right? | 2016/09/24 | [
"https://Stackoverflow.com/questions/39679005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6858507/"
] | Make sure your `else` block executes. | That's a VERY bad practice - use Retrofit library for consuming REST apis instead. <http://www.vogella.com/tutorials/Retrofit/article.html> |
44,403,562 | I have tried Googling this question but no luck. Probably because I'm asking the wrong way. Any help is much appreciated.
I have variables `copy1`, `copy2`, etc. I want to iterate through them and select each one to check if it's contents has a certain number of characters. When I use any variation of the below, it will either console an error or output a string in the console.
```
var copy1 = document.getElementById('copy1');
var copy2 = document.getElementById('copy2');
var copy3 = document.getElementById('copy3');
for(var i=0;i<4;i++){
console.log(copy+i);
console.log("copy"+i);
};
```
Ideally I would be able to select an element and style that via javascript.
Much appreciated
Thanks All.
Moe | 2017/06/07 | [
"https://Stackoverflow.com/questions/44403562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2067987/"
] | Agree with @jaromanda-x:
```
var copy1 = document.getElementById('copy1');
var copy2 = document.getElementById('copy2');
var copy3 = document.getElementById('copy3');
for (var i=1; i<4; i++) {
console.log(window['copy'+i]);
};
```
Or you can use more simple example, like:
```
for (var i=1; i<4; i++) {
var name = 'copy' + i;
console.log(document.getElementById(name));
};
```
Or even:
```
for (var i=1; i<4; i++) {
console.log(document.getElementById('copy' + i));
};
``` | You can store the properties in an object where values are set to the `DOM` element
```
let copies = {
1 : document.getElementById('copy1'),
2 : document.getElementById('copy2'),
3 : document.getElementById('copy3')
}
for (let [key, prop] of Object.entries(copies)) {
console.log(key, prop)
}
console.log(copies[1], copies[2], copies[3]);
```
Or use attribute begins with and attribute ends with selectors with `.querySelector()`
```
let n = 1;
let copy1 = document.querySelector(`[id^=copy][id$='${n}']`); // `#copy1`
let copy2 = document.querySelector(`[id^=copy][id$='${++n}']`); // `#copy2`
```
```
for (let i = 1; i < 4; i++) {
console.log(document.querySelector("[id^=copy][id$=" + i + "]"));
}
``` |
44,403,562 | I have tried Googling this question but no luck. Probably because I'm asking the wrong way. Any help is much appreciated.
I have variables `copy1`, `copy2`, etc. I want to iterate through them and select each one to check if it's contents has a certain number of characters. When I use any variation of the below, it will either console an error or output a string in the console.
```
var copy1 = document.getElementById('copy1');
var copy2 = document.getElementById('copy2');
var copy3 = document.getElementById('copy3');
for(var i=0;i<4;i++){
console.log(copy+i);
console.log("copy"+i);
};
```
Ideally I would be able to select an element and style that via javascript.
Much appreciated
Thanks All.
Moe | 2017/06/07 | [
"https://Stackoverflow.com/questions/44403562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2067987/"
] | Agree with @jaromanda-x:
```
var copy1 = document.getElementById('copy1');
var copy2 = document.getElementById('copy2');
var copy3 = document.getElementById('copy3');
for (var i=1; i<4; i++) {
console.log(window['copy'+i]);
};
```
Or you can use more simple example, like:
```
for (var i=1; i<4; i++) {
var name = 'copy' + i;
console.log(document.getElementById(name));
};
```
Or even:
```
for (var i=1; i<4; i++) {
console.log(document.getElementById('copy' + i));
};
``` | Since nobody has addressed your "certain number of characters" requirement yet, I thought I would.
You could always use jQuery or write your own $ method, which works as a document.getElementById() wrapper function.
Here is a [jsfiddle](https://jsfiddle.net/fza0n701/) to see it in action.
**HTML**
```
<div id="copy1">01234</div>
<div id="copy2">012345678</div>
<div id="copy3">0123456789 0123456789</div>
```
**JavaScript**
```
// Isn't this just a brilliant short-cut?
function $(id) {
return document.getElementById(id);
}
for (let i=1; i<4; i++){
let obj = $('copy' + i);
let value = (obj) ? obj.innerText : '';
console.log('value.length:', value.length);
};
``` |
17,984,686 | Using `Backbone.Marionette`, I would like to render a collection of items along with a header.
I'm aware that `Marionette.CollectionView` does not have a template, as it only renders `ItemView`s.
I'm currently using `Marionette.LayoutView`, but have to define an extra DOM element for the 'list' region.
Is there any other way to do this? Possibly without the extra DOM element?
Maybe I could change `open()` for this particular region?
---
**Current Result**:
```
<div class='collection'>
<h3>Featured</h3>
<div class="list"></div>
</div>
```
**Desired Result**:
```
<div class='collection'>
<h3>List Name</h3>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
```
---
**Render Code**:
```
var col = new LCollection([{name: "foo"}, {name: "bar"}]); // Defined earlier, not relevant here
var list = new ListView({collection: col});
var layout = new MyLayout({model: new Backbone.Model({name: "Featured"})});
app.featured.show(layout);
layout.list.show(list);
```
**Views**:
```
var ListItemView = Backbone.Marionette.ItemView.extend({
template: '#list-item',
tagName: 'li'
});
var LessonListView = Backbone.Marionette.CollectionView.extend({
tagName: 'ul',
itemView: ListItemView
});
var MyLayout = Backbone.Marionette.Layout.extend({
template: "list-layout",
regions: {
list: '.list'
}
});
```
**Templates**:
```
<script type="text/template" id="list-item">
<%= name %>
</script>
<script type="text/template" id="list-layout">
<h3><%= name %></h3>
<div class="list"></div>
</script>
``` | 2013/08/01 | [
"https://Stackoverflow.com/questions/17984686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/243673/"
] | <https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.compositeview.md>
Applied for you :
Templates
```
<script id="list-item" type="text/html">
<%= name %>
</script>
<script id="list-layout" type="text/html">
<div class='collection'>
<h3><%= name %></h3>
<ul></ul>
</div>
</script>
```
JS
```
RowView = Backbone.Marionette.ItemView.extend({
tagName: "li",
template: "#list-item"
});
TableView = Backbone.Marionette.CompositeView.extend({
itemView: RowView,
// specify a jQuery selector to put the itemView instances in to
itemViewContainer: "ul",
template: "#list-layout"
});
``` | I believe the solution above will render the li element directly under the containing div or other region specified, unless you also specify
```
tagName: "ul"
```
Then it renders the li elements within a ul element within the specified region. |
17,984,686 | Using `Backbone.Marionette`, I would like to render a collection of items along with a header.
I'm aware that `Marionette.CollectionView` does not have a template, as it only renders `ItemView`s.
I'm currently using `Marionette.LayoutView`, but have to define an extra DOM element for the 'list' region.
Is there any other way to do this? Possibly without the extra DOM element?
Maybe I could change `open()` for this particular region?
---
**Current Result**:
```
<div class='collection'>
<h3>Featured</h3>
<div class="list"></div>
</div>
```
**Desired Result**:
```
<div class='collection'>
<h3>List Name</h3>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
```
---
**Render Code**:
```
var col = new LCollection([{name: "foo"}, {name: "bar"}]); // Defined earlier, not relevant here
var list = new ListView({collection: col});
var layout = new MyLayout({model: new Backbone.Model({name: "Featured"})});
app.featured.show(layout);
layout.list.show(list);
```
**Views**:
```
var ListItemView = Backbone.Marionette.ItemView.extend({
template: '#list-item',
tagName: 'li'
});
var LessonListView = Backbone.Marionette.CollectionView.extend({
tagName: 'ul',
itemView: ListItemView
});
var MyLayout = Backbone.Marionette.Layout.extend({
template: "list-layout",
regions: {
list: '.list'
}
});
```
**Templates**:
```
<script type="text/template" id="list-item">
<%= name %>
</script>
<script type="text/template" id="list-layout">
<h3><%= name %></h3>
<div class="list"></div>
</script>
``` | 2013/08/01 | [
"https://Stackoverflow.com/questions/17984686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/243673/"
] | <https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.compositeview.md>
Applied for you :
Templates
```
<script id="list-item" type="text/html">
<%= name %>
</script>
<script id="list-layout" type="text/html">
<div class='collection'>
<h3><%= name %></h3>
<ul></ul>
</div>
</script>
```
JS
```
RowView = Backbone.Marionette.ItemView.extend({
tagName: "li",
template: "#list-item"
});
TableView = Backbone.Marionette.CompositeView.extend({
itemView: RowView,
// specify a jQuery selector to put the itemView instances in to
itemViewContainer: "ul",
template: "#list-layout"
});
``` | Marionette 3 doesn't use `CompositeView` any more, so if we want to get something like this:
```
<div class='collection'>
<h3>List Name</h3>
<ul>
<li>FOO - BAR</li>
<li>FOO - BAR</li>
<li>FOO - BAR</li>
...
</ul>
</div>
```
We have to use `CollectionView` & `View` with regions.
1 - Templates
=============
We are going to define two templates, a first one that is the 'parent' and another one for each 'child' that the parent has.
### parentTemplate.html
```
<div class='collection'>
<h3>List Name</h3>
<ul></ul>
</div>
```
### childTemplate.html
```
<p>Item <%= value%></p>
```
2 - Backbone Model and Collection
=================================
Lets define a default model and its collection to fill the list.
```
const Item = Backbone.Model.extend({});
const Items = Backbone.Collection.extend({
model: Item
});
```
3 - Views
=========
First, we have to create a `View` for our child representation, so:
```
import ItemViewTemplate from './childTemplate.html';
const ItemChildView = Marionette.View.extend({
template: _.template(ItemViewTemplate),
className: 'item-child-view',
tagName: 'li' // <-- The element where we will wrap our item template (it is not defined in the HTML file)
});
```
Second, we have to create a `CollectionView` that manages each child, so:
```
const ItemsCollectionView = Marionette.CollectionView.extend({
tagName: 'ul', // <-- The element where we will wrap our collection of items (it is already in the parent HTML file)
childView: ItemChildView,
className: 'items-collection-view'
});
```
Finally, we have to create the main `View`, that contains the parentTemplate.html and in this one we define the region where we will load the collection of elements, so:
```
import ItemsViewTemplate './parentTemplate.html';
const ItemsView = Marionette.View.extend({
tagName: 'div',
className: 'items-view',
template: _.template(ItemsViewTemplate),
regions: {
body: {
el: 'ul', // <-- This is the HTML tag where we want to load our CollectionView
replaceElement: true // <-- With this option, we overwrite the HTML tag with our CollectionView tag
}
}
});
```
4- Rest of the Code
===================
Now we create the instances needed to make this works:
```
const app = new Marionette.Application({
region: '#main'
});
// Three simple Items
let item1 = new Item({value: 1});
let item2 = new Item({value: 2});
let item3 = new Item({value: 3});
// Put this Items into a Collection of Items
let items = new Items([item1, item2, item3]);
// Create the main View
let itemsView = new ItemsView();
app.showView(itemsView);
// Create the CollectionView for the Items
let itemsCollectionView = new ItemsCollectionView({
collection: items
});
// Load the CollectionView of Items into the region that we specified in the main View
itemsView.showChildView('body', itemsCollectionView);
app.start();
```
5- Result
=========
If we run this, we get:
```
<div class="collection">
<h3>List Name</h3>
<ul class="items-collection-view">
<li class="item-child-view"><p>Item1</p></li>
<li class="item-child-view"><p>Item2</p></li>
<li class="item-child-view"><p>Item3</p></li>
</ul>
</div>
```
Hope it helps! [Reference](https://github.com/marionettejs/backbone.marionette/blob/v3.0.0-pre.5/docs/marionette.collectionview.md#tables-using-marionette-3 "Marionette.CollectionView") |
17,984,686 | Using `Backbone.Marionette`, I would like to render a collection of items along with a header.
I'm aware that `Marionette.CollectionView` does not have a template, as it only renders `ItemView`s.
I'm currently using `Marionette.LayoutView`, but have to define an extra DOM element for the 'list' region.
Is there any other way to do this? Possibly without the extra DOM element?
Maybe I could change `open()` for this particular region?
---
**Current Result**:
```
<div class='collection'>
<h3>Featured</h3>
<div class="list"></div>
</div>
```
**Desired Result**:
```
<div class='collection'>
<h3>List Name</h3>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
```
---
**Render Code**:
```
var col = new LCollection([{name: "foo"}, {name: "bar"}]); // Defined earlier, not relevant here
var list = new ListView({collection: col});
var layout = new MyLayout({model: new Backbone.Model({name: "Featured"})});
app.featured.show(layout);
layout.list.show(list);
```
**Views**:
```
var ListItemView = Backbone.Marionette.ItemView.extend({
template: '#list-item',
tagName: 'li'
});
var LessonListView = Backbone.Marionette.CollectionView.extend({
tagName: 'ul',
itemView: ListItemView
});
var MyLayout = Backbone.Marionette.Layout.extend({
template: "list-layout",
regions: {
list: '.list'
}
});
```
**Templates**:
```
<script type="text/template" id="list-item">
<%= name %>
</script>
<script type="text/template" id="list-layout">
<h3><%= name %></h3>
<div class="list"></div>
</script>
``` | 2013/08/01 | [
"https://Stackoverflow.com/questions/17984686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/243673/"
] | Marionette 3 doesn't use `CompositeView` any more, so if we want to get something like this:
```
<div class='collection'>
<h3>List Name</h3>
<ul>
<li>FOO - BAR</li>
<li>FOO - BAR</li>
<li>FOO - BAR</li>
...
</ul>
</div>
```
We have to use `CollectionView` & `View` with regions.
1 - Templates
=============
We are going to define two templates, a first one that is the 'parent' and another one for each 'child' that the parent has.
### parentTemplate.html
```
<div class='collection'>
<h3>List Name</h3>
<ul></ul>
</div>
```
### childTemplate.html
```
<p>Item <%= value%></p>
```
2 - Backbone Model and Collection
=================================
Lets define a default model and its collection to fill the list.
```
const Item = Backbone.Model.extend({});
const Items = Backbone.Collection.extend({
model: Item
});
```
3 - Views
=========
First, we have to create a `View` for our child representation, so:
```
import ItemViewTemplate from './childTemplate.html';
const ItemChildView = Marionette.View.extend({
template: _.template(ItemViewTemplate),
className: 'item-child-view',
tagName: 'li' // <-- The element where we will wrap our item template (it is not defined in the HTML file)
});
```
Second, we have to create a `CollectionView` that manages each child, so:
```
const ItemsCollectionView = Marionette.CollectionView.extend({
tagName: 'ul', // <-- The element where we will wrap our collection of items (it is already in the parent HTML file)
childView: ItemChildView,
className: 'items-collection-view'
});
```
Finally, we have to create the main `View`, that contains the parentTemplate.html and in this one we define the region where we will load the collection of elements, so:
```
import ItemsViewTemplate './parentTemplate.html';
const ItemsView = Marionette.View.extend({
tagName: 'div',
className: 'items-view',
template: _.template(ItemsViewTemplate),
regions: {
body: {
el: 'ul', // <-- This is the HTML tag where we want to load our CollectionView
replaceElement: true // <-- With this option, we overwrite the HTML tag with our CollectionView tag
}
}
});
```
4- Rest of the Code
===================
Now we create the instances needed to make this works:
```
const app = new Marionette.Application({
region: '#main'
});
// Three simple Items
let item1 = new Item({value: 1});
let item2 = new Item({value: 2});
let item3 = new Item({value: 3});
// Put this Items into a Collection of Items
let items = new Items([item1, item2, item3]);
// Create the main View
let itemsView = new ItemsView();
app.showView(itemsView);
// Create the CollectionView for the Items
let itemsCollectionView = new ItemsCollectionView({
collection: items
});
// Load the CollectionView of Items into the region that we specified in the main View
itemsView.showChildView('body', itemsCollectionView);
app.start();
```
5- Result
=========
If we run this, we get:
```
<div class="collection">
<h3>List Name</h3>
<ul class="items-collection-view">
<li class="item-child-view"><p>Item1</p></li>
<li class="item-child-view"><p>Item2</p></li>
<li class="item-child-view"><p>Item3</p></li>
</ul>
</div>
```
Hope it helps! [Reference](https://github.com/marionettejs/backbone.marionette/blob/v3.0.0-pre.5/docs/marionette.collectionview.md#tables-using-marionette-3 "Marionette.CollectionView") | I believe the solution above will render the li element directly under the containing div or other region specified, unless you also specify
```
tagName: "ul"
```
Then it renders the li elements within a ul element within the specified region. |
49,471,198 | I'm on Windows and I am trying to install the bcrypt\_elixir module.
I get the following error:
```
$ mix phx.server
==> bcrypt_elixir
could not compile dependency :bcrypt_elixir, "mix compile" failed. You can recompile this dependency with "mix deps.compile bcrypt_elixir", update it with "mix deps.update bcrypt_elixir" or clean it with "mix deps.clean bcrypt_elixir"
** (Mix) "nmake" not found in the path. If you have set the MAKE environment variable,
please make sure it is correct.
```
Here is a terminal screenshot of the error:
[](https://i.stack.imgur.com/1b5lP.png)
Here is my `deps` function from `mix.exs`:
```
defp deps do
[
{:phoenix, "~> 1.3.0"},
{:phoenix_pubsub, "~> 1.0"},
{:phoenix_ecto, "~> 3.2"},
{:postgrex, ">= 0.0.0"},
{:phoenix_html, "~> 2.10"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:gettext, "~> 0.11"},
{:cowboy, "~> 1.0"},
{:comeonin, "~> 4.0"},
{:elixir_make, "~> 0.4.1"},
{:bcrypt_elixir, "~> 1.0"}
]
end
``` | 2018/03/24 | [
"https://Stackoverflow.com/questions/49471198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1152980/"
] | In windows 10, you must add NMAKE to your path
[](https://i.stack.imgur.com/ry2l8.png)
After that you can run mix deps.compile until see message like this:
[](https://i.stack.imgur.com/dFozC.png)
After that you must run cmd as suggest from nmake:
```
cmd /K "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" amd64
```
Run this command on cmd and run `mix deps.compile` normarly. | I found that, running on Windows, it was the latest version of erlang OTP, version 21,
that was causing the problem. I uninstalled this version and went for version 20 (which installs erlang 9.3 and latest version of Elixir then looks for this version when being compiled) and then bcrypt\_elixir compiled al |
49,471,198 | I'm on Windows and I am trying to install the bcrypt\_elixir module.
I get the following error:
```
$ mix phx.server
==> bcrypt_elixir
could not compile dependency :bcrypt_elixir, "mix compile" failed. You can recompile this dependency with "mix deps.compile bcrypt_elixir", update it with "mix deps.update bcrypt_elixir" or clean it with "mix deps.clean bcrypt_elixir"
** (Mix) "nmake" not found in the path. If you have set the MAKE environment variable,
please make sure it is correct.
```
Here is a terminal screenshot of the error:
[](https://i.stack.imgur.com/1b5lP.png)
Here is my `deps` function from `mix.exs`:
```
defp deps do
[
{:phoenix, "~> 1.3.0"},
{:phoenix_pubsub, "~> 1.0"},
{:phoenix_ecto, "~> 3.2"},
{:postgrex, ">= 0.0.0"},
{:phoenix_html, "~> 2.10"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:gettext, "~> 0.11"},
{:cowboy, "~> 1.0"},
{:comeonin, "~> 4.0"},
{:elixir_make, "~> 0.4.1"},
{:bcrypt_elixir, "~> 1.0"}
]
end
``` | 2018/03/24 | [
"https://Stackoverflow.com/questions/49471198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1152980/"
] | I faced same problem during distillery setup with my elixir project.
Installing package resolve issue as shown below.
I found bcrypt\_elixir need to install make and build-essential from Elixir Forum.
**platform:- ubuntu**
$ sudo apt install make
$ sudo apt-get install build-essential | Actually looking at this a bit closer, since you're running Cygwin and trying to build bcrypt under Cygwin, `nmake` doesn't even enter into the question. You need to install `make` into Cygwin. Re-run the cygwin installer, select the `Devel` category and then under Devel look for make.
EDIT:
-----
Ok, so if I had to guess I'd say either you need to
a.) Stop trying to build everything under the Cygwin prompt--if bcrypt\_elixir is detecting that it's on Windows, it's going to look for nmake and nmake isn't part of Cygwin.
You didn't specify how you're looking for nmake but if I were you I'd try this from the `C:\Program Files (x86)` directory.
`dir /s nmake.exe`
Mind you run that from a Windows cmd prompt--it won't work from the Cygwin shell!
b.) Somehow set bcrypt\_elixir to think it's on Linux so it looks for make (which is not the same as nmake).
Basically I think the simplest answer would be to try to run mix phx.server from a normal Windows cmd prompt and then go from there. Or if you need Linux, then install virtual box and put a Linux VM on the machine and proceed that way. |
49,471,198 | I'm on Windows and I am trying to install the bcrypt\_elixir module.
I get the following error:
```
$ mix phx.server
==> bcrypt_elixir
could not compile dependency :bcrypt_elixir, "mix compile" failed. You can recompile this dependency with "mix deps.compile bcrypt_elixir", update it with "mix deps.update bcrypt_elixir" or clean it with "mix deps.clean bcrypt_elixir"
** (Mix) "nmake" not found in the path. If you have set the MAKE environment variable,
please make sure it is correct.
```
Here is a terminal screenshot of the error:
[](https://i.stack.imgur.com/1b5lP.png)
Here is my `deps` function from `mix.exs`:
```
defp deps do
[
{:phoenix, "~> 1.3.0"},
{:phoenix_pubsub, "~> 1.0"},
{:phoenix_ecto, "~> 3.2"},
{:postgrex, ">= 0.0.0"},
{:phoenix_html, "~> 2.10"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:gettext, "~> 0.11"},
{:cowboy, "~> 1.0"},
{:comeonin, "~> 4.0"},
{:elixir_make, "~> 0.4.1"},
{:bcrypt_elixir, "~> 1.0"}
]
end
``` | 2018/03/24 | [
"https://Stackoverflow.com/questions/49471198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1152980/"
] | For Visual Studio 2019 (VS2019) :
```
cmd /K "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" amd64
``` | bcrypt\_elixir uses Windows' NMake (cf. bcrypt\_elixir's [**`Makefile.win`**](https://github.com/riverrun/bcrypt_elixir/blob/master/Makefile.win)).
**It seems like you don't have NMake installed.**
From [**NMake's documentation**](https://msdn.microsoft.com/en-us/library/dd9y37ha.aspx):
>
> NMAKE is included when you install Visual Studio or the Visual C++ command-line build tools. It's not available separately.
>
>
>
So you need to [**download Visual Studio**](https://www.visualstudio.com/) in order to get NMake. Then you should be able to compile bcrypt\_elixir.
**If you already have NMake**, make sure `nmake.exe` is located under a directory from your [**path**](https://superuser.com/questions/284342/what-are-path-and-other-environment-variables-and-how-can-i-set-or-use-them). |
49,471,198 | I'm on Windows and I am trying to install the bcrypt\_elixir module.
I get the following error:
```
$ mix phx.server
==> bcrypt_elixir
could not compile dependency :bcrypt_elixir, "mix compile" failed. You can recompile this dependency with "mix deps.compile bcrypt_elixir", update it with "mix deps.update bcrypt_elixir" or clean it with "mix deps.clean bcrypt_elixir"
** (Mix) "nmake" not found in the path. If you have set the MAKE environment variable,
please make sure it is correct.
```
Here is a terminal screenshot of the error:
[](https://i.stack.imgur.com/1b5lP.png)
Here is my `deps` function from `mix.exs`:
```
defp deps do
[
{:phoenix, "~> 1.3.0"},
{:phoenix_pubsub, "~> 1.0"},
{:phoenix_ecto, "~> 3.2"},
{:postgrex, ">= 0.0.0"},
{:phoenix_html, "~> 2.10"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:gettext, "~> 0.11"},
{:cowboy, "~> 1.0"},
{:comeonin, "~> 4.0"},
{:elixir_make, "~> 0.4.1"},
{:bcrypt_elixir, "~> 1.0"}
]
end
``` | 2018/03/24 | [
"https://Stackoverflow.com/questions/49471198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1152980/"
] | Actually looking at this a bit closer, since you're running Cygwin and trying to build bcrypt under Cygwin, `nmake` doesn't even enter into the question. You need to install `make` into Cygwin. Re-run the cygwin installer, select the `Devel` category and then under Devel look for make.
EDIT:
-----
Ok, so if I had to guess I'd say either you need to
a.) Stop trying to build everything under the Cygwin prompt--if bcrypt\_elixir is detecting that it's on Windows, it's going to look for nmake and nmake isn't part of Cygwin.
You didn't specify how you're looking for nmake but if I were you I'd try this from the `C:\Program Files (x86)` directory.
`dir /s nmake.exe`
Mind you run that from a Windows cmd prompt--it won't work from the Cygwin shell!
b.) Somehow set bcrypt\_elixir to think it's on Linux so it looks for make (which is not the same as nmake).
Basically I think the simplest answer would be to try to run mix phx.server from a normal Windows cmd prompt and then go from there. Or if you need Linux, then install virtual box and put a Linux VM on the machine and proceed that way. | This answer is for anyone running elixir *directly on Windows*, and using VS Code with the ElixirLS extension. These instructions should work for other Visual Studio versions besides 2022, just change the path to vcvars64.bat.
1. Install Visual Studio 2022.
2. Use the Visual Studio Installer to install the optional `Desktop Development with C++` workload. This contains native C/C++ build tools, including nmake.exe.
3. Create a script in your home directory (C:\Users\UserName) ExVsCode.bat with the following (`%1` is how you access the first command line argument, which will be the project directory):
```
cd %1
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat
code .
```
4. When you want to work on an elixir project in VS Code, open a command prompt (CMD.exe), move to your home directory if you're not there already, and run `ExVsCode.bat C:\Users\Username\PathToProject` to open VS Code with all the build tools available to ElixirLS and the integrated terminal.
---
Credit to [exqlite documentation](https://hexdocs.pm/exqlite/windows.html#visual-studio-code-users-using-elixirls) for some of this.
Note: the original question may concern Cygwin, but many people will find this answer who are running elixir directly on Windows, and [a closed question](https://stackoverflow.com/questions/64061136/) that doesn't mention Cygwin or WSL already points here. |
49,471,198 | I'm on Windows and I am trying to install the bcrypt\_elixir module.
I get the following error:
```
$ mix phx.server
==> bcrypt_elixir
could not compile dependency :bcrypt_elixir, "mix compile" failed. You can recompile this dependency with "mix deps.compile bcrypt_elixir", update it with "mix deps.update bcrypt_elixir" or clean it with "mix deps.clean bcrypt_elixir"
** (Mix) "nmake" not found in the path. If you have set the MAKE environment variable,
please make sure it is correct.
```
Here is a terminal screenshot of the error:
[](https://i.stack.imgur.com/1b5lP.png)
Here is my `deps` function from `mix.exs`:
```
defp deps do
[
{:phoenix, "~> 1.3.0"},
{:phoenix_pubsub, "~> 1.0"},
{:phoenix_ecto, "~> 3.2"},
{:postgrex, ">= 0.0.0"},
{:phoenix_html, "~> 2.10"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:gettext, "~> 0.11"},
{:cowboy, "~> 1.0"},
{:comeonin, "~> 4.0"},
{:elixir_make, "~> 0.4.1"},
{:bcrypt_elixir, "~> 1.0"}
]
end
``` | 2018/03/24 | [
"https://Stackoverflow.com/questions/49471198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1152980/"
] | I found that, running on Windows, it was the latest version of erlang OTP, version 21,
that was causing the problem. I uninstalled this version and went for version 20 (which installs erlang 9.3 and latest version of Elixir then looks for this version when being compiled) and then bcrypt\_elixir compiled al | This answer is for anyone running elixir *directly on Windows*, and using VS Code with the ElixirLS extension. These instructions should work for other Visual Studio versions besides 2022, just change the path to vcvars64.bat.
1. Install Visual Studio 2022.
2. Use the Visual Studio Installer to install the optional `Desktop Development with C++` workload. This contains native C/C++ build tools, including nmake.exe.
3. Create a script in your home directory (C:\Users\UserName) ExVsCode.bat with the following (`%1` is how you access the first command line argument, which will be the project directory):
```
cd %1
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat
code .
```
4. When you want to work on an elixir project in VS Code, open a command prompt (CMD.exe), move to your home directory if you're not there already, and run `ExVsCode.bat C:\Users\Username\PathToProject` to open VS Code with all the build tools available to ElixirLS and the integrated terminal.
---
Credit to [exqlite documentation](https://hexdocs.pm/exqlite/windows.html#visual-studio-code-users-using-elixirls) for some of this.
Note: the original question may concern Cygwin, but many people will find this answer who are running elixir directly on Windows, and [a closed question](https://stackoverflow.com/questions/64061136/) that doesn't mention Cygwin or WSL already points here. |
49,471,198 | I'm on Windows and I am trying to install the bcrypt\_elixir module.
I get the following error:
```
$ mix phx.server
==> bcrypt_elixir
could not compile dependency :bcrypt_elixir, "mix compile" failed. You can recompile this dependency with "mix deps.compile bcrypt_elixir", update it with "mix deps.update bcrypt_elixir" or clean it with "mix deps.clean bcrypt_elixir"
** (Mix) "nmake" not found in the path. If you have set the MAKE environment variable,
please make sure it is correct.
```
Here is a terminal screenshot of the error:
[](https://i.stack.imgur.com/1b5lP.png)
Here is my `deps` function from `mix.exs`:
```
defp deps do
[
{:phoenix, "~> 1.3.0"},
{:phoenix_pubsub, "~> 1.0"},
{:phoenix_ecto, "~> 3.2"},
{:postgrex, ">= 0.0.0"},
{:phoenix_html, "~> 2.10"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:gettext, "~> 0.11"},
{:cowboy, "~> 1.0"},
{:comeonin, "~> 4.0"},
{:elixir_make, "~> 0.4.1"},
{:bcrypt_elixir, "~> 1.0"}
]
end
``` | 2018/03/24 | [
"https://Stackoverflow.com/questions/49471198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1152980/"
] | For Visual Studio 2019 (VS2019) :
```
cmd /K "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" amd64
``` | I found that, running on Windows, it was the latest version of erlang OTP, version 21,
that was causing the problem. I uninstalled this version and went for version 20 (which installs erlang 9.3 and latest version of Elixir then looks for this version when being compiled) and then bcrypt\_elixir compiled al |
49,471,198 | I'm on Windows and I am trying to install the bcrypt\_elixir module.
I get the following error:
```
$ mix phx.server
==> bcrypt_elixir
could not compile dependency :bcrypt_elixir, "mix compile" failed. You can recompile this dependency with "mix deps.compile bcrypt_elixir", update it with "mix deps.update bcrypt_elixir" or clean it with "mix deps.clean bcrypt_elixir"
** (Mix) "nmake" not found in the path. If you have set the MAKE environment variable,
please make sure it is correct.
```
Here is a terminal screenshot of the error:
[](https://i.stack.imgur.com/1b5lP.png)
Here is my `deps` function from `mix.exs`:
```
defp deps do
[
{:phoenix, "~> 1.3.0"},
{:phoenix_pubsub, "~> 1.0"},
{:phoenix_ecto, "~> 3.2"},
{:postgrex, ">= 0.0.0"},
{:phoenix_html, "~> 2.10"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:gettext, "~> 0.11"},
{:cowboy, "~> 1.0"},
{:comeonin, "~> 4.0"},
{:elixir_make, "~> 0.4.1"},
{:bcrypt_elixir, "~> 1.0"}
]
end
``` | 2018/03/24 | [
"https://Stackoverflow.com/questions/49471198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1152980/"
] | I faced same problem during distillery setup with my elixir project.
Installing package resolve issue as shown below.
I found bcrypt\_elixir need to install make and build-essential from Elixir Forum.
**platform:- ubuntu**
$ sudo apt install make
$ sudo apt-get install build-essential | I found that, running on Windows, it was the latest version of erlang OTP, version 21,
that was causing the problem. I uninstalled this version and went for version 20 (which installs erlang 9.3 and latest version of Elixir then looks for this version when being compiled) and then bcrypt\_elixir compiled al |
49,471,198 | I'm on Windows and I am trying to install the bcrypt\_elixir module.
I get the following error:
```
$ mix phx.server
==> bcrypt_elixir
could not compile dependency :bcrypt_elixir, "mix compile" failed. You can recompile this dependency with "mix deps.compile bcrypt_elixir", update it with "mix deps.update bcrypt_elixir" or clean it with "mix deps.clean bcrypt_elixir"
** (Mix) "nmake" not found in the path. If you have set the MAKE environment variable,
please make sure it is correct.
```
Here is a terminal screenshot of the error:
[](https://i.stack.imgur.com/1b5lP.png)
Here is my `deps` function from `mix.exs`:
```
defp deps do
[
{:phoenix, "~> 1.3.0"},
{:phoenix_pubsub, "~> 1.0"},
{:phoenix_ecto, "~> 3.2"},
{:postgrex, ">= 0.0.0"},
{:phoenix_html, "~> 2.10"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:gettext, "~> 0.11"},
{:cowboy, "~> 1.0"},
{:comeonin, "~> 4.0"},
{:elixir_make, "~> 0.4.1"},
{:bcrypt_elixir, "~> 1.0"}
]
end
``` | 2018/03/24 | [
"https://Stackoverflow.com/questions/49471198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1152980/"
] | I faced same problem during distillery setup with my elixir project.
Installing package resolve issue as shown below.
I found bcrypt\_elixir need to install make and build-essential from Elixir Forum.
**platform:- ubuntu**
$ sudo apt install make
$ sudo apt-get install build-essential | bcrypt\_elixir uses Windows' NMake (cf. bcrypt\_elixir's [**`Makefile.win`**](https://github.com/riverrun/bcrypt_elixir/blob/master/Makefile.win)).
**It seems like you don't have NMake installed.**
From [**NMake's documentation**](https://msdn.microsoft.com/en-us/library/dd9y37ha.aspx):
>
> NMAKE is included when you install Visual Studio or the Visual C++ command-line build tools. It's not available separately.
>
>
>
So you need to [**download Visual Studio**](https://www.visualstudio.com/) in order to get NMake. Then you should be able to compile bcrypt\_elixir.
**If you already have NMake**, make sure `nmake.exe` is located under a directory from your [**path**](https://superuser.com/questions/284342/what-are-path-and-other-environment-variables-and-how-can-i-set-or-use-them). |
49,471,198 | I'm on Windows and I am trying to install the bcrypt\_elixir module.
I get the following error:
```
$ mix phx.server
==> bcrypt_elixir
could not compile dependency :bcrypt_elixir, "mix compile" failed. You can recompile this dependency with "mix deps.compile bcrypt_elixir", update it with "mix deps.update bcrypt_elixir" or clean it with "mix deps.clean bcrypt_elixir"
** (Mix) "nmake" not found in the path. If you have set the MAKE environment variable,
please make sure it is correct.
```
Here is a terminal screenshot of the error:
[](https://i.stack.imgur.com/1b5lP.png)
Here is my `deps` function from `mix.exs`:
```
defp deps do
[
{:phoenix, "~> 1.3.0"},
{:phoenix_pubsub, "~> 1.0"},
{:phoenix_ecto, "~> 3.2"},
{:postgrex, ">= 0.0.0"},
{:phoenix_html, "~> 2.10"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:gettext, "~> 0.11"},
{:cowboy, "~> 1.0"},
{:comeonin, "~> 4.0"},
{:elixir_make, "~> 0.4.1"},
{:bcrypt_elixir, "~> 1.0"}
]
end
``` | 2018/03/24 | [
"https://Stackoverflow.com/questions/49471198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1152980/"
] | For Visual Studio 2019 (VS2019) :
```
cmd /K "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" amd64
``` | This answer is for anyone running elixir *directly on Windows*, and using VS Code with the ElixirLS extension. These instructions should work for other Visual Studio versions besides 2022, just change the path to vcvars64.bat.
1. Install Visual Studio 2022.
2. Use the Visual Studio Installer to install the optional `Desktop Development with C++` workload. This contains native C/C++ build tools, including nmake.exe.
3. Create a script in your home directory (C:\Users\UserName) ExVsCode.bat with the following (`%1` is how you access the first command line argument, which will be the project directory):
```
cd %1
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat
code .
```
4. When you want to work on an elixir project in VS Code, open a command prompt (CMD.exe), move to your home directory if you're not there already, and run `ExVsCode.bat C:\Users\Username\PathToProject` to open VS Code with all the build tools available to ElixirLS and the integrated terminal.
---
Credit to [exqlite documentation](https://hexdocs.pm/exqlite/windows.html#visual-studio-code-users-using-elixirls) for some of this.
Note: the original question may concern Cygwin, but many people will find this answer who are running elixir directly on Windows, and [a closed question](https://stackoverflow.com/questions/64061136/) that doesn't mention Cygwin or WSL already points here. |
49,471,198 | I'm on Windows and I am trying to install the bcrypt\_elixir module.
I get the following error:
```
$ mix phx.server
==> bcrypt_elixir
could not compile dependency :bcrypt_elixir, "mix compile" failed. You can recompile this dependency with "mix deps.compile bcrypt_elixir", update it with "mix deps.update bcrypt_elixir" or clean it with "mix deps.clean bcrypt_elixir"
** (Mix) "nmake" not found in the path. If you have set the MAKE environment variable,
please make sure it is correct.
```
Here is a terminal screenshot of the error:
[](https://i.stack.imgur.com/1b5lP.png)
Here is my `deps` function from `mix.exs`:
```
defp deps do
[
{:phoenix, "~> 1.3.0"},
{:phoenix_pubsub, "~> 1.0"},
{:phoenix_ecto, "~> 3.2"},
{:postgrex, ">= 0.0.0"},
{:phoenix_html, "~> 2.10"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:gettext, "~> 0.11"},
{:cowboy, "~> 1.0"},
{:comeonin, "~> 4.0"},
{:elixir_make, "~> 0.4.1"},
{:bcrypt_elixir, "~> 1.0"}
]
end
``` | 2018/03/24 | [
"https://Stackoverflow.com/questions/49471198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1152980/"
] | I faced same problem during distillery setup with my elixir project.
Installing package resolve issue as shown below.
I found bcrypt\_elixir need to install make and build-essential from Elixir Forum.
**platform:- ubuntu**
$ sudo apt install make
$ sudo apt-get install build-essential | For Visual Studio 2019 (VS2019) :
```
cmd /K "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat" amd64
``` |
14,572,773 | **Background**
I'm working on an academic project to (basically) analyze some "who follows whom" graphs and wanted to get some real data (by building some small datasets) from Twitter using one of the Python Twitter API packages in order to test some ideas I have.
I was a bit careless and installed two packages:
a) `python-twitter0.8.2` (<http://pypi.python.org/pypi/python-twitter/0.8.2>)
b) `twitter1.9.1` (<http://pypi.python.org/pypi/twitter/1.9.1>)
(a) is called `python-twitter` in pypi, and (b) is called `twitter`, so that's how I'll refer to them.
Both of these are called by `import twitter` in the Python interpreter, but when I write that line, I always get the `twitter` one (if I can figure out how to use the `python-twitter` one, I'll be able to proceed, but will still have the same underlying problem).
---
**Problem**
Since I don't need the `twitter` package, I decided to uninstall it with pip:
`$ sudo pip uninstall twitter`
which gives the output:
```
Uninstalling twitter:
Proceed (y/n)? y
Successfully uninstalled twitter
```
(actually, I tried the same thing with `python-twitter` and got a similar response).
However, when running `pip freeze`, both of these packages show up on the installed list! In fact, I can still use the `import twitter` command successfully in the interpreter. Clearly the packages have not been uninstalled. What I would love to know is how to uninstall them!
---
**Other Info**
I'm using Python 2.7 and Ubuntu 12.04
When running IDLE instead of the shell interpreter, and I type `help('modules')`, neither `twitter` nor `python-twitter` shows up in the list. When typing `help('modules')` into the shell interpreter, I get a segmentation fault error, and the interpreter crashes. Here's the error:
```
>>> help('modules')
Please wait a moment while I gather a list of all available modules...
/usr/lib/python2.7/dist-packages/gobject/constants.py:24: Warning:
g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed
import gobject._gobject
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning:
g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed
from gtk import _gtk
** (python:2484): CRITICAL **: pyg_register_boxed: assertion `boxed_type != 0' failed
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: cannot register
existing type `GdkDevice'
from gtk import _gtk
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: g_type_get_qdata:
assertion `node != NULL' failed
from gtk import _gtk
Segmentation fault (core dumped)
```
---
**Why other questions have not resolved this for me:**
I looked at the similar post at [pip freeze lists uninstalled packages](https://stackoverflow.com/questions/11640530/pip-freeze-lists-uninstalled-packages) and am not having the same issues.
```
$ sudo which pip
/usr/bin/pip
$ which pip
/usr/bin/pip
```
which is the same output. In addition, `$ sudo pip freeze` gives the same output as `$ pip freeze`.
Any help is very much appreciated! | 2013/01/28 | [
"https://Stackoverflow.com/questions/14572773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2019798/"
] | You can always manually delete the packages; you can run:
```
sudo rm -rf /usr/local/lib/python2.7/dist-packages/twitter
```
to remove that package from your `dist-packages` directory. You may have to edit the `easy-install.pth` file in the same directory and remove the `twitter` entry from it. | While Martin's solution works, as a work around, it does not provide a direct answer.
Ubuntu's pip version for your Ubuntu version (12.04) is:
```
python-pip (1.0-1build1)
```
This is also the same version for Debian Wheezy. This version has a weired bug, which causes packages not to be removed.
If you obtain pip from upstream using the script `get-pip.py` you will have a fixed version of pip which can remove pacakges (as of now v. 1.5.6).
update
======
Python's pip is really a fast moving target. So using Debian's or Ubuntu's pip is guaranteed to have bugs. *Please* don't use those distribution's `pip`.
Instead install pip from upstream.
If you would like to register pip installed packages as system packages I really recommend that you also use [stdeb](https://pypi.python.org/pypi/stdeb). |
14,572,773 | **Background**
I'm working on an academic project to (basically) analyze some "who follows whom" graphs and wanted to get some real data (by building some small datasets) from Twitter using one of the Python Twitter API packages in order to test some ideas I have.
I was a bit careless and installed two packages:
a) `python-twitter0.8.2` (<http://pypi.python.org/pypi/python-twitter/0.8.2>)
b) `twitter1.9.1` (<http://pypi.python.org/pypi/twitter/1.9.1>)
(a) is called `python-twitter` in pypi, and (b) is called `twitter`, so that's how I'll refer to them.
Both of these are called by `import twitter` in the Python interpreter, but when I write that line, I always get the `twitter` one (if I can figure out how to use the `python-twitter` one, I'll be able to proceed, but will still have the same underlying problem).
---
**Problem**
Since I don't need the `twitter` package, I decided to uninstall it with pip:
`$ sudo pip uninstall twitter`
which gives the output:
```
Uninstalling twitter:
Proceed (y/n)? y
Successfully uninstalled twitter
```
(actually, I tried the same thing with `python-twitter` and got a similar response).
However, when running `pip freeze`, both of these packages show up on the installed list! In fact, I can still use the `import twitter` command successfully in the interpreter. Clearly the packages have not been uninstalled. What I would love to know is how to uninstall them!
---
**Other Info**
I'm using Python 2.7 and Ubuntu 12.04
When running IDLE instead of the shell interpreter, and I type `help('modules')`, neither `twitter` nor `python-twitter` shows up in the list. When typing `help('modules')` into the shell interpreter, I get a segmentation fault error, and the interpreter crashes. Here's the error:
```
>>> help('modules')
Please wait a moment while I gather a list of all available modules...
/usr/lib/python2.7/dist-packages/gobject/constants.py:24: Warning:
g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed
import gobject._gobject
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning:
g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed
from gtk import _gtk
** (python:2484): CRITICAL **: pyg_register_boxed: assertion `boxed_type != 0' failed
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: cannot register
existing type `GdkDevice'
from gtk import _gtk
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: g_type_get_qdata:
assertion `node != NULL' failed
from gtk import _gtk
Segmentation fault (core dumped)
```
---
**Why other questions have not resolved this for me:**
I looked at the similar post at [pip freeze lists uninstalled packages](https://stackoverflow.com/questions/11640530/pip-freeze-lists-uninstalled-packages) and am not having the same issues.
```
$ sudo which pip
/usr/bin/pip
$ which pip
/usr/bin/pip
```
which is the same output. In addition, `$ sudo pip freeze` gives the same output as `$ pip freeze`.
Any help is very much appreciated! | 2013/01/28 | [
"https://Stackoverflow.com/questions/14572773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2019798/"
] | You can always manually delete the packages; you can run:
```
sudo rm -rf /usr/local/lib/python2.7/dist-packages/twitter
```
to remove that package from your `dist-packages` directory. You may have to edit the `easy-install.pth` file in the same directory and remove the `twitter` entry from it. | I was facing difficulty while upgrading a package because pip was not able to uninstall it successfully. I had to delete the .egg-info and the folder as well in /usr/lib/python2.7/dist-packages and then I tried to install with --upgrade and it worked. |
14,572,773 | **Background**
I'm working on an academic project to (basically) analyze some "who follows whom" graphs and wanted to get some real data (by building some small datasets) from Twitter using one of the Python Twitter API packages in order to test some ideas I have.
I was a bit careless and installed two packages:
a) `python-twitter0.8.2` (<http://pypi.python.org/pypi/python-twitter/0.8.2>)
b) `twitter1.9.1` (<http://pypi.python.org/pypi/twitter/1.9.1>)
(a) is called `python-twitter` in pypi, and (b) is called `twitter`, so that's how I'll refer to them.
Both of these are called by `import twitter` in the Python interpreter, but when I write that line, I always get the `twitter` one (if I can figure out how to use the `python-twitter` one, I'll be able to proceed, but will still have the same underlying problem).
---
**Problem**
Since I don't need the `twitter` package, I decided to uninstall it with pip:
`$ sudo pip uninstall twitter`
which gives the output:
```
Uninstalling twitter:
Proceed (y/n)? y
Successfully uninstalled twitter
```
(actually, I tried the same thing with `python-twitter` and got a similar response).
However, when running `pip freeze`, both of these packages show up on the installed list! In fact, I can still use the `import twitter` command successfully in the interpreter. Clearly the packages have not been uninstalled. What I would love to know is how to uninstall them!
---
**Other Info**
I'm using Python 2.7 and Ubuntu 12.04
When running IDLE instead of the shell interpreter, and I type `help('modules')`, neither `twitter` nor `python-twitter` shows up in the list. When typing `help('modules')` into the shell interpreter, I get a segmentation fault error, and the interpreter crashes. Here's the error:
```
>>> help('modules')
Please wait a moment while I gather a list of all available modules...
/usr/lib/python2.7/dist-packages/gobject/constants.py:24: Warning:
g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed
import gobject._gobject
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning:
g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed
from gtk import _gtk
** (python:2484): CRITICAL **: pyg_register_boxed: assertion `boxed_type != 0' failed
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: cannot register
existing type `GdkDevice'
from gtk import _gtk
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: g_type_get_qdata:
assertion `node != NULL' failed
from gtk import _gtk
Segmentation fault (core dumped)
```
---
**Why other questions have not resolved this for me:**
I looked at the similar post at [pip freeze lists uninstalled packages](https://stackoverflow.com/questions/11640530/pip-freeze-lists-uninstalled-packages) and am not having the same issues.
```
$ sudo which pip
/usr/bin/pip
$ which pip
/usr/bin/pip
```
which is the same output. In addition, `$ sudo pip freeze` gives the same output as `$ pip freeze`.
Any help is very much appreciated! | 2013/01/28 | [
"https://Stackoverflow.com/questions/14572773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2019798/"
] | You can always manually delete the packages; you can run:
```
sudo rm -rf /usr/local/lib/python2.7/dist-packages/twitter
```
to remove that package from your `dist-packages` directory. You may have to edit the `easy-install.pth` file in the same directory and remove the `twitter` entry from it. | In my case (moving pyusb 0.4x to 1.0x), removing the old package with apt-get remove python-usb and manually installing the manually downloaded package via python setup.py worked. Not pretty, but working. |
14,572,773 | **Background**
I'm working on an academic project to (basically) analyze some "who follows whom" graphs and wanted to get some real data (by building some small datasets) from Twitter using one of the Python Twitter API packages in order to test some ideas I have.
I was a bit careless and installed two packages:
a) `python-twitter0.8.2` (<http://pypi.python.org/pypi/python-twitter/0.8.2>)
b) `twitter1.9.1` (<http://pypi.python.org/pypi/twitter/1.9.1>)
(a) is called `python-twitter` in pypi, and (b) is called `twitter`, so that's how I'll refer to them.
Both of these are called by `import twitter` in the Python interpreter, but when I write that line, I always get the `twitter` one (if I can figure out how to use the `python-twitter` one, I'll be able to proceed, but will still have the same underlying problem).
---
**Problem**
Since I don't need the `twitter` package, I decided to uninstall it with pip:
`$ sudo pip uninstall twitter`
which gives the output:
```
Uninstalling twitter:
Proceed (y/n)? y
Successfully uninstalled twitter
```
(actually, I tried the same thing with `python-twitter` and got a similar response).
However, when running `pip freeze`, both of these packages show up on the installed list! In fact, I can still use the `import twitter` command successfully in the interpreter. Clearly the packages have not been uninstalled. What I would love to know is how to uninstall them!
---
**Other Info**
I'm using Python 2.7 and Ubuntu 12.04
When running IDLE instead of the shell interpreter, and I type `help('modules')`, neither `twitter` nor `python-twitter` shows up in the list. When typing `help('modules')` into the shell interpreter, I get a segmentation fault error, and the interpreter crashes. Here's the error:
```
>>> help('modules')
Please wait a moment while I gather a list of all available modules...
/usr/lib/python2.7/dist-packages/gobject/constants.py:24: Warning:
g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed
import gobject._gobject
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning:
g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed
from gtk import _gtk
** (python:2484): CRITICAL **: pyg_register_boxed: assertion `boxed_type != 0' failed
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: cannot register
existing type `GdkDevice'
from gtk import _gtk
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: g_type_get_qdata:
assertion `node != NULL' failed
from gtk import _gtk
Segmentation fault (core dumped)
```
---
**Why other questions have not resolved this for me:**
I looked at the similar post at [pip freeze lists uninstalled packages](https://stackoverflow.com/questions/11640530/pip-freeze-lists-uninstalled-packages) and am not having the same issues.
```
$ sudo which pip
/usr/bin/pip
$ which pip
/usr/bin/pip
```
which is the same output. In addition, `$ sudo pip freeze` gives the same output as `$ pip freeze`.
Any help is very much appreciated! | 2013/01/28 | [
"https://Stackoverflow.com/questions/14572773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2019798/"
] | You can always manually delete the packages; you can run:
```
sudo rm -rf /usr/local/lib/python2.7/dist-packages/twitter
```
to remove that package from your `dist-packages` directory. You may have to edit the `easy-install.pth` file in the same directory and remove the `twitter` entry from it. | For me, it was due to the fact that I was running `pip freeze`, which gave me different results than `sudo pip freeze`.
Since I was uninstalling using `sudo`, it was not uninstalling it in the "non-`sudo`" session. Uninstalling without `sudo` fixed that. |
14,572,773 | **Background**
I'm working on an academic project to (basically) analyze some "who follows whom" graphs and wanted to get some real data (by building some small datasets) from Twitter using one of the Python Twitter API packages in order to test some ideas I have.
I was a bit careless and installed two packages:
a) `python-twitter0.8.2` (<http://pypi.python.org/pypi/python-twitter/0.8.2>)
b) `twitter1.9.1` (<http://pypi.python.org/pypi/twitter/1.9.1>)
(a) is called `python-twitter` in pypi, and (b) is called `twitter`, so that's how I'll refer to them.
Both of these are called by `import twitter` in the Python interpreter, but when I write that line, I always get the `twitter` one (if I can figure out how to use the `python-twitter` one, I'll be able to proceed, but will still have the same underlying problem).
---
**Problem**
Since I don't need the `twitter` package, I decided to uninstall it with pip:
`$ sudo pip uninstall twitter`
which gives the output:
```
Uninstalling twitter:
Proceed (y/n)? y
Successfully uninstalled twitter
```
(actually, I tried the same thing with `python-twitter` and got a similar response).
However, when running `pip freeze`, both of these packages show up on the installed list! In fact, I can still use the `import twitter` command successfully in the interpreter. Clearly the packages have not been uninstalled. What I would love to know is how to uninstall them!
---
**Other Info**
I'm using Python 2.7 and Ubuntu 12.04
When running IDLE instead of the shell interpreter, and I type `help('modules')`, neither `twitter` nor `python-twitter` shows up in the list. When typing `help('modules')` into the shell interpreter, I get a segmentation fault error, and the interpreter crashes. Here's the error:
```
>>> help('modules')
Please wait a moment while I gather a list of all available modules...
/usr/lib/python2.7/dist-packages/gobject/constants.py:24: Warning:
g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed
import gobject._gobject
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning:
g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed
from gtk import _gtk
** (python:2484): CRITICAL **: pyg_register_boxed: assertion `boxed_type != 0' failed
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: cannot register
existing type `GdkDevice'
from gtk import _gtk
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: g_type_get_qdata:
assertion `node != NULL' failed
from gtk import _gtk
Segmentation fault (core dumped)
```
---
**Why other questions have not resolved this for me:**
I looked at the similar post at [pip freeze lists uninstalled packages](https://stackoverflow.com/questions/11640530/pip-freeze-lists-uninstalled-packages) and am not having the same issues.
```
$ sudo which pip
/usr/bin/pip
$ which pip
/usr/bin/pip
```
which is the same output. In addition, `$ sudo pip freeze` gives the same output as `$ pip freeze`.
Any help is very much appreciated! | 2013/01/28 | [
"https://Stackoverflow.com/questions/14572773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2019798/"
] | While Martin's solution works, as a work around, it does not provide a direct answer.
Ubuntu's pip version for your Ubuntu version (12.04) is:
```
python-pip (1.0-1build1)
```
This is also the same version for Debian Wheezy. This version has a weired bug, which causes packages not to be removed.
If you obtain pip from upstream using the script `get-pip.py` you will have a fixed version of pip which can remove pacakges (as of now v. 1.5.6).
update
======
Python's pip is really a fast moving target. So using Debian's or Ubuntu's pip is guaranteed to have bugs. *Please* don't use those distribution's `pip`.
Instead install pip from upstream.
If you would like to register pip installed packages as system packages I really recommend that you also use [stdeb](https://pypi.python.org/pypi/stdeb). | I was facing difficulty while upgrading a package because pip was not able to uninstall it successfully. I had to delete the .egg-info and the folder as well in /usr/lib/python2.7/dist-packages and then I tried to install with --upgrade and it worked. |
14,572,773 | **Background**
I'm working on an academic project to (basically) analyze some "who follows whom" graphs and wanted to get some real data (by building some small datasets) from Twitter using one of the Python Twitter API packages in order to test some ideas I have.
I was a bit careless and installed two packages:
a) `python-twitter0.8.2` (<http://pypi.python.org/pypi/python-twitter/0.8.2>)
b) `twitter1.9.1` (<http://pypi.python.org/pypi/twitter/1.9.1>)
(a) is called `python-twitter` in pypi, and (b) is called `twitter`, so that's how I'll refer to them.
Both of these are called by `import twitter` in the Python interpreter, but when I write that line, I always get the `twitter` one (if I can figure out how to use the `python-twitter` one, I'll be able to proceed, but will still have the same underlying problem).
---
**Problem**
Since I don't need the `twitter` package, I decided to uninstall it with pip:
`$ sudo pip uninstall twitter`
which gives the output:
```
Uninstalling twitter:
Proceed (y/n)? y
Successfully uninstalled twitter
```
(actually, I tried the same thing with `python-twitter` and got a similar response).
However, when running `pip freeze`, both of these packages show up on the installed list! In fact, I can still use the `import twitter` command successfully in the interpreter. Clearly the packages have not been uninstalled. What I would love to know is how to uninstall them!
---
**Other Info**
I'm using Python 2.7 and Ubuntu 12.04
When running IDLE instead of the shell interpreter, and I type `help('modules')`, neither `twitter` nor `python-twitter` shows up in the list. When typing `help('modules')` into the shell interpreter, I get a segmentation fault error, and the interpreter crashes. Here's the error:
```
>>> help('modules')
Please wait a moment while I gather a list of all available modules...
/usr/lib/python2.7/dist-packages/gobject/constants.py:24: Warning:
g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed
import gobject._gobject
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning:
g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed
from gtk import _gtk
** (python:2484): CRITICAL **: pyg_register_boxed: assertion `boxed_type != 0' failed
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: cannot register
existing type `GdkDevice'
from gtk import _gtk
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: g_type_get_qdata:
assertion `node != NULL' failed
from gtk import _gtk
Segmentation fault (core dumped)
```
---
**Why other questions have not resolved this for me:**
I looked at the similar post at [pip freeze lists uninstalled packages](https://stackoverflow.com/questions/11640530/pip-freeze-lists-uninstalled-packages) and am not having the same issues.
```
$ sudo which pip
/usr/bin/pip
$ which pip
/usr/bin/pip
```
which is the same output. In addition, `$ sudo pip freeze` gives the same output as `$ pip freeze`.
Any help is very much appreciated! | 2013/01/28 | [
"https://Stackoverflow.com/questions/14572773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2019798/"
] | While Martin's solution works, as a work around, it does not provide a direct answer.
Ubuntu's pip version for your Ubuntu version (12.04) is:
```
python-pip (1.0-1build1)
```
This is also the same version for Debian Wheezy. This version has a weired bug, which causes packages not to be removed.
If you obtain pip from upstream using the script `get-pip.py` you will have a fixed version of pip which can remove pacakges (as of now v. 1.5.6).
update
======
Python's pip is really a fast moving target. So using Debian's or Ubuntu's pip is guaranteed to have bugs. *Please* don't use those distribution's `pip`.
Instead install pip from upstream.
If you would like to register pip installed packages as system packages I really recommend that you also use [stdeb](https://pypi.python.org/pypi/stdeb). | In my case (moving pyusb 0.4x to 1.0x), removing the old package with apt-get remove python-usb and manually installing the manually downloaded package via python setup.py worked. Not pretty, but working. |
14,572,773 | **Background**
I'm working on an academic project to (basically) analyze some "who follows whom" graphs and wanted to get some real data (by building some small datasets) from Twitter using one of the Python Twitter API packages in order to test some ideas I have.
I was a bit careless and installed two packages:
a) `python-twitter0.8.2` (<http://pypi.python.org/pypi/python-twitter/0.8.2>)
b) `twitter1.9.1` (<http://pypi.python.org/pypi/twitter/1.9.1>)
(a) is called `python-twitter` in pypi, and (b) is called `twitter`, so that's how I'll refer to them.
Both of these are called by `import twitter` in the Python interpreter, but when I write that line, I always get the `twitter` one (if I can figure out how to use the `python-twitter` one, I'll be able to proceed, but will still have the same underlying problem).
---
**Problem**
Since I don't need the `twitter` package, I decided to uninstall it with pip:
`$ sudo pip uninstall twitter`
which gives the output:
```
Uninstalling twitter:
Proceed (y/n)? y
Successfully uninstalled twitter
```
(actually, I tried the same thing with `python-twitter` and got a similar response).
However, when running `pip freeze`, both of these packages show up on the installed list! In fact, I can still use the `import twitter` command successfully in the interpreter. Clearly the packages have not been uninstalled. What I would love to know is how to uninstall them!
---
**Other Info**
I'm using Python 2.7 and Ubuntu 12.04
When running IDLE instead of the shell interpreter, and I type `help('modules')`, neither `twitter` nor `python-twitter` shows up in the list. When typing `help('modules')` into the shell interpreter, I get a segmentation fault error, and the interpreter crashes. Here's the error:
```
>>> help('modules')
Please wait a moment while I gather a list of all available modules...
/usr/lib/python2.7/dist-packages/gobject/constants.py:24: Warning:
g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed
import gobject._gobject
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning:
g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed
from gtk import _gtk
** (python:2484): CRITICAL **: pyg_register_boxed: assertion `boxed_type != 0' failed
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: cannot register
existing type `GdkDevice'
from gtk import _gtk
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: g_type_get_qdata:
assertion `node != NULL' failed
from gtk import _gtk
Segmentation fault (core dumped)
```
---
**Why other questions have not resolved this for me:**
I looked at the similar post at [pip freeze lists uninstalled packages](https://stackoverflow.com/questions/11640530/pip-freeze-lists-uninstalled-packages) and am not having the same issues.
```
$ sudo which pip
/usr/bin/pip
$ which pip
/usr/bin/pip
```
which is the same output. In addition, `$ sudo pip freeze` gives the same output as `$ pip freeze`.
Any help is very much appreciated! | 2013/01/28 | [
"https://Stackoverflow.com/questions/14572773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2019798/"
] | While Martin's solution works, as a work around, it does not provide a direct answer.
Ubuntu's pip version for your Ubuntu version (12.04) is:
```
python-pip (1.0-1build1)
```
This is also the same version for Debian Wheezy. This version has a weired bug, which causes packages not to be removed.
If you obtain pip from upstream using the script `get-pip.py` you will have a fixed version of pip which can remove pacakges (as of now v. 1.5.6).
update
======
Python's pip is really a fast moving target. So using Debian's or Ubuntu's pip is guaranteed to have bugs. *Please* don't use those distribution's `pip`.
Instead install pip from upstream.
If you would like to register pip installed packages as system packages I really recommend that you also use [stdeb](https://pypi.python.org/pypi/stdeb). | For me, it was due to the fact that I was running `pip freeze`, which gave me different results than `sudo pip freeze`.
Since I was uninstalling using `sudo`, it was not uninstalling it in the "non-`sudo`" session. Uninstalling without `sudo` fixed that. |
14,572,773 | **Background**
I'm working on an academic project to (basically) analyze some "who follows whom" graphs and wanted to get some real data (by building some small datasets) from Twitter using one of the Python Twitter API packages in order to test some ideas I have.
I was a bit careless and installed two packages:
a) `python-twitter0.8.2` (<http://pypi.python.org/pypi/python-twitter/0.8.2>)
b) `twitter1.9.1` (<http://pypi.python.org/pypi/twitter/1.9.1>)
(a) is called `python-twitter` in pypi, and (b) is called `twitter`, so that's how I'll refer to them.
Both of these are called by `import twitter` in the Python interpreter, but when I write that line, I always get the `twitter` one (if I can figure out how to use the `python-twitter` one, I'll be able to proceed, but will still have the same underlying problem).
---
**Problem**
Since I don't need the `twitter` package, I decided to uninstall it with pip:
`$ sudo pip uninstall twitter`
which gives the output:
```
Uninstalling twitter:
Proceed (y/n)? y
Successfully uninstalled twitter
```
(actually, I tried the same thing with `python-twitter` and got a similar response).
However, when running `pip freeze`, both of these packages show up on the installed list! In fact, I can still use the `import twitter` command successfully in the interpreter. Clearly the packages have not been uninstalled. What I would love to know is how to uninstall them!
---
**Other Info**
I'm using Python 2.7 and Ubuntu 12.04
When running IDLE instead of the shell interpreter, and I type `help('modules')`, neither `twitter` nor `python-twitter` shows up in the list. When typing `help('modules')` into the shell interpreter, I get a segmentation fault error, and the interpreter crashes. Here's the error:
```
>>> help('modules')
Please wait a moment while I gather a list of all available modules...
/usr/lib/python2.7/dist-packages/gobject/constants.py:24: Warning:
g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed
import gobject._gobject
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning:
g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed
from gtk import _gtk
** (python:2484): CRITICAL **: pyg_register_boxed: assertion `boxed_type != 0' failed
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: cannot register
existing type `GdkDevice'
from gtk import _gtk
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: g_type_get_qdata:
assertion `node != NULL' failed
from gtk import _gtk
Segmentation fault (core dumped)
```
---
**Why other questions have not resolved this for me:**
I looked at the similar post at [pip freeze lists uninstalled packages](https://stackoverflow.com/questions/11640530/pip-freeze-lists-uninstalled-packages) and am not having the same issues.
```
$ sudo which pip
/usr/bin/pip
$ which pip
/usr/bin/pip
```
which is the same output. In addition, `$ sudo pip freeze` gives the same output as `$ pip freeze`.
Any help is very much appreciated! | 2013/01/28 | [
"https://Stackoverflow.com/questions/14572773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2019798/"
] | I was facing difficulty while upgrading a package because pip was not able to uninstall it successfully. I had to delete the .egg-info and the folder as well in /usr/lib/python2.7/dist-packages and then I tried to install with --upgrade and it worked. | In my case (moving pyusb 0.4x to 1.0x), removing the old package with apt-get remove python-usb and manually installing the manually downloaded package via python setup.py worked. Not pretty, but working. |
14,572,773 | **Background**
I'm working on an academic project to (basically) analyze some "who follows whom" graphs and wanted to get some real data (by building some small datasets) from Twitter using one of the Python Twitter API packages in order to test some ideas I have.
I was a bit careless and installed two packages:
a) `python-twitter0.8.2` (<http://pypi.python.org/pypi/python-twitter/0.8.2>)
b) `twitter1.9.1` (<http://pypi.python.org/pypi/twitter/1.9.1>)
(a) is called `python-twitter` in pypi, and (b) is called `twitter`, so that's how I'll refer to them.
Both of these are called by `import twitter` in the Python interpreter, but when I write that line, I always get the `twitter` one (if I can figure out how to use the `python-twitter` one, I'll be able to proceed, but will still have the same underlying problem).
---
**Problem**
Since I don't need the `twitter` package, I decided to uninstall it with pip:
`$ sudo pip uninstall twitter`
which gives the output:
```
Uninstalling twitter:
Proceed (y/n)? y
Successfully uninstalled twitter
```
(actually, I tried the same thing with `python-twitter` and got a similar response).
However, when running `pip freeze`, both of these packages show up on the installed list! In fact, I can still use the `import twitter` command successfully in the interpreter. Clearly the packages have not been uninstalled. What I would love to know is how to uninstall them!
---
**Other Info**
I'm using Python 2.7 and Ubuntu 12.04
When running IDLE instead of the shell interpreter, and I type `help('modules')`, neither `twitter` nor `python-twitter` shows up in the list. When typing `help('modules')` into the shell interpreter, I get a segmentation fault error, and the interpreter crashes. Here's the error:
```
>>> help('modules')
Please wait a moment while I gather a list of all available modules...
/usr/lib/python2.7/dist-packages/gobject/constants.py:24: Warning:
g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed
import gobject._gobject
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning:
g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed
from gtk import _gtk
** (python:2484): CRITICAL **: pyg_register_boxed: assertion `boxed_type != 0' failed
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: cannot register
existing type `GdkDevice'
from gtk import _gtk
/usr/lib/python2.7/dist-packages/gtk-2.0/gtk/__init__.py:40: Warning: g_type_get_qdata:
assertion `node != NULL' failed
from gtk import _gtk
Segmentation fault (core dumped)
```
---
**Why other questions have not resolved this for me:**
I looked at the similar post at [pip freeze lists uninstalled packages](https://stackoverflow.com/questions/11640530/pip-freeze-lists-uninstalled-packages) and am not having the same issues.
```
$ sudo which pip
/usr/bin/pip
$ which pip
/usr/bin/pip
```
which is the same output. In addition, `$ sudo pip freeze` gives the same output as `$ pip freeze`.
Any help is very much appreciated! | 2013/01/28 | [
"https://Stackoverflow.com/questions/14572773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2019798/"
] | For me, it was due to the fact that I was running `pip freeze`, which gave me different results than `sudo pip freeze`.
Since I was uninstalling using `sudo`, it was not uninstalling it in the "non-`sudo`" session. Uninstalling without `sudo` fixed that. | In my case (moving pyusb 0.4x to 1.0x), removing the old package with apt-get remove python-usb and manually installing the manually downloaded package via python setup.py worked. Not pretty, but working. |
6,211,613 | I decided to create simple *isEven* and *isOdd* function with a very simple algorithm:
```
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
```
That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.
```
// Returns true if:
//
// n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string
(function (global) {
function basicTests(n) {
// Deal with empty string
if (n === '')
return false;
// Convert n to Number (may set to NaN)
n = Number(n);
// Deal with NaN
if (isNaN(n))
return false;
// Deal with infinity -
if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
return false;
// Return n as a number
return n;
}
function isEven(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Convert to Number and proceed
n = Number(n);
// Return true/false
return n === 0 || !!(n && !(n%2));
}
global.isEven = isEven;
// Returns true if n is an integer and (n+1) is even
// Returns false if n is not an integer or (n+1) is not even
// Empty string evaluates to zero so returns false (zero is even)
function isOdd(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Return true/false
return n === 0 || !!(n && (n%2));
}
global.isOdd = isOdd;
}(this));
```
Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?
There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript. | 2011/06/02 | [
"https://Stackoverflow.com/questions/6211613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257182/"
] | ```
if (testNum == 0);
else if (testNum % 2 == 0);
else if ((testNum % 2) != 0 );
``` | ```
function isEven(n) {return parseInt(n)%2===0?true:parseInt(n)===0?true:false}
```
when 0/even wanted but
```
isEven(0) //true
isEven(1) //false
isEven(2) //true
isEven(142856) //true
isEven(142856.142857)//true
isEven(142857.1457)//false
```
|
6,211,613 | I decided to create simple *isEven* and *isOdd* function with a very simple algorithm:
```
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
```
That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.
```
// Returns true if:
//
// n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string
(function (global) {
function basicTests(n) {
// Deal with empty string
if (n === '')
return false;
// Convert n to Number (may set to NaN)
n = Number(n);
// Deal with NaN
if (isNaN(n))
return false;
// Deal with infinity -
if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
return false;
// Return n as a number
return n;
}
function isEven(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Convert to Number and proceed
n = Number(n);
// Return true/false
return n === 0 || !!(n && !(n%2));
}
global.isEven = isEven;
// Returns true if n is an integer and (n+1) is even
// Returns false if n is not an integer or (n+1) is not even
// Empty string evaluates to zero so returns false (zero is even)
function isOdd(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Return true/false
return n === 0 || !!(n && (n%2));
}
global.isOdd = isOdd;
}(this));
```
Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?
There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript. | 2011/06/02 | [
"https://Stackoverflow.com/questions/6211613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257182/"
] | Use modulus:
```
function isEven(n) {
return n % 2 == 0;
}
function isOdd(n) {
return Math.abs(n % 2) == 1;
}
```
You can check that any value in Javascript can be coerced to a number with:
```
Number.isFinite(parseFloat(n))
```
This check should preferably be done outside the `isEven` and `isOdd` functions, so you don't have to duplicate error handling in both functions. | Why not just do this:
```
function oddOrEven(num){
if(num % 2 == 0)
return "even";
return "odd";
}
oddOrEven(num);
``` |
6,211,613 | I decided to create simple *isEven* and *isOdd* function with a very simple algorithm:
```
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
```
That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.
```
// Returns true if:
//
// n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string
(function (global) {
function basicTests(n) {
// Deal with empty string
if (n === '')
return false;
// Convert n to Number (may set to NaN)
n = Number(n);
// Deal with NaN
if (isNaN(n))
return false;
// Deal with infinity -
if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
return false;
// Return n as a number
return n;
}
function isEven(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Convert to Number and proceed
n = Number(n);
// Return true/false
return n === 0 || !!(n && !(n%2));
}
global.isEven = isEven;
// Returns true if n is an integer and (n+1) is even
// Returns false if n is not an integer or (n+1) is not even
// Empty string evaluates to zero so returns false (zero is even)
function isOdd(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Return true/false
return n === 0 || !!(n && (n%2));
}
global.isOdd = isOdd;
}(this));
```
Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?
There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript. | 2011/06/02 | [
"https://Stackoverflow.com/questions/6211613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257182/"
] | ```js
var isOdd = x => Boolean(x % 2);
var isEven = x => !isOdd(x);
``` | Otherway using strings because why not
```
function isEven(__num){
return String(__num/2).indexOf('.') === -1;
}
``` |
6,211,613 | I decided to create simple *isEven* and *isOdd* function with a very simple algorithm:
```
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
```
That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.
```
// Returns true if:
//
// n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string
(function (global) {
function basicTests(n) {
// Deal with empty string
if (n === '')
return false;
// Convert n to Number (may set to NaN)
n = Number(n);
// Deal with NaN
if (isNaN(n))
return false;
// Deal with infinity -
if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
return false;
// Return n as a number
return n;
}
function isEven(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Convert to Number and proceed
n = Number(n);
// Return true/false
return n === 0 || !!(n && !(n%2));
}
global.isEven = isEven;
// Returns true if n is an integer and (n+1) is even
// Returns false if n is not an integer or (n+1) is not even
// Empty string evaluates to zero so returns false (zero is even)
function isOdd(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Return true/false
return n === 0 || !!(n && (n%2));
}
global.isOdd = isOdd;
}(this));
```
Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?
There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript. | 2011/06/02 | [
"https://Stackoverflow.com/questions/6211613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257182/"
] | A simple modification/improvement of Steve Mayne answer!
```
function isEvenOrOdd(n){
if(n === parseFloat(n)){
return isNumber(n) && (n % 2 == 0);
}
return false;
}
```
Note: Returns false if invalid! | ```
var num = someNumber
isEven;
parseInt(num/2) === num/2 ? isEven = true : isEven = false;
``` |
6,211,613 | I decided to create simple *isEven* and *isOdd* function with a very simple algorithm:
```
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
```
That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.
```
// Returns true if:
//
// n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string
(function (global) {
function basicTests(n) {
// Deal with empty string
if (n === '')
return false;
// Convert n to Number (may set to NaN)
n = Number(n);
// Deal with NaN
if (isNaN(n))
return false;
// Deal with infinity -
if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
return false;
// Return n as a number
return n;
}
function isEven(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Convert to Number and proceed
n = Number(n);
// Return true/false
return n === 0 || !!(n && !(n%2));
}
global.isEven = isEven;
// Returns true if n is an integer and (n+1) is even
// Returns false if n is not an integer or (n+1) is not even
// Empty string evaluates to zero so returns false (zero is even)
function isOdd(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Return true/false
return n === 0 || !!(n && (n%2));
}
global.isOdd = isOdd;
}(this));
```
Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?
There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript. | 2011/06/02 | [
"https://Stackoverflow.com/questions/6211613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257182/"
] | We just need one line of code for this!
Here a newer and alternative way to do this, using the new [ES6](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Functions/Arrow_functions) syntax for JS functions, and the [one-line syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) for the `if-else` statement call:
```
const isEven = num => ((num % 2) == 0);
alert(isEven(8)); //true
alert(isEven(9)); //false
alert(isEven(-8)); //true
``` | ```
function isEven(n) {return parseInt(n)%2===0?true:parseInt(n)===0?true:false}
```
when 0/even wanted but
```
isEven(0) //true
isEven(1) //false
isEven(2) //true
isEven(142856) //true
isEven(142856.142857)//true
isEven(142857.1457)//false
```
|
6,211,613 | I decided to create simple *isEven* and *isOdd* function with a very simple algorithm:
```
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
```
That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.
```
// Returns true if:
//
// n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string
(function (global) {
function basicTests(n) {
// Deal with empty string
if (n === '')
return false;
// Convert n to Number (may set to NaN)
n = Number(n);
// Deal with NaN
if (isNaN(n))
return false;
// Deal with infinity -
if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
return false;
// Return n as a number
return n;
}
function isEven(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Convert to Number and proceed
n = Number(n);
// Return true/false
return n === 0 || !!(n && !(n%2));
}
global.isEven = isEven;
// Returns true if n is an integer and (n+1) is even
// Returns false if n is not an integer or (n+1) is not even
// Empty string evaluates to zero so returns false (zero is even)
function isOdd(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Return true/false
return n === 0 || !!(n && (n%2));
}
global.isOdd = isOdd;
}(this));
```
Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?
There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript. | 2011/06/02 | [
"https://Stackoverflow.com/questions/6211613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257182/"
] | I prefer using a bit test:
```
if(i & 1)
{
// ODD
}
else
{
// EVEN
}
```
This tests whether the first bit is on which signifies an odd number. | ```
var num = someNumber
isEven;
parseInt(num/2) === num/2 ? isEven = true : isEven = false;
``` |
6,211,613 | I decided to create simple *isEven* and *isOdd* function with a very simple algorithm:
```
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
```
That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.
```
// Returns true if:
//
// n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string
(function (global) {
function basicTests(n) {
// Deal with empty string
if (n === '')
return false;
// Convert n to Number (may set to NaN)
n = Number(n);
// Deal with NaN
if (isNaN(n))
return false;
// Deal with infinity -
if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
return false;
// Return n as a number
return n;
}
function isEven(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Convert to Number and proceed
n = Number(n);
// Return true/false
return n === 0 || !!(n && !(n%2));
}
global.isEven = isEven;
// Returns true if n is an integer and (n+1) is even
// Returns false if n is not an integer or (n+1) is not even
// Empty string evaluates to zero so returns false (zero is even)
function isOdd(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Return true/false
return n === 0 || !!(n && (n%2));
}
global.isOdd = isOdd;
}(this));
```
Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?
There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript. | 2011/06/02 | [
"https://Stackoverflow.com/questions/6211613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257182/"
] | ```
var isEven = function(number) {
// Your code goes here!
if (number % 2 == 0){
return(true);
}
else{
return(false);
}
};
``` | ```
if (i % 2) {
return odd numbers
}
if (i % 2 - 1) {
return even numbers
}
``` |
6,211,613 | I decided to create simple *isEven* and *isOdd* function with a very simple algorithm:
```
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
```
That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.
```
// Returns true if:
//
// n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string
(function (global) {
function basicTests(n) {
// Deal with empty string
if (n === '')
return false;
// Convert n to Number (may set to NaN)
n = Number(n);
// Deal with NaN
if (isNaN(n))
return false;
// Deal with infinity -
if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
return false;
// Return n as a number
return n;
}
function isEven(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Convert to Number and proceed
n = Number(n);
// Return true/false
return n === 0 || !!(n && !(n%2));
}
global.isEven = isEven;
// Returns true if n is an integer and (n+1) is even
// Returns false if n is not an integer or (n+1) is not even
// Empty string evaluates to zero so returns false (zero is even)
function isOdd(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Return true/false
return n === 0 || !!(n && (n%2));
}
global.isOdd = isOdd;
}(this));
```
Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?
There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript. | 2011/06/02 | [
"https://Stackoverflow.com/questions/6211613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257182/"
] | Maybe this?
if(ourNumber % 2 !== 0) | ```
function isEven(n) {return parseInt(n)%2===0?true:parseInt(n)===0?true:false}
```
when 0/even wanted but
```
isEven(0) //true
isEven(1) //false
isEven(2) //true
isEven(142856) //true
isEven(142856.142857)//true
isEven(142857.1457)//false
```
|
6,211,613 | I decided to create simple *isEven* and *isOdd* function with a very simple algorithm:
```
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
```
That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.
```
// Returns true if:
//
// n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string
(function (global) {
function basicTests(n) {
// Deal with empty string
if (n === '')
return false;
// Convert n to Number (may set to NaN)
n = Number(n);
// Deal with NaN
if (isNaN(n))
return false;
// Deal with infinity -
if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
return false;
// Return n as a number
return n;
}
function isEven(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Convert to Number and proceed
n = Number(n);
// Return true/false
return n === 0 || !!(n && !(n%2));
}
global.isEven = isEven;
// Returns true if n is an integer and (n+1) is even
// Returns false if n is not an integer or (n+1) is not even
// Empty string evaluates to zero so returns false (zero is even)
function isOdd(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Return true/false
return n === 0 || !!(n && (n%2));
}
global.isOdd = isOdd;
}(this));
```
Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?
There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript. | 2011/06/02 | [
"https://Stackoverflow.com/questions/6211613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257182/"
] | A few
```
x % 2 == 0; // Check if even
!(x & 1); // bitmask the value with 1 then invert.
((x >> 1) << 1) == x; // divide value by 2 then multiply again and check against original value
~x&1; // flip the bits and bitmask
``` | ```
if (testNum == 0);
else if (testNum % 2 == 0);
else if ((testNum % 2) != 0 );
``` |
6,211,613 | I decided to create simple *isEven* and *isOdd* function with a very simple algorithm:
```
function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
```
That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.
```
// Returns true if:
//
// n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string
(function (global) {
function basicTests(n) {
// Deal with empty string
if (n === '')
return false;
// Convert n to Number (may set to NaN)
n = Number(n);
// Deal with NaN
if (isNaN(n))
return false;
// Deal with infinity -
if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
return false;
// Return n as a number
return n;
}
function isEven(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Convert to Number and proceed
n = Number(n);
// Return true/false
return n === 0 || !!(n && !(n%2));
}
global.isEven = isEven;
// Returns true if n is an integer and (n+1) is even
// Returns false if n is not an integer or (n+1) is not even
// Empty string evaluates to zero so returns false (zero is even)
function isOdd(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Return true/false
return n === 0 || !!(n && (n%2));
}
global.isOdd = isOdd;
}(this));
```
Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?
There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript. | 2011/06/02 | [
"https://Stackoverflow.com/questions/6211613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257182/"
] | We just need one line of code for this!
Here a newer and alternative way to do this, using the new [ES6](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Functions/Arrow_functions) syntax for JS functions, and the [one-line syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) for the `if-else` statement call:
```
const isEven = num => ((num % 2) == 0);
alert(isEven(8)); //true
alert(isEven(9)); //false
alert(isEven(-8)); //true
``` | ```js
for(var a=0; a<=20;a++){
if(a%2!==0){
console.log("Odd number "+a);
}
}
for(var b=0; b<=20;a++){
if(b%2===0){
console.log("Even number "+b);
}
}
``` |
29,344,335 | I am writing a game engine, in which a set of objects held in a `ArrayList` are iterated over using a for loop. Obviously, efficiency is rather important, and so I was wondering about the efficiency of the loop.
```
for (String extension : assetLoader.getSupportedExtensions()) {
// do stuff with the extension here
}
```
Where `getSupportedExtension()` returns an `ArrayList` of `String`s. What I'm wondering is if the method is called every time the loop iterates over a new extension. If so, would it be more efficient to do something like:
```
ArrayList<String> supportedExtensions = ((IAssetLoader<?>) loader).getSupportedExtensions();
for (String extension : supportedExtensions) {
// stuff
}
```
? Thanks in advance. | 2015/03/30 | [
"https://Stackoverflow.com/questions/29344335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3025267/"
] | By specification, the idiom
```
for (String extension : assetLoader.getSupportedExtensions()) {
...
}
```
expands into
```
for (Iterator<String> it = assetLoader.getSupportedExtensions().iterator(); it.hasNext();)
{
String extension = it.next();
...
}
```
Therefore the call you ask about occurs only once, at loop init time. It is the iterator object whose methods are being called repeatedly.
However, if you are honestly interested about the performance of your application, then you should make sure you're focusing on the big wins and not small potatoes like this. It is almost impossible to make a getter call stand out as a bottleneck in any piece of code. This goes double for applications running on HotSpot, which will inline that getter call and turn it into a direct field access. | No, the method `assetLoader.getSupportedExtensions()` is called only once before the first iteration of the loop, and is used to create an `Iterator<String>` used by the enhanced for loop.
The two snippets will have the same performance. |
29,344,335 | I am writing a game engine, in which a set of objects held in a `ArrayList` are iterated over using a for loop. Obviously, efficiency is rather important, and so I was wondering about the efficiency of the loop.
```
for (String extension : assetLoader.getSupportedExtensions()) {
// do stuff with the extension here
}
```
Where `getSupportedExtension()` returns an `ArrayList` of `String`s. What I'm wondering is if the method is called every time the loop iterates over a new extension. If so, would it be more efficient to do something like:
```
ArrayList<String> supportedExtensions = ((IAssetLoader<?>) loader).getSupportedExtensions();
for (String extension : supportedExtensions) {
// stuff
}
```
? Thanks in advance. | 2015/03/30 | [
"https://Stackoverflow.com/questions/29344335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3025267/"
] | No, the method `assetLoader.getSupportedExtensions()` is called only once before the first iteration of the loop, and is used to create an `Iterator<String>` used by the enhanced for loop.
The two snippets will have the same performance. | 1. Direct cost.
Since, as people said before, the following
```
for (String extension : assetLoader.getSupportedExtensions()) {
//stuff
}
```
transforms into
```
for (Iterator<String> it = assetLoader.getSupportedExtensions().iterator(); it.hasNext();) {
String extension = it.next();
//stuf
}
```
getSupportedExtensions() is called once and both of your code snippets have the same performance cost, but not the best performance possible to go through the List, because of...
2. Indirect cost
Which is the cost of instantiation and utilization of new short-living object + cost of method next(). Method iterator() prepares an instance of Iterator. So, it is need to spend time to instantiate the object and then (when that object becomes unreachable) to GC it. The total indirect cost isn't **so** much (about 10 instructions to allocate memory for new object + a few instructions of constructor + about 5 lines of ArrayList.Itr.next() + removing of the object from Eden on minor GC), but I personally prefer indexing (or even plain arrays):
```
ArrayList<String> supportedExtensions = ((IAssetLoader<?>) loader).getSupportedExtensions();
for (int i = 0; i < supportedExtensions.size(); i++) {
String extension = supportedExtensions.get(i);
// stuff
}
```
over iterating when I have to iterate through the list frequently in the main path of my application. Some other examples of standard java code with hidden cost are some String methods (substring(), trim() etc.), NIO Selectors, boxing/unboxing of primitives to store them in Collections etc. |
29,344,335 | I am writing a game engine, in which a set of objects held in a `ArrayList` are iterated over using a for loop. Obviously, efficiency is rather important, and so I was wondering about the efficiency of the loop.
```
for (String extension : assetLoader.getSupportedExtensions()) {
// do stuff with the extension here
}
```
Where `getSupportedExtension()` returns an `ArrayList` of `String`s. What I'm wondering is if the method is called every time the loop iterates over a new extension. If so, would it be more efficient to do something like:
```
ArrayList<String> supportedExtensions = ((IAssetLoader<?>) loader).getSupportedExtensions();
for (String extension : supportedExtensions) {
// stuff
}
```
? Thanks in advance. | 2015/03/30 | [
"https://Stackoverflow.com/questions/29344335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3025267/"
] | By specification, the idiom
```
for (String extension : assetLoader.getSupportedExtensions()) {
...
}
```
expands into
```
for (Iterator<String> it = assetLoader.getSupportedExtensions().iterator(); it.hasNext();)
{
String extension = it.next();
...
}
```
Therefore the call you ask about occurs only once, at loop init time. It is the iterator object whose methods are being called repeatedly.
However, if you are honestly interested about the performance of your application, then you should make sure you're focusing on the big wins and not small potatoes like this. It is almost impossible to make a getter call stand out as a bottleneck in any piece of code. This goes double for applications running on HotSpot, which will inline that getter call and turn it into a direct field access. | 1. Direct cost.
Since, as people said before, the following
```
for (String extension : assetLoader.getSupportedExtensions()) {
//stuff
}
```
transforms into
```
for (Iterator<String> it = assetLoader.getSupportedExtensions().iterator(); it.hasNext();) {
String extension = it.next();
//stuf
}
```
getSupportedExtensions() is called once and both of your code snippets have the same performance cost, but not the best performance possible to go through the List, because of...
2. Indirect cost
Which is the cost of instantiation and utilization of new short-living object + cost of method next(). Method iterator() prepares an instance of Iterator. So, it is need to spend time to instantiate the object and then (when that object becomes unreachable) to GC it. The total indirect cost isn't **so** much (about 10 instructions to allocate memory for new object + a few instructions of constructor + about 5 lines of ArrayList.Itr.next() + removing of the object from Eden on minor GC), but I personally prefer indexing (or even plain arrays):
```
ArrayList<String> supportedExtensions = ((IAssetLoader<?>) loader).getSupportedExtensions();
for (int i = 0; i < supportedExtensions.size(); i++) {
String extension = supportedExtensions.get(i);
// stuff
}
```
over iterating when I have to iterate through the list frequently in the main path of my application. Some other examples of standard java code with hidden cost are some String methods (substring(), trim() etc.), NIO Selectors, boxing/unboxing of primitives to store them in Collections etc. |
19,909,467 | I have a few div elements on the page, each has its own border.
The problem is that the lower div border ("#a") is visible although other elements ("#b", "c#") are on top of it.
see the following JS fiddle for example and code: <http://jsfiddle.net/4jntf/>
HTML:
```
<div id="container">
<div id="a"></div>
<div id="b" class="quarter"></div>
<div id="c" class="quarter"></div>
</div>
```
CSS:
```
#container {
position: absolute;
}
#a {
background: none repeat scroll 0 0 #0099FF;
border-style: solid;
border-top-left-radius: 55px;
border-top-right-radius: 55px;
border-width: 4px;
height: 50px;
position: absolute;
width: 104px;
border-color: #ff0000;
}
#b {
border-top-left-radius: 55px;
border-width: 4px 2px 4px 4px;
float: left;
}
#c {
border-width: 4px 4px 4px 2px;
border-top-right-radius: 55px;
float: right;
}
.quarter {
background: none repeat scroll 0 0 #0099FF;
border-style: solid;
height: 50px;
width: 50px;
}
```
the desired effect I want to get is to always see the middle line, click the button to see desired effect.
the only way I have been able to get the desired effect is by giving div "#a" CSS z-index of -1, but this causes all other elements in page to be on top of it and practically invisible. | 2013/11/11 | [
"https://Stackoverflow.com/questions/19909467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1117735/"
] | The compiler turns each source file into machine code (aka object code), but doesn't create an executable program.
The linker links together one or more object files to make an executable program.
The debugger allows you to examine the program while it's running, to help investigate why it doesn't work. | [Compiler, Assembler, Linker and Loader: A Brief Story](http://www.tenouk.com/ModuleW.html)
Whereas, [Debugger](http://en.wikipedia.org/wiki/Debugger) is a different beast compared to the above.
A lot of information is already available on this topic. Just use your favorite search engine :) |
19,909,467 | I have a few div elements on the page, each has its own border.
The problem is that the lower div border ("#a") is visible although other elements ("#b", "c#") are on top of it.
see the following JS fiddle for example and code: <http://jsfiddle.net/4jntf/>
HTML:
```
<div id="container">
<div id="a"></div>
<div id="b" class="quarter"></div>
<div id="c" class="quarter"></div>
</div>
```
CSS:
```
#container {
position: absolute;
}
#a {
background: none repeat scroll 0 0 #0099FF;
border-style: solid;
border-top-left-radius: 55px;
border-top-right-radius: 55px;
border-width: 4px;
height: 50px;
position: absolute;
width: 104px;
border-color: #ff0000;
}
#b {
border-top-left-radius: 55px;
border-width: 4px 2px 4px 4px;
float: left;
}
#c {
border-width: 4px 4px 4px 2px;
border-top-right-radius: 55px;
float: right;
}
.quarter {
background: none repeat scroll 0 0 #0099FF;
border-style: solid;
height: 50px;
width: 50px;
}
```
the desired effect I want to get is to always see the middle line, click the button to see desired effect.
the only way I have been able to get the desired effect is by giving div "#a" CSS z-index of -1, but this causes all other elements in page to be on top of it and practically invisible. | 2013/11/11 | [
"https://Stackoverflow.com/questions/19909467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1117735/"
] | The compiler turns each source file into machine code (aka object code), but doesn't create an executable program.
The linker links together one or more object files to make an executable program.
The debugger allows you to examine the program while it's running, to help investigate why it doesn't work. | Very roughly, the compiler converts from human-readable source code into (almost) machine-runnable object code, and the linker joins up all the different sections of object code (and external libraries) to form a complete program.
The debugger is totally separate. It lets the programmer analyse what's happening when the program runs, with the aim of tracking down mistakes and errors. |
49,937,863 | >
> error
> .Uncaught SyntaxError: Invalid shorthand property initializer angular.js:38 Uncaught Error: [$injector:modulerr] <http://errors.angularjs.org/1.4.5/>$injector/modul
>
>
>
This is my **app.js** code:
```
var myApp = angular.module("myapp", ["ngRoute"]);
myApp.controller("myController", function($scope){
console.log("This is app.js ...........");
$scope.users = [
{username="John" , email="john@mail.com"},
{username="Adam" , email="Adam@adam.com"}
];
});
```
This is my **index.html** code:
```
<!DOCTYPE html>
<html lang="en-US">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myController">
<div class="container">
<button type="button" class="btn btn-primary pull-right"
data-toggle="modal" data-target="#myModal">Add Product</button>
<h2>Product List</h2>
<table class="table table-striped">
<thead>
<tr>
<th>Index</th>
<th>UserName</th>
<th>Email</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users">
<td>{{$index+1}}</td>
<td>{{user.username}}</td>
<td>{{user.email}}</td>
<td>
<button type="button" class="btn btn-warning" data-toggle="modal"
data-target="#myModalEdit">Edit</button>
</td>
<td>
<button type="button" class="btn btn-danger" data-toggle="modal"
data-target="#myModalDelete">delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
``` | 2018/04/20 | [
"https://Stackoverflow.com/questions/49937863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7336130/"
] | Fix `ng-app="myApp"` to `ng-app="myapp"` in html file. [check this plunkr](https://plnkr.co/edit/DUqZ7xwhOwydfkxtjMT8?p=preview)
```
var myApp = angular.module("myApp", []);
myApp.controller("myController", function($scope){
console.log("This is app.js ...........");
$scope.users = [
{username: "John" , email:"john@mail.com"},
{username:"Adam" , email:"Adam@adam.com"}
];
});
``` | That's not the way to declare an object. Replace = with :
```
$scope.users = [
{username:"Shanto" , email:"shanto@gmail.com"},
{username : "Adam" , email : "Adam@adam.com"}
];
``` |
28,080,911 | New to the site as well as c#. This is my first time using c# and I can't get my objects to print properly. (example Million, Max 55. Cardenas, Jose, 22). I am pretty sure the error is in my accessors but I can't seem to get it right.
```
using System.IO;
using System;
class PersonApp
{
static void Main()
{
Random random = new Random();
Person p1 = new Person();
Person p2 = new Person();
p1.Fname = "Max";
p1.Lname = "Million";
p1.Id = random.Next(1,100);
p2.Fname = "Jose";
p2.Lname = "Cardenas";
p2.Id = random.Next(1,100);
Console.WriteLine(p1,p2);
}
}
using System.IO;
using System;
public class Person
{
private string Fname;
private string Lname;
private int Id;
public Person(){
Fname = string.empty;
Lname = string.empty;
Id = 0;
}
public string Fname
{
get
{
return Fname;
}
set
{
Fname = value;
}
}
public string Lname
{
get
{
return Lname;
}
set
{
Lname = value;
}
}
public int Id
{
get
{
return Id;
}
set
{
Id = value;
}
}
}
``` | 2015/01/22 | [
"https://Stackoverflow.com/questions/28080911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4480881/"
] | You need to access property of the method to get the values printed
Wrong code :
```
Console.WriteLine(p1,p2); // You are trying to print Objects and this is wrong. !!
```
Correction : Use accessory's get to print the output.
```
Console.WriteLine(p1.Fname); // Print first name "Max"
```
Likewise
```
Console.WriteLine(p1.Lname); // print Last name
Console.WriteLine(p1.Id); // Print ID
```
Also your class need to be corrected
```
using System.IO;
using System;
public class Person{
private string fname;
private string lname;
private int id;
public string Fname
{
get
{
return fname;
}
set
{
fname = value;
}
}
public string Lname
{
get
{
return lname;
}
set
{
lname = value;
}
}
public int Id
{
get
{
return id;
}
set
{
id = value;
}
}
}
```
Now you can use it like
```
Person a = new Person();
a.Fname = "k";
a.Lname = "Do";
a.Id = 1024;
Console.WriteLine(a.Fname+" "+a.Lname+" "+a.Id);
``` | You can't expect C# to know the format you want the object output in. You have to concatenate the strings yourself to produce the output.
The neatest way to do this is expose a readonly property on `Person` that formats it how you want, something like this:
```
public string DisplayName {
get {
return Lname + ", " + Fname + " " + Id;
}
}
``` |
28,080,911 | New to the site as well as c#. This is my first time using c# and I can't get my objects to print properly. (example Million, Max 55. Cardenas, Jose, 22). I am pretty sure the error is in my accessors but I can't seem to get it right.
```
using System.IO;
using System;
class PersonApp
{
static void Main()
{
Random random = new Random();
Person p1 = new Person();
Person p2 = new Person();
p1.Fname = "Max";
p1.Lname = "Million";
p1.Id = random.Next(1,100);
p2.Fname = "Jose";
p2.Lname = "Cardenas";
p2.Id = random.Next(1,100);
Console.WriteLine(p1,p2);
}
}
using System.IO;
using System;
public class Person
{
private string Fname;
private string Lname;
private int Id;
public Person(){
Fname = string.empty;
Lname = string.empty;
Id = 0;
}
public string Fname
{
get
{
return Fname;
}
set
{
Fname = value;
}
}
public string Lname
{
get
{
return Lname;
}
set
{
Lname = value;
}
}
public int Id
{
get
{
return Id;
}
set
{
Id = value;
}
}
}
``` | 2015/01/22 | [
"https://Stackoverflow.com/questions/28080911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4480881/"
] | You have a few issues in your code.
First, you can't pass multiple values to `Console.WriteLine` like this:
```
Console.WriteLine(p1, p2);
```
Do one at a time:
```
Console.WriteLine(p1);
Console.WriteLine(p2);
```
Second, you can't name your private backing field and the public property used to get/set it the same. You can name them whatever you want... typically the private variable starts with a lower case or an underscore, but that's up to you.
Once you fix those, you'll still get unusual output, which is actually the full namespace of your class. That's the result of `ToString()` being implicitly called when you pass `p1` to `Console.WriteLine`.
Override the `ToString()` method in your class:
```
public class Person
{
private string Fname;
private string Lname;
private int Id;
private override string ToString()
{
return string.Format("{0}, {1} {2}", Lname, Fname, Id);
}
...
...
}
``` | You can't expect C# to know the format you want the object output in. You have to concatenate the strings yourself to produce the output.
The neatest way to do this is expose a readonly property on `Person` that formats it how you want, something like this:
```
public string DisplayName {
get {
return Lname + ", " + Fname + " " + Id;
}
}
``` |
211,740 | We know that $$\oint \boldsymbol{F}\cdot d\boldsymbol{r}= \iint (\nabla \times \boldsymbol{F})\cdot d\boldsymbol{s}.$$ Now if $\boldsymbol{F}$ is a constant vector, then $\nabla \times \boldsymbol{F}=0$, this gives that $\oint \boldsymbol{F}\cdot d\boldsymbol{r}=0$. And $\oint \boldsymbol{F} \cdot d\boldsymbol{r}$ represents the work $$W=\int \boldsymbol{F} \cdot d\boldsymbol{r}$$ done by the vector field $\boldsymbol{F}$ along a curve. So this gives that work done by a constant vector field is $0$. How can it be possible? | 2015/10/10 | [
"https://physics.stackexchange.com/questions/211740",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/94972/"
] | This isn't surprising. Remember, $\oint$ means that you're integrating around a closed path. Without that requirement you can't use Stokes's Theorem to get a curl. All you've shown is that a constant vector does no work if you go in a big loop. This is the situation with, for instance, gravity close to Earth's surface. You throw a ball in the air, and when it returns to where it started it has the same amount of energy (it's just going the opposite direction). | It is possible for conservative forces. Closed integral of a conservative force (say Electric force) is zero.[](https://i.stack.imgur.com/22KrX.png) |
211,740 | We know that $$\oint \boldsymbol{F}\cdot d\boldsymbol{r}= \iint (\nabla \times \boldsymbol{F})\cdot d\boldsymbol{s}.$$ Now if $\boldsymbol{F}$ is a constant vector, then $\nabla \times \boldsymbol{F}=0$, this gives that $\oint \boldsymbol{F}\cdot d\boldsymbol{r}=0$. And $\oint \boldsymbol{F} \cdot d\boldsymbol{r}$ represents the work $$W=\int \boldsymbol{F} \cdot d\boldsymbol{r}$$ done by the vector field $\boldsymbol{F}$ along a curve. So this gives that work done by a constant vector field is $0$. How can it be possible? | 2015/10/10 | [
"https://physics.stackexchange.com/questions/211740",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/94972/"
] | It's perfectly possible, because it's not just any work; it's the work done around a closed curve. If you have a uniform force field (which is a special case of a conservative force field) and you move an object around in a closed curve you won't get any **net** work out of the force field. A good example is gravity close to the Earth's surface. | It is possible for conservative forces. Closed integral of a conservative force (say Electric force) is zero.[](https://i.stack.imgur.com/22KrX.png) |
23,594,867 | I have a JTextArea in which i want to display messages aligned to right or left, depending on a variable I pass along with the message. Can I do that?
---
What did I do wrong? Nothing gers added to the text pane when i run my GUI
```
battleLog = new JTextPane();
StyledDocument bL = battleLog.getStyledDocument();
SimpleAttributeSet r = new SimpleAttributeSet();
StyleConstants.setAlignment(r, StyleConstants.ALIGN_RIGHT);
try {
bL.insertString(bL.getLength(), "test", r);
} catch (BadLocationException e1) {
e1.printStackTrace();
}
``` | 2014/05/11 | [
"https://Stackoverflow.com/questions/23594867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3450315/"
] | Not with a JTextArea.
You need to use a `JTextPane` which supports different text and paragraph attributes. An example to CENTER the text:
```
JTextPane textPane = new JTextPane();
textPane.setText("Line1");
StyledDocument doc = textPane.getStyledDocument();
// Define the attribute you want for the line of text
SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
// Add some text to the end of the Document
try
{
int length = doc.getLength();
doc.insertString(doc.getLength(), "\ntest", null);
doc.setParagraphAttributes(length+1, 1, center, false);
}
catch(Exception e) { System.out.println(e);}
``` | ```
if("left".equals(input)){
setAlignmentX(Component.LEFT_ALIGNMENT);
}
```
Have a try! |
370,781 | I have a custom post type called products, which I have attached a custom taxonomy called Product Categories.
On each of the Product Categories, I have used Advanced Custom Fields to add fields such as product category colour, logo etc.
Initially, I'm trying to display the Product Category colour as a background colour for all of the products that fall inside that specific Product Category.
I've tried using the same method as I used to display the colour on the actual Product Category page (taxonomy-product\_category.php), by adding this to the top of the page:
```
// get the current taxonomy term
$term = get_queried_object();
// vars
$category_colour_primary = get_field('category_colour_primary', $term);
```
and then referencing it later on like this:
```
<div class="container-flex" style="background-color:<?php echo $category_colour_secondary; ?>;">
</div>
```
This works great on each of the Product Category pages, but doesn't seem to work on the single page template (single-products.php).
I feel I need to get the name (or terms?!) of the current product's taxonomy and then display them as usual...
I've come to a bit of a dead end and I'm unsure what I need to try next...
Can anyone point me in the right direction? I feel I've tried a million things, but can't quite get my head around it. Thanks for looking! | 2020/07/10 | [
"https://wordpress.stackexchange.com/questions/370781",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112099/"
] | I would try something like this...
```php
// Assume there is only one category.
$product_category = get_the_terms($post, 'product-category')[0];
$cat_fields = get_fields("term_$product_category");
$color = $cat_fields['category_colour_primary'];
```
You could also do this...
```php
// Assume there is only one category.
$product_category = get_the_terms($post, 'product-category')[0];
$color = get_field('category_colour_primary', "term_$product_category");
``` | Managed to get it working with the following code:
```
<?php
$terms = wp_get_object_terms($post->ID, 'product_category');
if(!empty($terms)){
foreach($terms as $term){
$exampleName = $term->name;
$exampleSlugs[] = $term->slug;
$category_colour_primary = get_field('category_colour_primary', $term);
$category_colour_secondary = get_field('category_colour_secondary', $term);
}
}
?>
``` |
11,782,812 | I'm sorry, for I'm sure there's a way to do this with a viewModel, however I'm very inexperienced with this and don't even know if I'm doing it correctly.
What I'm trying to do is pass multiple blogs and the profile info of the user who posted each blog to a view.
I'm getting the following error.
>
> The model item passed into the dictionary is of type
> 'ACapture.Models.ViewModels.BlogViewModel', but this dictionary
> requires a model item of type
> 'System.Collections.Generic.IEnumerable`1[ACapture.Models.ViewModels.BlogViewModel]'.
>
>
>
I'm trying to pass the following query results to the view.
```
var results = (from r in db.Blog.AsEnumerable()
join a in db.Profile on r.AccountID equals a.AccountID
select new { r, a });
return View(new BlogViewModel(results.ToList()));
}
```
This is my viewModel
```
public class BlogViewModel
{
private object p;
public BlogViewModel(object p)
{
this.p = p;
}
}
```
And my view
```
@model IEnumerable<ACapture.Models.ViewModels.BlogViewModel>
@{
ViewBag.Title = "Home Page";
}
<div class="Forum">
<p>The Forum</p>
@foreach (var item in Model)
{
<div class="ForumChild">
<img src="@item.image.img_path" alt="Not Found" />
<br />
<table>
@foreach (var comment in item.comment)
{
<tr><td></td><td>@comment.Commentation</td></tr>
}
</table>
</div>
}
</div>
```
Thanks in advance. | 2012/08/02 | [
"https://Stackoverflow.com/questions/11782812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1196221/"
] | I guess you need to change your view model a little to:
```
public class BlogViewModel
{
public Blog Blog { get; set; }
public Profile Profile{ get; set; }
}
```
and then return it as follow:
```
var results = (from r in db.Blog.AsEnumerable()
join a in db.Profile on r.AccountID equals a.AccountID
select new new BlogViewModel { Blog = r, Profile = a });
return View(results.ToList());
```
Then in your `foreach` loop inside of view, you will get an objects that will contain both - profile and blog info, so you can use it like f.e. `@item.Profile.Username` | I'm not entirely sure what you're trying to accomplish with the ViewModel in this case, but it seems like you are expecting for the page to represent a single blog with a collection of comments. In this case you should replace
```
IEnumerable<ACapture.Models.ViewModels.BlogViewModel>
```
With
```
ACapture.Models.ViewModels.BlogViewModel
```
Then `Model` represents a single BlogViewModel, that you can iterate over the comments by using `Model.comments` and access the image using `Model.image.img_path`.
If this not the case, and you intend to have multiple BlogViewModels per page, then you will have to actually construct a collection of BlogViewModels and pass that to the view instead. |
7,489 | We try to add the invoice status column to the sales order grid.
We added the code beneath to the prepareCollection function:
```
$collection->getSelect()->join('sales_flat_invoice', 'main_table.entity_id = sales_flat_invoice.parent_id',array('state'));
```
And the code beneath to the prepareColumns function:
```
$this->addColumn('state', array(
'header' => Mage::helper('sales')->__('Invoice Status'),
'index' => 'state',
'type' => 'options',
'options' => Mage::getResourceModel('sales/order_invoice_collection')->addAttributeToSelect('state'),
));
```
We got the following error:
```
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sales_flat_invoice.parent_id' in 'on clause'
```
What is going wrong? | 2013/09/03 | [
"https://magento.stackexchange.com/questions/7489",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/2289/"
] | Firstly - **be careful with joining live tables on your sales\_order\_grid** in the admin view. The reason is simple - any action or long-running query that your admins might be executing (for instance, sorting by a custom unindexed column with no other filters and 300k+ orders) may cause locks for your join table and prevent production orders.
Your column defines this as `type` of `options` but the option list you're providing is the entire invoice collection!!!
Out of the box, invoice `state` is only 1 of 3 potential values:
```
/**
* Invoice states
*/
const STATE_OPEN = 1;
const STATE_PAID = 2;
const STATE_CANCELED = 3;
```
So you can handle it one of two ways - explicitly state the options:
```
'type' => 'options',
'options' => array(
'1' => Mage::helper('core')->__('Open'),
'2' => Mage::helper('core')->__('Paid'),
'3' => Mage::helper('core')->__('Canceled'),
),
```
Or, use something handy that Magento provides -- a static method for all invoice states in case they differ from version to version:
```
'type' => 'options',
'options' => Mage_Sales_Model_Order_Invoice::getStates()
```
I prefer the latter as I am not a fan of typing out array options manually :)
Cheers. | Replace `sales_flat_invoice.parent_id` with `sales_flat_invoice.order_id`. Not sure if it will give you the desired result, but you won't get the error anymore. The reference to the order table is kept in `order_id`. `parent_id` does not exist. |
7,489 | We try to add the invoice status column to the sales order grid.
We added the code beneath to the prepareCollection function:
```
$collection->getSelect()->join('sales_flat_invoice', 'main_table.entity_id = sales_flat_invoice.parent_id',array('state'));
```
And the code beneath to the prepareColumns function:
```
$this->addColumn('state', array(
'header' => Mage::helper('sales')->__('Invoice Status'),
'index' => 'state',
'type' => 'options',
'options' => Mage::getResourceModel('sales/order_invoice_collection')->addAttributeToSelect('state'),
));
```
We got the following error:
```
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sales_flat_invoice.parent_id' in 'on clause'
```
What is going wrong? | 2013/09/03 | [
"https://magento.stackexchange.com/questions/7489",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/2289/"
] | Replace `sales_flat_invoice.parent_id` with `sales_flat_invoice.order_id`. Not sure if it will give you the desired result, but you won't get the error anymore. The reference to the order table is kept in `order_id`. `parent_id` does not exist. | If you want to add the invoice id in the sales order grid then you can use the following code in your prepareCollection() function as
```
$collection->getSelect()->joinLeft('sales_flat_invoice', 'main_table.entity_id = sales_flat_invoice.order_id', 'increment_id as invoice_id');
```
By using the following code you will able to get the invoice id from the current order id in sales order grid.
after this add column field as
```
$this->addColumn('invoice_id',
array(
'header'=> $this->__('Invoice Id'),
'align' =>'right',
'type=' => 'text',
'index' => 'invoice_id',
)
);
```
For more follow me on
<http://www.webtechnologycodes.com> |
7,489 | We try to add the invoice status column to the sales order grid.
We added the code beneath to the prepareCollection function:
```
$collection->getSelect()->join('sales_flat_invoice', 'main_table.entity_id = sales_flat_invoice.parent_id',array('state'));
```
And the code beneath to the prepareColumns function:
```
$this->addColumn('state', array(
'header' => Mage::helper('sales')->__('Invoice Status'),
'index' => 'state',
'type' => 'options',
'options' => Mage::getResourceModel('sales/order_invoice_collection')->addAttributeToSelect('state'),
));
```
We got the following error:
```
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sales_flat_invoice.parent_id' in 'on clause'
```
What is going wrong? | 2013/09/03 | [
"https://magento.stackexchange.com/questions/7489",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/2289/"
] | Replace `sales_flat_invoice.parent_id` with `sales_flat_invoice.order_id`. Not sure if it will give you the desired result, but you won't get the error anymore. The reference to the order table is kept in `order_id`. `parent_id` does not exist. | ```
$collection->getSelect()->joinLeft(array('soa'=> 'sales_flat_invoice'), 'soa.entity_id = main_table.entity_id', array('soa.state'));
$this->addColumn('state', array(
'header' => Mage::helper('sales')->__('invoice Status'),
'index' => 'state',
'type' => 'options',
'filter_index' => 'soa.state',
'options' => array(
'1' || '3' => Mage::helper('core')->__('0'),
'2' => Mage::helper('core')->__('1')),
//'3' => Mage::helper('core')->__('cancelled')),
));
``` |
7,489 | We try to add the invoice status column to the sales order grid.
We added the code beneath to the prepareCollection function:
```
$collection->getSelect()->join('sales_flat_invoice', 'main_table.entity_id = sales_flat_invoice.parent_id',array('state'));
```
And the code beneath to the prepareColumns function:
```
$this->addColumn('state', array(
'header' => Mage::helper('sales')->__('Invoice Status'),
'index' => 'state',
'type' => 'options',
'options' => Mage::getResourceModel('sales/order_invoice_collection')->addAttributeToSelect('state'),
));
```
We got the following error:
```
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sales_flat_invoice.parent_id' in 'on clause'
```
What is going wrong? | 2013/09/03 | [
"https://magento.stackexchange.com/questions/7489",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/2289/"
] | Firstly - **be careful with joining live tables on your sales\_order\_grid** in the admin view. The reason is simple - any action or long-running query that your admins might be executing (for instance, sorting by a custom unindexed column with no other filters and 300k+ orders) may cause locks for your join table and prevent production orders.
Your column defines this as `type` of `options` but the option list you're providing is the entire invoice collection!!!
Out of the box, invoice `state` is only 1 of 3 potential values:
```
/**
* Invoice states
*/
const STATE_OPEN = 1;
const STATE_PAID = 2;
const STATE_CANCELED = 3;
```
So you can handle it one of two ways - explicitly state the options:
```
'type' => 'options',
'options' => array(
'1' => Mage::helper('core')->__('Open'),
'2' => Mage::helper('core')->__('Paid'),
'3' => Mage::helper('core')->__('Canceled'),
),
```
Or, use something handy that Magento provides -- a static method for all invoice states in case they differ from version to version:
```
'type' => 'options',
'options' => Mage_Sales_Model_Order_Invoice::getStates()
```
I prefer the latter as I am not a fan of typing out array options manually :)
Cheers. | If you want to add the invoice id in the sales order grid then you can use the following code in your prepareCollection() function as
```
$collection->getSelect()->joinLeft('sales_flat_invoice', 'main_table.entity_id = sales_flat_invoice.order_id', 'increment_id as invoice_id');
```
By using the following code you will able to get the invoice id from the current order id in sales order grid.
after this add column field as
```
$this->addColumn('invoice_id',
array(
'header'=> $this->__('Invoice Id'),
'align' =>'right',
'type=' => 'text',
'index' => 'invoice_id',
)
);
```
For more follow me on
<http://www.webtechnologycodes.com> |
7,489 | We try to add the invoice status column to the sales order grid.
We added the code beneath to the prepareCollection function:
```
$collection->getSelect()->join('sales_flat_invoice', 'main_table.entity_id = sales_flat_invoice.parent_id',array('state'));
```
And the code beneath to the prepareColumns function:
```
$this->addColumn('state', array(
'header' => Mage::helper('sales')->__('Invoice Status'),
'index' => 'state',
'type' => 'options',
'options' => Mage::getResourceModel('sales/order_invoice_collection')->addAttributeToSelect('state'),
));
```
We got the following error:
```
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sales_flat_invoice.parent_id' in 'on clause'
```
What is going wrong? | 2013/09/03 | [
"https://magento.stackexchange.com/questions/7489",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/2289/"
] | Firstly - **be careful with joining live tables on your sales\_order\_grid** in the admin view. The reason is simple - any action or long-running query that your admins might be executing (for instance, sorting by a custom unindexed column with no other filters and 300k+ orders) may cause locks for your join table and prevent production orders.
Your column defines this as `type` of `options` but the option list you're providing is the entire invoice collection!!!
Out of the box, invoice `state` is only 1 of 3 potential values:
```
/**
* Invoice states
*/
const STATE_OPEN = 1;
const STATE_PAID = 2;
const STATE_CANCELED = 3;
```
So you can handle it one of two ways - explicitly state the options:
```
'type' => 'options',
'options' => array(
'1' => Mage::helper('core')->__('Open'),
'2' => Mage::helper('core')->__('Paid'),
'3' => Mage::helper('core')->__('Canceled'),
),
```
Or, use something handy that Magento provides -- a static method for all invoice states in case they differ from version to version:
```
'type' => 'options',
'options' => Mage_Sales_Model_Order_Invoice::getStates()
```
I prefer the latter as I am not a fan of typing out array options manually :)
Cheers. | ```
$collection->getSelect()->joinLeft(array('soa'=> 'sales_flat_invoice'), 'soa.entity_id = main_table.entity_id', array('soa.state'));
$this->addColumn('state', array(
'header' => Mage::helper('sales')->__('invoice Status'),
'index' => 'state',
'type' => 'options',
'filter_index' => 'soa.state',
'options' => array(
'1' || '3' => Mage::helper('core')->__('0'),
'2' => Mage::helper('core')->__('1')),
//'3' => Mage::helper('core')->__('cancelled')),
));
``` |
11,420,894 | I cannot figure out which way it goes. It seems like casting it into an int would make more sense because of the whole float point issue but like I said, I am not sure. Does anyone know? | 2012/07/10 | [
"https://Stackoverflow.com/questions/11420894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1260028/"
] | Try this code:
```
#include <stdio.h>
int main(void)
{
if (100.1 == 100)
printf("Must be integer compare\n");
else
printf("Must be floating point compare\n");
return 0;
}
```
Also, think about things like `int i = 10; float j = 100.5 + i;` or `100.2 == 100`. You don't want it to be done with integers! | It's listed in 6.3.1.8 under "the usual arithmetic conversions".
>
> Otherwise, if the corresponding real type of either operand is double,
> the other operand is converted, without change of type domain,
> to a type whose corresponding real type is double
>
>
>
And 6.5.9 spells it for `==`:
>
> If both of the operands have arithmetic type, the usual
> arithmetic conversions are performed.
>
>
>
### EDIT
I am citing C11 N1570. |
11,289,342 | When learning C I see that `printf` can receive many arguments as it is passed.
And I don't know how C can implement a function like this, where the user can type as many parameters as the user wants. I have thought about pointers, too but still have no bright idea. If anyone has any ideas about this type of function, please tell me. | 2012/07/02 | [
"https://Stackoverflow.com/questions/11289342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1192728/"
] | You need to use va\_args, va\_list and the like.
Have a look at this tutorial.
<http://www.cprogramming.com/tutorial/c/lesson17.html>
That should be helpful. | You have to use the `...` notation in your function declaration as the last argument.
Please see this tutorial to learn more: <http://www.cprogramming.com/tutorial/c/lesson17.html> |
11,289,342 | When learning C I see that `printf` can receive many arguments as it is passed.
And I don't know how C can implement a function like this, where the user can type as many parameters as the user wants. I have thought about pointers, too but still have no bright idea. If anyone has any ideas about this type of function, please tell me. | 2012/07/02 | [
"https://Stackoverflow.com/questions/11289342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1192728/"
] | You need to use va\_args, va\_list and the like.
Have a look at this tutorial.
<http://www.cprogramming.com/tutorial/c/lesson17.html>
That should be helpful. | You use C `varargs` to write a *variadic function*. You'll need to include `stdargs.h`, which gives you macros for iterating over an argument list of unknown size: `va_start`, `va_arg`, and `va_end`, using a datatype: `va_list`.
Here's a mostly useless function that prints out it's variable length argument list:
```
void printArgs(const char *arg1, ...)
{
va_list args;
char *str;
if (arg1) We
va_start(args, arg1);
printf("%s ", arg1);
while ((str = va_arg(argp, char *)) != NULL)
printf("%s ", str);
va_end(args);
}
}
...
printArgs("print", "any", "number", "of", "arguments");
```
[Here's](http://c-faq.com/varargs/varargs1.html) a more interesting example that demonstrates that you can iterate over the argument list more than once.
Note that there are type safety issues using this feature; the [wiki article](http://en.wikipedia.org/w/index.php?title=Stdarg.h#Type_safety) addresses some of this. |
11,289,342 | When learning C I see that `printf` can receive many arguments as it is passed.
And I don't know how C can implement a function like this, where the user can type as many parameters as the user wants. I have thought about pointers, too but still have no bright idea. If anyone has any ideas about this type of function, please tell me. | 2012/07/02 | [
"https://Stackoverflow.com/questions/11289342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1192728/"
] | You need to use va\_args, va\_list and the like.
Have a look at this tutorial.
<http://www.cprogramming.com/tutorial/c/lesson17.html>
That should be helpful. | ```
#include <stdarg.h>
#include <stdio.h>
int add_all(int num,...)
{
va_list args;
int sum = 0;
va_start(args,num);
int x = 0;
for(x = 0; x < num;x++)
sum += va_arg(args,int);
va_end(args);
return sum;
}
int main()
{
printf("Added 2 + 5 + 3: %d\n",add_all(3,2,5,3));
}
``` |
60,901,780 | So to provide context, my system is little endian and the file that I am reading from is big endian (MIDI format, for those that are interested). I am supposed to read a variety of data from the file, including unsigned integers (8 bit, 16 bit, and 32 bit), chars, and booleans.
So far I know that reading unsigned integers will be an issue with fread() because I would have to convert them from big endian to little endian. My first question is, although maybe stupid to some, do I need to convert chars and booleans as well?
My second question is regarding the entire file format. Since the file is in a different endian system, do I need to read the file from the end towards the beginning (since the MSB and LSB positions will be different)? Or do I need to read in the values from the start to the end, like I would normally, and then convert those to little endian?
Thanks for taking the time to read my post and for any answers that I might receive! | 2020/03/28 | [
"https://Stackoverflow.com/questions/60901780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I believe you have mistaken the `contractions` package available on [PyPI](https://pypi.org/project/contractions/) with the `contractions` module from a textbook called "Text Analytics with Python" ([source code](https://github.com/dipanjanS/text-analytics-with-python/tree/master/Old-First-Edition)).
The `CONTRACTIONS_MAP` variable is defined in the latter and is not part of the `contractions` package API (documented in the [GitHub Readme.md](https://github.com/kootenpv/contractions)).
From the documentation, the package can be used to fix contractions like:
```
import contractions
contractions.fix("you're happy now")
# "you are happy now"
```
If you want access to the map of contraction to expanded version, this can be imported using:
```
from contractions import contractions_dict
```
This `contractions_dict` contains entries like:
```
{..., 'you’ll': 'you will', ...}
``` | after you install contractions by pip install contractions, you can use contractions\_dict instead of CONTRACTION\_MAP |
603,469 | I recently downloaded Puppy Linux which is almost 280MB .iso file. I had a 4GB USB drive. So I fired up good old `dd` command to burn the iso to the live usb. Everything went well, however, after live boot, all I was left with was 4MB ish disk space in the USB. Then I formatted it, burned a Debian distro in the same USB, and live booted and also got the same 4MB ish space left. Are there any ways to get around, because I think PuppyLinux would most probably not use all of the space as same as a 3GB .iso file from a Debian distro. | 2020/08/08 | [
"https://unix.stackexchange.com/questions/603469",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/387728/"
] | try:
```
sed "s/\$t\>/foo/g" /tmp/file
```
`\>` is a regular expression pattern match for the end of the word. | Tried with below sed and awk command
```
awk '{for(i=1;i<=NF;i++){if($i =="$t"){gsub(/\$t/,"foo",$i)}}}1' filename
```
sed command
```
sed "s/\$t /foo /g" filename
```
output
```
$one foo $three
$one foo $three foo $thre
```
e |
2,346,363 | Am wondering if there are any drawbacks of using Adobe Stratus. Since it is only P2P, when will there be a case where P2P can't be used? On the site it says something like when UDP packets are blocked. How often is that? Say a thousand people use the service, approximately what percentage would not be able to use it?
Also, is it possible to port a Stratus app to AFCS/LCCS without any modification?
Thank you for your time. | 2010/02/27 | [
"https://Stackoverflow.com/questions/2346363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/426996/"
] | About half on average are not able to talk directly. Depending on service provider, organization if any, country, continent, weather, extraterrestrial presence etc :-) | I have been looking at this for a client who is developing a peer to peer video conferencing app.
In his experience about 10%+ of people out of a small group surveyed had UDP blocked, and therefore were unable to use Adobe Stratus to make connections and LTMFP |
2,346,363 | Am wondering if there are any drawbacks of using Adobe Stratus. Since it is only P2P, when will there be a case where P2P can't be used? On the site it says something like when UDP packets are blocked. How often is that? Say a thousand people use the service, approximately what percentage would not be able to use it?
Also, is it possible to port a Stratus app to AFCS/LCCS without any modification?
Thank you for your time. | 2010/02/27 | [
"https://Stackoverflow.com/questions/2346363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/426996/"
] | with a pretty global audience, i had about 20% failing the initial test with cc.rtmfp.net . then a number of those who passed couldn't make direct connections to some users, although they could with others.
i wouldn't use stratus by itself for anything where reliability matters. use fms until red5 adds support for rtmfp | I have been looking at this for a client who is developing a peer to peer video conferencing app.
In his experience about 10%+ of people out of a small group surveyed had UDP blocked, and therefore were unable to use Adobe Stratus to make connections and LTMFP |
64,267,107 | My problem that is in a child component, I have a state that updated via post method and I must show this state in my parent component both these component are the class base component | 2020/10/08 | [
"https://Stackoverflow.com/questions/64267107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13935145/"
] | The ReactJS is a library with **One directional data binding**. So that is not possible to pass data like *Angular* or *VueJS*. you should pass a handler function to the child-component and then after the *Axios* answer update the local and also the parent component.
And there is a little hint here, there is no different for your situation between *class components* and *functional components*. pay attention to the sample code:
```js
class ParentComponent extends React.Component {
state = {
data: undefined,
};
handleGetData = data => {
this.setState({
data,
});
};
render() {
return (
<ChildComponent onGetData={this.handleGetData} />
);
}
}
```
And now inside the *ChildComponent* you can access to the handler function:
```js
class ChildComponent extends React.Component {
componentDidMound() {
const { onGetData } = this.props;
Axios
.get('someSampleUrl')
.then( (data) => {
onGetData(data); // running this update your parent state
});
}
render() {
return (
<div />
);
}
}
``` | React's practice is one-directional. For best practice, you must 'Raise' the states into the parent component.
But if you were looking specifically to pass data up, you need to pass a callback down as a prop. use that callback function to pass the data up:
Parent:
```
<Parent>
<Child callback={console.log} />
</Parent>
```
Child:
```
const Child = (props) => {
const { callback } = props;
const postData = (...) => {
...
callback(result);
}
...
}
``` |
14,847,635 | I am using .NET framework 1.1 with C#. My problem description is given below.
1. I have server side textbox control with id:= *txtFromDate*. view state is enabled and its readonly.
2. when page loaded for the first time i am setting current date value in above textbox.
3. after that I change the value of textbox with jQuery.
4. then posting back the page using jQuery with some \_\_EVENTTARGET parameters.
5. I am using this changed textbox value in my code behind.
I have developed code in window XP machine 32 bit with 1.1 framework. But now I have put entire site on windows server 2008 R2 edition (64bit) in .NET 2.0 application pool
*Problem:* it works fine on development machine. but in windows server 2008 change in textbox value by jQuery is not being reflected in code behind. it retains old value which I assign when page gets loaded first time.
I want to run this application as it runs on my development machine.
In short I want to get changed value of textbox in codebehind on windows server 2008 machine too.
Thanks. | 2013/02/13 | [
"https://Stackoverflow.com/questions/14847635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1046955/"
] | Instead of using **txtFromDate.Text** I used **Request.Form[txtFromDate.ClientID]** and problem got solved. | Although you can always use set get method to store the values from java script ... But here is some simple way to solve it...
case 1 - If control is just for storing purpose ,
put display : none in it's style and make visible = true in the attribute of the control.
case 2 - if control is to be displayed but in disabled mode put ReadOnly="true" instead of Enabled = true
eg..
```
<asp:textbox runat="server" ID="textbox1" Enabled="false"></asp:textbox> will not work
<asp:textbox runat="server" ID="textbox2" ReadOnly="true"></asp:textbox> will work
``` |
14,847,635 | I am using .NET framework 1.1 with C#. My problem description is given below.
1. I have server side textbox control with id:= *txtFromDate*. view state is enabled and its readonly.
2. when page loaded for the first time i am setting current date value in above textbox.
3. after that I change the value of textbox with jQuery.
4. then posting back the page using jQuery with some \_\_EVENTTARGET parameters.
5. I am using this changed textbox value in my code behind.
I have developed code in window XP machine 32 bit with 1.1 framework. But now I have put entire site on windows server 2008 R2 edition (64bit) in .NET 2.0 application pool
*Problem:* it works fine on development machine. but in windows server 2008 change in textbox value by jQuery is not being reflected in code behind. it retains old value which I assign when page gets loaded first time.
I want to run this application as it runs on my development machine.
In short I want to get changed value of textbox in codebehind on windows server 2008 machine too.
Thanks. | 2013/02/13 | [
"https://Stackoverflow.com/questions/14847635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1046955/"
] | Instead of using **txtFromDate.Text** I used **Request.Form[txtFromDate.ClientID]** and problem got solved. | ```
clientIDMode="Static"
```
will work perfectly. |
14,847,635 | I am using .NET framework 1.1 with C#. My problem description is given below.
1. I have server side textbox control with id:= *txtFromDate*. view state is enabled and its readonly.
2. when page loaded for the first time i am setting current date value in above textbox.
3. after that I change the value of textbox with jQuery.
4. then posting back the page using jQuery with some \_\_EVENTTARGET parameters.
5. I am using this changed textbox value in my code behind.
I have developed code in window XP machine 32 bit with 1.1 framework. But now I have put entire site on windows server 2008 R2 edition (64bit) in .NET 2.0 application pool
*Problem:* it works fine on development machine. but in windows server 2008 change in textbox value by jQuery is not being reflected in code behind. it retains old value which I assign when page gets loaded first time.
I want to run this application as it runs on my development machine.
In short I want to get changed value of textbox in codebehind on windows server 2008 machine too.
Thanks. | 2013/02/13 | [
"https://Stackoverflow.com/questions/14847635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1046955/"
] | Instead of using **txtFromDate.Text** I used **Request.Form[txtFromDate.ClientID]** and problem got solved. | changes you make to the controls on client side are not accessible to the code behind at the server, unless those changes are made to the values of input controls.
so, youu can also use hiddenfield along with label which youu want to change in javascript/ Jquery then, store the new label value in hiddenfield as well
then, instead of reading value from label in codebehind, read it from hiddenfield.
```
<asp:hiddenfied id="hdnLblValue" runat="server"/>
``` |
14,847,635 | I am using .NET framework 1.1 with C#. My problem description is given below.
1. I have server side textbox control with id:= *txtFromDate*. view state is enabled and its readonly.
2. when page loaded for the first time i am setting current date value in above textbox.
3. after that I change the value of textbox with jQuery.
4. then posting back the page using jQuery with some \_\_EVENTTARGET parameters.
5. I am using this changed textbox value in my code behind.
I have developed code in window XP machine 32 bit with 1.1 framework. But now I have put entire site on windows server 2008 R2 edition (64bit) in .NET 2.0 application pool
*Problem:* it works fine on development machine. but in windows server 2008 change in textbox value by jQuery is not being reflected in code behind. it retains old value which I assign when page gets loaded first time.
I want to run this application as it runs on my development machine.
In short I want to get changed value of textbox in codebehind on windows server 2008 machine too.
Thanks. | 2013/02/13 | [
"https://Stackoverflow.com/questions/14847635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1046955/"
] | Instead of using **txtFromDate.Text** I used **Request.Form[txtFromDate.ClientID]** and problem got solved. | **Need to Keep in Mind**
1. If any Server Control Example: TextBox. is Disabled or ReadOnly from Aspx Page or Code behind.
2. It's value is being changed from JQuery or Javascipt.
3. You try to get the changed value of this control from code behind then you will never get it.
4. When you post back this control then server will validate the property (If it is Disabled or ReadOnly then server will not entertain this control's changed value.
5. You Need to use hidden field and populate this hidden field with changed value of this control.
<asp:HiddenField runat="server" ID="hdnTextBoxValue"/>
**You need to set the changed value by JQuery or Javascript to hidden Field and get the value from Code behind.** |
14,847,635 | I am using .NET framework 1.1 with C#. My problem description is given below.
1. I have server side textbox control with id:= *txtFromDate*. view state is enabled and its readonly.
2. when page loaded for the first time i am setting current date value in above textbox.
3. after that I change the value of textbox with jQuery.
4. then posting back the page using jQuery with some \_\_EVENTTARGET parameters.
5. I am using this changed textbox value in my code behind.
I have developed code in window XP machine 32 bit with 1.1 framework. But now I have put entire site on windows server 2008 R2 edition (64bit) in .NET 2.0 application pool
*Problem:* it works fine on development machine. but in windows server 2008 change in textbox value by jQuery is not being reflected in code behind. it retains old value which I assign when page gets loaded first time.
I want to run this application as it runs on my development machine.
In short I want to get changed value of textbox in codebehind on windows server 2008 machine too.
Thanks. | 2013/02/13 | [
"https://Stackoverflow.com/questions/14847635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1046955/"
] | changes you make to the controls on client side are not accessible to the code behind at the server, unless those changes are made to the values of input controls.
so, youu can also use hiddenfield along with label which youu want to change in javascript/ Jquery then, store the new label value in hiddenfield as well
then, instead of reading value from label in codebehind, read it from hiddenfield.
```
<asp:hiddenfied id="hdnLblValue" runat="server"/>
``` | Although you can always use set get method to store the values from java script ... But here is some simple way to solve it...
case 1 - If control is just for storing purpose ,
put display : none in it's style and make visible = true in the attribute of the control.
case 2 - if control is to be displayed but in disabled mode put ReadOnly="true" instead of Enabled = true
eg..
```
<asp:textbox runat="server" ID="textbox1" Enabled="false"></asp:textbox> will not work
<asp:textbox runat="server" ID="textbox2" ReadOnly="true"></asp:textbox> will work
``` |
14,847,635 | I am using .NET framework 1.1 with C#. My problem description is given below.
1. I have server side textbox control with id:= *txtFromDate*. view state is enabled and its readonly.
2. when page loaded for the first time i am setting current date value in above textbox.
3. after that I change the value of textbox with jQuery.
4. then posting back the page using jQuery with some \_\_EVENTTARGET parameters.
5. I am using this changed textbox value in my code behind.
I have developed code in window XP machine 32 bit with 1.1 framework. But now I have put entire site on windows server 2008 R2 edition (64bit) in .NET 2.0 application pool
*Problem:* it works fine on development machine. but in windows server 2008 change in textbox value by jQuery is not being reflected in code behind. it retains old value which I assign when page gets loaded first time.
I want to run this application as it runs on my development machine.
In short I want to get changed value of textbox in codebehind on windows server 2008 machine too.
Thanks. | 2013/02/13 | [
"https://Stackoverflow.com/questions/14847635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1046955/"
] | changes you make to the controls on client side are not accessible to the code behind at the server, unless those changes are made to the values of input controls.
so, youu can also use hiddenfield along with label which youu want to change in javascript/ Jquery then, store the new label value in hiddenfield as well
then, instead of reading value from label in codebehind, read it from hiddenfield.
```
<asp:hiddenfied id="hdnLblValue" runat="server"/>
``` | ```
clientIDMode="Static"
```
will work perfectly. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.