text stringlengths 70 452k | dataset stringclasses 2 values |
|---|---|
Merge rows and join matching values
I have two sets of data on the first set there is one column that has a list of IDs like below.
I have another set which could have several rows matching that same ID like below
I am trying to get all the 'Values' shown in the second worksheet for each ID so I end up with something like
How do I write the equation in the B column to do the cross matching?
what have you tried? Also, shouldn't b2 contain: 23, 232, 1112 - or do you want them separated into 3-digit sequences?
I've tried VLOOKUP but that stops after the first match, I'm trying Macros now but it seems to be getting complicated quickly.
does this help: http://stackoverflow.com/questions/4889056/excel-multiple-vlookups-to-pull-in-1-data-element - or this: http://office.microsoft.com/en-au/excel-help/how-to-look-up-a-value-in-a-list-and-return-multiple-corresponding-values-HA001226038.aspx
Desired output doesn't match description of process. -1
There aren't any Excel functions that return a range of cells. There are two possible other ways I can think of:
Write a VBA macro. You could build the first column using the Remove Duplicates feature. Then the code could loop over the range looking for matching values that match the ID and build a comma separate string.
Use a Pivot Table to do that:
Select the ID, Year and Value range of cells and select Pivot Table on the Insert tab.
Add the ID and Value fields to the Row Labels
Configure Field Settings to No Subtotals and 'Show Items labels in tabular form'
Get a layout something like this. You might be able to get it to layout in a single row but I couldn't find the option for that.
| common-pile/stackexchange_filtered |
Get Selected Value of html dropdown in razor page dotnet
With the below code how can I get the value of the dropdown list using page handlers or tag helpers?
One way I've been reading is using OnChange on the dropdown, I can set the value of a hidden field with javascript then get value of hidden field from code behind. Should I even be using page handlers/tag helpers to get the dropdown value?
I have tried using Request.Form["networks"] but this just gives the ID and not the Value.
<form method="post">
@Html.DropDownList("networks",
Model.GetNetworks().Select(s => new SelectListItem()
{
Text = s.networks,
Value = s.id.ToString(),
}),
new
{
@class = "dropdown form-control",
})
<input type="hidden" id="selectedwifivalue" />
<br />
<input type="text" placeholder="enter wifi password" asp-for="Password" class="input-sm form-control" />
<br />
<button asp-page-handler="submit" class="btn btn-primary btn-sm form-control">Submit</button>
</form>
Model is
public class WifiNetworks
{
public int id { get; set; }
public string networks { get; set; }
public IEnumerable<SelectListItem> UserNetworks { get; set; }
}
Code behind in cshtml file
[BindProperty]
public string Password { get; set; }
public string networks { get; set; }
public void OnPostSubmit()
{
{
var password = Request.Form["password"];
var network = Request.Form["networks"]; <--this just gives the ID and not the value
var wifi = networks; <---this is blank
}
}
To access the form elements value, You can use Request.Form collection by passing the name of the form element.Set name property of html element and check.
Below is sample code for get form element value using name property.
View :
@using (Html.BeginForm("ReceiveValueWithRequestFormData", "ControllerAndAction"))
{
<ol>
<li>
@Html.Label("Username")
@Html.TextBox("txtUserName") : user
</li>
<li>
@Html.Label("Password")
@Html.TextBox("txtPassword") : pass
</li>
</ol>
<input type="submit" value="Login" />
}
<div id="divResult"></div>
Controller :
[HttpPost]
public ActionResult ReceiveValueWithRequestFormData()
{
string userName = Request.Form["txtUserName"];
string password = Request.Form["txtPassword"];
if (userName.Equals("user", StringComparison.CurrentCultureIgnoreCase)
&& password.Equals("pass", StringComparison.CurrentCultureIgnoreCase))
{
return Content("Login successful !");
}
else
{
return Content("Login failed !");
}
}
Request.Form doesnt work on the dropdown it keeps getting the int value and not the selected string
In the end I could have done it using ajax but using the hidden field approach it works fine like below no idea if this is a good/bad/better way to do this (I seemed to be asking those questions quite alot)
get value of dropdown using jquery "change" function (keep this outside of the
$(document).ready function as it wont fire)
$('#dnetworks').change(function () {
var selectedwifi = $('#networks option:selected').text();
$('#hiddenselectedwifivalue').val(selectedwifi); //set value of hidden field
});
Razor page
<input type="hidden" id="hiddenselectedwifivalue" asp-for="WifiNetworks.networks" />
.cshtml file
var selectedwififromdd = WifiNetworks.networks;
I used the bind for the whole class in the model page (.cshtml file)
public class WifiModel : PageModel
{
[BindProperty] public WifiNetworks WifiNetworks { get; set; }
| common-pile/stackexchange_filtered |
Convert SVG polygon to an open curve
Let's consider the simple following image in its SVG representation (running the code snippet will display it):
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" height="200" width="200">
<g>
<path d="m 90.200184,21.865233 13.886726,0 0,91.406257 q 0,8.4375 -4.306646,11.86524 -3.7793,2.72461 -13.35938,2.72461 -10.37109,0 -18.19336,-1.05469 l -2.46094,-13.53516 q 11.07422,2.02148 18.45704,2.02148 5.97656,0 5.97656,-5.97656 l 0,-87.451177 z"/>
</g>
</svg>
The SVG path is actually a collection of points all around the shape, while it could be a simple top-down slanted curve (the red line here). Unfortunately, I am provided these images, and cannot change them.
I am looking for a way to convert—or rather approximate—the SVG polygon to an SVG open curve., either directly or in several steps.
Any solution is welcome, but my preference goes to this order:
programmatically (so that I can script it);
using Inkscape or GIMP (or any other Linux program);
well, anything that would work.
Thanks,
This class of algorithms is generally known as finding the "skeleton" or "medial axis". If you search on those terms you will find papers and other documents describing different potential approaches. Many/most usually involve starting with bitmaps though.
https://en.wikipedia.org/wiki/Topological_skeleton
Thanks a lot. For some reason, I had not thought about skeletons.
Isn't it as simple as deleting the closing z from the path?
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" height="200" width="200">
<g>
<path d="m 90.200184,21.865233 13.886726,0 0,91.406257 q 0,8.4375 -4.306646,11.86524 -3.7793,2.72461 -13.35938,2.72461 -10.37109,0 -18.19336,-1.05469 l -2.46094,-13.53516 q 11.07422,2.02148 18.45704,2.02148 5.97656,0 5.97656,-5.97656 l 0,-87.451177"/>
</g>
</svg>
Or are you looking for something more complicated than that?
Obviously, deleting the closing z is simple to script in your programming language of choice.
Not exactly, because I would still keep the outline around the shape instead of a line. Basically, what I want to get, is the red line on this picture: http://imgur.com/7kzi4Lp.
That's going to be difficult, if not practically impossible, for arbitrary paths. (Unless, of course, you're willing to delve into machine vision algorithms.)
| common-pile/stackexchange_filtered |
how to run query inside a custom validator in phalconphp
Im trying to make a custom validator to check if an email is already submited or not. for this I need to execute query in my custom validator, How can I do that?
use Phalcon\Validation\Validator,
Phalcon\Validation\ValidatorInterface,
Phalcon\Validation\Message;
Class Unique extends Validator implements ValidatorInterface {
public function validate($validator, $attribute) {
// how to execute "SELECT * FROM myTable" here...
}
}
If myTable is mapped to a Model you can just:
use Phalcon\Validation\Validator;
use Phalcon\Validation\ValidatorInterface;
use Phalcon\Validation\Message;
use MyTable;
class Unique extends Validator implements ValidatorInterface
{
public function validate($validator, $attribute)
{
$result = MyTable::findFirst("id = 1 AND status = 'sent'");
...
}
}
| common-pile/stackexchange_filtered |
Debug .NET source code with VS2015 update1 in UWP / WPF / Console applications?
Have tried these two,but they do not work :
http://blogs.msdn.com/b/dotnet/archive/2014/02/24/a-new-look-for-net-reference-source.aspx
http://referencesource.microsoft.com/
// EDIT
some other information
1, code:
class Program
{
static void Main(string[] args)
{
List<string> s = new List<string>() {"1", "2", "3"};
s.Sort();
}
}
2, dumpbin /headers:
Debug Directories
Time Type Size RVA Pointer
-------- ------- -------- -------- --------
570C5040 cv 25 004B34F0 4B16F0 Format: RSDS, {F0736C7E-9384-4F56-B409-82538DE2D731}, 2, mscorlib.pdb
3, Modules window:
mscorlib.dll C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_<IP_ADDRESS>__b77a5c561934e089\mscorlib.dll Yes N/A Symbols loaded. C:\Users\HaoPeng\AppData\Local\Temp\SymbolCache\mscorlib.pdb\f0736c7e93844f56b40982538de2d7312\mscorlib.pdb 1 4.6.1080.0 built by: NETFXREL3STAGE 2016/4/12 9:32 728E0000-73A29000 [9384] ConsoleApplication1.vshost.exe [1] ConsoleApplication1.vshost.exe
Microsoft.VisualStudio.HostingProcess.Utilities.dll C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.HostingProcess.Utilities\<IP_ADDRESS>__b03f5f7f11d50a3a\Microsoft.VisualStudio.HostingProcess.Utilities.dll Yes N/A Cannot find or open the PDB file. 2 14.00.23107.0 2015/7/7 15:24 00CB0000-00CBE000 [9384] ConsoleApplication1.vshost.exe [1] ConsoleApplication1.vshost.exe
System.Windows.Forms.dll C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Windows.Forms\v4.0_<IP_ADDRESS>__b77a5c561934e089\System.Windows.Forms.dll Yes N/A Symbols loaded. C:\Users\HaoPeng\AppData\Local\Temp\SymbolCache\System.Windows.Forms.pdb\eb5cb7959d814f46a194daf569c175ff1\System.Windows.Forms.pdb 3 4.6.1038.0 built by: NETFXREL2 2015/10/8 9:11 5D560000-5E1BA000 [9384] ConsoleApplication1.vshost.exe [1] ConsoleApplication1.vshost.exe
System.dll C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_<IP_ADDRESS>__b77a5c561934e089\System.dll Yes N/A Cannot find or open the PDB file. 4 4.6.1081.0 built by: NETFXREL3STAGE 2016/4/19 5:29 71730000-720B8000 [9384] ConsoleApplication1.vshost.exe [1] ConsoleApplication1.vshost.exe
System.Drawing.dll C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Drawing\v4.0_<IP_ADDRESS>__b03f5f7f11d50a3a\System.Drawing.dll Yes N/A Cannot find or open the PDB file. 5 4.6.1078.0 built by: NETFXREL3STAGE 2016/3/11 6:19 6E6C0000-6E84F000 [9384] ConsoleApplication1.vshost.exe [1] ConsoleApplication1.vshost.exe
Microsoft.VisualStudio.HostingProcess.Utilities.Sync.dll C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.HostingProcess.Utilities.Sync\<IP_ADDRESS>__b03f5f7f11d50a3a\Microsoft.VisualStudio.HostingProcess.Utilities.Sync.dll Yes N/A Cannot find or open the PDB file. 6 14.00.23107.0 2015/7/7 15:24 00FA0000-00FAC000 [9384] ConsoleApplication1.vshost.exe [1] ConsoleApplication1.vshost.exe
Microsoft.VisualStudio.Debugger.Runtime.dll C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.Debugger.Runtime\<IP_ADDRESS>__b03f5f7f11d50a3a\Microsoft.VisualStudio.Debugger.Runtime.dll Yes N/A Symbols not loaded. 7 14.00.23107.0 2015/7/7 15:24 01010000-0101A000 [9384] ConsoleApplication1.vshost.exe [1] ConsoleApplication1.vshost.exe
ConsoleApplication1.vshost.exe C:\Users\HaoPeng\documents\visual studio 2015\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.vshost.exe Yes N/A Cannot find or open the PDB file. 8 14.00.23107.0 2015/7/7 14:58 00BF0000-00BF8000 [9384] ConsoleApplication1.vshost.exe [1] ConsoleApplication1.vshost.exe
System.Core.dll C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_<IP_ADDRESS>__b77a5c561934e089\System.Core.dll Yes N/A Symbols loaded. C:\Users\HaoPeng\AppData\Local\Temp\SymbolCache\MicrosoftPublicSymbols\System.Core.pdb\5005a16d6f1d4f578a8a839f7ec4e7342\System.Core.pdb 9 4.6.1038.0 built by: NETFXREL2 2015/10/8 9:11 69680000-69DA9000 [9384] ConsoleApplication1.vshost.exe [1] ConsoleApplication1.vshost.exe
System.Xml.Linq.dll C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml.Linq\v4.0_<IP_ADDRESS>__b77a5c561934e089\System.Xml.Linq.dll Yes N/A Symbols loaded. C:\Users\HaoPeng\AppData\Local\Temp\SymbolCache\MicrosoftPublicSymbols\System.Xml.Linq.pdb\b5b962082bfa460e9fce41fdc43a7a022\System.Xml.Linq.pdb 10 4.6.1038.0 built by: NETFXREL2 2015/10/8 9:11 59CE0000-59D42000 [9384] ConsoleApplication1.vshost.exe [1] ConsoleApplication1.vshost.exe
System.Data.DataSetExtensions.dll C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Data.DataSetExtensions\v4.0_<IP_ADDRESS>__b77a5c561934e089\System.Data.DataSetExtensions.dll Yes N/A Symbols loaded. C:\Users\HaoPeng\AppData\Local\Temp\SymbolCache\MicrosoftPublicSymbols\System.Data.DataSetExtensions.pdb\ff8bd93350db450fb43f156c22d475e51\System.Data.DataSetExtensions.pdb 11 4.6.1038.0 built by: NETFXREL2 2015/10/8 9:10 05120000-05132000 [9384] ConsoleApplication1.vshost.exe [1] ConsoleApplication1.vshost.exe
Microsoft.CSharp.dll C:\Windows\Microsoft.Net\assembly\GAC_MSIL\Microsoft.CSharp\v4.0_<IP_ADDRESS>__b03f5f7f11d50a3a\Microsoft.CSharp.dll Yes N/A Symbols loaded. C:\Users\HaoPeng\AppData\Local\Temp\SymbolCache\MicrosoftPublicSymbols\Microsoft.CSharp.pdb\609aad548a5f4b1bafb09a5ccd9e8aa32\Microsoft.CSharp.pdb 12 4.06.1038.0 2015/10/8 9:11 54F60000-550E4000 [9384] ConsoleApplication1.vshost.exe [1] ConsoleApplication1.vshost.exe
System.Data.dll C:\Windows\Microsoft.Net\assembly\GAC_32\System.Data\v4.0_<IP_ADDRESS>__b77a5c561934e089\System.Data.dll Yes N/A Symbols loaded. C:\Users\HaoPeng\AppData\Local\Temp\SymbolCache\System.Data.pdb\ac876710b4974f1f984e433d02a293311\System.Data.pdb 13 4.6.1038.0 built by: NETFXREL2 2015/10/8 9:11 56340000-56ABD000 [9384] ConsoleApplication1.vshost.exe [1] ConsoleApplication1.vshost.exe
System.Net.Http.dll C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Net.Http\v4.0_<IP_ADDRESS>__b03f5f7f11d50a3a\System.Net.Http.dll Yes N/A Symbols loaded. C:\Users\HaoPeng\AppData\Local\Temp\SymbolCache\MicrosoftPublicSymbols\System.Net.Http.pdb\c43c636332fe4b53ad4e9f12dd1d68152\System.Net.Http.pdb 14 4.6.1038.0 built by: NETFXREL2 2015/10/8 9:10 668C0000-66941000 [9384] ConsoleApplication1.vshost.exe [1] ConsoleApplication1.vshost.exe
System.Xml.dll C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Xml\v4.0_<IP_ADDRESS>__b77a5c561934e089\System.Xml.dll Yes N/A Symbols loaded. C:\Users\HaoPeng\AppData\Local\Temp\SymbolCache\MicrosoftPublicSymbols\System.Xml.pdb\7f2700207ca5443a83d10b6e05ed34722\System.Xml.pdb 15 4.6.1064.2 built by: NETFXREL3STAGE 2015/12/3 9:36 66E30000-6753C000 [9384] ConsoleApplication1.vshost.exe [1] ConsoleApplication1.vshost.exe
mscorlib.resources.dll C:\Windows\Microsoft.Net\assembly\GAC_MSIL\mscorlib.resources\v4.0_<IP_ADDRESS>_zh-Hans_b77a5c561934e089\mscorlib.resources.dll Yes N/A Binary was not built with debug information. 16 4.6.1038.0 built by: NETFXREL2 2015/10/8 12:05 05540000-05636000 [9384] ConsoleApplication1.vshost.exe [1] ConsoleApplication1.vshost.exe
ConsoleApplication1.exe C:\Users\HaoPeng\documents\visual studio 2015\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe No N/A Symbols loaded. C:\Users\HaoPeng\Documents\Visual Studio 2015\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.pdb 17 <IP_ADDRESS> 2016/5/21 11:19 04FF0000-04FF8000 [9384] ConsoleApplication1.vshost.exe [1] ConsoleApplication1.vshost.exe
System.Configuration.dll C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_<IP_ADDRESS>__b03f5f7f11d50a3a\System.Configuration.dll Yes N/A Symbols loaded. C:\Users\HaoPeng\AppData\Local\Temp\SymbolCache\System.Configuration.pdb\870cb491dac3444aaa02db61d480a0e01\System.Configuration.pdb 18 4.6.1038.0 built by: NETFXREL2 2015/10/8 9:11 68720000-6880F000 [9384] ConsoleApplication1.vshost.exe [1] ConsoleApplication1.vshost.exe
4, symbol load info:
C:\Users\HaoPeng\Documents\Visual Studio 2015\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\mscorlib.pdb: Cannot find or open the PDB file.
C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_<IP_ADDRESS>__b77a5c561934e089\mscorlib.pdb: Cannot find or open the PDB file.
C:\Windows\mscorlib.pdb: Cannot find or open the PDB file.
C:\Windows\symbols\dll\mscorlib.pdb: Cannot find or open the PDB file.
C:\Windows\dll\mscorlib.pdb: Cannot find or open the PDB file.
C:\Users\HaoPeng\AppData\Local\Temp\SymbolCache\mscorlib.pdb\f0736c7e93844f56b40982538de2d7312\mscorlib.pdb: Symbols loaded.
// EDIT2
Symbol load info
C:\Users\HaoPeng\Documents\Visual Studio 2015\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\mscorlib.pdb: Cannot find or open the PDB file.
C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_<IP_ADDRESS>__b77a5c561934e089\mscorlib.pdb: Cannot find or open the PDB file.
C:\Windows\mscorlib.pdb: Cannot find or open the PDB file.
C:\Windows\symbols\dll\mscorlib.pdb: Cannot find or open the PDB file.
C:\Windows\dll\mscorlib.pdb: Cannot find or open the PDB file.
C:\Users\HaoPeng\AppData\Local\Temp\SymbolCache\mscorlib.pdb\f0736c7e93844f56b40982538de2d7312\mscorlib.pdb: Cannot find or open the PDB file.
C:\Users\HaoPeng\AppData\Local\Temp\SymbolCache\MicrosoftPublicSymbols\mscorlib.pdb\f0736c7e93844f56b40982538de2d7312\mscorlib.pdb: Cannot find or open the PDB file.
SYMSRV: C:\Users\HaoPeng\AppData\Local\Temp\SymbolCache\mscorlib.pdb\F0736C7E93844F56B40982538DE2D7312\mscorlib.pdb - file not found
*** ERROR: HTTP_STATUS_NOT_FOUND
*** ERROR: HTTP_STATUS_NOT_FOUND
*** ERROR: HTTP_STATUS_NOT_FOUND
SYMSRV: C:\Users\HaoPeng\AppData\Local\Temp\SymbolCache\mscorlib.pdb\F0736C7E93844F56B40982538DE2D7312\mscorlib.pdb not found
SYMSRV: http://referencesource.microsoft.com/symbols/mscorlib.pdb/F0736C7E93844F56B40982538DE2D7312/mscorlib.pdb not found
http://referencesource.microsoft.com/symbols: Symbols not found on symbol server.
SYMSRV: C:\Users\HaoPeng\AppData\Local\Temp\SymbolCache\mscorlib.pdb\F0736C7E93844F56B40982538DE2D7312\mscorlib.pdb - file not found
*** ERROR: HTTP_STATUS_NOT_FOUND
*** ERROR: HTTP_STATUS_NOT_FOUND
INFO: HTTP_STATUS_OK
SYMSRV: C:\Users\HaoPeng\AppData\Local\Temp\SymbolCache\mscorlib.pdb\F0736C7E93844F56B40982538DE2D7312\mscorlib.pdb - file not found
SYMSRV: mscorlib.pdb from https://msdl.microsoft.com/download/symbols: 133447 bytes
https://msdl.microsoft.com/download/symbols: Symbols downloaded from symbol server.
C:\Users\HaoPeng\AppData\Local\Temp\SymbolCache\mscorlib.pdb\F0736C7E93844F56B40982538DE2D7312\mscorlib.pdb: Symbols loaded.
what does not work? Give more information (and error messages if you get them)
:)
List<string> a = new List<string>() {"2", "1"}; a.Sort();
when I hit f11 at 'a.Sort();', VS2015 did not step into the source code of 'Sort' method. So, I mean it does not work.
have you uncheck Just my code? Also don't point to the public MS symbol server, they don't include source information.
:) of course I unchecked Just my code, also I did not point to Microsoft symbol server, but when I run my app, VS2015 starts to download symbols from Microsoft symbol server, when it is finished, I still can not step into .Net source code. Maybe you can try it yourself.
Microsoft symbol server hosts public symbols and this is why it doesn't work. Have you configured the environment variable _NT_SYMBOL_PATH and configured here the MS Symbol server?
http://stackoverflow.com/a/27655501/17034
:( does not work, thanks for providing me information.
It is the familiar problem I described in the linked Q+A. You have the same version of mscorlib.dll on your machine as I do. It got delivered through Windows Update on my machine on April 22nd. This breaks the reference source, that server is not updated automatically from the build server like the msdl server is and it still has the old PDBs. It can take a while before somebody wakes up and takes care of it. You are stuck until that happens.
@HansPassant Hope MS could solve this. :)
Hmya, SO is not the Microsoft Support email inbox. You got the ear of a Microsoft employee who never heard of this problem, not exactly the most efficient way to go about it. I'm closing this as dup, clearly it is.
Update: it looks like this is a problem on the Microsoft server side. The symbols for
http://referencesource.microsoft.com/symbols/mscorlib.pdb/f0736c7e93844f56b40982538de2d7312/mscorlib.pdb
haven't been published yet. I'm confirming internally and will update here once the team responds.
This can happen when you first loaded public symbols (without source code mappings) from Microsoft Symbol Server, they got cached in the SymbolsCache folder, then you turned off public symbol server, however the old symbols still get picked up from the cache.
Try deleting this folder:
C:\Users\HaoPeng\AppData\Local\Temp\SymbolCache
And try again.
I delete the folder and open the solution, then VS starts to Load symbols from: Microsoft Symbol Servers(a dialog shows up), when this is done, I click Start to run the demo, and VS starts to Downloading public symbols(another dialog shows up), when this is done, I still can not step into .net source code.
Could you please delete the folder again, then paste the Symbol load info for mscorlib.dll?
:) OK, I pasted the load info at 'EDIT2' above. Because it's too long to be a comment.
It looks like a problem on Microsoft side - symbols for f0736c... (NETFXREL3STAGE) haven't been published yet. Once I know more I will post more.
Also can you please make a screenshot of Visual Studio About dialog and paste here?
:) I do not have enough reputations to put more links here, so I put it on http://postimg.org/image/potvvhyup/ .
| common-pile/stackexchange_filtered |
Get all RSS feed entries with Rome Library
i am using Rome library for Java to parse some RSS.
By default it takes 25 entries.
Tell me please, how to get next 25 entries?
My test code is:
public static SyndFeed getSyndFeedForUrl(String url) throws Exception {
SyndFeed feed = null;
InputStream is = null;
try {
URLConnection openConnection = new URL(url).openConnection();
is = new URL(url).openConnection().getInputStream();
if("gzip".equals(openConnection.getContentEncoding())){
is = new GZIPInputStream(is);
}
InputSource source = new InputSource(is);
SyndFeedInput input = new SyndFeedInput();
feed = input.build(source);
} catch (Exception e){
e.printStackTrace();
} finally {
if( is != null) is.close();
}
return feed;
}
public static void main(String[] args) {
SyndFeed feed;
try {
feed = getSyndFeedForUrl("http://example.com/rss");
List res = feed.getEntries();
for(Object o : res) {
System.out.println(((SyndEntryImpl) o).getDescription().getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
Thank you!
When you call feed.getEntries(), Rome library returns all entries that are available in http://example.com/rss. It is not possible to get more than there are in the xml document (unless the entries have been cached in some service like Feedly).
See
How to get all the posts from rss feed rather than the latest posts?
How to get more feeds from RSS url?
How Do I Fetch All Old Items on an RSS Feed?
Awesome! Thank you! Unfortunately, i cannot rate your answer (not enough reputation)
| common-pile/stackexchange_filtered |
Issue using CoreData in Swift
So I have implemented CoreData into my Xcode project successfully and everything seems to be linked together correctly. The code I am currently using in my ViewController.swift is:
func runTests(){
let appDel : AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let contxt : NSManagedObjectContext = appDel.managedObjectContext!
let en = NSEntityDescription.entityForName( "SavedData", inManagedObjectContext: contxt )
var newItem = data( entity: en!, insertIntoManagedObjectContext: contxt )
newItem.test = "test123"
var error : NSError? = nil
if !contxt.save(&error) {
NSLog("Unresolved error \(error), \(error!.userInfo)")
}
NSLog("CoreData:\(newItem)")
}
and in my knoData.swift:
import Foundation
import UIKit
import CoreData
@objc( data )
class data: NSManagedObject {
@NSManaged var test : String
}
While the app is still running it will return "test123" correctly when referenced as "newItem.test" but when I try and run the app again and reference it it returns nil until set again. Am I not saving right? Is a class not referenced? Someone please help.
Edit: My code above returns no errors. When I run the app without referencing the class data in knoData.xcdatamodeld it returns this in NSLog
CoreData:<NSManagedObject: 0x79eb49d0> (entity: SavedData; id: 0x79eb6af0 <x-coredata://C40AE8E5-A846-4AC4-9A27-2FB109D6FE49/SavedData/p181> ; data: {
test = test123; // it is only returning test123 because it was set previously, but when I run the app again and try to get the value without setting it again, it returns nil
})
But when I do reference the class data in knoData.xcdatamodeld it returns this:
CoreData:
Why aren't you checking for an error when you save? Use something similar to var error : NSError? = nil if !contxt!.save(&error) { NSLog("Unresolved error \(error), \(error!.userInfo)") }
Are you fetching the saved data when you start the app? The code you have there just creates new objects and adds them to the database.
@pbasdf I use the same code to reference the object when opening the app, I just comment out the setter line and the save line and use NSLog to log newItem.test and it returns nil, how would you like me to try referencing it?
@RoboticCat I'm having trouble using your error pointer, it seems to have issues. When using context.save(error) it should call the error handle correct?
@RoboticCat What is happening can be seen here
@uhfocuz: Yes - obviously you need to put newlines into the code or insert semicolons. You must format the Swift code as you would any other Swift code. Unfortunately the comments section doesn't allow me to put the code on separate lines. The if statements starts a new line as does the NSLog statement. This should be obvious.
Not an answer to your question, but do you really save much by writing contxt and en instead of just spelling out the whole words as context and entity? Code is read by humans not computers.
You need to fetch the data from the database:
let fetchRequest = NSFetchRequest(entityName:"SavedData")
var error: NSError?
let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as [data]?
if let resultsArray = fetchedResults {
if resultsArray.count > 0 {
let newItem = resultsArray[0] as data
println("Saved data is \(newItem.test)")
} else {
println("No results from fetch request.")
}
}
I assume your entity name is "SavedData" is of class "data".
When I use the class data for the entity "SavedData" it stops returning data. Could you tell me if my current configuration for my NSManagedObject is correct here
It looks OK to me, though I do most of my CoreData in objective-C rather than Swift. Do you get an error, or 0 results?
I get 0 results when I NSLog("CoreData: (coredata)") my CoreData(it returns "CoreData: ", but when it doesn't reference the class data, and rather references NSManagedObject it returns results such as "CoreData: {test = 'test123'}" but as i said before, when I restart the app and try and get 'test' without setting it it returns nil @pbasdf
Please can you update your post with your code as it now stands?
Updated just now. @pbasdf
Thanks - it is odd that NSLog("CoreData:\(newItem)") should give a different result if the entity is set to data. But I don't think the newItem object is nil. If you change the log to NSLog("CoreData:\(newItem.description)"), you should see something very similar to the log when SavedData is defined as NSManagedObject. You should also be able to log NSLog("CoreData:\(newItem.test)") and see "CoreData:test123".
The newItem.description method worked as you said, but it is still having the saving issue. I'm not sure what to do to make it save.
Do you get an error when saving? Or just empty results when you fetch? Can you post some code for your fetch?
Sorry, I'm actually very new to Swift and I have it figured out now. I was incorrectly fetching it. Your code above works. Thanks for the help, it is much appreciated.
| common-pile/stackexchange_filtered |
Updating a mySQL row containing IDs
I have a mySQL table that have a column read_by which has the rows:
-17-6
-11-8-6-62
-6
-6-22-45
-16-77
-31-3-6-24
These are IDs of users, Every ID starts with a dash -
Now I have changed the user 6 to 136
How to update every row and just change 6 to 136 keeping in mind that there may be IDs like -16, -62, -167... and the ID 6 is in different positions.
Here are the WHERE conditions:
WHERE read_by = "-6"
WHERE read_by LIKE "%-6"
WHERE read_by LIKE "-6-%"
WHERE read_by LIKE "%-6-%"
UPDATE messages SET [...] WHERE ...
How to change the exact 6 and keep the rest as is?
Thanks.
Never, ever store data as dash separated items. (Or comma separated etc.) It will only cause you lots of trouble.
At least don't store lists of items if you actually need to use SQL to query or update individual items in the list. It might be okay to store a list if you always just store and fetch the whole list, not individual items in the list.
You need to append a dash to the column in order to filter and the remove it after the update:
update messages
set read_by = trim(trailing '-' from replace(concat(read_by, '-'), '-6-', '-136-'))
where concat(read_by, '-') like '%-6-%'
See the demo.
Results:
> | read_by |
> | :----------- |
> | -17-136 |
> | -11-8-136-62 |
> | -136 |
> | -136-22-45 |
> | -16-77 |
> | -31-3-136-24 |
If you need to change all "6"s to "136", you can do:
update t
set read_by = trim(both '-' from replace(concat('-', read_by, '-'), '-6-', '-136-'))
where concat('-', read_by, '-') like '%-6-%';
Then, you should think about fixing your id. Use an auto-incremented number. Information such as "6" should be stored in a column somewhere.
| common-pile/stackexchange_filtered |
Wine yard robotics?
My friend has acquired a (small) wine yard to discover how much work it is tending and harvesting the grapes.
Now we are musing to enlist robotic help. The vine stocks are usually connected by a stiff wire, so some dangling machine might be feasible.
We are looking for references/inspirations for an agricultural robotic vine assistant. Any ideas?
While interesting, the question (as it is) is not a good fit for stackexchange. You'd need to do some research and come up with a more specific question.
Sorry for that... just getting started. Would be asking for "vertical movement of a dangling robot" be specific enough?
No. But asking for "why when I use motor X controlled with algorithm Y on a robot dangling from a wire, the robot doesn't move smoothly?" would make a specific enough question. The way the question is currently, is open-ended. The answers would be some vague idea of what may perhaps work. It doesn't produce solid answers that correctly solve a specific problem which can be reused in different applications. (Read more in the faq)
Take a look at this question for example or this one or this one for a general idea of what is specific enough.
Thx for the hints, I'll try doing better
You might want to check out this grape vine pruning robot: https://www.youtube.com/watch?v=9GaGO9LIDEA.
| common-pile/stackexchange_filtered |
Total beginner's JS, can't set headers after they are sent
I am a beginner, and I am doing basic backend that runs on node.js and has express.js and mongodb.
My db model has one model - Story:
var storySchema = new mongoose.Schema({
name: String
});
var model = mongoose.model('Story', storySchema);
on get request I am trying take the data from db to display it, so I have:
var stories = [
'randomString',
'randomString',
'randomString'
];
stories.forEach(function(story, index) {
Story.find({'name': story}, function(err, stories) {
if(!err && stories.length) {
Story.create({name: story});
};
});
});
However in my stories.forEach something went wrong, so I got the error
"can't set headers after they are sent".
Can you please help me out?
Based on comments, in my index.js I got:
router.get('/stories', function(req, res) {
Story.find({}, function(err, stories) {
if(err) {
return res.status(500).json({message: err.message});
} res.json({stories: stories});
})
res.json({stories:[]});
});
The error you have seems related to http or express, not mongoose, are you sure the error come from this part of your code?
hum don't you have a res.send in you forEach ?
Seems you are trying to return more than one response to the client
updated the question
To elaborate, the error comes from your application trying to render headers on the page more than once. res.json() or res.send() write headers to the output; if Story.create() for example sends headers or tries to manipulate them, that may very well be causing the problem.
Dumb mistake, thanks everyone! Thanks @brandonscript
Possible duplicate of Node.js Error: Can't set headers after they are sent
| common-pile/stackexchange_filtered |
turn focus of page to a specific part on the body
In facebook fan page tab application I click tab button and like to go to the specific
portion of the fan page content without pixel calculation.
For example to point the comment box.
for that purpose url http://www.facebook.com/pages/AAAA/4444444?sk=app_UUUU8&app_data=php
and
<div id="php"><textarea name="a"></textarea></div>
is in body
but I would like to achieve that goal automatically using Javascript?
Why use JavaScript? <a href="#php">...</a> will do the job and work more consistently.
will this do?
<a href="http://abc.com/5677#php">link</a>
You could always style the link as a button, if you must.
Simply, <a href="link u want">Connect</a> is enough to do that instead.
<button onclick="document.getElementById("php").scrollIntoView()">Go</button>
or
<button onclick="document.getElementById(location.hash.substring(1)).scrollIntoView()">Go</button>
is a javascript alternative to using the anchor
try the following code on click of the button
window.location.href="#php";
You can go to any part of the body using the above code and providing the id of the content you wish to go....
| common-pile/stackexchange_filtered |
Save data from XSLT generated from to an XML file
i have a trouble while trying to save some data to XML using XSLT.
So the problem is that everything seems to be ok, no exceptions are thrown, log files are also clean, but I can't see any changes in XML file. And I can't
Here is my code for saving output to file
Transformer transformer = XslTemplatesPool.getTransformer(SAVE_ITEM, realPath);
setCategoryAndSubcateory(transformer, request);
String name = request.getParameter(NAME);
/*retrieving some more parameters*/
String price = request.getParameter(PRICE);
transformer.setParameter(NAME, name);
/*...*/
transformer.setParameter(XML_PATH, "E:/xslt/WebContent/xml/shop.xml");
if (price == null) {
price = "";
}
transformer.setParameter(PRICE, price);
if (notInStock == null) {
notInStock = "";
}
/*
* out is an instance of PrintWriter
* PrintWriter out = httpServletResponse.getWriter()
*/
transformer.setParameter(NOT_IN_STOCK, notInStock);
executeWrite(out, readWriteLock, transformer);
protected void executeWrite(PrintWriter out, ReadWriteLock readWriteLock, Transformer transformer) throws HandledException {
Source xmlSource = new StreamSource("E:/xslt/WebContent/xml/shop.xml");
StreamResult result = new StreamResult(out);
Lock writeLock = readWriteLock.writeLock();
writeLock.lock();
try {
transformer.transform(xmlSource, result);
} catch (TransformerException e) {
ExceptionHandler.logAndThrow(e, logger);
} finally {
writeLock.unlock();
}
}
From XSLT-generated form addItem (every peace of infomation I need comes nice and smooth at this stage) I retreve some data and try to add it to an xml file using template saveItem
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.example.org/products"
xmlns:redirect="http://xml.apache.org/xalan/redirect"
extension-element-prefixes="redirect"
xmlns:validation="xalan://com.xslt.util.Validator"
exclude-result-prefixes="validation redirect">
<xsl:import href="addItem.xsl" />
<xsl:import href="productsList.xsl" />
<xsl:param name="categoryName" />
<xsl:param name="subcategoryName" />
<xsl:param name="name" />
<xsl:param name="producer" />
<xsl:param name="model" />
<xsl:param name="date-of-issue" />
<xsl:param name="color" />
<xsl:param name="not-in-stock" />
<xsl:param name="price" />
<xsl:param name="xmlPath"/>
<xsl:param name="isValid" select="validation:validate($name, $producer, $model, $date-of-issue, $color, $price, $not-in-stock)" />
<xsl:param name="nameError" select="validation:getNameError()" />
<xsl:param name="producerError" select="validation:getProducerError()" />
<xsl:param name="modelError" select="validation:getModelError()" />
<xsl:param name="dateError" select="validation:getDateError()" />
<xsl:param name="priceError" select="validation:getPriceError()" />
<xsl:param name="colorError" select="validation:getColorError()" />
<xsl:template match="/" priority="2">
<xsl:choose>
<xsl:when test="not($isValid)">
<xsl:call-template name="addItem">
<xsl:with-param name="nameError" select="$nameError" />
<xsl:with-param name="producerError" select="$producerError" />
<xsl:with-param name="modelError" select="$modelError" />
<xsl:with-param name="dateError" select="$dateError" />
<xsl:with-param name="priceError" select="$priceError" />
<xsl:with-param name="colorError" select="$colorError" />
<xsl:with-param name="not-in-stock" select="$not-in-stock" />
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<redirect:write select="$xmlPath">
<xsl:call-template name="saveItem" />
</redirect:write>
<xsl:call-template name="returnToProducts" />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template name="saveItem" match="@*|node()" priority="2">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
</xsl:copy>
</xsl:template>
<xsl:template match="/xs:shop/xs:category[@name=$categoryName]/xs:subcategory[@name=$subcategoryName]">
<xsl:copy>
<xsl:apply-templates select="@*|node()" />
<xsl:element name="xs:product">
<xsl:attribute name="name">
<xsl:value-of select="$name" />
</xsl:attribute>
<xsl:attribute name="producer">
<xsl:value-of select="$producer" />
</xsl:attribute>
<xsl:attribute name="model">
<xsl:value-of select="$model" />
</xsl:attribute>
<xsl:element name="xs:date-of-issue">
<xsl:value-of select="$date-of-issue" />
</xsl:element>
<xsl:element name="xs:color">
<xsl:value-of select="$color" />
</xsl:element>
<xsl:choose>
<xsl:when test="$not-in-stock">
<xsl:element name="xs:not-in-stock" />
</xsl:when>
<xsl:otherwise>
<xsl:element name="xs:price">
<xsl:value-of select="$price" />
</xsl:element>
</xsl:otherwise>
</xsl:choose>
</xsl:element>
</xsl:copy>
</xsl:template>
<xsl:template name="returnToProducts">
<html>
<head>
<meta http-equiv="refresh" content="0;url=controller.do?command=productsList&categoryName={$categoryName}&subcategoryName={$subcategoryName}" />
</head>
</html>
</xsl:template>
</xsl:stylesheet>
example of my XML file
<xs:shop xmlns:xs="http://www.example.org/products" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org/products shop.xsd">
<xs:category name="bicycle">
<xs:subcategory name="frame">
<xs:product name="Soda FR" producer="NS" model="fr445">
<xs:date-of-issue>10-05-2012</xs:date-of-issue>
<xs:color>white</xs:color>
<xs:price>520$</xs:price>
</xs:product>
<xs:product name="Nucleon" producer="Nicolai" model="nc428">
<xs:date-of-issue>10-05-2012</xs:date-of-issue>
<xs:color>dark grey</xs:color>
<xs:not-in-stock/>
</xs:product>
</xs:subcategory>
</xs:category>
</xs:shop>
Is that your full XML document? It uses the prefix xs:, which isn't declared anywhere.
Sorry, I've lost it while posting, now XML is updated and looks just like one I am using.
So...
Finally I made it. Still there is a small bug
SystemId Unknown; Line #-1; Column #-1; Premature end of file.
but I hope it is one not very difficult to fix.
As you can see below the output stream is now written to StringWriter, and then StringWriter is written to a XML file. Still I can't understand why there is no result (file is just cleared) if you pass a file to StreamResult. May be just my hands growing out of a wrong place. May be I'll make a little research tomorrow.
So, method executeWrite(...) was changed a lot
protected void executeWrite(PrintWriter out, ReadWriteLock readWriteLock, Transformer transformer)
throws HandledException {
Lock readLock = readWriteLock.readLock();
StringWriter outWriter = new StringWriter();
Transformer t = null;
try {
readLock.lock();
StreamSource xmlStream = new StreamSource(/*path to XML*/);
t = transformer;
t.transform(xmlStream, new StreamResult(outWriter));
} catch (TransformerException e) {
ExceptionHandler.logAndThrow(e, logger);
} finally {
readLock.unlock();
}
Lock writeLock = readWriteLock.writeLock();
FileWriter fileWriter = null;
try {
writeLock.lock();
fileWriter = new FileWriter(new File(/*path to XML*/));
fileWriter.write(outWriter.toString());
} catch (IOException e) {
ExceptionHandler.logAndThrow(e, logger);
} finally {
if (fileWriter != null) {
try {
fileWriter.close();
} catch (IOException e) {
ExceptionHandler.logAndThrow(e, logger);
}
}
writeLock.unlock();
}
}
I would suggest two things to get you going. Until you get the results you want, I would keep the code as simple as possible. Since you get the file now, the problems has to be in the xsl. Of that only parts are posted here. Perhaps you can reduce your xsl to isolate which part makes your output empty?
| common-pile/stackexchange_filtered |
Does e.g. File.ReadAllText() utilize Windows File Caching?
Windows File Caching, as described here:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa364218(v=vs.85).aspx
By default, Windows caches file data that is read from disks and
written to disks. This implies that read operations read file data
from an area in system memory known as the system file cache, rather
than from the physical disk.
I have a C# app that reads files from disk in a very frequent, rapid manner. Should I worry about writing my own "file caching" mechanism, or will Windows handle this for me? When observing my app with Process Explorer, I still notice a lot of disk I/O during operation, even though I'm reading the same static file over and over again. Could it be that the Windows Cache Manager is simply telling the operating system that disk IO is taking place, when in fact the file is being read from the cache in memory?
You don't need to worry about. This is why 1000 smart developers wrote Windows OS, so you would just do File.ReadAllText(). If you want to access file, for example a template that doesn't get modified, yes, you can store it in memory and read memory. But for this, you need to pay attention to caching. For framework <= 3.5 use Enterprise Library 5 caching blocks. For 4.0 - system.runtime.caching or appFabric, etc, etc, etc
Caching is enabled by default for filesystem operations in all OSes I'm aware of, Windows included. I'd be astonished if the implementation of File.ReadAllText disabled it, because it gives a pretty huge performance benefit.
The filesystem cache is fast, but a custom cache can be purpose-built and therefor much faster.
For instance, ReadAllText needs to decode the file into a string -- the filesystem cache won't help you there. You can also keep that same instance around, so that all parts of your app accessing it reference the same copy. This gives your CPU's cache a better chance of skipping main memory. Less allocations also means reduced GC pressure.
Do you need your own second layer of caching? Maybe, maybe not -- you should write the simplest code you can first, and then work to optimize it if it's a bottleneck after measuring.
| common-pile/stackexchange_filtered |
Apache RewriteRule for a single static URL?
My current .htaccess contains the following:
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteRule ^(.*)-p-(.*).html$ product_info.php?products_id=$2&%{QUERY_STRING}
RewriteRule ^(.*)-c-(.*).html$ categories.php?cPath=$2&%{QUERY_STRING}
How can I add a single static rule so that product1-p-123.html is redirected (301) to product2-p-456.html without disrupting the other incoming requests?
Have it this way:
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
RewriteRule ^product1-p-123\.html$ /product2-p-456.html [L,NC,R=301]
RewriteRule ^.+-p-([^.]+)\.html$ product_info.php?products_id=$1 [L,QSA,NC]
RewriteRule ^.+-c-([^.]+)\.html$ categories.php?cPath=$1 [L,QSA,NC]
| common-pile/stackexchange_filtered |
WebMvcConfigurer and Jackson postprocessing
Consider a controller which returns urls with protocol and domain:
GET /test
{"url": "https://example.com/foo/bar"}
I would like to implement a filter or modification to Jackson which would postprocess such responses and remove the protocol and domain based on a parameter:
GET /test?clearDomain=true
{"url": "/foo/bar"}
I tried via Filters, but I got stuck in cycles with getWriter() has already been called for this response - I don't think that is going to work for all cases.
The way could probably be via Jackson postprocessing:
class WebConfigurer : WebMvcConfigurer {
override fun extendMessageConverters(converters: MutableList<HttpMessageConverter<*>>) {
// configureMessageConverters will leave out the default ones which are necessary
val originalList = ArrayList(converters)
converters.forEach {
if (it is MappingJackson2HttpMessageConverter) {
it.objectMapper // TODO postprocess somehow here
...
}
}
}
}
There are two issues:
Jackson is not aware of HttpServletRequest, so it cannot get hold of clearDomain parameter.
I can't find a way to tell Jackson to do something in the end of the response.
Did you try to create custom serializer for that class?
Jackson is the best for serializing and should be used only for that. In case the view should be modified we could use annotations, mixins or custom serializers. In this case you want to implement business logic, get data from HTTP request and do something with that. I would suggest to implement extra layer which would transform data into right form and pass this transformed object to serialization process. It would pay off when you start implementing more sophisticated logic. Unit tests also would be much easier to implement.
| common-pile/stackexchange_filtered |
Retrieve json parameters in current URL with php (and same name parameters)
I found lots of issues dealing with this kind of situation, but none like mine. Or maybe it was that I did not send the correct parameters via ajax?
This question is the following of that issue
Here is the ajax code
$('.valide').unbind().click(function (e) {
e.preventDefault();
var recupChoices= $('tr').map(function() {
var $row = $(this);
return {
idenR: $row.data('id'),
duree: $row.find($("select[name='chooseDuration']")).val()
};
}).get();
choices = (JSON.stringify(recupChoices));
$.ajax({
type : "GET",
url : "ajax/order.php",
dataType: "JSON",
data : choices ,
success: function(data) {
// Show success or fail messages
}
});
});
I suppose that I have chosen the standard values and the first id and I choose the GET method to see the URL parameters. This URL sent via AJAX will be :
http://[sitename]/ajax/order.php?[{%22idenR%22:1,%22duree%22:%221%22},{%22idenR%22:2,%22duree%22:%221%22}]
Already, from there, is that I make a mistake?
Then I can't at all to get the parameters in the file order.php. I tried to do that :
$currentURL= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$data = file_get_contents($currentURL);
var_dump(data);
// But it return "null"
I can't get the parameters or I was wrong before ... but where ?
I found my error. If you come across such cases, just remember that you must add a parameter to the data you send. I made a mistake in thinking that I already was sending parameters, while they were already encode with JSON.
In my example, you just have to add a name (here "datas") like this data : {datas : choice} in the AJAX request.
Here is the working code :
$.ajax({
type : "GET",
url : "ajax/order.php",
dataType: "JSON",
data : {datas : choices} ,
success: function(data) {
// Show success or fail messages
}
});
| common-pile/stackexchange_filtered |
Are innate intersubjectivity and theory of mind opposing theories or are they reconcilable?
What I get from Trevarthen's theory of innate intersubjectivity (2010) and the theory of theory of mind (Perner, 1999) is that they don't agree.
A considerable number of studies in theory of mind development suggest that infants are cognitively egocentric, that is they cannot understand that others may have different thoughts, feelings and points of view than they do until the age of 3 or 4 when a shift in cognitive development occurs.
Trevarthen on the other hand states that a newborn's view of the world is already intersubjective, that is a newborn can share parts of his/her inner world (thoughts, feelings) with other people and sense other people's intentions.
I was having a disagreement with my developmental psychology professor who thought they were reconcilable if one does a proper conceptual analysis of the statements of each theory and the methods and data that they use to formulate their theories, but she did not get any more specific as to what can be defined alternatively and how can this be done to avoid conflict.
Any thoughts on that?
Please ignore the nonsense below, it's not usually the way we do things around here. It should be deleted shortly.
Thank you for noticing. Seeing the question this guy had previously asked, I didn't expect a serious answer.
| common-pile/stackexchange_filtered |
Is there significance to the way the White Walkers/Others arrange dismembered body parts in patterns?
I just started watching Game of Thrones again and noticed something that I had never noticed previously. In the very first episode of the first series during the opening segment (just before the title sequence), there is a scene where one of the Rangers (in the books I think it is Gared) comes across a collection of the dismembered body parts from slaughtered Wildlings. The scene shifts to an aerial shot and it appears that those body parts are arranged in a crude circle with a line through the centre.
After noticing this it made me also recall that in a later episode there is a similar scene where severed horses heads and bodies are arranged in a pattern (I can't remember exactly but it was something like a spiral arrangement).
Are there any known reasons for White Walkers to arrange body parts in these geometric patterns? I certainly cannot recall anything mentioned in the TV series itself but I wonder if perhaps in any interviews with the TV show creators it is mentioned/explained? I thought it might simply be to create an additional sense of unease around the scenes and to perhaps enhance the sinister nature of the White Walkers but that is pure speculation on my part. I can't recall this behaviour mentioned anywhere within the books so the question applies just to the TV series.
The significance of it was that it was not enough for the TV-producers for Will to see dead wildlings. He had to see dismembered bodies spread out in arbitrary ways. In the books, the emphasis was "Were they really dead? Should we go back?" and in the TV-show it is "Oh shit, these guys are cold blooded."
I've closed this as a duplicate of the newer question because the answer on the newer one cites from official sources rather than all the speculation here.
If you have been watching the Season 6, in the episode 5, you see a similar symbol around the Godswood Tree, where the Children of the Forest turn the man into the First White Walker.
I think these symbols belong to the Children of the Forest and mean that the White Walkers are sending a message to the Children of the Forest and the Blood Raven. :-)
Refer to the image below:
Would be good to have a picture of the bodies for comparison.
This discussion had a few useful insights.
These scenes let us know something about the white walkers, EG:
it really hammers home the idea of the White Walkers as another intelligent species, and not just mindless monsters.
and
I think it's a bit creepy that the WWs would do things we simply have no rational explanation for, because it reinforces (forgive the pun) the "otherness" about them - they're not us.
Also there is the more pragmatic explanation, this allows the medium to show (not tell) the viewer the WW's did this:
By giving a certain amount of artistic flair to their "work," the viewer knows easily when someone has been killed by the Others, versus a normal conflict leading to loss of life.
It wasn't explained yet to my knowledge, but I came up with these viable theories:
Magic Rituals
Symbols(of some sort)
They mean something as to why the particular person was killed.
It is probably some sort of rune or symbol that has some meaning to them. Like celtic runes, I mean the "time" that GOT is set in makes it a magicy era.
But these fans appear to have some interesting chit chat about it.
[BOOK SPOILERS] Changes from book to screen
From User Josiah Rowe:
What do we think about the Others arranging the wildlings' body parts
into that pattern? It's suitably creepy, but does it have any
particular significance?
From User AHackeySackOfIceAndFire:
I think it was a replacement to the buildup around how strange it was
that the wildlings were gone. Just gone. they talk about it a fair bit
in the book, no? Strange necromancy ritual formation is a pretty quick
way to explain that this situation is abnormal.
From Reddit: Why would the White Walkers take the time to do something like this? Is there a symbol or purpose I don't understand? [Semi-NSFW for mild gore]
Brotherhood Without Banners
I think it serves to A. show the wildlings aren't the most
savage/dangerous thing north of the wall and B. show this wasn't done
by wildlife (wolves). It introduces the watcher to the actual threat
to the realm and that it is, contrary to the opinions of most, very
real.
The other discussions are equally as interesting, but I think we can agree that the symbols are based on magic, as I don't remember footprints.
It is probably a part of whatever magic the Others are a part of. They obviously have magic and these are magical markers that show:
The power of their magic
And symbolize something to come; At the very least it signals to everyone that they have been there. But mostly it means "Winter is Coming".
I remember noticing that symbol too and kept a look out for it in the 1st season.
You can see the Hand of the King badge is the same in a way; also in the 1st episode Dany's dress has similar pins on either shoulder with three dragon heads on top, and her brother has the same. I have a feeling that symbol might be related to the Targaryens, and that their blood line are the only ones able to stop the white walkers.
Nice catch! Could you possibly find images of the badge and pins you're referring to, and [edit] them into this answer?
It's a design iteration of a Celtic Brooch which is used to fasten fabric. but here, is just a pin.
The answer is this: the white walkers are starting a war with man because men created an imbalance through magic/dragons/etc. (Specifically dragons)
The shape laid out in the first episode of season 1 is the same shape as the fire in which Daenerys walks into in the last episode of season 1, (ice & fire), thus creating dragons.
The spiral of horse heads symbolizes the swarm of Dothraki surrounding Dany at the end of season 5. Both had a Targaryen in the middle. Horse heads with Jon (Targaryen) standing center, and Dothraki with Dany standing center.
As we know Starks can warg, and have greensight (see the future), Starks share some blood with the walkers, and the further north you go the more powerful these abilities are. White walkers know what's coming and it's meant as a warning to the impending doom the citizens of Westeros are creating for themselves
In the end it will be revealed as white walkers aren't as bad as they're made out to be, a recurring theme in GoT. Just like Jaime: we all hated him and now love him.
Interesting theory. Do you have any canon backup for this? Also, your last paragraph is kind of opinion-based...
What's Canon backup? And ofcourse it's opinion based, until the books are finished EVERY theory is opinion based. You have to be familiar with the books to understand the theory. It's very detailed, but in short, back during the first men an alliance was made between the white walkers and the first men. Man violated that alliance by crossing the wall into the north, and their use of magic.
@thedude Do you have any choice excerpts from the books or quotes from the series script/transcripts that illustrate this? Editing some in would really strengthen your answer.
The circle of bodies almost had the appearance of a compass with the line in the center being mostly on the bottom (south), possibly signifying that the white walkers are moving further toward the wall. I may be over thinking this, but it makes sense. I came here to see if anyone else had this thought.
I am not sure of the exact meaning. I remember that Sam and two other Nights Watch brothers uncovered an ancient rock that had dragon glass weapons hidden underneath. I believe there were some very old patterns carved on the rock that were similar to the large spiral pattern that was seen in Season 3. Didn't Sam say that the dragon glass was left by the first men?
Could it be that these patterns were a means of communication several thousand years ago, similar to petroglyphs that we find in ancient ruins?
Apparently many of these were subtle hints that the Children of the Forrest created The Others. According to D&D (showrunners). The Targaryen connection has me pondering more though. Plus John emerging from the beneath the crowd in The Battle of the Bastards was very reminiscent of Daenyrs' Mhysa moment.
Here are some pics and direct links:
[Mhysa Vid][1]
[Pyre Vid][2]
Could you some quotes to confirm your statements?
“John emerging from the beneath the crowd in The Battle of the Bastards was very reminiscent of Daenyrs' Mhysa moment.” — sure, but how is that related to the White Walkers arranging dismembered bodies?
Swirl pattern reminds me of symbols for infinity or chaos. The circular patter. Order direction think two dimensional astrolabe/gyroscope. Meaning is larger than show itself. Backstory is something about nature/cycles which explain the unusual seasons. I think the real war is to influence some phenomenon affecting catastrophic natural events. Flood, mini ice age, volcanism doom of old valaryia. Ect
Welcome to [scifi.se]! However, the question is looking for a stated significance from the show creators. This is currently just speculation on your part.
The symbol is pretty much the same as in season 1 when Dany revives her dragons...I'll have to look again but pretty much the same. Circle of life symbol? No clue just an idea
| common-pile/stackexchange_filtered |
Can't pick day if inline
I can't not pick a day at the weekend. The cursor is not changed. Only days in the width of the div, where the datepicker is in, can be picked. How I can fix this? I give an example using bootstrap to show the problem.
import React from "react";
import DatePicker from "react-datepicker";
class KSTabs extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.onOpenDatepicker = this.onOpenDatepicker.bind(this);
this.state = {
startDate: Date.now(),
isOpen: false
};
}
onOpenDatepicker = () => {
this.setState({ isOpen: !this.state.isOpen });
};
handleChange(date) {
this.setState({ isOpen: !this.state.isOpen, date: date });
}
render() {
return (
<div className="row">
<div className="col-sm-2">
<button onClick={this.onOpenDatepicker}> Open</button>
{this.state.isOpen && (
<DatePicker
selected={this.state.startDate}
onChange={this.handleChange}
inline
/>
)}
</div>
<div className="col-sm-2" />
</div>
);
}
}
export default KSTabs;
Edit
When the calendar is open, then I can select the first day on the left side, but I can't select the first date on the right side. The div column has a width of 185px and the datepicker 240px. Every days which are outside of the 185px are not selectable.
Give more detail what is error
| common-pile/stackexchange_filtered |
Get the alpha of an ImageView
How can I do this? There's a setAlpha but no getAlpha.
There is no easy way to do this. This is because an ImageView might have been set with a Bitmap, a StateListDrawable, a ColorDrawable, or something else entirely. Only one of those classes has a single color; on any other drawable the alpha might be different for each pixel (pixels are in ARGB format, w/ 1 byte each for alpha, red, green, and blue). I'm pretty sure the setAlpha() method only works on drawables that support it, as mentioned by Sephy above.
What exactly do you need to know about the image's transparency? If you know what the ImageView will be filled with ahead of time, then perhaps you can extract the alpha beforehand. If you don't have direct access to the alpha, but you are able to determine the color, then the alpha will be equal to color >>> 24.
I'm animating some ImageViews using an AlphaAnimation and I want to check if their alpha is 1 to determine if I should run my fadeIn animation on them.
Is this just to know the difference between which views were already animated and which views weren't? You should probably come up with some other way of figuring that out, for example if imgView.getAnimation() != fadeIn then you assume that the animation has yet to be applied. Alternatively, you could subclass ImageView and override the onSetAlpha() method; that's the method that will be called when alpha changes due to animation.
Here ya go View.ALPHA.get(View)
You can use this with an if statement to get a Boolean value and check for the current alpha state of a view.
In case anyone just need get and set a controls visibility, getVisibility and setVisibility may be an alternative you can use:
if(vw.getVisibility() == View.VISIBLE)
{
// do something
}
and you can set the visibility:
vw.setVisibility(View.INVISIBLE);
Actually, you need to use getOpacity() because get alpha existe only for ColorDrawable, Transformation and a few others. and you need to use it on the drawable of the ImageView not the view itself.
Hmm. getDrawable() is null if I set the ImageView src through XML instead of through setImageResource at run time. Any ideas?
Woops, I was setting background instead of src. getOpacity doesn't do anything useful though, it just returns one of 4 constants, I need something which returns the actual transparency value.
You can't directly. You can workaround, provided you're setting the alpha programmatically, is to keep the alpha value when you set it. E.g.:
private int mCurrentAlpha;
private void setAlpha(int newAlpha){
mCurrentAlpha=newAlpha;
ImageView imageView=...
imageView.setAlpha(mCurrentAlpha);
}
| common-pile/stackexchange_filtered |
Mathematica -- why does TreeForm[Unevaluated[4^5]] evaluate the 4^5?
If I give Mathematica the input
TreeForm[Unevaluated[4^5]]
I expect to see three boxes -- power, 4, and 5.
Instead I see a single box with 1024. Can anyone explain?
Compare
TreeForm@Unevaluated[4^5]
with
TreeForm@Hold[4^5]
From the help:
Unevaluated[expr]
represents the unevaluated form of expr when it appears as the argument to a function.
and
Hold[expr]
maintains expr in an unevaluated form.
so, as Unevaluated[4^5] gets to TreeForm ... it gets evaluated ...
It works like this:
f[x_+y_]:=x^y;
f[3+4]
(*
-> f[7]
*)
f[Unevaluated[3+4]]
(*
->81
*)
belisarius, it is my honor to give you the 400th Mathematica vote. Congratulations on the silver badge!
@Mr. Thanks. Awaiting for you here http://stackoverflow.com/badges/1079/mathematica?userid=353410
A level of Unevaluated is stripped off with every evaluation, so you can get what you want with:
TreeForm[Unevaluated@Unevaluated[4^5]]
I think the situation is more subtle than it may appear from this solution. If we try f[Unevaluated[4^5]] with some generic undefined f, we get the same back (as we should). Unevaluated is equivalent to a temporary Hold* - attribute for, in this case, TreeForm. What happens to the argument then, is determined by TreeForm internals.The fact that one layer of Unevaluated is not enough, reveals something that may perhaps be qualified as evaluation leak in the implementation of TreeForm - apparently it evaluates the passed expression once somewhere inside its implementation.
Continuing... But then, there is no way to know how many levels of Unevaluated we my need, if any. In some other cases (other built-ins) we may need just one level, as the OP expected. In other words, IMO this aspect of the behavior or TreeForm is rather puzzling and unintuitive (to me, I join the OP here), and the solution with many levels of Unevaluated reveals certain specifics about the internals of TreeForm, and, while totally valid, should have a status of a workaround tailored specifically at TreeForm, rather than a general solution for similar cases with other built-ins.
@Leonid Just as an example FullForm[Unevaluated[4^5]] works as expected
@belisarius Your example is rather special, because FullForm is special - it is not a normal function in some ways, see my comments to this post: http://stackoverflow.com/questions/4851948/return-equality-from-mathematica-function/4854542#4854542 . But we can make a very simple experiment: f[x_] := Hold[x]; f[Unevaluated[4^5]] will return Hold[4^5]. The fact that we need 2 levels of Unevaluated for TreeForm means that TreeForm does one extra internal evaluation of the input argument, while IMO it should not, as it is given all it needs to know. I'd consider this a borderline bug.
@Leonid ALL other xxxForm commands show Unevaluated[ ] as a head. It's not only a FullForm[ ] issue
@belisarius I did not mean specifically FullForm - all these xxxForm must be special (as compared to other built-in or user-defined functions), in this sense.
| common-pile/stackexchange_filtered |
Google dataflow fails with JVM after 8 consecutive periods for Combine globally
In my pipeline I have around 4 million records and the flow is as follows
Read all records from bigquery
Transform to proto
Combine globally and create a sorted kv based SST file which is later used for Rocksdb
This pipeline works for records upto 1.5 million but later fails with this error.
Shutting down JVM after 8 consecutive periods of measured GC
thrashing. Memory is used/total/max = 2481/2492/2492 MB, GC last/max =
97.50/97.50 %, #pushbacks=0, gc thrashing=true. Heap dump not written.
The error doesn't change even I used several optimizations suggested in various other threads such as
Changing machine type to high memory
Decreasing the accumulators (reduced the worker count to 1)
Use ssd disk
--experiments=shuffle_mode=service
Current stats
I can't use a custom file sink as the underlying SST writer doesn't support writing from bytable channel as here
Any insight on resolving this would be helpful
Do you have a memory leak?
As in? The part where it fails is at the stage Combine-globally and Sort the kv pairs which i assume is very memory intensive. But even running with 1 worker with high memory having the same issue
Try connecting a profiler and look at memory usage.
How much data do you have in total? Will it all fit into memory at once?
Noticed that the Current memory is still 3.75 GB, upgrading the worker machine type to n1-standard-2 worked
| common-pile/stackexchange_filtered |
Sending a non-client message to a WebSock process
The WebSock documentation states that the handle_info/2 callback is
Called by WebSock when the socket process receives a
GenServer.handle_info/2 call which was not otherwise processed by the
server implementation.
is there another, idiomatic way to send a message to a WebSock process from another process, that is not a websocket client?
Probably as with any other GenServer, you can just Kernel.send/2 a message to the WebSock process.
The WebSocket Lifecycle section of the documentation appears to suggest that handle_info/2 is the idiomatic way:
"WebSock will call the configured handler's WebSock.handle_info/2 callback whenever other processes send messages to the handler process"
@zwippie you're right, that is the idiomatic way to send a message from another process, handle_info just handles it. Please can you make your comment an answer?
Just as with any other GenServer, you can Kernel.send/2 a message to the WebSock process.
| common-pile/stackexchange_filtered |
Writing a C++ extension for PHP 5.4, example code is obsolete
I am trying to write an extension for php5.4 which basically wraps a very simple class in CPP.
This is for education purposes.
I find the way to do it in php5.4 has changed from php5.3
Where do I find the documentation on how to do it? Or even better, code example, any other extension that wrappes CPP classes and works in php5.4
For example, what used to work, and no longer is. Taken from http://devzone.zend.com/1435/wrapping-c-classes-in-a-php-extension/
zend_object_value car_create_handler(zend_class_entry *type TSRMLS_DC)
{
zval *tmp;
zend_object_value retval;
car_object *obj = (car_object *)emalloc(sizeof(car_object));
memset(obj, 0, sizeof(car_object));
obj->std.ce = type;
ALLOC_HASHTABLE(obj->std.properties);
zend_hash_init(obj->std.properties, 0, NULL, ZVAL_PTR_DTOR, 0);
zend_hash_copy(obj->std.properties, &type->default_properties,
(copy_ctor_func_t)zval_add_ref, (void *)&tmp, sizeof(zval *));
retval.handle = zend_objects_store_put(obj, NULL,
car_free_storage, NULL TSRMLS_CC);
retval.handlers = &car_object_handlers;
return retval;
}
The line
zend_hash_copy(obj->std.properties, &type->default_properties,
(copy_ctor_func_t)zval_add_ref, (void *)&tmp, sizeof(zval *));
will fail as the structure instance type (forgot it's definition) no longer has the member default_properties
Probably your best resource is the PHP5.4 source code
@Mark Baker I am not great in CPP, if there is a specific extension that already does it, would be great help. Otherwise, yes, Ill do exactly what u suggest
http://php.net/manual/en/internals2.structure.php ?
@Marc B there is a lot of knowledge there. Which I will read, but from a quick reading it, I see nothing about wrapping CPP classes.
Maybe you could provide details about what used to work and what's stopping it from working now?
@Charles - edited question with example
Does the information on this PHP wiki page help?
Specifically, to address your zend_hash_copy(obj->std.properties, &type->default_properties, (copy_ctor_func_t)zval_add_ref, (void *)&tmp, sizeof(zval *)); example, they suggest the following:
#if PHP_VERSION_ID < 50399
zend_hash_copy(tobj->std.properties, &(class_type->default_properties),
(copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval*));
#else
object_properties_init(&tobj->std, class_type);
#endif
| common-pile/stackexchange_filtered |
Using where clause in SSRS expression
I have a data set with multiple rows. The columns are name and plot; plot is a binary image file. If I want to display the plot whose name is secondPlot, for example, how would I do this? I can display just the first plot with =First(Fields!plot.Value, "DataSet1") but haven't had any luck with retrieving a plot with a certain name value.
I found if IIf function but am unsure on its usage or whether it's actually what I'm looking for anyway. =First(IIF(Fields!name.Value = "secondPlot", Fields.plot.Value, Nothing)) gives the error "The definition of the report '/MainReport' is invalid", for example.
For clarification, I'm typing this in Insert>Image>Database source.
Are you giving the user the option to select which plot is currently being shown? Or are you attempting to retrieve all plot images in one dataset and display at the same time?
@Aidan Neither really. I just want to display a single plot with a name that I specify, as opposed a single plot that just happens to be the first one in the database.
You should use a report parameter and use that parameter in the underlying query.
From your original question, I think you just needed to add your dataset - =First(IIF(Fields!name.Value = "secondPlot", Fields.plot.Value, Nothing), "DataSet1")) But I don't know if it will work with the Image like you want.
Add a tablix component to your report, then assign your dataset to your tablix in the DataSetName property.
Delete columns and rows leaving only a textbox. Right click in the tablix and select Tablix properties... go to filter tab and add a new filter.
For Expression select Name, operator = and value use ="secondPlot".
The tablix will filter the row that contain secondPlot name and you can show the image in the tablix textbox by configuring background image property in the Fill tab.
Right click the textbox and select Textbox properties / Fill tab, in background image pane use settings like this.
UPDATE:
If your image is PNG, BMP, JPEG, GIF or X-PNG you can select the proper MIME Type.
Also if your image is encoded in Base64 you can try:
=System.Convert.FromBase64String(Fields!Plot.Value)
In the Use this field: expression.
Don't use any expression for the textbox. Just use the image field as textbox background.
Let me know if you need further help.
Thanks for the response. This seems very promising, I got up to the last instruction without a hitch! Could you please clarify what you mean by "you can show the image in the tablix textbox"? If I right click on the textbox and select Expression then I've tried typing in =Fields!plot.Value, but when it renders it the textbox is just blank. The same happens if I set it to =Fields!name.Value so it's not just an issue with the plot itself. Is this not where I should be setting it? (Update: I've also tried setting it by selecting Textbox properties after rightclicking, also to no avail).
Thanks, it's still not working correctly though unfortunately. I'm just seeing an empty textbox as if I hadn't done anything to it...
| common-pile/stackexchange_filtered |
How do I configure vhost to read system path when enabled
I'm trying to set up a vhost to allow a specific file system path beneath the public directory.
Current Configuration:
<VirtualHost *:80>
ServerName mysite.com
DocumentRoot "..etc/www/mysite.com/public_html"
</VirtualHost>
I want to include the path "../etc/bin/zend/library" inside "../etc/www/mysite.com/library"
I am not sure if I need to change the documentroot to beneath the public_html and reference all public traffic to public_html or if I can use a mod_rewrite or directory to include a system directory. Also the directory should only be run/read; no write permissions.
Try using an Alias:
<VirtualHost *:80>
ServerName mysite.com
DocumentRoot "..etc/www/mysite.com/public_html"
Alias /library ../etc/bin/zend/library
</VirtualHost>
So if you go to http://mysite.com/library, it will serve the contents from ../etc/bin/zend/library
only problem is the directory should not be accessible publicly. I'm trying to make the directory locally visible/accessible only.
@MatthewSprankle what do you mean by "locally"? via a script in the document root or via localhost?
that brings the idea of creating another virtual host that is only accessible through local sites. I'm trying to push/pull files to the different virtual hosts via the system. Trying to create a repository of libraries that a number of sites can run off of locally.
Maybe it's not an apache issue ...
You should create a symbolic link :
cd .etc/www/mysite.com/
ln -s ../etc/bin/zend/library library
it should work.
régards
Mimiz
| common-pile/stackexchange_filtered |
Prove PQ is parallel to BC with angle chase?
I've been working on this geometry problem for a long time, but I haven't been able to make any progress. I have tried angle chase but that didn't get me anywhere.
Acute triangle $ABC$ has $AB<AC.$ Let $D, E, F$ be the foots of perpendiculars from $A, B, C \text{ and } H $ is orthocenter. $EF$ and $AD$ intersect at $P.$ The reflection of $AB$ in $AD$ intersects BE at $Q$, making $\angle DAB = \angle DAB' $
I want to prove that line joining $P,Q$ is parallel to $BC.$ How can I prove?
Please embed a pertinent diagram, directly into the posting. If you need help doing this, see the Edit-Images section of this article on MathSE protocol.
I am very sorry for my mistake, and I have edited my post correspondingly. Please forgive me for my errors, I hope my question can still be answered.
I edited the image and text a bit, roll it back if not okay.
Dear Narasimhan, that is certainly OK. Do you have any ideas for how to solve?
Would you like a solution with coordinates?
That would work well.
Note that $AFHE$ is cyclic because $\angle HFA = 90^\circ = \angle AEH$. Hence $\angle FEH = \angle FAH = \angle HAQ$. This shows that $\angle PEQ = \angle PAQ$, hence $APQE$ is cyclic. Since $\angle AEQ = 90^\circ$, it follows that $\angle QPA = 90^\circ$. Hence $PQ \perp AH$. Since $BC \perp AH$, it follows that $PQ \parallel BC$.
Let D be the origin and DA be the $y$-axis. Suppose $A(0,a)$, $B(b,0)$, $C(c,0)$, with $a\not=0$ and $b\not=c$.
$AB$: $x/b+y/a=1$
$CH$: $y=b/a(x-c)$
$F$: $(\frac{b(a^2+bc)}{a^2+b^2}, \frac{ab(b-c)}{a^2+b^2})$
$AC$: $x/c+y/a=1$
$BH$: $y=c/a(x-b)$
$E$: $(\frac{c(a^2+bc)}{a^2+c^2}, \frac{ac(c-b)}{a^2+c^2})$
The $y$-coordinate of $P$ is $\frac{\frac{b(a^2+bc)}{a^2+b^2} \frac{ac(c-b)}{a^2+c^2}-\frac{c(a^2+bc)}{a^2+c^2}\frac{ab(b-c)}{a^2+b^2}}{\frac{b(a^2+bc)}{a^2+b^2}-\frac{c(a^2+bc)}{a^2+c^2}}=\frac{-2abc}{a^2-bc}$
$AB'$: $x/(-b)+y/a=1$
$BH$: $y=c/a(x-b)$
The $y$-coordinate of $Q$ is $\frac{\frac{-2cb}a}{1-\frac{bc}{a^2}}=\frac{-2abc}{a^2-bc}$.
Hence $PQ$ is parallel to the $x$-axis, i.e., $BC$.
Because of the generic nature of the coordinates, we have proved the proposition is true for all triangles, including right triangles and obtuse triangles, except when $a^2=bc$, in which case $EF$ is parallel to $AD$ and $BH$ is parallel to $AB'$, both $P$ and $Q$ "at infinity".
| common-pile/stackexchange_filtered |
Is there a way to let an object to call a function after calling certain function?
I'm using PhpStorm to develop PHP and I'm curious about that calling a function limits itself before calling certain function with auto-complete.
Here is the codes below I want to do.
$this->Order = new Order();
$this->Order->setProductDetail()->setOrderDetail()->sendPayment();
So the sendPayment() function should be the last to be called.
and setProductDetail() & setOrderDetail() functions should be prior than sendPayment().
Therefore this code is invalid.
$this->Order->sendPayment()->setProductDetail()->setOrderDetail();
Is it possible for PhpStorm to do this with auto-complete?
The only way is to declare sendPayment() as function that returns nothing (e.g. @return void in PHPDoc for that function). Other than that -- that's up to developer to use methods in the right order. If it's hard to remember the right sequence (for whatever reason -- e.g. this API will be used by junior devs/3rd party and they do not always read the docs etc) .. then better create one more easy-to-use method that will do that in one go (not ideal solution, but might work if there is no many parameters).
You could make those methods private and call another method which runs them in the right order? i.e. $this->order->process(); which just does the code you added above...
But to answer your question: there is no functionality in PhpStorm that would check the order of calling methods. If all methods follow fluid interface (return $this) then from IDE point of view any sequence is perfectly valid.
hmm. alright then. Thank you for letting me know that there is no such a functionality. Understanding the fact is helpful for me. Thanks!!
| common-pile/stackexchange_filtered |
Understanding ExtJs Class properties
I try to understand how properties works in ExtJs class.
Refer to below code:
Ext.define('My.sample.Person', {
name: 'Unknown',
food: undefined,
foodList: [],
constructor: function(name) {
if (name) {
this.name = name;
}
},
eat: function(foodType) {
console.log(this.name + " is eating: " + foodType);
this.food = foodType;
this.foodList.push(foodType);
//this.foodList = [foodType]
},
showFood:function() {
console.log(this.name);
console.log(this.food);
},
showFoodList:function() {
console.log(this.name);
console.log(this.foodList);
}
});
var bob = Ext.create('My.sample.Person', 'Bob');
bob.eat("Salad");
bob.showFood();
bob.showFoodList();
console.log(bob)
var alan = Ext.create('My.sample.Person', 'alan');
console.log(alan)
alan.showFood();
alan.showFoodList();
<script src="https://cdnjs.cloudflare.com/ajax/libs/extjs/6.2.0/ext-all.js"></script>
If you check the result of "alan", the food = undefined and foodList = ['salad'] because somehow foodList was assigned to prototype.
Meanwhile, if you do like this, then it will behave normally like it should. Any idea why? What is the concept behind?
Result:
But alan has not eaten any salad yet. :)
haha, yeah. exactly.
but this.foodList.push(foodType); will modify the prototype.
it seems only array and object will do that, while string wont have this issue
You're right. Here is a good article. https://moduscreate.com/blog/a-dive-into-the-sencha-class-config-system/
yeah, i saw the article before, but doesnt really solve my puzzle.. because it focus more on config while i'm not using the config .. hmm..
This is what exactly your issue is: https://stackoverflow.com/a/42129243/1068246
Thanks. Ya, i think that should answer it.
only weird thing is by right, all the properties of the prototype should remain value as well. But in ExtJs, only object/array remain. Refer my example above, the "food" property get refreshed as undefined.
`function MyClass(item) {
this.items.push(item);
}
MyClass.prototype.items = [];
MyClass.prototype.item = 'test';
var c1 = new MyClass(1);
var c2 = new MyClass(2);
console.log(c2.items); // returns an array of [1, 2]
console.log(c2.item); //returns 'test'`
| common-pile/stackexchange_filtered |
Check following C# code
Errors in My code
I am creating a wpf calculator app.In the picture working area is the name of my text block.I want to Add a keydown event on the textblock but the code is showing error.Please give me any solution if you have.
Code:
private void workingarea_previewkeydown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.D1)
{
workingarea.Text == workingarea.Text + "1";
}
}
Please paste your code here instead of taking a screenshot
private void workingarea_previewkeydown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.D1)
{
workingarea.Text == workingarea.Text + "1";
}
}
It is an unholy mix of Winforms and WPF code. It is unclear why the IntelliSense popup cannot help you discover e.Key. Use = instead of == to assign the Text property.
Can i use key = to assign text property
could you please move the mouse over the error to show us more information about your situation, you can click the bottom button at your left with the text "Error list".
Maybe the probleme is related to System.Windows.Forms
Edit:
You Missabled PreviewKeyDownEventArgs with KeyEventArgs
private void workingarea_previewkeydown(object sender, PreviewKeyDownEventArgse)
Control.PreviewKeyDown Event
private void button1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Down:
case Keys.Up:
e.IsInputKey = true;
break;
}
}
Control.KeyDown Event
void button1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Down:
case Keys.Up:
if (button1.ContextMenuStrip != null)
{
button1.ContextMenuStrip.Show(button1,
new Point(0, button1.Height), ToolStripDropDownDirection.BelowRight);
}
break;
}
}
Maybe it's related to https://stackoverflow.com/questions/20129727/e-keycode-and-keyeventargs-not-working#20129787.
this is not related to the probleme but instead of
workingarea.Text == workingarea.Text + "1";
i think you want to do this
workingarea.Text = workingarea.Text + "1";
a more good way to do it
workingarea.Text += "1";
this was also one error but one more error is shown in line 36 of my code.
the error is that you are using KeyEventArgs instead of PreviewKeyDownEventArgs.
void button1_KeyDown(object sender, KeyEventArgs e) is for KeyDown event, private void button1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) is for previewkeydown
| common-pile/stackexchange_filtered |
How to get the same time the update(currentTime:) function uses? (before it is called)
Question: The update(currentTime:) function in SKScene is called every frame with a currentTime argument. I'm wondering how to get the time from the same source update(currentTime:) uses without using the update function. I only found CFAbsoluteTimeGetCurrent() which is different.
Reason: To calculate timeSinceLastUpdate you need an instance variable called timeOfLastUpdate. To implement timeOfLastUpdate you need to set it to an arbitrary value before the first update which makes the first calculation of timeSinceLastUpdate incorrect. You could have a simple if statement to detect this or use optionals but that is an unneeded branch which could be avoided if I just set timeOfLastUpdate in didMoveToView(view:). And that is what I'm trying to do.
I have noticed that currentTime returns the time in seconds the device has been running, meaning it is reset every time you reboot. There are ways to get this value, but for what you are doing, rickster's answer is the way to go.
The first timeSinceLastUpdate will always be different from the rest. Typically one stores the absolute time from the previous update call and subtracts it from the current call's time to get a timeSinceLastUpdate. If the previous time doesn't exist because you're on the first pass through the render loop — it's set to zero or infinity or negative something or whatever sentinel value you initialized it to, just set your timeSinceLastUpdate to some nominal value for getting started. Something like your frame interval (16.67 ms if you're going for 60 fps) would make sense — you don't want game code that depends on that time interval to do something wild because you passed it zero or some wildly huge value.
In fact, it's not a bad idea to have logic for normalizing your timeSinceLastUpdate to something sane in the event that it gets foo large — say, because your user paused and resumed the game. If you have game entities (such as GameplayKit agents) whose movement follows some sort of position += velocity * timeSinceLastUpdate model, you want them to move by one frame's worth of time when you resume from a pause, not take a five-minute pause times velocity and jump to hyperspace.
If you initialize your previous time to zero, subtract, and normalize to your expected frame interval, you'll cover both the starting and unpausing cases with the same code.
I'm wondering how to get the "previous" time from the didMoveToView method. Since the current solution requires evaluating a boolean expression ~60 times per second even though it is only needed once at the first update.
As I noted, that Boolean check is useful/needed for more than just the first update. And it's thousands of times faster than everything else you might be doing in your update method — what I'm getting at is that trying to invent a fictitious "previous" time just to optimize that check away is overthinking things.
You could always use coalesce:
let deltaTime = currentTime - (previousTime ?? currentTime).
On first loop, your deltaTime is 0 (Should be this) after that, it is the change
Of course previousTime must be an optional for this to work
| common-pile/stackexchange_filtered |
Why draw operation in android canvas are using float instead of int for (x,y)?
Why draw operation in android canvas are using float instead of int for (x,y)?
For example:
http://developer.android.com/reference/android/graphics/Canvas.html#drawCircle(float, float, float, android.graphics.Paint)
http://developer.android.com/reference/android/graphics/Canvas.html#drawRect(float, float, float, float, android.graphics.Paint)
If I have a lot of objects (say 200) to draw in my application and i have a class for each object, should I use 'int' or 'float' for the x, y attribute (the location of the object when drawn on screen)? i think 'float' use less memory than 'int'.
class MyObject {
public int x;
public int y;
}
Thank you.
Float because anti-aliasing allows you to paint at sub-pixel level.
Also because there can be a transformation matrix active (e.g. A scale).
A float and int take both 32 bit (most likely)
| common-pile/stackexchange_filtered |
How can i generate pseudorandom numbers in MATLAB of a specific range
How can i generate 1000 pseudorandom numbers in range [-0.7,0.7] and store them in a vector, i've tried different methods but none of them actually worked for me ?
I figurred out the answer myself you can actually do the following
array = rand(1,1000) * (B - A) + A
based on that :
array = rand(1,1000) * 1.4 + 0.7
will produce the desired vector
Yeap , fixed !! @LuisMendo
Welcome to the site!
| common-pile/stackexchange_filtered |
ASP.NET Core MVC : ModelState error message - localization not working
en-US:
zh-CN:
Why are [Display(Name = "LoginUserName")] and other data annotations not working?
This is my localization config
What could be the fix for me?
You can try the following two ways:
1. Use the old way of localizing data annotations:
[Display(Name = nameof(MyResources.LoginUserName),
ResourceType = typeof(MyResources))]
2. DataAnnotation localization can be configured in the startup file(Put in Program.cs in .NET 6):
services.AddMvc()
.AddViewLocalization(o=>o.ResourcesPath = "Resources")
.AddDataAnnotationsLocalization(o=> {
var type = typeof(ViewResource);
var assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
var factory = services.BuildServiceProvider().GetService<IStringLocalizerFactory>();
var localizer = factory.Create("ViewResource", assemblyName.Name);
o.DataAnnotationLocalizerProvider = (t, f) => localizer;
});
Here is a work demo, you can refer to it.
Hope this can help you.
| common-pile/stackexchange_filtered |
Python Pandas spit to series groupBy
I have a dataframe which I can run split on a specific column and get a series - but how do I then add my other columns back into this dataframe? or do I somehow specify in the split that there's column a which is the groupBy then split on columnb ?
input:
ixd _id systemA systemB
0 abc123 1703.0|1144.0 2172.0|735.0
output:
pandas series data (not expanded) for systemA and B split on '|' groupedBy _id
you should provide a minimal input/output example for clarity
added more detail
It sounds like a regular .groupby will achieve what you are after:
for specific_value, subset_df in df.groupby(column_of_interest):
...
The subset_df will be a pandas dataframe containing only rows for which column_of_interest contains specific_value.
Thanks- added more details to the post but not sure if that even changes anything here
I'm not looking for specific value though? just a split on the two columns as mentioned in my OP
Also this doesn't help me add the new series back into the dataframe
| common-pile/stackexchange_filtered |
Need help getting access to Clipboard to work from MTA application
I just am changing a GUI application from STAThread to MTAThread as it does some parallel background work. Now I encountered the issue of accessing the Clipboard from within a MTAThread application.
I tried to create a dedicated STA thread on my own, failed, then tried this class https://stackoverflow.com/a/21684059/2477582 and failed again.
From dot net framework source code I found that Application.OleRequired() not matching ApartmentState.STA is the only condition to raise ThreadStateException.
But this matches for my implementation, while the exception is raised nevertheless!
Tests without VS debugger let me proceed the application from this ".NET encountered an unhandled exception" dialog and then the Clipboard contains the correct value! So it works, but I have no chance to catch the exception, as it raises from some unidentifyable thread void directly into Application.Run(new MyMainform()).
Am I doing something wrong or has .NET behaviour changed here?
Program.cs:
[MTAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try
{
Application.Run(new ds_Main());
}
catch (System.Threading.ThreadStateException ex)
{
// It always falls out here
System.Diagnostics.Debug.WriteLine("ThreadStateException: " + ex.ToString());
}
}
ds_Main.cs, DataGridView KeyDown handler:
private void ds_ImportTableView_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.C)
{
string ll_CopyString = "foobar"; // some other stuff is here of course...
try
{
Thread l_StaThread = new Thread(() =>
{
// this prints: STA=?STA
System.Diagnostics.Debug.WriteLine(Application.OleRequired().ToString() + "=?" + System.Threading.ApartmentState.STA.ToString());
try
{
Clipboard.SetDataObject(ll_CopyString);
}
catch (Exception ex)
{
// It never catches here ...
System.Diagnostics.Debug.WriteLine("Exception in STA Delegate: " + ex.Message);
}
});
l_StaThread.SetApartmentState(ApartmentState.STA);
l_StaThread.Start();
}
catch (Exception ex)
{
// It doesn't catch here either ...
System.Diagnostics.Debug.WriteLine("Exception in STA Thread: " + ex.ToString());
}
}
}
Programmers never know how to do this correctly. You don't either, that STA thread you created is drastically wrong. You got lucky and got the framework to step in, denying your right to make code you did not write randomly crash or deadlock. That was just blind luck, you can't depend on it. The entrypoint of a UI thread of a program must be [STAThread], no shortcuts.
Well ... thank you for your comment, but I am not sure if it is of any help to me. Given the fact, that the [STAThread] and [MTAThread] attributes exist, one has to conclude that the intention for their existence is to be able to use them. Also, I didn't asked for an answer to the heavily emotionally polluted question of whether to use MTA or not. Instead, I asked why my implementation of the referred solutions don't work for me. If you feel the necessity to discuss the validity of those solutions, I would ask you to do this there and not here. Thank you for your understanding.
http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem
I don't see why this should apply, as I described the broader picture, but you did not provided an alternative to fulfill it. Instead, you disgraced me personally, which - in no situation ever possible - is/will be a legitimate approach. I ask you again to either start providing help, or stop commenting my question. If you don't like it, you are not forced to comment/answer it. Thank you.
While I still don't know the correct answer of this question, I announce that there is no need to answer it anymore.
This is because I found out that multithreading do work in STAThread attributed UI applications as well.
To identify this, I made synthetic tests, that proved the parallel execution while interacting/invoking with the UI as it was implemented always in my application.
The reason for me to try the MTAThread attribute was an external library not behaving as expected, giving the impression of overall single threaded execution throughout the UI application.
For anyone, wondering about similar issues, I have deep understanding for your confusion regarding this topic. But I advise, to first make synthetic tests prior to asking a question out here, as there seems little tolerance for errors in reasoning.
| common-pile/stackexchange_filtered |
GitHub for Windows - is it open source?
Is GitHub for Windows open source? If so, I can't seem to find the repository.
According to Tom Preston-Werner, one of the GitHub founders, in his post "Open Source (Almost) Everything", about the open-sourcing philosophy
Don't open source anything that represents core business value. [...] Notice that everything we keep closed has specific business value that could be compromised by giving it away to our competitors. Everything we open is a general purpose tool that can be used by all kinds of people and companies to build all kinds of things.
However, Hubot, previsouly a closed-source asset of GitHub, was eventually open-sourced in late 2011.
For the past year or so we've been telling people about Hubot [...] So we decided to rewrite him from scratch, open source him, and share him with everyone.
Currently, the Windows Github client is not an open source software... but who knows, it might be open-sourced one day.
Sad ... They've used a ton of open source libraries to build it. There doesn't seem to be much open WCF reactive UI code to learn from.
As @Lincoln said that's a pity, could have had a great pedagogical value
Phil Haack (who currently works at GitHub) gave a hint in his blog comments to this effect:
At the moment, it is not open source. Many of the libraries we created are open source. As we polish up more and more of those libraries, we'll release more components we used to make the app.
So no, the application is not open source, but keep a look out for some parts of it being published on GitHub. (But bear in mind that this is just a blog comment, not an official announcement of any kind).
Yeah like gitlib2, good stuff. I prefer linking over parsing almost any day.
According to the latest news, GitHub for Windows is renamed to GitHub Desktop. It is redisigned with Electron and completely open sourced. The beta version has been released. The weblink of GitHub Desktop open source repository leaves here: https://github.com/desktop/desktop .
| common-pile/stackexchange_filtered |
Inherit ES6/TS class from non-class
Given the class is extended from non-class (including, but not limited to, function),
function Fn() {}
class Class extends Fn {
constructor() {
super();
}
}
what are the the consequences? What do the specs say on that?
It looks like the current implementations of Babel, Google V8 and Mozilla Spidermonkey are ok with that, and TypeScript throws
Type '() => void' is not a constructor function type
If this is a valid ES2015 code, what's the proper way to handle it in TypeScript?
The result of class Foo { ... } in ES2015 is a (constructor) function named Foo. So, naturally, you can use extends with either a function or the result of a class, because they're both actually functions. (i.e., class is only special syntax for defining functions; there is no such thing as a "class object"). I don't know what's going on with TypeScript, though.
TypeScript Part
Up to now, the spec says a extends claus must be followed by a TypeReference. And a TypeReference must be in the form of A.B.C<TypeArgument>, like MyModule.MyContainer<MyItem>. So, syntactically your code is right. But it is not the typing case.
The spec says the BaseClass must be a valid typescript class. However, the spec is outdated, as said here. Now TypeScript allows expressions in extends clause, as long as expressions are computed to a constructor function. The definition is, well, implementation based. You can see it here. Simply put, a expression can be counted as constructor if it implements new() {} interface.
ES2015 Part
So, your problem is plain function is not recognized as constructor in TypeScript, which is arguable because ES2015 spec only requires the object has a [[construct]] internal method. While user-defined function object does have it.
ES2015 requires BaseClass is a constructor at runtime. An object isConstructor if it has [[construct]] internal methd. The spec says [[construct]] is an internal method for Function Object. User functions are instances of Function Objects, so naturally they are constructor. But builtin function and arrow function can have no [[construct]].
For example, the following code will throw runtime TypeError because parseInt is a builtin function and does not have [[construct]]
new parseInt()
// TypeError: parseInt is not a constructor
And from ECMAScript
Arrow functions are like built-in functions in that both lack .prototype and any [[Construct]] internal method. So new (() => {}) throws a TypeError but otherwise arrows are like functions:
As a rule of thumb, any function without prototype is not new-able.
Work Around
In short, not every function is constructor, TypeScript captures this by requiring new() {}. However, user-defined function is constructor.
To work around this, the easiest way is declare Fn as a variable, and cast it into constructor.
interface FnType {}
var Fn: {new(): FnType} = (function() {}) as any
class B extends Fn {}
Reasoning the incompatiblity
DISCALIMER: I'm not a TypeScript core contributor, but just a TS fan who has several side project related to TS. So this section is my personal guess.
TypeScript is a project originated in 2012, when ES2015 was still looming in dim dark. TypeScript didn't have a good reference for class semantics.
Back then, the main goal of TypeScript was to keep compatible with ES3/5. So, newing a function is legal in TypeScript, because it is also legal in ES3/5. At the same time, TypeScript also aims to capture programming errors. extends a function might be an error because the function might not be a sensible constructor (say, a function solely for side effect). extends did not even exist in ES3/5! So TypeScript could freely define its own usage of extends, making extends must pair with class variable. This made TypeScript more TypeSafe, while being compatible with JavaScript.
Now, ES2015 spec is finalized. JavaScript also has a extends keyword! Then incompatibility comes. There are efforts to resolve incompatibility. However, still problems exist. () => void or Function type should not be extendsable, as stated above due to builtin function. The following code will break
var a: (x: string) => void = eval
new a('booom')
On the other hand, if a ConstructorInterface was introduced into TypeScript and every function literal implemented it, then backward incompatibility would emerge. The following code compiles now but not when ConstructorInterface was introduced
var a = function (s) {}
a = parseInt // compile error because parseInt is not assignable to constructor
Of course, TS team can have a solution that balancing these two options. But this is not a high priority. Also, if salsa, the codename for TS powered JavaScript, is fully implemented. This problem will be solved naturally.
Thanks for the detailed summary. So, it is fine for ES2015 and shouldn't accidentally break with later ES implementations, isn't it? Are there any problems with var Fn = <FunctionConstructor> function() {} as more concise way to do the same thing in TS?
Yes, a plain function literal is a legal constructor. And, you cannot cast function literal into constructor in TS because incompatible types are not convertible, in this case they are () => void and new (). Casting to any is a workaround TS provides intentionally.
I see. I wonder why TS doesn't throw anything with that then.
Because TS allows bivariant type assertion: a subtype can be casted to a supertype, and a supertype can be casted to subtype. FunctionConstructor is declared as {new (...args): Function} & {(...args): Function}, so it is a subtype of () => void, thus castable. You can refer to this for more formal explanation
what are the the consequences? What do the specs say on that?
It is the same as extending a "EcmaScript 5" class. Your declare a constructor function and no prototype at all. You can extend it without any problem.
But for TypeScript, there is a big difference between function Fn() {} and class Fn {}. The both are not of the same type.
The first one is a just a function returning nothing (and TypeScript show it with the () => void). The second one is a constructor function. TypeScript refuse to do an extends on a non constructor function.
If one day javascript refuse to do that, it will break many javascript codes. Because at the moment, function Fn() {} is the most used way to declare a class in pure javascript. But from the TypeScript point of view, this is not "type safe".
I think the only way for TypeScript is to use a class :
class Fn {}
class Class extends Fn {
constructor() {
super();
}
}
I'm not sure I answer your question but I was very interested how to extend a JS function by a TypeScript class so I tried following:
fn.js (note the .js extension!)
function Fn() {
console.log("2");
}
c.ts
declare class Fn {}
class C extends Fn {
constructor() {
console.log("1");
super();
console.log("3");
}
}
let c = new C();
c.sayHello();
Then I ran:
$ tsc --target es5 c.ts | cat fn.js c.js | node # or es6
and the output is:
1
2
3
Hello!
Note, that this is not code for production use but rather a workaround for cases when you don't have time to convert some old JS file to TypeScript.
If I was in OP situation, I would try to convert Fn to a class because it makes code easier for others in a team.
This is indirectly related to TypeScript interface to describe class
Although the typeof a class is function, there is no Class (nor Interface) in Typescript which is the super class of all classes.
functions however are all interfaced by Function
I guess to be consistent with Javascript, Function should be probably be a class, all functions should be of that class and all classes should extend it...
| common-pile/stackexchange_filtered |
Disabling specific userforms based on corresponding cells
I have a group of cells, A1:A5, that each have a corresponding combobox user form, combobox1-5. If any of these cells are empty, I need to disable their combobox. I'm sure I could do it with something like:
Dim count As Integer
count = 0
Do Until count = 4
If Cells(1 + count, "A").Value = "" Then
Select Case count
Case 0
combobox1.disable
Case 1
combobox2.disable
Case 2
combobox3.disable
Case 3
combobox4.disable
Case 4
combobox5.disable
End Select
End If
count = count + 1
Loop
..but it seems like there must be a better way to do this.
FWIW a UserForm has very little to do with MSForms controls on a worksheet. You're looking for the Enabled property.
You can use a loop:
Dim n As Integer
for n = 1 to 5
Me.controls("combobox" & n).Enabled = (ActiveSheet.Cells(n, "A").Value <> "")
next
Perfect. That IS much simpler. Thanks!
| common-pile/stackexchange_filtered |
Cannot parse data from the phpmyadmin
I'm trying to retrieve data from phpmyadmin on my android app ,but first I want to test through the logcat to see if it works .When I test it ,I don't get back the names of the users in the database sadly .
This is my ShowUsers class :
package ie.example.artur.adminapp;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toolbar;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
/**
* Created by family on 24/07/2017.
*/
public class ShowUsers extends AppCompatActivity {
ListView lv;
String[] names = {"Amy","John","Joseph","Carl"};
InputStream is = null;
String line= null;
String result = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showusers);
lv = (ListView) findViewById(R.id.lv);
//Inlfate the list view with the items
lv.setAdapter(new ArrayAdapter<String>(ShowUsers.this,android.R.layout.simple_list_item_1,names));
android.widget.Toolbar toolbar = (android.widget.Toolbar) findViewById(R.id.toolbar);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
//set up the code to fetch data from the database
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://<IP_ADDRESS>/tut.php");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
//SETUP THE INPUTSTREAM TO RECEIVE THE DATA (INITIAL)
}catch (Exception e){
System.out.println("Exception 1 caught");
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
// Create a String builder object to hold the data
StringBuilder sb = new StringBuilder();
while((line = reader.readLine())!=null)
sb.append(line+"\n");
//Use the toString() method to get the data in the result
result = sb.toString();
is.close();
//check the data by printing the results in the logcat
System.out.println("-----Here is my data -----");
System.out.println(result);
}catch(Exception e){
System.out.print("Exception 2 caught");
}
}
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
{
switch (item.getItemId())
{
case R.id.action_settings : startActivity (new Intent(this, ShowUsers.class));
break;
}
return super.onOptionsItemSelected(item);
}}
}
This is the setup for tut.php file and the location is C:\xampp\www:
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("socialmedia_website",$con);
$r=mysql_query("select name from users where 1";
while($row=mysql_fetch_array($r))
{
$out[]=$row;
}
print(json_encode($out));
mysql_close($con)
The table in phpyadmin :
This is what is being outputted at the moment:
It should be outputting the users from the database
Can you open the file in your browser and see if it throws any exception...try http://localhost/tut.php
Mysql functions are depricated. Also, tut.php should output only the json data not any html
@Hackerman I have tried that before ,got error NotFoundHttpException in RouteCollection.php (line 179)
@WillParky93 I was following a video on how to do this ,that's why they are depreciated ,yes how to change it from html to Json then ?
@Lucy To change to JSON, add header('Content-Type: application/json'); above your print statement.
On top of what elan wrote, in the file you want the json to output, do not include anything else that will output html (header files/css items) unless you're going to parse inside your Java. Your tut.php code should only contain the code in your example, nothing else.
| common-pile/stackexchange_filtered |
What controls things like cursor appearance in a terminal?
In the GUI version of Emacs, it is easy to see that something like (blink-cursor-mode t) makes the cursor blink.
However, in a terminal emulator, such as on Mac OS X, it is possible to set things such as the cursor color or whether or not the cursor blinks, in various places (like your ~/.profile or in the Terminal Preferences.
So, my question is, what determines when a "graphical" element, such as text color, is controlled by a terminal emulator (in Terminal in Mac OS you can set the ANSI colors) versus when Emacs controls it (specifically when Emacs is running in a terminal emulator)
~/.profile controls the shell that the terminal emulator is running (like bash). AFAIK it has no control over the appearance of a particular terminal emulator
The terminal application has full control over the graphical elements. The gui terminal app will give text applications some control via “escape codes”. For example, vt100/xterm terminals, including Mac OS X Terminal, allow you to change colors using the sequence ESC [ numbers m. Try it in the shell:
echo -e "\e[1;37;41mhello"
This should print the word “hello” in a white foreground on red background.
Emacs uses these codes to control the text color. Note: although most terminals use the same sequences for colors, other codes are not always the same, so applications normally go through some library (termcap? curses?) and the TERM environment variable to look up what's needed and available in the given terminal. Emacs has its own elisp for each terminal type; see the source file term/xterm.el for example, or term/README for more details.
Cursor style is available in some terminals but not all. iTerm2 has its own set of sequences; I don't know if there's a similar list for Mac OS Terminal. They both emulate xterm/vt100 which has a long list here. The “set cursor style” sequences on that page show control over blink/underline/solid, but I don't think Terminal or iTerm2 support those. I've not seen any codes for cursor color; Emacs on my system is unable to set the cursor color in either Terminal or iTerm2. You can fake blinking by hiding the cursor (ESC ? 2 5 l) and then showing it again (ESC ? 2 5 h) at some interval.
Related: an emacs frequently asked question is why you can't bind some keys in the terminal version of emacs, and the answer is that it's up to the terminal to decide which keys are sent to the program, and not all keys are assigned an escape code, so emacs can't see them all.
| common-pile/stackexchange_filtered |
Odd results from Bash-4 recursion
I devised a simple test to see how Bash behaves with recursion, and I do not understand the results.
Test:
Assign a global variable X in the shell
Create a function f() that assigns a variable local X of the same name
Assign local X the value of the global X i.e. local X=$X
Recurse this function a few times and check whether, on each recursion, it uses the global X or the local X from the previous turn of the function
I expected one of two outcomes:
On each recursion, the local X from the previous f() would be the new "global" X, i.e. the X in the next-up scope, which would indicate that each recursion creates a new scope beneath the previous scope
On each recursion, the previous local X value would be forgotten, and each new local X=$X would simply reassign the value of the global X I initially assigned. This would indicate that Bash creates adjacent scopes.
I didn't get any of these. I got something weird. Below is the copy-paste from the terminal.
I assign a global variable in the shell:
user@ubuntu-zesty:~$ X=1
I create a function f() in the shell that creates local X, assigns the value of the global X to it, enters a while loop, adds 1 to local X (I assume its the local one), prints the new local X value, and calls itself. Repeat 5 or 6 times.
user@ubuntu-zesty:~$ f() { local X=$X; while [ $X -lt 6 ]; do X=$(( $X + 1 )); echo $X; sleep 1; f; done; }
Then I call f(), and the output is just baffling.
user@ubuntu-zesty:~$ f
2
3
4
5
6
6
5
6
6
4
5
6
6
5
6
6
3
4
5
6
6
5
6
6
4
5
6
6
5
6
6
At this point it exited on its own. And as expected the global X was unaffected.
user@ubuntu-zesty:~$ echo $X
1
So what's going on here? Is it sometimes using the global X, sometimes the local X? Please if you know what's going on here don't spare me the gory details.
Lastly, just for fun, a graph of the output:
1 ==
2 ===
3 ====
4 =====
5 ======
6 ======
7 =====
8 ======
9 ======
10 ====
11 =====
12 ======
13 ======
14 =====
15 ======
16 ======
17 ===
18 ====
19 =====
20 ======
21 ======
22 =====
23 ======
24 ======
25 ====
26 =====
27 ======
28 ======
29 =====
30 ======
31 ======
Specs:
Bash-4.4.5(1)-release
x86_64 Ubuntu Zesty
Linux kernel 4.10.0-17-generic
VMware Workstation 12 virtual machine
I think that the best way to visualize dynamic scoping as perfectly explained by @chepner in his answer is to modify your function slightly:
function f() {
local X="$X"
while [ "$X" -lt 6 ]; do
X=$((X + 1))
echo "${FUNCNAME[*]}" "$X" # This will print the call stack
sleep 1
f
done
}
And see how the values increase: if you follow the output columns, you can debug what happens at each level.
$ f
f f f f f 2
f f f f f f 3
f f f f f f f 4
f f f f f f f f 5
f f f f f f f f f 6
f f f f f f f f 6
f f f f f f f 5
f f f f f f f f 6
f f f f f f f 6
f f f f f f 4
f f f f f f f 5
f f f f f f f f 6
...
bash is dynamically scoped, not statically (aka lexically) scoped. That means when you execute the line local X=$X, you are not getting the value of $X based on the value assigned at the global lexical scope, but the value that exists in the closest runtime scope, namely the value in the scope from which f was called. This means that the a local value is not just visible in the function call, but from any call made from there.
Note that this is not specific to recursion.
$ X=3
$ foo () { local X=5; bar; }
$ bar () { echo $X; }
$ bar
3
$ foo
5
$ echo $X
3
Okay that is closest to my first hypothesis, but it isn't obvious how it explains the odd output. I'll need to sit down later and think though @ikkachu and your answers. (also thanks for fixing my post)
There are 31 output lines, which is suspiciously the same as 25-1. What seems to happen is that every iteration of the loop copies the function, with the value of X being the same as it was at that point.
So on every level the function completes the remaining part of the loop twice creating a binary tree. Visually the outermost parts would look like this:
4
+--5
| +--6
| +--6
+--5
+--6
+--6
(Isn't this your first suggestion? I'm not exactly sure.)
This produces the same result (run with f 1), but passes the value explicitly as an argument to the lower level.
f() {
local X=$1;
while [ $X -lt 6 ]; do
X=$(( $X + 1 ));
echo $X;
f $X;
done;
}
Very interesting, I'll need to sit down later and work though this.
| common-pile/stackexchange_filtered |
iOS 7: Importing CSV data from email attachement
I have a logging app that currently outputs a CSV as an email attachment. However, it's become somewhat critical to also allow users to import said CSV into other devices for sharing their logs.
It was somewhat trivial to get XCode to register CSV as one of the formats my app reads. And I can even launch the app from Mail's "open with...". However, I am having the hardest time working in Objective C (very different from what I am used to... PHP, JS, AS).
What I need help with is finding a working example as to how I can pass the CSV that was passed on from Mail into my app.
In Android, you can just declare "intent" and there are even Cordova Plugins, like WebIntent. But nothing for iOS.
Any suggestions?
Why do you post questions when you not are interested in the answers?
//In the app delegate
-(BOOL) application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
if (url != nil && [url isFileURL])
{
[self.myViewController handleCSV:url];
}
return YES;
}
//In myViewController (or what you call it)
-(void)handleCSV:(NSURL *)url
{
NSError *readError;
NSString *csvString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:& readError];
if(csvString && readError==nil)
{
NSArray *csvItems;
NSRange matchComma= [csvString rangeOfString: @","];
NSRange matchSemi= [csvString rangeOfString: @";"];
if(matchComma.location != NSNotFound) csvItems = [csvString componentsSeparatedByString: @","];
else if(matchSemi.location != NSNotFound) csvItems = [csvString componentsSeparatedByString: @";"];
}else
{
NSLog(@"error %@", readError);
}
}
| common-pile/stackexchange_filtered |
How to multiple value in BindingContext in xamarin ContentPage
I have xamarin application where I need to pass two objects to .cs file on button click event.
I have two ListView and have button in inside the 2nd Listview items. Both ListViews will be loaded dynamically based on the JSON. Now the problem is I need to send Parent ListView datasource and second ListView data source in the button click event. currently I am able to send only one using BindingContext but I need to send two or more objects to .cs file.
<ListView x:Name="StaffListMaster_List" RowHeight="150">
<ListView.ItemTemplate>`
<ListView x:Name="Staff_Record" ItemsSource="{Binding Path=detailsobj}">`
<ListView.ItemTemplate>`
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal" >
<Button Clicked="OnActionSheetCancelDeleteClicked" BorderRadius="0" BindingContext ="{Binding item}" Text="{Binding item[6]}"/>`
I want to get StaffListMaster_List data source and Staff_Record datasource inside
OnActionSheetCancelDeleteClicked(object sender, EventArgs e) {}`
First of all, don't do that. that's not what BindingContexts are for, secondly if you are responding to the event on your code behind you could just access both the DataSources using the ListView's name i.e. Staff_Record.ItemSource
If you want to use a nested Listview inside Listview, we could do that with ListView.GroupHeaderTemplate.
ParentItems class:
public class ParentItems : ObservableCollection<ChildItems>
{
public string ID { get; set; }
public string Title { get; set; }
public ParentItems(List<ChildItems> list) : base(list)
{
}
}
ChilsItems class:
public class ChildItems
{
public string ChildTitle { get; set; }
public string Description { get; set; }
}
Xaml:
<ListView HasUnevenRows="True" x:Name="listView" IsGroupingEnabled = "True">
<ListView.GroupHeaderTemplate>
<DataTemplate>
<ViewCell Height="40">
<StackLayout Orientation="Horizontal"
BackgroundColor="#3498DB"
VerticalOptions="FillAndExpand">
<Label Text="{Binding ID}"
VerticalOptions="Center" />
<Label Text=" "/>
<Label Text="{Binding Title}"
VerticalOptions="Center" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.GroupHeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding ChildTitle}" Detail="{Binding Description}"></TextCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Result:
I have uploaded on GitHub, you could download ListViewBindng folder for reference on GitHub.
https://github.com/WendyZang/Test
Finally I am able to solve the issue as follows :
Step 1 : Create IMultiValueConverter interface
Step 2 : created MultiBinding.cs class (ref : [https://gist.github.com/Keboo/0d6e42028ea9e4256715][1] )
Step 3 : Include xmlns:multi="clr-namespace:MultiBindingExample" namespace
step 4 :
<Button Command="{Binding ClearListItem}">
<Button.CommandParameter>
<multi:MultiBinding >
<Binding Source="{x:Reference control1}" Path="BindingContext"/>
<Binding Source="{x:Reference control2}" Path="BindingContext"/>
</Button.CommandParameter>
</Button>
step 4 : In view model
void ClearListViewSelectedItem( object param)
{
var commandParamList = (object[])param;
}
Final expected result would be.
| common-pile/stackexchange_filtered |
Error with Leaflet Map - Unable to display tiles on the map
I am encountering an issue when drawing polygons, point, and line features on a map using the Leaflet.js library.
The polygon is correctly displayed on the map, but the moment I try to draw a point ** or **line, they **disappear **immediately after releasing the mouse click. I need assistance to correct this issue and make the drawing of points and lines on the map functional.
var map = L.map("leaflet-map", {
center: [37.7749, -122.4194],
zoom: 8,
});
let osm = L.tileLayer("https://tile.openstreetmap.org/{z}/{x}/{y}.png?{foo}", {
foo: "bar",
attribution: "© OpenStreetMap contributors",
});
osm.addTo(map);
var CyclOSM = L.tileLayer(
"https://{s}.tile-cyclosm.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png",
{
attribution: "CyclOSM | Map data: © OpenStreetMap contributors",
}
);
CyclOSM.addTo(map);
var Esri_WorldImagery = L.tileLayer(
"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}",
{
attribution:
"Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community",
}
).addTo(map);
let baseLayers = {
"Esri World Imagery": Esri_WorldImagery,
"Open Street Map": osm,
"Cycl OSM": CyclOSM,
};
//Creates three feature groups for points, polygons, and lines on the map
var pointLayer = L.featureGroup().addTo(map);
var polygonsLayer = L.featureGroup().addTo(map);
var lineLayer = L.featureGroup().addTo(map);
var polygon;
var point;
var line;
var allLayers = L.featureGroup([pointLayer, polygonsLayer, lineLayer]).addTo(
map
);
//Add new shapes drawn on the map to the appropriate feature group
map.on("draw:created", function (e) {
var type = e.layerType,
layer = e.layer;
if (type === "point") {
point = layer;
point.addTo(pointLayer);
point.addTo(map);
} else if (type === "polygon") {
polygon = layer;
polygon.addTo(polygonsLayer);
polygonsLayer.addTo(map);
} else if (type === "line") {
line = layer;
line.addTo(lineLayer);
lineLayer.addTo(map);
}
});
var drawControl = new L.Control.Draw({
draw: {
marker: true,
polyline: true,
polygon: true,
rectangle: true,
circle: true,
},
}).addTo(map);
You define 5 types of shapes:
marker, polyline, polygon, rectangle, and circle
but in the feature group, you only catch polyline
To catch makers, you need to change this block:
if (type === "point") {
point = layer;
point.addTo(pointLayer);
point.addTo(map);
to:
if (type === "marker") {
point = layer;
point.addTo(pointLayer);
pointLayer.addTo(map); //add the layer to the map
same for polyline, rectangle and circle.
You can have a look at the Leaflet Draw documentation, you can catch all shapes by not checking for type and directly adding the e.layer from the draw event to the map.
| common-pile/stackexchange_filtered |
Passing Parameters in PHP
I know how to process parameters using the GET URL method in PHP like this: example.com/?item=23413
However I'm curious on how a site like Producteev.com achieved a different structure parameter. Producteev is also built in PHP framework, it is a task management site and when you open a task a similar url is what you will get:
producteev.com/workspace/t/5263c59f7301964e000004 (something like a page)
and not something like:
producteev.com/workspace/?t=5263c59f7301964e000004
Stackoverflow's framework is ASP.NET, right? I would like also to know if this is a natural way of passing url parameters or query in ASP.NET:
stackoverflow.com/questions/60174/how-to-do
A: mod_rewrite()
ah like this one? mod rewrite and query strings
Yes, and there are many other examples that you will find by Googling "mod_rewrite tutorial"
| common-pile/stackexchange_filtered |
Do I have to implement mapView:regionWillChangeAnimated:on my MKMapview delegate?
Apple's docs tell you this method should be as lightweight as possible, what's a standard use here? Resetting the annotation pins?
Tells the delegate that the region
displayed by the map view is about to
change.
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated
Parameters
mapView
The map view whose visible region is
about to change.
animated
If YES, the change to the new region
will be animated. If NO, the change
will be made immediately.
This method is called whenever the
currently displayed map region
changes. During scrolling, this method
may be called many times to report
updates to the map position.
Therefore, your implementation of this
method should be as lightweight as
possible to avoid affecting scrolling
performance.
The problem with this delegate method is "During scrolling, this method may be called many times to report updates to the map position" (so you need IF/THEN or CASE/BREAK, etc to keep it "lightweight").
You don't NEED to use this method at all (not required), but if you do wish to incorporate some sort of functionality (such as removing worthless pins, etc), then example code to keep it lightweight would be:
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated{
if(!animated){
//Instantaneous change, which means you probably did something code-wise, so you should have handled anything there, but you can do it here as well.
} else {
//User is most likely scrolling, so the best way to do things here is check if the new region is significantly (by whatever standard) away from the starting region
CLLocationDistance *distance = [mapView.centerCoordinate distanceFromLocation:originalCoordinate];
if(distance > 1000){
//The map region was shifted by 1000 meters
//Remove annotations outsides the view, or whatever
//Most likely, instead of checking for a distance change, you might want to check for a change relative to the view size
}
}
}
Oh so the annotation views do not auto-correct their position?
The views do, but the pins of course don't. I simply meant removing outside pins. The code above is really just for developers who specifically need to do something when the region changes. It's nice if you want to record what people have been looking at.
| common-pile/stackexchange_filtered |
emacs projectile: override vcs mode
GNU Emacs 24.3.1 + projectile 0.11.0 (installed using melpa)
When I try to find a file (C-c p f) in an svn project (https) it takes ages before the completion comes up. Additionally I require a secure VPN connection which is not always active.
From the debug stacktrace (see below) I suspect it's due to the svn list (which is also very slow when I run it on command line).
Projectile is automatically selecting the svn mode because it recognized this project as an svn project however that's not strictly required for me. I'd be fine if projectile would just do a local find (projectile-generic-command)
My questions:
Does projectile allow me to configure/override the vcs mode somehow (e.g. through .projectile file)?
I know I can switch to native indexing mode, however I don't want to do that globally. How would I set that up for this project only?
Any other solutions?
Stacktrace from the debug-on-quit:
Debugger entered--Lisp error: (quit)
call-process("/bin/bash" nil t nil "-c" "svn list -R . | grep -v '$/' | tr '\\n' '\\0'")
apply(call-process "/bin/bash" nil t nil ("-c" "svn list -R . | grep -v '$/' | tr '\\n' '\\0'"))
process-file("/bin/bash" nil t nil "-c" "svn list -R . | grep -v '$/' | tr '\\n' '\\0'")
shell-command-to-string("svn list -R . | grep -v '$/' | tr '\\n' '\\0'")
projectile-files-via-ext-command("svn list -R . | grep -v '$/' | tr '\\n' '\\0'")
projectile-get-repo-files()
projectile-dir-files-external("<svn_path>" "<svn_path>")
projectile-dir-files("<svn_path>")
#[(it) "^H !\207" [fn it] 2]("<svn_path>")
mapcar(#[(it) "^H !\207" [fn it] 2] ("<svn_path>"))
-mapcat(projectile-dir-files ("<svn_path>"))
projectile-current-project-files()
projectile-find-file(nil)
call-interactively(projectile-find-file nil nil)
I just stumbled upon configuring projectile's behavior. Somehow I overlooked it initially.
I created a .dir-locals.el with: ((nil . ((projectile-svn-command . "find . -type f -print0"))))
I do have a follow up issue as it now where emacs keeps asking me about allowing The local variables list in ... contains variables that are risky (**). ** projectile-svn-command : "find . -type f -print0"... (looking into emacs docs)
Adding '(safe-local-variable-values (quote ((projectile-svn-command . "find . -type f -print0"))))) to my .emacs safe sets the variable
| common-pile/stackexchange_filtered |
set cookie in theme header.php based on page - wordpress
I'm trying to set a cookie in my wordpress theme header.php file.
I've found a bit of information about this but it all seems to use the functions.php file, this isn't really an option for me as I'm setting the cookie based on the page.
I'm just wondering how I could go about doing this, or what a possible work around might be.
Here's my code from my header.php file.
<?
// Set cookie
if (is_page('437')) {
setcookie("DM", "mis", time()+31536000);
} else if (is_page('441')) {
setcookie("DM", "w2p", time()+31536000);
}
echo $_COOKIE["DM"];
print_r($_COOKIE);
// Check cookie to load style
if (!is_front_page()){
if (isset($_COOKIE["DM"])) {
if ($_COOKIE["DM"] == "mis") { ?>
<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo('template_directory'); ?>/css/mis.css" />
<? } else if ($_COOKIE["DM"] == "w2p") { ?>
<link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo('template_directory'); ?>/css/w2p.css" />
<? }
}
}
?>
Setting the cookie, queues it up to be sent to the client, but doesn't add it to the $_COOKIE array. I believe the $_COOKIE array is only constucted and populated once--at the initial request time. Any cookie you want to get to goes to the client and is sent back in the following request for the next page and is then available.
I should add that the cookie does work when viewing page 437 or 441, but once I navigate to another page the cookie doesn't seem to have a value but I haven't done anything to remove its value.
I'd check to see if they're not being set at an earlier request. From the PHP.net manual "Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST. " ---> a set cookie requires a new page load as far as I know.
@Adam and this too: Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.
| common-pile/stackexchange_filtered |
How to have two class names share the same style in ReactJS useStyles
ReactJS useStyles newbie question. In regular CSS I can have two classes share the same style, such as...
.firstDiv, .secondDiv { border: 1px solid red; }
but I'm not clear on how I would do this using ReactJS useStyle.
const useStyles = makeStyles((theme) => ({
firstDiv: {
border: "border: 1px solid red"
},
secondDiv: {
border: "border: 1px solid red"
}
})
I tried firstDiv, secondDiv: { border: "border: 1px solid red" } but doing so just returns a reference error stating firstDiv isn't defined.
Any assistance is greatly appreciated. I'm sure it's a simple syntax issue but all of my searching online only returns examples on how to add two classes to an element, which isn't what I'm looking for. Thanks in advance!
Why can't you just make one class? Do some of them have other rules, not applicable to another one?
@Cerberus The example provided is simplified. I need to hide the border on firstDiv when hovering over secondDiv. Similar to example seen at https://codesandbox.io/s/editable-div-jss-cjdn8?fontsize=14&hidenavigation=1&theme=dark
Since makeStyles takes a JavaScript function that returns an object, your question really is: "How to create an object, where two object keys have the same value?"
For that question, you may found the answer: here.
If you want that for instance that two classes share some properties, that is only possible if you extract them:
const sharedProperties = {
border: "border: 1px solid red",
color: "red"
};
const useStyles = makeStyles((theme) => ({
firstDiv: {
fontSize: 10,
...sharedProperties,
},
secondDiv: {
fontSize: 20,
...sharedProperties,
}
});
Thanks Laczkó Örs! Your example works as intended. I wish there were a cleaner way of doing this all within useStyles to avoid having to create another const but it works. Thanks again!
Really happy to help!
| common-pile/stackexchange_filtered |
Return Array from NPAPI plugin to java script
I want to return array of string from NPAPI plugin to Javascript. Currently I am using only plain NPAPI. I have read the following links:
NPVariant to string array
http://www.m0interactive.com/archives/2010/10/21/how_to_communicate_back_to_javascript_from_npapi_plugin.html
I am able to return alert() from plugin to javascript and I can get the NPNVWindowObject, but I am stuck right now on figuring out how to push elements onto the array and return it to javascript.
Working code samples would be appreciated, thanks
You're already close; you just need to fill in a few details. The FireBreath codebase has examples of doing this, but the actual implementation is a bit abstracted. I don't have any raw NPAPI code that does this; I build plugins in FireBreath and it's almost ridiculously simple there. I can tell you what you need to do, however.
The problem gets simpler if you break it down into a few steps:
Get the NPObject for the window (sounds like you have this)
Create a new array and get the NPObject for that array
Invoke "push" on that NPObject for each item you want to send to the DOM
Retain the NPObject for the array and return it in the return value NPVariant
I'll take a stab at the code you'd use for these; there might be some minor errors.
1) Get the NPObject for the window
// Get window object.
NPObject* window = NULL;
NPN_GetValue(npp_, NPNVWindowNPObject, &window);
// Remember that when we're done we need to NPN_ReleaseObject the window!
2) Create a new array and get the NPObject for that array
Basically we do this by calling window.Array(), which you do by invoking Array on the window.
// Get the array object
NPObject* array = NULL;
NPVariant arrayVar;
NPN_Invoke(_npp, window, NPN_GetStringIdentifier("Array"), NULL, 0, &arrayVar);
array = arrayVar.value.objectValue;
// Note that we don't release the arrayVar because we'll be holding onto the pointer and returning it later
3) Invoke "push" on that NPObject for each item you want to send to the DOM
NPIdentifier pushId = NPN_GetStringIdentifier("push");
for (std::vector<std::string>::iterator it = stringList.begin(); it != stringList.end(); ++it) {
NPVariant argToPush;
NPVariant res;
STRINGN_TO_NPVARIANT(it->c_str(), it->size(), argToPush);
NPN_Invoke(_npp, array, pushId, &argToPush, 1, &res);
// Discard the result
NPN_ReleaseVariantValue(&res);
}
4) Retain the NPObject for the array and return it in the return value NPVariant
// Actually we don't need to retain the NPObject; we just won't release it. Same thing.
OBJECT_TO_NPVARIANT(array, *retVal);
// We're assuming that the NPVariant* param passed into this function is called retVal
That should pretty much do it. Make sure you understand how memory management works; read http://npapi.com/memory if you haven't.
Good luck
Thanks a lot taxilian , it works i am iterating my arraylist and returning it to javascript.
One issue i have is first time it sends array contents seemlesly , next time array's some contents are sended to javascript, after then it crashes.don't know why i tried NPN_RetainObject(array). Problem is same first time no problem, second time array's 2-3 contents browser crashes. In Javascript i am iterating over array and displaying it's contents.
Thanks in advance.
can you attach a debugger and find out where the crash is occurring?
one simple solution i have implemented also ->
std::vector intList;
intList.push_back(10); intList.push_back(20);
for(int i=0;i<intList.size();i++){
int value = args[0].value.intValue; // it is the iterator (i) fetching from javascript
if(value<intList.size())
INT32_TO_NPVARIANT(value,*result);
}
// Javascript side
var test = obj.testArray(); //testArray will give the object of my class where i am implementing the Array returning code inside plugin.
for(var i=0;i<test.length;i++){ //length is property i have set in my plugin class returning the size of the vector
alert(test.item(i)); // this (i) i am receiving in my plugin as args[0].value.intvalue
}
Add another question, don't ask totally different questions in the comments. However, the principle is the same. Get the NPObject and make calls. also, flag the answer as correct; people like to help you more if you are polite about thanking them, and on stackoverflow that means upvotes and flagging correct answers.
Upvotes requires >15 reputation points , i have only 1 right now , but i flagged ur answer . Thanks for ur suggestion .
My answer has not been flagged... but mainly I'm making sure you know. many users who join to ask fb questions dont' seem to
I'll remember it taxilian . To flag the post i had just clicked on flag , one dialog came and filled info.
Thanks taxilian , now i am able to pass array from javascript to NPAPI plugin and viceversa.
you don't click of "flag", you click on the checkmark next to the question.
| common-pile/stackexchange_filtered |
iOS / Xcode - Picking files from Dropbox and transferring to a Public Server
I need to develop an App in which the user can pick files from their Dropbox account and initiate a transfer a Public / Crowd sourced server.
This is not a migration of cloud storage, but manually selecting files and transferring them to a server. I have seen apps which help in migration of cloud storage through an automated script. As this is not a migration, the user may not understand what he is actually doing, or the implications of it.
My question is:
Will Apple reject the app when uploaded to the App Store for such an operation?
Will this be violating User privacy, as the user might unintentionally transfer sensitive information to a public cloud / server?
Diagrammatic representation of the operation:
As per Apple's guidelines
17.1 Apps cannot transmit data about a user without obtaining the user's prior permission and providing the user with access to
information about how and where the data will be used
So basically, to answer your question
You should provide proper message to the user of what exactly your app intends to do. Lets say in the form of a cancellable alert.
Without this apple will surely reject your app.
Secondly, this
should not be the necessary condition for your app to work. Meaning
that your app should work even if the user denies to share his
images and stuff from dropbox.
Prior to sharing / uploading user should get a view of what is being shared. Without this the application will be rejected. (This is even applicable even in the simple facebook share)
You always have a quick look on the Apple's privacy policies here
| common-pile/stackexchange_filtered |
Appium vs Espresso for automated testing framework
For last few weeks, I was using Appium(python) for android testing but yesterday we have decided to shift to Expresso(Java) for automated testing. There are couple of reasons why we are making this shift:
We want to scale out our automated testing, and there are lot of features not present in appium.
This is one of the latest testing framework for android, and has nice backward compatibility.
Small API and very easy to customize.
I have been reading for Espresso but I don't find anything great at all, If I compare it with Appium. I am a Python/R developer so maybe there are couple of points I am not able to understand. Would anyone like to help me understand if the shift to this new testing framework will be good for future? I am missing the bigger picture here, and any help would be greatly appreciated.
don't forget to share your experience/impressions
The Shifting will be very much useful as Espresso supports testing activities outside the app like camera, browser and dialer etc which appium does not support.
Espresso you can test toast message, auto complete and dialogs which are outside app.
With Espresso Test Suit you can find code coverage and measure your testing efforts.
I'm not sure you can test things outside of your app with Espresso. For that you would need to use something like ui-automator. See https://developer.android.com/training/testing/ui-testing/espresso-testing.html and https://developer.android.com/training/testing/ui-testing/uiautomator-testing.html
@YairKukielka That's true, Espresso does not support testing outside the app but it can work in tandem with UiAutomator. So, in the same test code, you can write Espresso as well as UiAutomator and so test in as well as outside the app. Reference: https://plus.google.com/+AndroidDevelopers/posts/WCWANrPkRxg
you can use Espresso Intent to test Camera and phone's dialer activity outside of your app.That's what I meant in my answer.
One of the most important points in my opinion: You just can just test end-to-end / on integration level with Appium. These tend to be indeterministic, rendering the tests more or less useless in my opinion. Failures of the tests are hard to investigate. Furthermore: With complex workflows or with an increasing number of tests they simply don't scale. The solution would be to test component-wise (e.g. per Activity) which is much faster, reliable, traceable, adaptable (mochable), and so on. You can't do that with Appium.
You can go to Espresso if you're sticking only to Android automation and have no idea of automating iOS.
AFIKW, Espresso needs source code of the app in order to automate it.
Advantage is, it's directly open-sourced by google.
But my go is to go with Appium since its a large open sourced community with huge enhancements on its way and easy to automate with any programming language and needless to say it supports both Android and iOS.
I Agree with your views.
Can you clarify what you mean by 'huge enhancements on its way"? I was unable to find much of significance.
i think appium support very low api level still now its only 5.0, which is something not good.
I agree that Espresso may be be very efficient when it comes to Android testing solely. For example, it can run only the activity it's testing, which is great.
Still, I stick to the Appium because it has the same API for both AndroidDriver and iOSDriver. Usually Android apps are accompanied by iOS apps, and if you're responsible for the UI automation, you have to take overall costs into account.
Appium has following advantages over platform-specific solution:
Android and iOS tests can share many classes, including helper methods and configuration,
Android and iOS tests can share common tests logic on higher level, while having different or slightly different implementation on lower level (for example sometimes I can just copy whole page object class and make simple change of locators in order to make it work on the other platform),
same API enables us to seamlessly switch between the iOS and Android test development in a team. Easy switching to Selenium for Web development is additional benefit.
The biggest disadvantage of Appium is the speed of longer test scenarios and some difficulties in locating elements, but still it's my choice.
As the side note, I'd like to add that you shouldn't forget about the test pyramid which refers to test automation. Please keep balance between Unit Tests, Integration tests and UI tests http://martinfowler.com/bliki/TestPyramid.html
What would you recommend in terms of stability and long-term maintenance cost? Appium or Espresso?
The main difference between the two is,
Espresso test is within the application and it is aware of all the layers of the application. So you can mock certain layers of app, more like a white-box testing
Appium tests are black-box, tests know only the UI layer of the app. Main advantage is for cross-platform testing.
| common-pile/stackexchange_filtered |
Determination of file extension not working for large files
I've coded the following script such that it shows error if any non-image file is uploaded or any image that is larger than 4 MB. Now, when I upload any image larger that 4 Mb or when I upload any small video file , it shows error and that's fine. But when I upload a larger file(say 50 MB or so), it doesn't show any error.. Rather it just shows blank page in registration.php. It should have redirected to 'complete_profile.php' if there was any error. This happens only with large file.. Why is this?
Code in registration.php:
if(isset($_POST['answerbox1']) && isset($_POST['answerbox5']) && isset($_POST['answerbox6']) && isset($_POST['sex']) && isset($_FILES['hiddenfilebutton'])){
$img_name = $_FILES['hiddenfilebutton']['name'];
$img_temp = $_FILES['hiddenfilebutton']['tmp_name'];
$a = explode('.',$img_name);
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$img_extension = strtolower(end($a));
unset($a);
$img_size = $_FILES['hiddenfilebutton']['size'];
if(!getimagesize($img_temp)) {
$error = 'Invalid image';
$_SESSION['error'] = $error;
header('Location: ../../../complete_profile.php');
} else if($img_size > 4000000) {
$error = 'Image should be less than 4 MB';
$_SESSION['error'] = $error;
header('Location: ../../../complete_profile.php');
} else if(!in_array($img_extension, $allowed_ext)) {
$error = "Unsupported image format";
$_SESSION['error'] = $error;
header('Location: ../../../complete_profile.php');
} else {
header('Location: ../../../desk.php');
}
}
put this at the top of you're file error_reporting(E_ALL);ini_set('display_errors', 1);
My guess would be to look at the post_max_size and upload_max_filesize config variables
It was post_max_size.. Thanks a tonne.. Changed it and everything's fine..
| common-pile/stackexchange_filtered |
Cobordisms between spheres
In the category $Cob_n$ of closed $n-1$ dimensional manifolds and cobordisms between them, I am wondering what happens when we restrict our attention only to spheres. In the case when $n=2$, the only closed $1$ manifolds are disjoint unions of circles and any cobordism between any two closed $1$-manifolds can be built from pants, copants, cups and caps. Is it always true that any cobordism between two disjoint unions of spheres can be built from these elementary pieces?
| common-pile/stackexchange_filtered |
How can I create an animation showing how a circular sector deformed to a cone?
I want to create the following animation with Mathematica.
What is the simplest way to do so?
My first effort:
GenerateLines[a_, b_, r_, n_] :=
Table[r {Cos[\[Theta]], Sin[\[Theta]], 0}, {\[Theta], a, b, (b - a)/
n}];
basePts = GenerateLines[\[Pi]/6, 2 \[Pi] - \[Pi]/6, 3, 200];
peakPt = {{0, 0, 3}};
baseLine = Line@basePts;
slantedLines = Line /@ Tuples[{basePts, peakPt}];
Graphics3D[{baseLine, slantedLines}]
The wireframe can be removed with a textured surface as shown in this site.
What have you tried?
ClearAll[cone, radius]
radius[h_] = r /. First@
Solve[{Pi r Sqrt[r^2 + h^2] (1 + h )/2 == Pi /2, h > 0}, r, Reals];
radius[0] = 1;
cone[h_] := ParametricPlot3D[{Cos[θ] (1 - z) radius[h], Sin[θ] (1 - z) radius[h], h z},
{θ, 0, Pi + h Pi}, {z, 0, 1},
PlotStyle -> None,
MeshFunctions -> {#4&},
Boxed -> False,
PlotRange -> 1.5 {{-1, 1}, {-1, 1}, {0, 1}},
BoundaryStyle -> GrayLevel[.2],
PerformanceGoal -> "Quality",
Axes -> False];
axes = Graphics3D[{Red, Arrowheads[Medium],
MapThread[{Arrow[{{0, 0, 0}, 1.4 #2}], Text[#, 1.5 #2]} &,
{{"X", "Y", "Z"}, IdentityMatrix[3]}]}];
Manipulate[Show[cone @ h, axes], {{h, 0, "height"}, 0, 1}]
Animation above produced using:
frames = Table[Show[cone @ h, axes], {h, 0, 1, .01}];
Export["animatecone.gif", frames, AnimationRepetitions -> ∞, DisplayAllSteps -> True]
@KimJongUn, please see the updated version.
Thank you very much!
ClearAll[draw];
draw[deg_, segmentsNumber_Integer, z_] :=
With[{singleSegment =
Polygon@{{0, 0, z}, {1, 0, 0}, {Cos[deg Degree], Sin[deg Degree], 0}}},
NestList[
GeometricTransformation[#,
RotationTransform[deg Degree, {0, 0, 1}]] &, singleSegment,
segmentsNumber]]
Manipulate[
Graphics3D[{Red, Arrow[{{0, 0, 0}, {1.5, 0, 0}}],
Arrow[{{0, 0, 0}, {0, 1.5, 0}}], Arrow[{{0, 0, 0}, {0, 0, 1.5}}],
Text["x", {1.6, 0, 0}], Text["y", {0, 1.6, 0}],
Text["z", {0, 0, 1.6}], Transparent, draw[10 + i*8, 19, i]},
Boxed -> False, PlotRange -> {{-2, 2}, {-2, 2}, {-2, 2}}], {i, 0, 1}]
Update
For removing axes moves, use PlotRange in Graphics3D:
PlotRange -> {{-2, 2}, {-2, 2}, {-2, 2}}
Excellent! Let me wait for a couple of hours or maybe days.
@KimJongUn I used Snagit to capture which also have a built-in gif converter.
Thank you very much!
Animate[
r = Sqrt[1 - h^2];
phi = Sqrt[2] Pi /r;
pts = Table[r {Cos[p], Sin[p], 0}, {p, 0, phi, phi/10}];
ptsc = Table[r {Cos[p], Sin[p], 0}, {p, 0, phi, phi/100}];
Graphics3D[{Line[ptsc], Line[{#, {0, 0, h}}] & /@ pts, Red,
Arrow[{{0, 0, 0}, {1, 0, 0}}], Arrow[{{0, 0, 0}, {0, 1, 0}}],
Arrow[{{0, 0, 0}, {0, 0, 1}}], Text["X", {1.1, 0, 0}],
Text["Y", {0, 1.1, 0}], Text["Z", {0, 0, 1.1}]}, Boxed -> False,
PlotRange -> {{-1, 1}, {-1, 1}, {0, 1}}]
, {h, 0, 1/Sqrt[2]}, TrackedSymbols -> h]
Just a start:
Manipulate[
Graphics3D[Cone[{{0, 0, h}, {0, 0, 1}}]],
{h, 0, 0.9}
]
And a bit more...
Manipulate[
Graphics3D[{
{Opacity[0.5], Cone[{{0, 0, h}, {0, 0, 1}}]},
Line[{{1.25, 0, 0}, {0, 0, 0}}],
Line[{{0, 1.25, 0}, {0, 0, 0}}],
Line[{{0, 0, 1.25}, {0, 0, 0}}]
},
Boxed -> False],
{h, 0, 0.9}
]
From a sector to a cone rather than from a circle to a cone. :-)
At first we shrinking the boundary of sector to circle, keeping the arc length. That is l*α==R*θ
α = 0.8*2 π;
l = 4;
Manipulate[
ParametricPlot3D[R*{Cos[s], Sin[s], 0} /.R->(l*α)/θ, {s, 0, θ}, PlotRange -> 4,
PerformanceGoal -> "Quality"], {θ, α, 2 π}]
Then we draw line from the shrinking curve to the vertex of the cone {0,0,Sqrt[l^2 - R^2]} so we keep the length of generatrix say l.
α = 0.8*2 π;
l = 4;
Manipulate[
ParametricPlot3D[(1 - t)*(R*{Cos[s], Sin[s], 0}) +
t*{0, 0, Sqrt[l^2 - R^2]} /. R -> (l*α)/θ, {s,
0, θ}, {t, 0, 1}, PlotRange -> 4,
PerformanceGoal -> "Quality", MeshFunctions -> {#4 &}, Mesh -> 20,
Boxed -> False], {θ, α, 2 π, .2}]
| common-pile/stackexchange_filtered |
Clustered Bar plot in r using ggplot2
Snip of my data frame is
Basically i want to display barplot which is grouped by Country i.e i want to display no of people doing suicides for all of the country in clustered plot and similarly for accidents and Stabbing as well.I am using ggplot2 for this.I have no idea how to do this.
Any helps.
Thanks in advance
For future reference, posting an image of your data is about the least useful method of displaying it here. Look at how to make a reproducible example http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example - you'll get much more help if you make your data easy to use
Edit to update for newer (2017) package versions
library(tidyr)
library(ggplot2)
dat.g <- gather(dat, type, value, -country)
ggplot(dat.g, aes(type, value)) +
geom_bar(aes(fill = country), stat = "identity", position = "dodge")
Original Answer
dat <- data.frame(country=c('USA','Brazil','Ghana','England','Australia'), Stabbing=c(15,10,9,6,7), Accidents=c(20,25,21,28,15), Suicide=c(3,10,7,8,6))
dat.m <- melt(dat, id.vars='country')
I guess this is the format you're after?
ggplot(dat.m, aes(variable, value)) +
geom_bar(aes(fill = country), position = "dodge")
library(reshape)
@Hack-R check to be sure you are not trying to plot a factor.
library(ggplot2)
library(reshape2)
df <- data.frame(country=c('USA','Brazil','Ghana','England','Australia'), Stabbing=c(15,10,9,6,7), Accidents=c(20,25,21,28,15), Suicide=c(3,10,7,8,6))
mm <- melt(df, id.vars='country')
ggplot(mm, aes(x=country, y=value)) + geom_bar(stat='identity') + facet_grid(.~variable) + coord_flip() + labs(x='',y='')
| common-pile/stackexchange_filtered |
Convert 12 hour time g:i a to 24 hh:mm:ss PHP
I've been working on a PHP powered site, and made use of this very nice jquery-based timepicker: http://sourceforge.net/projects/pttimeselect/
However I need to be able to convert the time that this outputs, which is styled as 1:00 PM, to hh:mm:ss that I can insert into a MySQL database.
How can this be done with PHP?
This can be achieve pretty simply with strtotime().
So let's say you're starting off with "1:30 PM", and want to get that to "13:00:00". The advantage to this, for me, is to pull from the database only results with a time that is later than right now, and this is quite possible with the hh:mm:ss format. This code will do it:
$twelveHourTime = "1:30 PM";
$twentyFourHourTime = (date("H:i", strtotime($twelveHourTime))) . ":00";
And that's it! You can check it out here: http://sandbox.onlinephpfunctions.com/code/a8957d18717c5ccb43c1701551ea8399156fd84f
| common-pile/stackexchange_filtered |
Apache configuration so images are cached for a long time
I'm asking here since no matter what I try I keep noticing images keep being reloaded after a while. Basically I want images to be cached for 11 months, but if anything they seem to be cached for minutes or hours. This is a node.js application with static files served by apache. The images are inside the public/static dir. This is what I have:
NameVirtualHost *:443
<VirtualHost *:443>
ServerName app.site.com
ProxyPreserveHost On
RequestHeader set "X-Forwarded-Proto" expr=%{REQUEST_SCHEME}
RequestHeader set "X-Forwarded-SSL" expr=%{HTTPS}
Alias "/static/" "/home/node/app/public/static/"
<Directory /home/node/app/public>
Options FollowSymLinks
AllowOverride None
Require all granted
ExpiresActive On
ExpiresByType image/jpeg "access plus 11 months"
ExpiresByType image/jpg "access plus 11 months"
ExpiresByType image/png "access plus 11 months"
ExpiresByType image/gif "access plus 11 months"
</Directory>
RewriteEngine On
RewriteCond %{HTTP:Upgrade} =websocket [NC]
RewriteRule /(.*) ws://localhost:3210/$1 [P,L]
RewriteCond %{HTTP:Upgrade} !=websocket [NC]
RewriteRule ^/(?!static/)(.*)$ http://localhost:3210/$1 [P,L]
SSLCertificateFile /root/.lego/certificates/_.site.com.crt
SSLCertificateKeyFile /root/.lego/certificates/_.site.com.key
</VirtualHost>
Having the console open and reloading to catch network activity shows this on a random image:
200 OK
Response header:
HTTP/1.1 200 OK
Date: Wed, 12 Aug 2020 10:27:50 GMT
Server: Apache
Last-Modified: Mon, 01 Jun 2020 19:03:16 GMT
ETag: "3313-5a70a727f2500"
Accept-Ranges: bytes
Content-Length: 13075
Cache-Control: max-age=28512000
Expires: Thu, 08 Jul 2021 10:27:50 GMT
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: image/png
Request header:
GET /static/img/profile_5a914158141c9367e38c4d8a.png?ver=74 HTTP/1.1
Host: hue.merkoba.com
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:79.0) Gecko/20100101 Firefox/79.0
Accept: image/webp,*/*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Referer: https://app.site.com/
Cookie: connect.sid=s%3AUZb7Zopuy6LId0iMeMYVaKDtfuppIIxL.8F7Hx%2FeqrodOsS2fHPZjOqRDKTBM4RoBwcKiUu0PUUg; io=fbMMZAHDTJzbnoVvAAAo
Cache-Control: max-age=0
If-Modified-Since: Mon, 01 Jun 2020 19:03:16 GMT
If-None-Match: "3313-5a70a727f2500"
Some curl test:
curl -vso /dev/null https://app.site.com/static/img/profile_5f192733805c646004ecf4c8.png?ver=1
* Trying <IP_ADDRESS>:443...
* TCP_NODELAY set
* Connected to app.site.com (<IP_ADDRESS>) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
* CAfile: /etc/ssl/certs/ca-certificates.crt
CApath: /etc/ssl/certs
} [5 bytes data]
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
} [512 bytes data]
* TLSv1.3 (IN), TLS handshake, Server hello (2):
{ [112 bytes data]
* TLSv1.2 (IN), TLS handshake, Certificate (11):
{ [2391 bytes data]
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
{ [147 bytes data]
* TLSv1.2 (IN), TLS handshake, Server finished (14):
{ [4 bytes data]
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
} [37 bytes data]
* TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1):
} [1 bytes data]
* TLSv1.2 (OUT), TLS handshake, Finished (20):
} [16 bytes data]
* TLSv1.2 (IN), TLS handshake, Finished (20):
{ [16 bytes data]
* SSL connection using TLSv1.2 / ECDHE-ECDSA-AES256-GCM-SHA384
* ALPN, server accepted to use http/1.1
* Server certificate:
* subject: CN=*.site.com
* start date: May 14 20:51:05 2020 GMT
* expire date: Aug 12 20:51:05 2020 GMT
* subjectAltName: host "app.site.com" matched cert's "*.site.com"
* issuer: C=US; O=Let's Encrypt; CN=Let's Encrypt Authority X3
* SSL certificate verify ok.
} [5 bytes data]
> GET /static/img/profile_5f192733805c646004ecf4c8.png?ver=1 HTTP/1.1
> Host: app.site.com
> User-Agent: curl/7.68.0
> Accept: */*
>
{ [5 bytes data]
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Date: Wed, 12 Aug 2020 10:30:40 GMT
< Server: Apache
< Last-Modified: Thu, 23 Jul 2020 06:01:07 GMT
< ETag: "16f27-5ab15950eeec0"
< Accept-Ranges: bytes
< Content-Length: 93991
< Cache-Control: max-age=28512000
< Expires: Thu, 08 Jul 2021 10:30:40 GMT
< Content-Type: image/png
<
{ [5 bytes data]
* Connection #0 to host app.site.com left intact
| common-pile/stackexchange_filtered |
How to measure EVM?
I am trying to understand the concept of EVM and how it is measured at different points in transceiver. I have a basic understanding that the error difference is calculated between two vectors (i.e. ideal and measured symbols on IQ plot) and RMS EVM is computed.
I believe this happens at receiver end after a radio receives signals , goes through RF Front end , converts to baseband and then CFO & SFO estimation/compensation. Once the symbols are mapped onto the constellation , we measure the EVM . Is my understanding correct ?
In my case , I am generating 11b waveform and it goes through the power amplifier model . Want to see houw much the EVM is before and after it goes through Tx hardware impairment module . All I have is time domain IQ samples .
TO measure EVM in this case , Do I need to again convert the iq Samples to the respective symbols and then measure EVM ?
Can anyone please throw some light on this and suggest any docs which I should go through ?
Jani
This is answered here I believe, please take a look to see if it applies: https://dsp.stackexchange.com/questions/67183/how-to-calculate-evm-in-age-of-an-equalized-constellation-in-16qam/67185#67185
Also you can derive it from a correlation coefficient-- here is the EVM to SNR relationship https://www.keysight.com/main/editorial.jspx?ckey=847674&id=847674&nid=-11143.0.00&lc=eng&cc=UG#:~:text=The%20relationship%20between%20EVM(Vector,power%20to%20the%20error%20power. and here is the SNR to correlation coefficient relationship: https://dsp.stackexchange.com/questions/30847/noise-detection
(But to do any of that you have to demodulate, so yes to your last question)
Thanks Dan.. Going through KS link and SE posts now
| common-pile/stackexchange_filtered |
Repository does not exist or may require 'docker login': denied: requested access to the resource is denied
I have a docker-compose.yml file that should spin up a test server for me to run my integration tests against:
version: '3.8'
services:
testserver:
image: registry.gitlab.com/group/image:latest
...
On my .gitlab-ci.yml file I have the following scripts to log into the container registry so that I can pull the private image.
before_script:
- echo '>>>>> DEBUG - install all required packages and project dependencies'
- apk update && apk add nodejs npm git
- npm install --global yarn
- yarn install
- echo '>>>>> DEBUG - login to the container registry'
- docker login registry.gitlab.com -u $CONTAINER_REGISTRY_USER -p $CONTAINER_REGISTRY_TOKEN
- echo '>>>>> DEBUG - create the docker container'
- docker compose -f docker-compose.yml up --force-recreate -d && sleep 3
On my CI/CD output, I see the following logs:
$ echo '>>>>> DEBUG - login to the container registry'
>>>>> DEBUG - login to the container registry
$ docker login registry.gitlab.com -u $CONTAINER_REGISTRY_USER -p $CONTAINER_REGISTRY_TOKEN
Login Succeeded
$ echo '>>>>> DEBUG - create the docker container'
>>>>> DEBUG - create the docker container
$ docker compose -f docker-compose.yml up --force-recreate -d && sleep 3
testserver Pulling
testserver Error
Error response from daemon: pull access denied for registry.gitlab.com/group/image, repository does not exist or may require 'docker login': denied: requested access to the resource is denied
I'm confused because I see a Login Succeeded being outputted but as soon as I do a docker compose up, I get this error:
repository does not exist or may require 'docker login': denied: requested access to the resource is denied
| common-pile/stackexchange_filtered |
JS Bin while infinite loop
I noticed strange behaviour of JS Bin runner when I execute the following code:
var ask = prompt("test");
while(ask!=="yes"){
ask = prompt("test");
}
I get this kind of error:
Exiting potential infinite loop at line 4. To disable loop protection:
add "// noprotect" to your code
I was wandering why is that happening ? (The execution of that code works fine in site code)
It says potential because unless you answer yes, it will be an infinite loop. Don't worry too much about JSBin, personally I never use it.
Yeach, I know, but because of that it completely blocks my code from execution
Run it on JSFiddle or just add //noprotect
There is an unsolvable problem in computer science called The Halting Problem.
In short, it means that a computer cannot look at a piece of code and figure out if it will go into an endless loop or end at some time. However, they can make some guesses about it and warn you if they spot anything that might be dangerous.
Not is. Might be.
This is one of those cases. The system is warning you and you have to say "Yea, yea, I heard you. Do it anyways."[*]
[*] This, of course, is to prepare us for a Star-Trek Universe where we disable the safety on everything to save the day.
prompt, alert, confirm.
These JS functions are synchronous, that means browser will stop doing anything and will hold/wait for the user response. Since you also possibly created a infinite loop by prompting again by checking the result of previous prompt, it throws that message.
This infinite loop will make the browser nonresponsive
| common-pile/stackexchange_filtered |
Python with google cloud language api Problem?
Using the google-cloud-language library for python how can I get the JSON returned from the following methods.
client.classify_text()
client.analyze_entity_sentiment()
the method response.serializetostring() seems to encode the result in a manner that can't be decoded in python. Not UTF-8 or unicode escape.
I want to get the JSON so that I can dump it in mongodb.
Thanks in advance.
You can use the google.protobuf.json_format.MessageToJson method to serialize a plain protobuf object to JSON. For example:
from google.cloud import language
from google.protobuf.json_format import MessageToJson
client = language.LanguageServiceClient()
document = language.types.Document(
content='Mona said that jogging is very fun.',
type='PLAIN_TEXT',
)
response = client.analyze_entity_sentiment(
document=document,
encoding_type='UTF32',
)
print(MessageToJson(response))
Prints:
{
"entities": [
{
"name": "Mona",
"type": "PERSON",
"salience": 0.6080747842788696,
"mentions": [
{
"text": {
"content": "Mona"
},
"type": "PROPER",
"sentiment": {
"magnitude": 0.10000000149011612,
"score": 0.10000000149011612
}
}
],
"sentiment": {
"magnitude": 0.10000000149011612,
"score": 0.10000000149011612
}
},
{
"name": "jogging",
"type": "OTHER",
"salience": 0.39192524552345276,
"mentions": [
{
"text": {
"content": "jogging",
"beginOffset": 15
},
"type": "COMMON",
"sentiment": {
"magnitude": 0.8999999761581421,
"score": 0.8999999761581421
}
}
],
"sentiment": {
"magnitude": 0.8999999761581421,
"score": 0.8999999761581421
}
}
],
"language": "en"
}
| common-pile/stackexchange_filtered |
PIC18F25k50 - 10-bit PWM resolution with 8-bit timer?
Im messing around with PIC18F25k50 standard mode PWM.
I found something weird. Datasheet says, that PWM is 10-bit, and timer is 8-bit.
How that can be?
Is that datasheet is wrong, or my english is too bad to understand that correctly?
What is the point of 10-bit PWM with 8-bit timer?
Where did you get that timer (which one?) is 8-bit? I don't see it in the snippet from the datasheet.
Timer2 in PIC18F25k50 is 8-bit for sure. "The maximum PWM resolution is 10 bits when PR2 is 255". Maximum PR2 value is 255 (PR2 is stored in single 8-bit register).
This is clearly answered in the datasheet right where you'd expect to find it. Duh.
See the datasheet:
Either two bits of the timer prescaler or the divider for the internal system clock is used for the two LSBs.
Similarly, the duty cycle value storage is split between CCPRxL and CCPxCON<5:4> as shown.
So... I have to change prescaler to get 1024 diffrent pulse width values?
Nope just load CCPRxL and CCPxCON<5:4>.
I don't know about that chip specifically, but some PIC PWM peripherals can make use of the timer prescaler bits to create "extended" resolution.
The datasheet states on page 189 that the timer is combined with two clock bits or prescaler bits to create the 10 bit pwm counter.
| common-pile/stackexchange_filtered |
Modular arithmetic with polynomial
Given $n=pq$ where $p\;\&\; q,p\ne q$ are primes,
P(x) is polynomial and $z\in\mathbb Z_{n}$
I need to prove that:
$p(z)\equiv 0\pmod{n}\iff p(z\pmod{p})\equiv 0\pmod{p}\;\land p(z\pmod{q})\equiv0\pmod{q}$
If i could prove the more general case: P(z) mod n ≡ P(z mod p) mod p
(q is the same) then i could also prove what i need of course.
from my understanding so far, the above is true, but i can't figure out a way to prove this.
Back to the original question, i tried to see why the fact that p divides P(z mod p) and q divides P(z mod q) implies that pq divides P(z) and vice versa, but i didn't have much success with this.
A hint is sufficient. thank you!
I guess $p$ and $q$ are different primes?
Hints:
Chinese remainder theorem, to go from $p,q$ to $n$.
Expand the polynomial $P$, to see that $P(z \mod m)\equiv P(z)\pmod{m}$.
First, generally $\rm\,\ p,q\mid n\iff {\rm lcm}(pq)\mid n.\,$ But $\rm\ {\rm lcm}(p,q) = pq\,$ when $\rm\,p,q\,$ are coprime.
Second $\rm\,\ p\mid P(n)\iff p\mid P(n\ {\rm mod}\ p)\ $ holds true because $\rm\ {\rm\ mod}\ p\!:\ A\equiv a\ \Rightarrow\ P(A)\equiv P(a),\,$ for any polynomial $\rm\,P\,$ with integer coefficients. This is true because polynomials are composed of Sums and Products, and these operations respect congruences, i.e. the rules below hold true
Congruence Sum Rule $\rm\qquad\quad A\equiv a,\quad B\equiv b\ \Rightarrow\ \color{#0a0}{A+B\,\equiv\, a+b}\ \ \ (mod\ m)$
Proof $\rm\ \ m\: |\: A\!-\!a,\ B\!-\!b\ \Rightarrow\ m\ |\ (A\!-\!a) + (B\!-\!b)\ =\ \color{#0a0}{A+B - (a+b)} $
Congruence Product Rule $\rm\quad\ A\equiv a,\ \ and \ \ B\equiv b\ \Rightarrow\ \color{#c00}{AB\equiv ab}\ \ \ (mod\ m)$
Proof $\rm\ \ m\: |\: A\!-\!a,\ B\!-\!b\ \Rightarrow\ m\ |\ (A\!-\!a)\ B + a\ (B\!-\!b)\ =\ \color{#c00}{AB - ab} $
Beware that such rules need not hold true for other operations, e.g.
the exponential analog of above $\rm A^B\equiv a^b$ is not generally true (unless $\rm B = b,\,$ so it follows by applying $\,\rm b\,$ times the Product Rule).
thank you, i understood this from the answer of vadim123 as he mentioned chinese remainder theorem. but your answer is still helpful and appreciated.
@flyman It's is quite overkill to invoke CRT to deduce the first line of my answer. It is much better, conceptually (and computationally) to be familiar with properties of lcm and gcds. Ditto for the conceptual foundations of the second part. It is essential to comprehend these fundamental ideas if you wish to master elementary number theory.
I am familiar with these ideas, just had difficulty solving this problem. i didn't use CRT, it just helped think of the solution, i proved that P(z) mod n ≡ P(z mod p) mod p with the congruence sum & product rules that are used in CRT (mapping P(z) mod n to P(z mod p) mod p). thank you again!
| common-pile/stackexchange_filtered |
Validating an Azure AD generated JWT signature and algorithm in .NET Core 3.1
I am new to Azure AD. We are using v1.0 token. I have an Azure JWT token validation routine mostly based on ValidateSignature and AzureTokenValidation
The below is my ClaimsTransformer:
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
<do something>
var token = httpContextAccessor.HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
if (Validate(token))
{
<proceed to add claims>
}
and my validation routine:
public bool Validate(string token)
{
string stsEndpoint = "https://login.microsoftonline.com/common/.well-known/openid-configuration";
ConfigurationManager<OpenIdConnectConfiguration> configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsEndpoint, new OpenIdConnectConfigurationRetriever());
OpenIdConnectConfiguration config = configManager.GetConfigurationAsync().Result;
TokenValidationParameters parameters = new TokenValidationParameters
{
ValidIssuer = "https://sts.windows.net/<mytenant-id>",
ValidAudience = <my client-id>,
IssuerSigningKeys = config.SigningKeys,
ValidateAudience = true,
ValidateIssuer = true,
ValidateLifetime = true,
};
JwtSecurityTokenHandler tokendHandler = new JwtSecurityTokenHandler();
SecurityToken jwt;
bool verified;
try
{
var handler = tokendHandler.ValidateToken(token, validationParameters, out jwt);
var signature = ((System.IdentityModel.Tokens.Jwt.JwtSecurityToken)jwt).RawSignature;
string algorithm = ((System.IdentityModel.Tokens.Jwt.JwtSecurityToken)jwt).Header["alg"].ToString();
if (signature.Length == 0 || algorithm.ToLower().Equals("none"))
{
tokenVerified = false;
}
tokenVerified = true;
}
catch
{
tokenVerified = false;
}
return tokenVerified;
}
Please tell me if I am doing the right thing or can I just use (in my Validate(string token)
try
{
var result = tokendHandler.ValidateToken(token, validationParameters, out _);
verified = true;
}
catch {
verified = false;
}
and is, the checking for algorithm (to not accept "none" in alg) and signature presence is required or this way to check is right? There is no "secret keys"
Any reason you are not implementing standard Azure AD JWT authentication in your app? Why write manual validation?
hi junas no reason, since I am new I don't know if any exists. Are there any routines? Or am I missing something obvious (Mostly I may not know). Are you able to help?
Here's the official sample on building an API protected by Azure AD JWTs: https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/blob/master/4-WebApp-your-API/4-1-MyOrg/README.md
JwtBearer middleware, like the OpenID Connect middleware in web apps, validates the token based on the value of TokenValidationParameters. The token is decrypted as needed, the claims are extracted, and the signature is verified. The middleware then validates the token by checking for this data:
Audience: The token is targeted for the web API.
Sub: It was issued for an app that's allowed to call the web API.
Issuer: It was issued by a trusted security token service (STS).
Expiry: Its lifetime is in range.
Signature: It wasn't tampered with.
For more details refer this document
Example:
String token = "Token";
string myTenant = "Tenant Name";
var myAudience = "Audience";
var myIssuer = String.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{0}/v2.0", myTenant);
var mySecret = "Secrete";
var mySecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(mySecret));
var stsDiscoveryEndpoint = String.Format(CultureInfo.InvariantCulture, "https://login.microsoftonline.com/{0}/.well-known/openid-configuration", myTenant);
var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever());
var config = await configManager.GetConfigurationAsync();
var tokenHandler = new JwtSecurityTokenHandler();
var validationParameters = new TokenValidationParameters
{
ValidAudience = myAudience,
ValidIssuer = myIssuer,
IssuerSigningKeys = config.SigningKeys,
ValidateLifetime = false,
IssuerSigningKey = mySecurityKey
};
var validatedToken = (SecurityToken)new JwtSecurityToken();
// Throws an Exception as the token is invalid (expired, invalid-formatted, etc.)
tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
Console.WriteLine(validatedToken);
Console.ReadLine();
OUTPUT
Thanks you @ShrustiJoshi-MT. But as you can see in my code I don't have a "mySecurityKey". There is no secret shared between Azure and local API. Is this secret a must to validate the signature? Is there a way to validate the token's signature without this key?
| common-pile/stackexchange_filtered |
Example of a proper class of graphs for which no member is isomorphic to an induced subgraph of a different member?
Sorry if this is trivial but can someone construct for me any proper class of (not necessarily finite) undirected graphs $C$ for which no graph in $C$ is isomorphic to an induced subgraph of a different graph in $C$?
Or if not then prove that there exists no such class with this property.
It is relatively easy to think of proper classes of graphs, for example the class of complete graphs, since for any set $S$ there exists a unique complete graph $G$ with $V(G)=S$.
However I can't seem to think of any that satisfy the second condition that no graph in the proper class can be isomorphic to an induced subgraph of a different graph in said class.
I have a feeling that it is either impossible to construct such a class or there are many simple examples of such classes which I am just failing to notice due to an error in my intuition, so sorry if it is trivial.
This came up because I was thinking about hereditary graph properties during a bus ride (graph properties closed under induced subgraphs) and I know its not hard to show that for every hereditary property there exists a class of forbiden induced subgraphs which characterise it e.g. trivially take those graphs without the property, though this doesn't seem to imply the existence of a set of forbiden induced subgraphs rather only the existence of a class of such graphs which may or may not be a set as a result if there existed no such class as I described then the existence of a set of forbidden induced subgraphs not just a class of them would in fact be guaranteed for any hereditary graph property.
Perhaps surprisingly, you can't do this without additional set-theoretic axioms (so far as we currently know): the statement that there is no such proper class, Vopenka's principle, is currently not known to be inconsistent with ZFC (in fact, it's generally believed that it is consistent - which is amusing, given that Vopenka didn't think so and introduced it somewhat sarcastically).
Actually, Vopenka's principle says something stronger: that we can always find an elementary embedding. The definition of elementary embedding is a bit technical, but for now it suffices to observe that every elementary embedding is in fact an induced subgraph embedding. (That said, it turns out that we can drop elementarity here and get an equivalent principle - Vopenka's principle is very robust.)
That said, Vopenka's principle is in a precise sense "less likely" than its negation: while we can prove (in a very weak theory - much weaker than ZFC) ZFC + "Vopenka's principle fails" is consistent if ZFC itself is, the theory ZFC + Vopenka proves the consistency of ZFC itself. The standard example of the former is if V=L.
Indeed, Vopenka is extremely strong in terms of consistency strength - it lies fairly high up the large cardinal hierarchy.
Not really.
Vopěnka's principle states that every class of graphs, one embeds elementarily into the other.
But what is an elementary embedding of $G$ into $G'$? Well, it means, in particular, that $G$ is an induced subgraph of $G'$, since having an edge or not having an edge must be preserved by an elementary embedding of graphs.
So what you're asking for is a counterexample to Vopěnka's principle. And if you can prove that there is one, then you give a new upper bound to the large cardinal hierarchy.
Dangit, you beat me to it!
@Asaf, I'm not really sure how graphs are formalized in model theory, but what if we have multiple edges between our vertices? How does elementarity help there?
@ShervinSorouri: Graphs are irreflexive and symmetric relations. You're thinking about multigraphs. In either case, elementarity tells you how many (in the case of finitely many).
Oh, I see. Thanks for the explanation!
| common-pile/stackexchange_filtered |
Incorporate dropdown and dialog together in React Typescript
I am new to react and need your help.
I have a dropdown and on selecting a value I am checking if selected value is not meeting a condition I need to prompt a dialog box to user if he wants to continue to go with the selection,if he selects yes then selected value to be saved in database.
On select and on selecting yes are two callback functions. My query is how to set the state for current selected value during OnSelect callback so that I can make it available within OnSelectYes also.
please provide minimal implementations in your question.
Please provide enough code so others can better understand or reproduce the problem.
You should look into https://react-select.com/async
Will make it easier to make this select component that you want.
| common-pile/stackexchange_filtered |
Rvest Unable to Webscrape Certain Site
Trying to create an application in R that returns search data from the following website:
https://www.gsaadvantage.gov/advantage/main/start_page.do
and then perform necessary analysis of data. I am using the "rvest" package, and the website's formatting is nearly impossible to work with. For example, something similar to the following method works on other websites, but something about this site is causing problems:
library('rvest')
url <-"https://www.gsaadvantage.gov/advantage/s/search.do?s=0&c=100&q=0:2mouse+pad&searchType=1&p=1"
data <- read_html(url) %>%
html_nodes('.arial strong') %>%
html_text()
IS there something we're doing wrong, and is there a better package for use on the GSA website. Thank you!
Did you mean to add a %>% between the last two calls? Otherwise, I'm not sure why the search yields 404
In addition to the missing %>%, your url seems to be invalid
Yesterday that url was buggy, but worked fine. Now it doesn't seem to be working. The previous problem we were encountering was not with accessing the site, but now we have that problem too. I updated the code with the following url: https://www.gsaadvantage.gov/advantage/s/search.do?s=0&c=100&q=0:2mouse+pad&searchType=1&p=1
| common-pile/stackexchange_filtered |
How do you validate password using mongoose for mongoDB in an express app for logging in a user?
I am trying to have a user log in by their email and password. MongoDb docs shows hashing the password with bcrypt in the user model. It also provides a nice way to validate the password in the model as well. My problem is how to I use that validation from the "controller"? I am very aware "if (req.body.password === user.password)" will not work because one is hashed and the other is not.
I have been searching for answers for hours and can't seem to find that connection on how I use that "UserSchema.methods.comparePassword" method in my post request to log in. This isn't completely a real log in, just trying to get the password to validate and send back a key once logged in. Here are the docs: https://www.mongodb.com/blog/post/password-authentication-with-mongoose-part-1
// This is my UserModel
let mongoose = require('mongoose'),
Schema = mongoose.Schema,
bcrypt = require('bcrypt'),
SALT_WORK_FACTOR = 10
var hat = require('hat');
let UserSchema = new Schema({
email: {
type: String,
required: true,
index: {
unique: true
}
},
password: {
type: String,
require: true
},
api_key: {
type: String
}
});
UserSchema.pre('save', function(next) {
var user = this;
// only hash the password if it has been modified (or is new)
if (!user.isModified('password')) return next();
// generate a salt
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
if (err) return next(err);
// hash the password using our new salt
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
// override the cleartext password with the hashed one
user.password = hash;
user.api_key = hat();
next();
});
});
});
UserSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
module.exports = mongoose.model('user', UserSchema);
// This is the sessions.js
let UserModel = require('../../../models/user.model');
var express = require('express');
var router = express.Router();
router.post('/', (req, res, next) => {
UserModel.findOne(
{
$or: [
{ email : req.body.email }
]
}
)
.then(user => {
if (req.body.password === user.password) {
res.setHeader("Content-Type", "application/json");
res.status(200).send(JSON.stringify({
"api_key": `${user.api_key}`
}));
} else {
res.status(404).send("Incorrect email or password")
}
})
.catch(error => {
res.setHeader("Content-Type", "application/json");
res.status(500).send({error})
})
})
module.exports = router
If I just find user by email, everything works fine. Just need to figure out how to use the compare password method in the user model. Thanks!
So I ended up removing UserSchema.methods.comparePassword = function(candidatePassword, cb) { bcrypt.compare(candidatePassword, this.password, function(err, isMatch) { if (err) return cb(err); cb(null, isMatch); }); }; from the user model and replaced req.body.password === user.password with if (bcrypt.compareSync(req.body.password, user.password)) {
I already suggested that in the answer below like hours ago, if you found it useful, mark it as answer
Maybe have something like this in your model:
User = require('./user-model');
.......
User.findOne({ username: 'jmar777' }, function(err, user) {
if (err) throw err;
user.comparePassword('Password123', function(err, isMatch) {
if (err) throw err;
console.log('Password123:', isMatch); // -> Password123: true
});
........
Other resources:
http://devsmash.com/blog/password-authentication-with-mongoose-and-bcrypt
https://www.abeautifulsite.net/hashing-passwords-with-nodejs-and-bcrypt
<EMAIL_ADDRESS>Hope it helps!
| common-pile/stackexchange_filtered |
Angular: have side effects and return Observable from a method
I have this function:
/**
* Attempt login with provided credentials
* @returns {Observable<number>} the status code of HTTP response
*/
login(username: string, password: string): Observable<number> {
let body = new URLSearchParams();
body.append('grant_type', 'password');
body.append('username', username);
body.append('password', password);
return this.http.post(Constants.LOGIN_URL, body, null)
.do(res => {
if (res.status == 200) {
this.authTokenService.setAuthToken(res.json().auth_token);
}
})
.map(res => res.status)
.catch(err => { return Observable.throw(err.status) });
}
This function attempts to perform login and returns Observable<number> that the caller can use in order to be notified of the HTTP code of the response.
This seems to work, but I have one problem: if the caller just calls the function without subscribing to the returned Observable, do function is not called and the received auth token is not being saved.
Documentation of do states:
Note: this is different to a subscribe on the Observable. If the
Observable returned by do is not subscribed, the side effects
specified by the Observer will never happen. do therefore simply spies
on existing execution, it does not trigger an execution to happen like
subscribe does.
What I'd like to achieve, is to have this side effect regardless of whether the caller of login() subscribed or not. What should I do?
This method returns an observable. What's the point of calling it if you are not going to subscribe to it's response? (you won't be making this request if you don't subscribe)
@echonax, this method is in service. There might be multiple clients - some of them will subscribe, others won't. I don't want the functionality of the service to depend on the semantics of external usage.
you can call subscribe() inside the login() method
As explained by @Maximus, by design, cold Observable (like http call) will not emit any data before you subscribe to them. So your .do() callback will never get called.
Hot Observables on the other hand will emit data without caring if there is a subscriber or not.
You can convert your cold Observable to a ConnectableObservable using the publish() operator. That Observable will start emitting when its connect() method get called.
login(username: string, password: string): Observable < number > {
let body = new URLSearchParams();
body.append('grant_type', 'password');
body.append('username', username);
body.append('password', password);
let request = this.http.post(Constants.LOGIN_URL, body, null)
.do(res => {
if (res.status == 200) {
this.authTokenService.setAuthToken(res.json().auth_token);
}
})
.map(res => res.status)
.catch(err => {
return Observable.throw(err.status)
}).publish();
request.connect();
// type assertion because nobody needs to know it is a ConnectableObservable
return request as Observable < number > ;
}
As @Maximus stated. If the subscription happen after the ajax call as completed, you won't get notified of the result. To handle this case you can use publishReplay(1) instead of simple publish(). PublishReplay(n) will repeat the last n-th elements emitted by the source Observable to new subscribers.
you will have a new request for each call to login
That's not OP's question. (BTW: so does your solution.)
no, my solution doesn't send the request each time. that is why I use the variable sent.
also bear in mind that with publish().connect() all subscriptions to login() will not be notified once the http.get() completes
@n00dl3, this seems to work, but I have one issue. authTokenService.setAuthToken() is always called with undefined argument. Looks like res.json().auth_token doesn't resolve to the actual data I'm receiving. Do you happen to know what the problem is?
@Vasiliy no idea. Are you sure your response has that auth_token property ?
@n00dl3, nop :( Probably some issue with the test driver. Accepting your answer as it seems to work. Thanks
In my answer below I assume that you got used to behavior provided by Promises in previous versions of HTTP in AngularJS:
login(username: string, password: string): Observable<number> {
return this.http.post(Constants.LOGIN_URL, body, null)
.then(res => {
if (res.status == 200) {
this.authTokenService.setAuthToken(res.json().auth_token);
}
})
.then(res => res.status)
.catch(err => { return Observable.throw(err.status) });
The observable returned from this.http.get() call is cold observable. It means that it will not start doing anything unless someone subscribes to it. That is by design. All operators that you chain to the returned observables don't do anything as well since there's no subscription.
You need to subscribe to make a request and then share the result with future subscribers. And I think AsyncSubject is a good candidate here:
sent = false;
s = new AsyncSubject();
login(username: string, password: string): Observable<number> {
if (!this.sent) {
this.http.post(Constants.LOGIN_URL, body, null)
.do(res => {
if (res.status == 200) {
this.authTokenService.setAuthToken(res.json().auth_token);
}
})
.map(res => res.status)
.catch(err => { return Observable.throw(err.status) })
.subscribe(s);
this.sent = true;
}
return s;
}
In this way only one http call will be made and all operators include do will run only once. After that, the returned result will be cached in AsyncSubject and it will pass it along to all future subscribers.
You don't need a subject. Plus your code is wrong. How a constant set to false can become true ?
no idea why the downvote, this really solves his problem. Even though I still have difficulties understanding what the issue is.
@n00dl3, how come I don't need a subject? Why make multiple calls for authentication if one would do? Also you probably realize that I don't put the code exactly as it should be. I write pseudocode where typos are expected things
@PierreDuc, I believe that the OP worked with promises before where if you wrote this.http.get().then(do)... would make request instantly without requiring any subscription to then. This is hot behavior and that is what I think OP expects from the existing http.get()
You still don't need a subject, you can convert to hot observable. Your sent variable will always be false when the method is called so it is useless.
@n00dl3, how can I convert to hot observable? I don't understand why sent will always be false, I change it to true when the call is made. Why don't you provide your solution?
You can convert using publish() and connect(). it will always be false when the method is called as it is not a class property, but a simple variable. Whenever you call that method, sent is false, so what is the point in keeping it ?
so make it a class property, what's the problem? again, I dont post tested solutions, I expect OP to do that
I'm sorry if I offended you, that wasn't my intention. But the problem is your solution is wrong. That little difference makes your solution pointless. You don't know OP's code, you imagine that you can handle the whole session state with a single boolean ? You don't even reset it to false when the request has completed. What if there is another call to login with different parameters ? you will send back the same Observable with old login and password ? If you only talked about AsyncSubject I wouldn't have downvoted.
I was answering having in mind a certain pattern from previous HTTP clients. I added this information to the answer.
| common-pile/stackexchange_filtered |
else statement gets printed every time along with if statement
Here through constructor I'm initialising my private data member based on a if-else logic. Here is my code below -
public BookMyMovie(int movieId, int noOfTickets) {
int arr[]= {101,102,103};
for(int i: arr)
{
if(movieId==i)
{
this.movieId=movieId;
}
else
{
System.out.println("Sorry! Invalid Movie ID!\n"
+ "Please check the Movie ID and enter once again.\n");
}
}
this.noOfTickets = noOfTickets;
}
So, here I'm only taking id's which falls under one of those three id's declared in the array. But everytime it prints the else statement along with the if. Any advice on this?
Your loop runs three times for every invocation, and "it runs the else statement along with the if" does not convey useful information. How are you running this? What happens? What do you expect to happen? What have you tried to resolve the issue?
what are the inputs values you tried passing to BookMyMovie method
A few things from viewing your code. Why are you setting your this.movieId every time in your conditional if statement? In this.movieId=movieId; you should have done a break; afterwards to stop the loop. This is assuming you want to set this.movieId only once. Or, depending on what you want, you just don't set this.movieId at all and leave the conditional with no code inside.
You could return after having found the desired movie and only print the error if none is found.
public BookMyMovie(int movieId, int noOfTickets) {
this.noOfTickets = noOfTickets;
int arr[]= {101,102,103};
for(int i: arr)
{
if(movieId==i)
{
this.movieId=movieId;
return;
}
}
System.out.println("Sorry! Invalid Movie ID!\n"
+ "Please check the Movie ID and enter once again.\n");
}
Let's walk through the execution of the code. Let's say we call this.BookMyMovie(101, 2).
We will iterate through each element of the array.
On the first iteration, we will have i = 101. In this case, we see that movieId == i is true, so we set this.movieID to 101.
On the second iteration, we will have i = 102. In this case, movieID does not equal i, so we enter the else case.
On the third iteration, we will have i = 103, and we again enter the else case.
Finally, we set this.noOfTickets to 2.
If this is not what you want to happen, you need to write different code. For example, you could do something like this:
public BookMyMovie(final int movieId, final int noOfTickets) {
final int[] array = {101, 102, 103};
final int index = Arrays.asList(array).indexOf(movieId);
if (index == -1) {
System.out.println("Sorry! Invalid Movie ID!\n"
+ "Please check the Movie ID and enter once again.\n");
} else {
this.movieId = array[index];
}
this.noOfTickets = noOfTickets;
}
Note that you'll need to import java.util.Arrays for this to work.
You can avoid repeated looping of array elements by using arraylist and checking if movieId exists in list as below
if required, Storing values in list can be moved out of this method
List<Integer> movieNumbers = new ArrayList<Integer>();
movieNumbers.add(101);
movieNumbers.add(102);
movieNumbers.add(103);
if(movieNumbers.contains(movieId)) {
System.out.println("It is valid Movie ID!\n");
}else
{
System.out.println("Sorry! Invalid Movie ID!\n"
+ "Please check the Movie ID and enter once again.\n");
}
| common-pile/stackexchange_filtered |
How to display current music position using FMOD and C++?
I want to display the time that has elapsed as music plays in real-time.
FMOD's Core API provides Channel::getPosition() function to obtain the current position in milliseconds. I want to update the position every second.
I am a beginner and have no knowledge of multithreaded programming.
I call Channel::getPosition() in a loop and use std::this_thread::sleep_for() to delay the loop for one second before the next iteration.
Here is the code:
unsigned int position = 0;
std::chrono::milliseconds timespan(1000);
while(true) {
channel -> getPosition(&position, FMOD_TIMEUNIT_MS);
std::cout << postion / 1000 << "\n"; //Display seconds
std::this_thread::sleep_for(timespan);
}
However, I get some buggy output :
0
1
...
13
13
14
16
...
13 appears twice and 15 does not even appear. In another case, 5 appears twice.
I am thinking of rounding up or rounding down the number I obtain from Channel::getPosition() to correct the output.
How can I fix this?
Note: Error checking is omitted for simplicity
Use <chrono> even for trivial timing functions.
Use the C++17 round function for truncating milliseconds to seconds for this example. If you don't have C++17, steal round from here.
Use sleep_until instead of sleep_for in order to keep a more accurate "timespan" for each iteration of the loop.
Putting that all together:
#include <chrono>
#include <iostream>
#include <memory>
#include <thread>
enum unit{FMOD_TIMEUNIT_MS};
struct Channel
{
void getPosition(unsigned int* position, unit)
{
using namespace std::chrono;
static auto start = steady_clock::now();
*position = duration_cast<milliseconds>(steady_clock::now()-start).count();
}
};
int
main()
{
using namespace std::chrono;
auto channel = std::make_unique<Channel>();
auto constexpr timespan = 1s;
auto next_start = system_clock::now() + timespan;
while (true)
{
unsigned int position_as_integral;
channel->getPosition(&position_as_integral, FMOD_TIMEUNIT_MS);
milliseconds position{position_as_integral};
std::cout << round<seconds>(position).count() << '\n';
std::this_thread::sleep_until(next_start);
next_start += timespan;
}
}
The problem that you have is that position / 1000 rounds down to the nearest integer and std::this_thread::sleep_for is not guaranteed to sleep for exactly the time you specify, and so you might get a duplicate or you might miss one.
Try this instead:
unsigned int position = 0;
std::chrono::milliseconds timespan(100);
unsigned last_sec = 0x7fffffff;
while(true) {
channel -> getPosition(&position, FMOD_TIMEUNIT_MS);
unsigned sec = position / 1000;
if (sec != last_sec)
{
std::cout << sec << "\n"; //Display seconds
last_sec = sec;
}
std::this_thread::sleep_for(timespan);
}
Additionally, playback probably happens in another thread at another "rate" - so there's no precise "wall clock" time synchronization.
At line 3, shouldn't the argument be 1000 instead of 100? Also, whenever we round down, that reading is omitted. Instead, can we print sec + 1 if sec == last_sec or something like that?
No, using 100 is deliberate. Think about it. And if you want to round sec to thd nearest second, do sec = (position + 500) / 1000;
| common-pile/stackexchange_filtered |
What might ChannelReader<T>.ReadAny implementation look like?
BlockingCollection<T> has the handy static TakeFromAny method allowing you to consume multiple collections "I want the next item from any of these collections".
ChannelReader<T> doesn't have an equivalent so if you did want to consume multiple channels into a single stream - say to print received items to Console 1 by 1, how might this be done?
Maybe you may add items to the single BlockingCollection from multiple producers such as Channels and consume it with a single loop.
I would be seeking to use Channel to replace BlockingCollection but the the same idea, of multiple ChannelsReaders feeding another ChannelWriter, which is then consumed by another ChannelReader, could work. It seems pretty clunky though.
The fast path is easy, but the slow path is quite tricky. The implementation below returns a Task<ValueTuple<T, int>> that contains the value taken from one of the readers, and the zero-based index of that reader in the input array.
public static Task<(T Item, int Index)> ReadFromAnyAsync<T>(
params ChannelReader<T>[] channelReaders) =>
ReadFromAnyAsync(channelReaders, CancellationToken.None);
public static async Task<(T Item, int Index)> ReadFromAnyAsync<T>(
ChannelReader<T>[] channelReaders,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Fast path
for (int i = 0; i < channelReaders.Length; i++)
{
if (channelReaders[i].TryRead(out var item)) return (item, i);
}
// Slow path
var locker = new object();
int resultIndex = -1;
T resultItem = default;
while (true)
{
using (var cts = CancellationTokenSource
.CreateLinkedTokenSource(cancellationToken, default))
{
bool availableAny = false;
Task[] tasks = channelReaders
.Select(async (reader, index) =>
{
try
{
bool available = await reader.WaitToReadAsync(cts.Token)
.ConfigureAwait(false);
if (!available) return;
}
catch // Cancellation, or channel completed with exception
{
return;
}
availableAny = true;
lock (locker) // Take from one reader only
{
if (resultIndex == -1 && reader.TryRead(out var item))
{
resultIndex = index;
resultItem = item;
cts.Cancel();
}
}
})
.ToArray();
await Task.WhenAll(tasks).ConfigureAwait(false);
if (resultIndex != -1) return (resultItem, resultIndex);
cancellationToken.ThrowIfCancellationRequested();
if (!availableAny) throw new ChannelClosedException(
"All channels are marked as completed.");
}
}
}
| common-pile/stackexchange_filtered |
Django redirect after GET - MEDIA_URL
All work fine for the moment. For example, an url with an image name encoded base64, is redirected correctly :
with GET operation "https://myurl/v1/images/c3VwZXJpbWFnZS5qcGc=/contenu" there is a 302 status code and the navigator send the image with 200 status code with the url "https:myurl/api/mediafiles/superimage.jpg"
This is a part of my urls.py :
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(router_v1.urls)),
path('myurl/v1/images/<str:nom_image>/contenu', v1.myRedirectView.as_view(), name='image_redirect'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and the correspondig views.py :
class myRedirectView(View):
def get(self, request, *args, **kwargs):
nom_image = kwargs['nom_image']
nom_image = nom_image.encode('utf-8')
nom_image = base64.urlsafe_b64decode(nom_image).decode()
url = '/api/mediafiles/' + nom_image
return HttpResponseRedirect(url)
Now, i would like to find a solution to hide the url (GET) "https:myurl/api/mediafiles/superimage.jpg"
What is the best way ?
Second redirect (i try but doesn't work)
Work with my webserver nginx ?
DjangoRest is not the solution to serve images with API REST ?
Thank's !
update my post, the solution to work in my development environment is to execute the redirection through Nginx :
location ~ ^/myurl/v1/images/(.*)$ {
proxy_pass https://<IP_ADDRESS>/api/mediafiles/fastorchidee/$1;
}
The regex have to be modified, but it works for the moment !
| common-pile/stackexchange_filtered |
Splitting string causing Value of type 'Any?' has no member 'components'
I have a function using webview IOS with swift 4. I am trying to explode result, but I am getting Value of type 'Any?' has no member 'components' and I have no idea how to fix this. I am new to swift.
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.webView.evaluateJavaScript("document.getElementById('user_id').innerText") { (result, error) in
if result != nil {
let items = result.components(separatedBy: "|")
self.ref?.child("people").child(result as! String).setValue(["device_token": self.deviceTokenStringfinal])
}
}
}
Because result can be anything: a string, a number, an array, a JSON object... depending on what your Javascript returns. Swift has no way of knowing that at compile time so it marks result as Any.
You must do a cast at runtime:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.webView.evaluateJavaScript("document.getElementById('user_id').innerText") { (result, error) in
guard let result = result as? String else { return }
let items = result.components(separatedBy: "|")
self.ref?.child("people").child(result).setValue(["device_token": self.deviceTokenStringfinal])
}
}
| common-pile/stackexchange_filtered |
pandas create quantiles for a column based weighted by another column
I have a df like
df= pd.DataFrame({'v': [100, 300, 200, 900, 100, 400, 300, 300, 800, 1100], 's':[1.1, 2.7, 0.87, 1.6, 3.2, 0.2, 1.1, 0.3, 1.2, 1.3]})
s v
0 1.10 100
1 2.70 300
2 0.87 200
3 1.60 900
4 3.20 100
5 0.20 400
6 1.10 300
7 0.30 300
8 1.20 800
9 1.30 1100
I want to get the quantiles almost similar to
pd.qcut(df["s"], 3,labels=[-1, 0, 1])
but instead of having each bin contain an equal number of entries, I would like to create bins such that the sum of v for each category is equal.
Something like
df= pd.DataFrame({'v': [100, 300, 200, 900, 100, 400, 300, 300, 800, 1100], 's':[1.1, 2.7, 0.87, 1.6, 3.2, 0.2, 1.1, 0.3, 1.2, 1.3] ,\
'c': [-1, 1, -1, 1, 1, -1, -1, -1, 0, 0]})
c s v
0 -1 1.10 100
1 1 2.70 300
2 -1 0.87 200
3 1 1.60 900
4 1 3.20 100
5 -1 0.20 400
6 -1 1.10 300
7 -1 0.30 300
8 0 1.20 800
9 0 1.30 1100
Interpolation doesn't matter much as the actual set is quite large.
I can achieve this by sorting for s, doing a cumsum on v and then setting values based on comparing the cumsum to the total sum. But I am wondering if there is any approach using some pandas magic
This solution is quite awful if you have a large dataframe, but here something different and simpler from your solution (which is nice):
pd.qcut(np.concatenate([[s]*v for s,v in zip(df.s, df.v)]), 3, labels=[-1,0,1])
You may check before with cumsum on v if your computer is going to explode before...
Thanks, interesting solution. But yea, that numpy will blow up with the actual data
| common-pile/stackexchange_filtered |
Remember me login - Asp script
hello
i have to create a "remeber me login" asp script, have read many scripts about this procedure and have see that many people use to store username and password inside a cookie.
In my opinion it is not secure (safety), some advice
Why wouldn't this be safe using proper encryption?
It's best practice NOT to store usernames and passwords in client side cookies. Store some kind of opaque reference instead that matches something in your server side authentication database.
Even better still encrypt this value before storing it in a cookie.
so i have to create a field on DB then compare this value with cookie if it matches is ok
Something like, try something like a GUID.
You don't need to store the password. You only need the username and if you make sure that it is properly encrypted it is OK to save it in a cookie. It is important for the user to not be able tamper with the value and if he does the server should detect it. SHA1 for HMAC generation and AES for encryption are commonly used algorithms.
Including the username increases the risk, storing a cookie with an encrypted not easily identifiable piece of information like a GUID associated with the user record in the database is best.
public partial class Login : System.Web.UI.Page
{
StudentService.Service1Client studentCleint = new StudentService.Service1Client();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
lbnLogin.Text = studentCleint.login(txtusername.Text, txtPassword.Text);
if (lbnLogin.Text == "Succesful")
{
Response.Redirect("Students.aspx");
}
else
{
lbnLogin.Text = "failed";
}
}
}
how does that answer help in any way to the original question?
This isn't even [tag:asp-classic] so has no place in this question, thats before you consider the fact its completely ambiguous without any explanation.
| common-pile/stackexchange_filtered |
How can I use OpenLayers3 to put an icon on a selected point of interest in my map?
I am absolutly new in OpenLayers 3 and I have create the following page that use it and that show an Open Street map in which when the user click on a point it retrieve the GPS coordinates of this point:
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="http://openlayers.org/en/v3.12.1/css/ol.css" type="text/css">
<style>
.map {
height: 400px;
width: 100%;
}
</style>
<script src="http://openlayers.org/en/v3.12.1/build/ol.js" type="text/javascript"></script>
<title>OpenLayers 3 example</title>
</head>
<body>
<h2>My Map</h2>
<div id="map" class="map"></div> <!-- Map Container -->
<!-- JavaScript to create a simple map, With this JavaScript code, a map object is created with a MapQuest Open Aerial layer
zoomed on the African East coast: -->
<script type="text/javascript">
var rome = ol.proj.fromLonLat([12.5, 41.9]);
var map = new ol.Map({ // Creates an OpenLayers Map object
target: 'map', // Attach the map object to the <div> having id='map0
// The layers: [ ... ] array is used to define the list of layers available in the map. The first and only layer right now is a tiled layer:
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
// The view allow to specify the center, resolution, and rotation of the map:
view: new ol.View({
// The simplest way to define a view is to define a center point and a zoom level. Note that zoom level 0 is zoomed out:
center: ol.proj.fromLonLat([12.5, 41.9]),
zoom: 10
})
});
map.on('click', function(evt) {
var prettyCoord = ol.coordinate.toStringHDMS(ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326'), 2);
alert("COORDINATE: " + prettyCoord);
});
</script>
</body>
</html>
So, as you can see in my code, it is pretty simple I have use this function to retrieve the GPS coordinates:
map.on('click', function(evt) {
var prettyCoord = ol.coordinate.toStringHDMS(ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326'), 2);
alert("COORDINATE: " + prettyCoord);
});
My problem now is: how can I put something like a pointer icon on the selected point in the map? I want put an icon like the one shown in this tutorial: http://openlayers.org/en/v3.13.0/examples/icon-negative.html
but that have to be shown in the selected point.
I want to do something like give to the user the possibility to select a point of interest on my map but I can't find a solution. How can I do it?
EDIT 1: this is the JSFiddle on my example: https://jsfiddle.net/AndreaNobili/uqcyudex/1/
That depends. If you want the point to be at the exact center of a point in the map you would require a way to get the coordinate of that point first, though a WMS server, for example. If you just want to put a marker where the user clicked, that should be easy. If you could create a JSFiddle out of your example I'd be willing in showing you how it could be done.
@AlexandreDubé At the end of my original post I have added a JSFiddle of the example on which I am working on.
So as you can see in the JSFiddle, clicking on a point of the map, an alert message showing the coordinates of the clicked point is retrieved, it show something like: "COORDINATE: 41° 54′ 46″ N 12° 20′ 30″ E" that I think represent the GPS coordinates of the clicked point. What I need is simply add something like a "vector icon" on the clicked point to hightlight it.
Here, I have asked a similar question, http://stackoverflow.com/questions/34731134/display-markers-popups-whit-openlayer3/34769351#34769351, you have a working jsfiddle example as an anwer to the question
Here is a working example http://jsfiddle.net/copser/0zpm9mws/5/, I'm displaying markers on openstreetmap using openlayes3
You can create a vector layer to add to you map to which you configure with a vector source. Upon clicking on the map, you can clear the source first, then add a feature to the source, which gets rendered in the map.
See your updated JSFiddle: https://jsfiddle.net/uqcyudex/5/
var vectorSource = new ol.source.Vector();
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
...
// add it to the map
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vectorLayer
],
...
// clear the source and add the feature
vectorSource.clear();
var feature = new ol.Feature(new ol.geom.Point(evt.coordinate));
vectorSource.addFeatures([feature]);
To have the vector feature styled as a marker, look at this example to see how it's done: http://openlayers.org/en/v3.13.0/examples/icon.html
| common-pile/stackexchange_filtered |
when i scroll down the window it is not removing or adding the active class
I am not able to use the classList.remove('active')when scroll down despite my code is same as shown in the tutorial i am following
also when i click #search-btn it is not removing the active class from navbar
let searchForm = document.querySelector('.search-form');
document.querySelector('#search-btn').onclick = () => {
searchForm.classList.toggle('active');
navbar.classList.remove('active');
}
let navbar = document.querySelector('.nav_bar');
document.querySelector('#menu-btn').onclick = () => {
navbar.classList.toggle('active');
searchForm.classList.remove('active');
}
window.onscroll = () => {
searchForm.classList.remove('active');
navbar.classList.remove('active');
{
if (window.scrollY > 0) {
document.querySelector('.header').classList.add('active');
} else {
document.querySelector('.header').classList.remove('active');
}
}
}
I am not able to use the classList.remove('active')when scroll down despite my code is same as shown in the tutorial i am following
also when i click #search-btn it is not removing the active class from navbar
the html code i use contain nav_bar class in nav and search-form class in form in these classes i am not able to add .active class by using queryselector
<nav class="nav_bar">
<a href="#home">home</a>
<a href="#offers">offers</a>
<a href="#destinations">destinations</a>
<a href="#packages">packages</a>
<a href="#contact">contact</a>
</nav>
<div class="icons">
<div id="menu-btn" class="fas fa-solid fa-bars"></div>
<div id="search-btn" class="fas fa-solid fa-search"></div>
<div class="fas fa-solid fa-shopping-cart"></div>
<div class="fas fa-solid fa-user"></div>
</div>
<form action="" class="search-form">
<input type="search" placeholder="search here ...."
id="input-
box">
<label for="input-box" class="fas fa-search"></label>
</form>
</header>
Please add the minimum HTML necessary so we can see the problem.
You have a problem with this:
if (window.screenY > 0) {
document.querySelectorAll('.header').classList.add('active');
} else {
document.querySelectorAll('.header').classList.remove('active');
}
querySelectorAll returns a collection of all the elements with class header.
If you know you only have one such element then you can use document.querySelector('.header') as this selects the first one it comes across.
However, if you have several and you want to select them all you need to go through each one in the collection, for example using:
document.querySelectorAll('.header').forEach
Using your browser's dev tools inspection facility you will see that your code gives an error because it was trying to find the classList of a null element given querySelectorAll returns a collection not a single element.
thanks for helping i resolved the issue
First of all I need more context (html) to know why your button clicking is not working correctly. Nonetheless I can give you an answer why the scrolling part doesnt work.
First you need to change if (window.screenY > 0) to window.scrollY > 0 to get the actual position of the scrolling.
Then change document.querySelectorAll('.header') to document.querySelector('.header') because querySelectorAll gives you a list of nodes wich you would have to change all separately to achieve your goal.
As I said, if you give me more context I can look in to your second problem as well.
thanks for helping i resolved the issue
Nice! You found the problem with you button clicking as well?
yes, it was a silly mistake
| common-pile/stackexchange_filtered |
Retrieving result from celery worker constantly
I have an web app in which I am trying to use celery to load background tasks from a database. I am currently loading the database upon request, but would like to load the tasks on an hourly interval and have them work in the background. I am using flask and am coding in python.I have redis running as well.
So far using celery I have gotten the worker to process the task and the beat to send the tasks to the worker on an interval. But I want to retrieve the results[a dataframe or query] from the worker and if the result is not ready then it should load the previous result of the worker.
Any ideas on how to do this?
Edit
I am retrieving the results from a database using sqlalchemy and I am rendering the results in a webpage. I have my homepage which has all the various links which all lead to different graphs which I want to be loaded in the background so the user does not have to wait long loading times.
can you please explain what you mean by "load background tasks from a database"? or "loading the database"? it would help to provide the best approach to solve your needs. Generally, you dont get result from worker, worker is executing tasks and store the results in the backend... so from your terminology it is a bit hard to tell what you should do.
@creativeChips do you retrieve the results from redis server?
I personally got mongo as backend, and I indeed query for the results directly from the mongo collection, when needed.
I took a chance hoping I get your usecase, and posted an answer ...
The Celery Task is being executed by a Worker, and it's Result is being stored in the Celery Backend.
If I get you correctly, then I think you got few options:
Ignore the result of the graph-loading-task, store what ever you need, as a side effect of the task, in your database. When needed, query for the most recent result in that database. If the DB is Redis, you may find ZADD and ZRANGE suitable. This way you'll get the new if available, or the previous if not.
You can look for the result of a task if you provide it's id. You can do this when you want to find out the status, something like (where celery is the Celery app): result = celery.AsyncResult(<the task id>)
Use callback to update farther when new result is ready.
Let a background thread wait for the AsyncResult, or native_join, which is supported with Redis, and update accordingly (not recommended)
I personally used option #1 in similar cases (using MongoDB) and found it to be very maintainable and flexible. But possibly, due the nature of your UI, option #3 will more suitable for you needs.
| common-pile/stackexchange_filtered |
When is the right time to inquire about the status of my manuscript after second round of revisions?
After resubmitting my manuscript following revisions for the second time, when should I contact the journal? Here is a timeline of the process thus far:
First submission: March 2023
Request for major revisions: June 2023
Resubmission after revisions: August 2023
The manuscript then underwent a second round of review.
Email regarding the status of the manuscript: January 2024
Request for minor revisions: February 2024
Resubmission after revisions: February 2024
Current manuscript status: With editor
I'm uncertain about when to inquire about the status of my paper. I realise this might seem hasty, but as I'm pursuing my PhD by publication and planning to defend next year, I need my papers published or at least accepted before then. I don't mind if the editor rejects it, but given how lengthy the review/publication process can be, it would be helpful to know sooner so I can submit my paper to another journal.
What is the usual time-frame for papers in your field? How long is the paper? What your describes seems very fast for a 60-page pure-math paper, a bit slow for a five-page physics paper.
I think you can wait and I also think you will hear soon-ish if it is "with editor" after minor revisions. The history suggests acceptance. You also have about a year and the paper has, I assume, been improved.
Don't give up on other possible submissions of related work, however, so that you have some backup.
But if it has been two months since your last communication you could make a polite request for a status update. But Feb-April could be just one month and a bit depending on dates.
Note also that a request for status update isn't going to speed the process and withdrawal will certainly slow it.
Thank you for your response! Yes, the paper has significantly improved. It's been one month since I resubmitted. I'll wait another month or so.
| common-pile/stackexchange_filtered |
My own created function: RemoveNA runs half
Here is my code :
PATH <-
"https://raw.githubusercontent.com/thomaspernet/data_csv_r/master/data/titanic_csv.csv"
df_titanic <- read.csv(PATH, sep = ",")
RemoveNA =
function(x)
{
colmiss = colnames(x)[apply(x,2,anyNA)]
colmiss
i = 1
while ( i <= length(colmiss))
{
col_na_col = match(colsmiss[i],names(x))
col_na_col
for (n in col_na_col)
{
#column_name = colsmiss[i]
cat(' Your missing column is: ' ,'"',colsmiss[i],'"',' and col.no is : ',n, '||||')
# Create mean
average_missing <- mean(x[,colsmiss[i]],na.rm =TRUE)
average_missing
x[n][is.na(x[n])] = average_missing
}
i = i + 1
}
}
sum(is.na(df_titanic))
RemoveNA(df_titanic)
When I run the function RemoveNA, it gives :
Your missing column is: " age " and col.no is : 6 |||| Your missing column is: " fare " and col.no is : 10 ||||
which is okay, but the replacement below is not done properly, as sum(is.na(df_titanic)) both before and after sums upto 264
Here's a more straightforward way :
df1 <- data.frame(a= c(NA,1,NA,2), b = 1:4)
df1[] <- lapply(df1, function(x) replace(x,is.na(x),mean(x,na.rm=TRUE)))
df1
# a b
# 1 1.5 1
# 2 1.0 2
# 3 1.5 3
# 4 2.0 4
Your code has a type, you typed colsmiss instead of colmiss.
Also your code doesn't return anything (well it returns the last value of I), so your transformation of the NA values is not recorded anywhere.
Your corrected function :
RemoveNA = function(x)
{
colmiss = colnames(x)[apply(x,2,anyNA)]
colmiss
i = 1
while ( i <= length(colmiss))
{
col_na_col = match(colmiss[i],names(x))
col_na_col
for (n in col_na_col)
{
#column_name = colsmiss[i]
cat(' Your missing column is: ' ,'"',colmiss[i],'"',' and col.no is : ',n, '||||')
# Create mean
average_missing <- mean(x[,colmiss[i]],na.rm =TRUE)
average_missing
x[n][is.na(x[n])] = average_missing
}
i = i + 1
}
x
}
| common-pile/stackexchange_filtered |
How can I maintain a permanent shade lawn?
My Fescue Grass does fine here in my shady South Carolina yard. However, it needs to be re-seeded every year or it gets bare patches. Are there any alternatives that do not involve buying more seed every year (besides chopping down my trees and planting a sunny grass or naturalizing the area)?
There is a type of fescue called RTF (Rhizomatous Tall Fescue) which I think works better than most common types of fescue. It has the ability to send out runners underground that will fill in bare patches over time. I've had it for a couple of years in my front yard and have been very happy with it.
| common-pile/stackexchange_filtered |
trouble installing MozRepl
I've been trying to install WWW::Mechanize::Firefox through CPAN and I am having trouble installing the dependency MozRepl. The installation goes through but the tests all fail, and when I force install it and run my perl script, I run into an error
Failed to connect to , at /Library/Perl/5.12/MozRepl/RemoteObject.pm line 467.
SO I uninstalled MozRepl and looked at the tests I get the following errors in the log:
# Failed test at t/10-plugin-repl-enter.t line 11.
Can't locate object method "repl_enter" via package "MozRepl" at t/10-plugin-repl-enter.t line 12.
...
# Failed test at t/20-plugin-json.t line 16.
Can't locate object method "json" via package "MozRepl" at t/20-plugin-json.t line 17.
# Failed test at t/19-plugin-repl-util-doc_for.t line 14.
Can't locate object method "repl_doc_for" via package "MozRepl" at t/19-plugin-repl-util-doc_for.t line 16.
# Failed test at t/18-plugin-repl-util-help_url_for.t line 14.
Can't locate object method "repl_help_url" via package "MozRepl" at t/18-plugin-repl-util-help_url_for.t line 16.
etc..
I am running on Mac OSX 10.8.4, 4 GB Ram 2.5 Ghz, Perl version 5.12. Does anybody have any idea what is causing these errors?
UPDATE:
i reinstalled mozrepl, and now I get this error when i run my script:
Failed to connect to , problem connecting to "localhost", port 4242: Connection refused at /Users/thui/perl5/perlbrew/perls/perl-5.16.0/lib/site_perl/5.16.0/MozRepl/Client.pm line 144
Do you use cpanm? If not it could help you with dependencies versions.
I'm not sure, but you might need an older version of MozRepl (the firefox addon). I think there have been breaking changes in the API that haven't made it to MozRepl (the perl Package).
I just installed the MozRepl addon on firefox to no avail. And yes I am using cpanm. I just upgraded my version of Perl to 5.16 to no avail as well.
I've created an answer with a working recipe below. I installed Debian 7 on a new VM, installed Firefox, installed CPANminus via cpan, then followed the recipe.
Didn't see your update there. If it says problem connecting to "localhost", port 4242: Connection refused that means that MozRepl (the Firefox addon) isn't running IN FIREFOX. See the instructions in my answer for how to properly install and configure MozRepl (the Firefox addon).
This works for me with perl 5.10 or later, latest Firefox (26 as of writing) and Mozrepl from github.
At command propmpt:
(1) Download MozRepl and build the XPI file (Firefox extension):
git clone git://github.com/bard/mozrepl
cd mozrepl
zip -r ../mozrepl.zip *
cd ..
mv mozrepl.zip mozrepl.xpi
(2) Install the extension in Firefox via about:addons [Install from file].
In Firefox:
(3) Menu->Tools->Mozrepl->Activate On Startup
(4) Menu->Tools->Mozrepl->Start
At command propmpt:
(5) which firefox
Make sure the firefox executable (or your OS's wrapper script) is in $PATH - you should get some output!
(6) cpanm WWW::Mechanize::Firefox
(7) Test it!
At this point, if CPANminus reports no errors then WWW::Mechanize::Firefox should be working. The first example from the synopsis is a good test:
#!/usr/bin/perl
use WWW::Mechanize::Firefox;
my $mech = WWW::Mechanize::Firefox->new();
$mech->get('http://google.com');
That assumes MozRepl is listening on port 4242 (check in Menu->Tools->Mozrepl->Change Port). You can also change the port from the perl side; see options for ->new().
(8) cpanm HTML::Display::Common
I found that bcat.pl from the examples required this module, but it wasn't installed as a dependency.
hello - i need to re-work your recipe for the OpenSuse version 13.1. I try to install Mecha :: FireFox for a long long time now. All fails.
| common-pile/stackexchange_filtered |
Keeps printing null
This code is supposed to read one text file of multiple grocery lists and then split them up into an arraylist of separate grocery lists. Then it should split each element of the arraylist (each individual grocery list) into a new arraylist by line. So it's almost like an array list within an arraylist. Does this code work for that? When I try to get the array using the getArray method in my main method and then I print the array but it keeps printing null. What's up?
public class Grocery{
Scanner input;
String listLine;
String line;
ArrayList<String> grocery = new ArrayList<String>();
String groceryString;
//ArrayList<String> newString = new ArrayList<String>();
String store;
String brand;
String serialNumber;
String[] newString;
public Grocery()throws IOException{
File inFile = new File ("groceryList.txt");
input = new Scanner (inFile);
String grocery;
while (input.hasNext())
{
grocery = input.nextLine();
}
}
public void makeLists(){
while(input.hasNextLine()){
line = input.nextLine();
if(line.equals("<END>")){
grocery.add(groceryLine);
}
else{
groceryLine = groceryLine + "\n" + line;
}
}
}
public String[] getArray(){
for(int i=0; i<grocery.size(); i++){
groceryString = grocery.get(i);
newString =groceryString.split("\n");
// store = newString[1];
// brand = newString[4];
// serialNumber = newString[5];
}
return newString;
}
}
^
Array types don't have an add() method.
Shouldn't it be throwing an exception instead of allowing it to run if the method doesn't exist?
@Keikoku It shouldn't even get that far; the code shouldn't even compile.
newString is a String array and not an Arraylist. It does not contain the add() method. You just need to directly assign the resultant String[] to it which is returned from the String#split() method.
newString = emailString.split("\n");
The add method you are using is a method in the ArrayList class. It doesn't exist in an array.
| common-pile/stackexchange_filtered |
PyQt cross-platform way of communicating between running applications
Hey guys/ladies of python mastery, need some help.
I'm using PyQt to create some integrated ui elements for an application written in python (appA) that runs on windows/linux/osx, I need those elements to be able to communicate with a PyQt app (appB) I have written that runs separately (same host).
What would be the best (cross-platform) approach to creating a communication link between the integrated ui elements in one app and the standalone app i have written?
I want to be able to send/receive messages from appA to appB...
For example appA launches, integrated ui elements load in a form of an input field with a 'Send' button. Upon entering data and hitting 'Send' a test is performed to check if appB is running/needs to be launched, after appB launches, data arrives at appB and appB sends a confirmation of delivery back to appA and vice versa. This needs to work with least delay and hackery on windows/linux/osx.
I was looking at DBus but that looks a little buggy for WIN, win32api is good for WIN but useless elsewhere, maybe there is a magic bullet to these things.
Any links to tutorials/sites/docs would be great or if u have some ready code :) ! whatever , thanks in advance...
If you don't want to use raw sockets, you should try zmq (zeromq). You can find a good introduction to zmq here
Thanks Viktor, This is very helpful. I'm going to shortlist zmq as a method. I really like the promised speed and ability to scale, maybe I can couple this with Google Protobuf
You can send over zmq connection whatever you want.
| common-pile/stackexchange_filtered |
Geographic Synonyms
Let's say I have a table representing principal country divisions (ex States):
create table principal_country_divisions (
id int primary key,
name text not null,
country_code char(2)
);
insert into principal_country_divisions values (1, 'New York', 'US');
I want users to be easily able to find New York via synonyms such as 'New York', 'NY', or 'New York State'.
So I have a synonyms table:
create table synonyms (
syn text,
name text,
primary key (syn, name)
);
insert into synonyms values
('NY', 'New York'),
('New York State', 'New York');
What is an efficient and easy way to query this and return ONE record for New York?
In particular, they should be able to find the result for the default name 'New York' OR any synonym:
select * from principal_country_divisions where name = 'NY';
result: {1, 'New York', 'US'}
I guess I would start with something like this:
select
id,
name,
country_code
from principal_country_divisions a
where name = 'NY'
or exists (select 1 from synonyms where name = a.name and syn = 'NY')
Can I do this only using a view, or should I use a function?
First of all, you have an integer primary key on principal_country_divisions. Use it. More efficient than joining via name for multiple reasons (storage size, index size, faster integer arithmetic, no collations involved, fixed length).
create table principal_country_divisions (
country_id int primary key
,name text not null
,country_code char(2)
);
create table synonyms (
country_id int REFERENCES principal_country_divisions (country_id)
,syn text
,primary key (syn, country_id)
);
syn needs to the the first column of the index (pk), you had that right already. The accompanying index automatically covers equality tests on synonyms.syn.
Be sure to add an index on principal_country_divisions.name:
CREATE INDEX foo ON principal_country_divisions (name);
If you'd want to match patterns, not whole strings, the job would become more complex.
Next, how can you be sure to
return ONE record for New York?
Obviously, name and syn can be the same. There is no unique constraint over both columns and there isn't even one on syn alone. Otherwise your EXISTS query is a good approach - usually fast. You'd just have to avoid multiple rows. The added benefit of EXISTS would be to eliminate duplicates from synonyms alone, but that's ruled out by the pk. This may be faster for the case:
SELECT DISTINCT ON (1)
a.country_id, a.name, a.country_code
FROM principal_country_divisions a
LEFT JOIN synonyms s USING (country_id)
WHERE a.name = 'NY'
OR s.syn = 'NY'
-- ORDER BY 1, <more expressions to pick from peers>
As you commented, a LEFT JOIN is in order to preserve finds in name.
In case of multiple finds, you can chose what to pick by adding more ORDER BY expressions. Leading columns have to agree with DISTINCT ON, though. Details in this related answer on SO.
Thanks Erwin. Looks like your last query won't work if a country doesn't have a synonym. A left join seems to fix it.
@NeilMcGuigan: Exactly, that was an oversight on my part. Fixed and added a bit more.
| common-pile/stackexchange_filtered |
How to validate Contact Form 7 Submit
I'm trying to send events to GA when a form is submitted, but while testing it, I've found that the wpcf7submit will send an event even if some required fields weren't fulfilled.
"wpcf7submit — Fires when an Ajax form submission has completed successfully, regardless of other incidents."
I've tested it with alerts and whenever I don't fill all the required fields I still get the alert
var wpcf7Elm = document.querySelector( '.wpcf7' );
wpcf7Elm.addEventListener( 'wpcf7submit', function( event ) {
alert( "Fire!" );
}, false );
var wpcf7Elm = document.querySelector('.wpcf7');
wpcf7Elm.addEventListener('wpcf7submit', function (event) {
ga('send', 'event', 'Lead Form', 'submit');
}, false);
You may want to try the wpcf7mailsent event if you're only interested in successes.
var wpcf7Elm = document.querySelector('.wpcf7');
wpcf7Elm.addEventListener('wpcf7mailsent', function (event) {
ga('send', 'event', 'Lead Form', 'submit');
}, false);
wpcf7mailsent — Fires when an Ajax form submission has completed successfully, and mail has been sent.
Note, this doesn't work with the skip mail setting enabled.
| common-pile/stackexchange_filtered |
How do I loop through a column and check if the value matches the next value then append?
I am attempting to loop through a column. If the the item in the column matches the next item in the column. If they are the same, I will take values associated with the first row item and append it with stuff from the lines below.
I have tried using nested if loops to loop through a column. Ignore some of the functionality my code, but I am not sure why my comparisons are not working.
For bigLoop = 1 To Length + 1
firstString = Workbooks("VBA_Basics.xlsm").Worksheets("TestSheet").Cells(bigLoop, 24).Value
Cells(bigLoop, 28).Value = Cells(bigLoop, 26)
Debug.Print firstString
For smallLoop = 1 To Length + 1
secondString = Workbooks("VBA_Basics.xlsm").Worksheets("TestSheet").Cells(smallLoop + 1, 4).Value
Debug.Print secondString
myComp = StrComp(firstString, secondString, vbBinaryCompare)
If myComp = 0 Then
Cells(bigLoop, 28).Value = Cells(bigLoop, 26).Value & " :) " & Cells(smallLoop + 1, 26).Value
End If
Debug.Print myComp
Next smallLoop
Next bigLoop
You have a mixture of explicit worksheet references and implicit ActiveSheet references. It might be that you are not comparing the cells you think you are.
Please sort your column! Then try this:
Option Explicit
Option Base 1
Private Const NITEMS As Integer = 11
' Column "A"
Private Const COLUMN As Integer = 1
' Column "B"
Private Const TARGET_COLUMN As Integer = 2
' Please sort your column!
Public Sub X()
Dim I As Integer
Dim J As Integer
Dim V1 As Variant
Dim V2 As Variant
I = 1
While I <= NITEMS
V1 = ActiveSheet.Cells(I, COLUMN).Value
ActiveSheet.Cells(I, TARGET_COLUMN).Value = V1
J = I + 1
V2 = ActiveSheet.Cells(J, COLUMN).Value
While V1 = V2 And J <= NITEMS
ActiveSheet.Cells(I, TARGET_COLUMN).Value = _
ActiveSheet.Cells(I, TARGET_COLUMN).Value & " :) " & V2
J = J + 1
V2 = ActiveSheet.Cells(J, COLUMN).Value
Wend
I = J
Wend
End Sub
| common-pile/stackexchange_filtered |
Is the construction "a/an X so Y" correct?
I often see this construction: "Who had spread such a horrible rumor?" Or "He told her a rumor so horrible, she gasped."
How about this construction: "Who had spread a rumor so horrible."?
Note: I could have written "Who had spread such a horrible rumor?" But I wanted horrible to go at the end of the sentence.
The common usage of this form is as part of a "so X that Y" construction, which may already be familiar to you:
Who would spread a rumor so horrible that it would force her to go into hiding?
This is also just a rewording of your first construction:
Who would spread so horrible a rumor that ...
However, it can be used by itself, although this still implies some unmentioned (or unmentionable) consequence. Because of this it can feel somewhat dramatic, even melodramatic:
"Who would spread a rumor so horrible!" the old duchess cried, throwing her arm across her face in distress.
| common-pile/stackexchange_filtered |
New to Android Dev - Problem installing SECOND App/APK
I am writing some test Android apps using Eclipse. I created my 1st project, a simple hello app, built the apk (app1.apk), and was able to install and run that on an Android tablet.
I then created a new project in eclipse, for a 2nd app. I exported the apk (app2.apk). But, when I try to install this 2nd apk (app2.apk) on the tablet, it warns me that it wants to REPLACE the 1st app.
When I built the apks, I used a different key for app1 vs. app2, and the project and class names are different, so what is it that the Android installer is using that makes it think that both apks are the same app?
Thanks,
Jim
It sounds like you are using the same package name in both apps.
Yup. You can use the same signing key, the same Java package names, the same sharedUserId, the same application name (and so on, and so on), but the package name in the manifest must be different for each app.
Christopher (and mbaird), You're correct that the packagename in the Java code was the same in both apps. But can you clarify what you said about the package name in the manifest being different? Doesn't the package name in the manifest have to match the package statement in the Java code? Jim
Yes it has to match the package in the Java code. Thus you have to use a different package name for each app (in the code and the manifest)
| common-pile/stackexchange_filtered |
Create a file throught code in Kubernetes
I need (or at least I think I need) to create a file (could be a temp file but for now it does not work while I was testing it) where I can copy a file stored in google cloud storage.
This file is a geojson file and after load the file i will read it using geopandas.
The code will be run it inside a Kubernete in Google Cloud
The code:
def geoalarm(self,input):
from shapely.geometry import Point
import uuid
from google.cloud import storage
import geopandas as gpd
fp = open("XXX.geojson", "w+")
storage_client = storage.Client()
bucket = storage_client.get_bucket('YYY')
blob = bucket.get_blob('ZZZ.geojson')
blob.download_to_file(fp)
fp.seek(0)
PAIS = gpd.read_file(fp.name)
(dictionaryframe,_)=input
try:
place = Point((float(dictionaryframe["lon"])/100000), (float(dictionaryframe["lat"]) / 100000))
<...>
The questions are:
How could I create the file in kubernetes?
Or, how could I use the content of the file as string (if I use download_as_string) in geopandas to do the equivalent of geopanda.read_file(name)?
Extra
I tried using:
PAIS = gpd.read_file("gs://bucket/xxx.geojson")
But I have the following error:
DriverError: '/vsigs/bucket/xxx.geojson' does not exist in the file system, and is not recognized as a supported dataset name.
A solution to avoid to create a file in kubernetes:
storage_client = storage.Client()
bucket = storage_client.get_bucket('buckte')
blob = bucket.get_blob('file.geojson')
string = blob.download_as_string()
PAIS = gpd.GeoDataFrame.from_features(json.loads(string))
A VERY general overview of the pattern:
You can start by putting the code on a git repository. On Kubernetes, create a deployment/pod with the ubuntu image and make sure you install python, your python dependencies and pull your code in an initialization script, with the final line invoking python to run your code. In the "command" attribute of your pod template, you should use /bin/bash to run your script. Assuming you have the correct credentials, you will be able to grab the file from Google Storage and process it. To debug, you can attach to the running container using "kubectl exec".
Hope this helps!
| common-pile/stackexchange_filtered |
Microsoft Bot: Show options from database instead of enums
In the example bot implementations from Microsoft, they use enums to define options for dialog, as shown in the example below:
public enum LengthOptions { SixInch, FootLong };
public enum BreadOptions { NineGrainWheat, NineGrainHoneyOat, Italian, ItalianHerbsAndCheese, Flatbread };
Can we use a normal list to fetch the values from the database and display it as options?
Thanks
You can't do this out of the box, but you could subclass FormBuilderBase<T>, overriding various methods to build the Form using whatever datasource you prefer.
Edit:
You can find the base class and implementation of FormBuilder here: https://github.com/Microsoft/BotBuilder/blob/master/CSharp/Library/FormFlow/FormBuilder.cs
Basically, there are a mess of virtual methods that you can override to customize how you want to form to behave, but the main one is Build. In the default implementation, it iterates though the enums to create a list of Field, which are basically each step in you form. Instead of that, you can iterate through whatever data you have pulled from your database and create a new Field for each item. It may look something like this:
public override IForm<T> Build(Assembly resourceAssembly = null, string resourceName = null)
{
var list = GetListOfItemsFromDatabase();
foreach (var item in _list)
{
// FieldFromItem is an IField and will also need to be created
Field(new FieldFormItem<T>(item));
}
Confirm(new PromptAttribute(_form.Configuration.Template(TemplateUsage.Confirmation)));
}
return base.Build(resourceAssembly, resourceName);
}
Thanks, can you give some more elaborate examples
I know its late but found myself struggling with the same and found that below would be the right solution for this.In your FormFlow class just add the Terms and Descriptions manually.From your example if we are talking about length options then change the type of LengthOptions to string add following code when you build the form.
return new FormBuilder<SandwichForm>()
.Field(new FieldReflector<SandwichForm>(nameof(LengthOptions))
.SetDefine(async (state, field) =>
{
// Call database and get options and iterate over the options
field
.AddDescription("SixInch","Six Inch")
.AddTerms("SixInch", "Six Inch")
.AddDescription("FootLong ","Foot Long")
.AddTerms("FootLong ", "Foot Long")
return true;
}))
.OnCompletion(completionDelegate)
.Build();
But this does not show the options like an enum would do; right?
@Jasper its exactly the same thing...only dynamic
| common-pile/stackexchange_filtered |
angulardart: how StreamController works in the following example?
I am reading the tutorial.
Example 1:
lib/src/hero_search_component.dart
class HeroSearchComponent implements OnInit {
HeroSearchService _heroSearchService;
Router _router;
Stream<List<Hero>> heroes;
StreamController<String> _searchTerms =
new StreamController<String>.broadcast();
HeroSearchComponent(this._heroSearchService, this._router) {}
// Push a search term into the stream.
void search(String term) => _searchTerms.add(term);
Future<Null> ngOnInit() async {
heroes = _searchTerms.stream
.transform(debounce(new Duration(milliseconds: 300)))
.distinct()
.transform(switchMap((term) => term.isEmpty
? new Stream<List<Hero>>.fromIterable([<Hero>[]])
: _heroSearchService.search(term).asStream()));
}
}
lib/src/dashboard_component.html
<h3>Top Heroes</h3>
<div class="grid grid-pad">
<a *ngFor="let hero of heroes" [routerLink]="['HeroDetail', {id: hero.id.toString()}]" class="col-1-4">
<div class="module hero">
<h4>{{hero.name}}</h4>
</div>
</a>
</div>
<hero-search></hero-search>
I am confused how StreamController works. I have some questions:
1, In void search(String term) => _searchTerms.add(term);, a term is added to _searchTerms, which is a StreamController, not a Stream. Am I right?
2, The heroes in <a *ngFor="let hero of heroes"> is Stream<List<Hero>> heroes?
3, heroes is initialized in ngOnInit() and a stream is assigned to heroes. I cannot understand how heroes are updated. Can anyone explain the process to me?
4, I am also reading the Custom events session in https://webdev.dartlang.org/angular/guide/template-syntax.
The codes are as following. (Example 2)
final _deleteRequest = new StreamController<Hero>();
@Output()
Stream<Hero> get deleteRequest => _deleteRequest.stream;
void delete() {
_deleteRequest.add(hero);
}
<hero-detail (deleteRequest)="deleteHero($event)" [hero]="currentHero"></hero-detail>
In the above codes, hero is added to _deleteRequest. deleteRequest is the custom event, which is triggered and $event is passed to deleteHero() function. $event is just hero. Am I right? Can I consider deleteRequest to be a event?
5, In the first example, property heroes is connected to a stream. In the second example, a stream is bind to a event deleteRequest. Am I right?
Any hints welcomed. Thanks
Here are some answers to your multipart question:
In void search(String term) => _searchTerms.add(term);, a term is added to _searchTerms, which is a StreamController, not a Stream. Am I right?
A StreamController, as the name implies, controls a stream. Values get fed into that stream when you call StreamController.add().
Here is lib/src/hero_search_component.html:
<div id="search-component">
<h4>Hero Search</h4>
<input #searchBox id="search-box"
(change)="search(searchBox.value)"
(keyup)="search(searchBox.value)" />
<div>
<div *ngFor="let hero of heroes | async"
(click)="gotoDetail(hero)" class="search-result" >
{{hero.name}}
</div>
</div>
</div>
Notice: <input ... (keyup)="search(searchBox.value)" />. After every key you type in the input search box (on keyup), the HeroSearchComponent.search(String term) method gets call, which in turn calls StreamController.add(). That is how values get pumped into the stream.
5, In the first example, property heroes is connected to a stream.
heroes is a stream obtained as follows: start with the stream from the controller but apply some transformations to it (debounce, etc).
... $event is just hero. Am I right? Can I consider deleteRequest to be a event?
Yes the value of $event will be the Hero instance to be deleted. Yes, "deleteRequest" is the name of the custom even being fired.
heroes is assigned a stream in ngOnInit(). Any hero added by _searchTerms.add(term) will be fed into heroes?
Right, that's it!
| common-pile/stackexchange_filtered |
Number of bits needed to represent the product of the first primes
Input
An integer \$n\$ greater than or equal to 1.
Output
The number of bits in the binary representation of the integer that is the product of the first \$n\$ primes.
Example
The product of the first two primes is 6. This needs 3 bits to represent it.
Given unlimited memory and time your code should always output the correct value for n <= 1000000.
That would be A045716 :-)
@Giuseppe Except that the first term is different (must be 2 here instead of 1).
I'm inclined to close this as a dupe of sum of first n primes (which was the closest to "calculate first n primes" I could find) and bit length of n, since the two are the necessary building blocks and there is no way to avoid them.
@Bubbler: The bit-length Q&A is "for any positive 32-bit integer". This question requires BigInt. It's only a duplicate if you limit this question to languages where the native integer type is a BigInt, or where one works as a drop-in replacement including for bit-scan functions. A machine-code answer to that question is trivial (4 bytes for x86, for a bsr bit-scan reverse + ret), but would take much more work for this question. (You could approximate the answer by summing bit-lengths (logs) of each prime, but low bits can make the difference between carry-out to a new bit-pos.)
@Bubbler If you look, for example, at dingledooper's answer you'll find at least one nontrivial synergy that is unique to the combined task: Using the primorial instead of the more common (squared) factorial to generate the prime numbers.
To be pedantic, you should specify "bits of the binary representation". I could compactly represent the 3rd primorial with just 3# or as a factorization binary string 111 (where each base is the prime power). In some number theory programming problems those are useful.
Factor, 24 bytes
[ primorial bit-length ]
Try it online!
primorial ! get the primorial of the input
bit-length ! how many bits does it have?
JavaScript (ES12), 75 bytes
-1 byte thanks to @tsh
Expects a BigInt.
n=>eval("for(p=k=1n;p;d?0:p*=n--&&k)for(d=k++;k%d--;)p.toString(2).length")
Try it online!
JavaScript (ES12), 76 bytes
n=>eval("for(p=k=1n;n;d?0:p*=n--&&k)for(d=k++;k%d--;);p.toString(2).length")
Try it online!
Commented
This is a version without eval() for readability.
n => { // n = input
for( // outer loop:
p = // p = product
k = 1n; // k = current prime candidate
n; // stop when n = 0
d ? // if d is not 0:
0 // do nothing
: // else:
p *= n-- && k // decrement n and multiply p by k
) //
for( // inner loop:
d = k++; // start with d = k and increment k
k % d--; // decrement d until it divides k
); //
return p.toString(2) // convert the final product to base 2
.length // and return the length
} //
I naively thought that you had to use bigint for big ints in JavaScript!
@Simd but 1n is a bigint...
@Neil Ah, thanks.
n=>eval("for(p=k=1n;p;d?0:p*=n--&&k)for(d=k++;k%d--;)p.toString(2).length") with input changed to bigint.
For those wondering why not to do a tagged template (mdn) (i.e. n=>eval`...`) is because "If the argument of eval() is not a string, eval() returns the argument unchanged." (mdn) and a tagged template literal passes in an Array as the first argument (not a string primitive)
PARI/GP, 30 bytes
n->#binary(vecprod(primes(n)))
Attempt This Online!
Jelly, 5 bytes
Ẓ#PBL
A full program that accepts an integer from STDIN that prints the result.
Try it online!
How?
Straight forward, just saving a byte over the monadic Link ÆN€PBL
Ẓ#PBL - Main Link: no arguments
# - starting at {implict k=0} find the first {STDIN} k for which:
Ẓ - is prime?
P - product
B - to binary
L - length
Pretty fast too!
Uses sympy under the hood. Will get slower as the input increases as it is testing every single integer for primality. I don't really understand why ÆN€PBL is so much slower for small inputs, I would have thought calling lambda z: sympy.ntheory.generate.prime(z) for [1..input] would be as fast or faster than repeating lambda z: int(sympy.primetest.isprime(z)) for each number until input primes are found. Perhaps it's not using the same hardcoded lookup for small primes.
Ẓ# is a clever replacement for ÆN€, nice!
Python, 70 bytes
f=lambda n,x=1,i=1:n and f(n-(b:=x**i%i>0),x*i**b,i+1)or len(bin(x))-2
Try it online!
The idea is that if x is the product of every prime number up to n, then the next prime number must not share any prime factors with x. This is done by calculating the first i greater than n such that x**i%i>0. This works because if i isn't the next prime, all of its prime factors are below n, so it will easily divide x**i. Raising x to the ith power makes sure that prime powers are also caught, since x by itself only contains each prime factor once.
Ruby -rprime, 39 bytes
->n{'%b'%Prime.take(n).inject(:*)=~/$/}
Attempt This Online!
Vyxal, 34 bitsv2, 4.25 bytes
ʁǎΠbL
Try it Online!
Very simple
Explained
ʁǎΠbL
ʁǎ # A list of the first n primes
Π # Take the product of that
bL # And get the length of the binary representation
Created with the help of Luminespire.
357 is the largest input value that works on your TIO link.
@Simd that's because it times out after 10 seconds (by design). You can use the T flag to up the time out to 60 seconds or use the offline interpreter for unlimited time.
Pari/GP, 26 bytes
-3 Thanks to alephalpha:
n->#binary(lcm(primes(n)))
Try it online!
Pari/GP, 29 bytes (original)
n->logint(lcm(primes(n)),2)+1
Try it online!
Arturo, 58 bytes
$=>[0x:∏select.first:&2..∞=>prime? while->x>0[1+'x/2]]
Unfortunately, I have to count bits by counting how many halvings it takes to get to zero since both log and as.binary no longer work properly once values get into bignum territory. Perhaps there is a smarter way...?
Try it!
$=>[ ; a function where input is assigned to &
0 ; push 0 -- we'll use this to count bits later
x: ; to x, assign...
∏ ; product of
select.first:& ; the first <input> number of
2..∞=>prime? ; prime numbers in [2..∞]
while->x>0[ ; while x is greater than zero...
1+ ; increment our bit count
'x/2 ; divide x by two in place
] ; end while
] ; end function
MATLAB, 35 bytes
upd. use nthprime instead of primes(n)(get all primes up to n)
@(n)ceil(log2(prod(nthprime(1:n))))
Full code with test cases:
f=...
@(n)ceil(log2(prod(nthprime(1:n))));
disp(arrayfun(f,1:57));
What's the 300?
It needs to take arbitrary input, not just the number 300.
Rust + num + num-prime, 59 bytes
|n|num_prime::nt_funcs::primorial::<num::BigUint>(n).bits()
Does BigUint have a limit to how large an int it can handle?
@Simd It's arbitrarily large
How can BigUInt exist and how would it do 0-1?
05AB1E, 5 bytes
ÅpPbg
Try it online!
Explanation
ÅpPbg # Implicit input
Åp # First n primes
P # Product
b # To binary
g # Take the length
# Implicit output
Thunno 2 L, 4 bytes
Æppḃ
Try it online!
Explanation
Æppḃ # Implicit input
Æp # First n primes
p # Product
ḃ # To binary
# Take the length
# Implicit output
Excel, 98 94 92 bytes
2 bytes saved thanks to Taylor Alex Raine
=LET(
a,ROW(1:99),
LEN(BASE(PRODUCT(TAKE(FILTER(a,MMULT(N(MOD(a,TOROW(a))=0),a^0)=2),A1)),2))
)
Input in cell A1.
Fails for A1>13.
use 1:99 for -2 bytes
Charcoal, 26 bytes
Nθ→→W‹Lυθ¿⬤υ﹪ⅈκ⊞υⅈM→IL↨Πυ²
Try it online! Link is to verbose version of code. Explanation:
Nθ
Input n.
→→
Start searching for primes at 2.
W‹Lυθ
Stop when n primes have been found.
¿⬤υ﹪ⅈκ
If none of the primes found so far is a factor of the current value, then...
⊞υⅈ
... push the current value to the list of primes.
M→
Otherwise increment the current value. (Note that after a prime is pushed, the value is not immediately incremented, but if more primes are needed then it will "fail" the divisibility test and get incremented that way.)
IL↨Πυ²
Output the length of the base 2 representation of the product.
J, 18 bytes
f=:3 :'##:*/p:i.y'
Try it online!
Python, 67 bytes
f=lambda N,P=1,p=1:len(-N*f"{P:b}")or f(N-P**p%-~p,P-P**p%~p*P,p+1)
Attempt This Online!
Disclaimer: This one has one flaw which is that it is "zero-based" which is stretching the rules, I suppose. But I'd still very much like to show it off.
Obviousy, this is heavily based on @dingledooper's answer.
How?
This leverages a bit of elementary number theory, i.e. Fermat's little theorem, to squeeze out a few bytes.
The basic strategy is the same as dingledooper's: Use the nascent primorial to identify the next prime.What we do differently is when testing the next prime number candidate \$p\$ we raise the primorial \$P\$ to one less power, \$P^{p-1}\mod p\$ instead of \$P^p \mod p\$ That way we know the value can only be \$1\$ (iff \$p\$ is indeed a prime) or \$0\$. The value can, for example, directly be used to decrement the prime number counter. The conditional update of the primorial is also streamlined.
Wolfram Language (Mathematica), 45 bytes
Try it online!
Length@IntegerDigits[Times@@Prime~Array~#,2]&
JavaScript (Node.js), 74 bytes
n=>eval("for(i=s=p=1;n;s*=j?1:n--&&i)for(j=i++;s*i<2?i%j--:[++p,s/=2];)p")
Try it online!
Little RAM. Assumes n#(Product of first n primes) don't get too near to \$2^k\$ and therefore need confirm.
JavaScript (Node.js), 73 bytes basically by Arnauld
n=>eval("for(p=k=i=1n;n;d?0:p*=n--&&k)for(d=k++;k%d--;);for(;p/=2n;)++i")
Try it online!
| common-pile/stackexchange_filtered |
Java Map Value Equality
While writing a graph algorithm, I saw that this -
Definition:
Map<Integer, Integer> componentNames = new HashMap<Integer, Integer>();
CASE I:
if (componentNames.get(A) == componentNames.get(B)) {
System.out.printn("Hi");
}
Does not print anything.
CASE II:
int componentNameA = componentNames.get(A);
int componentNameB = componentNames.get(B);
if (componentNameA == componentNameB) {
System.out.printn("Hi");
}
Prints "Hi"
I have printed to check the values. And, they were indeed same.
This is the first time I have seen strange behavior for Java.
What could be the reason for this?
What is A and B in case 1 and case 2??
Related: http://stackoverflow.com/documentation/java/138/autoboxing/538/using-int-and-integer-interchangeably#t=201608270624487872982
@Hulk +1. OP should use equals() instead of == to compare objects equality
CASE I:
if (componentNames.get(A) == componentNames.get(B)) {
System.out.printn("Hi");
}
The code doesn't enter the if condition because you are trying to compare two Integer references using == which will only return true if the LHS and RHS refer to the same object. In your case, it is safe to assume that componentNames.get(A) and componentNames.get(B) both return a reference to a separate Integer object.
It would be helpful to know that the JVM caches the values for wrapper classes and it is quite possible that the above if condition may be true if the JVM has cached the int value returned by componentNames.get(A) and componentNames.get(B). The JVM used to cache Integer values ranging between -128 to 127 but modern JVMs can cache values greater than this range as well.
int componentNameA = componentNames.get(A);
int componentNameB = componentNames.get(B);
if (componentNameA == componentNameB) {
System.out.printn("Hi");
}
The code enters condition because you are unboxing an Integer into an int and the comparison is done between two primitive values.
In general, two references when compared using == will only return true if both the references point to the same object. Therefore, it is advisable to compare two references using equals if you are checking for equality and compare them using == if you are looking to check for identity.
CASE 1:
componentNames.get(A) and componentNames.get(B) are references / pointers of two different instances of Integer Class.
So, componentNames.get(A) == componentNames.get(B) is false.
CASE 2:
int componentNameA and int componentNameB are int type variables.
As they both contain same value, componentNameA == componentNameB is true.
Also have a glance at http://stackoverflow.com/questions/4036167/comparing-integer-objects-vs-int
This is strictly speaking not correct. int is not a reference type, so in case II the variables hold the same value rather than referring to the same value, which is why == equality is true. @RafafTahsin’ s link should explain the difference better.
@OleV.V. OMG .. I'm amazed how I did that!!!! fixed.
That’s fixed alright. I still like the link. :-)
Thanks man ... @Hulk
| common-pile/stackexchange_filtered |
How does binary code execution vulnerability work on a modern OS?
In a modern OS I think that:
the .text section where binary assembled CPU instructions are stored cannot be modified
the .data/.bss section is marked as no-execute so that the information there will only be treated as data, will never be executed by the CPU
So how is it possible for an exploit containing a payload of binary assembled instructions to get execution?
The execution of the Binary Assembled instructions works by exploiting the vulnerability in the Application Program.For example inserting malicious code into a PDF,if there is a flaw in the PDF Software the Code from the Data Section can be executed.
Now coming to your question.As far as i know after 8086,Intel started employing 4 levels of protection.The inner level is for Kernel Level processes and the outermost level is for User Level Processes.There are separate stacks for both the processes but the Memory space is shared.
A user level process(caller) cannot directly perform a privileged task,it needs to call a trusted code that does the work for the caller.But for the user level process to call the trusted code say to write a data item X,it should have the permission to do so(indirectly).
There are some exploits commonly called as Trojan Horses that allow the User Level process to use a Trusted Code to do stuff it is actually not allowed to do.
So if the Application program itself has vulnerabilities,combining that with such exploits can get the desired code in execution.
You're basically right in your knowledge about binaries. But they're too abstract to be of any use. I am assuming you're speaking about all binaries, not only the kernel or OS-level apps...
In short, the .bss section (where user-provided input resides in memory), stores variables that are loaded into critical process registers (local processor variables) during runtime. Manipulating any of these stored variables, preferably through a stack-based overflow (where user input overflows memory, and writes over one of the critical variables...) would possibly lead to executing user-provided bytes (intended to be input) as processor instructions.
So, if you're careful with your input, you could make the computer do whatever you want (that was not part of the program's job). If you're careful with user-supplied input, you would curb an attacker's attempt in exploiting your computer.
| common-pile/stackexchange_filtered |
Is there a way to use B&W conversion to reduce noise
My understanding of noise is that it's caused, effectively, because photos aren't evenly distributed accross time. So if you are shooting in low light, you get more noise because there aren't enought photons to 'average out'.
My question is this: I feel like there should be an algorithmic way by which you can sacrifice colour information (perhaps by going back to the demosaicing phase) of a RAW file to remove noise - effectively saying (well, the green pixels either side of this blue one didn't pick up as much light, so that's probably an error on this (white balanced) image).
Does such an algorithm exist?
Is there a way to use B&W conversion to reduce noise?
That depends on what you mean by 'noise'.
The conversion to B&W will effectively eliminate all chrominance noise.
It won't do much for luminance noise.
You must keep in mind that even though the values reported by each photosite (a/k/a pixel well, sensel, etc.) on a digital sensor are monochromatic, they're all filtered by one of three differently colored filters. If most "green" filtered pixels have a lower luminance value than adjacent "blue" filtered pixels, it most likely means that the light falling in that area has more "blue" than "green" in it. Noise reduction algorithms are more likely to interpret "green" filtered pixels that are brighter than other nearby "green" filtered pixels as noise.
The only real way to do what you suggest is to eliminate the Bayer mask altogether so that each photosite can be purely monochrome when the light is collected. There are a few monochrome digital cameras available that do just that.
Most noise is not caused by variance in the photon count. On an area as large as a sensor pixel (many times larger an a grain of high speed film) it makes very little difference. Instead it is literal signal noise within the electronics themselves which is then amplified along with the signal as the ISO is increased.
The algorithm you're describing is more or less how current noise reduction technology works, it uses context of the surrounding pixels to guess how much noise affects the current pixel. More advanced ones have edge detection and other features to improve the result. Even the, it's not very good.
When talking about black and white specifically, how you convert the image can greatly affect the amount of noise in the final image.
There are many methods for converting an image from color to black and white. The favorite (and Adobe recommended method) seems to be the "Black & White" adjustment. This method is actually not very good. It works by calculating the desaturated pixel and then multiplying the value based on its hue angle based on the sliders you select. This is essentially signal amplification, which also amplifies noise, so any slider with a positive ratio (a value above 50 in the Black & White adjustment) is also increasing the noise in those areas.
On the other hand, using the channel mixer uses a weighted average of three values. It is much easier with this method to avoid the signal amplification trap because all three channels sliders can be under 100%. The green and red channels usually have less noise than the blue channels, so you can lean on those two when possible to reduce it further. My go-to starting point is [R 60, G 90, B -40] then adjust from there.
| common-pile/stackexchange_filtered |
How can one write about illegal deeds without getting into trouble?
What is some good advice for writing about things done, in an autobiographical sense, that may have been or still are illegal?
For example, smoking or buying marijuana is illegal in many countries, yet people write about doing this without a problem. Likewise other minor illegal acts such as sex in public, harder drugs, etc also seem to be written about (Look at Hunter Thompson for example) without any consequence.
Is it a matter of degree? O.J. Simpsons was found innocent by a court of law, yet his book If I Did It was taken by some to be a confession of sorts. However this did not prompt any new investigations that I am aware of.
I want to write some stories about my travels and adventures without facing consequences for what I saw as minor, mostly harmless and/or necessary and infractions at the time.
What should I keep in mind and how free/honest can I be?
In essence, the question is: "Can a purportedly nonfiction book be used as evidence in court?" Logically speaking, the author could have written anything whatsoever. There is no physical evidence to prove that what is written actually took place. Therefore, the answer must be 'no, you don't have to worry about it.' However, if you say you murdered someone and buried the body at latitude X and longitude Y and someone goes digging and finds it, that's a whole other can of worms. You get my drift?
Also, in the case of O.J.-- even if my prior comment were invalid, remember the law regarding double jeopardy.
Separately, I suggest that if you are writing about someone else committing these illegal deeds with you, get that person's permission before identifying him or her in your book, or construct a pseudonym or otherwise blur your friend's identity. You may not mind volunteering that you smoked a bit of weed, but your friend might object to having the world know.
@Aerovistae Bear in mind that "double jeopardy" is an American legal principle. Britain repealed their double jeopardy law about 10 years ago, and many countries have no such law. And even in the U.S., the protection is very weak. The courts have ruled that you can't be tried twice for the same offense, but you can be tried for other offenses related to the same event. Ever notice how when someone is charged with a major crime, they often say "10 counts of robbery, 3 counts of assault, and 2 counts of kidnapping" or some such? Each of those is a separate crime. So if, say, you rob a bank, ...
... and you are charged with robbery but are found not guilty, but then later the police get new evidence, they can come back and say, in the course of the robbery you threatened the teller with a gun, that's a separate crime from the robbery itself, and so you could then be charged with that crime. In fact prosecutors today often "hold back" some charges just to cover this possibility.
Comment as this is a law answer, not a literary answer. Check statute of limitations. Even a confession does not matter if you are past those dates.
Be free and honest in what you did, unless you committed an extremely serious offence - murder, serious fraud, rape - because your writing does not, as a rule, constitute a formal confession. The police would have to find other evidence that you committed the crime to make it worth their while investigating - with acts like drug taking or public lewdity, that is unlikely to be still present.
If you are talking about crimes of violence or large scale activity, then the police are liable to consider it worth their while to investigate, in which case your writing may be a starting point, but unless you make a formal confession, the writings you publish are merely a small piece of evidence.
Of course, as you are talking about travelling, you may want to consider whether you ever wish to return to those countries that you committed "minor infractions" in. Irrespective of your guilt or otherwise, they might not be prepared to let you pass the border again.
I am not a lawyer. But ...
I don't know how police and courts treat an autobiography. I've never heard of someone being convicted of a crime because he confessed to it in an autobiography. But a very common method for police to catch a criminal is that he tells someone else about the crime and that person reports it to the police. Many criminals seem to get caught because they foolishly brag about how they got away with it to their buddies at the bar. And I've seen several stories in the news lately about people being arrested after making posts on Facebook and the like describing a crime they just committed. So I wouldn't just assume that something you put in a book "doesn't count".
As others have noted, a lot depends on the seriousness of the crime. If you write that 20 years ago you exceeded the speed limit by 2 miles per hour, I can't imagine that the police or courts would care enough to track you down on this. On the other hand, if you write that you were the person who committed an unsolved murder, then I think the authorities will be interested.
You mention committing various (minor) illegal acts while travelling. That means we are talking about the laws of not just one country, but many. Even if a lawyer assured you 100% that mentioning in your book that you smoked marijuana in the United States won't get you into trouble, maybe it will get you in trouble if you say you did it in Saudi Arabia or Singapore and then return to that country.
I wouldn't be too encouraged by the fact that some celebrity confessed to drug use in a book and nothing came of it. I don't want to get off into politics, but I think reality is that the rich and famous get away with things that ordinary people do not. When a famous Hollywood actor is caught using drugs, they get sent to a luxury rehab clinic. When some poor man living in a trailer park is caught using drugs, he goes to prison. When Timothy Geitner, former U.S. Secretary of the Treasury, was found not to have paid his taxes for several years, he was forced to promise not to do it again. If you or I did that, we'd be in jail. Etc.
My take: I'd talk to a lawyer and generally be very careful.
Hunter Biden, son of President Joe Biden, was convicted partially due to admitting to his drug use in his memoir: https://www.foxnews.com/politics/jury-likely-considered-hunter-bidens-own-words-memoir-powerful-evidence-convict-experts.
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
For what you're deciding to write, you could create an outline and ask a lawyer to consider the possible ramifications if the authorities decided to act upon it.
However, you'd probably be better off introducing a secondary character that performed the various actions that you're concerned about.
In Farley Mowat's And No Birds Sang, his autobiographical account of his WWII experienced made note of an event where "someone else," mowed down some German soldiers with a machine gun, though from the context you can realize that he was actually describing something that he had done.
However, even fictional writing can get you in trouble. An absurd case involved Steve Jackson games back in the early 1990's, where their offices were stormed by the Secret Service, resulting in the seizure of their computers and related equipment. As it turns out, one of their games, GURPS Cyberpunk, sounded too realistic, which brought down the authorities. Keep in mind that this was six years after the cyberpunk novel Neuromancer by William Gibson.
Ask a lawyer.
Like if you're writing about travels and adventures it's possible that you first need to check which countries/states laws apply in the first place and if violation of laws in one place are able to be prosecuted in another.
Also with regards to drugs, there are countries where everything about them is illegal while in others the consumption is decriminalized to not prevent people from seeking help for their addiction, while everything relating to making it available (sales, giving up, etc.) is illegal. So is there a crime and what is the crime.
Then there can be statues of limitation, so things that are so far in the past that they are no longer legally relevant even if you admit them. Though there could also be a difference between penal and civil lawsuits regarding that. So idk you might no longer be charged for theft but would need to give back the object that you've stolen or stuff like that.
Also is that incriminating evidence or could you later deny that and law enforcement couldn't prove it even with that knowledge.
Is it a crime that triggers default investigations or is it a crime where only the person effected can trigger the investigation.
Anonymization of partners-in-crime. Who might otherwise sue or have to sue for defamation to save their reputation, which they likely could do even if the actual deed is far in the past.
Are you popular enough so that media and fans or the police are going on the hunt to uncover evidence or is it a tidbit of information that isn't further able to be investigated.
Is it an autobiography or just autobiographical. So are you writing about yourself or just let your character go through the events of your life but having a distance between them and you.
Like what layer of plausible deniability do you have between, putting a legally binding oath of accuracy in the intro to writing about a friend that everyone knows is actually you.
Also might want to check if it gets you in trouble if you claim a factual crime the police investigates and finds nothing, so whether you could be charged with inventing a crime and wasting their time or worse incriminate someone else.
Like some of these things you could check for yourself, in some cases the risk is quite small anyway and you'd get at most a monetary fine. While if you want to be on the safe side, ask a lawyer what could hypothetically happen in those cases.
| common-pile/stackexchange_filtered |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.