text
stringlengths
175
47.7k
meta
dict
Q: How to save ALL Excel files every say minute / 10 seconds? Question: How to save ALL Excel files every given time period - say every minute or every 10 seconds ? Related: here How to save Excel file every say minute? a way to save given file is described. But if I have many files it is a problem to process like that. Remark: In case if I need to save every minute - I can use Excel's autosave, but autosave is is in *.xlsb format which I have a problem reading by Python, also several files are created and it is not clear what file is saved in what moment. Also that would not work if I need to save every 10 seconds. A: To save all open excel files every 10 seconds, you can use this code. You can assign it to shape and run it from one of the excel files. Sub Save1() Dim xWb As Workbook Application.DisplayAlerts = False For Each xWb In Application.Workbooks If Not xWb.ReadOnly And Windows(xWb.Name).Visible Then xWb.Save End If Next Application.DisplayAlerts = True Application.OnTime Now + TimeValue("00:00:10"), "Save1" End Sub
{ "pile_set_name": "StackExchange" }
Q: How to create databases, users and grants with terraform mysql and output the created credentials? For a new deployment I want to create databases, users and grants on a previous created MySQL database on azure. The following code used inside a module creates the environment as expected and I still struggle how to create the outputs of the module and so I get something like the following, to give it to the operations team: module.test_cluster.mysql_users[cat].password = randompassword1 module.test_cluster.mysql_users[dog].password = randompassword2 Code example: mysql_databases = [ "foo", "bar" ] mysql_users = [ "stage-cat", "stage-dog", "stage-snake" ] mysql_grants = { "cat-0" = { name = "stage-cat" database = "foo" grant = ["ALL"] }, "cat-1" = { name = "stage-cat" database = "bar" grant = ["SELECT", "EXECUTE", "SHOW VIEW"] }, "dog-0" = { name = "stage-dog" database = "bar" grant = ["ALL"] } } resource "mysql_database" "test" { for_each = var.mysql_databases name = each.key } resource "mysql_user" "test" { for_each = var.mysql_users user = each.value host = "%" tls_option = "SSL" plaintext_password = random_password.test[each.value].result } resource "mysql_grant" "test" { for_each = var.mysql_grants user = mysql_user.test[each.value["name"]].user host = "%" database = each.value["database"] privileges = each.value["grant"] } resource "random_password" "test" { for_each = var.mysql_users length = 32 special = false } A: This is my solution how to output usernames and passwords: In the module: output "mysql_credentials" { value = [ for user in var.mysql_users : { "username" = "${user}@${var.cluster_name}" // Hostname is for Azure MySQL service "password" = "${random_password.test[user]["result"]}" } ] } In the terraform file referencing the module: output "mysql_service_credentials" { value = module.cluster.mysql_credentials } The output: mysql_credentials = [ { "Password" = "OecheeP1Iequ6zeis2aipai5eiyooL8g" "Username" = "stage-cat@stage" }, { "Password" = "xaed1EiGh4ahbea4ohjeetouw0Geph8o" "Username" = "stage-dog@stage" }, { "Password" = "Seu8ieciewoh4Ohl6Ut7em1aiVie1Ao0" "Username" = "stage-snake@stage" }, ]
{ "pile_set_name": "StackExchange" }
Q: Querying Archive Class with REST API of ArcGIS Server? I would like to know if there is a way to access the archive class through a Map Service of ArcGIS Server. I have a Map Service with feature class stored in a SDE GeoDatabase with Archiving and Versionning enable. Is it possible to query the Archive Class in order to retrieve features at a perticular moment using the Feature Access or Mapping capabilities through the REST API? When I try to publish a Map Service containing an Archive Class to ArcGIS Server I have an error saying: Layer's data source is not registered with the geodatabase (Feature Service). A: For the posterity I post the solution suggested in the comment of Below The Radar as an answer as it helps me. When publishing a map service the capability Feature Access cannot be enabled when an Archive Class is present in the Map Service. This doesn't mean you can't query features in published Archive Class. You can still query the Archive Class if you enable the Queryoperation from the capability Data Management.
{ "pile_set_name": "StackExchange" }
Q: bootstrap selectpicker knockoutjs disable option I have the following binding in js fiddle. <div class="container body-content"> <div>Name : <span data-bind="text: Name"></span> </div>The select control should be below <select multiple data-bind="selectPicker: teamID, optionsText: 'text', optionsValue : 'id', selectPickerOptions: { optionsArray: teamItems, disabledOption: IsDisabled }"></select> <div>Selected Value(s) <div data-bind="text: teamID"></div> </div> </div> I am thinking of doing this disabledOption: IsDisabled and then adding this.teamItems = ko.observableArray([{ text: 'Chris', id: 1, IsDisabled: false }, { text: 'Peter', id: 2, IsDisabled: false }, { text: 'John', id: 3, IsDisabled: false }]); I would like to know how to disable an option in the select. A: In the knockout docs, there's an example that shows how you can disable an item using an optionsAfterRender method. About the method you can pass to it: It has to be in your viewmodel, not in your items It takes in the option HTML node, and the item it's bound to So step one is to find a place to store which items are disabled. The easiest option would be to store it inside your teamItems' objects: { text: 'Chris', id: 1, disable: ko.observable(true) } Now, we need to add a method that takes in an item and creates a binding. We can take this straight from the example: this.setOptionDisable = function(option, item) { ko.applyBindingsToNode(option, { disable: item.disable }, item); } Finally, we need to tell knockout to call this method: <select multiple data-bind="optionsAfterRender: setOptionDisable, ... Note that after changing a disable property in one of your items, you'll have to call teamItems.valueHasMutated manually. Here's an updated fiddle: http://jsfiddle.net/nq56p9fz/
{ "pile_set_name": "StackExchange" }
Q: Jquery loop with condition I'm new with jquery and I don't know how to do a loop with a condition. I want to get all the div with the same id (yeah I know id should be unique) and color the border in red. It seems that it's not doing the loop since only the first "#column3" is colored. I want that when #column3 exists, we add class focus. <div id="div2"> <div id="column1">1 <div class="price">400</div> <span>hello</span> <span>undefined</span> </div> <div id="column2">hello </div> <div id="column3">3 <div class="price">600</div> <span>hello</span> <span>undefined</span> </div> </div> <div id="div2"> <div id="column1">1 <div class="price">400</div> <span>hello</span> <span>undefined</span> </div> <div id="column2">hello </div> </div> <div id="div2"> <div id="column1">1 <div class="price">400</div> <span>hello</span> <span>undefined</span> </div> <div id="column2">hello </div> <div id="column3">3 <div class="price">600</div> <span>hello</span> <span>undefined</span> </div> </div> And I tried this: $("#div2 #column3").each(function (index) { if ($("#div2 #column3").length) { $("#column3").addClass("focus"); } }); Here is a fiddle: https://jsfiddle.net/qm89a1cf/2/ A: In for each you will get the two parameters first is index and second one element it's self. You can add this code in your fiddler and it will works. $("#div2 #column3").each(function (index,key) { if ($("#div2 #column3").length) { $(key).addClass("focus"); //key is elemnt } });
{ "pile_set_name": "StackExchange" }
Q: Is there a library in php to handle and compress mp3 files in php..? Is there anyway in php to handle i.e compress a mp3 file using php...? Is there any library out there like ZZIPlib library (To handle .ZIP files)...? Thanks for your suggestions...! A: I don't think there are any libraries that will let you compress MP3s (I presume you're talking about generating an MP3 from a WAV/AIFF, etc. file?) As such, it would probably make more sense to simply shell escape out (using exec and escapeshellarg if relevant) and use standard command line utils such as lame.
{ "pile_set_name": "StackExchange" }
Q: Let $T$ be a Hermitian operator and $\|v\|=1$, prove $\langle T^2(v),v\rangle \ge\langle T(v),v\rangle^2$ Let $T$ be a Hermitian operator on an inner product space $V$ over the field of complex numbers, $C$ (of a finite dimension), also assume $\|v\|=1$. Prove: $$\langle T^2(v),v\rangle \ge\langle T(v),v\rangle^2$$ A: It's not true as stated, because it has the wrong scaling behaviour with respect to $v$. Were you supposed to assume $\|v\|=1$? EDIT: With that assumption, the hint is overkill. The result follows directly from Cauchy-Schwarz. Note that $\langle T^2 v, v \rangle = \langle T v, T v \rangle$ since $T$ is Hermitian. A: Edit: As pointed out by Robert Israel, this follows immediately from Cauchy-Schwarz. I so wanted to use your (wrong and now deleted hint), that I actually basically reproved Cauchy-Schwarz... Develop the following $$ ((T-\alpha I)^2v,v)=\alpha^2\|v\|^2-2\alpha(Tv,v)+(T^2v,v). $$ Note that for every $\alpha\in \mathbb{R}$, the operator $(T-\alpha I)^2=(T-\alpha I)^*(T-\alpha I) $ is hermitian positive so $$ ((T-\alpha I)^2v,v)\geq 0. $$ We have a quadratic in $\alpha$ which is always nonnegative. This means that its discriminant is nonpositive: $$ \Delta=4((Tv,v)^2-(T^2v,v)\|v\|^2)\leq 0. $$ Hence $$ (Tv,v)^2\leq (T^2v,v)\|v\|^2. $$ So your inequality holds for all $\|v\|\leq 1$.
{ "pile_set_name": "StackExchange" }
Q: Make API query to only one Stack Exchange site Is there a way to limit a /search or a /similar query to a specific site or sites? A: By definition all /search and /similar queries are made on one specific site. There is currently no way to search more than one site. Example: http://api.stackoverflow.com/1.1/search?intitle=linq This example will search only Stack Overflow for the term linq.
{ "pile_set_name": "StackExchange" }
Q: How to parse RxJava to receive just the data that i want? I just want the numbers, but this is what i'm receiving at log: [Boletim(grade=4.5), Boletim(grade=9.5)] The Response: public class GradeResponse { @Inject Retrofit retrofit; @Inject MainPresenter mainPresenter; public void getGradeRx() { MyApplication.getMainComponent().injectIntoGradeResponse(this);// informando ao dagger sobre o uso de um component e a necessidade de injetar dependência Subscription getGrade = retrofit .create(GradeService.class) .getGrade() .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .map(model -> { return model.getBoletim(); }) .subscribe(new Observer<Boletim[]>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { Log.i(TAG, "saporra vai me matar ainda"); } @Override public void onNext(Boletim[] grades) { Log.i(TAG, Arrays.asList(grades).toString()); } }); } } The models: GradeModel: @SerializedName("boletim") @Expose private Boletim[] boletim; Boletim.class public class Boletim { @SerializedName("grade") @Expose private double grade; The retrofit service is ok, the dependency injection is working. I'm receiving the onSuccess method from rxJava, i just need now receiving only the numbers without this "[Boletim(grade=". A: You are seeing the toString of your objects because you get the entire object in your map! only the numbers without this "[Boletim(grade=". Way can't you map again and extract it? .map(model -> { // This map returns a Boletim[] return model.getBoletim(); }) .map(boletim -> { // This map returns a double[] Double grades = new Double[boletim.length]; for (int i =0; i < grades.length ; i++) { grades[i] = boletim[i].getGrade() ; } return grades; }).subscribe(new Observer<Double[]>() { // This subscribes to a double[] @Override public void onCompleted() { } @Override public void onError(Throwable e) { Log.i(TAG, "saporra vai me matar ainda"); } @Override public void onNext(Double[] grades) { Log.i(TAG, Arrays.toString(grades)); } } Or you could put the for loop into onNext If you don't want an Observable of arrays, then use flatMap
{ "pile_set_name": "StackExchange" }
Q: How to make AutoFac use same instance of nested dependency per top-level object? (SignalR dependency injection per hub) I am trying to set up my AutoFac registration in such a way that this test passes: [Test] public void Autofac_registration_test() { // Given var builder = new ContainerBuilder(); RegisterServices(builder); var container = builder.Build(); // When var firstHub = container.Resolve<Hub>(); var secondHub = container.Resolve<Hub>(); // Then firstHub.Should().NotBe(secondHub); firstHub.FooRepo.Context.Should().Be(firstHub.BarRepo.Context); firstHub.FooRepo.Context.Should().NotBe(secondHub.FooRepo.Context); } i.e. I want to use the same Context object all the way down within a single Hub, but use a different one when a new Hub is created. RegisterServices is currently just: private void RegisterServices(ContainerBuilder builder) { builder.RegisterType<MyHub>(); builder.RegisterType<FooRepo>(); builder.RegisterType<BarRepo>(); builder.RegisterType<Context>(); // How should I scope this? } Which fails at firstHub.FooRepo.Context.Should().Be(firstHub.BarRepo.Context); because Context is transiently scoped. But scoping context per lifetime also fails, this time at firstHub.FooRepo.Context.Should().NotBe(secondHub.FooRepo.Context);. It feels like this is a reasonable thing to want to do, so am I missing anything obvious out-of-the-box here? Or will I have to do something manual to track Hub creation? (For context, this is for a SignalR app. Hubs are created per SignalR request, so this was an attempt to match the unit-of-work lifetime of an HTTP request in normal webby situations). A: What @Steven said in his comment was correct, I needed a per-object-graph lifestyle. Castle.Windsor supports this, so I swicthed to using that for my dependency injection instead of AutoFac. The registration now looks like: container.Register(Component.For<Hub>().LifestyleTransient()); container.Register(Component.For<FooRepo>().LifestyleTransient()); container.Register(Component.For<BarRepo>().LifestyleTransient()); container.Register(Component.For<Context>().LifestyleBoundTo<Hub>()); // Important bit For more information, see: http://docs.castleproject.org/Windsor.LifeStyles.ashx?HL=scope#Bound_8
{ "pile_set_name": "StackExchange" }
Q: ESTA Elegible after Qatar? I am planning a week vacation at the end of august, since I am a EU citizen I would like to know if visiting Qatar, Bahrain and Dubai will make me ineligible for an ESTA and therefore for a trip to USA later A: The US State Department says: Visa Waiver Program Improvement and Terrorist Travel Prevention Act of 2015 Under the Visa Waiver Program Improvement and Terrorist Travel Prevention Act of 2015, travelers in the following categories must obtain a visa prior to traveling to the United States as they are no longer eligible to travel under the Visa Waiver Program (VWP): Nationals of VWP countries who have traveled to or been present in Iran, Iraq, Libya, Somalia, Sudan, Syria, or Yemen on or after March 1, 2011 (with limited exceptions for travel for diplomatic or military purposes in the service of a VWP country). Nationals of VWP countries who are also nationals of Iran, Iraq, Sudan, or Syria. Qatar, Bahrain and Dubai are fine. Indeed, all three are very close allies of the US: the US has a huge air base in Qatar , a large naval base in Bahrain and a customs pre-clearance station in the UAE.
{ "pile_set_name": "StackExchange" }
Q: How do I make Linux recognize a new SATA /dev/sda drive I hot swapped in without rebooting? Hot swapping out a failed SATA /dev/sda drive worked fine, but when I went to swap in a new drive, it wasn't recognized: [root@fs-2 ~]# tail -18 /var/log/messages May 5 16:54:35 fs-2 kernel: ata1: exception Emask 0x10 SAct 0x0 SErr 0x50000 action 0xe frozen May 5 16:54:35 fs-2 kernel: ata1: SError: { PHYRdyChg CommWake } May 5 16:54:40 fs-2 kernel: ata1: link is slow to respond, please be patient (ready=0) May 5 16:54:45 fs-2 kernel: ata1: device not ready (errno=-16), forcing hardreset May 5 16:54:45 fs-2 kernel: ata1: soft resetting link May 5 16:54:50 fs-2 kernel: ata1: link is slow to respond, please be patient (ready=0) May 5 16:54:55 fs-2 kernel: ata1: SRST failed (errno=-16) May 5 16:54:55 fs-2 kernel: ata1: soft resetting link May 5 16:55:00 fs-2 kernel: ata1: link is slow to respond, please be patient (ready=0) May 5 16:55:05 fs-2 kernel: ata1: SRST failed (errno=-16) May 5 16:55:05 fs-2 kernel: ata1: soft resetting link May 5 16:55:10 fs-2 kernel: ata1: link is slow to respond, please be patient (ready=0) May 5 16:55:40 fs-2 kernel: ata1: SRST failed (errno=-16) May 5 16:55:40 fs-2 kernel: ata1: limiting SATA link speed to 1.5 Gbps May 5 16:55:40 fs-2 kernel: ata1: soft resetting link May 5 16:55:45 fs-2 kernel: ata1: SRST failed (errno=-16) May 5 16:55:45 fs-2 kernel: ata1: reset failed, giving up May 5 16:55:45 fs-2 kernel: ata1: EH complete I tried a couple things to make the server find the new /dev/sda, such as rescan-scsi-bus.sh but they didn't work: [root@fs-2 ~]# echo "---" > /sys/class/scsi_host/host0/scan -bash: echo: write error: Invalid argument [root@fs-2 ~]# [root@fs-2 ~]# /root/rescan-scsi-bus.sh -l [snip] 0 new device(s) found. 0 device(s) removed. [root@fs-2 ~]# [root@fs-2 ~]# ls /dev/sda ls: /dev/sda: No such file or directory I ended up rebooting the server. /dev/sda was recognized, I fixed the software RAID, and everything is fine now. But for next time, how can I make Linux recognize a new SATA drive I have hot swapped in without rebooting? The operating system in question is RHEL5.3: [root@fs-2 ~]# cat /etc/redhat-release Red Hat Enterprise Linux Server release 5.3 (Tikanga) The hard drive is a Seagate Barracuda ES.2 SATA 3.0-Gb/s 500-GB, model ST3500320NS. Here is the lscpi output: [root@fs-2 ~]# lspci 00:00.0 RAM memory: nVidia Corporation MCP55 Memory Controller (rev a2) 00:01.0 ISA bridge: nVidia Corporation MCP55 LPC Bridge (rev a3) 00:01.1 SMBus: nVidia Corporation MCP55 SMBus (rev a3) 00:02.0 USB Controller: nVidia Corporation MCP55 USB Controller (rev a1) 00:02.1 USB Controller: nVidia Corporation MCP55 USB Controller (rev a2) 00:04.0 IDE interface: nVidia Corporation MCP55 IDE (rev a1) 00:05.0 IDE interface: nVidia Corporation MCP55 SATA Controller (rev a3) 00:05.1 IDE interface: nVidia Corporation MCP55 SATA Controller (rev a3) 00:05.2 IDE interface: nVidia Corporation MCP55 SATA Controller (rev a3) 00:06.0 PCI bridge: nVidia Corporation MCP55 PCI bridge (rev a2) 00:08.0 Bridge: nVidia Corporation MCP55 Ethernet (rev a3) 00:09.0 Bridge: nVidia Corporation MCP55 Ethernet (rev a3) 00:0a.0 PCI bridge: nVidia Corporation MCP55 PCI Express bridge (rev a3) 00:0b.0 PCI bridge: nVidia Corporation MCP55 PCI Express bridge (rev a3) 00:0c.0 PCI bridge: nVidia Corporation MCP55 PCI Express bridge (rev a3) 00:0d.0 PCI bridge: nVidia Corporation MCP55 PCI Express bridge (rev a3) 00:0e.0 PCI bridge: nVidia Corporation MCP55 PCI Express bridge (rev a3) 00:0f.0 PCI bridge: nVidia Corporation MCP55 PCI Express bridge (rev a3) 00:18.0 Host bridge: Advanced Micro Devices [AMD] K8 [Athlon64/Opteron] HyperTransport Technology Configuration 00:18.1 Host bridge: Advanced Micro Devices [AMD] K8 [Athlon64/Opteron] Address Map 00:18.2 Host bridge: Advanced Micro Devices [AMD] K8 [Athlon64/Opteron] DRAM Controller 00:18.3 Host bridge: Advanced Micro Devices [AMD] K8 [Athlon64/Opteron] Miscellaneous Control 00:19.0 Host bridge: Advanced Micro Devices [AMD] K8 [Athlon64/Opteron] HyperTransport Technology Configuration 00:19.1 Host bridge: Advanced Micro Devices [AMD] K8 [Athlon64/Opteron] Address Map 00:19.2 Host bridge: Advanced Micro Devices [AMD] K8 [Athlon64/Opteron] DRAM Controller 00:19.3 Host bridge: Advanced Micro Devices [AMD] K8 [Athlon64/Opteron] Miscellaneous Control 03:00.0 VGA compatible controller: Matrox Graphics, Inc. MGA G200e [Pilot] ServerEngines (SEP1) (rev 02) 04:00.0 PCI bridge: NEC Corporation uPD720400 PCI Express - PCI/PCI-X Bridge (rev 06) 04:00.1 PCI bridge: NEC Corporation uPD720400 PCI Express - PCI/PCI-X Bridge (rev 06) Update: In perhaps a dozen cases, we've been forced to reboot servers because hot swap hasn't "just worked." Thanks for the answers to look more into the SATA controller. I've included the lspci output for the problematic system above (hostname: fs-2). I could still use some help understanding what exactly isn't supported hardware-wise in terms of hot swap for that system. Please let me know what other output besides lspci might be useful. The good news is that hot swap "just worked" today on one of our servers (hostname: www-1), which is very rare for us. Here is the lspci output: [root@www-1 ~]# lspci 00:00.0 RAM memory: nVidia Corporation MCP55 Memory Controller (rev a2) 00:01.0 ISA bridge: nVidia Corporation MCP55 LPC Bridge (rev a3) 00:01.1 SMBus: nVidia Corporation MCP55 SMBus (rev a3) 00:02.0 USB Controller: nVidia Corporation MCP55 USB Controller (rev a1) 00:02.1 USB Controller: nVidia Corporation MCP55 USB Controller (rev a2) 00:04.0 IDE interface: nVidia Corporation MCP55 IDE (rev a1) 00:05.0 IDE interface: nVidia Corporation MCP55 SATA Controller (rev a3) 00:05.1 IDE interface: nVidia Corporation MCP55 SATA Controller (rev a3) 00:05.2 IDE interface: nVidia Corporation MCP55 SATA Controller (rev a3) 00:06.0 PCI bridge: nVidia Corporation MCP55 PCI bridge (rev a2) 00:08.0 Bridge: nVidia Corporation MCP55 Ethernet (rev a3) 00:09.0 Bridge: nVidia Corporation MCP55 Ethernet (rev a3) 00:0b.0 PCI bridge: nVidia Corporation MCP55 PCI Express bridge (rev a3) 00:0c.0 PCI bridge: nVidia Corporation MCP55 PCI Express bridge (rev a3) 00:0f.0 PCI bridge: nVidia Corporation MCP55 PCI Express bridge (rev a3) 00:18.0 Host bridge: Advanced Micro Devices [AMD] K10 [Opteron, Athlon64, Sempron] HyperTransport Configuration 00:18.1 Host bridge: Advanced Micro Devices [AMD] K10 [Opteron, Athlon64, Sempron] Address Map 00:18.2 Host bridge: Advanced Micro Devices [AMD] K10 [Opteron, Athlon64, Sempron] DRAM Controller 00:18.3 Host bridge: Advanced Micro Devices [AMD] K10 [Opteron, Athlon64, Sempron] Miscellaneous Control 00:18.4 Host bridge: Advanced Micro Devices [AMD] K10 [Opteron, Athlon64, Sempron] Link Control 00:19.0 Host bridge: Advanced Micro Devices [AMD] K10 [Opteron, Athlon64, Sempron] HyperTransport Configuration 00:19.1 Host bridge: Advanced Micro Devices [AMD] K10 [Opteron, Athlon64, Sempron] Address Map 00:19.2 Host bridge: Advanced Micro Devices [AMD] K10 [Opteron, Athlon64, Sempron] DRAM Controller 00:19.3 Host bridge: Advanced Micro Devices [AMD] K10 [Opteron, Athlon64, Sempron] Miscellaneous Control 00:19.4 Host bridge: Advanced Micro Devices [AMD] K10 [Opteron, Athlon64, Sempron] Link Control 03:00.0 VGA compatible controller: Matrox Graphics, Inc. MGA G200e [Pilot] ServerEngines (SEP1) (rev 02) 04:00.0 PCI bridge: NEC Corporation uPD720400 PCI Express - PCI/PCI-X Bridge (rev 06) 04:00.1 PCI bridge: NEC Corporation uPD720400 PCI Express - PCI/PCI-X Bridge (rev 06) 09:00.0 SCSI storage controller: LSI Logic / Symbios Logic SAS1064ET PCI-Express Fusion-MPT SAS (rev 04) A: If your SATA controller supports hot swap, it should "just work(tm)." To force a rescan on a SCSI BUS (each SATA port shows as a SCSI BUS) and find new drives, you will use: echo "0 0 0" >/sys/class/scsi_host/host<n>/scan On the above, < n > is the BUS number. A: echo "- - -" >/sys/class/scsi_host/host<n>/scan ^ ^ \_\_______ note spaces between the dashes. A: When a drive has failed in some circumstances Linux won't realise you've actually pulled it physically from the array. If you have that problem (as I did this morning) you can do the following: echo 1 > /sys/block/<devnode>/device/delete e.g., in my case, /dev/sda had failed and I didn't want to reboot the server, so I did: echo 1 > /sys/block/sda/device/delete After I did that, the new drive (which had actually been physically added already) was immediately visible. If it is not visible at this point, you can also do this to force a re-scan: echo "- - -" > /sys/class/scsi_host/host<n>/scan That "- - -" is wildcards for channel, id & LUN respectively, so you can restrict the scan to some subset if you want by specifying numbers instead. Before you start, you could also: readlink /sys/block/<devnode> Which will show you the path with the right host number to check in /proc/scsi/scsi for disappearence after removal.
{ "pile_set_name": "StackExchange" }
Q: Dispatch event occurs multiple times I'm using a dispatch event in Symfony, And I don't understand because I have the kernel.response twice. Controller: /** * @Route("/evento", name="evento") */ public function eventoAction() { $dispatcher = new EventDispatcher(); $subscriber = new StoreSubriber(); $dispatcher->addSubscriber($subscriber); $event = new FilterOrderEvent($order); $dispatcher->dispatch(StoreEvents::STORE_ORDER,$event); return $this->render('::event.html.twig'); } Subscriber: namespace AppBundle\Events; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Event\FilterResponseEvent; use Symfony\Component\HttpKernel\Event\GetResponseEvent; class StoreSubriber implements EventSubscriberInterface { public static function getSubscribedEvents() { return array( 'kernel.request' => array( array('onKernelResponsePre', -10), array('onKernelResponseMid', 5), array('onKernelResponsePost', 0), ), 'store.order' => array('onStoreOrder', 0), ); } public function onKernelResponsePre(GetResponseEvent $event) { echo "<br>"; echo "onKernelResponsePre"; } public function onKernelResponseMid(GetResponseEvent $event) { echo "<br>"; echo "onKernelResponseMid"; } public function onKernelResponsePost(GetResponseEvent $event) { echo "<br>"; echo "onKernelResponsePost"; } public function onStoreOrder(FilterOrderEvent $event) { echo "<br>"; echo "ORDER"; } } service.yml: services: user_check_token: class: AppBundle\Events\StoreSubriber tags: - { name: kernel.event_subscriber } My Output: onKernelResponseMid onKernelResponsePost onKernelResponsePre ORDER Events ( twig ) onKernelResponseMid onKernelResponsePost onKernelResponsePre My question is, why am I seeing onKernelResponseMid, onKernelResponsePost, and onKernelResponsePre twice? A: I would say because you subscribed to the event twice. First inside your eventoAction $dispatcher->addSubscriber($subscriber); Second with Tagging your subscriber in your configuration tags: - { name: kernel.event_subscriber } Try removing this $dispatcher->addSubscriber($subscriber); from eventoAction. edit other possible reasons multiple kernel event event can fire for each request, symfony can do subrequest, anywhere during running the code. This can be also in twig like this: {{ render(controller('AcmeArticleBundle:Article:recentArticles') }}. As this is another real request the event will fire. To handle this you need to add conditions to your subscriber to filter only request which you want to handle if you use prod environment clear cache as your twice registered subscriber can be cached. edit 2 how to debug subrequest To easily find out if there where any sub request going on, you can look in the web debug toolbar. go to the fullpage view (click any section) upper left corner find link "last 10" (meaning show last 10 requests) at glance you should see how each request went one after another, with they urls and times, and possibility to go to that request full page debug. This way you'll should be able to find if there are any subrequests and where they originated from.
{ "pile_set_name": "StackExchange" }
Q: Getting error "Can not retrieve link from link field" while importing I am getting error 'Cannot retrieve link from link field while content importing using content porter'. But I am not able to figure out where exactly the problem is existing. Help!!!!! A: I have Figured out the issue. There was a change in structure group metadata schema in which there was a drop down to select yes or no. When I changed this value in structure group and done save and close. then the issue resolved. For some of the pages this thing is working but still some are not getting imported.
{ "pile_set_name": "StackExchange" }
Q: Format fails to copy text properties from the format-string for adjacent %-sequences Take a look at this example: (format (concat "%s" (propertize "%s" 'face 'error)) "foo" "bar") "foobar" (format (concat "%s " (propertize "%s" 'face 'error)) "foo" "bar") #("foo bar" 4 7 (face error)) And the documentation of format explicitly states: Text properties, if any, are copied from the format-string to the produced text. Why is that? I know I can work around this with: (format "%s%s" "foo" (propertize "bar" 'face 'error)) #("foobar" 3 6 (face error)) Or even: (concat "foo" (propertize "bar" 'face 'error)) #("foobar" 3 6 (face error)) But my original use case is a bit more complex than this. Edit A probably more general example is the following: (format (concat (propertize "%s" 'face 'bold) "" ; any non-empty string works (propertize "%s" 'face 'error)) "foo" "bar") #("foobar" 0 6 (face bold)) A: So it was a bug which has now been fixed in this commit.
{ "pile_set_name": "StackExchange" }
Q: Newtonsoft.JSON Serialization Array, Object, or Null I have some JSON that can be a List or null. How do I create a POCO for this JSON? Here is an example array: http://pastebin.com/qAZF2Ug9 Here is my POCO: http://pastebin.com/hUtgyytc How can I tell Newtonsoft.JSON to ignore the SalesLine object, if it is null? A: You can specify the settings: var settings = new Newtonsoft.Json.JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore}; and use that in various serializer constructors and serialize calls. Alternatively, IIRC it supports conditional serialization, i.e. public bool ShouldSerializeFoo() { return Foo != null; } // pairs to property Foo
{ "pile_set_name": "StackExchange" }
Q: ¿Se puede transformar esta fecha por PHP o MySQL? tengo la siguiente fecha: Sat, 30 May 2020 07:25:30 +0000 ¿Se puede transformar usando PHP o MySQL al siguiente formato? Como esta: Sat, 30 May 2020 07:25:30 +0000 Como debería estar: 2020-05-30 07:25:30 Gracias. A: En PHP podrías primero leer el string inicial para convertirlo a tipo fecha: $fecha = date_create_from_format('D, d M Y h:i:s O', 'Sat, 30 May 2020 07:25:30 +0000'); y luego: $fechaFormateada = date ( 'Y-m-d h:i:s', date_timestamp_get($fecha)) En el manual de PHP están todos los formatos posibles: https://www.php.net/manual/es/datetime.createfromformat.php
{ "pile_set_name": "StackExchange" }
Q: Utilization of MOSFETs as switches, design methodology Let's say I want to use an nMos FET in a low side switching circuit as follows: simulate this circuit – Schematic created using CircuitLab Datasheet for IRF530 here. Now, during my education in EE, I have learnt some operation regions for MOSFETs and formulas for drain current related to these regions. And one parameter Kn which was the key parameter shows up in everywhere. But now, I am having hard time in my calculations, because, there is not a Kn value in the datasheets of such MOSFETs. If it were present, what I would do is: (For Vgs = high case, SW1 is closed) Assume an operation region for the nMOS, I start with SAT generally Use Idsat formula for the SAT region. Idsat = Kn/2*(Vgs-Vtn)^2 Find the drain voltage using Vd = Vdd - Rload * Idsat Check if Vds >= Vgs - Vtn or not, if so, assumption for SAT is validated, if not, then MOSFET is in linear region, since it cannot be in cut-off This was working great while doing it on paper, however, now in reality, I am stuck how to approach this kind of a design using the information present in datasheets. I'm not able to make any comments on the operation region of the MOSFET because I cannot guess drain voltage without any information about drain current flowing through the circuit. So, what I am asking is something like the followings: In which operation region a MOSFET should be operated for switching applications? For ON(mosfet conducts) part of the operation, what should I replace MOSFET with? Rds(on)? Or a voltage difference between source and drain? How should I decide whether I can directly replace the MOSFET with a resistance of Rds(on) or not. What criterias do I have to satisyf for it to act as an almost short circuit when it is ON. And as an extra, if anyone knows, an answer to the following would be nice: Why Kn is not present in these datasheets while it is heavily used in theoretical calculations, at least in my college education? A: Powermosfets like this are not meant to be used in their constant-current region (I call it that because people like to confuse saturation/linear, because they are flipped with BJT. In this case it would be saturation). When you do, they very often suffer from thermal runaway. As a result, you are pretty much always going to be in the linear region (which you will definitely be doing with the 5V gate-source you show in the schematic). The Rds(on) value is the only one you really care about. You can actually look at the figures in the Datasheet to see where you would be operating. In Fig.1 you can see that in order to get in saturation with a gate-source voltage of 5 V, you would need a drain-source current of 3 A. With your 9 V battery that would mean you have a maximum 3 Ohm total load. You can use the same graphs to figure out the Rdson. With a gate-source of 5 V, you can see that we have about 200 mV drain-source voltage for 1A drain-source current, or about 200 mOhm. Of course this gets worse with higher temperature, see Fig.4 for that. As to what you should model the device with: Depends on what you are doign. If it is a simple DC circuit hand-calculation, the Rds(on) will suffice probably. A: For ON(mosfet conducts) part of the operation, what should I replace MOSFET with? Rds(on)? If you look in the data sheet, figure 1 will give you a lot of information: - With a \$V_{GS}\$ of 4.5 volts and a drain current of 1 amp, the MOSFET will be dropping about 1 volt. So if the supply voltage is 10 volts and the load were 9 ohms you'd get 9 volts across the load and 1 volt dropped between drain and source. If \$V_{GS}\$ was 5 volts you can see that with a 1 amp load current, the volt drop is only 0.2 volts hence a 9.8 ohm load on a 10 volt supply would see around 9.8 volts across it with the MOSFET only losing 0.2 volts. If \$V_{GS}\$ was 15 volts a ten amp drain current would only drop typically 0.9 volts. I never try and replace the MOSFET with a single figure for RDS(on) because it just doesn't give me the full story - I always look at the data in the graph above. In which operation region a MOSFET should be operated for switching applications? The graph above depicts that - for an NMOS both voltage and current are positive. When operating the MOSFET with a "reduced gate drive" you have to be aware of the temperature coefficients that can cause thermal runaway. See this graph below from the IRF530: - I've marked on the graph the ZTC point - this means the zero temperature coefficient point and basically it means that with a gate source voltage below circa 5.7 volts, there is a possibility that as the device warms up, it's drain current will increase causing more warming and hence more drain current and therefore thermal runaway. For instance, at a gate drive of 4 volts, the drain current will be typically 0.1 amps and, if the power supply drain-source voltage is (say) 10 volts, the MOSFET power dissipation will be 1 watt and this will warm the MOSFET causing more drain current heading towards 1.2 amps on the graph. Now the MOSFET is dissipating 12 watts and rapidly heading to heaven. It will self-destruct without a heatsink. So, if a switching application is being targeted use a MOSFET gate drive voltage greater than 5.7 volts plus a safety margin.
{ "pile_set_name": "StackExchange" }
Q: TypeERROR after yarn upgrade (ReactJS project) I ran the command yarn upgrade and then I got this error next time I did yarn start, and I have no idea why? Hoping someone can tell me whats going on here? No idea what to do to solve it. Tried googling it, without much luck as to what is wrong. TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined at validateString (internal/validators.js:113:11) at Object.join (path.js:375:7) at noopServiceWorkerMiddleware (C:\Users\perni\Projects\prime\node_modules\react-dev-utils\noopServiceWorkerMiddleware.js:14:26) at Layer.handle [as handle_request] (C:\Users\perni\Projects\prime\node_modules\express\lib\router\layer.js:95:5) at trim_prefix (C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:317:13) at C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:284:7 at Function.process_params (C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:335:12) at next (C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:275:10) at launchEditorMiddleware (C:\Users\perni\Projects\prime\node_modules\react-dev-utils\errorOverlayMiddleware.js:20:7) at Layer.handle [as handle_request] (C:\Users\perni\Projects\prime\node_modules\express\lib\router\layer.js:95:5) at trim_prefix (C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:317:13) at C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:284:7 at Function.process_params (C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:335:12) at next (C:\Users\perni\Projects\prime\node_modules\express\lib\router\index.js:275:10) at handleWebpackInternalMiddleware (C:\Users\perni\Projects\prime\node_modules\react-dev-utils\evalSourceMapMiddleware.js:42:7) at Layer.handle [as handle_request] (C:\Users\perni\Projects\prime\node_modules\express\lib\router\layer.js:95:5) A: Try running yarn cache list to print out your cached packages, then you can compare with the version in your package.json to make sure they match. If you still get errors, run yarn cache clean to clear your entire cache and run yarn install to repopulate them.
{ "pile_set_name": "StackExchange" }
Q: "Error Code: 2014. Commands out of sync; you can't run this command now" while creating a trigger I am trying to write a trigger that in case of inserting will do following: 1)count number of seats in the plane 2)count number of passengers that are already on this flight 3)compare these values and insert new row into the table OR raise an error saying that there are no more free seats in the plane. Here is my code: DELIMITER // USE AIRPORT; CREATE TRIGGER CHECK_FOR_PLACES BEFORE INSERT ON TICKET FOR EACH ROW BEGIN DECLARE NUM_OF_PLACES INT; DECLARE NUM_OF_PASSENGERS INT; SET NUM_OF_PLACES := (SELECT CAPACITY FROM AIRPLANE INNER JOIN FLIGHT ON FLIGHT.ID_AIRPLANE = AIRPLANE.ID_AIRPLANE WHERE FLIGHT.ID_FLIGHT = NEW.ID_FLIGHT); SET NUM_OF_PASSENGERS := (SELECT COUNT(*) FROM TICKET WHERE TICKET.ID_FLIGHT = NEW.ID_FLIGHT); IF NUM_OF_PASSENGERS >= NUM_OF_PLACES THEN SIGNAL SQLSTATE '-20000' SET MESSAGE_TEXT = 'NO MORE PLACES ON THIS FLIGHT'; END IF; END// DELIMITER ; After trying to compile the script I get the following error: Error Code: 2014. Commands out of sync; you can't run this command now I have no idea what might be the reason of this error. I'd appreciate any help. Thanks in advance A: use airport is a separate statement, should be terminated by // since you changed the delimiter: DELIMITER // USE AIRPORT// ...
{ "pile_set_name": "StackExchange" }
Q: Rails Devise: two different after_update_path_for I have two pages rendering the update user form of Devise. The classic one (users/edit) and a '/page' page with just a part of the full edit form. I would like to have two different after_update_path whether the form is submited to one or the other page. I tried several things but I none are working... def after_update_path_for(resource) if current_page?('/page') :page else :root_path end end I get the following error: undefined method `current_page?' for #RegistrationsController:0x007fe9db304e28 Did you mean? current_user Any idea if it's possible to do that? A: Looks like you need to include ActionView::Helpers::UrlHelper, as the method is undefined in that controller. class Users::RegistrationsController < Devise::SessionsController include ActionView::Helpers::UrlHelper def after_update_path_for(resource) if current_page?( '/path' ) render :page else render :root_path end end end Here's the docs for the method. Note the comment above: The default url to be used after updating a resource. You need to overwrite this method in your own RegistrationsController. If for some reason this doesn't work in rails 3, you could try to do something like this: def after_update_path_for(resource) if params[:action] == 'my_action' && params[:controller] == 'my_controller' render :page else render :root_path end end
{ "pile_set_name": "StackExchange" }
Q: What should I do/study in high school if I want to be a software project manager? I'm in high school and I'm curious about what I can do now to increase my knowledge about software management. What should I know about software management to better my chances of becoming a manager? How can I get 'real-world' experience at this stage that's as valuable as possible? A: My honest advice is that there is so much time and "cognitive distance" between high school and a professional career in management, that I would say "take classes you love and will do well in" Go to college/university and discover your passion and career interests there. If you are successful and want to move into management, then you have many options. There are just too many "good paths" into management: I've seen English Majors, Art Majors, History Majors, Biology Majors, CS Majors, EE Majors, and I'm a Physics Major myself. If you want to focus on software, then do something that keeps you coding and developing. having domain experience is a huge help for any management position. Don't be afraid to change directions and try new things. If you really love Project Management, there will always be opportunities... good luck and enjoy the trip! A: Find some projects to manage. The principles of project management apply across all different types of activities. You could help work on a website, blog or coordinate a group event. I would focus on doing something that entails gathering requirements from somebody, working with another person or group of people to produce the deliverable that meets those requirements then deliver the project.
{ "pile_set_name": "StackExchange" }
Q: How to get screen resolution in C++? Possible Duplicate: How to get the Monitor Screen Resolution from an hWnd? Is there a way to get the screen resolution in C++? I have searched MSDN but with no luck. The closest thing I found was ChangeDisplaySettingsEx() but that doesn't seem to have a way to just return the res without changing it. A: #include "wtypes.h" #include <iostream> using namespace std; // Get the horizontal and vertical screen sizes in pixel void GetDesktopResolution(int& horizontal, int& vertical) { RECT desktop; // Get a handle to the desktop window const HWND hDesktop = GetDesktopWindow(); // Get the size of screen to the variable desktop GetWindowRect(hDesktop, &desktop); // The top left corner will have coordinates (0,0) // and the bottom right corner will have coordinates // (horizontal, vertical) horizontal = desktop.right; vertical = desktop.bottom; } int main() { int horizontal = 0; int vertical = 0; GetDesktopResolution(horizontal, vertical); cout << horizontal << '\n' << vertical << '\n'; return 0; } Source: http://cppkid.wordpress.com/2009/01/07/how-to-get-the-screen-resolution-in-pixels/
{ "pile_set_name": "StackExchange" }
Q: How to disable Warnings of Visual Studio 2012? I have this error: error C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. and similar errors pop up when I use other old C functions. My question is: Is there a way that these errors show up like Warnings, without actually preventing the code from compiling ? A: You must define _CRT_SECURE_NO_WARNINGS in the preprocessor settings of your project, or #define _CRT_SECURE_NO_WARNINGS at the beginning of your file where you use fopen(). Or just use fopen_s() instead.
{ "pile_set_name": "StackExchange" }
Q: Area of overlap of two circular Gaussian functions I am trying to write code that finds the overlap of between 3D shapes. Each shape is defined by two intersecting normal distributions (one in the x direction, one in the y direction). Do you have any suggestions of existing code that addresses this question or functions that I can utilize to build this code? Most of my programming experience has been in R, but I am open to solutions in other languages as well. Thank you in advance for any suggestions and assistance! The longer research context on this question: I am studying the use of acoustic space by insects. I want to know whether randomly assembled groups of insects would have calls that are more or less similar than we observe in natural communities (a randomization test). To do so, I need to randomly select insect species and calculate the similarity between their calls. For each species, I have a mean and variance for two call characteristics that are approximately normally distributed. I would like to use these two call characteristics to build a 3D probability distribution for the species. I would then like to calculate the amount by which the PDF for one species overlaps with another. Please accept my apologies if the question is not clear or appropriate for this forum. A: I work in small molecule drug discovery, and I frequently use a program (ROCS, by OpenEye Scientific Software) based on algorithms that represent molecules as collections of spherical Gaussian functions and compute intersection volumes. You might look at the following references, as well as the ROCS documentation: (1) Grant and Pickup, J. Phys. Chem. 1995, 99, 3503-3510 (2) Grant, Gallardo, and Pickup, J. Comp. Chem. 1996, 17, 1653-1666
{ "pile_set_name": "StackExchange" }
Q: how to change width of without affecting width I have here 2 photos. 1 is my HTML page and the other one is my print page. My question is, how am I going to make my print page the same as my html page? As you can see, the print page is less wide than the HTML page. Also, I want to ask how am I going to make the width of <th> longer without affecting the width of <td>? Is that possible? Sorry, I don't have that much knowledge in CSS. Print Page HTML Page and here is my code: <table width="100%" border="1"> <tr> <th align="left" width="20%">II. Documentation</th> </tr> <tr> <td align="center">Subject Routine</td> <td width="20%" align="center">Person-in-charge</td> <td width="15%" align="center">Complied</td> <td width="10%" align="center">Date</td> <td width="17%" align="center">Remarks</td> <td align="center">Signature</td> </tr> <tr> <td>1. Travel Documents</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>2. National License</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>3. NAC Certificates/MARINA COP</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>4. Medical</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>5. POEA / AMOSUP Contracts</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>6. Flag License</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>7. US Visa</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>8. Joining Port Visa</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>9. Other Certificate</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </table> A: To get a nice print page width use media queries for example: @media print { @page { margin: 30mm; size:297mm 210mm; } } Or use diffent stylesheets with different widths in stead of the same 100% <link href="style.css" rel="stylesheet" type="text/css" media="screen"> <link href="style_print.css" rel="stylesheet" type="text/css" media="print"> And in the style.css add: table {width:100%} And in style_print.css add: table {width:297mm} Play with the widths untill you are happy in both ;) Here are some great posts on how to set up CSS for printing: https://www.smashingmagazine.com/2011/11/how-to-set-up-a-print-style-sheet/ https://www.smashingmagazine.com/2015/01/designing-for-print-with-css/ Just add colspan="6" to your th to set the correct width of your first cell. <table width="100%" border="1"> <tr> <th colspan="6" align="left" width="20%">II. Documentation</th> </tr> <tr> <td align="center">Subject Routine</td> <td width="20%" align="center">Person-in-charge</td> <td width="15%" align="center">Complied</td> <td width="10%" align="center">Date</td> <td width="17%" align="center">Remarks</td> <td align="center">Signature</td> </tr> <tr> <td>1. Travel Documents</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>2. National License</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>3. NAC Certificates/MARINA COP</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>4. Medical</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>5. POEA / AMOSUP Contracts</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>6. Flag License</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>7. US Visa</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>8. Joining Port Visa</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td>9. Other Certificate</td> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </table>
{ "pile_set_name": "StackExchange" }
Q: How to apply my own function with r::apply() I have following dataframe GRATE GSHAPE 1 0.04 1.0 2 0.08 0.5 3 0.12 2.0 I want to compute a new column COL by following function myfun = function (Rmax=150, precision=0.1, grate, gshape){ s = seq(0,Rmax,precision) R = pgamma(s, rate=grate, shape=gshape) Rc = 1-R Rc2 = Rc^2 Rc2ds = Rc2*precision intRc2ds = sum(Rc2ds, na.rm=TRUE) return(intRc2ds) } This is not working correctly: mydf$COL = apply(mydf, 2, myfun, grate=mydf$GRATE, gshape=mydf$GSHAPE) How should I do this? A: What do you wish to accomplish exactly? Making it run across columns doesn't make sense, because then you never have both a grate and gshape, but only one at a time. If you want to make it run across rows (so that you get an answer for the combinations of grate and gshape presented in your rows), this code works: mydf$COL = apply(mydf, 1, function(x) {myfun(grate=x[1], gshape=x[2])})
{ "pile_set_name": "StackExchange" }
Q: Garbage collection on the JVM for anonymous variable I have a theoretical question I can't find an answer to - Assuming I have a singelton instance A with inner private member a and a public setter, now let's assume I set this member from another instance of class type B in a private method as a consequence to some event i.e. if something happen I will call A.setA(a) from B's private method. My question is - Once the use in instance of class B is over and the instance of class A still "lives" in the system, will the instance of class B get garbage collected? That is if B use anonymous member to init A's a. Thanks in advance. Edit - Code example - public class A { Object a; public void setA(Object a) { this.a = a; } } public class B { private void foo() { if(...condition) { A.getInstance().setA(new Object()); } } } To further explain - the instance of class A is a singleton in the system, there is no other class referencing to the instance of class B and it's done it's part after setting A's private member A: Any object becomes eligible to be collected as garbage as soon as it is no longer considered alive. An object is alive when there is a reference to it from another life object. In other words: as long as that B object is referenced from somewhere, it can't be collected. See here for example. It absolutely does not matter here what code within the B class is doing. The only thing that matters is: is the B object still referenced from somewhere. In that sense you should rather study how GC works in general, see here for example.
{ "pile_set_name": "StackExchange" }
Q: test phonegap BarcodeScanner plgin in xcode simulator I am using the BarcodeScanner PhoneGap plugin to build an ios app, to allow me to scan barcodes. The build gives no errors and the simulator starts fine. In the Xcode simulator however, when I click on the scan link, I get the following error: unable to obtain video capture device Does this mean that I cannot test the app in Xcode, and the only way is to deploy to an actual device? Thanks in advance A A: The iOS Simulator User Guide lists the limitations of the simulator. It states that camera (and so the barcode scanner) can only be tested on a real device. However you could capture some scanning results on a real device and use them to test your code in the simulator.
{ "pile_set_name": "StackExchange" }
Q: Trigger is not working in SQL Server 2012 on runtime? In SQL Server 2012, I create two tables TABLE1 and TABLE2 After that, I created a trigger for TABLE1 Trigger name: PUSH_TABLE2 SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TRIGGER [dbo].[PUSH_TABLE2] ON [dbo].[TABLE1] AFTER INSERT AS BEGIN DECLARE @col1 VARCHAR(20), @col2 VARCHAR(20), @col3 VARCHAR(20) SELECT @col1=column1, @col2=column2, @col3=column3 FROM INSERTED SET NOCOUNT ON; INSERT INTO [dbo].[TABLE2] VALUES (@col1, @col2, @col3); END After creating the trigger PUSH_TABLE2, I test with below insert query manually on TABLE1, triggers works perfectly and its populate the data to both TABLE1 and TABLE2. INSERT INTO TABLE1 VALUES('session1', 'value1', 'type1'); (1) rows affected. (1) rows affected. The problem is if the data is populated through application, it will only populate the data to TABLE1 only, seems trigger is not working. Is it because of my trigger script problem? A: The problem is that your trigger only handles single-row inserts. That was as true in SQL Server 2008 as it is in SQL Server 2012. Given two tables: CREATE TABLE dbo.Table1 ( col1 varchar(20) NULL, col2 varchar(20) NULL, col3 varchar(20) NULL ); CREATE TABLE dbo.Table2 ( col1 varchar(20) NULL, col2 varchar(20) NULL, col3 varchar(20) NULL ); A trigger that handles multi-row inserts is: CREATE TRIGGER dbo.PushTable2 ON dbo.Table1 AFTER INSERT AS BEGIN SET ROWCOUNT 0; SET NOCOUNT ON; IF EXISTS (SELECT * FROM Inserted) BEGIN INSERT dbo.Table2 ( col1, col2, col3 ) SELECT INS.col1, INS.col2, INS.col3 FROM Inserted AS INS END; END; Test it with: INSERT dbo.Table1 (col1, col2, col3) VALUES ('session1', 'value1', 'type1'); INSERT dbo.Table1 (col1, col2, col3) VALUES ('session2', 'value2', 'type2'), ('session3', 'value3', 'type3'); SELECT * FROM dbo.Table1 AS T1; SELECT * FROM dbo.Table2 AS T2; Results:
{ "pile_set_name": "StackExchange" }
Q: How Do I Use C# Code In HTML To Get ID Out Of A SQL Database? So I'm trying to create a website with a database and currently just wanting to check the database connnection by printing a number from the database in the HTML code. I'm terrible at scripts so please ignore that. The C# code: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.SqlClient; public class LogFiller { public int userID; string connectionstring = "USER ID=x;" + "PASSWORD=x;server=x;" + "Trusted_Connection=yes;" + "database=x; " + "connection timeout=30"; public LogFiller() { // // TODO: Add constructor logic here // } public int getUserID { get { using (var connection = new SqlConnection(connectionstring)) { try { connection.Open(); SqlCommand myCommand = new SqlCommand("SELECT ID FROM x WHERE Name = 'x'", connection); SqlDataAdapter adapter = new SqlDataAdapter(myCommand); DataTable dt = new DataTable(); adapter.Fill(dt); return (int)dt.Rows[0][0]; } catch (Exception e) { Console.WriteLine(e.ToString()); } } return userID; } } } The script I thought of (but doesn't work) @{ LogFiller lf = new LogFiller(); lf.getUserID; } For clarification: I want to just write the number that the C# code returns anywhere on my page. A: Once you open a C# block with the @{ }, in order to write the value from a variable inside that block you need to escape it with another @ like this: @{ LogFiller lf = new LogFiller(); <p>User ID: @lf.getUserID</p> } Also, as someone in a comment stated, you'll likely need to fully qualify your LogFiller type with the namespace. So WhateverYourNamespaceIs.LogFiller
{ "pile_set_name": "StackExchange" }
Q: Deserialize JSON with Gson - Expected BEGIN_OBJECT but was String - Reddit's JSON I'm trying to deserialize JSON from Reddit that you can obtain by appending .json to the url. An example would be: http://www.reddit.com/r/pics/comments/1wvx52/.json?sort=top However, I am getting the error message: Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 9765 At line 1 column 9765 in the json there is the following code: "replies": "", whereas normally this would contain an object like this: replies: { kind: "Listing", data: {} }, Does this mean that the json is a String when there is no data, but an object otherwise? How can I deserialize with gson properly if this is the case? I've included my classes below. I still need to figure out how to handle the json starting off with an array of basically two different objects (the first listing in the json is describing the link, while the second listing is describing the comments), but I'll cross that bridge when I get there. Thanks in advance if anyone can shed some light on this issue. Main Class public static void main(String[] args) { ArrayList<CommentsResults> commentsResults = new ArrayList<CommentsResults>(); String commentsURL = "http://www.reddit.com/r/pics/comments/1wvx52/.json?sort=top"; URL url = null; try { url = new URL(commentsURL); } catch (MalformedURLException ex) { System.out.println(ex.getMessage()); } try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); String jsonText = readAll(bufferedReader); Gson gson = new GsonBuilder().create(); commentsResults = gson.fromJson(jsonText, new TypeToken<ArrayList<CommentsResults>>(){}.getType()); } catch (IOException ex) { System.out.println(ex.getMessage()); } } private static String readAll(Reader reader) throws IOException { StringBuilder stringBuilder = new StringBuilder(); int cp; while ((cp = reader.read()) != -1) { stringBuilder.append((char) cp); } return stringBuilder.toString(); } CommentsResults Class public class CommentsResults { private String kind; private CommentsData data; public CommentsResults() { } public CommentsResults(String kind, CommentsData data) { this.kind = kind; this.data = data; } public String getKind() { return kind; } public CommentsData getData() { return data; } public void setKind(String kind) { this.kind = kind; } public void setData(CommentsData data) { this.data = data; } } CommentsData Class private String modhash; private List <CommentsChild> children; public CommentsData() { } public CommentsData(String modhash, List<CommentsChild> children) { this.modhash = modhash; this.children = children; } public String getModhash() { return modhash; } public List<CommentsChild> getChildren() { return children; } public void setModhash(String modhash) { this.modhash = modhash; } public void setChildren(List<CommentsChild> children) { this.children = children; } CommentsChild Class private String kind; private Comment data; public CommentsChild() { } public CommentsChild(String kind, Comment comment) { this.kind = kind; this.data = comment; } public String getKind() { return kind; } public Comment getComment() { return data; } public void setKind(String kind) { this.kind = kind; } public void setComment(Comment comment) { this.data = comment; } Comment Class public class Comment { private CommentsResults replies; private String id; private int gilded; private String author; private String parent_id; private String body; private int downs; private String link_id; private boolean score_hidden; private int created_utc; private String distinguished; public Comment() { } public Comment(CommentsResults replies, String id, int gilded, String author, String parent_id, String body, int downs, String link_id, boolean score_hidden, int created_utc, String distinguished) { this.replies = replies; this.id = id; this.gilded = gilded; this.author = author; this.parent_id = parent_id; this.body = body; this.downs = downs; this.link_id = link_id; this.score_hidden = score_hidden; this.created_utc = created_utc; this.distinguished = distinguished; } public CommentsResults getReplies() { return replies; } public String getId() { return id; } public int getGilded() { return gilded; } public String getAuthor() { return author; } public String getParent_id() { return parent_id; } public String getBody() { return body; } public int getDowns() { return downs; } public String getLink_id() { return link_id; } public boolean isScore_hidden() { return score_hidden; } public int getCreated_utc() { return created_utc; } public String getDistinguished() { return distinguished; } public void setReplies(CommentsResults replies) { this.replies = replies; } public void setId(String id) { this.id = id; } public void setGilded(int gilded) { this.gilded = gilded; } public void setAuthor(String author) { this.author = author; } public void setParent_id(String parent_id) { this.parent_id = parent_id; } public void setBody(String body) { this.body = body; } public void setDowns(int downs) { this.downs = downs; } public void setLink_id(String link_id) { this.link_id = link_id; } public void setScore_hidden(boolean score_hidden) { this.score_hidden = score_hidden; } public void setCreated_utc(int created_utc) { this.created_utc = created_utc; } public void setDistinguished(String distinguished) { this.distinguished = distinguished; } } A: So in the off chance this helps somebody (which seems dubious at this point) I decided to parse the Json manually using recursion. Here's how I did it: public static void getCommentsOnLink() { String commentsURL= "http://www.reddit.com/r/pics/comments/1wvx52/.json?sort=top"; URL url = null; try { url = new URL(commentsURL); } catch (MalformedURLException ex) { System.out.println(ex.getMessage()); } String JsonText = readCommentJsonFromURL(url); RedditCommentResults redditCommentResults = getCommentResults(JsonText); } private static String readCommentJsonFromURL(URL url) { String JSONText = null; try { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); JSONText = readAll(bufferedReader); } catch (IOException ex) { System.out.println(ex.getMessage()); } return JSONText; } private static String readAll(Reader reader) throws IOException { StringBuilder stringBuilder = new StringBuilder(); int cp; while ((cp = reader.read()) != -1) { stringBuilder.append((char) cp); } return stringBuilder.toString(); } private static RedditCommentResults getCommentResults(String JsonText) { JsonParser parser = new JsonParser(); JsonArray completeJson = (JsonArray) parser.parse(JsonText); //get link and comment object from the array containing an object for each JsonObject linkParentJson = (JsonObject) completeJson.get(0); JsonObject commentParentJson = (JsonObject) completeJson.get(1); //use automatic deserializer for redditLink JsonObject linkListingDataJson = linkParentJson.getAsJsonObject("data"); JsonObject linkChildrenJson = linkListingDataJson.getAsJsonArray("children").get(0).getAsJsonObject(); JsonObject linkDataJson = linkChildrenJson.getAsJsonObject("data"); Link commentLink = gson.fromJson(linkDataJson, Link.class); RedditLink redditCommentLink = new RedditLink(commentLink); //parse comments manually JsonObject commentDataJson = commentParentJson.getAsJsonObject("data"); JsonArray commentChildrenJson = commentDataJson.getAsJsonArray("children"); //get all of the comments from the JsonArray ArrayList<RedditComment> redditComments = getNestedComments(commentChildrenJson); RedditCommentResults redditCommentResults = new RedditCommentResults(redditComments, redditCommentLink); return redditCommentResults; } private static ArrayList<RedditComment> getNestedComments(JsonArray commentWrapperJsonArray) { ArrayList<RedditComment> redditComments = new ArrayList(); for (JsonElement commentWrapperJson : commentWrapperJsonArray) { //cast Element to Object so we can search for the primitive "kind". Finally we get it as a String String kind = commentWrapperJson.getAsJsonObject().getAsJsonPrimitive("kind").getAsString(); //if the comment is of type t1 meaning it is a comment and not a "more" (a "more" is a comment which //hasn't been loaded yet because it does not have a great deal of upvotes relative to other comments) if (kind.equals("t1")) { JsonObject commentJson = commentWrapperJson.getAsJsonObject().getAsJsonObject("data"); Comment comment = gson.fromJson(commentJson, Comment.class); RedditComment redditComment = new RedditComment(comment); JsonElement repliesJson = commentJson.get("replies"); //if the reply is not equal to an empty String (i.e. if there is at least one reply) if (!repliesJson.isJsonPrimitive()) { JsonObject dataJson = repliesJson.getAsJsonObject().getAsJsonObject("data"); JsonArray childrenJson = dataJson.getAsJsonArray("children"); ArrayList<RedditComment> nestedComments = getNestedComments(childrenJson); redditComment.setReplies(nestedComments); } redditComments.add(redditComment); } } return redditComments; }
{ "pile_set_name": "StackExchange" }
Q: How to make a variables within a constructor call methods? So I am doing an assignment that is based around the energy consumption within a house. I have created a Person constructor that emulates a person within the house. I now want to make that person perform a task which is to have a shower. I have added the task into the Person class and now I need to call it in a timePasses() method. The assignment is about registering the amount of energy consumption used up by applications within a house during a 1 day period. I have created appliances such as PowerShowerthat has a shower() method which reads the amount of energy consumption used by that appliance. Now I have been asked to create a Person class which has people that us these appliances. So I have created a constructor to store the details of the person and now I want to make that person call the PowerShower.shower() method to emulate them using that appliance. I'm having trouble with figuring out how to actually make a person do this task which is what I need help with. Here is what I have so far: public abstract class Person { public int personAge; public String personName; PowerShower callPowerShower = new PowerShower(1,1,1,1); Person(int personAge, String personName) { this.personAge = personAge; this.personName = personName; } public void addTask() { callPowerShower.shower(); } public void timePasses() { //Make Person execute task callPowerShower.shower(). } } How would I make a person perform the task? Any help is appreciated, thanks. A: Assuming shower takes a Person Object as a parameter? Person bob = new Person(25,"Bob"); PowerShower callPowerShower = new PowerShower(1,1,1,1); callPowerShower.shower(bob)
{ "pile_set_name": "StackExchange" }
Q: Arduino Assembler programming: Nothing happens Hi StackOverflow community, I am trying to program my old Arduino Duemilanove Board (Atmega 168V-10PU) in Assembler. I tried it a few times before but everytime the code was not executed. So i tried to program an equivalent test program in C, and it worked. Here it is: // file led.c #include <avr/io.h> int main(void) { DDRB = 0xFF; PORTB = 0xFF; while (1) { asm("nop\n"); } return 0; } The asm dump of the compiler results in (shortened), ldi r24,lo8(-1) ; tmp44, out 0x4,r24 ; MEM[(volatile uint8_t *)36B], tmp44 out 0x5,r24 ; MEM[(volatile uint8_t *)37B], tmp44 which works and activates the LED at Arduino Pin 13 (AVR pin PB5). But when I use this asm file, // file led.S #include "avr/io.h" .global main main: ldi r24, 0xFF out DDRB, r24 out PORTB, r24 end: jmp end the compiler dump results in (shortened), ldi r24, 0xFF out ((0x04) + 0x20), r24 out ((0x05) + 0x20), r24 what might explain why nothing happens. In addition here are the makefiles for the C version and the Assembler version Thanks for helping! EDIT: Here are also the full assembler dump files of the C version and the Assembler version EDIT 2: I looked up the register addresses in the include file iom168.h, which references to iomx8.h, where it says #define PORTB _SFR_IO8 (0x05). The compiler follows the include chain io.h -> iom168.h -> iomx8.h io.h -> common.h -> sfr_defs.h In sfr_defs.h is written: #define _SFR_IO8(io_addr) ((io_addr) + __SFR_OFFSET) A few more lines upwards the offset is defined: #ifndef __SFR_OFFSET /* Define as 0 before including this file for compatibility with old asm sources that don't subtract __SFR_OFFSET from symbolic I/O addresses. */ # if __AVR_ARCH__ >= 100 # define __SFR_OFFSET 0x00 # else # define __SFR_OFFSET 0x20 # endif #endif (Sorry for the formatting) Any idea where this error comes from? A: You should use the helper macros _SFR_IO_ADDR() and _SFR_MEM_ADDR() to access SFRs using i/o and memory instructions, respectively, because they have different addresses in the two namespaces. The default is apparently memory mapped, but don't count on it. As such your code could look like: #include "avr/io.h" .global main main: ldi r24, 0xFF out _SFR_IO_ADDR(DDRB), r24 out _SFR_IO_ADDR(PORTB), r24 end: jmp end Or, you can switch to memory mapped access: #include "avr/io.h" .global main main: ldi r24, 0xFF sts _SFR_MEM_ADDR(DDRB), r24 sts _SFR_MEM_ADDR(PORTB), r24 end: jmp end
{ "pile_set_name": "StackExchange" }
Q: iOS and Google api I am developing an app that will make a google search from a text input entered by the user. My question is, do i need to use the google api or is it possible to just make a URL fetch with the user text, like so: user entered "Skype" NSURLSessionConfiguration * config = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession * session = [NSURLSession sessionWithConfiguration:config]; NSURLRequest * request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:@"https://www.google.com/search?q=%@"], userInput]; NSURLSessionDataTask *data = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSDictionary *theDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; NSLog(@"%@", theDic); }]; [data resume]; and in the returned data i will get all the results from the search "Skype". Is it possible? thanks, A: You're definitely going to want to use the actual API. You'll need to sign up and get an API key. Using the regular web search URL will give you back a webpage as a result, which is probably not want you want for interacting with in an iOS app. Here is a link to the API and here is a link to this specific API call. Your query will look something like this: https://www.googleapis.com/customsearch/v1?key=<YOUR API KEY>&q=<YOUR QUERY>&cx=<CUSTOM SEARCH ENGINE ID> Here is an answer with more info about the Custom Search API.
{ "pile_set_name": "StackExchange" }
Q: How do I run drush migrate for specific path site I want to use drush to run the migrate command to upgrade my drupal version 6 to 7 using Data Export Import module. I have two site in different path. How do I run drush migrate for the Testing website below. Drupal version is 6. Main website /domains/site.com/public_html Testing website /domains/site.com/public_html/testsite A: To use Drush to more effectively migrate sites from one VPS to another, to manage more than one site and to synchronize easily between them. It assumes that you are running your own cloud server, have Drush on it, and have already installed a Drupal site. Drush Aliases Drush aliases are a simple set of configuration that allows you to reference Drupal sites from anywhere in your server's folder structure by using a shortcut of the following format @site. Before being able to use these shortcuts though, you'll need to configure the respective alias. To do this, and if you don't have one already, create a file called aliases.drushrc.php in the .drush folder that resides in your server's root folder: nano /root/.drush/aliases.drushrc.php Here, you have to create a php opening tag, <?php, for the file and below copy the following array declaration: $aliases['site1'] = array( 'root' => '/var/www/drupal_folder', 'uri' => '88.88.88.88/drupal_folder', ); Save the file, exit, and the alias is set. To test it out, navigate to a folder that is outside of your Drupal site and run the following command: drush @site1 status Now you should get the regular status information about the site you just referenced in the alias. And you can use this shortcut also with other commands. Migrating sites Now that you know how to reference sites, we can look at migrating (copying) a site from one folder to another using Drush. Let's say you want to move @site1 from /var/www/drupal_folder to /var/www/drupal_folder2. First, you need to create a new alias for this future installation. For this, like always, edit the aliases.drushrc.php file: nano /root/.drush/aliases.drushrc.php Here, you need to create below two aliases, both with the same format. Just copy-paste the old one and make the appropriate changes: $aliases['site2'] = array( 'root' => '/var/www/drupal_folder2', 'uri' => '88.88.88.88/drupal_folder2', ); Save the file and exit. If you run drush @site2 status, it will not work because obviously the folder not only does not contain a Drupal installation, but it doesn't even exist. So let's create it: mkdir /var/www/drupal_folder2 In order to prepare for the new Drupal installation, you'll need to create a new database as well. So login to your MySQL through your preferred way and create a new database, making a note of the access username and password. If you are unsure how to do this, read the tutorial that shows how to deploy a Drupal site with Drush. Now that your database is set up, you can proceed to migrate the site. To copy all the codebase from the first folder to the other, run the following command: drush core-rsync @site1 @site2 --include-conf Now, edit this newly copied settings.php file in the drupal_folder2 copy and change the database information to reflect the new database you just created. nano /var/www/drupal_folder2/sites/default/settings.php In this file, you need to make changes to the following block of code to reflect your own database information: $databases = array ( 'default' => array ( 'default' => array ( 'database' => 'your_db', 'username' => 'your_username', 'password' => 'your_password', 'host' => 'localhost', 'port' => '', 'driver' => 'mysql', 'prefix' => '', ), ), ); Save the file and exit. Now you can also migrate the database using Drush because it knows that the site in the drupal_folder2 now uses this database, even if it's currently empty. All you need to do is run the following command: drush sql-sync @site1 @site2 --create-db This will drop the tables in the database associated with @site2 (the one that is currently empty) due to the --create-db option and insert the ones from the database associated with @site1 - your original Drupal installation. So now you have 2 exact replicas of the same site. You may run into the following error message (with the applicable credentials): ERROR 1044 (42000) at line 1: Access denied for user 'your_username'@'localhost' to database 'your_db' If this is the case, make sure that your user has the required privileges. Log into MySQL (mysql -u root -p). Grant the following privileges: grant all privileges on your_db.* to your_username@localhost with grant option; grant reload on *.* to druser2@localhost; flush privileges; Synchronizing Drupal Sites Now that you have a duplicate of your original site (@site2), you can use it for development work. If you make codebase modifications to it, you can use the core-rsync command to sync the files with the original (@site1): drush core-rsync @site2 @site1 Obviously, you would not want to copy the settings.php file again, which prevents making database changes again. Next, to sync the database as well, run the same sql-sync command: drush sql-sync @site2 @site1 --create-db In most cases, it's recommended that the receiving database is emptied before the copy (using the --create-db option) to avoid conflicting configuration saved in the database that will then cause problems. Remote sites nano /root/.drush/aliases.drushrc.php And let's create a new alias for a site on a remote server. Copy the following code below and replace appropriately with your information: $aliases['site3'] = array( 'root' => '/var/www/drupal_folder3', 'uri' => '99.99.99.99/drupal_folder3', 'remote-host' => '99.99.99.99' ); So, what does this mean? The site with the alias @site3 is located in the folder drupal_folder3 on the remote server and has that URI pointing to it on the remote server. This is to be expected. Additionally, you have to specify the remote host (which is the IP address of the remote host). Given that you have set up SSH keys, you will not be required to enter a password unless of course you have a password protecting your private SSH key itself, which I recommend if you are creating keys between two remote hosts (none being your personal computer). And that's it. Now when you run the commands we've be talking about, you can perform the same actions remotely, as well as migrating and keeping sites synchronized. But just to test out the alias, run: drush @site3 status
{ "pile_set_name": "StackExchange" }
Q: Center element inside div (circle) How to center element inside circle. Here is example how is now https://codepen.io/anon/pen/JNmEVB. What I need to make to center inside div. I am trying with margin: 0 auto; but nothig :(. Do you guys any ideas how to make this. I need to center counter inside circle Html <body> <div id="del-countdown"> <div id="clock"></div> <div id="units"> <span>Hours</span> <span>Minutes</span> <span>Seconds</span> </div> </div> </body> Css * { margin:0; padding:0; box-sizing:border-box; } body { font-family: Ubuntu, sans-serif; } h1 { color: #fff; text-align: center; font-size: 74px; letter-spacing: 10px; margin-bottom: 70px; } #del-countdown { width: 600px; height: 600px; margin: 15% auto; background-color: rgba(255, 0, 0, 0.3); border-radius: 50%; border-style: solid; border-color: #0000ff; } #clock span { float: left; text-align: center; font-size: 84px; margin: 0 2.5%; color: #fff; padding: 20px; width: 20%; border-radius: 20px; box-sizing: border-box; } #clock span:nth-child(1) { background: #fa5559; } #clock span:nth-child(2) { background: #26c2b9; } #clock span:nth-child(3) { background: #f6bc58; } #clock:after { content: ''; display: block; clear: both; } #units span { float: left; width: 25%; text-align: center; margin-top: 30px; color: #ddd; text-transform: uppercase; font-size: 13px; letter-spacing: 2px; text-shadow: 1px 1px 1px rgba(10, 10, 10, 0.7); } span.turn { animation: turn 0.7s ease forwards; } @keyframes turn { 0% { transform: rotate(0deg); } 100% { transform: rotate(0deg); } } JS "use strict"; function updateTimer(deadline) { var time = deadline - new Date(); return { hours: Math.floor(time / (1000 * 60 * 60) % 24), minutes: Math.floor(time / 1000 / 60 % 60), seconds: Math.floor(time / 1000 % 60), total: time }; } function animateClock(span) { span.className = "turn"; setTimeout(function () { span.className = ""; }, 700); } function startTimer(id, deadline) { var timerInterval = setInterval(function () { var clock = document.getElementById(id); var timer = updateTimer(deadline); clock.innerHTML = "<span>" + timer.hours + "</span><span>" + timer.minutes + "</span><span>" + timer.seconds + "</span>"; var spans = clock.getElementsByTagName("span"); animateClock(spans[2]); if (timer.seconds == 59){ animateClock(spans[1]); } if (timer.minutes == 59 && timer.seconds == 59){ animateClock(spans[0]); } if (timer.total < 1) { clearInterval(timerInterval); clock.innerHTML = "<span>0</span><span>0</span><span>0</span>"; } }, 1000); } window.onload = function () { var deadline = new Date("Jan 1, 2018 12:00:00"); startTimer("clock", deadline); }; A: You can use flexbox. "use strict"; function updateTimer(deadline) { var time = deadline - new Date(); return { hours: Math.floor(time / (1000 * 60 * 60) % 24), minutes: Math.floor(time / 1000 / 60 % 60), seconds: Math.floor(time / 1000 % 60), total: time }; } function animateClock(span) { span.className = "turn"; setTimeout(function () { span.className = ""; }, 700); } function startTimer(id, deadline) { var timerInterval = setInterval(function () { var clock = document.getElementById(id); var timer = updateTimer(deadline); clock.innerHTML = "<span>" + timer.hours + "</span><span>" + timer.minutes + "</span><span>" + timer.seconds + "</span>"; var spans = clock.getElementsByTagName("span"); animateClock(spans[2]); if (timer.seconds == 59){ animateClock(spans[1]); } if (timer.minutes == 59 && timer.seconds == 59){ animateClock(spans[0]); } if (timer.total < 1) { clearInterval(timerInterval); clock.innerHTML = "<span>0</span><span>0</span><span>0</span>"; } }, 1000); } window.onload = function () { var deadline = new Date("Jan 1, 2018 12:00:00"); startTimer("clock", deadline); }; * { margin:0; padding:0; box-sizing:border-box; } body { font-family: Ubuntu, sans-serif; } h1 { color: #fff; text-align: center; font-size: 74px; letter-spacing: 10px; margin-bottom: 70px; } #del-countdown { width: 600px; height: 600px; margin: 15% auto; background-color: rgba(255, 0, 0, 0.3); border-radius: 50%; border-style: solid; border-color: #0000ff; position: relative; display: flex; align-items: center; justify-content: center; flex-direction: column; } #clock,#units { width: 100%; display: flex; justify-content: center; } #clock span { text-align: center; font-size: 84px; margin: 0 2.5%; color: #fff; padding: 20px; width: 20%; border-radius: 20px; box-sizing: border-box; } #clock span:nth-child(1) { background: #fa5559; } #clock span:nth-child(2) { background: #26c2b9; } #clock span:nth-child(3) { background: #f6bc58; } #clock:after { content: ''; display: block; clear: both; } #units span { width: 25%; text-align: center; margin-top: 30px; color: #ddd; text-transform: uppercase; font-size: 13px; letter-spacing: 2px; text-shadow: 1px 1px 1px rgba(10, 10, 10, 0.7); } span.turn { animation: turn 0.7s ease forwards; } @keyframes turn { 0% { transform: rotate(0deg); } 100% { transform: rotate(0deg); } } <body> <div id="del-countdown"> <div id="clock"></div> <div id="units"> <span>Hours</span> <span>Minutes</span> <span>Seconds</span> </div> </div> </body>
{ "pile_set_name": "StackExchange" }
Q: Bootstrap4 Disabled button white instead of supposed color I am using a bootstrap button on one of my page, that is disabled, and the styling seems to not be working properly <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"> <button disabled class="btn btn-primary">suivant</button> <button class="btn btn-primary disabled">suivant</button> I tried these 2 ways and the result look like this for both approach: initial look || on Mouse over EDIT: Important to mention that i only have bootstrap4, no personnal style sheet and no other themes This is a react Project, className is used instead of class A: https://codepen.io/jacobweyer/pen/ybqxBK I've updated this codepen to show Bootstrap4 buttons with BS4 alpha 6. They look like they show up as intended in and outside of React. <button class="btn btn-primary">suivant</button> <button class="btn btn-primary" disabled>suivant disabled</button>
{ "pile_set_name": "StackExchange" }
Q: Can I disable an account in mysql after x failed login attempts? I would like to disable accounts after x failed login attempts. Is it possible? A: Also you can use fail2ban for this goal as too easily way . In this case you just install it on you linux OS, then enable the section for [mysqld-iptables] in the /etc/fail2ban/jail.local. [mysqld-iptables] enabled = true filter = mysqld-auth action = iptables[name=mysql, port=3306, protocol=tcp] sendmail-whois[name=MySQL, dest=root, sender=fail2ban@example.com] logpath = /var/log/mysqld.log maxretry = 5 This program check the mysql logs by its own given pattern and then blocks the IP addresses which they try to login more than 5 times, in iptables.
{ "pile_set_name": "StackExchange" }
Q: changing the computer name on a IIS 7 Are there any issues in regards to IIS that result from changing the computer name on a IIS 7 server? A: IIS7 (Windows 2008) Does not have the same issue with the userids that IIS6 (Windows 2003) had. You can safely rename your web server.
{ "pile_set_name": "StackExchange" }
Q: can command more read from stdin? It's common to use the command more. more is usually used with pipe. so I think more has the ability to read from stdin. every command separated by pipe is a process, and the one before more just create pipe and dup2 the write pipe to more's stdin. but I found that if I type "more" in the console, just some usages appear. so what is the matter? A: Why do you think that anything is wrong? More pages output for the terminal so what would be the point in waiting for enough typed stdin input to page? If you type more and one or more filenames it will page that input. So the behavior is something like: am I attached to a terminal? ("isatty") are there filenames in argv page files else display help else page pipe input
{ "pile_set_name": "StackExchange" }
Q: Unexpected match of regex I expect the regex pattern ab{,2}c to match only with a followed by 0, 1 or 2 bs, followed by c. It works that way in lots of languages, for instance Python. However, in R: grepl("ab{,2}c", c("ac", "abc", "abbc", "abbbc", "abbbbc")) # [1] TRUE TRUE TRUE TRUE FALSE I'm surprised by the 4th TRUE. In ?regex, I can read: {n,m} The preceding item is matched at least n times, but not more than m times. So I agree that {,2} should be written {0,2} to be a valid pattern (unlike in Python, where the docs state explicitly that omitting n specifies a lower bound of zero). But then using {,2} should throw an error instead of returning misleading matches! Am I missing something or should this be reported as a bug? A: The behavior with {,2} is not expected, it is a bug. If you have a look at the TRE source code, tre_parse_bound method, you will see that the min variable value is set to -1 before the engine tries to initialize the minimum bound. It seems that the number of "repeats" in case the minimum value is missing in the quantifier is the number of maximum value + 1 (as if the repeat number equals max - min = max - (-1) = max+1). So, a{,} matches one occurrence of a. Same as a{, } or a{ , }. See R demo, only abc is matched with ab{,}c: grepl("ab{,}c", c("ac", "abc", "abbc", "abbbc", "abbbbc")) grepl("ab{, }c", c("ac", "abc", "abbc", "abbbc", "abbbbc")) grepl("ab{ , }c", c("ac", "abc", "abbc", "abbbc", "abbbbc")) ## => [1] FALSE TRUE FALSE FALSE FALSE
{ "pile_set_name": "StackExchange" }
Q: Can I use Titan XP on MacBook? Is the Nvidia's Titan XP compatible with Apple's MacBook (mid-2017)? I have never used external GPU but it seems to be that you can use it on MacBook Pro. However, MacBook doesn't have Thunderbolt. Is it possible to use Titan XP on MacBook, with a connector like Thunderbolt to USB 3.1? Is the performance drained via the connector and not a good solution in general? The use cases are deep neural net and I don't use gaming, for your information. A: No you really need a Thunderbolt connection. It wasn't until Thunderbolt 3 that the bandwidth of the protocol fully caught up with the idea. Realizing this, the group responsible for the spec created implementations with the possibility of some configurations being able to pass the video signal back to the computer it was boosting. Using a External GPU with older Thunderbolt connections will not fully utilise the performance increase of an External GPU.
{ "pile_set_name": "StackExchange" }
Q: Adding link tags and rel="lightbox" around images Regex How can i change this example when i just got the <image> tag and i want to add link tags around them and the rel lightbox attribute as well? i cant figure it out. I'm just not good with regular expressions at all. the example $pattern ="/<a(.*?)href=('|\")(.*?).(bmp|gif|jpeg|jpg|png)('|\")(.*?)>/i"; $replacement = '<a$1href=$2$3.$4$5 rel="lightbox" title="'.$post->post_title.'"$6>'; So in my case i have <img src="...." class="...." alt="....."> and i need <a href="....." rel="lightbox" title="....."><img src="...." class="...." alt="....."></a> How would i change this? Thanks for help. A: It's unclear what you exactly want to do here, but I would utilize DOM for this task instead. $doc = DOMDocument::loadHTML(' <img src="www.foo.com/1.gif" class="foo" alt="..."> <img src="www.bar.com/1.jpg" class="bar" alt="..."> <img src="example.com/2.jpg" class="example" alt="..."> '); foreach ($doc->getElementsByTagName('img') as $node) { $link = $node->ownerDocument->createElement('a'); $a = $node->parentNode->insertBefore($link, $node); $a->setAttribute('href', $node->getAttribute('src')); $a->setAttribute('rel', 'lightbox'); $a->setAttribute('title', 'some title'); $a->appendChild($node); } echo $doc->saveHTML(); Output: <a href="www.foo.com/1.gif" rel="lightbox" title="some title"><img src="www.foo.com/1.gif" class="foo" alt="..."></a> <a href="www.bar.com/1.jpg" rel="lightbox" title="some title"><img src="www.bar.com/1.jpg" class="bar" alt="..."></a> <a href="example.com/2.jpg" rel="lightbox" title="some title"><img src="example.com/2.jpg" class="example" alt="..."></a>
{ "pile_set_name": "StackExchange" }
Q: Access private method or Variable in Test Class I want to access Private Method or Variable in Test class.?? A: Read about and use the @TestVisble annotation. From the documentation: Use the TestVisible annotation to allow test methods to access private or protected members of another class outside the test class. These members include methods, member variables, and inner classes. This annotation enables a more permissive access level for running tests only. This annotation doesn’t change the visibility of members if accessed by non-test classes.
{ "pile_set_name": "StackExchange" }
Q: Determine if the VBE is open I'm trying to develop an 'auto run' macro to determine if the VBE is open (not necessarily the window of focus, just open). If this is TRUE then ... take some action. If this macro is connected to a CommandButton it works but I can't get it to function anywhere in the ThisWorkbook: Sub CloseVBE() 'use the MainWindow Property which represents ' the main window of the Visual Basic Editor - open the code window in VBE, ' but not the Project Explorer if it was closed previously: If Application.VBE.MainWindow.Visible = True Then MsgBox "" 'close VBE window: Application.VBE.MainWindow.Visible = False End If End Sub I was given the following FUNCTION to do the same but I can't get it to work either: Option Explicit Private Declare Function FindWindow Lib "User32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long Private Declare Function GetWindowText Lib "User32" Alias "GetWindowTextA" (ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long Private Declare Function GetWindowTextLength Lib "User32" Alias "GetWindowTextLengthA" (ByVal hWnd As Long) As Long Private Declare Function GetWindow Lib "User32" (ByVal hWnd As Long, ByVal wCmd As Long) As Long Private Const GW_HWNDNEXT = 2 Function VBE_IsOpen() As Boolean Const appName As String = "Visual Basic for Applications" Dim stringBuffer As String Dim temphandle As Long VBE_IsOpen = False temphandle = FindWindow(vbNullString, vbNullString) Do While temphandle <> 0 stringBuffer = String(GetWindowTextLength(temphandle) + 1, Chr$(0)) GetWindowText temphandle, stringBuffer, Len(stringBuffer) stringBuffer = Left$(stringBuffer, Len(stringBuffer) - 1) If InStr(1, stringBuffer, appName) > 0 Then VBE_IsOpen = True CloseVBE End If temphandle = GetWindow(temphandle, GW_HWNDNEXT) Loop End Function 1/23/2018 Here is an update to the original question: I located the following code that performs EXACTLY as I was needing but when closing the workbook, the macro errors out on the line indicated: Public Sub StopEventHook(lHook As Long) Dim LRet As Long Set lHook = 0'<<<------ When closing workbook, errors out on this line. If lHook = 0 Then Exit Sub LRet = UnhookWinEvent(lHook) Exit Sub End Sub Here is the entire code, paste this into a regular Module: Option Explicit Private Const EVENT_SYSTEM_FOREGROUND = &H3& Private Const WINEVENT_OUTOFCONTEXT = 0 Private Declare Function SetWinEventHook Lib "user32.dll" (ByVal eventMin As Long, ByVal eventMax As Long, _ ByVal hmodWinEventProc As Long, ByVal pfnWinEventProc As Long, ByVal idProcess As Long, _ ByVal idThread As Long, ByVal dwFlags As Long) As Long Private Declare Function GetCurrentProcessId Lib "kernel32" () As Long Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hWnd As Long, lpdwProcessId As Long) As Long Private pRunningHandles As Collection Public Function StartEventHook() As Long If pRunningHandles Is Nothing Then Set pRunningHandles = New Collection StartEventHook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, 0&, AddressOf WinEventFunc, 0, 0, WINEVENT_OUTOFCONTEXT) pRunningHandles.Add StartEventHook End Function Public Sub StopEventHook(lHook As Long) Dim LRet As Long On Error Resume Next Set lHook = 0 '<<<------ When closing workbook, errors out on this line. If lHook = 0 Then Exit Sub LRet = UnhookWinEvent(lHook) Exit Sub End Sub Public Sub StartHook() StartEventHook End Sub Public Sub StopAllEventHooks() Dim vHook As Variant, lHook As Long For Each vHook In pRunningHandles lHook = vHook StopEventHook lHook Next vHook End Sub Public Function WinEventFunc(ByVal HookHandle As Long, ByVal LEvent As Long, _ ByVal hWnd As Long, ByVal idObject As Long, ByVal idChild As Long, _ ByVal idEventThread As Long, ByVal dwmsEventTime As Long) As Long 'This function is a callback passed to the win32 api 'We CANNOT throw an error or break. Bad things will happen. On Error Resume Next Dim thePID As Long If LEvent = EVENT_SYSTEM_FOREGROUND Then GetWindowThreadProcessId hWnd, thePID If thePID = GetCurrentProcessId Then Application.OnTime Now, "Event_GotFocus" Else Application.OnTime Now, "Event_LostFocus" End If End If On Error GoTo 0 End Function Public Sub Event_GotFocus() Sheet1.[A1] = "Got Focus" End Sub Public Sub Event_LostFocus() Sheet1.[A1] = "Nope" End Sub Paste this into the ThisWorkbook : Option Explicit Private Sub Workbook_BeforeClose(Cancel As Boolean) StopAllEventHooks End Sub Private Sub Workbook_Open() StartHook End Sub A: Why not just using the ThisWorkBook module with an Workbook_Open event? Code in ThisWorkBook code module Private Sub Workbook_Open() ' or... Sub Workbook_Activate() ' checkIsVBEOpen If Application.VBE.MainWindow.Visible = True Then MsgBox "VBE window is open", vbInformation ' do something ' ... ' close VBE window Application.VBE.MainWindow.Visible = False Else MsgBox "VBE window is NOT open" ' do nothing else End If End Sub
{ "pile_set_name": "StackExchange" }
Q: Android Google Map Marker info to TextView i would like to get my Marker info to textView, i am able to do that but it shows always only last one from JSON, any good ideas how to fix that? My Plan was pretty easy, when user Clicks on Marker then it will make RealitveLayout "VISIBLE", it works so far, but my issue is that i gather my Markers from JSON, and then ads them to the MAP, There is OnClick listener what makes the trick (Sets layout VISIBLE and sends info to TextView what is on that Layout.) IT works, but it only takes the last object from JSON array. public GoogleMap.OnInfoWindowClickListener getInfoWindowClickListener() { return new GoogleMap.OnInfoWindowClickListener() { @Override public void onInfoWindowClick(Marker marker) { RelativeLayout rl1 = (RelativeLayout) findViewById(R.id.popup); rl1.setVisibility(View.VISIBLE); // Set the View to VISIBLE //Title to TextView (also "Score" info) TextView pealkiriTextView = (TextView) findViewById(R.id.pealkiriTextView); pealkiriTextView.setText(title + " (" + punkte + " punkti)"); //Description to TextView TextView pKirlejdusTextView = (TextView) findViewById(R.id.pKirlejdusTextView); pKirlejdusTextView.setText(kirjeldus); } };} Thats how i get info from JSON (from URL) private void getMarkers() { StringRequest strReq = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.e("Response: ", response.toString()); try { JSONObject jObj = new JSONObject(response); String getObject = jObj.getString("punktid"); JSONArray jsonArray = new JSONArray(getObject); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); nr = jsonObject.getString(NR); title = jsonObject.getString(TITLE); kirjeldus = jsonObject.getString(KIRJELDUS); vahend = jsonObject.getString(VAHEND); punkte = jsonObject.getString(PUNKTE); latLng = new LatLng(Double.parseDouble(jsonObject.getString(LAT)), Double.parseDouble(jsonObject.getString(LNG))); // Anname addMarkerile väärtused addMarker(latLng, title, kirjeldus,punkte, nr, vahend); } } catch (JSONException e) { // JSON error e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("Error: ", error.getMessage()); Toast.makeText(kaart.this, error.getMessage(), Toast.LENGTH_LONG).show(); } }); And ADDing Markers to Map : private void addMarker(LatLng latlng,final String nr, final String title, final String kirjeldus,final String punkte, final String vahend) { markerOptions.position(latlng); //markerOptions.title(title +"(" + punkte +"p)"); markerOptions.title(punkte +" Punkti"); //markerOptions.snippet(kirjeldus); if (vahend.equalsIgnoreCase("auto")) { markerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.auto)); } else { markerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.jala)); } gMap.addMarker(markerOptions);} //addMarker A: To get the Google map Marker information here i created one custom info window public class CustomWindowInfo implements GoogleMap.InfoWindowAdapter { // Use default InfoWindow frame @Override public View getInfoWindow(Marker arg0) { return null; } // Defines the contents of the InfoWindow @Override public View getInfoContents(Marker arg0) { // Getting view from the layout file info_window_layout View v = getLayoutInflater().inflate(R.layout.custom_map_window, null); TextView texttitle = (TextView) v.findViewById(R.id.texttitle); TextView text_description = (TextView) v.findViewById(R.id.text_description); texttitle.setText(arg0.getTitle()); // Setting the location to the textview text_description.setText(arg0.getSnippet()); return v; }} Setting a custom info window for the google map googleMap.setInfoWindowAdapter(new CustomWindowInfo()); googleMap.setOnInfoWindowClickListener(listenerInfowindow_click); and to get the inforamtion of marker on click public GoogleMap.OnInfoWindowClickListener listenerInfowindow_click = new GoogleMap.OnInfoWindowClickListener() { @Override public void onInfoWindowClick(final Marker marker) { AlertDialog.Builder builder = new AlertDialog.Builder(MapActivity.this); builder.setTitle(""); builder.setMessage(dialog_mas); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (InterNet.isConnectedToInternet()) { Geocoder selected_place_geocoder = new Geocoder(MapActivity.this); address = selected_place_geocoder.getFromLocationName(marker.getSnippet(), 1); } else { Toast.makeText(MapActivity.this,InterNet.interNetMsg, Toast.LENGTH_LONG).show(); } dialog.cancel(); } }); builder.setNegativeButton("N0", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } };
{ "pile_set_name": "StackExchange" }
Q: Teamcity build on every git commit vs build on pull request We are setting up teamcity for our project which uses git. We have this debate on if we should trigger a build on every commit or on every pull request. If i push a branch say A, and we have configured build on pull request on master then will the build be triggered on how the merged code will appear or it will just build the branch ? Lets imagine that we have configures our teamcity to build every pull request Now Lets say i have a branch master, developer A checksout a branch ftb_A. Creates a new test case and commits. Developer A code is not yet merged to master. Develope B creates a new branch ftb_B he also creates new test case. Now developer A pushes the branch and raises a pull request so build runs the test case added by develope A runs. Now pull request from developer A is merged and the newly created tesr case is available in master now. Now developer B also pushes his branch, but he has not rebased his branch i.e. the test case which was added by developer A is not available in brach ftb_B. Now developer B raises a pull request. So build is triggered. Now my question is when the build is triggered for pull request raised by developer B will the test case added by developer A in master will run or not A: Though not indicated, I'm going to assume that you are using GitHub here. In short: yes, the pull request from ftb_B will be updated any time changes are pushed to master. However, you must trigger your build on the pull request branch, not on ftb_B itself. To explain: when a pull request from ftb_B is created, GitHub will generate you a new (hidden) branch that consists of the changes from ftb_B merged to the tip of master. This enables you to review the changes, run TeamCity builds against it and perform any other steps you might want before accepting the pull request. If the pull request from ftb_A is accepted before the creation of the pull request from ftb_B, these changes will naturally be included in the pull request branch. If the pull request from ftb_A is accepted after the creation of the pull request from ftb_B, GitHub will detect the change in the master branch and update the pull request branch for you. So you are good in either case. The flow might look something like this: ftb_A pull request created ftb_A pull request branch created automatically by GitHub ftb_B pull request created ftb_B pull request branch created automatically by GitHub This branch does not include changes from ftb_A at this point ftb_A pull request accepted master is updated ftb_B pull request branch is updated automatically by GitHub Now changes from ftb_A are reflected in the pull request branch Check this out for more info: https://blog.jetbrains.com/teamcity/2013/02/automatically-building-pull-requests-from-github-with-teamcity/
{ "pile_set_name": "StackExchange" }
Q: Are complex projective spaces orientable? I know that $\mathbb{RP}^1$ is oriented (since it is essentially the projectively extended real line), but $\mathbb{RP}^2$ is not (as the non-orientable surface of genus 1 it is arguably the simplest non-orientable surface). According to Wikipedia, for real projective spaces, this pattern continues -- orientable for $n$ odd and non-orientable for $n$ even. However, in contrast, Wikipedia says nothing about the orientability of complex projective spaces. I know that $\mathbb{CP}^1$ is homeomorphic to the sphere (provided $\mathbb{R}^2 \sim \mathbb{C}$) which is orientable, and that the real projective space of dimension $1$ is orientable. On the other hand, complex dimension $1$ is in some sense more like real dimension $2$, and the real projective surface $\mathbb{RP}^2$ is non-orientable. My questions: Is orientability invariant under homeomorphisms? Or just diffeomorphisms? In the former case we could use the orientability of $S^2$ and the homeomorphism with $\mathbb{CP}^1$; in the latter case we would still have more work to do if we were to claim that $\mathbb{CP}^1$ is orientable. Are all complex projective spaces orientable? (E.g. not just the complex projective line $\mathbb{CP}^1$, but also the complex projective plane $\mathbb{CP}^2$.) Wikipedia says that all complex manifolds are oriented (not just orientable), which would imply that they are. Is this claim about complex manifolds true? (I don't know complex manifold theory, thus why I am asking.) A: Every complex manifold is orientable, as every complex vector space as a canonical orientation as a real space. Namely if $V$, is a complex vector space, and $B= (u_1,...,u_n)$ is a base (over C), then $B^*=(u_1,...,u_n, iu_1,...iu_n)$ is a base over $\bf R$. Note that if $B'$ is another base over $C$ and $l$ the unique linear map $C$ map such that $lB=B'$, $lB^*=B'^*$, and the determinant of $l$, viwed as a $R$ linear map is the squre of the modulus of the determinant of $l$, hence positive. Thus the orientation given by $B$ is the same than that given by $B'$, and complex linear maps preserves this orientation.
{ "pile_set_name": "StackExchange" }
Q: Impossible to fire CSV file download from Ajax query I want to fire a download window from an Ajax query. The Ajax query is launched when I click on a button on my page. Here is the Ajax query (function called on click on the button): function exportDetailOuvrage(idData){ $.ajax({ url : 'ouvrage.php', type : 'POST', data : { typeOuvrage : idData }, success : function (data){ $('body').append(data); } }); } Here is the PHP code to generate the CSV: <?php $csv = "Town;Name;Code\r\n" ; foreach($result as $row){ $csv .= $row['town'].";".$row['name'].";".$row['code']."\r\n" ; } header("Content-Type: text/csv; charset=utf-8"); header("Content-Disposition: attachment; filename=data.csv"); echo $csv; ?> In the PHP code, $result is an array built on a SQL query in a database. The CSV string is generated as wanted, the server answer is 200 (no errors using firebug). I have checked the sent parameters and the CSV string returned: everyting is OK. The only issue is that no download window appears and no data.csv file is saved... I was wondering if my Ajax code, especially the content of success parameter is good. I don't know what to put exactly inside this parameter. EDIT : According to @MonkeyZeus answer and comments, here is the content of my gimme_file.php: <?php session_start(); header("Content-Type: text/csv; charset=utf-8"); header("Content-Disposition: attachment; filename=data.csv"); readfile($_SESSION['I_CAN_DOWNLOAD_ONLY_THIS']); exit; ?> I get the following error message inside the data.csv downloaded file: <br /> <b>Notice</b>: Undefined index: I_CAN_DOWNLOAD_ONLY_THIS in <b>D:\STAT\modele\gimme_file.php</b> on line <b>7</b><br /> <br /> <b>Warning</b>: readfile(): Filename cannot be empty in <b>D:\STAT\modele\gimme_file.php</b> on line <b>7</b><br /> A: Javascript (jQuery) can absolutely NOT trigger a file download natively; it would be a gigantic security issue. What you must do is the following: Call the CSV generator Save the CSV to the server with a unique name Pass this unique name to your success: callback Use window.location to redirect the browser to the CSV file My apologies if my post is very terse but I just do not want you to chase your tail for hours trying to achieve something that is fundamentally blocked by web browsers. jQuery function exportDetailOuvrage(idData){ $.ajax({ url : 'ouvrage.php', type : 'POST', data : { typeOuvrage : idData }, success : function (data){ window.location = 'http://www.mywebsite.com/gimme_file.php'; } }); } ouvrage.php <?php session_start(); $csv = "Town;Name;Code\r\n" ; foreach($result as $row){ $csv .= $row['town'].";".$row['name'].";".$row['code']."\r\n" ; } $filename = 'ouvrage_'.uniqid('', TRUE).'.csv'; file_put_contents($filename, $csv); $_SESSION['I_CAN_DOWNLOAD_ONLY_THIS'] = $filename; ?> gimme_file.php <?php session_start(); header("Content-Type: text/csv; charset=utf-8"); header("Content-Disposition: attachment; filename=data.csv"); readfile($_SESSION['I_CAN_DOWNLOAD_ONLY_THIS']); exit; ?>
{ "pile_set_name": "StackExchange" }
Q: A Problem With Deriving Ideal Gas Entropy From Multiplicity To derive the entropy of an ideal gas via the ergodic hypothesis, we first find the density of states function: $$g(E)=\frac{V^{N}}{h^{3N}}\frac{(2\pi m E)^{\frac{3N}{2}}}{\left(\frac{3N}{2}-1\right)!}\frac{1}{E}$$ The multiplicity is then give by $\Omega=\int_{E-\frac{\Delta}{2}}^{E+\frac{\Delta}{2}}g(E')dE'\approx \frac{V^{N}}{h^{3N}}\frac{(2\pi m E)^{\frac{3N}{2}}}{\left(\frac{3N}{2}-1\right)!}\frac{\Delta}{E}$, for small $\Delta$. Then using the definition of entropy $S=k_{B} \ln(\Omega)$, and applying Stirling's approximation, as well as assuming that $N \gg 1$, I obtained: $$S=Nk_{B}\left(\frac{5}{2}+\ln\left(\frac{V}{N}\left(\frac{4\pi m E}{3Nh^{2}}\right)^{\frac{3N}{2}}\right)\right)+k_{B}\ln\left(\frac{\Delta}{E}\right)$$ The first term is the Sackur Tetrode equation which is known to be correct, but the second term seems wrong. Most resources seem to appeal to the fact that $\Delta$ is arbitrarily small, and set $k_{B}\ln\left(\frac{\Delta}{E}\right)=0$, but if $\Delta \ll E$, then $\frac{\Delta}{E}\ll1$, which would mean $k_{B}\ln\left(\frac{\Delta}{E}\right)\ll 0$, i.e. the extra term is approaching $-\infty$, rather than $0$, and is thus not negligible. In short, I can't find a way to jsutify throwing away this tem, as it seems to blow up rather than vanish for small $\Delta$, and an esplanation would be much appreciated. A: You seem to have calculated $\ln \Omega$ assuming permutations are distinguishable and assuming energy is distributed in range $E-\Delta/2..E+\Delta/2$. This is OK mathematically, but leads to: exponent $3N/2$ which means the result is not a homogeneous function of first order of variables $E,V,N$ like thermodynamic entropy is. One consequence of this is that this "entropy" does not obey usual thermodynamic relations like $T=1/(\partial S/\partial E)$. For the concept of homogeneity in thermodynamics, check e.g. https://faculty.uca.edu/saddison/GordonConference/GordonConferencePoster.pdf ; even if correcting factor is introduced to $\Omega$ so the resulting expression is homogeneous, the result depends on the width $\Delta$, which to some extent is arbitrary. In expressions of function $S(E,V,N)$ (for thermodynamic entropy), magnitude of some term does not matter much; a term may be installed or written off even if it is very big, provided it does not depend on $N$ and $E$. So magnitude is not the reason some terms are written off. The way you did the calculation - using some arbitrary $\Delta$ - leads to result that depends on $\Delta$, but only very weakly. Sometimes such non-complying term is written off, if it can be shown that the term has negligible consequences on the measurable physical quantities. What matters are magnitudes of derivatives of entropy with respect to $N$ and $E$. Let us assume we have expression that is Sackur-Tetrode plus your problematic term: $$ S = Nk_{B}\left(\frac{5}{2}+\ln\left(\frac{V}{N}\left(\frac{4\pi m E}{3Nh^{2}}\right)^{\frac{3}{2}}\right)\right)+k_{B}\ln\left(\frac{\Delta}{E}\right) $$ Calculating chemical potential defined as $$ - T \frac{\partial S}{\partial N}_{E,V=const} $$ the arbitrary term gives no contribution, as it does not depend on $N$. Calculating inverse of temperature defined as $$ 1/T = \frac{\partial S}{\partial E}_{V,N=const} $$ the Sackur-Tetrode expression gives contribution $\frac{3}{2}N k_B / E$, while the arbitrary term gives contribution $-k_B/E$. This second one is much smaller and makes only a small difference in the resulting temperature. Since the arbitrary term does not depend on any other physical quantity, those are all derivatives that matter. So the arbitrary term can be neglected.
{ "pile_set_name": "StackExchange" }
Q: MSDeploy 1-click publish not working from VS2010 We are working towards automated deployments and I was really exited about using MSdeploy to help get us there. Unfortunately, I have been having no luck with getting MS deploy to work with VS2010 and I am about to give up. Our Win 2008 server is in the datacenter and I have the firewall and MS deploy remote service and IIS Management service setup correctly as per: http://learn.iis.net/page.aspx/516/configure-the-web-deployment-handler/ I have setup the IIS Manager user and checked everything, I can think off. I can even connect from our dev environment if I use IIS remote management. However when I publish from VS 2010, I get: Error 1 Web deployment task failed.(Could not connect to the destination computer ("x.x.x.x"). On the destination computer, make sure that Web Deploy is installed and that the required process ("The Web Management Service") is started.) The requested resource does not exist, or the requested URL is incorrect. Error details: Could not connect to the destination computer ("x.x.x.x"). On the destination computer, make sure that Web Deploy is installed and that the required process ("The Web Management Service") is started. The remote server returned an error: (404) Not Found. 0 0 UI What am I missing? Please help? A: That error pops up when you aren't using the correct URL for the msdeploy service. It should look something like this: http://x.x.x.x:80/MsDeployAgentService The: /MsDeployAgentService is the default path that msdeploy uses. Other things to try: 1. Turning off the firewall and see if it works. 2. validate the "web deployment service" is running in the windows service manager of the destination server.
{ "pile_set_name": "StackExchange" }
Q: Format styles based on some conditions in highcharts I am developing a chart for an app(android/ios) . I want to style the graph based on some condition , like if the OS is android , the font size should be 14dp and if OS is iphone , it should be 9dp . I get the osname as parameter in the function , I am able to set some chartproperties , but I am not able to change the fontsize and other properties of x axis and y axis based on the osname parameter . Please help in setting the properties for x and y axis . <!DOCTYPE html> <html> <head> <script src="./jquery.min.jsl"></script> <script src="./highcharts.jsl"></script> <script src="./highcharts-more.jsl"></script> <meta name="viewport" content="user-scalable=no"> <script > function renderGraph(graphdata, osname) { var parsed = JSON.parse(graphdata); alert(osname); var s1 = []; var s2 = []; var s3 = []; var s4 = []; var s5 = []; var s6 = []; var cat = []; for (var i = 0; i < parsed.length; i++) { cat.push(parsed[i].QUARTER); s1.push(parsed[i].FTE_OPEX); s2.push(parsed[i].FTE_CAPEX); s3.push(parsed[i].AWF_OPEX); s4.push(parsed[i].AWF_CAPEX); s5.push(parsed[i].HW_SW); s6.push(parsed[i].OTHERS); }; var chartProperties = {}; // height of chart var graphHeight = 0; // width of chart var graphWidth = 0; // Separating the graph dimensions & styling properties as per OS name & version if (osname == "iphone") { chartProperties = { type : 'column', plotBackgroundColor : null, plotBackgroundImage : null, plotBorderWidth : 0, plotShadow : false, height : 250, width : 300, marginLeft : 30, }; } else if (osname == "android") { chartProperties = { type : 'column', plotBackgroundColor : null, plotBackgroundImage : null, plotBorderWidth : 0, plotShadow : false, height : 700, marginLeft : 80, marginTop : 50, marginBottom : 100 }; } ; Highcharts.setOptions({ lang : { numericSymbols : ["K", "M", "G", "T", "P", "E"] } }); $(function() { $('#container').highcharts({ colors : ['#8dafb7', '#f19962', '#e97381', '#f8c465', '#6cd299', '#87cfe2'], chart : chartProperties, title : { text : '' }, xAxis : { categories : cat, tickmarkPlacement : 'on', tickWidth : 0, labels : { y : 20, style : { color : '#333333', fontSize : '9dp', fontFamily : 'Metropolis-Light', opacity : '.6' }, } }, yAxis : { gridLineWidth : 0, min : 0, offset : 10, tickAmount : 5, title : { text : '' }, labels : { align : 'left', style : { color : '#333333', fontSize : '9dp', fontFamily : 'Metropolis-Light', opacity : '.5' }, formatter : function() { var value = this.axis.defaultLabelFormatter.call(this); return '$' + (this.value === 0 ? '0K' : value); } }, stackLabels : { style : { color : '#555555', fontSize : '11dp', fontFamily : 'Metropolis-Regular' }, enabled : true, formatter : function() { if (this.total < 1000) { return '$' + this.total; } else { return '$' + (this.total / 1000).toFixed(2) + 'K'; }; } }, }, legend : { enabled : false }, tooltip : { enabled : false }, plotOptions : { series : { animation : false }, column : { stacking : 'normal', dataLabels : { enabled : false, color : (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white' } } }, credits : { enabled : false }, series : [{ name : 'FTE-OpEx', data : s1, index : 0, pointWidth : 20 }, { name : 'FTE-CapEx', data : s2, index : 1, pointWidth : 20 }, { name : 'AWF-OpEx', data : s3, index : 2, pointWidth : 20 }, { name : 'AWF-CapEx', data : s4, index : 3, pointWidth : 20 }, { name : 'HW/SW', data : s5, index : 4, pointWidth : 20 }, { name : 'Other', data : s6, index : 5, pointWidth : 20 }] }); }); } </script> </head> <body id="body"> <div id="container" style="height: 100%; width: 100%; position: center; margin-left: 3%;"></div> </body> </html> A: Font size and other properties can be updated as the same way you are doing with the chart properties. function updateChart(obj) { if (obj.value == "iphone") { yAxisLabelst={ fontSize:'7px', color:'green', cursor:'pointer', } chartProperties = { type: 'column', plotBackgroundColor: null, plotBackgroundImage: null, plotBorderWidth: 0, plotShadow: false, height: 250, width: 300, marginLeft: 30, }; } else if (obj.value == "android") { yAxisLabelst={ fontSize:'15px', color:'green', cursor:'pointer', } chartProperties = { type: 'column', plotBackgroundColor: null, plotBackgroundImage: null, plotBorderWidth: 0, plotShadow: false, height: 700, marginLeft: 80, marginTop: 50, marginBottom: 100 }; } drawChart(chartProperties,yAxisLabelst) } function updateChart(obj) { if (obj.value == "iphone") { yAxisLabelst={ fontSize:'7px', color:'green', cursor:'pointer', } chartProperties = { type: 'column', plotBackgroundColor: null, plotBackgroundImage: null, plotBorderWidth: 0, plotShadow: false, height: 250, width: 300, marginLeft: 30, }; } else if (obj.value == "android") { yAxisLabelst={ fontSize:'15px', color:'green', cursor:'pointer', } chartProperties = { type: 'column', plotBackgroundColor: null, plotBackgroundImage: null, plotBorderWidth: 0, plotShadow: false, height: 700, marginLeft: 80, marginTop: 50, marginBottom: 100 }; } drawChart(chartProperties,yAxisLabelst) } Highcharts.setOptions({ lang: { numericSymbols: ["K", "M", "G", "T", "P", "E"] } }); function drawChart(chartProperties,yAxisLabelst) { Highcharts.chart('container', { chart: chartProperties, title: { text: 'Solar Employment Growth by Sector, 2010-2016' }, subtitle: { text: 'Source: thesolarfoundation.com' }, yAxis: { title: { text: 'Number of Employees' }, labels:{ style:yAxisLabelst } }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle' }, plotOptions: { series: { label: { connectorAllowed: false }, pointStart: 2010 } }, series: [{ name: 'Installation', data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175] }, { name: 'Manufacturing', data: [24916, 24064, 29742, 29851, 32490, 30282, 38121, 40434] }, { name: 'Sales & Distribution', data: [11744, 17722, 16005, 19771, 20185, 24377, 32147, 39387] }, { name: 'Project Development', data: [null, null, 7988, 12169, 15112, 22452, 34400, 34227] }, { name: 'Other', data: [12908, 5948, 8105, 11248, 8989, 11816, 18274, 18111] }], responsive: { rules: [{ condition: { maxWidth: 500 }, chartOptions: { legend: { layout: 'horizontal', align: 'center', verticalAlign: 'bottom' } } }] } }); } #container { min-width: 310px; max-width: 800px; height: 400px; margin: 0 auto } <script src="https://code.highcharts.com/highcharts.js"></script> <script src="https://code.highcharts.com/modules/series-label.js"></script> <script src="https://code.highcharts.com/modules/exporting.js"></script> <select onchange="updateChart(this)"> <option value="" >Select Device </option> <option value="iphone" >iphone</option> <option value="android">android</option> </select> <div id="container"></div>
{ "pile_set_name": "StackExchange" }
Q: How can you access the Visual Studio solution level platform from a C# project's build event? We have a large VS 2010 solution that is mostly C# code but there are a few native DLLs that various C# projects depend upon (including our unit testing DLL). We're in the processing of trying to support both 32-bit and 64-bit versions of our libraries. So we're now build the native DLLs as 32-bit and 64-bit. The problem is that a lot of our C# project's have post-build events that copy the required native DLLs into the project's TargetDir. Now that we have two different versions of the native DLLs (32 and 64 bit), I need to be able to specify the correct dir to copy the native DLL from. I originally thought I could simply use $(Platform) in the path like so: copy $(SolutionDir)\NativeDll\$(Platform)\$(Configuration) $(TargetDir) But that doesn't work because $(Platform) is the project's platform and not the solution level platform. In this case $(Platform) is "Any CPU". From what I can see looking at the post-build event macros in C# project, there doesn't appear to be a way to access the solution level platform that is being built. Is there a better way to accomplish my goal? A: I believe the solution's platform, unlike that of the projects is simply text. What I have down in the past is: Delete Win32 and "mixed platform" from solution (and keep doing so after adding projects). Set all C# DLLs to build as AnyCPU in solution platforms AnyCPU, x86, x64. (Do not delete AnyCPU if you want to be able to open in Blend or if you have any pure managed applications in the solution.) Set C# EXEs and unit tests to build in x86 in x86 solution platform and x64 in x64 solution platform and not to build at all in AnyCPU solution platform. Set all natives to build in Win32 when solution is x86 and output to $(ProjectDir)\bin\x86\$(Configuration) and intermediate to same with obj in path instead of bin. x64 the same with x64 instead of x86 and Win32. Set pre build events of C# EXEs and unit tests to copy native DLLs they are depended on from relative path with project's configuration name: $(Config) Set unit tests' class initialize to copy entire contents of tests bin dir (correct platform and configuration, of course) to tests' out dir. Use if #DEBUG and unsafe sizeof(IntPtr) to tell where to look for tests' bin dir. Manually (using Notepad) add relative reference path to .csproj files outside solution that use x86/x64 assemblies from solution's deployment location, so path will include $(Platform) and $(Configuration) and will not be per user. Microsoft: Better 32/64 bit support in Visual Studio would be really in place.
{ "pile_set_name": "StackExchange" }
Q: polymerfire/firebase-query transaction complete event Very new to Polymer and Polymerfire. I couldn't find an answer here so hoping I can get help here. The basic question I have is "how do I work with the data that polymerfire/firebase-query sends?" Note I'm using polymerfire version 0.9.4, and polymer is version 1.4.0. I can load my data from Firebase no problem using Firebase query, however some of the values are raw numbers that I need to convert to user friendly information. For example I have time stored in ms that I want to convert to a date, and a numeric field that indicates the "type" of data that is stored and I want to show an icon for it, not just a raw number. I figured my best option would be to use the transactions-complete promise or an observer. Both fire but neither seems to give me access to the data. The Observer's newData is an empty array, and transactions-complete.. well I don't really know what to do with that when the promise fires. Below is my relevant code. I also tried using notify: true, but I seem to not be grasping the concept correctly. <firebase-query id="query" app-name="data" path="/dataPath" transactions-complete="transactionCompleted" data="{{data}}"> </firebase-query> <template is="dom-repeat" items="{{data}}"> <div class="card"> <div>Title: <span>{{item.title}}</span></div> <div>Date Created: <span>{{item.dateCreated}})</span></div> <div>Date Modified: <span>{{item.dateModified}}</span></div> <div>Status: <span>{{item.status}}</span></div> </div> </template> Polymer({ is: 'my-view1', properties: { data: { notify: true, type: Object, observer: 'dataChanged' } }, dataChanged: function (newData, oldData) { console.log(newData[0]); // do something when the query returns values? }, transactionCompleted: new Promise(function(resolve, reject) { // how can I access "data" here? })` A: I wound up going another way entirely, which seemed to be a cleaner approach to what I was doing anyways. I broke it down into separate components. This way when the detail component was loaded, the ready function would allow me to adjust the data before it got displayed: list.html: <firebase-query id="query" app-name="data" path="/dataPath" data="{{data}}"> </firebase-query> <template is="dom-repeat" items="{{data}}"> <my-details dataItem={{item}}></my-details> </template> details.html <template> <div id="details"> <paper-card heading="{{item.title}}"> <div class="card-content"> <span id="description">{{item.description}}</span><br/><br/> <div class="details">Date Created: <span id="dateCreated">{{item.dateCreated}}</span><br/></div> <div class="details">Last Modified: <span id="dateModified">{{item.dateModified}}</span><br/></div> <div class="status"><span id="status">{{item.status}}</span><br/></div> </div> </paper-card> </template> Then in the javascript ready function I can intercept and adjust the data accordingly: Polymer({ is: 'my-details', properties: { item: { notify: true, }, }, ready: function() { this.$.dateModified.textContent = this.getDate(this.item.dateModified); this.$.dateCreated.textContent = this.getDate(this.item.dateCreated); this.$.status.textContent = this.getStatus(this.item.status); },
{ "pile_set_name": "StackExchange" }
Q: What was said by swami Vivekananda about Hinduism in Chicago Speech? He has given a great speech about Hinduism and makes feel proud of us on our culture and Hinduism. I have only always one thing in his that speech "All my dear Brothers and Sisters". I didn't hear anything else. Here, I just want some brief description of his speech. A: There are actually many addresses which were given by Swami Vivekananda at Chicago. The one that you're referring to was given on September 11, 1893. You can download this PDF. It contains the addresses. Chicago, 11 September 1893 Sisters and Brothers of America, It fills my heart with joy unspeakable to rise in response to the warm and cordial welcome which you have given us. I thank you in the name of the most ancient order of monks in the world; I thank you in the name of the mother of religions; and I thank you in the name of the millions and millions of Hindu people of all classes and sects. My thanks, also, to some of the speakers on this platform who, referring to the delegates from the Orient, have told you that these men from far -off nations may well claim the honour of bearing to different lands the idea of toleration. I am proud to belong to a religion which has taught the world both tolerance and universal acceptance. We believe not only in universal toleration, but we accept all religions as true. I am proud to belong to a nation which has sheltered the persecuted and the refugees of all religions and all nations of the earth. I am proud to tell you that we have gathered in our bosom the purest remnant of the Israelites, who came to southern India and took refuge with us in the very year in which their holy temple was shattered to pieces by Roman tyranny . I am proud to belong to the religion which has sheltered and is still fostering the remnant of the grand Zoroastrian nation. I will quote to you, brethren, a few lines from a hymn which I remember to have repeated from my earliest boyhood, which is every day repeated by millions of human beings: As the different streams having their sources in different places all mingle their water in the sea, so, O Lord, the different paths which men take through different tendencies, various though they appear , crooked or straight, all lead to Thee. The present convention, which is one of the most august assemblies ever held, is in itself a vindication, a declaration to the world, of the wonderful doctrine preached in the Gita : Whosoever comes to Me, through whatsoever form, I reach him; all men are struggling through paths which in the end lead to Me. 2 Sectarianism, bigotry, and its horrible descendant, fanaticism, have long possessed this beautiful earth. They have filled the earth with violence, drenched it often and often with human blood, destroyed civilization, and sent whole nations to despair . Had it not been for these horrible demons, human society would be far more advanced than it is now . But their time is come; and I fervently hope that the bell that tolled this morning in honour of this convention may be the death-knell of all fanaticism, of all persecutions with the sword or with the pen, and of all uncharitable feelings between persons wending their way to the same goal.
{ "pile_set_name": "StackExchange" }
Q: Qt Cryptographic Hashing I been trying to use the Qt Encryption libraries and have been having trouble. The ones that ship with Qt (QCryptographicHash) work well but only support hash schemes that are insecure like md5 and SHA1, there is no SHA256 for example. I found the Qt Cryptographic Architecture (QCA) which has much more features. I got the libraries from the Delta XMPP Project site. http://delta.affinix.com/qca/ The link to the QCA library is http://delta.affinix.com/download/qca/2.0/qca-2.0.3.tar.bz2 It is the newest version of the QCA Libary. The instruction are as follows. Installing QCA QCA requires Qt 4.2 or greater. For Windows: configure nmake (or make) installwin Using newest Qt everything. Everything works great in Qt except this library. I use Windows XP. I followed the installation instructions and got no errors. The problem is that I get errors when I try to use any code that has anything to do with the QCA library. I would really appreciate any help getting this lib to work. Here is my code. The project file. #------------------------------------------------- # # Project created by QtCreator 2011-11-14T14:23:21 # #------------------------------------------------- QT += core QT -= gui TARGET = kde_crypto2 CONFIG += console CONFIG -= app_bundle CONFIG += crypto TEMPLATE = app SOURCES += main.cpp The source file. #include <QtCore/QCoreApplication> #include <QTextStream> #include <QString> #include <QtCrypto/QtCrypto> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QTextStream t(stdout); if(!QCA::isSupported("sha1")) t << "SHA1 not supported!\n"; else { QByteArray fillerString; fillerString.fill('a', 1000); QCA::Hash shaHash("sha1"); for (int i=0; i<1000; i++) shaHash.update(fillerString); QByteArray hashResult = shaHash.final(); if ( "34aa973cd4c4daa4f61eeb2bdbad27316534016f" == QCA::arrayToHex(hashResult) ) { t << "big SHA1 is OK\n"; } else { t << "big SHA1 failed\n"; } } return a.exec(); } Error code is error: conversion from 'QCA::MemoryRegion' to non-scalar type 'QByteArray' requested EDIT (UPDATE) I did not include the --debug-and-release flag when compiling the library. After re-compiling thelibrary with this flag I no longer get errors while compiling my code. However, when I run my code the application crashes when ever any line is reached that uses the QCA library. Therefore I believe there is either something wrong with the library or the way it is installed. The error code when running is: ASSERT: "global" in file qca_core.cpp, line 260 A: Looks like the cause of the error is that you get a MemoryRegion with shaHash.final() and you try to stuff it into a QByteArray. Try adding a .toByteArray() after the final() call. See http://delta.affinix.com/docs/qca/classQCA_1_1MemoryRegion.html Whether it makes sense to use QCA (and its maintenance state) I don't know though.
{ "pile_set_name": "StackExchange" }
Q: auto-rotating a jq.carousel using setInterval, and pausing on hover I'm using jq.carousel and as it doesn't have an auto-rotate function built in I'm using setInterval to advance it every second by calling $carouselHome.carousel('next'). This works, but I need to add 'pause on hover'. Here's what I have so far which works as required only after the mouse has entered and left the element once. How would I 'kick off' the interval on first page load? (example: http://jsfiddle.net/meredevelopment/hmUbd/) var $carouselHome = $('#carousel-home').carousel(); $('#carousel-home_prev').on('click', function(ev) { $carouselHome.carousel('prev'); }); $('#carousel-home_next').on('click', function(ev) { $carouselHome.carousel('next'); }); /*setInterval(function() { $carouselHome.carousel('next'); }, 1000);*/ $("#carousel-home").mouseenter(function(){ clearInterval($(this).data('timeoutId')); }).mouseleave(function(){ var someElement = $(this); var timeoutId = setInterval(function() { $carouselHome.carousel('next'); }, 1000); console.log(timeoutId); someElement.data('timeoutId', timeoutId); }); Thanks! Ben A: Something like this should work: if ($("#carousel-home").length > 0) { var $carouselHome = $('#carousel-home').carousel(); var timeoutId = setInterval(function() { $carouselHome.carousel('next'); }, 1000); $('#carousel-home_prev').on('click', function(ev) { $carouselHome.carousel('prev'); }); $('#carousel-home_next').on('click', function(ev) { $carouselHome.carousel('next'); }); $("#carousel-home").mouseenter(function() { clearInterval(timeoutId); }).mouseleave(function() { var someElement = $(this); timeoutId = setInterval(function() { $carouselHome.carousel('next'); }, 1000); }); }
{ "pile_set_name": "StackExchange" }
Q: How to speed up this TSQL query? I have a TSQL select query that is running "slow" SELECT CustomerKey ,ProductKey ,RepresentativeKey ,ReportingDateKey ,SUM(i.InvoiceQuantity) AS InvoiceQuantity ,SUM(i.InvoiceQuantityKg) AS InvoiceQuantityKg ,SUM(i.BrutoInvoiceLineAmount) AS BrutoInvoiceLineAmount ,SUM(i.EndOfYearDiscount) AS EndOfYearDiscount ,SUM(i.NettoInvoiceLineAmount) AS NettoInvoiceLineAmount ,SUM(i.TotalLineCostPrice) AS CostPrice ,SUM(i.MarginAmount) AS MarginAmount FROM FactInvoices i WHERE i.DossierKey =2 AND i.ReportingDate BETWEEN '2016-01-01' AND '2017-12-31' GROUP BY CustomerKey ,ProductKey ,RepresentativeKey ,ReportingDateKey I'm running the query in SSMS 32bit. Execution time is 17-21s, I have tested adding non clustered indexs on DossierKey and ReportingDate, but this is only slowing down the query. The table has about 6.04M record and this result set is giving back 1M records. It's running on SQL 2016 Developers edition. Server specs: 8core 16gb ram and HDD => Virual server. Looking at the execution plan, I can't find any improvements. How do I speed up? More hardware? But I don't think that will help because the server is not fully used when running this query. Edit: Execution Plan: Index: CREATE NONCLUSTERED INDEX [_dx1] ON [dbo].[FactInvoices] ([DossierKey],[ReportingDate]) INCLUDE ([CustomerKey],[ProductKey],[ReportingDateKey],[RepresentativeKey],[InvoiceQuantity],[InvoiceQuantityKg],[BrutoInvoiceLineAmount],[NettoInvoiceLineAmount],[MarginAmount],[EndOfYearDiscount],[TotalLineCostPrice]) Thanks. A: For this query: SELECT CustomerKey, ProductKey, RepresentativeKey, ReportingDateKey, . . . FROM FactInvoices i WHERE i.DossierKey = 2 AND i.ReportingDate BETWEEN '2016-01-01' AND '2017-12-31' GROUP BY CustomerKey, ProductKey, RepresentativeKey, ReportingDateKey; I would recommend an index on FactInvoices(DossierKey, ReportingDate, CustomerKey, ProductKey, RepresentativeKey). The first two are the primary elements of the index used for the WHERE clause. The remaining three columns may be useful for the aggregation. You could also include all the additional columns used in the query.
{ "pile_set_name": "StackExchange" }
Q: What does "interactive query" or "interactive analytics" mean in Presto SQL? The Presto website (and other docs) talk about "interactive queries" on Presto. What is an "interactive query"? From the Presto Website: "Facebook uses Presto for interactive queries against several internal data stores, including their 300PB data warehouse." A: An interactive query system is basically a user interface that translates the input from the user into SQL queries. These are then sent to Presto, which processes the queries and gets the data and sends it back to the user interface. The UI then renders the output, which is typically NOT just a simple table of numbers and text, but rather a complex chart, a diagram or some other powerful visualization. The users expects to be able to e.g. update one criteria and get the updated chart or visualization in near real time, just like you expect on any application typically. Even if the creation of this analysis involves LOTS of data to be processed. Presto can do that since it can query massive distributed object storage systems like HDFS and many other cloud storage systems, as well as RDBMSs and so on. And it can be set up to have a huge cluster of workers that query the source in parallel and therefore process massive amounts of data for analysis, and still be fast enough for the user expectations. A typical application to use for the visualization is Apache Superset. You just hook up Presto to it via the JDBC driver. Presto has to be configured to point at the underlying data sources and you are ready to go.
{ "pile_set_name": "StackExchange" }
Q: Export table to $\LaTeX$ - copy as I have the following final expression which is a table (I am posting only a subsection of the table to illustrate the problem). I am pasting it from Mathematica without table formatting (to the bottom of the post) directly and it looks ugly, however, in table form looks as in the picture: Now, I would love to have this in $\LaTeX$. It is a very simple table from the visual point of view, however, Mathematica, upon using copy as $\LaTeX$, gives bunch of errors: Is there a way to get the table in $\LaTeX$ or do I just have to generate the $\LaTeX$ output with Mathematica directly? {{" ", "C2ung(\!\(\*FormBox[\(1\), TraditionalForm]\))", "CM1(\!\(\*FormBox[\(2\), TraditionalForm]\))"}, {"Olivine", "\!\(\*FormBox[TemplateBox[{TagBox[\nInterpretationBox[\"\\\"14.8\\\ \"\", 14.799999999999999`, AutoDelete -> True], NumberForm[#, {3, \ 1}]& ],TagBox[\nInterpretationBox[\"\\\"14.8\\\"\", \ 14.799999999999999`, AutoDelete -> True], NumberForm[#, {3, \ 1}]& ],TagBox[\nInterpretationBox[\"\\\"14.8\\\"\", \ 14.799999999999999`, AutoDelete -> True], NumberForm[#, {3, 1}]& ]},\n\ \"Subsuperscript\"], TraditionalForm]\)", "\!\(\*FormBox[TemplateBox[{TagBox[\n\ InterpretationBox[\"\\\"7.0\\\"\", 7.000000000000001, \ AutoDelete -> True], NumberForm[#, {3, 1}]& ],TagBox[\n\ InterpretationBox[\"\\\"6.3\\\"\", 6.3, AutoDelete -> True], \ NumberForm[#, {3, 1}]& ],TagBox[\nInterpretationBox[\"\\\"7.7\\\"\", \ 7.7, AutoDelete -> True], NumberForm[#, {3, 1}]& ]},\n\ \"Subsuperscript\"], TraditionalForm]\)"}, {"Pyroxene", "\!\(\*FormBox[TemplateBox[{TagBox[\n\ InterpretationBox[\"\\\"1.4\\\"\", 1.4000000000000001`, \ AutoDelete -> True], NumberForm[#, {3, 1}]& ],TagBox[\n\ InterpretationBox[\"\\\"1.4\\\"\", 1.4000000000000001`, \ AutoDelete -> True], NumberForm[#, {3, 1}]& ],TagBox[\n\ InterpretationBox[\"\\\"1.4\\\"\", 1.4000000000000001`, \ AutoDelete -> True], NumberForm[#, {3, 1}]& ]},\n\"Subsuperscript\"], TraditionalForm]\)", "\!\(\*FormBox[TemplateBox[{TagBox[\n\ InterpretationBox[\"\\\"0.0\\\"\", 0., AutoDelete -> True], \ NumberForm[#, {3, 1}]& ],TagBox[\nInterpretationBox[\"\\\"0.0\\\"\", \ 0., AutoDelete -> True], NumberForm[#, {3, 1}]& ],TagBox[\n\ InterpretationBox[\"\\\"0.0\\\"\", 0., AutoDelete -> True], \ NumberForm[#, {3, 1}]& ]},\n\"Subsuperscript\"], TraditionalForm]\)"}} A: Errors of the sort described by the OP can be reproduced by copying the lengthy block of code in the question to a notebook, prefixing TeXForm@TableForm, and executing it. (Be prepared to abort the execution.) However, the same table shown near the top of the question can be produced from TableForm@{{"", "C2ung(1)", "CM1(2)"}, {"Olivine", Subscript[14.8, 14.8]^14.8, Subscript["7.0", 6.3]^7.7}, {"Pyroxene", Subscript[1.4, 1.4]^1.4, Subscript["0.0", "0.0"]^"0.0"}} (I enclosed numbers with trailing zeroes in quotation marks to prevent Mathematica from deleting those zeros in the display. In fact, all numbers could be enclosed with quotation marks, if desired.) Then, prefixing TeXForm gives the desired result \left( \begin{array}{ccc} \text{} & \text{C2ung(1)} & \text{CM1(2)} \\ \text{Olivine} & 14.8_{14.8}^{14.8} & 7.0_{6.3}^{7.7} \\ \text{Pyroxene} & 1.4_{1.4}^{1.4} & 0.0_{0.0}^{0.0} \\ \end{array} \right) i.e., $\left( \begin{array}{ccc} \text{} & \text{C2ung(1)} & \text{CM1(2)} \\ \text{Olivine} & 14.8_{14.8}^{14.8} & 7.0_{6.3}^{7.7} \\ \text{Pyroxene} & 1.4_{1.4}^{1.4} & 0.0_{0.0}^{0.0} \\ \end{array} \right)$ Incidentally, replacing Subscript[14.8, 14.8]^14.8 by the more natural choice Subsuperscript[14.8, 14.8, 14.8] does not work well, because TeXForm cannot translate it to TeX.
{ "pile_set_name": "StackExchange" }
Q: SQL inserting value of a specific column under multple case Suppose I have got a table which I have to insert the description of the contract under different keys of contract. But when executing, there is a n error near then Is there any limitation of using syntax set ? The below is my SQL declare @i int, @j v nvarchar(MAX) set @i = 1 while (@i<=8) begin set @j = case when @i = 1 then 'CR' when @i = 2 then 'Facebook' else 'N/A' end INSERT INTO CostNature (CNKey, CNNDescription) VALUES (@i , @j ); set @i = @i + 1 end A: Incorrect @j v nvarchar(MAX) Correct @j nvarchar(MAX) Otherwise, all other code is fine.
{ "pile_set_name": "StackExchange" }
Q: Como utilizar Infinite Scroll dentro de um ion-card? Preciso que o InfiniteScroll emita um evento ao rolar o scroll do card, e não da página. import { Component, OnInit, ViewChild } from '@angular/core'; import { GrupoService } from 'src/app/services/grupo.service'; import { ActivatedRoute, Router } from '@angular/router'; import { LoadingController, IonInfiniteScroll } from '@ionic/angular'; @Component({ selector: 'app-temporadas', templateUrl: './temporadas.page.html', styleUrls: ['./temporadas.page.scss'], }) export class TemporadasPage implements OnInit { @ViewChild(IonInfiniteScroll) infinite : IonInfiniteScroll temporadas : any = [] grupoId : any loading : any erro : boolean erroJogos : boolean = false spin : boolean = true page : number = 1; isAdministrador : boolean = false constructor( private grupoService : GrupoService, private activeRoute : ActivatedRoute, private loadingCtrl : LoadingController, private router : Router, ) { } async ngOnInit() { if(localStorage.getItem('administrador') == '1') { this.isAdministrador = true } this.loading = await this.loadingCtrl.create() this.loading.present() this.grupoId = this.activeRoute.snapshot.params['grupo'] this.obterTemporadas() } toggleInfiniteScroll() { this.infinite.disabled = !this.infinite.disabled; } obterTemporadas() { this.erro = false let params = { grupo : this.grupoId } this.grupoService.obterTemporadas(params).subscribe( data => { this.temporadas = data this.loading.dismiss() for(let temporada of this.temporadas){ let jogosParams = { temporada : temporada.id, page : this.page } this.grupoService.obterJogos(jogosParams).subscribe( data => { this.spin = false temporada.jogos = data console.log(data) return temporada.jogos.data }, err => { this.spin = false if(err.error.resultado == false) { return false } } ) console.log(temporada) } }, err =>{ if(err.error.resultado == false) { this.erro = true } this.loading.dismiss() console.log(err) } ) } /*infiniteJogos(event) { setTimeout(() => { console.log('Done'); this.page++ this.obterTemporadas() event.target.complete(); if (data.length == 1000) { event.target.disabled = true; } }, 500); }*/ cadastrarTemporada() { this.router.navigate(['temporada/cadastrar',this.grupoId]) } cadastrarJogos(temporada) { this.router.navigate([this.grupoId,'jogos','cadastrar',temporada]) } jogoDetalhes(jogo,temporada) { this.router.navigate([this.grupoId,temporada,'detalhes-jogos',jogo]) } jogoFinalizadoDetalhes(jogo,temporada) { this.router.navigate([this.grupoId,temporada,'detalhes-jogo-finalizado',jogo]) } } ion-button { //padding-left:50%!important; //padding-right:50%!important; //align-content: center!important; //align-items: center!important; } .jogos { height: 250px; overflow: scroll; } .jogoFinalizado { background-color: greenyellow; color: white; font-size: 30px; } h2{ text-align: center; } ion-spinner{ top:50%; left:50%; } ion-icon{ text-align: right!important; font-size: 40px; } <ion-card *ngIf="erro == true"> <ion-label>Sem temporadas</ion-label> </ion-card> <ion-button *ngIf="isAdministrador" (click)="cadastrarTemporada()">(+) Temporada</ion-button> <div *ngIf="erro == false"> <ion-card *ngFor="let temporada of temporadas"> <ion-card-header> <ion-card-title>Temporada: {{temporada.nome}}</ion-card-title> <ion-card-subtitle>{{temporada.descricao}}</ion-card-subtitle> </ion-card-header> <ion-card-content> <ion-button *ngIf="isAdministrador" (click)="cadastrarJogos(temporada.id)">(+) Jogos</ion-button> <ion-item *ngIf="!temporada.jogos"> Não há jogos cadastrados nesta temporada. </ion-item> </ion-card-content> <ion-spinner icon="crescent" class="spinner-royal" *ngIf="spin"></ion-spinner> <h2 *ngIf="!spin"> Jogos </h2> <div *ngIf="temporada.jogos" class="jogos"> <div *ngFor="let jogo of temporada.jogos.data"> <!-------------------------JOGO Ñ FINALIZADO------------------------------------> <ion-card *ngIf="!jogo.hora_final" (click)="jogoDetalhes(jogo.id,jogo.temporada)"> <ion-card-content> <ion-col> Dia : {{jogo.data | date: 'dd/MM/yyyy'}} <br /> Hora : {{jogo.hora_inicial}} </ion-col> <ion-col> <ion-icon name="md-add-circle" float-right></ion-icon> </ion-col> </ion-card-content> </ion-card> <!-------------------------JOGO FINALIZADO!!!!!!------------------------------------> <ion-card class="jogoFinalizado" *ngIf="jogo.hora_final" (click)="jogoFinalizadoDetalhes(jogo.id,jogo.temporada)"> <ion-card-content> <ion-col> Dia : {{jogo.data | date: 'dd/MM/yyyy'}} <br /> Hora Inicial : {{jogo.hora_inicial}} <br> Hora Final : {{jogo.hora_final}} </ion-col> <ion-col> <ion-icon name="done-all" float-right></ion-icon> </ion-col> </ion-card-content> </ion-card> </div> <ion-infinite-scroll threshold="10px" (ionInfinite)="loadData($event)"> <ion-infinite-scroll-content loadingSpinner="bubbles" loadingText="Loading more data..."> </ion-infinite-scroll-content> </ion-infinite-scroll> </div> </ion-card> </div> Print da compilação : A: Pesquisei algo sobre a algum tempo, e pelo que entendo, infinite-scroll precisa de um scroll para ter referência do "fim" da lista. Ficaria algo como: <ion-card> <ion-card-header> Título </ion-card-header> <ion-card-content> <ion-scroll scrollY="true"> <ion-list *ngFor="let item of items"> <!-- Conteúdo se repetindo --> </ion-list> <ion-infinite-scroll threshold="10px" (ionInfinite)="loadData($event)"> <ion-infinite-scroll-content loadingSpinner="bubbles" loadingText="Loading more data..."> </ion-infinite-scroll-content> </ion-infinite-scroll> </ion-scroll> </ion-card-content> </ion-card>
{ "pile_set_name": "StackExchange" }
Q: Does pthread_create start the created thread? Does the function "pthread_create" start the thread (starts executing its function), or does it just creates it and make it wait for the right moment to start? A: pthread_create creates the thread (by using clone syscall internally), and return the tid (thread id, like pid). So, at the time when pthread_create returns, the new thread is at least created. But there are no guaranties when it will be started. From the Man: http://man7.org/linux/man-pages/man3/pthread_create.3.html Unless real-time scheduling policies are being employed, after a call to pthread_create(), it is indeterminate which thread—the caller or the new thread—will next execute. POSIX has the similar comment in the informative description of pthread_create http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_create.html There is no requirement on the implementation that the ID of the created thread be available before the newly created thread starts executing. There is also long "Rationale" why pthread_create is single step process without separate thread creation and start_execution (as it was in good old Java epoch): A suggested alternative to pthread_create() would be to define two separate operations: create and start. Some applications would find such behavior more natural. Ada, in particular, separates the "creation" of a task from its "activation". Splitting the operation was rejected by the standard developers for many reasons: The number of calls required to start a thread would increase from one to two and thus place an additional burden on applications that do not require the additional synchronization. The second call, however, could be avoided by the additional complication of a start-up state attribute. An extra state would be introduced: "created but not started". This would require the standard to specify the behavior of the thread operations when the target has not yet started executing. For those applications that require such behavior, it is possible to simulate the two separate steps with the facilities that are currently provided. The start_routine() can synchronize by waiting on a condition variable that is signaled by the start operation. You may use RT scheduling; or just add some synchronization in the created thread to get exact information about it's execution. It can be also useful in some cases to manually bind the thread to specific CPU core using pthread_setaffinity_np A: It creates the thread and enters the ready queue. When it gets its slice from the scheduler, it starts to run. How early it gets to run will depend upon thread's priority, no of threads it is competing against among other factors.
{ "pile_set_name": "StackExchange" }
Q: Why does sample() not work for a single number? sample(x,n) The parameters are the vector, and how many times you wish to sample sample(c(5,9),1) returns either 5 or 9 however, sample(5,1) returns 1,2,3,4, or 5? I've read the help section: If x has length 1, is numeric (in the sense of is.numeric) and x >= 1, sampling via sample takes place from 1:x. Note that this convenience feature may lead to undesired behaviour when x is of varying length in calls such as sample(x). See the examples. But is there a way to make it not do this? Or do I just need to include an if statement to avoid this. A: Or do I just need to include an if statement to avoid this. Yeah, unfortunately. Something like this: result = if(length(x) == 1) {x} else {sample(x, ...)}
{ "pile_set_name": "StackExchange" }
Q: Again, ObservableCollection doesnt Update item Thats my first project using MVVM , MVVM light. I have a listbox, that gets refreshed from the PersonList Observable collection, adding and removing refresh it normal. the problem is when editing an item. I looked for all the solutions for this problem, nothing worked, which make me think that I missed something. so here is the code : public class AdminViewModel : ApplicationPartBaseViewModel { private ObservableCollection<Person> personList; public AdminViewModel() { this.context = new Entities(); this.SavePersonCommand = new RelayCommand(() => this.SavePerson ()); this.PersonList = new ObservableCollection<Peson>(context.Person.OrderBy(o => o.PersonName).ToList()); } public ObservableCollection<Person> PersonList { get { return personList; } set { this.personList = value; RaisePropertyChanged("PersonList"); } } private void SavePerson() { //Add and update code here this.context.SaveChanges(); RaisePropertyChanged("PersonList"); } } Person Class is Autogenerated template from the DataModel edmx //------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ public partial class Person { #region Primitive Properties public virtual int PersonId { get; set; } public virtual string PersonName { get; set; } public virtual Nullable<int> PersonAge { get; set; } #endregion #region Navigation Properties public virtual ICollection<Humans> Humans { get { if (_human == null) { var newCollection = new FixupCollection<Human>(); newCollection.CollectionChanged += FixupHuman; _human = newCollection; } return _human; } set { if (!ReferenceEquals(_human, value)) { var previousValue = _human as FixupCollection<Human>; if (previousValue != null) { previousValue.CollectionChanged -= FixupHuman; } _human = value; var newValue = value as FixupCollection<Human>; if (newValue != null) { newValue.CollectionChanged += FixupAssets; } } } } private ICollection<Human> _human; #endregion #region Association Fixup private void FixupHuman(object sender, NotifyCollectionChangedEventArgs e) { if (e.NewItems != null) { foreach (Human item in e.NewItems) { if (!item.Person.Contains(this)) { item.Person.Add(this); } } } if (e.OldItems != null) { foreach (Human item in e.OldItems) { if (item.Person.Contains(this)) { item.Person.Remove(this); } } } } #endregion } I thought that MVVM light update the item when I call RaisePropertyChanged. I am so confused. Thanks in advance. A: First option is try to get your auto-generated class to implement INPC if you can. Have a look at Fody.PropertyChanged If that's not possible, since it does have it's properties as "virtual", we can over-ride them in a derived class such as public class ObservablePerson : Person, INotifyPropertyChanged { public override int PersonId { get { return base.PersonId; } set { base.PersonId = value; OnPropertyChanged(); } } public override string PersonName { get { return base.PersonName; } set { base.PersonName = value; OnPropertyChanged(); } } public override int? PersonAge { get { return base.PersonAge; } set { base.PersonAge = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } } Now in your AdminViewModel work with objects of type ObservablePerson than Person
{ "pile_set_name": "StackExchange" }
Q: How do I replace only a specific value in an XML document without changing anything else? I've been trying to replace a specific value from an xml document in memory before creating a message log of the XML. I've managed to do a replace, but the Regex replace method seems to replace other items as well. I've had to make this a little more funky than I would have liked but the elements within the document can contain different XML namespaces... string pattern = "(<).*?(ElementName>).*?(<\\/).*?(ElementName>).*?"; string replacementPattern = "(<).*?(ReplacedElementName>)xxxxxxxxxxxxxx(<\\/).*?(ReplacedElementName>).*?"; string messageToLog = Regex.Replace(messageToSanitise, pattern, replacementPattern); Can anyone point out where I'm going wrong? [Update 16:11 BST 09/08/2013] Thanks Dash, I tried to do that, but then I realised that the object Contains an xml and isn't actually an xml document itself, looks like the object has some headers, with the xml is within a document envelope. Ideally I don't want to lose any information (including the headers) before logging. There will always be 1 or 2 occurences of the element I am trying to change never more and never less than 1. A: Given your xml is in the string messageToSantise, you can try the following: Using XmlDocument: (classic XML parsing common in older versions of the framework, and your only choice on older versions) XmlDocument messageDoc = new XmlDocument(); messageDoc.Load(messageToSanitise); messageDoc.SelectSingleNode(path_to_node).Value = replacementValue path_to_node can be used with the appropriate XPath expression. To get the xml string back out of the XmlDocument, use the messageDoc.OuterXml property. string messageToLog = messageDoc.OuterXml; Using XDocument: (xml parsing via a LINQ style mechanism, supported in new versions of the framework) XDocument messageDocument = new XDocument(); messageDocument.Parse(messageToSanitise); messageDocument.Element(path_to_element).value = replacementValue; To navigate through an XDocument, you may wish to also use the Descendents property. Examples of how to arrive at the node include this answer and the MSDN documentation here. To get the Xml from the XDocument, use messageDocument.ToString(); string messageToLog = messageDocument.ToString(); This allows you to specify exactly what you want to replace. If you want to decide whether to use XmlDocument or XDocument, I recommend reading the answer to this question.
{ "pile_set_name": "StackExchange" }
Q: Generating pdf using itextsharp in asp.net c# I want to generate pdf file as attached in the picture. i want to harcode the contents shown in the picture into a pdf file on button click. How do i proceed, using table structure will work?I am unable to form the table stucture here. Please help me to sort out my problem.i want the output as shown in below image. A: First create one table with two columns like below _______________________________________________ | | | | | | | | | | COL.0.1 | COL.0.2 | | | | | | | ----------------------------------------------- keep reference to its columns, then create table for left side content and insert it as child content of left column COL.0.1 ------------------------------ | designation: xxxxxxx | <---- colspan = 2 ------------------------------ | Audit No. | xxxx | ------------------------------ | Received on ....... | ------------------------------- and you can continue for the rest of content similar to this. The idea is to split content to smaller tables and nest them.
{ "pile_set_name": "StackExchange" }
Q: What's wrong when I use ImageApplyIndexed? I am reading a ebook called Basic image processing in Mathematica which can download free in the iBooks. In the page 114,it introduce a function ImageApplyIndexed. i = ConstantImage[Black, {50, 50}]; {width, height} = ImageDimensions@i; Clear[f]; f[pixel_, pos_] := Module[{dis = Norm[{width/2, height/2} - pos]}, pixel + dis/Norm[Min[width/2, height/2]]]; ImageApplyIndexed[f, i] output: But if I change the ImageSize of i: i = ConstantImage[Black, {100, 50}]; output: I don't know why the center of the black circle not in the center of the image? A: ImageApplyIndexed passes an index to your function, not X/Y coordinates, i.e. a list containing the row index and the column index (in that order). So you need to you Norm[{height/2, width/2} - pos. Because height is the number of rows, and width is the number of columns.
{ "pile_set_name": "StackExchange" }
Q: Rails and Authlogic. Show currently logged in users I would like to have the list of currently logged in users. This code doesn't work : <% UserSession.all.each do |user_session| %> <% end %> A: @syed-aslam has a good solution, but you could just let Authlogic do the work. Check out the module Authlogic::ActsAsAuthentic::LoggedInStatus which defines two scopes: logged_in, logged_out Your code becomes: <% User.logged_in.each do |user| %> <% end %> P.S. I would normally link to the RDoc instead of source code, but the RDoc seems to have problems at the moment. A: Authlogic gives you all kind of automatic columns that you don’t really need to update or maintain on your own, they are maintained by the actual code flow of Authlogic itself. Those fields can contain some basic functionality related issues like the number of login attempts made, the ip address from which the attempt was made an or even what was the ip address the last time that user logged in. fun. The magic column that will help us find who is probably online is the one called last_request_on, which basically indicates when was the last time that user made a request to your application. The second parameter we’ll need in order to make a more accurate selection, is the configuration option named logged_in_timeout, which sets the timeout after which a stale session will be expired, by default it will expire after 10 minutes. so if you set your session expiry to 30 minutes: class User << ActiveRecord::Base acts_as_authentic do |c| c.logged_in_timeout 30.minutes end end searching for those users is pretty easy: module OnlineUsers def count_online_users User.count(:conditions => ["last_request_at > ?", 30.minutes.ago]) end end
{ "pile_set_name": "StackExchange" }
Q: Avoding instanceof in Java In my application I have a 2d array of entities to represent a grid. Each location in the grid can either be empty or occupied by an entity (in this case it's just a person or wall). Right now I use instanceof to check whether an entity is a person or a wall. I was thinking of giving each entity a method which returns an enum stating their type so i.e. a wall entity would return EntityType.WALL. I was wondering if this is the best idea to remove the use of instanceof or is instanceof suitable in this scenario? A: Use Tell, Don't Ask: instead of asking the objects what they are and then reacting on that, tell the object what to do and then walls or people do decide how they do what they need to do. For example: Instead of having something like this: public class Wall { // ... } public class Person { // ... } // later public class moveTo(Position pos) { Object whatIsThere = pos.whatIsThere(); if (whatIsThere instanceof Wall) { System.err.println("You cannot move into a wall"); } else if (whatIsThere instanceof Person) { System.err.println("You bump into " + person.getName()); } // many more else branches... } do something like this: public interface DungeonFeature { void moveInto(); } public class Wall implements DungeonFeature { @Override public void moveInto() { System.err.println("You bump into a wall"); } // ... } public class Person implements DungeonFeature { private String name; @Override public void moveInto() { System.err.println("You bump into " + name); } // ... } // and later public void moveTo(Position pos) { DungeonFeature df = currentPosition(); df.moveTo(pos); } This has some advantages. First, you don't need to adjust a giant if then else tree each time you add a new dungeon feature. Second, the code in the dungeon features is self-contained, the logic is all in the said object. You can easily test it and move it. A: The theoretical solution to removing the instanceof in a refined way is the usage of the Visitor Pattern. How it works is that the object that needs to know whether the other element is a wall or person calls that object with itself as a parameter, and that particular object calls back thus providing information about its type. Example, public class Person { void magic() { if(grid.getAdjacent() instanceof Person) { Person otherPerson = (Person)grid.getAdjacent(); doSomethingWith(otherPerson); } else if(grid.getAdjacent() instanceof Wall) { Wall wall = (Wall)grid.getAdjacent(); doOtherThingWith(wall); } } } Can become public class Person extends Entity { void magic() { grid.getAdjacent().visit(this); } void onVisit(Wall wall) { doOtherThingWith(wall); } void onVisit(Person person) { doSomethingWith(person); } public void visit(Person person) { person.onVisit(this); } } public class Wall extends Entity { public void visit(Person person) { person.onVisit(this); } }
{ "pile_set_name": "StackExchange" }
Q: Reduce 0-1 knapsack prob. to a SAT prob Is there any way to reduce the 0-1 knapsack problem to a SAT problem in Conjunctive Norm Form? A: You could always work out the digital circuits necessary to implement adders and comparators and then turn the result of that into conjunctive normal form. You can get circuits into CNF form without expanding them exponentially by making up intermediate variables which represent the outputs of small sections of circuit. Each node of a circuit amounts to a=f(b, c) where a is the output, b and c the input, and f is some simple function like & or |. You can create a CNF function that is true only when a really is the result of f(b, c) and it can't be too unwieldy, because it is a function on only three variables. You can rewrite any circuit into a large number of terms of the form a=f(b, c) and all you have to do with the CNF versions of these is to AND them all together. Assuming you want to solve for the output being true, you then just stick on the output variable as the final component of that big AND.
{ "pile_set_name": "StackExchange" }
Q: Find value in array of objects I have an array of objects, each object contains n key/value pairs. I need to return an array of the objects which has a value matching x. Using Underscore.js I could use _.findWhere however I don't know what key the value will be under. I could obviously loop the array, fetch all of the keys in each object, then run _.findWhere on each key and check if the value is there, but it doesn't seem like a good way of doing this. A: I could obviously loop the array, fetch all of the keys in each object... Yes. Write a function that accepts an array and a value to look for in its elements members, loop over the array, loop over the keys of the current element, and push the objects containing a member with a matching value to an array and return it after the iteration. function findValues (arr,val) { var result = []; for (var i=0,current;i<arr.length;i++) { current = arr [i]; for (var key in current) { if (current [key] === val) { result.push (current); } } } return result } Here is an example output findValues ( [{ a:1, b:2, c:3 },{ a:1, b:2, },{ a:1, b:2, },{ a:1, b:2, c:3, d:4 },{ a:1, b:2, }], 3 ) //[{"a":1,"b":2,"c":3},{"a":1,"b":2,"c":3,"d":4}]
{ "pile_set_name": "StackExchange" }
Q: How to fix a workspace that has been opened with "Run as Administrator" in Eclipse? I opened Eclipse IDE with the "Run As Administrator" one day to do updates and install new software. Then I forgot, and continued to work on my project. Now, I can't work in that workspace unless I run Eclipse IDE with "Run As Administrator" which I would prefer not to do. Any suggestions on fixing this? A: Edit access rights of the workspace dir and give full access right to your user.
{ "pile_set_name": "StackExchange" }
Q: Yahoo Pipes and regex: Why does it work only for my first item? Here is my pipe: http://pipes.yahoo.com/pipes/pipe.info?_id=a732be6cf2b7cb92cec5f9ee6ebca756 I am currently trying to get the part before the first space to my item.url and the second part will be the title. For instance, first item is: http://carto1.wallonie.be/documents/terrils/fiche_terril.idc?TERRIL_id=1 Crachet 7/12 The expected result would be to get the "Crachet 7/12" as title and the other part as link. My regex query "([^\s]+)" seem to work only for my first item, I don't understand why, as all the items are formatted the same way. Thank a lot for any help! EDIT: Pictures to understand better: BEFORE REGEX AFTER REGEX Trying to check the g symbol A: You can use \S+ instead of [^\s]+. Also, you need to specify the "global" flag or the regex engine stops after the first successful match. In order to match only the first non-whitespace part of the line, use the ^ anchor with the "multiline" flag: /^\S+/gm or new RegExp("^\\S+", "gm") In your case, you need to check the appropriate checkboxes.
{ "pile_set_name": "StackExchange" }
Q: How can I set a listnode value to Null without getting this error? I just would Like to take a moment to thank Remy Lebeau for editing this post for me. MY compiler is giving me this error: main.cpp:93:20: error: invalid conversion from ‘int’ to ‘listnode*’ [-fpermissive] temp -> next = NULL; This is in the InsertTail method. I don't understand where the issue is. Can someone help me to solve this please? All I need is to be able to set the listnode value to Null. Here is my C++ file: program4.cpp #include <iostream> using namespace std; #undef NULL const int NULL = 0; typedef int element; const element SENTINEL = -1; element read_element(); class listnode{ public: element data; listnode * next; }; class LList { private: listnode * head; listnode * tail; public: LList(); ~LList(); void Print(); void InsertHead(element thing); void InsertTail(element thing); element DeleteHead(); void ReadForward(); void ReadBackward(); void Clean(); void Steal(LList & Victim); void Append(LList & Donor); void Duplicate(LList & Source); void Reverse(); }; void LList::Print(){ // PRE: the N. O. LList is valid // POST: the N. O. LList is unchanged, and its elements // have been displayed listnode * temp; temp = head; while (temp != NULL){ cout << temp -> data << endl; temp = temp -> next; } } void LList::ReadForward(){ // PRE: the N. O. LList is valid // POST: the N. O. LList is valid, all of its previous // listnodes have been deleted, and it now // consists of new listnodes containing elements // given by the user in forward order element userval; Clean(); cout << "Enter elements, " << SENTINEL << " to stop: "; userval = read_element(); while (userval != SENTINEL){ InsertTail(userval); userval = read_element(); } } void LList::InsertTail(element thing){ // PRE: the N. O. LList is valid // POST: the N. O. LList is unchanged, except that a // new listnode containing element thing has been // inserted at the tail-end of the list listnode * temp; temp = new listnode; temp -> data = thing; temp -> next = NULL; if (head == NULL) head = temp; else tail -> next = temp; tail = temp; } element read_element(){ // PRE: the user must enter a series of zero or // more non-valid element values, followed // by a valid element value // // POST: all entered non-valid element values will // be successfully discarded, and the first // valid element value entered will be // returned element userval; cin >> boolalpha >> userval; while (! cin.good()){ cin.clear(); cin.ignore(80, '\n'); cout << "Invalid data type, should be an element, " << "try again: "; cin >> boolalpha >> userval; } return userval; } void LList::ReadBackward(){ // PRE: the N. O. LList is valid // POST: the N. O. LList is valid, all of its previous // listnodes have been deleted, and it now // consists of new listnodes containing elements // given by the user in backward order element userval; Clean(); cout << "Enter elements, " << SENTINEL << " to stop: "; userval = read_element(); while (userval != SENTINEL){ InsertHead(userval); userval = read_element(); } } void LList::InsertHead(element thing){ // PRE: the N. O. LList is valid // POST: the N. O. LList is unchanged, except that a // new listnode containing element thing has been // inserted at the head-end of the list listnode * temp; temp = new listnode; temp -> data = thing; temp -> next = head; if (head == NULL) tail = temp; else ; head = temp; } void LList::Clean(){ // PRE: the N. O. LList is valid // POST: the N. O. LList is valid and empty, and all of // its listnodes have been deleted while (head != NULL) DeleteHead(); } element LList::DeleteHead(){ // PRE: the N. O. LList is valid and not empty // POST: the N. O. LList is unchanged, except that the // listnode at the head end of the list has been // deleted, and its data element has been // returned listnode * temp; element thing; temp = head; head = head -> next; thing = temp -> data; delete temp; return thing; } LList::LList(){ // PRE: none // POST: the N. O. LList is valid and empty head = NULL; } LList::~LList(){ // PRE: the N. O. LList is valid // POST: the N. O. LList is valid and empty, and its // listnodes have been deleted Clean(); } void LList::Steal(LList & Victim){ // PRE: the N. O. and Victim LLists are valid // POST: the Victim LList is valid and empty // the N. O. LList is valid, all of its previous // listnodes have been deleted, and it now // consists of the listnodes originally on the // Victim LList Clean(); head = Victim.head; tail = Victim.tail; Victim.head = NULL; } void LList::Append(LList & Donor){ // PRE: the N. O. and Donor LLists are valid // POST: the Donor LList is valid and empty // the N. O. LList is valid, and it now consists // of its own original listnodes followed by the // listnodes originally on the Donor LList if (head != NULL) tail -> next = Donor.head; else head = Donor.head; if (Donor.head != NULL) tail = Donor.tail; else ; Donor.head = NULL; } void LList::Duplicate(LList & Source){ // PRE: the N. O. and Source LLists are valid // POST: the Source LList is unchanged // the N. O. LList is valid, all of its previous // listnodes have been deleted, and it now // consists of listnodes containing the same // elements and in the same order as on the // Source LList listnode * temp; Clean(); temp = Source.head; while (temp != NULL){ InsertTail(temp -> data); temp = temp -> next; } } void LList::Reverse(){ // PRE: the N. O. LList is valid // POST: the N. O. LList is unchanged, except its // elements are in reverse order listnode * temp; LList Helper; temp = head; while (temp != NULL){ Helper.InsertHead(temp -> data); temp = temp -> next; } Steal(Helper); } iny main(){ cout << "creating/constructing LList object L" << endl; LList L; cout << "L has been created/constructed" << endl; cout << "L is calling its print method" << endl; L.Print(); cout << "L has been printed" << endl; cout << "L is calling its ReadForward method" << endl; L.ReadForward(); cout << "L has been read forward" << endl; cout << "L is calling its Print method" << endl; L.Print(); cout << "L has been printed" << endl; cout << "L is calling its ReadBackward method" << endl; L.ReadBackward(); cout << "L has been read backward" << endl; cout << "L is calling its Print method" << endl; L.Print(); cout << "L has been printed" << endl; cout << "L is calling its Clean method" << endl; L.Clean(); cout << "L has been cleaned" << endl; cout << "L is calling its Print method" << endl; L.Print(); cout << "L has been printed" << endl; } A: The reason of the error this code #undef NULL const int NULL = 0; It is unclear why you decided to use it. But to avoid the error just remove these two lines. This declaration const int NULL = 0; does not introduce a null-pointer constant. Moreover instead of NULL you could use nullptr. Pay attention to that the class listnode should be a private member of the class LList. For example class LList { private: struct listnode{ element data; listnode * next; } *head = nullptr, *tail = nullptr; //...
{ "pile_set_name": "StackExchange" }
Q: Autocompletion library in C++ I need an auto-completion routine or library in C++ for 1 million words. I guess I can find a routine on the net like Rabin–Karp. Do you know a library that does this. I don't see it in Boost. Also, is it a crazy idea to use MySql LIKE SQL request to do that ? Thank you EDIT: It is true that it is more suggestions than auto-completion that I need (propose ten words when the user typed the first 2 letters). I actually also have expressions "Nikon digital camera". But for a first version, I only need suggestions on "Ni" of Nikon and not on "digital camera". A: You don't have to use any crazy algorithm if you begin by preparing an index. A simple Trie/Binary Search Tree structure, that keeps the words ordered alphabetically, would allow efficient prefix searches. In C++, for example, the std::map class has the lower_bound member which would point in O(log N) to the first element that could possibly extend your word.
{ "pile_set_name": "StackExchange" }
Q: Passing parameters in the Form constructor, winforms c# I have a following inheritance hierarchy: Class A : Form Class B : Class A Class A needs to be able to accept a parameter so that I can create the instance of Class B like this: ClassB mynewFrm = new ClassB(param); How do I define such a constructor in Class A? thanks! I am using Winforms in .net 3.5, c# EDITED: Class A and Class B are defined as forms, using partial classes. So I guess this is turning into a question about partial classes and custom (overriden) constructors. A: Here is a complete demo sample that demostrates required behaviour. For the sake of ease your learning, I chose a string type parameter that you adjust to your case. To test it, create a new Visual Studio *C#* project and fill program.cs with the following code using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace Stackoverflow { public class ClassA : Form { public ClassA() { InitializeComponent(); } public ClassA(string WindowTitleParameter) { InitializeComponent(); this.Text = WindowTitleParameter; MessageBox.Show("Hi! I am ClassB constructor and I have 1 argument. Clic OK and look at next windows title"); } private void InitializeComponent() // Usually, this method is located on ClassA.Designer.cs partial class definition { // ClassA initialization code goes here } } public class ClassB : ClassA { // The following defition will prevent ClassA's construtor with no arguments from being runned public ClassB(string WindowTitleParameter) : base(WindowTitleParameter) { InitializeComponent(); //this.Text = WindowTitleParameter; //MessageBox.Show("Hi! I am ClassB constructor and I have 1 argument. Clic OK and look at next windows title"); } private void InitializeComponent() // Usually, this method is located on ClassA.Designer.cs partial class definition { // ClassB initialization code goes here } } static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // If you debug this code using StepInto, you will notice that contructor of ClassA (argumentless) // will run prior to contructor of classB (1 argument) Application.Run(new ClassB("Look at me!")); } } }
{ "pile_set_name": "StackExchange" }
Q: Jquery doesn't update an attribute as expected I have an MVC App and on one of my pages as part of the display I will render one of two partials based on a user selection of a radio button. This bit all works ok, but I have a button on the main form where I need to set/reset values that will be passed to my controller based on the user selection. The button is declared on my main form as: @Html.GlobalModalAuthorizeButton("Upload Document", "Upload", "Documents", new { serviceUserId = Model.ServiceUser.Id, folderId = Model.CurrentFolderId, viewType = Model.ViewTypes.ToString() }, new { @class = "icon upload btn-primary" }) when this page is initially rendered the viewtype is set to the default view that the user is initially presented with. when the user changes the view the viewtype doesn't seem to get updated. So from the partial that has been loaded I try to set the value to the correct value. Using the Chrome browsers Developer tools if I do the following: $(this).parent().parent().parent().parent().find($('.upload')).attr('data-url').replace('FileView', 'TreeView'); it returns in the console window the value I want (idea is that i set the value on the button before the user presses it). The trouble is the above doesn't really seem to have changed the data-url attribute on the button so consequently when the controller is hit, 'FileView' is still passed through. A: For full attribute: var new_attr = "/ServiceUser/Documents/Upload?serviceUserId=21&viewType=FileView"; $(this).parent().parent().parent().parent().find($('.upload')).attr('data-url', new_attr); Or, as @Rup already suggested, you should first get the original attribute value, modify that using replace method and then reassign the new_attr.
{ "pile_set_name": "StackExchange" }
Q: Closed launchd in OS X, the screen is now blank I have a 2 year old Mac book running whatever the newer OS X is. For some reason I was playing in activity manager and deleted launchd and now I'm just looking at a blank screen and my computer won't even shut down. Please help? A: Hold down the power button for 10 full seconds. If somehow that doesn't shut it down, just pull the power (both the AC power adapter and the battery, if your model has an externally removable battery).
{ "pile_set_name": "StackExchange" }
Q: How to input data into table from MySQL? I've created a page that is supposed to pull all the domains from my database and display them in a table. Pagination is setup to show 1002 domains per page and the table should be 3 columns. When I'm not sure what to do is towards the end where you can see "Row Test1" and "Row Test1" - those show up on the page correctly. However, how do I make it so that instead of showing those, it will actually show the domains from my database. If someone can post an example of the fixed part of the code it would be highly appreciated, I feel like I've been trying so many things and it's getting a bit confusing. Here's the entire code: <?php include("header.html"); ?> <center> <?php /* Place code to connect to your DB here. */ include('database.php'); // include your code to connect to DB. $tbl_name="list"; //your table name // How many adjacent pages should be shown on each side? $adjacents = 3; /* First get total number of rows in data table. If you have a WHERE clause in your query, make sure you mirror it here. */ $query = "SELECT COUNT(*) as num FROM $tbl_name"; $total_pages = mysql_fetch_array(mysql_query($query)); $total_pages = $total_pages[num]; /* Setup vars for query. */ $targetpage = "index.php"; //your file name (the name of this file) $limit = 1002; //how many items to show per page $page = $_GET['page']; if($page) $start = ($page - 1) * $limit; //first item to display on this page else $start = 0; //if no page var is given, set start to 0 /* Get data. */ $sql = "SELECT website FROM $tbl_name LIMIT $start, $limit"; $result = mysql_query($sql); /* Setup page vars for display. */ if ($page == 0) $page = 1; //if no page var is given, default to 1. $prev = $page - 1; //previous page is page - 1 $next = $page + 1; //next page is page + 1 $lastpage = ceil($total_pages/$limit); //lastpage is = total pages / items per page, rounded up. $lpm1 = $lastpage - 1; //last page minus 1 /* Now we apply our rules and draw the pagination object. We're actually saving the code to a variable in case we want to draw it more than once. */ $pagination = ""; if($lastpage > 1) { $pagination .= "<div class=\"pagination2\">"; //previous button if ($page > 1) $pagination.= "<a href=\"$targetpage?page=$prev\">&lt; previous</a>"; else $pagination.= "<span class=\"disabled\">&lt; previous</span>"; //pages if ($lastpage < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up { for ($counter = 1; $counter <= $lastpage; $counter++) { if ($counter == $page) $pagination.= "<span class=\"current\">$counter</span>"; else $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>"; } } elseif($lastpage > 5 + ($adjacents * 2)) //enough pages to hide some { //close to beginning; only hide later pages if($page < 1 + ($adjacents * 2)) { for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++) { if ($counter == $page) $pagination.= "<span class=\"current\">$counter</span>"; else $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>"; } $pagination.= "..."; $pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>"; $pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>"; } //in middle; hide some front and some back elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) { $pagination.= "<a href=\"$targetpage?page=1\">1</a>"; $pagination.= "<a href=\"$targetpage?page=2\">2</a>"; $pagination.= "..."; for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++) { if ($counter == $page) $pagination.= "<span class=\"current\">$counter</span>"; else $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>"; } $pagination.= "..."; $pagination.= "<a href=\"$targetpage?page=$lpm1\">$lpm1</a>"; $pagination.= "<a href=\"$targetpage?page=$lastpage\">$lastpage</a>"; } //close to end; only hide early pages else { $pagination.= "<a href=\"$targetpage?page=1\">1</a>"; $pagination.= "<a href=\"$targetpage?page=2\">2</a>"; $pagination.= "..."; for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++) { if ($counter == $page) $pagination.= "<span class=\"current\">$counter</span>"; else $pagination.= "<a href=\"$targetpage?page=$counter\">$counter</a>"; } } } //next button if ($page < $counter - 1) $pagination.= "<a href=\"$targetpage?page=$next\">next &gt;</a>"; else $pagination.= "<span class=\"disabled\">next &gt;</span>"; $pagination.= "</div>\n"; } ?> <?php $i = 0; echo '<table><tr>'; while($row = mysql_fetch_array($result)) { $i ++; if ($i<=2) { echo '<td> <div>Row Test1</div> </td>'; } else { echo '</tr><tr>'; echo '<td><div>Row Test2</div></td>'; $i = 0; } } echo '</tr></table>'; ?> <?=$pagination?> </center> <?php include("footer.html"); ?> A: I am a bit unsure why you need to split your row prints in your while statement. The while statement will print out results for all that whether that be one, twenty, or none so long as the statement evaluates true.. <?php $i = 0; echo '<table><tr>'; while($row = mysql_fetch_array($result)) { $i ++; echo '<td><div>'.$row[databasecolumnnamethatcontainsurlgoeshere].'</div></td>'; } echo '</tr></table>'; ?>
{ "pile_set_name": "StackExchange" }
Q: Am I locked to one solc version for upgradeable smart contracts? I want to use delegatecall to make my contracts upgradeable. Is it true that variable layout may break if I change the solc version and therefore I should use the same Solidity version for all future versions of my contract? A: From Solidity the documentation: The layout of state variables in storage is considered to be part of the external interface of Solidity due to the fact that storage pointers can be passed to libraries. This means that any change to the rules outlined in this section is considered a breaking change of the language and due to its critical nature should be considered very carefully before being executed. Since that kind of changes might break a lot of already deployed contracts my guess is that they will not change the layout unless there's a very very good reason to do so.
{ "pile_set_name": "StackExchange" }
Q: Send gridview data from client side to server side at once In an ASP.NET 2.0 web application, there is a gridview containing checkbox in first column. When checkbox is checked either Header Checkbox or Row Checkbox, OnCheckChange event triggers on server side. In this event, the specfic row data or all rows data (in case of header checkbox) is added to a data table in session for further processing. Along side this, it call a few javascript function as well to check/uncheck the checkboxes, highlight the row on client side. In case, when user wanted to check multiple checkbox but not via header checkbox. It's behavior gets wrong. If user quickly check the checkbox, few checkboxes are checked and few remain unchecked. What I guess is that since on each OnCheckChange event there is a request to server side and then some js methods so it takes time, but befor request completeed, user checked the next checkbox and it is not actually checked. Is there any way, I can allow user to check how many checkboxes he/she wants to check and then send them to server for storing in data table ? Suggestions are appreciated. A: You should add loader for this kind of functionality. I hope you should be using update panel. You can add update progress control for the time request is processing on server side. It will hint the user to wait. You can also use ajax request by jquery to do similar kind of work.
{ "pile_set_name": "StackExchange" }
Q: ListView+Viewpager Android I am confused on implementing a design. I have a list of items which I want to show in a ListView. Now what I want to achieve is that the listview would show first 4 items and to view the next set of items, I want to enable view pager instead of vertical scrolling i.e the next set of 4 items should appear on the next page of the view pager. Sorry, I just want to get a clear picture. How can I achieve this? Thanks. EDIT* Something like so if I have a list of 8 items. A: Look use a list view. Just show your first fours item as interviewees. And then the fifth item of list View will be View Pager. And pass all the remaining data list after first four elements to this view Pager Adapter which will show the rest of elements in horizontal scrolling of view Pager. But do not use List View and view pager in a same hierarchy. This will cause you problem in scrolling and touch events. You can use different views for different items in List View. Better to switch to Recycler View instead of List View. Just have fifth element view a viewPager. I hope this will solve your problem. Let me know if you have any problem in achieving this. <*EDIT> Hey I did some workaround with ViewPager and RecyclerView as you said. Look at the screen Shots below. I hope you want to achieve as same. For Any issue drop a comment. I will try to help you out once I get time. You can find the source code at https://github.com/MacSimmy/SpannableRecyclerViewExample which is my Github profile. enter image description here
{ "pile_set_name": "StackExchange" }
Q: how to remove path of my command line? When I start to enter in different folder the path is registered in my command line and I don't know how to remove it. I am almost sure my question wasn't clear. An example is always better. Once in home: luiz@feynman:~$ cd Music/ luiz@feynman:~/Music$ cd Beatles/ luiz@feynman:~/Music/Beatles$ cd 17\ Love/ What is annoying me is this :~/Music or ~/Music/Beatles before $. It seems a stupid problem but when I need to enter into many folders is really a big problem. I guess I should change something in my .bashrc, but I don't know what. Thanks A: You can use this prompt for PS1 PS1='\u@\h: $(x=$(pwd); l=${#x}; if [ $l -lt 24 ]; then echo $x; else echo ... ${x: -20};fi;)\$' Just put this at the very end of your .bashrc. From now every time you go to a path with a length greater than 24 it'll show the last 20 characters preceding by .... In fact when we go deep down a directory only the last directories become significant. Because we already know where we started. A: look at and edit the value of $PS1. It contains the template for your prompt. Something like '\u@\h \w $ ' is typical, in this the '\w' is a placeholder for the working directory. SettingPS1'\u@\h $ '` would remove the working directory. For full details on how to set PS1, consult the bash man page
{ "pile_set_name": "StackExchange" }
Q: Jquery how to select all element but children I have a code like that: <div id="mn"> <span></span> <span> <span></span></span> <span></span> <span> <span></span></span> <span></span> </div> when i use: $("#mn").each(function(index, element) { )}; it selects all span tags and span inside span tags, how do i select only parents span tags. A: you can do this way: $("#mn > span").each(function(index, element) { )}; This will only give immediate child span elements. JQUERY DOCS
{ "pile_set_name": "StackExchange" }
Q: How to avoid redundant data (list fetching) in JPA One To Many mapping (Two One to Many relation in same model)? I have three Model. BookingDetail have One To Many relation to both LookupFoodItem and LookupFacility model.In my database there is 4 LookupFacility record and 4 LookupFoodItem record. When I'm fetching BookingDetail one record there should be 4 LookupFoodItem record but I found 16 record which is redundant.How can I solve this problem to get only real record not redundant data? public class BookingDetail { @OneToMany(mappedBy = "bookingDetail", cascade = CascadeType.ALL, fetch = FetchType.EAGER) public List<LookupFacility> lookupFacilities; @OneToMany(mappedBy = "bookingDetail", cascade = CascadeType.ALL, fetch = FetchType.EAGER) public List<LookupFoodItem> lookupFoodItems; } public class LookupFacility { @ManyToOne @JoinColumn(name="booking_details_id") BookingDetail bookingDetail; } public class LookupFoodItem{ @ManyToOne @JoinColumn(name="booking_details_id") BookingDetail bookingDetail; } When I'm fetching BookingDetail information from database using JPA it's giving me redundant data like this LookupFoodItem{id=40, name='Beef ', price=120.0} LookupFoodItem{id=41, name='Polao', price=300.0} LookupFoodItem{id=42, name='Crab Fry', price=299.0} LookupFoodItem{id=43, name='Chicken Soup', price=100.0} LookupFoodItem{id=40, name='Beef ', price=120.0} LookupFoodItem{id=41, name='Polao', price=300.0} LookupFoodItem{id=42, name='Crab Fry', price=299.0} LookupFoodItem{id=43, name='Chicken Soup', price=100.0} LookupFoodItem{id=40, name='Beef ', price=120.0} LookupFoodItem{id=41, name='Polao', price=300.0} LookupFoodItem{id=42, name='Crab Fry', price=299.0} LookupFoodItem{id=43, name='Chicken Soup', price=100.0} LookupFoodItem{id=40, name='Beef ', price=120.0} LookupFoodItem{id=41, name='Polao', price=300.0} LookupFoodItem{id=42, name='Crab Fry', price=299.0} LookupFoodItem{id=43, name='Chicken Soup', price=100.0} There is no relation between LookupFoodItem and LookupFacilities. A: Not sure if you are using LOMBOK or actually missing the getters and setter so I added it here. Used Set instead of List and changed the fetching to Lazy. This is from one of my working solutions. Hope this helps. Feel free to change the annotations as needed For more details this has some info public class BookingDetail { private Set<LookupFacility> lookupFacilities = new HashSet<LookupFacility>(); private Set<LookupFoodItem> lookupFoodItems = new HashSet<LookupFoodItem>(); @OneToMany(fetch = FetchType.LAZY, mappedBy = "bookingDetail", cascade = CascadeType.ALL, orphanRemoval = true) @Fetch(FetchMode.SUBSELECT) public Set<LookupFacility> getLookupFacilities() { return lookupFacilities; } public void setLookupFacilities(final Set<LookupFacility> lookupFacilities) { this.lookupFacilities = lookupFacilities; } @OneToMany(fetch = FetchType.LAZY, mappedBy = "bookingDetail", cascade = CascadeType.ALL, orphanRemoval = true) @Fetch(FetchMode.SUBSELECT) public Set<LookupFoodItem> getLookupFoodItems() { return lookupFoodItems; } public void setLookupFoodItems(final Set<LookupFoodItem> lookupFoodItems) { this.lookupFoodItems = lookupFoodItems; } } And for class LookupFacility and LookupFoodItem us this private BookingDetail bookingDetail; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "booking_details_id") public BookingDetail getBookingDetail() { return bookingDetail; } public void setBookingDetail(BookingDetail bookingDetail) { this.bookingDetail = bookingDetail; }
{ "pile_set_name": "StackExchange" }
Q: Reading file backward while using variable from first line I want to read a file back ward while using a variable present in the first line (here: 2636). My file: nx_ 2355 ny_ 2636 0.000000 0.000000 0.000000 1.000000 68.000000 0.428139 2.000000 68.000000 0.939878 3.000000 67.000000 0.757181 4.000000 68.000000 0.000000 5.000000 69.000000 -1.229728 To read the file forward, and process it, I used: cat $1 | awk 'NR==1 {nb=$4} NR>1 {up=nb-$1; print $2,up,$3}' To read the file backward it seems I should use tac, but I don't know how to retrieve the variable in the first line, and avoid to process the last line. I am searching for something like this: tac $1 | awk 'NR==END {nb=$4} NR<END {up=nb-$1; print $2,up,$3}' I want to have as output: 69.000000 2631 -1.229728 68.000000 2632 0.000000 67.000000 2633 0.757181 68.000000 2634 0.939878 68.000000 2635 0.428139 0.000000 2636 0.000000 A: Is this what you're trying to do? $ awk 'NR==1{nb=$4; next} {print $2, nb-$1, $3}' file | tac 69.000000 2631 -1.229728 68.000000 2632 0.000000 67.000000 2633 0.757181 68.000000 2634 0.939878 68.000000 2635 0.428139 0.000000 2636 0.000000 If you really did have to do what you said you wanted to do then that'd be this: $ read -r _ _ _ nb < file; tail +2 file | tac | awk -v nb="$nb" '{print $2, nb-$1, $3}' 69.000000 2631 -1.229728 68.000000 2632 0.000000 67.000000 2633 0.757181 68.000000 2634 0.939878 68.000000 2635 0.428139 0.000000 2636 0.000000 or this: $ read -r _ _ _ nb < file; tac file | awk -v nb="$nb" 'NR>1{print p[2], nb-p[1], p[3]} {split($0,p)}' 69.000000 2631 -1.229728 68.000000 2632 0.000000 67.000000 2633 0.757181 68.000000 2634 0.939878 68.000000 2635 0.428139 0.000000 2636 0.000000 or similar but it seems unlikely that's what you really need given the script you posted. If the above doesn't answer your question then edit your question to clarify your requirements and provide the expected output given your posted sample input.
{ "pile_set_name": "StackExchange" }
Q: Using backspace with getch() in python curses I want the user to be able to type with each character, the way that getch() works. I also have echo() turned on because I want to print out each character that the user types. However, I also want the user to be able to hit backspace and have the key that he pressed before he hit backspace to be deleted from the screen, just like how backspace works in a text editor. How can I do this? I am using python 3.6 with the curses lib (obviously). If you want to see my code so far, here it is: import curses # ----- INIT ----- stdscr = curses.initscr() curses.cbreak() stdscr.keypad(1) # ----- PRINT ----- text = "Hello world" stdscr.addstr(1, 0, text + "\n") stdscr.refresh() # ----- MAIN LOOP ------ while 1: c = stdscr.getch() if c == ord('q'): break # ----- RESET TERMINAL ----- curses.echo() curses.nocbreak() stdscr.keypad(1) curses.endwin() A: You could do something like this: disable echo, use explicit library calls to echo the characters other than the usual choices for "backspace": import curses # ----- INIT ----- stdscr = curses.initscr() curses.cbreak() curses.noecho() stdscr.keypad(1) # ----- PRINT ----- text = "Hello world" stdscr.addstr(1, 0, text + "\n") stdscr.refresh() # ----- MAIN LOOP ------ while 1: c = stdscr.getch() if c == ord('q'): break if c == 8 or c == 127 or c == curses.KEY_BACKSPACE: stdscr.addstr("\b \b") else: stdscr.addch(c) # ----- RESET TERMINAL ----- curses.echo() curses.nocbreak() stdscr.keypad(1) curses.endwin() The Python curses reference does not go into much detail for addch, but since it is a wrapper around curses, you can read its manual page about the way the literal backspace \b is interpreted to make the cursor move backward. The example then writes a space (erasing whatever was there), and then moves the cursor back onto the empty space.
{ "pile_set_name": "StackExchange" }
Q: how to update record in rails controller am using stripe for users to subscribe. from there i collected the stripe date and save it in subscription mode. i created enum for my user model to assign different roles base on the stripe subscription id. here is how my user model looks like class User < ApplicationRecord enum role: [:user, :gold, :platinum, :diamond ] has_one :subscription has_one :shipping extend FriendlyId friendly_id :firstname, use: [:slugged, :finders] # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable end and bellow is my subscription controller def subscription_checkout user = current_user plan_id = params[:plan_id] plan = Stripe::Plan.retrieve(plan_id) # This should be created on signup. customer = Stripe::Customer.create( description: 'Customer for test@example.com', source: params[:stripeToken], email: 'test@example.com' ) # Save this in your DB and associate with the user;s email stripe_subscription = customer.subscriptions.create(plan: plan.id) @sub = Subscription.create(plan: stripe_subscription.plan.name, stripeid: stripe_subscription.id, user_id: current_user.id, customer: stripe_subscription.customer, subscriptionenddate: stripe_subscription.current_period_end) if @sub.save current_user.role plan.id current_user.save flash[:success] = 'sub created!' redirect_to root_url else render 'new' end end when it reach to update the role i get ArgumentError: wrong number of arguments (1 for 0) how can i update the role and what am i doing wrong? A: Have you tried: current_user.role = plan.id ? It looks like you are just calling the role() method on the curent_user object.
{ "pile_set_name": "StackExchange" }
Q: dSPACE ControlDesk error - No free memory available.[0.000] When using a large sampling rate, no data could be measured (displayed yes but not plotted/stored) and I get the following error from the log file: ControlDesk NG Platform: Error 16:19:41 0,0:No free memory available.[0.000] (0xCA,1) dSPACE used - RT1104 ControlDesk version - 5.5 Operating System details: A: It is indeed coming from the Real-TimePlatform. The memory depends on the number of measured signals, the raster speed and the dureation trigger length in the ControlDesk measurment configuration. On the hardware, a buffer is created to be able to hold one entire trigger shot, which may fail if it does not fit to the RAM. Often a long trigger duration is used causing this problem. Then, the soultion is to measure continuously, which the user most of the time wants instead. See http://www.dspace.com/faq?408 15kHz is quite fast for the ds1104, by the way, try with litte # of measurements if it works. Regards, the dspace support :) (I answered just because i found this question randomly, please contact support@dspace.de (or your local dSPACE company) if you need us!
{ "pile_set_name": "StackExchange" }
Q: Optimize SQL query multiple joins with count tables By any chance you would be able to help optimize this query without me showing you the tables? My original table that all of these queries are derived from has the following columns and the table is named laterec-students -------------------------------------------------------------- | studentid | name | class | latetime | waived | -------------------------------------------------------------- | ID1111STU | Stu 1 | 1A |2012-01-09 08:09:00 |Waived | SELECT A.class, NoStudentsLate, 1xLATE, 2xLATE FROM ( SELECT class, count(DISTINCT studentid) AS NoStudentsLate FROM `laterec-students` WHERE waived!="Waived" GROUP BY class ) AS A LEFT JOIN ( SELECT class, count(distinct studentid) AS 1xLATE from ( SELECT `laterec-students`.class, `laterec-students`.studentid FROM `laterec-students` WHERE waived!="Waived" GROUP BY studentid HAVING count(studentid)=1) as temp GROUP BY class ) AS B ON A.class=B.class LEFT JOIN ( SELECT class, count(distinct studentid) AS 2xLATE from ( SELECT `laterec-students`.class, `laterec-students`.studentid FROM `laterec-students` WHERE waived!="Waived" GROUP BY studentid HAVING count(studentid)=2) as temp GROUP BY class ) AS C ON A.class=C.class This is what I am trying to accomplish --------------------------------------------------------------------- | Class | Total # of students late | # late 1 times | # late 2 times | --------------------------------------------------------------------- | 1A | 5 | 3 | 2 | | 1B | 3 | 3 | 0 | --------------------------------------------------------------------- So what this means, in class 1A, there are a total of 5 student late as counted using the student id. Out of this 5, 3 students are late once, and 2 students are late twice. Again in class 1B, total 3 students are late, and all of them are only late once. A: I hope that I understood your query, but the following works with my SQL Fiddle example. SELECT class, SUM(cnt > 0) AS NoStudentsLate, SUM(cnt = 1) AS 1xLate, SUM(cnt = 2) AS 2xLate FROM ( SELECT class, studentid, COUNT(*) AS cnt FROM `laterec-students` WHERE waived!='Waived' GROUP BY class, studentid ) t GROUP BY class;
{ "pile_set_name": "StackExchange" }
Q: Change the check box position In the view I've browse file and check box currenlty the check Box is above the browse control and I want it to be in the left side of it,how should I change it? <div class="form-group"> @Html.LabelFor(model => model.Cert, new { @class = "control-label col-md-2" }) <div class="col-md-10"> @if (Model.Certificate !=null) { <input type="checkbox" checked="checked" disabled="disabled" /> } else { <input type="checkbox" disabled="disabled" /> } <input type="file" name=ficateFile /> </div> </div> A: Without seeing your full code and css this is a tricky thing to answer however perhaps you could try this? input[type=checkbox], input[type=file] { display: inline-block; } If that doesnt work you could allways split the checkbox and file upload into 2 columns eg <div class="form-group"> <div class="col-md-2"></div> <!-- Label --> <div class="col-md-2"></div> <!-- Checkbox --> <div class="col-md-8"></div> <!-- File Upload --> </div>
{ "pile_set_name": "StackExchange" }
Q: Python: drop duplicated index in pandas dataframe I have the date as below and the Date as Index. I want to remove the duplicated Date Stock Open High Low Close Adj Close Volume Date 2016-05-13 AAD 5.230000 5.260000 5.200000 5.260000 5.260000 5000 2016-05-16 AAD 5.220000 5.260000 5.220000 5.260000 5.260000 6000 2016-05-17 AAD 5.210000 5.260000 5.210000 5.260000 5.260000 2000 2016-05-17 AAD 5.210000 5.260000 5.210000 5.260000 5.260000 2000 2016-05-18 AAD 5.200000 5.250000 5.200000 5.250000 5.250000 3000 The output I needed Stock Open High Low Close Adj Close Volume Date 2016-05-13 AAD 5.230000 5.260000 5.200000 5.260000 5.260000 5000 2016-05-16 AAD 5.220000 5.260000 5.220000 5.260000 5.260000 6000 2016-05-17 AAD 5.210000 5.260000 5.210000 5.260000 5.260000 2000 2016-05-18 AAD 5.200000 5.250000 5.200000 5.250000 5.250000 3000 I try by using df.drop_duplicates() and the output delete extra lines after the duplicated date. Stock Open High Low Close Adj Close Volume Date 2016-05-13 AAD 5.230000 5.260000 5.200000 5.260000 5.260000 5000 2016-05-16 AAD 5.220000 5.260000 5.220000 5.260000 5.260000 6000 2016-05-17 AAD 5.210000 5.260000 5.210000 5.260000 5.260000 2000 A: Let's use the information Jezrael provided. Input Dataframe: print(df) Stock Open High Low Close Adj Close Volume 2016-05-13 AAD 5.23 5.26 5.20 5.26 5.26 5000 2016-05-16 AAD 5.22 5.26 5.22 5.26 5.26 6000 2016-05-17 AAD 5.21 5.26 5.21 5.26 5.26 2000 2016-05-17 AAD 5.21 5.26 5.21 5.26 5.26 2000 2016-05-18 AAD 5.20 5.25 5.20 5.25 5.25 3000 df1 = df[~df.index.duplicated(keep='last')] print(df1) Output: Stock Open High Low Close Adj Close Volume 2016-05-13 AAD 5.23 5.26 5.20 5.26 5.26 5000 2016-05-16 AAD 5.22 5.26 5.22 5.26 5.26 6000 2016-05-17 AAD 5.21 5.26 5.21 5.26 5.26 2000 2016-05-18 AAD 5.20 5.25 5.20 5.25 5.25 3000
{ "pile_set_name": "StackExchange" }
Q: Was Valentino the first person to be called ‘sexy’? According Etymonline , the term sexy underwent a semantic change in the early 1920s when it was used to for the first time with the connotation of “sexually attractive” in reference to Rudolph Valentino: Sexy: 1905, from sex (n.) + -y (2). Originally "engrossed in sex;" sense of "sexually attractive" is 1923, first in reference to Valentino. An earlier word in this sense was sexful (1898). I couldn’t find any evidence of sexy used at that time referring to Valentino in Google Books or other online sources. Questions: Was the term “sexy” meaning attractive really first used for Valentino in the early 1920s or was this usage already in place in before then? Is there evidence that “sexy” was used at that time to refer to the famous actor? A: Etymonline seems to be out of date here. The earliest examples in this sense are from before Valentino was even in a movie (at least according to the Wikipedia page linked in the question). I found what looks to be a really early example from 1901: You should always take a windy day when you wish to study the Sex; because on a calm day the Sex is not, so to speak, anything like so sexy. The Clipper The Oxford English Dictionary gives an example from 1912: If a woman is genuinely keen to win the affections of a man she is a universal woman of the real sexy sort. Colorado Springs Gazette The OED also has an example from the 1923 LA Times referring to both men and women, but this doesn't seem to be the quote Etymonline is referring to either: Even Elinor Glyn, who rather specializes in sexy heroines, has obviously been confronted with this type... The sexiest men have quite a number of other and more important interests. Also, Etymonline asserts that the first use of the word (in any sense) was first used in 1905, but the OED has an earlier quote from 1896 (albeit with a different spelling): Lane had decided..not to handle your work of genius, on the score that it was seksy & America didn't want no seks-problems. A. Bennett's Letters (Do note that "seksy" means "erotic" in the above quote as it is a different sense of the word.)
{ "pile_set_name": "StackExchange" }
Q: Phonagap and Cordova cli not working My problem is a little bit weird, I installed phonegap and cordova cli step by step from the official tutorial and when I try to use phonegap create or something else on my Ubuntu 14.04, but the terminal is not write anything and then waiting for the next command. Example#1: expa@a42book:~$ cordova add platform android expa@a42book:~$ Example#2: expa@a42book:~$ cordova platform add android expa@a42book:~$ I could only this way: expa@a42book:~$ sudo nodejs /usr/local/lib/node_modules/cordova/bin/cordova platform add android Someone has pulled into this problem and solved it? A: The problem was with my cordova install (and the command too), I followed this tutorial: http://jeffmcmahan.info/blog/installing-cordova-on-linux/ and it began to working. If that’s you, start by removing node.js as follows: $ sudo apt-get remove node Next, you’ll fix up up some Python dependencies: $ sudo apt-get install python-software-properties python g++ make And now we’ll add the proper repo for up-to-date releases of Node.js, and then we’ll run an update to grab the list of packages required to install node: $ sudo add-apt-repository ppa:chris-lea/node.js $ sudo apt-get update We can now install Node.js itself: $ sudo apt-get install nodejs Finally, we install Cordova. $ sudo npm install -g cordova
{ "pile_set_name": "StackExchange" }
Q: How can an engine provide more torque at the point of contact than the ground's response by static friction without slipping? In response to the top answer here: Newtonian Mechanics - How does something like a car wheel roll? I clearly fundamentally misunderstand something here. I can't reconcile there being an angular acceleration about the tires (and thus, a net torque) and the torque provided by the engine being equal to the torque in response to static friction. If the torque provided by the engine was greater than the torque in response to static friction, wouldn't the wheel slip? update: My confusion was resolved in chat with @V.F., and for anyone else who might have had the same simple misunderstanding in this system, it came down to a misunderstanding of contact forces. As stated, the response from static friction is equal to the force of the tyre on the road, but the force of the tyre on the road (and of the road of the tyre though static friction) is NOT equal to the force of the engine on the tyre. This is because the tyre delivers the force to the road through contact, meaning it must physically accelerate to bring the atoms closer to the atoms of the tyre on the road, resulting in both the tyre and the road experiencing a force in opposing directions via Coloumbs Law. Therefore, a little bit of the engine force necessarily goes into accelerating the tyre into the road, and the rest of it is is then delivered between the road and the tyre as a contact force, through static friction. This delta is what results in the constraint of rolling motion, as the tyre experiences both a clockwise rotational acceleration from the engine to bring into contact with the road, and then a forward translation via static friction. This was easier to understand in the simpler translational case that is typically used to illustrate the difference between contact force and input force. Imagine two boxes, A and B, of equal mass, M, on a frictionless surface. If you exerted a force, F, on box A, it's clear that both boxes would equally accelerate as one system over the surface - but if you exert a force on box A, and box A is in contact with box B, wouldn't box B respond with an equal and opposite force? Then why would box A accelerate at all? i.e. why isn't the force, F, perfectly transmitted through box A to box B? Well, because box A and box B are, of course, not actually in contact. The atoms at their respective surfaces are at some mutual equilibrium caused by Columbus Law. So, to transmit force F to box B would require accelerating box A into box B - i.e. force F is actually distributed between box A and box B based on their respective masses, as "contact" in this sense requires the acceleration of box A into box B, and thus the contact force between box A and box B is necessarily less than the input force F. A: We can treat a driving wheel as just another gear that has to pass the torque down the line. Ideally, the torque it passes should be equal to the torque it receives, but, since the wheel has some mass and, therefore, some moment of inertia, a little torque differential is needed to speed it up. At steady state, though, the torque on both sides should be the same. The wheel may slip, if the drive torque exceeds the maximum torque that can be supported by static friction, which can happen, for instance, on a slippery surface (low static friction) or when the car is overloaded or somehow is blocked from moving or there is an attempt to accelerate it too fast.
{ "pile_set_name": "StackExchange" }
Q: Fitting and transforming text data in training, testing, and validation sets I'm trying to implement a simple text classifier wherein the data is split into training (70%) and testing (30%) sets, but cross validation (k=10) to be performed on the training set. My main concern here is the basis used for transforming a given set. I've seen tutorials where the whole data set was used to fit a Count/TFIDF vectorizer, but wouldn't this introduce bias when transforming the validation and testing sets since the previously mentioned sets were included in the whole data set? Or is the bias so small that it is acceptable to do so? Within a fold, would it be better if the training set was used to fit a vectorizer and transform the validation set? And for testing, should the training + validation sets be used to fit a vectorizer to transform the testing set? And on this note, should the validation set also be treated as "unseen" data similar to the test set? A lot of the tutorials and notes online show ready made datasets, but there are certain cases with text data where values are dependent on a given set of documents (e.g. like how IDF is computed based on some group of documents) and that there are a lot more nitty gritty details when extracting features. I think I'm just confused and am seeking a little clarification regarding this manner. Thanks! A: It's best to leave the test data unseen. You can create a data transformation pipeline for your test data so that your test data will be transformed into a TFIDF vector after being passed through the pipeline. This way you get to know how well your model performs on unseen data. And it's OK to transform the entire training data into a TFIDF vector and run the k-fold validation.
{ "pile_set_name": "StackExchange" }
Q: Google script spreadsheet, email sending row based I am trying to make a script that would make a spreadsheet, sending an email if expiry date is less than today but for each row by itself. So I have a spreadsheet that has an expiry date, and email for each supplier and I want to send a reminder for the supplier email if the expiry date is less than today. Each row of the spreadsheet contain information about a supplier and the script should check for the expiry date compare with today and it less than then send an email to the supplier email which exists in a cell. I tried to do for loop and such but failed. A: If you have this kind of table in a Spreadsheet: name | email | date -------------------------------------------- Mario Rossi | mario@test.com | 2018/03/08 Luigi Bianchi | luigi@test.com | 2018/02/25 Giuseppe Verdi | giuse@test.com | 2018/09/01 You can create a bound script in Google Apps Script like this: function myFunction() { var today = new Date(); var values = SpreadsheetApp.getActiveSheet().getDataRange().getValues(); for(n=1;n<values.length;++n){ var cell_date = values[n][2]; var expired = today > cell_date; if (expired) { //MailApp.sendEmail(values[n][1], subject, message); Logger.log('send mail to ' + values[n][1]); } } } Schedule the script to run one time every day at specific time. Assuming that today is the 2018/03/30 the result is: send mail to mario@test.com send mail to luigi@test.com
{ "pile_set_name": "StackExchange" }
Q: Disable wifi adapter warning I normally have my WIFI adapter disabled in Windows 7. Whenever I restart or boot the machine, it pops up a warning that it is disabled. Doh, I know this. The balloon notification appears in the bottom right of the screen: How can I disable this annoying warning (which interrupts and delays the startup process btw)? Note that this is a "balloon warning" from the righthand side of the taskbar (where utilities/hardware are located). The activating software is the "Intel PROSet Wireless WiFi Software". Here is the "Customize" options from Windows with the Wireless item among them. Note that there is no "Show Icon and Hide Notifications" choice: A: I figured out how to solve the problem. The key is to single click on the notification balloon. You have to do this fast, because it disappears after a few seconds. When you do this the following "troubleshooter" pops up: Notice how there is a blue "Disable notifications" label in the lower left. This is actually a toggle believe it or not. Click it once to disable notifications.
{ "pile_set_name": "StackExchange" }