source
sequence | text
stringlengths 99
98.5k
|
---|---|
[
"gaming.stackexchange",
"0000108054.txt"
] | Q:
What button do I have to press in this scene?
Possible spoiler.
I got captured and I am stuck on a scene where the bad guy finds my hiding place and drags me out. There is a cinematic and afterwards he chokes me.
Here is a picture of the scene:
There are two circles and some kind of "call to action" but I cannot figure out what to do.
I tried pressing left click, right click, space etc. with no effect. Either I get the timing wrong or I am pressing the wrong buttons.
I am playing the PC version.
A:
I figured it out. It is "F" or melee action. There is a red exclamation mark (!) for a very short period of time. I thought this was something like: Image or Action missing but it means "melee attack". Checkout "button mappings" "actions" to figure out what symbol refers to each "call to action".
|
[
"stackoverflow",
"0054770360.txt"
] | Q:
How can I wait for an object's __del__ to finish before the async loop closes?
I have a class that will have an aiohttp.ClientSession object in it.
Normally when you use
async with aiohttp.ClientSession() as session:
# some code
The session will close since the session's __aexit__ method is called.
I cant use a context manager since I want to keep the session persistent for the entire lifetime of the object.
This works:
import asyncio
import aiohttp
class MyAPI:
def __init__(self):
self.session = aiohttp.ClientSession()
def __del__(self):
# Close connection when this object is destroyed
print('In __del__ now')
asyncio.shield(self.session.__aexit__(None, None, None))
async def main():
api = MyAPI()
asyncio.run(main())
However if in some place an exception is raised, the event loop is closed before the __aexit__ method is finished.
How can I overcome this?
stacktrace:
Traceback (most recent call last):
File "/home/ron/.PyCharm2018.3/config/scratches/async.py", line 19, in <module>
asyncio.run(main())
File "/usr/local/lib/python3.7/asyncio/runners.py", line 43, in run
return loop.run_until_complete(main)
File "/usr/local/lib/python3.7/asyncio/base_events.py", line 568, in run_until_complete
return future.result()
File "/home/ron/.PyCharm2018.3/config/scratches/async.py", line 17, in main
raise ValueError
ValueError
In __del__ now
Exception ignored in: <function MyAPI.__del__ at 0x7f49982c0e18>
Traceback (most recent call last):
File "/home/ron/.PyCharm2018.3/config/scratches/async.py", line 11, in __del__
File "/usr/local/lib/python3.7/asyncio/tasks.py", line 765, in shield
File "/usr/local/lib/python3.7/asyncio/tasks.py", line 576, in ensure_future
File "/usr/local/lib/python3.7/asyncio/events.py", line 644, in get_event_loop
RuntimeError: There is no current event loop in thread 'MainThread'.
sys:1: RuntimeWarning: coroutine 'ClientSession.__aexit__' was never awaited
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f49982c2e10>
A:
Don't use a __del__ hook to clean up asynchronous resources. You can't count it being called at all, let alone control when it'll be used or if the async loop is still available at that time. You really want to handle this explicitly.
Either make the API an async context manager, or otherwise explicitly clean up resources at exit, with a finally handler, say; the with and async with statements are basically designed to encapsulate resource cleanup traditionally handled in finally blocks.
I'd make the API instance a context manager here:
class MyAPI:
def __init__(self):
self.session = aiohttp.ClientSession()
async def __aenter__(self):
return self
async def __aexit__(self, *excinfo):
await self.session.close()
Note that all that ClientSession.__aexit__() really does is await on self.close(), so the above goes straight to that coroutine.
Then use this in your main loop with:
async def main():
async with MyAPI() as api:
pass
Another option is to supply your own session object to the MyAPI instance and take responsibility yourself for closing it when you are done:
class MyAPI:
def __init__(self, session):
self.session = session
async def main():
session = aiohttp.ClientSession()
try:
api = MyAPI(session)
# do things with the API
finally:
await session.close()
|
[
"stackoverflow",
"0047884141.txt"
] | Q:
Autofac scope configuration for multi-project solution
I have an ASP.NET web application which until now has been using an Autofac configuration class which has specified an InstancePerRequest() for services in the application.
Since then, I have created a new console application in the same solution which will be responsible for running automated job processes. Since I can't use the InstancePerRequest configuration for my console application, then I need to make a change to my configuration. Ideally, I don't want to copy and paste all the configuration into my JobRunner application and use the 'InstancePerLifetimeScope()' configuration there.
Is there a better solution where I can largely use the same configuration to serve both projects? Perhaps there is a way to override the configuration for my Job Runner application but without having to specify a change in scope for every single service?
A:
Although InstancePerLifetimeScope and InstancePerRequest often have the same bahviour, they definitely have different intentions. I'd avoid using InstancePerLifetimeScope as a drop-in replacement, as it's easy to create unintended side-effects. For example, if you have a service that you had intended to only live for the duration of a web request, and all of a sudden it lives for the duration of you application (since it unintentionally resolved from the root scope).
This effect would be worse inside your job runner, especially if you're not creating your own lifetime scopes - in this scenario, everything will live in the root scope, which means that one job will be sharing instances of a service with every other job that has a dependency on it.
Under the covers, InstancePerRequest() actually just delegates to InstancePerMatchingLifetimeScope() with a well-known lifetime scope tag (which you can get from MatchingScopeLifetimeTags.RequestLifetimeScopeTag). So, one way you could achieve what you're asking is you could just cut-out the middle-man... for example, you could change your Autofac modules to take the lifetime scope tag as a constructor parameter:
internal class MyModule : Module
{
private string _lifetimeScopeTag;
public MyModule(string lifetimeScopeTag)
{
_lifetimeScopeTag = lifetimeScopeTag;
}
protected override void Load(ContainerBuilder builder)
{
builder.RegisterAssemblyTypes()
// equivalent to: .InstancePerRequest()
.InstancePerMatchingLifetimeScope(_lifetimeScopeTag);
}
}
Now, when you're building your container from the web, you need to supply the well-known lifetime scope tag:
internal static class WebIoC
{
public static IContainer BuildContainer()
{
var lifetimeScopeTag = MatchingScopeLifetimeTags.RequestLifetimeScopeTag;
var builder = new ContainerBuilder();
builder.RegisterModule(new MyModule(lifetimeScopeTag));
return builder.Build();
}
}
For your job runner, you can now mimic this behaviour, with a lifetime scope tag of your very own!
internal static class JobRunnerIoC
{
public const string LifetimeScopeTag = "I_Love_Lamp";
public static IContainer BuildContainer()
{
var builder = new ContainerBuilder();
builder.RegisterModule(new MyModule(LifetimeScopeTag));
// Don't forget to register your jobs!
builder.RegisterType<SomeJob>().AsSelf().As<IJob>();
builder.RegisterType<SomeOtherJob>().AsSelf().As<IJob>();
return builder.Build();
}
}
(I'm assuming here that each of your jobs implements an interface, let's say it looks like this):
public interface IJob
{
Task Run();
}
Now you just need to run the jobs in their own lifetime scope, using the tag you just made up, e.g.:
public class JobRunner
{
public static void Main(string[] args)
{
var container = JobRunnerIoC.BuildContainer();
// Find out all types that are registered as an IJob
var jobTypes = container.ComponentRegistry.Registrations
.Where(registration => typeof(IJob).IsAssignableFrom(registration.Activator.LimitType))
.Select(registration => registration.Activator.LimitType)
.ToArray();
// Run each job in its own lifetime scope
var jobTasks = jobTypes
.Select(async jobType =>
{
using (var scope = container.BeginLifetimeScope(JobRunnerIoC.LifetimeScopeTag))
{
var job = scope.Resolve(jobType) as IJob;
await job.Run();
}
});
await Task.WhenAll(jobTasks);
}
}
|
[
"stackoverflow",
"0014132105.txt"
] | Q:
Implementing Flash in JavaFX WebEngine
I understand that Adobe has a Flash API for Java called Air, but what would I use this for and would it be appropriate for a JavaFX WebEngine? I need some pointing in the right direction.
A:
Air is not a Flash API for Java.
According to Adobe's What is Air? FAQ:
Adobe AIR is a cross-operating-system runtime that lets developers
combine HTML, JavaScript, Adobe Flash® and Flex technologies, and
ActionScript.
Air is used to:
deploy rich Internet applications (RIAs) on a broad range of devices
... AIR allows developers to ... build their applications and
easily deliver a single application installer that works across
operating systems.
Attempting to integrate Air and the JavaFX WebEngine is definitely the wrong direction. Air is inappropriate for the JavaFX WebEngine as JavaFX has no notion of the Air runtime.
|
[
"stackoverflow",
"0011105665.txt"
] | Q:
Bitwise Operations C on long hex Linux
Briefly: Question is related to bitwise operations on hex - language C ; O.S: linux
I would simply like to do some bitwise operations on a "long" hex string.
I tried the following:
First try:
I cannot use the following because of overflow:
long t1 = 0xabefffcccaadddddffff;
and t2 = 0xdeeefffffccccaaadacd;
Second try: Does not work because abcdef are interpreted as string instead of hex
char* t1 = "abefffcccaadddddffff";
char* t2 = "deeefffffccccaaadacd";
int len = strlen(t1);
for (int i = 0; i < len; i++ )
{
char exor = *(t1 + i) ^ *(t2 + i);
printf("%x", exor);
}
Could someone please let me know how to do this? thx
A:
Bitwise operations are usually very easily extended to larger numbers.
The best way to do this is to split them up into 4 or 8 byte sequences, and store them as an array of uints. In this case you need at least 80 bits for those particular strings.
For AND it is pretty simple, something like:
unsigned int A[3] = { 0xabef, 0xffcccaad, 0xddddffff };
unsigned int B[3] = { 0xdeee, 0xfffffccc, 0xcaaadacd };
unsigned int R[3] = { 0 };
for (int b = 0; b < 3; b++) {
R[b] = A[b] & B[b];
}
A more full example including scanning hex strings and printing them:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef unsigned int uint;
void long_Print(int size, const uint a[]) {
printf("0x");
for (int i = 0; i < size; i++) {
printf("%x", a[i]);
}
}
void long_AND(int size, const uint a[], const uint b[], uint r[]) {
for (int i = 0; i < size; i++) {
r[i] = a[i] & b[i];
}
}
// Reads a long hex string and fills an array. Returns the number of elements filled.
int long_Scan(int size, const char* str, uint r[]) {
int len = strlen(str);
int ri = size;
for (const char* here = &str[len]; here != str; here -= 8) {
if (here < str) {
char* tmp = (char*)malloc(4);
tmp[0] = '%';
tmp[1] = (char)(str - here + '0');
tmp[2] = 'x';
tmp[3] = '\0';
sscanf(str, tmp, &r[ri--]);
free(tmp);
break;
}
else {
sscanf(here, "%8x", &r[ri--]);
}
}
for (; ri >= 0; ri--) {
r[ri] == 0;
}
return size - ri;
}
int main(int argc, char* argv[])
{
uint A[3] = { 0 };
uint B[3] = { 0 };
uint R[3] = { 0 };
long_Scan(3, "abefffcccaadddddffff", A);
long_Scan(3, "deeefffffccccaaadacd", B);
long_Print(3, A);
puts("\nAND");
long_Print(3, B);
puts("\n=");
long_AND(3, A, B, R);
long_Print(3, R);
getchar();
return 0;
}
|
[
"movies.stackexchange",
"0000087486.txt"
] | Q:
Why is Hollywood not casting Jim Carrey anymore?
Jim Carrey is a great comedian.
But why are we not seeing him in Hollywood movies anymore?
Any reason behind it.?
A:
There are plenty of reasons, as shown in this article on Looper:
He's too much of a risk
He's not as much of a box office draw as he used to be
He stopped promoting Kick-Ass 2
His method acting got crazy during Man on the Moon
There may be issues getting him insured
He's been dealing with some personal issues
He's gone public with some pretty controversial beliefs
Jim Carrey no longer exists
He won't take a role unless it 'chooses' him
He hasn't been nominated for any major awards recently
And he's happy that way
He's busy mentoring the next generation of actors
He's been working behind the camera
He's been focused on making art for the past several years
Each of these reasons is discussed at length in the source article.
Most likely it's a combination of several of those factors, which means in the end he's too much trouble for a studio to bother with him.
A:
In 2013 he ended his relationship with his agents/managers Eric Gold and Jimmy Miller - they had represented him for the prior 25 years of his career.
The following year he signed with Rick Yorn's LBI Entertainment.
We are not privy to the discussions of possible work or contractual obligations each party had for the other during each contract. However, many managers only make money when their stars make money, and so will push talent to accept work they might otherwise refuse.
Carrey is not in a position where he needs to accept work in order to meet his financial needs.
Further, the extraordinary decline in acting jobs does align strongly with the switch of management.
I suspect the main reason is that he simply doesn't want to do any of the parts which he could perform, and his manager is not pushing him to accept parts that he isn't interested in.
A:
As other answers have provided, it's true Carrey has had some problems including the circumstances with his ex-girlfriend's murder (for which he has been cleared) along with taking some time to seek [controversial] artistic passions, --but Carrey is CURRENTLY still working in the film industry. He has been executive producing, I'm Dying Up Here AND later this year, he is returning to the small screen, set to star in the Showtime comedy Series, Kidding.
Jim Carrey will star in a new Showtime comedy series in his first
regular television role since his days on the 1990’s sketch show “In
Living Color,” Showtime announced Thursday.
The half-hour series is titled “Kidding,” in which Carrey will play
Jeff, a.k.a. Mr. Pickles, an icon of children’s television, who also
anchors a multimillion dollar branding empire. But when his family
begins to implode, Jeff finds no fairy tale or fable or puppet will
guide him through this crisis, which advances faster than his means to
cope. Showtime has ordered a 10-episode first season.
The role further expands Carrey’s relationship with Showtime, as he
currently executive produces the dramedy “I’m Dying Up Here,” which
was recently renewed for a second season.
The project will also reunite Carrey with “Eternal Sunshine of the
Spotless Mind” director Michel Gondry, who will direct for “Kidding.”
Dave Holstein–a writer and producer on both Showtime’s “Weeds” and
“I’m Dying Up Here”– created the series, wrote the pilot, and will
serve as showrunner. Carrey and Gondry will also executive produce
along with Jason Bateman, Raffi Adlan, Jim Garavente, and “I’m Dying
Up Here” executive producer Michael Aguilar. http://variety.com/2017/tv/news/jim-carrey-showtime-series-kidding-michael-gondry-1202558804/
|
[
"stackoverflow",
"0020507084.txt"
] | Q:
Highcharts paint zero axis black
I have a Highchart bar chart with negative values (with the bars then going downwards). Now I would like to paint a black line for y=0 like so: .
I haven't found a trivial way to do this and I would like to avoid directly modifing the SVG or adding a fake line chart or something. Maybe someone knows better way? I've already played around with (minor)tickInterval and (minor)gridLineColor but that wouldn't solve my problem.
A:
you can use plot lines for this like shown in this example http://jsfiddle.net/4rpNU/
yAxis:{
plotLines:{}
}
here is the api reference for it http://api.highcharts.com/highcharts#yAxis.plotLines
Hope this will be useful for you :)
|
[
"photo.stackexchange",
"0000065113.txt"
] | Q:
How can I connect multiple Canon dSLRs in parallel to a computer?
I want to connect a couple of Canon cameras with my computer in such a way that a single click both captures images and stores them on the computer.
I am trying the same in c#. Actually, I have connected the camera with computer, but it connects only a single camera at a time.
A:
James Shell, Yes there is limitation with Canon SDK. You need to tweak it a bit to work. (Kindly do, at your own risk, it may cost Camera).
Forgot to mention the link
Check in comment section, you will find solution.
// my 2 cameras - they are populated by a selection logic.
public Camera camL;
public Camera2 camR;
if (camL == null || camR == null) return;
try
{
// code for closing session - removed for simplicity
CameraHandler.OpenSession(camL);
CameraHandler2.OpenSession(camR);
}
catch (Exception ex) { ReportError(ex.Message, false); }
}
Where Camera is the core class of camera.
|
[
"stackoverflow",
"0054816202.txt"
] | Q:
Do I have to create Sonatype JIRA ticket when publishing an upgraded version of an existing library to maven central?
I'm trying to publish a upgraded version of an existing library in maven central
Do I need to create a JIRA for every version upload to maven central?
A:
No, is it today on sonatype and automatic several days after.
|
[
"stackoverflow",
"0018937494.txt"
] | Q:
Trying to save Custom Array of Objects Android
So I'm making a notepad application that logs date entered, a subject, and a body text field. When I hit my post button, everything appears properly in my ListView, but when I close the application and re-open it, only the date remains intact and the other two values are NULL. Below is the code I'm using.
public class LogList implements Serializable {
private String logDate;
private String logBody;
private String logSubject;
public LogList(String date, String LogBody, String LogSubject){
super();
this.logDate = date;
this.logBody = logBody;
this.logSubject = logSubject;
}
Back in my main class, I have my method that is supposed to save the three values into an ArrayList lts.
private void saveInFile(String subject_text, String date, String body_text ){
LogList lt = new LogList(date, subject_text, body_text);
lts.add(lt);
saveAllLogs();
}
Now if I change the order of the values in my new LogList, only the first one will be properly displayed after I close my app and reopen it. The following are my saveAllLogs method and my loadFromFile method.
private ArrayList<String> loadFromFile(){
ArrayList<String> logs = new ArrayList<String>();
try {
FileInputStream fis = openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
while (true) {
LogList lt = (LogList) ois.readObject();
logs.add(lt.toString());
lts.add(lt);
}
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
catch (ClassNotFoundException e) { e.printStackTrace(); }
return logs;
}
private void saveAllLogs() {
try {
FileOutputStream fos = openFileOutput(FILENAME, 0);
ObjectOutputStream oos = new ObjectOutputStream(fos);
for (LogList lti : lts) {
oos.writeObject(lti);
}
fos.close();
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
}
Any help would be greatly appreciated!
A:
For one thing,
public LogList(String date, String LogBody, String LogSubject){
super();
this.logDate = date;
this.logBody = logBody;
this.logSubject = logSubject;
}
Seems wrong. As you have capitalized argument names, but you're setting the members with lowercase names.
Do you mean:
public LogList(String date, String logBody, String logSubject){
super();
this.logDate = date;
this.logBody = logBody;
this.logSubject = logSubject;
}
EDIT: Trivial thing, not impacting your code: You don't need your call to super() in your constructor as you're not extending any class.
|
[
"stackoverflow",
"0063185454.txt"
] | Q:
How to read redirected url parameters from Office.context.ui.displayDialogAsync
I am stuck on how to read url parameters/token from redirected page url in Outlook web-addin. I am using DialogAPI to pop up my azure app sign-in/consent page and then trying to read tokens from redirected page.
I can see that token are passed but I couldn't figure out how to read token from url?
function GetToken(url)
{
_dlg = Office.context.ui.displayDialogAsync(url, { height: 40, width: 40 }, function (result) {
_dlg = result.value;
_dlg.addEventHandler(Office.EventType.DialogMessageReceived, processMessage);
Office.context.ui.messageParent(somevalue);
});
}
Besides that the processMessage call back never gets triggered, wondering why?
Guys any feedback would be helpful.
Thanks
A:
Office.context.ui.displayDialogAsync must be called from the host page and Office.context.ui.messageParent must be called from the Dialog box.
This should be on the host page :
var dialog;
Office.context.ui.displayDialogAsync(url,
{height: 40, width: 40}, function (result) {
dialog = result.value;
dialog.addEventHandler(Office.EventType.DialogMessageReceived,
function(somevalue){
console.log(somevalue);});
});
This should be on the Dialog Box :
Office.initialize = function (reason) {
$(document).ready(function () {
Office.context.ui.messageParent(somevalue);
}
}
in your manifest, must have all the domains being accessed with "https".
The URL uses the HTTPS protocol. This is mandatory for all pages loaded in a dialog box, not just the first page loaded.
The dialog box's domain is the same as the domain of the host page, which can be the page in a task pane or the function file of an add-in command. This is required: the page, controller method, or other resource that is passed to the displayDialogAsync method must be in the same domain as the host page.
Please visit here for more info.
|
[
"stackoverflow",
"0053258730.txt"
] | Q:
How to address this warning? - Is a raw type. References to generic type should be parameterized
I have created a Custom Table Cell in JavaFX, pursuant to this answer, so I can have different font styling for different parts of the cell's text.
I use this Custom Table Cell on two different types of TableViews:TableView<Track> and TableView<Album>.
Both Track and Album implement the Interface AlbumInfoSource:
public interface AlbumInfoSource {
public String getAlbumTitle();
public String getFullAlbumTitle();
public String getReleaseType();
public String getDiscSubtitle();
public Integer getDiscCount();
public Integer getDiscNumber();
}
My Custom TableCell is typed with that AlbumInfoSource, so it can render cells for both a TableView<Album> and a TableView<Track>.
Here is the basic code:
public class FormattedAlbumCell<T, S> extends TableCell <AlbumInfoSource, String> {
private TextFlow flow;
private Label albumName, albumType, albumDisc;
public FormattedAlbumCell () {
/* Do constructor stuff */
}
@Override
protected void updateItem ( String text, boolean empty ) {
super.updateItem ( text, empty );
/* Do pretty rendering stuff */
}
}
And then I apply it to a column like this:
TableColumn<Album, String> albumColumn;
albumColumn = new TableColumn<Album, String>( "Album" );
albumColumn.setCellFactory( e -> new FormattedAlbumCell () );
Which works perfectly fine, but I get a warning on that last line, which says:
Warning: FormattedAlbumCell is a raw type. References to generic type FormattedAlbumCell< T ,S > should be parameterized
If I change my FormattedAlbumCell class such that it extends TableCell <Album, String>, then the warning goes away. But then I can't use the FormattedAlbumCell for a TableView<Track>, I would have to duplicate the FormattedAlbumCell class make it extend TableCell, which seems dumb to me.
Is there a way to get these parameters straight without creating two separate classes? It seems like the issue comes from the paramaterizing stuff having trouble with Interfaces.
A:
Your FormattedAlbumCell has two generic type parameters (<T, S>) which, by the looks of things, are completely unused. Remove them.
class FormattedAlbumCell<T, S> extends TableCell<AlbumInfoSource, String>
becomes
class FormattedAlbumCell extends TableCell<AlbumInfoSource, String>
Your next problem is that generics are invariant. A TableCell<AlbumInfoSource, String> is not a TableCell<Album, String>, or vice-versa.
If you need to be able to create a TableColumn<Album, String> in your method then you need a TableCell<Album..., not a TableCell<AlbumInfoSource.... But you also want this to work for other implementations of AlbumInfoSource, so changing the cell won't work.
This means that you need to introduce another level of indirection via generics.
class FormattedAlbumCell<T extends AlbumInfoSource> extends TableCell<T, String>
This says that we can create different generic versions of FormattedAlbumCell, subject to the constraint that T is a more specific type of AlbumInfoSource (i.e. extends or implements it).
Now we can create a FormattedAlbumCell<Track> which would be a TableCell<Track, String>, or we can create a FormattedAlbumCell<Album> which will be a TableCell<Album, String>.
See also Oracle's generics tutorial
|
[
"stackoverflow",
"0048749781.txt"
] | Q:
Angular 5 Browsing animations but conditional
I've got a numbered nav menu with 6 items and their order is important, say, for example, like a checkout then login/create account then shipment then payment setup :
You can go back in the steps at any step. Forward is authorized too. Jumping several forward and back as well.
I'd like animations for the page content that follow suit with the logic of the order of these steps.
For this I snagged my code from here : https://plnkr.co/edit/Uo1coU9i1GsB1I4U3809?p=preview
(I duplicated the routerTransition code, then renamed the first into slideLeft inversed the animation and renamed the second to slideRight).
(This is not part of this question but so as to give you an idea of where this is heading : As a bonus I'll add a functions that navigates to each intermediary step successively for you if you click a nav element more then n+1 away from itself. the purpose of this would be to emulate the feeling that each page does indeed constitute a single slider or carousel toe-to-toe.)
I've already successfully set up the routing and the animation, I can already visualize the logic of function that with parameters : "current route" and "new route", can spit out a boolean signifying "slideLeft" or "slideRight".
What I'm missing is how to tell the app whether to slide left or slide right?
What I don't get is that in the routing.module.html the syntax doesn't allow, as far as I know, for implementing conditionality :
<main [@slideRight]="getState(o)">
<router-outlet #o="outlet"></router-outlet>
</main>
routing.component.ts :
import { Component, OnInit } from '@angular/core';
import { slideLeft, slideRight } from './router.animations';
@Component({
selector: 'app-routing',
templateUrl: './routing.component.html',
styleUrls: ['./routing.component.scss'],
animations: [slideLeft, slideRight],
host: { '[@slideLeft, slideRight]': '' }
})
export class RoutingComponent implements OnInit {
constructor() { }
ngOnInit() {
}
getState(outlet) {
return outlet.activatedRouteData.state;
}
}
I noticed the :
export const slideRight = trigger('slideRight', [
transition('* => *', [
the : * => * means "from any name to any name" and at first I though I could be using that by replacing that each time with the route names but I got lost in the implementation and I now believe there must be an easier way.
what I'd like to do is something along the lines of :
<main {{isCurrentStepIncreasing ? '[@slideLeft]' : '[@slideRight]'}}="getState(o)">
<router-outlet #o="outlet"></router-outlet>
</main>
I doubt that's actually possible though.
A:
It looked like no animation is being played when returning null in the getStateLeft(outlet) method. You could try something like this:
<main [@slideRight]="getStateLeft(o)" [@slideLeft]="getStateRight(o)">
<router-outlet #o="outlet"></router-outlet>
</main>
getStateLeft(outlet) {
if (isCurrentStepIncreasing) {
return outlet.activatedRouteData.state;
}
return null;
}
getStateRight(outlet) {
if (!isCurrentStepIncreasing) {
return outlet.activatedRouteData.state;
}
return null;
}
|
[
"stackoverflow",
"0028746778.txt"
] | Q:
How to use jquery onchange to update input field?
How do you use the jquery onchange function to update an input field so that it keeps a running total?
e.g. I have the following dropdown list options:
<select name="select" id="set1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="select" id="set2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="text" name="total" id="total" value="" />
When a user select an option from the two dropdowns above, I need the total of the two selected options to be displayed in the input field. This would need to dynamically change each time a different option was selected. How can you achieve this with jquery?
A:
Works with any number of 'select' :
$select = $('select.numberSelect');
$select.on('change', function(){
var total = 0;
$select.each(function(e){
total += parseInt($(this).val()); // or parseInt(e.currentTarget.value)
})
$('#total').val(total);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class='numberSelect'>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<select class='numberSelect'>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<select class='numberSelect'>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<input type="text" id="total" value="3" />
Edit : Removed a lot of useless stuff (names, IDs, value="", ...) and added a third select for demonstration purposes.
Edit 2 : added a class to target the specific 'select' elements, and not others in the DOM.
|
[
"stackoverflow",
"0031769963.txt"
] | Q:
OR element wise operation over two binary lists
I have the following code of two binary lists and I want to obtain a resulting list in which the element i will be the OR operation applied to the i elements of the two lists:
from operator import ior
l_0 = [01100]
l_1 = [11000]
print map(ior, l_0, l_1)
And I was expecting a result of [11100], but the result is:
[11000]
I have checked ior operator and the documentation says that it performs the operation:
a = ior(a, b) is equivalent to a |= b
So I tried the following to check as well:
print ior(0,0)
print ior(1,0)
print ior(0,1)
print ior(1,1)
Getting as results:
0
1
1
1
Which makes sense, but doesn't coincide with the result obtained in the 3rd position of the lists. I don't understand why the result of the map operation of above is not [11100]. I am missing something here and I hope that you can throw some light on it.
A:
[11000] (for example) is not a list of five binary digits, it's a list of one decimal number, 11000.
Similarly, 01100 is a single octal number equal to 576 decimal, so:
11000d = 0010101011111000b
01100o = 576d = 0000001001000000b
-----------------
perform or: 0010101011111000b = 11000d
That's why you're getting 11000 as the answer, exactly the same as if you'd done:
[l_0[i] | l_1[i] for i in range(len(l_0))]
If you want to process a list of five binary digits, that would be something like:
>>> l_0 = [0,1,1,0,0]
>>> l_1 = [1,1,0,0,0]
>>> [l_0[i] | l_1[i] for i in range(len(l_0))]
[1, 1, 1, 0, 0]
|
[
"math.stackexchange",
"0000484974.txt"
] | Q:
$s_{n+1} = \sqrt{s_n+1}$ converges to $\frac{1+\sqrt{5}}{2}$
Let $s_n = 1$ and for $n \geq 1$, let $s_{n+1} = \sqrt{s_n+1}$.
Given this sequence and assume that it converges. I have to prove that the limit is $\frac{1+\sqrt{5}}{2}$
By using the definition of limit, I tried to set $n > N\ implies\ |\sqrt{s_n+1}-\frac{1+\sqrt{5}}{2}| < \epsilon$.
But I have no idea how to simplify the expression in the absolute value and get rid of absolute value!!!
Can anyone give some hints??
A:
If we are forced to use an $\epsilon$-$N$ calculation, here is how it could go.
Let $\tau=(1+\sqrt{5})/2$. Then
$$s_{n+1}-\tau =\sqrt{s_n+1}-\tau=\frac{s_n+1-\tau^2}{\sqrt{s_n+1}+\tau}.$$
(We multiplied "top" and "bottom" by $\sqrt{s_n+1}+\tau$.)
Now use the fact that $1-\tau^2=-\tau$, and that $\sqrt{s_n+1}+\tau \gt 1+\tau\gt 2$ to get the inequality
$$|s_{n+1}-\tau| \lt \frac{1}{2}|s_n-\tau|.\tag{1}$$
Note that $|s_1-\tau|\lt 1$. Using (1) we then obtain
$$|s_{k}-\tau|\lt \frac{1}{2^{k-1}}.$$
This estimate now can be used in a routine way to find a suitable $N$, given $\epsilon$.
Remark: We deliberately gave away a lot in the calculation. One can sharpen estimates to get precise information about the rate of convergence.
|
[
"stackoverflow",
"0012859232.txt"
] | Q:
Android beginner: onDestroy
Shall I place commands before or after super.onDestroy() when overwriting an activity's ondestroy?
protected void onDestroy() {
//option 1: callback before or ...
super.onDestroy();
//option 2: callback after super.onDestroy();
}
(Now I fear: If super.onDestroy is too fast, it will never arrive in option 2.)
A:
Anything that might be related to using the activity resources should be before the call to super.onDestroy(). The code after it will b reached, but might cause problems if it needs those resources.
A:
Place your code after the super.onDestroy(); eg:
protected void onDestroy() {
super.onDestroy();
// Put code here.
}
Your code will finish executing when overriding the method.
A:
This is what happens when you call super.onDestroy();
Android Source
protected void onDestroy() {
mCalled = true;
// dismiss any dialogs we are managing.
if (mManagedDialogs != null) {
final int numDialogs = mManagedDialogs.size();
for (int i = 0; i < numDialogs; i++) {
final Dialog dialog = mManagedDialogs.valueAt(i);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
// also dismiss search dialog if showing
// TODO more generic than just this manager
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchManager.stopSearch();
// close any cursors we are managing.
int numCursors = mManagedCursors.size();
for (int i = 0; i < numCursors; i++) {
ManagedCursor c = mManagedCursors.get(i);
if (c != null) {
c.mCursor.close();
}
}
}
Essentially this means that it does not matter if you call it before or after your code.
|
[
"stackoverflow",
"0004201210.txt"
] | Q:
How to save a (Jpeg) image to MySql and retrieve it later?
Looking for a code sample, preferably using TADOConnection.
I want to save the TPicture of a TImage to a MySql (preferably ODBC, rather than just MySql) database and later I want to crate a TImage and retrieve the picture to its TPicture property.
Any code snippets, or links to same?
A:
You can use BLOB fields. Suppose you have an instance of TAdoDataset, and you want to edit an image field. You can use a code like this:
AStream := TMemoryStream.Create;
try
Image1.Picture.Graphic.SaveToStream(AStream);
AStream.Position := 0;
if ADODataSet1.Active then
begin
ADODataSet1.Edit;
TBlobField(ADODataSet1.FieldByName('MyField')).LoadFromStream(AStream);
ADODataSet1.Post;
end;
finally
AStream.Free;
end;
You can also use a DBImage control which is data-aware, and loading any image into it means loading that image into the field.
To retrieve the field data, and load it into a TImage instance, you can have a code like this:
var
AStream : TMemoryStream;
begin
AStream := TMemoryStream.Create;
try
if ADODataSet1.Active then
begin
TBlobField(ADODataSet1.FieldByName('MyField')).SaveToStream(AStream);
AStream.Position := 0;
Image1.Picture.Graphic.LoadFromStream(AStream);
end;
finally
AStream.Free;
end;
end;
Warning: In this code I assumed Image1.Picture.Graphic is not Nil. If your image control is empty, then Picture.Graphic property is Nil, and the code above will give you Access Violation. You have two options to avoid this:
Instead of saving the image into a
memory stream, save it into a local
temp file, then load the picture
using Image1.Picture.LoadFromFile.
LoadFromFile checks file extension,
and according to the file extension,
creates a proper object from one of
TGraphics descendant classes. For
example if the file is JPEG, it
creates an instance of TJPEGImage
class, and loads the data into it.
You yourself create the proper
object and assign it to
Image1.Picture.Graphic. For example,
if your image is JPEG, create an
instance of TJPEGImage, load the
stream into it, then assign it to
Image1.Picture.Graphic.
If you are inserting or updating a DB record using SQL commands (INSERT/UPDATE), you have to use SQL parameters in your SQL command, then you can load the stream into the parameter which represents your image field:
///Sample SQL Command:
INSERT INTO My_Table_Name
(MyField1, MyField2)
VALUES (:prmMyField1, :prmMyField2)
/// Sending INSERT command to DB server
var
AStream : TMemoryStream;
begin
AStream := TMemoryStream.Create;
try
Image1.Picture.Graphic.SaveToStream(AStream);
AStream.Position := 0;
// Save some random data into the first param
ADOCommand1.Parameters.ParamByName('prmMyField1').Value := 1;
// Save image stream into the second param
ADOCommand1.Parameters.ParamByName('prmMyField2').LoadFromStream(AStream);
ADOCommand1.Execute;
finally
AStream.Free;
end;
end;
|
[
"stackoverflow",
"0004667311.txt"
] | Q:
SQL GROUP BY question
I have a table:
id group data
1 a 10
2 a 20
3 b 10
4 b 20
I want to get ids of records with max "data" value grouped by "group", i.e.
id
2
4
A:
A more modern answer using CTEs:
;WITH Numbered as (
SELECT ID,ROW_NUMBER() OVER (PARTITION BY group ORDER BY data desc) rn FROM Table
)
SELECT ID from Numbered where rn=1
PostgreSQL has some pretty decent documentation online, look at window functions and WITH queries. In this case, we partition the rows in the table based on which group they belong to. Within each partition, we number the rows based on their data column (with row number 1 being assigned to the highest data value).
In the outer query, we just ask for the rows which were assigned row number 1 within their partition, which if you follow the logic, it must be the maximum data value within each group.
If you need to deal with ties (i.e. if multiple rows within a group both have the maximum data value for the group, and you want both to appear in your result set), you could switch from ROW_NUMBER() to RANK()
A:
Portable solution:
SELECT T1.id
FROM yourtable T1
JOIN (
SELECT grp, MAX(data) AS data
FROM yourtable
GROUP BY grp
) T2
WHERE T1.grp = T2.grp AND T1.data = T2.data
PostgreSQL solution:
SELECT DISTINCT ON (grp) id
FROM yourtable
ORDER BY grp, data DESC;
PS: I changed the column name from group to grp because group is a reserved word. If you really want to use group you'll have to quote it.
|
[
"stackoverflow",
"0005855990.txt"
] | Q:
Check if now is less than 3 hours before
How to check if a timestamp is more than 3 hours old?
I have a timestamp in the following format:
15.03.2011 18:42
How to write the following function?
function isMoreThan3HoursOld(timestamp) {
// parse the timestamp
// compare with now (yes, client side time is ok)
// return true if the timestamp is more than 3 hours old
}
(I need to do it quite often, that is on a table with about 500 timestamps (50 rows, 10 columns with timestamps))
Regards
Larsi
A:
Should explain itself:
var nowMinus3h = new Date,
dateToTest = new Date('2011/03/15 18:42');
nowMinus3h.setMinutes(nowMinus3h.getMinutes()-180); //=> now minus 180 minutes
// now the difference between the dateToTest and 3 hours ago can be calculated:
var diffMinutes = Math.round( (dateToTest - nowMinus3h )/1000/60) ;
if you need transformation of '15.03.2011 18:42' to valid input for the Date Object use:
var dat_ = '15.03.2011 18:42'.split(' '),
dat = dat_[0].split('.').reverse().join('/')+' '+dat_[1];
|
[
"stackoverflow",
"0035681969.txt"
] | Q:
Getting "subquery returns more than one row" error whenever trying to join a column from another table as alias?
I am stuck with this problem for a whole 2 days. I have a users table and it contains:
+--------+--------+----------+--------------------------------------------+
| userId | name | username | profile_pic |
+--------+--------+----------+--------------------------------------------+
| 1 | john | john123 | http://localhost/profile_pic/user1pic.jpg |
| 2 | andrew | andrew | http://localhost/profile_pi/user2pic.jpg |
| 3 | doe | doe | http://localhost/profile_pic/user3pic.jpg |
+--------+--------+----------+--------------------------------------------+
I have another table called userpost which contains:
+--------+--------+-------------+----------------------------+
| postId | userId | postMessage | postImage |
+--------+--------+-------------+----------------------------+
| 1 | 1 | "Hey" | http://localhost/post1.jpg |
| 2 | 3 | "Add me" | http://localhost/post2.jpg |
| 3 | 2 | "boring" | http://localhost/post3.jpg |
+--------+--------+-------------+----------------------------+
userId is refrenced to users.userId. I am trying to join profile_pic to userpost but mysql is returning error. Here is what I am doing:
SELECT *, (SELECT profile_pic FROM users
INNER JOIN userpost on users.userId = userpost.userId) as profile_pic FROM userpost
But getting Subquery returns more than 1 row error
I know I am doing something stupid with the query. I just want something like this:
+--------+--------+-------------+----------------------------+--------------------------------------------+
| postId | userId | postMessage | postImage | profile_pic |
+--------+--------+-------------+----------------------------+--------------------------------------------+
| 1 | 1 | "Hey" | http://localhost/post1.jpg | http://localhost/profile_pic/user1pic.jpg |
| 2 | 3 | "Add me" | http://localhost/post2.jpg | http://localhost/profile_pic/user3pic.jpg |
| 3 | 2 | "boring" | http://localhost/post3.jpg | http://localhost/profile_pi/user2pic.jpg |
+--------+--------+-------------+----------------------------+--------------------------------------------+
I am having a meeting tomorrow to showcase my prototype app. Help will be appreciated.
A:
You are using a sub query not a join. When using subquery in the select, you have to make sure it returns exacly one row like
SELECT COL1,COL2,(SELECT 1) from YourTable
Or by using a correlated query, which I assume was your purpose but is not required since its from the same table as you select, so just use a simple join:
SELECT s.*, t.profile_pic
FROM users t
INNER JOIN userpost s on t.userId = s.userId
|
[
"stackoverflow",
"0030269586.txt"
] | Q:
flot is it possible to set just the begining of the x axis?
I am working on flot jquery library, and I used to use this code in order to tell flot to inference the x-axis itself
xaxis: {
},
now i have a case in which I need to show the values starting from zero in x-axis, i don't care about last value, so I need flot to calculate it dinamically. it is possible to set just the begining ?
what I tried
I couldn't find such an option using google so I calculated the max value my self and I set the x-axis manually between zero and that max value. that approaches works in some cases, but i do need to handle all the senarios so i thought let me ask here first to see if there is a built-in option for that
A:
You can set the minimum or maximum extent of the axes like this:
xaxis: {min: 0, max: 999}
See https://github.com/flot/flot/blob/master/API.md#customizing-the-axes
|
[
"stackoverflow",
"0014328894.txt"
] | Q:
How can I make expandable panels without using JS?
My question is how can I create expandable panels in an HTML form without using javascript, so that when a user clicks on each panel it expands and displays the form.
Before click:
<ul>
<li id="panel1"><a></a><div class="content"></div></li>
<li id="panel2"><a></a><div class="content"></div></li>
<li id="panel3"><a></a><div class="content"></div></li>
</ul>
After click:
<ul>
<li id="panel1">
<a></a>
<div class="content">
<form id="FORM"> ..... </form>
</div>
</li>
<li id="panel2"><a></a><div class="content"></div></li>
<li id="panel3"><a></a><div class="content"></div></li>
</ul>
A:
You can do that using :target css pseudo selector - it is not very elegant though, as clicking on the anchor tag modifies the url so it is hard to toggle the form. Best use javascript.
<style>
form {
display: none;
}
form:target {
display: block;
background: red;
}
</style>
<ul>
<li id="panel1" ><div class="content"><a href="#form">Show form</a><form id="form" > My form <input type="text"></form></div></li>
<li id="panel2"><div class="content">My content</div></li>
<li id="panel3"><div class="content">My content</div></li>
</ul>
some examples of :target in action:
http://css-tricks.com/css-target-for-off-screen-designs/ and http://css-tricks.com/on-target/
|
[
"stackoverflow",
"0060726510.txt"
] | Q:
Flutter Driver test timeout
I am new to Flutter Driver testing, and I have an issue that the tests always time out (in 30 seconds) while waiting for widgets to appear. My main class is only checking whether the Firebase user is not null. If a user is logged in, it is showing a dashboard, otherwise a login screen. While running the check, it is displaying a SplashScreen. The test "check flutter driver health" completes normally.
I tried find.byValueKey("auth_screen") instead of find.byType("AuthScreen"), it gives the same problem.
Error log:
VMServiceFlutterDriver: Connected to Flutter application.
00:01 +0: rendin app check flutter driver health
HealthStatus.ok
00:01 +1: rendin app Check login screen widgets
Splash screen
VMServiceFlutterDriver: waitFor message is taking a long time to complete...
VMServiceFlutterDriver: waitFor message is taking a long time to complete...
00:31 +1 -1: rendin app Check login screen widgets [E]
TimeoutException after 0:00:30.000000: Test timed out after 30 seconds.
Bad state: The client closed with pending request "ext.flutter.driver".
Here is my test code:
import 'package:test/test.dart';
import 'package:flutter_driver/flutter_driver.dart';
import 'package:test/test.dart';
void main() {
group('app', () {
FlutterDriver driver;
// Connect to the Flutter driver before running any tests.
setUpAll(() async {
driver = await FlutterDriver.connect();
});
test('check flutter driver health', () async {
Health health = await driver.checkHealth();
print(health.status);
});
test("Check login screen", () async {
await driver.waitFor(find.byType("AuthScreen")).then((value) async {
print("Auth screen");
});
});
// Close the connection to the driver after the tests have completed.
tearDownAll(() async {
if (driver != null) {
driver.close();
}
});
});
}
Piece of futureBuilder code in the main class:
builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return SplashScreen(key: Key("splashScreen2"));
} else if (snapshot.hasData) {
return DashboardScreen();
} else {
return AuthScreen();
}
},
and the AuthScreen() piece of code:
class AuthScreen extends StatelessWidget {
static const routeName = '/auth';
@override
Widget build(BuildContext context) {
final deviceSize = MediaQuery.of(context).size;
return Scaffold(
key: Key("auth_screen"),
backgroundColor: Colors.white,
A:
test() has a param called timeout
Here's demo:
test("Check login screen", () async {
await driver.waitFor(find.byType("AuthScreen")).then((value) async {
print("Auth screen");
});
}, timeout:Timeout.none);
which timeout defaults value = 30 seconds;
|
[
"stackoverflow",
"0048936497.txt"
] | Q:
Capturing characters for fields which are enabled
The fields in question look like this
Each password character field is chosen randomly and the user is required to enter their corresponding password character in the specific field. For example if my password is swordfish, in the picture above I would be required to enter the letters s, d and s. So far I have an If statement for each element which is hardly ideal and only the input[] of the xpath changes with each field.
WebElement p1 = driver.findElement(By.xpath("/html/body/div[3]/div[3]
/div[2]/div/div[2]/div[1]/div[1]/div/div[2]/div[2]/div/form/table/tbody/tr[6]/td/input[1]
"));
if (p1.isEnabled()){
p1.click();
p1.sendKeys("s");
}
WebElement p2 = driver.findElement(By.xpath("/html/body/div[3]/div[3]
/div[2]/div/div[2]/div[1]/div[1]/div/div[2]/div[2]/div/form/table/tbody/tr[6]/td/input[2]
"));
if (p2.isEnabled()){
p2.sendKeys("d");
}
WebElement p3 = driver.findElement(By.xpath("/html/body/div[3]/div[3]
/div[2]/div/div[2]/div[1]/div[1]/div/div[2]/div[2]/div/form/table/tbody/tr[6]/td/input[3]
"));
if (p3.isEnabled()){
p3.sendKeys("s");
}
I have a solution in pseudocode but I don't know exactly how to do it in Java.
for i =0;i<10;i++
associate i with a field
if passworfield is enabled
set password letter based on xpath
A:
If you take a look at the xPath you are using, they only differ on the index of the input.
For my suggested approach you would need to have a char array where you hold the password.
So, a possible approach would be to have a loop with an index more or less like this:
char[] password = new char[]{'p','a','s','s','w','o','r','d','1'};
for (int i = 0; i < 9; i++)
{
WebElement elem = driver.findElement(By.xpath("/html/body/div[3]/div[3]/div[2]/div/div[2]/div[1]/div[1]/div/div[2]/div[2]/div/form/table/tbody/tr[6]/td/input[" + (i + 1) + "]"));
if (elem != null && elem.isEnabled())
elem.sendKeys(Character.toString(password[i]));
}
Just notice that I'm using Character.toString because I'm not sure if sendKeys allows a char instead of a String. If there's any way that's possible I'd recommend you do so.
EDIT:
Another possibility that has been suggested is to get all the elements first (which would improve the performance as you'd not need to force Selenium to analyze the webpage over and over again.. where it would be simplified to (something approximately like):
char[] password = new char[]{'p','a','s','s','w','o','r','d','1'};
List<WebElement> elements = driver.findElements(By.xpath("/html/body/div[3]/div[3]/div[2]/div/div[2]/div[1]/div[1]/div/div[2]/div[2]/div/form/table/tbody/tr[6]/td/input"));
for (WebElement elem : elements)
{
if (elem.isEnabled())
elem.sendKeys(Character.toString(password[elements.indexOf(elem)]));
}
|
[
"math.stackexchange",
"0002914092.txt"
] | Q:
Proving $\int_0^1\frac{(1-t)^n}{(1+t)^{n+1}}dt = \frac{1}{2n} + O\left( \frac{1}{n^2}\right)$
The integral $\int_0^1\frac{(1-t)^n}{(1+t)^{n+1}}dt$ pops up when estimating the remainder of the series $\sum_{k} \frac{(-1)^k}k$.
Indeed, by Taylor's theorem with integral remainder, $$\log(1+x) = \sum_{k=1}^n (-1)^{k+1}\frac{x^k}{k} + \int_0^x \frac{(x-t)^n}{n!}\frac{(-1)^nn!}{(1+t)^{n+1}}dt$$
For $x=1$, this yields $$\sum_{k=n+1}^\infty \frac{(-1)^{k+1}}k =(-1)^n\int_0^1\frac{(1-t)^n}{(1+t)^{n+1}}dt$$
Mathematica says that $\displaystyle \int_0^1\frac{(1-t)^n}{(1+t)^{n+1}}dt=\frac{1}{2n} + O\left( \frac{1}{n^2}\right)$. I'm wondering how this can be proved.
Since $t\mapsto \frac{(1-t)^n}{(1+t)^{n+1}}$ converges pointwise to $\mathbb 1_{\{0\}}(t)$, the integral can be estimated by splitting it as $\int_0^{\epsilon_n} + \int_{\epsilon_n}^1$, for some $\epsilon_n$. However choosing the right $\epsilon_n$ seems difficult. I don't have any other approach in mind.
A:
Apply the substitution $u = \frac{1-t}{1+t}$ to notice that
$$ \int_{0}^{1} \frac{(1-t)^n}{(1+t)^{n+1}} \, dt
= \int_{0}^{1} \frac{u^n}{1+u} \, du. $$
Now integration by parts proves the desired estimates:
\begin{align*}
\int_{0}^{1} \frac{u^n}{1+u} \, du
&= \left[ \frac{u^{n+1}}{n+1} \cdot \frac{1}{1+u} \right]_{0}^{1}
+ \int_{0}^{1} \frac{u^{n+1}}{n+1} \cdot \frac{1}{(1+u)^2} \, du \\
&= \frac{1}{2(n+1)} + \mathcal{O}\left( \int_{0}^{1} \frac{u^{n+1}}{n+1} \, du \right) \\
&= \frac{1}{2n} + \mathcal{O}\left( \frac{1}{n^2} \right).
\end{align*}
Addendum. Generalizing this observation leads to the following convergent series representation:
\begin{align*}
\int_{0}^{1} \frac{u^n}{1+u} \, du
&= \frac{1}{2} \int_{0}^{1} \frac{u^n}{1 - \frac{1-u}{2}} \, du \\
&= \sum_{k=0}^{\infty} \frac{1}{2^{k+1}} \int_{0}^{1} u^n(1-u)^k \, du \\
&= \sum_{k=0}^{\infty} \frac{1}{2^{k+1}} \cdot \frac{k!}{(n+1)\cdots(n+k+1)}.
\end{align*}
|
[
"stackoverflow",
"0004525791.txt"
] | Q:
How to sort JSON array with time??( not working as suggested before)
with reference of this question Sort json array
I have the following JSON String using ajax and store the object as an array:
var homes = [
{
"h_id":"3",
"city":"Dallas",
"state":"TX",
"zip":"75201",
"price":"162500",
"start_time":"2011-01-26 08:00:00",
"end_time":"2011-01-26 05:00:00"
},
{
"h_id":"4",
"city":"Bevery Hills",
"state":"CA",
"zip":"90210",
"price":"319250",
"start_time":"2011-01-26 12:00:00",
"end_time":"2011-01-26 05:00:00"
},
{
"h_id":"5",
"city":"New York",
"state":"NY",
"zip":"00010",
"price":"962500",
"start_time":"2011-01-28 08:00:00",
"end_time":"2011-01-26 05:00:00"
}
];
How do I create a function to sort the "start_date" field in ASC and also sort in DESC ordering using only JavaScript?
i used below function suggested by Triptych
var sort_by = function(field, reverse, primer){
reverse = (reverse) ? -1 : 1;
return function(a,b){
a = a[field];
b = b[field];
if (typeof(primer) != 'undefined'){
a = primer(a);
b = primer(b);
}
if (a<b) return reverse * -1;
if (a>b) return reverse * 1;
return 0;
}
}
and apply in below manner
// Sort by start_time
homes.sort(sort_by('start_time', false, function(a){return a.getTime()}));
but not working..:((, give this error
a.getTime is not a function
please tell me where i m doing mistake..
Thanks in advance
Note: sorry for copying same
question...
A:
As I said in the comment, a string does not have a getTime() method. Only Date objects have. Therefore you have to convert the date string into a Date object. Change your function to:
function(a){return (new Date(a)).getTime()}
Now, there are various implementations of Date and I think only the newer ones support parsing of this kind of date string (not sure though). Maybe you have to parse the string first and pass the single values to Date:
function(a){
var parts = a.match(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/);
var date = new Date(parts[1], parts[2], parts[3], parts[4], parts[5], parts[6]);
return date.getTime()}
}
Reference: Date
|
[
"stackoverflow",
"0037651015.txt"
] | Q:
Webpack using bootstrap - jquery is not defined
import $ from 'jquery';
require("./node_modules/bootstrap/dist/css/bootstrap.min.css")
require("./node_modules/bootstrap/js/dropdown.js")
import React from 'react';
import ReactDOM from 'react-dom';
var _ = require('lodash');
Please refer above my setting . Some reason I've got error saying "Uncaught ReferenceError: jQuery is not defined() from dropdown.js
I also included the following lines at webpack.config.js
plugins: [
new webpack.NoErrorsPlugin({
$: "jquery",
jQuery: "jquery"
})
]
But, No luck - Still having jQuery undefined error.
Any idea ? Can someone help this issue please?
Many thanks
A:
please use webpack ProviderPlugin, use global is not a good idea.
// webpack.config.js
module.exports = {
...
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})
]
};
A:
This will work!
global.jQuery = require('jquery');
instead of
import $ from 'jquery';
A:
global.jQuery did not work for me. But I found an interesting read here: http://reactkungfu.com/2015/10/integrating-jquery-chosen-with-webpack-using-imports-loader/
The basic idea is to use webpacks 'imports-loader'. Notice, though, that it's not installed by default, so first thing install (npm install --save imports-loader). And in webpack.config add to your loaders the following:
{ test: /bootstrap.+\.(jsx|js)$/, loader: 'imports?jQuery=jquery,$=jquery,this=>window' }
After that just import jquery and bootstrap, or some other plugins extending on 'jQuery', as usually.
regards
|
[
"stackoverflow",
"0001462744.txt"
] | Q:
C++ enum by step
I'm trying to write the equivalent of an enum in C++ going in steps of eight instead of one, like
enum
{
foo,
bar = 8,
baz = 16,
};
There will be a lot of entries, new ones will be added at intervals, and for clarity they really want to be written in an order other than order of entry, so it would be nice not to have to keep updating all the numbers by hand. I've tried mucking around with macro preprocessor tricks, but no dice so far. Is there a way to do this that I'm overlooking?
A:
#define NEXT_ENUM_MEMBER(NAME) \
NAME##_dummy, \
NAME = NAME##_dummy - 1 + 8
enum MyEnum {
Foo,
NEXT_ENUM_MEMBER(Bar),
NEXT_ENUM_MEMBER(Baz),
...
};
A:
I prefer something like this:
enum {
foo = (0 << 3),
bar = (1 << 3),
baz = (2 << 3),
};
It's not automated, but it doesn't require much thinking when adding a new enum constant.
A:
I'm not quite sure what you're asking, but this approach will autogenerate values at steps of 8, and make it relatively easy to insert new values in the middle of the enum and have all the following values update to accomodate the change:
enum
{
foo,
bar = foo + 8,
baz = bar + 8
}
After editing to add a "newvalue" you would have:
enum
{
foo,
bar = foo + 8,
newvalue = bar + 8,
baz = newvalue + 8
}
You could also use a "Step" constant so that you can (a) change your mind about the step later, and (b) stop anyone accidentally adding the wrong step:
const int EnumStep = 8;
enum
{
foo,
bar = foo + EnumStep,
baz = bar + EnumStep
}
|
[
"stackoverflow",
"0041756963.txt"
] | Q:
Hibernate Spatial Create Geometry object
I am developing an location app with oracle spatial in Java. I am using hibernate 4.0 spatial for orm layer. I am new in spatial and i couldn't find best practise for hibernate spatial. My database model following;
CREATE TABLE SYSTEM.POI (
POI_ID INTEGER,
SERVICE_ID INTEGER,
POI_NAME VARCHAR2(255 CHAR),
DESCRIPTION VARCHAR2(1023 CHAR),
CATEGORY VARCHAR2(127 CHAR),
ADDRESS VARCHAR2(4000 CHAR),
MOBILE_PHONE VARCHAR2(15 CHAR),
FIXED_PHONE VARCHAR2(15 CHAR),
BUSINESS_HOURS VARCHAR2(1023 CHAR),
SHAPE SDO_GEOMETRY
)
insert statement is following;
INSERT INTO SYSTEM.POI (SERVICE_ID, POI_NAME, DESCRIPTION, CATEGORY, ADDRESS, MOBILE_PHONE, FIXED_PHONE, BUSINESS_HOURS, SHAPE)
VALUES(
'1320',
'PO-Kral Petrol Ürünleri San ve Tic. Ltd. şti.',
'Camilerimiz',
'CAMI',
'İSLİCE MAHALLESİ DERE SOKAK NO:5',
'2762151093',
'5552552343',
'Hafta içi 09:00 - 17:00, haftasonu 09:00 - 13:00 açık',
SDO_GEOMETRY(
2001,
3785,
SDO_POINT_TYPE(28.90762, 41.1521, NULL),
NULL,
NULL
)
);
entity model is following i'm sharing just sdo_geometry object;
import com.vividsolutions.jts.geom.Geometry;
...
@Column(name="SHAPE")
@Type(type = "org.hibernatespatial.GeometryUserType")
private Geometry shape;
public Geometry getShape() {
return shape;
}
public void setShape(Geometry shape) {
this.shape = shape;
}
How can i fill this spahe object with dynamic parameters. For example;
SDO_GEOMETRY(
2001, --> sdo_gtype
3785, --> sdo_srid
SDO_POINT_TYPE(28.90762, 41.1521, NULL), --> sdo_point
NULL, --> sdo_elem_info
NULL --> sdo_ordinates
)
How to pass sdo_gtype,sdo_srid,sdo_point_type parameters to geometry object dynamically?
A:
You can create as shown below.
com.vividsolutions.jts.geom.Point p = new GeometryFactory().createPoint(new Coordinate(12.34343, 12.232424));
System.out.println(p);
In the GeonmetryFactory constructor you can pass precision model, srid and CoordinateReferenceSystem.
However there is spatial wrapper around JTS called geolatte, which is shipped with Hibernate Spatial(automatically downloads jars in maven). You can create Point using Geolatte as shown below.
org.geolatte.geom.Point<G2D> point = Geometries.mkPoint(new G2D(12.34343, 12.232424), CoordinateReferenceSystems.WGS84);
System.out.println(point);
There are utility class to tranform from JTS to Geolatte and vice-versa. And attaching output of the program also.
org.geolatte.geom.Point<G2D> point = Geometries.mkPoint(new G2D(12.34343, 12.232424), CoordinateReferenceSystems.WGS84);
System.out.println(point);
com.vividsolutions.jts.geom.Point p = new GeometryFactory(new PrecisionModel(), 4326).createPoint(new Coordinate(12.34343, 12.232424));
System.out.println(p);
System.out.println(JTS.to(point));
System.out.println(JTS.from(p));
Output:
SRID=4326;POINT(12.34343 12.232424)
POINT (12.34343 12.232424)
POINT (12.34343 12.232424)
SRID=4326;POINT(12.34343 12.232424)
UPDATE
Projection you are looking for is supported by Geolatte, here are SRID supported by Geolatte, Since you are using Project CS, you need to use C2D(Cartesian 2D)
Here is code example to create
System.out.println(CrsRegistry.getProjectedCoordinateReferenceSystemForEPSG(3785).getName());
org.geolatte.geom.Point<C2D> point1 = Geometries.mkPoint(new C2D(12.34343, 12.232424), CrsRegistry.getProjectedCoordinateReferenceSystemForEPSG(3785));
System.out.println(point1);
output:
Popular Visualisation CRS / Mercator (deprecated)
SRID=3785;POINT(12.34343 12.232424)
|
[
"stackoverflow",
"0008883337.txt"
] | Q:
Set image expire date in IIS6 using Ionics ISAPI Rewrite Filter
I have a shared hosting account with ASP.NET , Windows Server 2003 , IIS6 and Plesk 8.6 control panel.
How can I set the expiry date of CSS, JS and images? Is it possible in shared hosting? With web.config or other file? How?
Currently gtmetrix.com says that the expiry date of some files are not set.
EDIT : There is an almost same question for IIS7. will the method in this question also works for IIS6?
EDIT 2 : My hosting provider uses ionic's isapi rewrite filter for wild card mapping.
A:
Ionics Isapi help documentation can be found here:
http://iirf.codeplex.com/documentation
Depending on the version of the filter there is different documentation. The filter has a function called RewriteHeader which will allow you to set the header.
You'll need to create a RewriteCondition that parses the URL for .js, .css, .jpg, .jpeg, .png, .gif, etc and then RewriteHeader with a new expires header..
You can review the following page for more information on how to set an expires header, mainly see 14.9.3 and 14.21.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
As for how to calculate the value to set in the header, you may want to post that in the Discussion section of the CodePlex site for the project:
http://iirf.codeplex.com/discussions
|
[
"stackoverflow",
"0009459944.txt"
] | Q:
How to achieve DataBinding of a code behind element?
I have the following scenario: I'm creating a card game, and as part of it, I want to create a UserControl to make the interface programming easier and better. I'm creating the following user control:
.cs
public partial class ChimeraUserControl : UserControl
{
private ChimeraViewModel Chimera { get; set; }
public ChimeraUserControl(Chimera chimera)
{
this.Chimera = new ChimeraViewModel(chimera);
InitializeComponent();
}
}
I want to be able to do two things: when using this user control, to be able to send a Chimera through binding, and also, to make all the texts and other elements to be binded to this Chimera. I've searched a lot, but didn't find nothing that satisfied me.
What do you guys think?
What I already tried to read:
http://dev-for-fun.blogspot.com/2008/06/wpf-example-create-usercontrol-and.html
Binding from View-Model to View-Model of a child User Control in Silverlight? 2 sources - 1 target
And a lot of other pages, but none seemed straight-forward enough, and by hacking its codes I didn't find my problem's solution.
A:
First off, make Chimera a Dependency Property so it can participate in the binding system
public static readonly DependencyProperty ChimeraProperty =
DependencyProperty.Register("Chimera ", typeof(ChimeraViewModel),
typeof(ChimeraUserControl), new FrameworkPropertyMetadata(null));
public ChimeraViewModel Chimera
{
get { return (ChimeraViewModel)GetValue(ChimeraProperty ); }
set { SetValue(ChimeraProperty, value); }
}
Second, you can reference your Chimeria property through a RelativeSource or ElementName binding
<UserControl x:Name="ChimeraViewRoot" ... >
<StackPanel>
<!-- ElementName Binding -->
<TextBlock Text="{Binding ElementName=ChimeraViewRoot, Path=Chimeria.Name}" />
<!-- RelativeSource Binding -->
<TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:ChimeraView}}, Path=Chimeria.Name}" />
</StackPanel>
</UserControl>
You can also just set the DataContext of the controls inside your UserControl to the Chimera property to make your binding syntax cleaner
<UserControl x:Name="ChimeraViewRoot" ... >
<StackPanel DataContext="{Binding RelativeSource={RelativeSource AncestorType={x:Type local:ChimeraView}}, Path=Chimeria}" >
<TextBlock Text="{Binding Name}" />
<TextBlock Text="{Binding Description}" />
</StackPanel>
</UserControl>
I usually do not suggest defining the UserControl.DataContext in your UserControl because that value is supposed to be passed in from whatever uses the UserControl. Setting in inside the UserControl can cause confusion later on when you're trying to figure out why a specific UserControl doesn't work with an expected DataContext.
Personally when I create a ViewModel that is supposed to go with a specific UserControl, I prefer to set a DataTemplate in the application so that all instances of my ViewModel get drawn with my custom UserControl. This means that I assuming the UserControl.DataContext will always be of a specific ViewModel type
<DataTemplate DataType="{x:Type local:ChimeriaViewModel}">
<local:ChimeriaView /> <!-- DataContext will always be ChimeriaViewModel -->
</DataTemplate>
This will use the ChimeriaView implicitly whenever the Visual Tree encounters an object of type ChimeriaViewMmodel.
For example, the following will render a StackPanel filled with ChimeriaView objects
<ItemsControl ItemsSource="{Binding MyListOfChimeriaViewModels}" />
Or to display a single object I'll usually use something like a ContentControl
<!-- Will get drawn using ChimeriaView due to DataTemplate defined above -->
<ContentControl Content="{Binding MyChimeriaViewModelProperty}" />
Also, by knowing the DataContext for the ChimeriaView is going to be an object of type ChimeriaViewModel, I would get rid of the DependencyProperty altogether
<UserControl>
<StackPanel>
<!-- I know the DataContext is ChimeriaViewModel -->
<TextBlock Text="{Binding Name}" />
<TextBlock Text="{Binding Description}" />
</StackPanel>
</UserControl>
|
[
"stackoverflow",
"0015870198.txt"
] | Q:
H 264 Baseline Profile - Azure media services
All,
I am new to azure media services and generally media programming, so might be a foolish question.
I have requirement to upload videos from clients and stream them for Android (immediate) and iOS (later). Now we choose azure media services for this and wen through zillions of posts to find the best encoding for Android - multitude of devices. I figured that H.264 Baseline profile, even though is not of top notch quality, it will do just fine. Our customers will watch videos in low cost android tablets, so i guess I am good there.
Ref: http://social.msdn.microsoft.com/Forums/en-US/MediaServices/thread/95ec8895-4a73-4a0c-8505-3ca5d8bbe13e
Now, if the above makes sense, I could not see a "Task Preset" here http://msdn.microsoft.com/en-us/library/windowsazure/jj129582.aspx#H264Encoding targetting the baseline profile.
Per http://msdn.microsoft.com/en-us/library/azure/dn535852.aspx Azure supports Baseline profile, but what is the "TASK PRESET" for Base profile so that i can programmatically create a job?
Please help
Cheers
A:
The forum post you reference is a very old one from the early preview days of Azure Media Services. The Task Preset mentioned there is no longer available. From what I can see in the rest of documentation is that H.264 Baseline profile is supported, but currently there is no Task Preset that would encode input video to a H.264 Baseline. The H.264 codec presets include High and Main profiles.
You correctly see that currently there is no single task preset that targets Baseline profile.
But Windows Azure Media services is a hidden beast! I've written an article that with Azure Media Services, something that is not documented and not officially supported - Clip or Trim your video files.
Your challenge is a bit interesting since it appears to have been supported before, but dropped out after GA. Follow my blog as I might come up with a "Task Preset" for your needs soon!
UPDATE
You can create H.264 Baseline profile videos by using a custom task preset. User this XML String as task preset with Windows Azure Media Encoder:
<?xml version="1.0" encoding="utf-16"?>
<!--Created with Expression Encoder version 4.0.4276.0-->
<Preset
Version="4.0">
<Job />
<MediaFile
WindowsMediaProfileLanguage="en-US"
VideoResizeMode="Letterbox">
<OutputFormat>
<MP4OutputFormat
StreamCompatibility="Standard">
<VideoProfile>
<BaselineH264VideoProfile
RDOptimizationMode="Speed"
HadamardTransform="False"
SubBlockMotionSearchMode="Speed"
MultiReferenceMotionSearchMode="Speed"
ReferenceBFrames="True"
AdaptiveBFrames="True"
SceneChangeDetector="True"
FastIntraDecisions="False"
FastInterDecisions="False"
SubPixelMode="Quarter"
SliceCount="0"
KeyFrameDistance="00:00:05"
InLoopFilter="True"
MEPartitionLevel="EightByEight"
ReferenceFrames="4"
SearchRange="32"
AutoFit="True"
Force16Pixels="False"
FrameRate="0"
SeparateFilesPerStream="True"
SmoothStreaming="False"
NumberOfEncoderThreads="0">
<Streams
AutoSize="False"
FreezeSort="False">
<StreamInfo>
<Bitrate>
<ConstantBitrate
Bitrate="4000"
IsTwoPass="False"
BufferWindow="00:00:04" />
</Bitrate>
</StreamInfo>
</Streams>
</BaselineH264VideoProfile>
</VideoProfile>
<AudioProfile>
<AacAudioProfile
Level="AacLC"
Codec="AAC"
Channels="2"
BitsPerSample="16"
SamplesPerSecond="44100">
<Bitrate>
<ConstantBitrate
Bitrate="160"
IsTwoPass="False"
BufferWindow="00:00:00" />
</Bitrate>
</AacAudioProfile>
</AudioProfile>
</MP4OutputFormat>
</OutputFormat>
</MediaFile>
</Preset>
Check out this blog post for further information.
|
[
"stackoverflow",
"0023004882.txt"
] | Q:
Choosing a folder with JFileChooser
I want the user to choose where should a certain file be produced in which folder using aJFileChooser. However, I do not want the user to choose a file, but a folder only.
How would i go on about doing that?
A:
You would use setFileSelectionMode():
Sets the JFileChooser to allow the user to just select files, just select directories, or select both files and directories. The default is JFilesChooser.FILES_ONLY.
A:
Take a look at JFileChooser#setFileSelectionMode(int mode)
Sets the JFileChooser to allow the user to just select files, just
select directories, or select both files and directories. The default
is JFilesChooser.FILES_ONLY. Parameters: mode - the type
of files to be displayed: - JFileChooser.FILES_ONLY -
JFileChooser.DIRECTORIES_ONLY -
JFileChooser.FILES_AND_DIRECTORIES
|
[
"stackoverflow",
"0050827558.txt"
] | Q:
Partition dataset by timestamp
I have a dataframe of millions of rows like so, with no duplicate time-ID stamps:
ID | Time | Activity
a | 1 | Bar
a | 3 | Bathroom
a | 2 | Bar
a | 4 | Bathroom
a | 5 | Outside
a | 6 | Bar
a | 7 | Bar
What's the most efficient way to convert it to this format?
ID | StartTime | EndTime | Location
a | 1 | 2 | Bar
a | 3 | 4 | Bathroom
a | 5 | N/A | Outside
a | 6 | 7 | Bar
I have to do this with a lot of data, so wondering how to speed up this process as much as possible.
A:
I am using groupby
df.groupby(['ID','Activity']).Time.apply(list).apply(pd.Series).rename(columns={0:'starttime',1:'endtime'}).reset_index()
Out[251]:
ID Activity starttime endtime
0 a Bar 1.0 2.0
1 a Bathroom 3.0 4.0
2 a Outside 5.0 NaN
Or using pivot_table
df.assign(I=df.groupby(['ID','Activity']).cumcount()).pivot_table(index=['ID','Activity'],columns='I',values='Time')
Out[258]:
I 0 1
ID Activity
a Bar 1.0 2.0
Bathroom 3.0 4.0
Outside 5.0 NaN
Update
df.assign(I=df.groupby(['ID','Activity']).cumcount()//2).groupby(['ID','Activity','I']).Time.apply(list).apply(pd.Series).rename(columns={0:'starttime',1:'endtime'}).reset_index()
Out[282]:
ID Activity I starttime endtime
0 a Bar 0 1.0 2.0
1 a Bar 1 6.0 7.0
2 a Bathroom 0 3.0 4.0
3 a Outside 0 5.0 NaN
|
[
"judaism.stackexchange",
"0000109400.txt"
] | Q:
What Rabbis originally supported and opposed Rambam's 13 principles and why?
I heard the when Rambam presented his 13 principles the opinions divided pretty sharply between the Sefardic Rabbis that openly supported it and the Ashkenazi (Rabaney Tzarfat) that opposed it for different reasons.
I'd like to know more and have sources for who are the Rabbis that supported and opposed Rambam's 13 principles and what were their arguments.
A:
What an excellent question! They were many rabbis who supported and opposed the Rambam's 13 principles of faith.
In his The Limits of Orthodox Theology: Maimonides’ Thirteen Principles Reappraised, Rabbi Marc B. Shapiro examines the principals. In his Commentary on the Mishnah, Introduction to Perek Chelek, Maimonides calls this dogma; whoever rejects these principles loses their share in the World to Come. Menachem Kellner calls the principles the first dogma of Judaism. But some have condemned this as a scare tactic, similar to those used in Christianity (accept Jesus or else). Yet, as we will see, even well-respected Orthodox rabbis rejected his ideas. Some speculate on whether Rambam himself accepted them. We will go through a few (but of course not all).
13 Principles reappraised
There is many responsa literature on the subject. While Maimonides listed 13, Shimon ben Zemah Duran, in his Ohev mishpat and Joseph Albo, in Sefer Ha-ikkarim listed only three. Hasdai Crescas, in Or ha-shem listed only six. David ben Yom Tov ibn Bilia lists twenty-six principles of faith. Don Isaac Abravanel lists 613.
The Tosaphist Rabbi Moses Taku disagreed with Maimonides' first principle. He felt that G-d could do the impossible (create a rock so big that He cannot lift and yet lifts it). He also felt that sometimes G-d can take human form and calls Rambam's position that G-d does not change and is always incorporeal, thus denying that G-d sometimes change is considered heresy.
Rabbi Abraham ben David of Posquieres (known as Rabad, or Ra’avad,) disagreed with the second and third principles'. Writing, "There are many people greater and superior to him who adhere to such a belief [that G-d has a body like humans] on the basis of what they have seen in verses of Scripture and even in the words of those aggadot which corrupt right opinion about religious matters.” He also wrote, “greater and better people than Rambam” were corporealists. Comment to Hilchos Teshuvah 3:7. According to Rabbi Slifkin Rashi was a corporealist. You can read that article here. Additionally, Kabbalist believes that G-d is made up of ten parts called Sefirot.
Abraham ibn Ezra rejects the fourth, saying, that G-d created the world out of preexisting matter. Some scholars dispute whether the Rambam might have also felt this way and might have used "Nessecary beliefs" to state the opposite if that was not his true conviction. (more on that later).
Some Jews seemingly reject the fifth principle when they pray to angels every Friday night in the Shalom Aleichem, which states: “Bless me for peace, angels of peace.” Others have rationalized it, saying that it's not to be taken literally. Maimonides himself seemingly rejects the sixth principle, stating that prophecy is the result of a higher intellect.
The Babylonian Talmud seems to disagree with the 7th. Sanhedrin 21b states that Ezra is greater than Moses: “If Moses had not preceded him, Ezra would have been worthy to have the Torah revealed to Israel through him.” The Midrash Genesis Rabbah 14:34 thinks it was Balaam: “What prophet did they [non-Israelites] have who was like Moses? Balaam the son of Beor.” Regarding the 8th, the Masoretic text has changed a few letters, though with minor variations. See the Midrash Numbers Rabbah and Avot d’Rabbi Natan regarding the Masorites placing dots.
Regarding the ninth, the Babylonian Talmud, Nidah 61b, Rabbi Joseph says: “The mitzvot [commandments] will be abolished in the time to come.” Rabbi Joseph Albo, in his Sefer Ha-ikkarim) writes that a future prophet can abolish [or, nullify] all of the biblical commands except the Decalogue (the Ten Commandments). Regarding the 10th, ibn Ezra writes in Genesis 18:21, “The whole [G-d] knows the individual in a general manner rather than a detailed manner.” Ralbag writes similarly in Milhamot Hashem, that G-d knows the universal but not the particular. Many think the Rambam disputes reward and punishment in his Commentary on the Mishnah, Introduction to Perek Chelek. Rabbi Hillel (Babylonian Talmud, Sanhedrin 99a), would reject principle 12, stating that the messiah already came in the days of King Hezekiah. Regarding the 13th, Rabad writes in his Commentary on the Mishnah, Introduction to Perek Chelek and Mishneh Torah, Hilkhot Teshuvah 8: “There is no resurrection for bodies, but only for souls.” Whether or not bodies resurrect spiritually or physically, all agree that Maimonides wrote that after the messianic age no bodies exist, only intellects.
Necessary beliefs
Some scholars think Maimonides himself did not believe in all of his principles, only the first few that talks about G-d. Some scholars have pointed to a concept called "Necessary beliefs." Spinoza, as well as many Arab philosophers, such as Averroes, used this tradition called Plato's Noble Lie. It was sometimes used to keep civilization in check, to tell untruths or essential beliefs because the masses couldn't grasp deeper philosophy.
Summary
In short, many well-respected rabbis accepted or reject these views. Shapiro stresses in his book that what matters more is behavior. He puts emphasis on action over beliefs.
Disclaimer
Personally, I think Maimonides accepted all of his principles. These [above] are only some of the views proposed by Rabbi Marc B. Shapiro in his book The Limits of Orthodox Theology.
|
[
"stackoverflow",
"0056569839.txt"
] | Q:
How to correctly copy and paste info (charts,tables etc) from a webpage to excel via vba
I have a table on a webpage that I am trying to copy and paste into excel, correctly formatted. It comes out all of it in one column, no matter what I try to do to fix it.
I am able to copy it and paste it, it's just super incorrectly formatted. please help.
a lot of stuff before this....
lastrow = ws.Cells(ws.rows.Count, "A").End(xlUp).Row
' lastrow = ws.Range("A1").End(xlUp).Row
i = i + 1
For i = 3 To lastrow
Set svalue1 = .getElementbyID("provideANumber")
svalue1.Value = ws.Cells(i, 1).Value
For Each eInput In .getElementsbyTagName("input")
If eInput.getAttribute("value") = "ENTERit" Then
eInput.Click
Exit For
End If
Next
IE.Visible = True
Exit For
Next i
more stuff in between.....
'Copy and Paste Results into Excel
Sheets("Sheet4").Select
Range("A1:Z50") = ""
Range("A1:Z150").Select
Application.Wait DateAdd("s", 10, Now)
IE.ExecWB 17, 0 '//select all
IE.ExecWB 12, 2 '//Copy Selection
ActiveSheet.PasteSpecial Format:="Text", link:=False, displayasicon:=False
Range("A1:Z100").Select
I expect it to show up similiarly to how it looks on the website, however, it shows up all together in one column (and not even legible)
A:
Sheets("Sheet4").Select
Range("A1:Z100") = ""
Range("A1:Z100").Select
Selection.ClearContents
Application.Wait DateAdd("s", 2, Now) '//Loads
IE.ExecWB 17, 0 '//select all from webpage
IE.ExecWB 12, 2 '//Copy Selection
Application.DisplayAlerts = False '//Doesnt display alerts
ActiveSheet.Paste
Sheets("Sheet4").Select '//Selects sheet 4 again
Range("A3:Q32").Select
Selection.Copy
'Creates a new sheet after & pastes content into it, formats
Sheets.Add After:=ActiveSheet
ActiveSheet.Paste
Selection.Columns.AutoFit
Selection.rows.AutoFit
This code allowed me to copy and paste the data from the web page the way it's formatted on the web page
|
[
"stackoverflow",
"0028354931.txt"
] | Q:
Incorrect table definition; there can be only one auto column and it must be defined as a key
I keep getting error while migrating in Laravel
[PDOException]
SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table definition; there can be only one auto column and it must be defined
as a key
Code
public function up()
{
Schema::create('inventories', function($table){
$table->engine = 'InnoDB';
$table->increments('id')->unsigned();
$table->string('sku',255);
$table->string('description', 255 )->nullable;
$table->tinyInteger('stock',5)->nullable()->unsigned();
$table->tinyInteger('day_of_week',1)->unsigned();
$table->text('note')->nullable();
$table->timestamps();
});
}
A:
/**
* Create a new tiny integer column on the table.
*
* @param string $column
* @param bool $autoIncrement
* @param bool $unsigned
* @return \Illuminate\Support\Fluent
*/
public function tinyInteger($column, $autoIncrement = false, $unsigned = false)
{
return $this->addColumn('tinyInteger', $column, compact('autoIncrement', 'unsigned'));
}
This is the tinyInteger() function from Blueprint.php. As you can see it expects a boolean parameter here. It looks like you're trying to add a argument for size. You cannot specify the size of tinyint in Laravel.
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('sku',255);
$table->string('description', 255 )->nullable();
$table->tinyInteger('stock')->nullable()->unsigned();
$table->tinyInteger('day_of_week')->unsigned();
$table->text('note')->nullable();
This works fine.
|
[
"stackoverflow",
"0006217100.txt"
] | Q:
check duplicate mysql row
I have a mysql table that contains field_one, field_two, field_three
I want to check if field_one contains a duplicate value (like if it was unique).
How to do that in mysql?
Thanks
A:
This will show you values for field_one that occur more than once:
select field_one, count(*) as Count
from MyTable
group by field_one
having count(*) > 1
|
[
"german.stackexchange",
"0000038327.txt"
] | Q:
German phrase or idiom for "Stay put!"
I'm looking for the German phrase most likely to be used in a tense, dangerous situation (in which a sudden move could get one shot) to warn people to stay put.
To be more precise, the warning is coming from one of the good guys, yelling to the other good guys not to move.
My author has "Ort und Stelle bleiben!", but I fear it was arrived at by direct translation, and is unidiomatic.
A:
An Ort und Stelle has the doubled "place" to assure someone or something is reliably there. That's not what you intend to say.
Sei an Ort und Stelle!
Be at that place reliably!
Bleib an Ort und Stelle!
Stay at that place reliably (I need you to be there)!
Better phrases for your situation just use the verb bleiben:
Bleib, wo du bist!
Bleibt, wo ihr seid!
Telling someone to stay put.
Bleib weg!
Typical warning from someone at a dangerous place or from someone attempting suicide.
Bleib stehen!
Telling someone to stop walking or running.
Stehenbleiben!
Typical movie cop yelling at the bad guy.
Sometimes other verbs match better:
Nicht bewegen!
Typical bomb defusing phrase.
Halt still!
Typical phrase of someone cutting someone else's shackles.
|
[
"stackoverflow",
"0052444657.txt"
] | Q:
Python array confusion
I'm a python newbie. I come from a C/C++ background and it's really difficult for me to get my head around some of python's concepts. I have stumbled upon this block of code which just plain confuses me:
file_names = [os.path.join(label_directory, f)
for f in os.listdir(label_directory)
if f.endswith(".ppm")]
So, it's an array that joins label_directory with a variable f (both strings), which is initially uninitialized. The for loop then populates the variable f if the condition f.endswith(".ppm") is true.
Now, from my C/C++ perspective I see this:
A for loop that has an if statement that returns True or False. Where is the logic that excludes all the files that don't end with ".ppm" extension?
A:
This syntax is called list comprehension. It constructs a list by evaluating expression after the opening square bracket for each element of the embedded for loop that meets criteria of the if.
|
[
"stackoverflow",
"0005080895.txt"
] | Q:
Use of FB.ui with method permissions.request opens popup
I am working on a Facebook IFrame app and using FB.ui to display the permissions request dialog using the JS SDK.
Here is the code I`m using:
FB.ui(
{
method: 'stream.publish',
message: '',
attachment: {
name: 'תחרות התחפושות הגדולה של לגדול',
caption: '',
media: [{ 'type': 'image', 'src': 'http://www.p-art.co.il/ligdol_purim/logo.gif', 'href': 'http://apps.facebook.com/ligdolpurim/', 'width': '101', 'height': '84'}],
description: ('פורים 2011'),
href: 'http://apps.facebook.com/ligdolpurim/'
},
action_links: [
{ text: 'Ligdol Purim', href: 'http://apps.facebook.com/ligdolpurim/' }
],
user_prompt_message: 'פרסם את השתתפותך בתחרות'
},
function(response) {
alert(response.post_id);
});
}
A happy surprise is that the SDK knows to show the dialog only for the missing permissions (if any). The problem is that a new IE window pops up and then disappears before the dialog is shown inside an iframe.
I have tried several variations on this code I found all over the net and all of them give me this popup before showing the dialog.
A:
I had not considered that in order to open a facebook lightbox, you actualy need to be on facebook. I was testing my IFrame outside facebook. When I began testing the app inside a page tab, I got the lightbox. Ya learn something new everyday.
|
[
"math.stackexchange",
"0002696436.txt"
] | Q:
If $S<G:=\text{Gal}(E/R)$ is a Sylow 2-subgroup, then $[\text{Fix}_E(S):R] = [G:S]$
My question pertains to page 235 in Grillet's 'Abstract Algebra', Second Edition. The setup is as follows:
Let $R$ be a formally real field, such that
(i) every positive element of $R$ is a square in $R$
(ii) every polynomial of odd degree in $R[X]$ has a root in $R$
where 'formally real means that there is a total order relation on $R$ that makes it an ordered field.
From the algebraic closure of $R$, pick $i$ as a square root of $-1$ and consider
$$C := R(i)$$
It can be shown that every element of $C$ is a square root and that $C$ has no irreducible polynomial of degree 2 (which implies that $C$ has no extension of degree 2).
Wanting to show that $C$ is algebraically closed, pick some element $\alpha \in \overline C$.
Along with its $R$-conjugates, $\alpha$ generates a finite Galois extension $E$ of $C$, which is also a finite Galois extension of $R$.
Now it can be shown that $G:=\text{Gal}(E/R)$ is of even order. So we can pick a Sylow 2-subgroup $S$ of $G$ and consider its fixed field $F:=\text{Fix}_E(S)$.
I know that $E/F$ is Galois and that $S = \text{Gal}(E/F)$. However, Grillet states the equation
$$[F:R] = [G:S]$$
which I can only come up with, if $F/R$ is a Galois extension ($\iff \text{Gal}(E:F)$ is a normal subgroup of $G$), using that in such a case, $[F:R] = \text{Gal}(F/R) \cong \text{Gal}(E/R)\,/\,\text{Gal}(E/F)$.
But I don't know how to show this. Or is there another way to arrive at the above equation $[F:R]=[G:S]$?
Any help would be appreciated. I have 'self-studied' the basics of Galois theory for progressing with this theorem, so maybe I'm just missing some theorems/propositions here.
Note:
A:
It's very simple, as Jef Laga pointed out in a comment on my question.
We have
$$
|\text{Gal}(E/R)| = [E:R] = [E:F][F:R] \overset{E/F \,\text{finite, Galois}}= |\text{Gal}(E/F)|[F:R]
$$
and hence
$$
[G:S] = [\text{Gal}(E/R) : \text{Gal}(E/F)] = \frac{|\text{Gal}(E/R)|}{|\text{Gal}(E/F)|} = [F : R]
$$
|
[
"stackoverflow",
"0008376895.txt"
] | Q:
Get new contents of a file
A node.js script calls the maxima computer algebra system and redirects my input to the stdin of maxima. Maxima the writes the processed input to a temporary text file where there is a new line for every result maxima returns.
Can node watch for new data written to the file and somehow capture this data (only the new line which is written to the file, not the whole file)?
I already tried fs.watchFile but was unable to capture the actual data returned by it.
Thanks.
A:
fs.watchFile plugs in to the actual file watching functionality in your Operating System (inotify in Linux), it does nothing more than just routing these events through. Any logic on which lines has been changed etc. has to be implemented by yourself. As it's a log file you probably are only interested in the tail, and you can reuse other programs for that. See this example for instance.
If you want to roll your own just do something like:
fs.watchFile("/path/to/log.txt", function (prev, curr) {
// verify writes
if (x && y && z) {
fs.readFile("/path/to/log.txt", "utf8", function (err, body) {
// check what has been appended
});
}
});
|
[
"stackoverflow",
"0023020107.txt"
] | Q:
Casting derived class to base class keeps knowledge of derived when using generics
I have a weird scenario that I can't seem to wrap my head around. I have the following base class:
public class Note
{
public Guid Id { get; set; }
public string SenderId { get; set; }
...
}
Which is then derived by the following class:
public class NoteAttachment : Note
{
public string FileType { get; set; }
public string MD5 { get; set; }
...
}
I use these classes to communicate with a server, through a generic wrapper:
public class DataRequest<T> : DataRequest
{
public T Data { get; set; }
}
public class DataRequest
{
public string SomeField { get; set; }
public string AnotherField { get; set; }
}
So I have a NoteAttachment sent to the method, but I need to wrap a Note object to send to the server. So I have the following extension method:
public static DataRequest<T> GetDataRequest<T>(this T data)
{
DataRequest<T> dataRequest = new DataRequest<T>
{
SomeField = "Some Value",
AnotherField = "AnotherValue",
Data = data
};
return dataRequest;
}
Now the problem. Calling the extension method in the following way works fine, however even though the DataRequest type is DataRequest<Note>, the Data field is of type NoteAttachment.
var noteAttachment = new NoteAttachment();
...
Note note = (Note)noteAttachment;
var dataRequest = note.GetDataRequest();
Debug.WriteLine(dataRequest.GetType()); //MyProject.DataRequest`1[MyProject.Note]
Debug.WriteLine(dataRequest.Data.GetType()); //MyProject.NoteAttachment <--WHY?!
What am I doing wrong?
A:
You are mixing two things: run-time type of an object and compile type of a field.
Type of Data field is still Note. You can verify for yourself with reflection. For example, the following will print "Note":
Console.Write(
typeof(DataRequest<Note>).GetProperty("Data").PropertyType.Name);
The Type of the object that this field contains can be Note or any derived type. Assigning an object to the variable of a base class does not change its run-time class. And since GetType() returns the type of an object you get the actual derived type (NoteAttachment).
A:
As @Alexi answered your first question, ill try the second question in the comment. Add a KnownType attribute to your note class like this:
[KnownType(typeof(NoteAttachment)]
public class Note
|
[
"stackoverflow",
"0047304371.txt"
] | Q:
Connect to RServe from JAVA using authentication
I am running RServe from Server machine using cmd
Rserve.exe --RS-conf Rserv.conf --RS-port 12306
Rserv.conf file has following content:
pwdfile RserveAuth.txt
auth required
remote enable
plaintext disable
RserveAuth.txt has following contents:
Admin 123456
I am connecting to R Server from JAVA
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.REngineException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
import org.rosuda.REngine.REXP;
import org.rosuda.REngine.*;
public class ConnecttoR
{
...
...
public void connectR()
{
try
{
RConnection connection = new RConnection("172.16.33.242",12306); // Works if authentication is not required in Rserv.conf
}
catch (RserveException e) {
e.printStackTrace();
}
catch(REXPMismatchException e){
e.printStackTrace();
}
catch(REngineException e){
e.printStackTrace();
}
}
}
Connection to Rserve is open to all without username & Password. How shall I add security and allow connection only with valid credentials to access Rserve
A:
As you have enabled the authentification after creating the connection as a first command you need to execute the login command. The Java library has a special wrapper for it.
See code below for example use case.
RConnection connection = new RConnection("127.0.0.1",12306);
connection.login("Admin", "123456");
REXP x = connection.eval("R.version.string");
System.out.println(x.asString());
Also, I would recommend using full path as the pwdfile value.
|
[
"stackoverflow",
"0034310488.txt"
] | Q:
Qt cannot find dll, though everything is set
When I start my program it crashes (I made an earlier Post about a very simple program: Programm crashes when QTcpServer is called)
The problem
Running the programm with GDB it immediately exits with the following messages:
The GDB process terminated unexpectedly (exit code 0).
and
During startup program exited with code 0xc0000135
Which means a .dll is missing. Running the program outise of QtCreator, a message pops up that tells me QtNetwork4.dll is missing
What I did to solve
The code is shown in the link mentioned above, as you can see there
I've included QT += network to the the projects .pro-file.
Then I copied that missing .dll from the Qt-install directory
directly to the same folder as the .exe of my program.
I also appended to my PATH the directory where the .dll is located in
the QT-install dir.
Still I'm getting the message that the QtNetwork4.dll is missing, and right now I'm running out of ideas. Somebody knows whats going on?
Kind Regards
A:
sorry to bother you, was my mistake he was looking for QtNetwork4d.dll I missed the d thanks for your support
|
[
"stackoverflow",
"0017949697.txt"
] | Q:
Can't "pull-right" icon glyph in bootstrap
I want to pull right icon glyph in drop down menu like as below
<div class="navbar">
<div class="navbar-inner">
<ul class="nav">
<li class="dropdown">
<a data-toggle="dropdown" class="dropdown-toggle" href="#">Dropdown <b class="caret"></b></a>
<ul class="dropdown-menu">
<li>
<a href="#">2-level Dropdown <i class="icon-arrow-right pull-right"></i></a>
<ul class="dropdown-menu sub-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
</ul>
</li>
<li><a href="#">Another action</a></li>
<li class="divider"></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
</div>
</div>
But when I run this code on FireFox (Chrome and IE are oke), "icon-arrow-right" and "2-level Dropdown" aren't same a line . How can I fix it ?
Full code on JSFIDDLE
A:
<a href="#" style="overflow: hidden;">
<span class="pull-left">2-level Dropdown</span>
<span class="icon-arrow-right pull-right"></span>
</a>
jsfiddle
A:
The solution from cetver works well for me.
For the record though, here's another way to get the same results:
http://www.bootply.com/70536
HTML
<a href="#"><i class="icon-arrow-right"></i> 2-level Dropdown</a>
CSS
.icon-arrow-right {
float: right;
margin-top: 2px;
margin-right: -6px;
}
|
[
"stackoverflow",
"0010607547.txt"
] | Q:
Sending emails through SMTP client using current logged in user
I have web site set up that has some forms authentication through LDAP. I'm sending an email when the currently logged in user clicks a button, however the email is being sent from my address, and not the user. This creates a bit of confusion.
What I want to do is send emails using the logged users account without having them enter their user information again.
I basically want to do this:
MailMessage message = new MailMessage();
message.From = new MailAddress(User.GetIdentity);
message.Subject = Subject;
message.Body = body;
message.IsBodyHtml = true;
SmtpClient client = new SmtpClient("address.qweqwe", 25);
client.Credentials = new System.Net.NetworkCredential(User.Identity);
client.Send(message);
Getting the users email isn't a big deal, I've already got methods for that, but I'm not sure how I should go about getting their credentials. They've already logged on to access the page, and I know they have an LDAP email.
Is there any way to do this without forcing the user to log in again just to send the email?
A:
If your SMTP server requires Credentials, I can see 2 solutions.
Ask the user through the page from their Network Credential (username/password)
Setup an account that has right to relay on behalf of all users. This would allow you to set a single account for the SMTP server. Then, every time you send an email all you would do is change the MailMessage.From property.
|
[
"stackoverflow",
"0011730304.txt"
] | Q:
android - Programmatically turn on/off blink/flipper animation/effect for a ShapeDrawable (RectShape)
Below is the code necessary to draw a rectangle. How would it be possible without using some Runnables to make it blink? Is there an option to make this? Or maybe I should put a blinking background gif?
ShapeDrawable ohMyShape = new ShapeDrawable(new RectShape());
ohMyShape.getPaint().setColor(Color.RED);
ohMyShape.getPaint().setStyle(Style.STROKE);
ohMyShape.setBounds(x, y, x+l, y+h);
ohMyShape.draw(canvas);
I mean something like
ohMyShape.getPain().setAnimation(Animation.BLINK);
would really remove the pain.
A:
Looks like the easiest way of doing this so far is, using 2 images and drawing them on the screen. One of these images should be a blinking gif and the the other is the not blinking version of it.
Thanks anybody who has participated in this monolog.
|
[
"worldbuilding.stackexchange",
"0000115259.txt"
] | Q:
Why would radio signals be invented/transmitted when communication is not an issue?
Imagine a world where you can talk to anyone at all at any time, and telepathically transmit any amount of information to any select group of people.
Why would a world like this ever get to the invention of radio, much less valuing it and transmitting?
Basically, in other words, what other uses could they find for radio?
A:
If they have machines like computers that perform tasks, these may not be able to perform telepathy as they can. Then they would sometimes need a way for computers to communicate wirelessly with each other. Radio isn't usually an ideal way for computers to do this, but it is one way they could have discovered radio and developed communication protocols around it.
A:
Mass Media
The answer comes from the question, specifically select group of people. Radio has two purposes:
Two-way communication between select groups of people. This ranges from individual-to-individual communication on up to shared communication both structured - e.g., emergency responders, air-traffic control - and unstructured - e.g., CB Radio. The telepathic method would work great for individual communication and plausibly well for small groups - you just need a way to identify the group.
Broadcasting. Radio (and over-the-air TV) lets anyone, anywhere within range, receive broadcasts where the sender has no advance knowledge of who is receiving the broadcast. Telepathy doesn't (in my understanding of your world) work that way - the sender needs to (a) have a mental image of the recipients(s) and (b) the telepathic channel is always 2-way.
If I look at a stadium of people (too large for voice communication without amplification) I can instantly telepathically send to them, but I have to be prepared for the mental pressure of all of them (or even a small percentage) sending to me at the same time.
All the more so, if I want to communicate with anyone willing to listen, anywhere within hundreds of miles - including people I have never seen or been introduced to - I can't open the telepathic link, and if I can get past that (send me your picture and address?) then I have the fear of thousands of people trying to talk at one time.
Even worse if I am saying something inflammatory - the opposition would try to get in on the conversation and "mess with my head".
In addition, as @JBH pointed out, radio also allows nonverbal communication, particularly music.
So radio as mass media is the key use. Development would have to take a slightly different path from the real world as much of the initial development was as a wireless telegraph - replacement for a point-to-point wired connection. But it could definitely be done and would definitely be useful.
Machine communication? As in the real world, this will come later, possibly much later. While there are some very basic methods (e.g., radio controlled toy cars) that can be done without computers, the vast majority of what we think of as radio-based machine communications relies on computers. And not just any computers, integrated circuit based microcomputers. This requires advances in a number of different fields, far beyond what you need to have a big vacuum tube transmitter and crystal receivers, which is all you need to get radio functioning as mass media.
A:
If They have Science They will Discover Radio
Radio is part of the electromagnetic (EM) spectrum. EM radiation includes radio, infrared, visible light, x-rays, gamma rays, etc. As they seek to understand the natural world, scientists will classify and quantify the portion of the EM spectrum that we call radio.
Applications
Any species that discovers radio will use it - they just might not use it the same way. Some useful applications include:
RADAR - Radio is integral to RADAR (it's right in the name - RAdio Detection and Ranging) - all kinds of aircraft and self driving cars are using radar today.
Wifi - Wifi is a type of radio wave. If we eliminated broadcast radio we could expand Wifi bandwidth into this space.
Machine to Machine comms - same as above, only use the frequency space for backbone internet traffic instead of edge internet traffic.
Long range comms - If there's any limit on the range for telepathy, radio could come into play. Can you speak telepathically to astronauts in orbit around your world?
|
[
"stackoverflow",
"0014758196.txt"
] | Q:
How to remove every thing after last comma character in a string?
With JavaScript, how can I remove every thing after last coma character in a string using regular expressions?
For example if i input Vettucaud, Thiruvananthapuram, Kerala, India,last word India should be removed and the output need tro be like Vettucaud, Thiruvananthapuram, Kerala
Exactly the reverse thing in
How to get the string after last comma in java?
get all characters after “,” character
A:
Simple:
str = str.replace(/,[^,]+$/, "")
|
[
"stackoverflow",
"0037697520.txt"
] | Q:
Get JSON into Apache Spark from a web source in Java
I have a web server which returns JSON data that I would like to load into an Apache Spark DataFrame. Right now I have a shell script that uses wget to write the JSON data to file and then runs a Java program that looks something like this:
DataFrame df = sqlContext.read().json("example.json");
I have looked at the Apache Spark documentation and there doesn't seem a way to automatically join these two steps together. There must be a way of requesting JSON data in Java, storing it as an object and then converting it to a DataFrame, but I haven't been able to figure it out. Can anyone help?
A:
You could store JSON data into a list of Strings like:
final String JSON_STR0 = "{\"name\":\"0\",\"address\":{\"city\":\"0\",\"region\":\"0\"}}";
final String JSON_STR1 = "{\"name\":\"1\",\"address\":{\"city\":\"1\",\"region\":\"1\"}}";
List<String> jsons = Arrays.asList(JSON_STR0, JSON_STR1);
where each String represents a JSON object.
Then you could transform the list to an RDD:
RDD<String> jsonRDD = sc.parallelize(jsons);
Once you've got RDD, it's easy to have DataFrame:
DataFrame data = sqlContext.read().json(jsonRDD);
|
[
"stackoverflow",
"0010384845.txt"
] | Q:
Merge two json/javascript arrays in to one array
I have two json arrays like
var json1 = [{id:1, name: 'xxx' ...}]
var json2 = [{id:2, name: 'xyz' ...}]
I want them merge in to single arrays
var finalObj = [{id:1, name: 'xxx' ...},{id:2, name: 'xyz' ...}]
A:
You want the concat method.
var finalObj = json1.concat(json2);
A:
Upon first appearance, the word "merg" leads one to think you need to use .extend, which is the proper jQuery way to "merge" JSON objects. However, $.extend(true, {}, json1, json2); will cause all values sharing the same key name to be overridden by the latest supplied in the params. As review of your question shows, this is undesired.
What you seek is a simple javascript function known as .concat. Which would work like:
var finalObj = json1.concat(json2);
While this is not a native jQuery function, you could easily add it to the jQuery library for simple future use as follows:
;(function($) {
if (!$.concat) {
$.extend({
concat: function() {
return Array.prototype.concat.apply([], arguments);
}
});
}
})(jQuery);
And then recall it as desired like:
var finalObj = $.concat(json1, json2);
You can also use it for multiple array objects of this type with a like:
var finalObj = $.concat(json1, json2, json3, json4, json5, ....);
And if you really want it jQuery style and very short and sweet (aka minified)
;(function(a){a.concat||a.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);
;(function($){$.concat||$.extend({concat:function(){return Array.prototype.concat.apply([],arguments);}})})(jQuery);
$(function() {
var json1 = [{id:1, name: 'xxx'}],
json2 = [{id:2, name: 'xyz'}],
json3 = [{id:3, name: 'xyy'}],
json4 = [{id:4, name: 'xzy'}],
json5 = [{id:5, name: 'zxy'}];
console.log(Array(10).join('-')+'(json1, json2, json3)'+Array(10).join('-'));
console.log($.concat(json1, json2, json3));
console.log(Array(10).join('-')+'(json1, json2, json3, json4, json5)'+Array(10).join('-'));
console.log($.concat(json1, json2, json3, json4, json5));
console.log(Array(10).join('-')+'(json4, json1, json2, json5)'+Array(10).join('-'));
console.log($.concat(json4, json1, json2, json5));
});
center { padding: 3em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<center>See Console Log</center>
jsFiddle
A:
You could try merge
var finalObj = $.merge(json1, json2);
|
[
"stackoverflow",
"0012564291.txt"
] | Q:
What is c++ monomorphic class and would this be an example?
Please tell me, if the following class is monomorphic?
What makes it monomorphic? What does monomorphic actually mean?
class Foo
{
public:
Foo(int n)
{
this->m = n;
}
void print()
{
std::cout << this->m << std::endl;
}
private:
int m;
};
Edit:
in context of a class Boo:
class Boo
{
public:
Boo& Boo::operator=(const Boo &boo)
{
*foo1 = *boo.foo1;
*foo2 = *boo.foo2;
return *this;
}
private:
Foo* foo1;
Foo* foo2;
};
A:
First, in order to answer this question, we need to examine what monomorphic really means. To do that, let's break down the word:
mono - morphic
So, if we assume that mono = one and morphic = transformable (at least for this example - don't kill me over dictionary semantics)
So, we can take this to mean many things, here are a few off of the top of my head:
Our class can only be changed once
Or it could be used as the opposite to polymorphism (meaning that it cannot be subclassed)
Finally, it could refer to the property of mathematics: http://en.wikipedia.org/wiki/Monomorphism
So, assuming that that answer 3 isn't what we are looking for (in which case you'd have to find a better answer because that article is confusing), let's step through one and two.
1. Our class can only be changed once
In my opinion, this is the most likely meaning. At first glance, your object is monomorphic, meaning it can only be changed once, through the constructor (be that the designated constructor or the built-in copy constructor).
In any computer that has memory that is read-write, this cannot be true, because there's almost always a way to manually set the bits in memory, if you want / need to.
However, barring from that scenario, using the interface you provided, then yes, your class is monomorphic in that it's member (m) is only set through the constructor.
2. Our class isn't polymorphic
The answer to this one is a bit complex. C++, unlike most languages, has two forms of polymorphism. In a traditional OO sense, it has the ability to create functions that are overwritten by a subclass, which would be marked as virtual. You do not do this, however, so OO polymorphism is NOT possible with your class.
However, as I said earlier, there is more than one type of polymorphism available in C++. The second type is referred to as template polymorphism or function polymorphism, which is used throughout the STL (mainly for iterators), and it works a bit like this:
template<typename aImpl>
void printA(const aImpl &a)
{
a.print();
}
class A {
public:
void print() { puts("I'm in A!"); }
};
Which is a perfectly valid interface, and it would work as expected. However, there is nothing to prevent the following class from being placed to the function:
class B {
public:
void print() { puts("I'm in B!"); }
};
Which would obviously print a different value.
In the end, C++ is a complex language, and if you truly want a class to be unable to be polymorphic, you need to have all members and functions be private, which defeats the purpose of having an object in the first place.
|
[
"stackoverflow",
"0032946548.txt"
] | Q:
Parsing received GCM message into push notification
I'm sending GCM messages from my server to my application.
the notification works with sample data, but when I'm trying to use the received message information from my server, I get empty values.
The is exmplae for a message I get from my server: (received as msg at showNotification())
Received: {
"subtitle": "text",
"sound": "1",
"message": "bla bla",
etc..
This is how I tried to handle it (look for showNotification()):
public class GcmService extends GcmListenerService {
String title;
@Override
public void onMessageReceived(String from, Bundle data) {
JSONObject jsonObject = new JSONObject();
Set<String> keys = data.keySet();
for (String key : keys) {
try {
jsonObject.put(key, data.get(key));
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
sendNotification("Received: " + jsonObject.toString(5));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onDeletedMessages() {
sendNotification("Deleted messages on server");
}
@Override
public void onMessageSent(String msgId) {
sendNotification("Upstream message sent. Id=" + msgId);
}
@Override
public void onSendError(String msgId, String error) {
sendNotification("Upstream message send error. Id=" + msgId + ", error" + error);
}
private void sendNotification(final String msg) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
MainActivity.mTextView.setText(msg);
//JSON Parsing
try {
JSONObject thePush = new JSONObject(msg);
JSONArray pushData;
pushData = thePush.optJSONArray("Received");
thePush = pushData.optJSONObject(0);
if (thePush != null) {
//Initalize data from my JSON
title = thePush.optString("title");
}
} catch (JSONException e) {
e.printStackTrace();
}
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.beer)
.setContentTitle(title)
.setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(1, mBuilder.build());
}
});
}
}
When I Receive GCM message from the below code, I get a message with no title.
the body works since the value is not from my json, for testing.
What's the problem with the way I received the json?
A:
Data you are receiving is already in json format so you can do something like below to get value from the corresponding key
@Override
public void onMessageReceived(String from, Bundle data) {
String subtitle = data.getString("subtitle","defValue");
String sound = data.getString("sound","defValue");
String message = data.getString("message","defValue");
//..... fetch other values similarly
Log.d("Data ->",subtitle+"-"+sound+"-"+message);
}
|
[
"stackoverflow",
"0005864495.txt"
] | Q:
Matching the occurrence and pattern of characters of String2 in String1
I was asked this question in a phone interview for summer internship, and tried to come up with a n*m complexity solution (although it wasn't accurate too) in Java.
I have a function that takes 2 strings, suppose "common" and "cmn". It should return True based on the fact that 'c', 'm', 'n' are occurring in the same order in "common". But if the arguments were "common" and "omn", it would return False because even though they are occurring in the same order, but 'm' is also appearing after 'o' (which fails the pattern match condition)
I have worked over it using Hashmaps, and Ascii arrays, but didn't get a convincing solution yet! From what I have read till now, can it be related to Boyer-Moore, or Levenshtein Distance algorithms?
Hoping for respite at stackoverflow! :)
Edit: Some of the answers talk about reducing the word length, or creating a hashset. But per my understanding, this question cannot be done with hashsets because occurrence/repetition of each character in first string has its own significance. PASS conditions- "con", "cmn", "cm", "cn", "mn", "on", "co". FAIL conditions that may seem otherwise- "com", "omn", "mon", "om". These are FALSE/FAIL because "o" is occurring before as well as after "m". Another example- "google", "ole" would PASS, but "google", "gol" would fail because "o" is also appearing before "g"!
A:
I think it's quite simple. Run through the pattern and fore every character get the index of it's last occurence in the string. The index must always increase, otherwise return false.
So in pseudocode:
index = -1
foreach c in pattern
checkindex = string.lastIndexOf(c)
if checkindex == -1 //not found
return false
if checkindex < index
return false
if string.firstIndexOf(c) < index //characters in the wrong order
return false
index = checkindex
return true
Edit: you could further improve the code by passing index as the starting index to the lastIndexOf method. Then you would't have to compare checkindex with index and the algorithm would be faster.
Updated: Fixed a bug in the algorithm. Additional condition added to consider the order of the letters in the pattern.
|
[
"stackoverflow",
"0032212920.txt"
] | Q:
Minimizing JS getter/setter boilerplate
I am doing closure-oriented object creation with an object that has substantial boilerplate around getter/setter methods. Is there any way to declare these properties as getter/setters without so much repetition?
Currently I have:
var test = function(){
var width = 10;
var height = 10;
return {
width: {get: function(){return width;}, set: function(_){width=_;}},
height: {get: function(){return height;}, set: function(_){height=_;}},
}
}
but I want something more like:
var test = function(){
var width = 10;
var height = 10;
return {
width: getset(width)
height: getset(height),
}
}
I want to write a function like:
var test = function(){
var getset = function(val){
return {
get: function(){
console.log('getting');
return val
},
set: function(_){
console.log('besetted');
param=_
},
}
}
var width = 10;
var height = 10;
return {
width: getset(width),
height: getset(height),
}
}
but this does not work; variables are not overridden properly. What is the best way? Is there a language feature for this?
A:
Here you go:
var test = function(){
var getset = function(value){
var val = value;
return {
get: function(){
console.log('getting');
return val
},
set: function(_){
console.log('besetted');
val=_
},
}
}
var width = 10;
var height = 10;
return {
width: getset(width),
height: getset(height),
}
}
A thing to remember with closures - You need a variable that is accessible throughout the scope inside your inner function as well as outside it.
|
[
"stackoverflow",
"0046038154.txt"
] | Q:
Pass cython functions via python interface
Can a cdef Cython function be passed to another (python def) cython function from a Python script?
Minimal example:
test_module.pyx
cpdef min_arg(f, int N):
cdef double x = 100000.
cdef int best_i = -1
for i in range(N):
if f(i) < x:
x = f(i)
best_i = i
return best_i
def py_f(x):
return (x-5)**2
cdef public api double cy_f(double x):
return (x-5)**2
test.py
import pyximport; pyximport.install()
import testmodule
testmodule.min_arg(testmodule.py_f, 100)
This works well, but I want to be able to also do
testmodule.min_arg(testmodule.cy_f, 100)
from a test.py, to have cython's speed (no Python overhead for each f(i) call). But obviously, Python doesn't know about cy_f, because it's not def or cpdef declared.
I was hoping something like this existed:
from scipy import LowLevelCallable
cy_f = LowLevelCallable.from_cython(testmodule, 'cy_f')
testmodule.min_arg(cy_f, 100)
But this gives TypeError: 'LowLevelCallable' object is not callable.
Thank you in advance.
A:
The LowLevelCallable is a class of functions that must be accepted by the underlying Python module. This work has been done for a few modules, including the quadrature routine scipy.integrate.quad
If you wish to use the same wrapping method, you must either go through the SciPy routines that make use of it, such as scipy.ndimage.generic_filter1d or scipy.integrate.quad. The code sits in compiled extensions, however.
The alternative, if your problem is reasonably well defined for the callback, is to implement this yourself. I have done this in one of my codes, so I post the link for simplicity:
In a .pxd file, I define the interface cyfunc_d_d: https://github.com/pdebuyl/skl1/blob/master/skl1/core.pxd
I can re-use this interface in the "base" cython module https://github.com/pdebuyl/skl1/blob/master/skl1/euler.pyx and also in a "user-defined" module.
The final code makes plain "cython-cython" calls while allowing the passing of objects at the Cython level
I adapted the code to your problem:
test_interface.pxd
cdef class cyfunc:
cpdef double f(self, double x)
cdef class pyfunc(cyfunc):
cdef object py_f
cpdef double f(self, double x)
test_interface.pyx
cdef class cyfunc:
cpdef double f(self, double x):
return 0
def __cinit__(self):
pass
cdef class pyfunc(cyfunc):
cpdef double f(self, double x):
return self.py_f(x)
def __init__(self, f):
self.py_f = f
setup.py
from setuptools import setup, Extension
from Cython.Build import cythonize
setup(
ext_modules=cythonize((Extension('test_interface', ["test_interface.pyx"]),
Extension('test_module', ["test_module.pyx"]))
)
)
test_module.pyx
from test_interface cimport cyfunc, pyfunc
cpdef min_arg(f, int N):
cdef double x = 100000.
cdef int best_i = -1
cdef int i
cdef double current_value
cdef cyfunc py_f
if isinstance(f, cyfunc):
py_f = f
print('cyfunc')
elif callable(f):
py_f = pyfunc(f)
print('no cyfunc')
else:
raise ValueError("f should be a callable or a cyfunc")
for i in range(N):
current_value = py_f.f(i)
if current_value < x:
x = current_value
best_i = i
return best_i
def py_f(x):
return (x-5)**2
cdef class cy_f(cyfunc):
cpdef double f(self, double x):
return (x-5)**2
To use:
python3 setup.py build_ext --inplace
python3 -c 'import test_module ; print(test_module.min_arg(test_module.cy_f(), 10))'
python3 -c 'import test_module ; print(test_module.min_arg(test_module.py_f, 10))'
|
[
"stackoverflow",
"0016418673.txt"
] | Q:
Tips on releasing memory resources in C#
Could someone give me some tips related with release resources (memory resources)? I'm just a student and I'm building a system to an hypothetical small market, and during the testing of the option that add new products to cart, I discovered - using the Task Manager - that something is holding the resources, because the memory used by the program during debugging is increased in some bytes after every time I click on a specific button.
I'd like to know what I'm doing wrong, I also used dispose to release the resources used to connect with the database. Please help me, you don't have to code anything for me, just explain me what else should I release.
The button I'm referring to above is the buttonAdicionar it's event is at, buttonAdicionar_Click.
Here is the code at pastebin if you could take a look: pastebin.com/CdJbJAqc
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace Projeto_TCC
{
public partial class FormCaixa : Form
{
#region Campos
// const string CONNECTION_STRING = "server=localhost;uid=root;pwd=root;database=Projeto_TCC";
private string mensagemDeSaida = "finalizar da aplicação";
private int item = 0;
private double totalVenda = 0.0;
#endregion
#region Método construtor
public FormCaixa()
{
InitializeComponent();
}
#endregion
#region Evento Click do ToolStrip Encerrar sessão
private void encerrarSessãoToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Yes;
mensagemDeSaida = "encerrar esta sessão";
this.Close();
}
#endregion
#region Evento Click do ToolStrip Sair
private void sairToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
#endregion
#region Evento Click do ToolStrip Sobre
private void sobreToolStripMenuItem_Click(object sender, EventArgs e)
{
new AboutBoxProjeto().ShowDialog(); // Isso é uma boa prática?
}
#endregion
#region Evento FormClosing do FormCaixa
private void FormCaixa_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("Deseja " + mensagemDeSaida + "?", "Caixa", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
e.Cancel = true;
mensagemDeSaida = "finalizar da aplicação";
}
#endregion
#region Evento Click do Button Adicionar
private void buttonAdicionar_Click(object sender, EventArgs e)
{
// Prepara a conexão com o DB
MySqlConnection con = new MySqlConnection(Properties.Settings.Default.ConnectionString);
// Objetos utilizado para a realização de alguns processos
MySqlDataAdapter da = new MySqlDataAdapter();
DataTable dt = new DataTable();
// Prepara o comando em SQL que retorná os dados sobre o item a ser adicionado à lista
MySqlCommand cmd = new MySqlCommand("SELECT codigo, descricao, unidMedida, vlUnitario FROM tabEstoque WHERE codBar = @codBar;", con);
cmd.Parameters.Add("@codBar", MySqlDbType.VarChar).Value = textBoxCodBarras.Text;
try
{
// Abre a conexão e executa o comando em SQL
con.Open();
da.SelectCommand = cmd;
da.SelectCommand.ExecuteNonQuery();
da.Fill(dt);
// Caso haja alguma linha no DataSet ds então existe um produto com o codigo de barra procurado no banco de dados
if (dt.Rows.Count == 1)
{
bool itemIgual = false;
int rowIndex = 0;
// Passa por todas as linhas da lista de compras para verificar se existe outro item igual
foreach (DataGridViewRow dgvListaRow in dataGridViewLista.Rows)
{
// Verifica se o produto da linha da lista de compra é o mesmo do código de barras
if (dgvListaRow.Cells[1].FormattedValue.ToString() == dt.Rows[0][0].ToString())
{
// Verifica se estão tentando vender uma certa quantidade de um produto que esteja acima da quantidade do mesmo no estoque
if (!this.VerificarSeExcede(Convert.ToInt32(dgvListaRow.Cells[1].FormattedValue), Convert.ToInt32(dgvListaRow.Cells[3].FormattedValue) + 1))
{
// Adiciona mais um na quantidade do item na lista de compra
dgvListaRow.Cells[3].Value = Convert.ToInt32(dgvListaRow.Cells[3].FormattedValue) + 1;
// Multiplica o VL. ITEM. pela nova quantidade e armazena o resultado em VL. ITEM
dgvListaRow.Cells[6].Value = String.Format("{0:f}",
(Convert.ToDouble(dgvListaRow.Cells[3].Value) * Convert.ToDouble(dgvListaRow.Cells[5].Value)));
// Adiciona o valor do produto ao valor total da venda
totalVenda += Convert.ToDouble(dgvListaRow.Cells[5].Value);
}
else
{
MessageBox.Show("Ocorreu a tentativa de vender uma certa quantidade deste produto que excede a quantidade do mesmo no estoque.", "Caixa", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
itemIgual = true; // Evita que o if abaixo seja executado
break; // Sai do loop para econimizar tempo no processamento
}
rowIndex++;
}
// Caso o item não seja igual a nenhum outro na lista ele é adicionado à lista
if (!itemIgual)
{
// Verifica se estão tentando vender uma certa quantidade de um produto que esteja acima da quantidade do mesmo no estoque
if (!this.VerificarSeExcede(Convert.ToInt32(dt.Rows[0][0].ToString()), 1))
{
dataGridViewLista.Rows.Add(
++item, // ITEM
dt.Rows[0][0], // CÓDIGO
dt.Rows[0][1], // DESCRIÇÃO
1, // QTD.
dt.Rows[0][2], // UN.
dt.Rows[0][3], // VL. UNIT.
dt.Rows[0][3]); // VL. ITEM.
// Adiciona o valor do produto ao valor total da venda
totalVenda += Convert.ToDouble(dt.Rows[0][3].ToString());
}
else
{
MessageBox.Show("Ocorreu a tentativa de vender uma certa quantidade deste produto que excede a quantidade do mesmo no estoque.", "Caixa", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// Atualiza a label que o exibe o total da venda
labelTotal.Text = String.Format("Total: {0:c}", totalVenda);
}
else // Mensagem exibida caso a cosulta nao retorne alguma coisa
{
MessageBox.Show("Este item não consta no banco de dados.", "Caixa", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (MySqlException ex)
{
MessageBox.Show("Ocorreu um erro durante a comunicação com o banco de dados.\n\n" + ex.Message, "Caixa", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
con.Close(); // Fecha a conexão
// Liberam os recursos/espaços ocupados na memória
da.Dispose();
dt.Dispose();
cmd.Dispose();
}
//textBoxCodBarras.Clear();
//textBoxCodBarras.Focus();
}
#endregion
private bool VerificarSeExcede(int codProd, int quantItem)
{
MySqlConnection con = new MySqlConnection(Properties.Settings.Default.ConnectionString);
MySqlCommand cmd = new MySqlCommand("SELECT codigo, quantidade FROM tabestoque WHERE codigo = @codProd", con);
cmd.Parameters.Add("@codProd", MySqlDbType.Int32).Value = codProd;
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
con.Open();
da.SelectCommand.ExecuteNonQuery();
da.Fill(dt);
int quantDB = Convert.ToInt32(dt.Rows[0][1]);
con.Close();
cmd.Dispose();
da.Dispose();
dt.Dispose();
// Verifica se a quantidade do produto no banco de dados é >= que a quantidade do item na lista
if (quantDB >= quantItem)
return false;
else
return true;
}
}
}
Thanks.
A:
My best guess would be by starting to use the using tags in C#
instead of
myConnection = new connection(connectionString);
myConnection.open();
//do something with connection
myconnection.close();
you should try:
using (connection myConnection = new connection(connectionstring))
{
//do something with myConnection
}
Also, make your buttons so that its not calling DB injecting code directly, but use a Control class.
Eg on
`private void buttonAdicionar_Click(object sender, EventArgs e)`
{
controlClass.DoSomethingNow()
}
and in your control class the following method:
controlClass :class
{
//make singleton?
public void DoSomethingNow()
{
using (connection myConnection = new connection(connectionstring))
{
//do something with myConnection
}
}
}
This way you exactly know when you're using what. Your IDE, like Visual Studio, might help you relocate code for better performance, based on tips form the compiler.
Also, as a general tip, try to read up on Design Patterns. these patterns aren't limited to C# so it's a nice to know / must know later on.
|
[
"worldbuilding.stackexchange",
"0000134321.txt"
] | Q:
Habitability of a planet with highly variable temperatures
The surface of the planet I have envisioned is almost entirely desert save for several city-sized "oases," or pockets of water, flora, and fauna that do not exist elsewhere. The temperature fluctuations on this planet are abnormally high, perhaps resembling that of the Gobi Desert in China (around -20 Fahrenheit to 90+ Fahrenheit in one day-night cycle). This would mean that at night, the desert would freeze over, but by midday, temperatures would be sweltering.
Would humans be able to live on such a planet (as a full-on civilization, not just as nomads)? I expect that humans would settle at these "oases" and begin agriculture there, but with such dramatic climate variations, would that even be feasible?
Assume for this question that this civilization has access to Renaissance-level technology, and that this planet's wildlife resembles that of Earth's.
Addendum: Due to the abundance of questions on the topic, I figure I should probably add some more details about the world as a whole.
The world is not one single, uniform biome. Although generally speaking the planet is more desert-like than Earth, the poles are, as one would expect, freezing wastelands almost year-round, while the equatorial region is essentially a scorch zone. Any reasonable group of settlers would probably find it easiest to survive right in between the two. Some regions contain more water than others, and while oceans as we know them do not exist, I'll say for the sake of the question that relatively small, saline seas pockmark the planet as well.
"Earthlike" flora and fauna is relative. Obviously you won't see penguins waddling about the surface of my planet, but creatures and plants similar to those of Earth's harshest deserts, with various adaptations to maintain homeostasis despite the environment, do exist.
A:
First some caveats/issues with the setup, some of which are mentioned in the comments. Your setting has some gaps/logical inconsistency. Though after I mention these caveats I will attempt to give you an answer specific to the point in time you lay out in your question.
Humans, as we know them likely don't evolve in this environment, humanoids of some sort may evolve, but they'd be a whole lot different.
They'd likely be thicker this is good insulation and helps with water retention
With their extra girth they'd also have tougher skin, similar to some lizards perhaps who have skin that collects water.
They'd also probably be active twice a day during the dusk/dawn hours to minimize exposure to extreme temperatures
Single biome planets don't really make sense. The variation in lat/lon any axial tilt etc, virtually guarantees that some variation will exist in your biomes. This is pretty easy though, just refrain from introducing other settings, put some big huge mountains in the way or something so that the people in the story don't realize other biomes exist.
It's going to be tough to get significant plant life let alone animal life to thrive in this environment. You are simply not going to have Earth-like creatures on a world that has totally different selection pressures than Earth. Creatures and plants that do show up will have to be different. Plants would end up as some cactus/pine tree hybrid and in reality it would probably just be scrubby and dormant most of the time. Animals would be tiny and would likely burrow to avoid the temperature fluctuations/retain water. You could in theory have wholly underground cave based biomes where temperature is moderated and water readily available.
You're going to need seasons...at least a relatively wet season to give plants a chance to grow and whatnot, this would also moderate the temperature swings (humidity is good at that) over night. So the whole year shouldn't be the same temperature wise, this goes back to the single biome conversation, worlds are big and climate is complicated. A static climate breaks suspension of disbelief for me.
Ok, on to your question. How do we make this settlement work (ignoring how we got to this point in the first place):
Humans can certainly survive in this place. A reasonable/likely setup comes to mind.
Clearly civilization will cluster around your oases. It provides water and at least some temperature normalization during the hot days/cold nights.
For dwellings your best bet would be to have underground lodgings, again this helps manage the temps. Alternatively you could create stone structures that will bake in the daytime heat and then radiate that heat throughout the cold nights. I would expect to see a lot of covered streets and shaded lanes for daytime...like with camouflage netting.
You could hypothetically harness the daytime heat to create simple steam powered generators or tools. A mill for example.
Windstorms....you're probably going to have crazy strong winds on this planet. This will impact where and how you build. Dust storms would be...messy. Buildings are going to be low and sturdy, thatch/mud huts are just not going to cut it...
Agriculture. You can't have a civilization without ag, at least not in the "lets build a permanent settlement" sense.
Water. Water seems easy enough based on your setup. Space is going to be geographically limited any decent distance from your oases and the soil will be too barren to support life. Hypothetically you could gradually expand your ag space over time by keeping land wet so microbes and little critters could survive further and further from the water sources. You're going to need canals and whatnot.
Soil. As mentioned the soil will be sterile any reasonable distance from town...so collect all your poop, you're going to need it to fertilize.
Temperature. Clearly sunlight is not a problem...actually you have so much it becomes a problem. You're going to want to tent your fields with fabric to keep everything from roasting during the day. A low tech solution comes to mind for the night though. Surround and criss-cross your fields with stone walls. Like your dwellings they will absorb heat during the day and then radiate it through the evening, that should keep the air temp from getting too cold for your plants at night. In the end it probably just makes sense to have plants that have evolved to this place so you don't have to deal with this.
Wind. As mentioned wind is going to be strong on this planet, so you are going to need walls/berms/some form of wind break to keep the winds from ripping your plants apart.
A general note. Unless these oases are fairly common and fairly close to one another, as in, a bird could make the flight in a few hours you are going to have problems with genetic diversity. Pollination and such could be a problem and depending on the population size of your humanoids you could have issues as well.
|
[
"stackoverflow",
"0021626423.txt"
] | Q:
How is barrier implemented in message passing systems?
What I understand is, that one master process sends a message to all other processes. All the other processes in return send a message to the master process. Would this be enough for a barrier to work? If not, then what more is needed?
A:
Let's have a look at OpenMPI's implementation of barrier. While other implementations may differ slightly, the general communication pattern should be identical.
First thing to note is that MPI's barrier has no setup costs: A process reaching an MPI_Barrier call will block until all other members of the group have also called MPI_Barrier. Note that MPI does not require them to reach the same call, just any call to MPI_Barrier. Hence, since the total number of nodes in the group is already known to each process, no additional state needs to be distributed for initializing the call.
Now, let's look at some code:
/*
* Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana
* University Research and Technology
* Corporation. All rights reserved.
* Copyright (c) 2004-2005 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
* Copyright (c) 2004-2005 High Performance Computing Center Stuttgart,
* University of Stuttgart. All rights reserved.
* Copyright (c) 2004-2005 The Regents of the University of California.
* All rights reserved.
* Copyright (c) 2012 Oak Ridge National Labs. All rights reserved.
* [...]
*/
[...]
/*
* barrier_intra_lin
*
* Function: - barrier using O(N) algorithm
* Accepts: - same as MPI_Barrier()
* Returns: - MPI_SUCCESS or error code
*/
int
mca_coll_basic_barrier_intra_lin(struct ompi_communicator_t *comm,
mca_coll_base_module_t *module)
{
int i;
int err;
int size = ompi_comm_size(comm);
int rank = ompi_comm_rank(comm);
First all nodes (except the one with rank 0, the root node) send a notification that they have reached the barrier to the root node:
/* All non-root send & receive zero-length message. */
if (rank > 0) {
err =
MCA_PML_CALL(send
(NULL, 0, MPI_BYTE, 0, MCA_COLL_BASE_TAG_BARRIER,
MCA_PML_BASE_SEND_STANDARD, comm));
if (MPI_SUCCESS != err) {
return err;
}
After that they block awaiting notification from the root:
err =
MCA_PML_CALL(recv
(NULL, 0, MPI_BYTE, 0, MCA_COLL_BASE_TAG_BARRIER,
comm, MPI_STATUS_IGNORE));
if (MPI_SUCCESS != err) {
return err;
}
}
The root node implements the other side of the communication. First it blocks until it received n-1 notifications (one from every node in the group, except himself, since he is inside the barrier call already):
else {
for (i = 1; i < size; ++i) {
err = MCA_PML_CALL(recv(NULL, 0, MPI_BYTE, MPI_ANY_SOURCE,
MCA_COLL_BASE_TAG_BARRIER,
comm, MPI_STATUS_IGNORE));
if (MPI_SUCCESS != err) {
return err;
}
}
Once all notifications have arrived, it sends out the messages that every node is waiting for, signalling that everyone has reached the barrier, after which it leaves the barrier call itself:
for (i = 1; i < size; ++i) {
err =
MCA_PML_CALL(send
(NULL, 0, MPI_BYTE, i,
MCA_COLL_BASE_TAG_BARRIER,
MCA_PML_BASE_SEND_STANDARD, comm));
if (MPI_SUCCESS != err) {
return err;
}
}
}
/* All done */
return MPI_SUCCESS;
}
So the communication pattern is first an n:1 from all nodes to the root and then a 1:n from the root back to all nodes. To avoid overloading the root node with requests, OpenMPI allows use of a tree-based communication pattern, but the basic idea is the same: All nodes notify the root when entering the barrier, while the root aggregates the results and inform everyone once they are ready to continue.
|
[
"stackoverflow",
"0042927339.txt"
] | Q:
How to reliably refer to static file in a Go application?
I am writing a Go command-line tool that generates some files based on templates.
The templates are located in the Git repository alongside the code for the command-line tool itself.
I wanted to allow the following:
The binary, wherever it is called from, should always find the templates directory.
The templates directory can be overriden by the user if need be.
Since this is a Go application, I went with something like:
templateRoot := filepath.Join(
os.Getenv("GOPATH"),
"src/github.com/myuser/myproject/templates",
)
But being rather new to Go, I wonder if this approach is reliable enough: is it guaranteed that my application template will always be accessible at that path ?
What if someone vendorize my application into their own project ? Does that even make sense for a command-line tool ?
Because of 2., I obviously can't/won't use go-bindata because I want to allow for the templates to be overriden if need be.
In summary: what is a good strategy to reliably refer to non-go, static files in a Go command-line tool ?
A:
GOPATH is used for building the application. While you could look for GOPATH and check relative locations to each GOPATH entry at runtime, you can't be sure it will exist (unless of course you make it a prerequisite for running your application).
go get itself is a convenience for developers to fetch and build a go package. It relies on having a GOPATH (though there's a default now in go1.8), and GOBIN in your PATH. Many programs require extra steps not covered by the simple go tool, and have scripts or Makefiles to do the build. If you're targeting users that aren't developers, you need to provide a way to install into standard system paths anyway.
Do what any regular program would do, and use some well-known path to locate the template files. You can certainly add some logic in your program to check for a hierarchy of locations: relative to $GOPATH, relative to the binary, working directory, $HOME, etc; just provide a list of locations to the user that your program will look for templates.
|
[
"stackoverflow",
"0018357529.txt"
] | Q:
ThreeJS: Remove object from scene
I'm using ThreeJS to develop a web application that displays a list of entities, each with corresponding "View" and "Hide" button; e.g. entityName View Hide. When user clicks View button, following function is called and entity drawn on screen successfully.
function loadOBJFile(objFile){
/* material of OBJ model */
var OBJMaterial = new THREE.MeshPhongMaterial({color: 0x8888ff});
var loader = new THREE.OBJLoader();
loader.load(objFile, function (object){
object.traverse (function (child){
if (child instanceof THREE.Mesh) {
child.material = OBJMaterial;
}
});
object.position.y = 0.1;
scene.add(object);
});
}
function addEntity(object) {
loadOBJFile(object.name);
}
And on clicking Hide button, following function is called:
function removeEntity(object){
scene.remove(object.name);
}
The problem is, entity is not removed from screen once loaded when Hide button is clicked. What can I do to make Hide button to work?
I did small experiment. I added scene.remove(object.name); right after scene.add(object); within addEntity function and as result, when "View" button clicked, no entity drawn (as expected) meaning that scene.remove(object.name); worked just fine within addEntity. But still I'm unable to figure out how to use it in removeEntity(object).
Also, I checked contents of scene.children and it shows: [object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Complete code: http://devplace.in/~harman/model_display1.php.html
Please ask, if more detail is needed. I tested with rev-59-dev and rev-60 of ThreeJS.
Thanks. :)
A:
I think seeing your usage for addEntity and removeEntity code would be helpful, but my first thought is are you actually setting the object.name? Try in your loader just before scene.add(object); something like this:
object.name = "test_name";
scene.add(object);
What might be happening is the default "name" for an Object3D is "", so when you then call your removeEntity function it fails due to the scene objects name being ""
Also, I notice you pass in object.name to your loader? Is this where your storing the URL to the resource? If so, I would recommend using the Object3D's built in .userData method to store that information and keep the name field for scene identification purposes.
Edit: Response to newly added Code
First thing to note is it's not a great idea to have "/" in your object name, it seems to work fine but you never know if some algorithm will decide to escape that string and break your project.
Second item is now that I've seen your code, its actually straight forward whats going on. Your delete function is trying to delete by name, you need an Object3D to delete. Try this:
function removeEntity(object) {
var selectedObject = scene.getObjectByName(object.name);
scene.remove( selectedObject );
animate();
}
Here you see I lookup your Object3D in the Three.js Scene by passing in your object tag's name attribute. Hope that helps
A:
clearScene: function() {
var objsToRemove = _.rest(scene.children, 1);
_.each(objsToRemove, function( object ) {
scene.remove(object);
});
},
this uses undescore.js to iterrate over all children (except the first) in a scene (it's part of code I use to clear a scene). just make sure you render the scene at least once after deleting, because otherwise the canvas does not change! There is no need for a "special" obj flag or anything like this.
Also you don't delete the object by name, just by the object itself, so calling
scene.remove(object);
instead of scene.remove(object.name);
can be enough
PS: _.each is a function of underscore.js
A:
THIS WORKS GREAT - I tested it
so, please SET NAME for every object
give the name to the object upon creation
mesh.name = 'nameMeshObject';
and use this if you have to delete an object
delete3DOBJ('nameMeshObject');
function delete3DOBJ(objName){
var selectedObject = scene.getObjectByName(objName);
scene.remove( selectedObject );
animate();
}
open a new scene , add object
delete an object and create new
|
[
"dba.stackexchange",
"0000039409.txt"
] | Q:
How to enforce full integer (no floating point)?
Why is the following allowed
INSERT INTO c VALUES (123.2,'abcdefghijklmnopqrstuvwxyzabcdef', 'abcdefghijklmnop');
When table contains
CustomerID NUMBER(3,0) -- That's the 123.2 entry
In other words, total of 3 digits with 0 after floating point?
If number is not a way to go, how would you enforce full integer only (no floating point)
A:
When you define a column as number(m,n) where m is larger than n and n is positive, the values you can store in it can have m-n digits to the left from period and n digits to the right after period. For example when you defined your column as number(5,3), these are valid values: 1,234, 12,345. If you attempt to insert a value with a precision higher than n, it is automatically rounded, for example 1,2345 is rounded to 1,235.
When you define a column as number(m,0) you can have m digits to the left before the decimal point, and the numbers you insert are automatically rounded.
When you define a column as number(m,n) where n is larger than m, the values you can store in it can have zero digits to the left from the period and n digits to the right from the period with n-m zeros right after the decimal point. For example, if you defined your column as number(3,5), you can have values like 0.00123 in it, but not 0.01200. If you insert the value with more than n digits like 0.001235 it's automatically rounded to 0.00124.
When you define a column as number(m,n) where n is negative then it can store m-n digits to the left from decimal point, there should be exactly abs(n) zeros to the left from the decimal point, and the number is rounded to the last abs(n) places. For example, if you defined your column as number(3,-1), you can store numbers with 3 - -1 = 4 digits before decimal point which should have zeros in the last abs(n)=1 places. You can have values like 280, 1230, and if you isert values with digits other than zero in the last abs(n) places, the numbers are automatically rounded, for example 536 will eventually be stored as 540, 1245 will be stored as 1250.
|
[
"mathematica.stackexchange",
"0000176906.txt"
] | Q:
Cosine similarity calculation
I am interested in calculating the cosine distance between each pair of the element of a sparse matrix. I am using the built-in function DistanceMatrix with the option CosineDistance.
My data is a sparse matrix sp with dimension ~{30000,6} and number of non zero vectors in sp is ~3000. I calculate the distance matrix in the following manner:
sp = SparseArray[
Table[{RandomInteger[{1, 30000}], RandomInteger[{1, 6}]} ->
RandomReal[1], {3000}]]
DistanceMatrix[sp,
DistanceFunction -> CosineDistance]; // AbsoluteTiming
The calculation does not converge, any suggestion why the calculation does not converge.
I have a list of sparse matrices, and for each one of them, I want to calculate the cosine distance. I calculate the distance matrix with @Henrik solution.
When I run the code outside Module (or Table as in the following example), I get the distance matrix with right dimensions, but when I run it inside Module, I get wrong dimensions of the distance matrix.
SeedRandom[123];
sp = matrices[[1]];
ilist = Flatten[
SparseArray[Unitize[Total[Abs[sp], {2}]]]["NonzeroPositions"]];
B = SparseArray[{}, {1, 1} Length[sp], 0.];
B[[ilist, ilist]] =
SparseArray@
DistanceMatrix[sp[[ilist]],
DistanceFunction -> CosineDistance]; // AbsoluteTiming // First
Table[
sp = matrices[[i]];
ilist = Flatten[
SparseArray[Unitize[Total[Abs[sp], {2}]]]["NonzeroPositions"]];
BB = SparseArray[{}, {1, 1} Length[sp], 0.];
BB[[ilist, ilist]] =
SparseArray@
DistanceMatrix[sp[[ilist]],
DistanceFunction -> CosineDistance], {i, 1}]
A:
You can try the following. It computes the distance matrix of merely the nonzero rows.
SeedRandom[123];
sp = SparseArray[ Table[{RandomInteger[{1, 30000}], RandomInteger[{1, 6}]} -> RandomReal[1], {3000}]];
ilist = Flatten[SparseArray[Unitize[Total[Abs[sp], {2}]]]["NonzeroPositions"]];
A = SparseArray[{}, {1, 1} Length[sp], 0.];
A[[ilist, ilist]] = SparseArray@DistanceMatrix[
sp[[ilist]],
DistanceFunction -> CosineDistance
]; // AbsoluteTiming // First
0.384662
|
[
"stackoverflow",
"0021643740.txt"
] | Q:
Head tags are appearing inside body
I have a simple web page, and a title, meta, etc in my page. But when I debug it with Firebug, Chrome and Firefox's default debugger, all my tags inside the head show up in the body.
This is all my code of index.html
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width"/>
<link href="style.css" rel="stylesheet" />
</head>
<body>
<canvas id="game"></canvas>
<div id="mainmenu">
<div id="title"></div>
<a href="#" id="play" onclick="play()"></a>
<!--<div id="ground"></div>-->
</div>
<script src="game.js"></script>
</body>
</html>
When I check the code in the debugger, all the elements inside the head tag are moved outside the head tag
(sorry for my bad English)
A:
I fixed it by complete rewriting it, this is the update code:
<!DOCTYPE html>
<html>
<head>
<title>Flappy Bird</title><!-- yep, a flappy bird clone ;)-->
<meta name="viewport" content="width=device-width"/>
<link href="style.css" rel="stylesheet" />
</head>
<body>
<!-- Het spel -->
<canvas id="game"></canvas>
<!-- Menu -->
<div id="mainmenu">
<div id="title"></div>
<a href="#" id="play" onclick="play()"></a>
<div id="ground"></div>
<!-- Het script voor de game-->
<script src="game.js"></script>
</div>
</body>
</html>
I really don't understand what's wrong with the previous code
EDIT: A code editor placed invisible characters inside my code. The characters messed up the rendering I think.
|
[
"stackoverflow",
"0041949895.txt"
] | Q:
How to set timeout on before hook in mocha?
I want to set timeout value on before hook in mocha test cases. I know I can do that by adding -t 10000 on the command line of mocha but this will change every test cases timeout value. I want to find a way to change the timeout programmatically below is my code:
describe('test ', () => {
before((done) => {
this.timeout(10000);
...
it will complain about the line this.timeout(1000) that timeout is not defined. How to set the timeout on before hook.
A:
You need to set a timeout in your describe block rather than in the hook if you want it to affect all the tests in the describe. However, you need to use a "regular" function as the callback to describe rather than an arrow function:
describe('test', function () {
this.timeout(10000);
before(...);
it(...);
});
In all places where you want to use this in a callback you pass to Mocha you cannot use an arrow function. You must use a "regular" function which has its own this value that can be set by Mocha. If you use an arrow function, the value of this won't be what Mocha wants it to be and your code will fail.
You could set a different timeout for your before hook but there are two things to consider:
Here too you'd need to use a "regular" function rather than an arrow function so:
before(function (done) {
this.timeout(10000);
This would set a timeout only for the before hook and would not affect your tests.
A:
You can also call timeout() on the return value from describe, like this:
describe('test', () => {
before(...);
it(...);
}).timeout(10000);
With this approach you can use arrow functions, because you're no longer relying on this.
A:
as instructed at https://mochajs.org/#hook-level, you have to use a regular function call to set the timeout.
before(function(done) {
this.timeout(3000); // A very long environment setup.
setTimeout(done, 2500);
});
if you insist on use arrow or async function in the hook. You may do it this way:
before(function (done) {
this.timeout(3000);
(async () => {
await initilizeWithPromise();
})().then(done);
});
It is quite helpful and nice-looking if you got multiple async calls to be resolved in the hook.
updated: fuction def works well with async too. So this hook can be upgraded to
before(async function () {
this.timeout(3000);
await initilizeWithPromise();
});
So it provides benefits from both this and await.
By the way, mocha works pretty fine with promises nowadays. If timeout is not a concern. Just do this:
before(async () => {
await initilizeWithPromise();
});
|
[
"stackoverflow",
"0055506272.txt"
] | Q:
Datetime format for series - Highcharts
I need to implement this https://www.highcharts.com/demo/line-time-series, but that needs data like these https://cdn.jsdelivr.net/gh/highcharts/[email protected]/samples/data/usdeur.json, 1167868800000 is a datetime date format but I do not know how to pass my datatime to this format
I need to convert this date 2019-04-02 21:35:04 -0600 to this 1167868800000
How could I solve this? I'm working on ruby on rails
A:
You can use momentjs to convert your date to epoch time.
Here is a sample.
var ADBE = [
['2019-04-02 21:35:04',23.17],
['2019-04-02 22:35:04',23.78],
['2019-04-02 23:35:04',24.10],
['2019-04-03 20:35:04',23.86],
['2019-04-03 21:35:04',24.54]
];
ADBE = ADBE.map(function(data) { return [moment(data[0], "YYYY-MM-DD HH:mm:ss").valueOf(), data[1]]});
Highcharts.stockChart('container', {
rangeSelector: {
selected: 1
},
legend: {
enabled: true,
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
y: 100
},
series: [{
name: 'ADBE',
data: ADBE
}]
});
<div id="container" style="height: 400px; min-width: 600px"></div>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script type="text/javascript" src="https://www.highcharts.com/samples/data/three-series-1000-points.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
|
[
"stackoverflow",
"0004846894.txt"
] | Q:
NullPointerException On a Calling a Function
I'm building a program that gets the value of a TextField, concatenate with some other Strings and then display them on a TextBox when the ScreenCommand is clicked, the problem is that it's calling a NullPointerException. My code is like this(of course it has a lot more stuff):
/* .... */
} else if (command == submitCommand) {
FirstPart();
// write pre-action user code here
switchDisplayable(null, getTextBox3());
// write post-action user code here
}
/* .... */
public void FirstPart() {
String test = null;
test = "tst" + textField.getString() + "test";
textBox3.setString(test);
}
/* .... */
And I get this when I click the menu:
TRACE: <at java.lang.NullPointerException: 0>, Exception caught in Display class
java.lang.NullPointerException: 0
at mp.releaser.MPReleaser.FirstPart(MPReleaser.java:535)
at mp.releaser.MPReleaser.commandAction(MPReleaser.java:128)
at javax.microedition.lcdui.Display$ChameleonTunnel.callScreenListener(), bci=46
at com.sun.midp.chameleon.layers.SoftButtonLayer.processCommand(), bci=74
at com.sun.midp.chameleon.layers.SoftButtonLayer.commandSelected(), bci=11
at com.sun.midp.chameleon.layers.MenuLayer.pointerInput(), bci=188
at com.sun.midp.chameleon.CWindow.pointerInput(), bci=88
at javax.microedition.lcdui.Display$DisplayEventConsumerImpl.handlePointerEvent(), bci=19
at com.sun.midp.lcdui.DisplayEventListener.process(), bci=296
at com.sun.midp.events.EventQueue.run(), bci=179
at java.lang.Thread.run(Thread.java:680)
What should I do to correct this?
PS: Netbeans should have a NullPointerException corrector tool :P
A:
Looking at the FirstPart method, the only thing I can imagine is that textField is null or textBox3 is null. Are you sure it isn't null?
If I'm completely missing the point of your question, I apologize.
EDIT: Thank you, StriplingWarrior!
|
[
"stackoverflow",
"0003650320.txt"
] | Q:
Convert bigint to datetime
I want to convert a value from bigint to datetime.
For example, I'm reading the HISTORY table of teamcity server. On the field build_start_time_server, I have this value on one record 1283174502729.
How can I convert it to a datetime value?
A:
Does this work for you? It returns 30-8-2010 13:21:42 at the moment on SQL Server 2005:
select dateadd(s, convert(bigint, 1283174502729) / 1000, convert(datetime, '1-1-1970 00:00:00'))
I've divided by 1000 because the dateadd function won't work with a number that large. So you do lose a little precision, but it is much simpler to use.
A:
Slightly different approach:
Your scenario:
SELECT dateadd(ms, 1283174502729 / 86400000, (1283174502729 / 86400000) + 25567)
FROM yourtable
Generic code:
SELECT dateadd(ms, yourfield / 86400000, (yourfield / 86400000) + 25567)
FROM yourtable
Output:
August, 30 2010 00:00:14
SQL Fiddle: http://sqlfiddle.com/#!3/c9eb5a/2/0
A:
CAST(SWITCHOFFSET(CAST(dateadd(s, convert(bigint, [t_stamp]) / 1000, convert(datetime, '1-1-1970 00:00:00')) AS DATETIMEOFFSET), DATENAME (TZoffset, SYSDATETIMEOFFSET())) AS DATETIME)
|
[
"stackoverflow",
"0041236504.txt"
] | Q:
How can I add ImageJ to my build path in Eclipse, and where can I find the ImageJ .jar file?
I am extremely novice when it comes to using external libraries in my code. I have been looking for an embarrassing amount of time on how to actually add this particular library to my build path.
My main issue is that I cannot find the .jar file, or I don't know how to go from a cloned git repository to a jar file.
Any help would be immensely appreciated.
If it makes a difference, I am interested this Non Local Means Denoise Class, along with a few others.
A:
If you have the source code for that project, you can build it yourself (if, for instance, you're using maven just do "mvn install" and then look in the "target" directory for the jar).
Regardless of how you get the jar, once you have it you can add it to the project in Eclipse by right-clicking on the project, going to "build path"... "configure build path" and then adding it as a library.
|
[
"stackoverflow",
"0056702762.txt"
] | Q:
Removing duplicate entries from database Laravel
I've read a few "solutions" on stack overflow but none really definitely answer the question.
How do I remove duplicate data based on a few fields from the database but keeping one entry.
For example I have stored in my Database:
[
['id' => 1, 'name' => 'Spend', 'amount' => 10.55],
['id' => 2, 'name' => 'Spend', 'amount' => 10.52],
['id' => 3, 'name' => 'Spend', 'amount' => 10.55],
]
and the end result id want is:
[
['id' => 1, 'name' => 'Spend', 'amount' => 10.52],
['id' => 2, 'name' => 'Spend', 'amount' => 10.55],
]
Im not too sure how to do this because i need to check for duplicates with the same name AND amount fields, then delete all but 1.
Any help is appreciated.
A:
One approach to do this Like using DB::delete() running raw query.
$affectedRow = DB::delete('DELETE t1 FROM table t1, table t2 WHERE t1.id > t2.id AND t1.name = t2.name AND t1.amount = t2.amount');
change table with your actual table name.
It return the no of rows deleted.
Another Solution: Not tested!
Here you can add your other custom queries as well!
// find the duplicate ids first.
$duplicateIds = DB::table("table")
->selectRaw("min(id) as id")
->groupBy("amount", "name")
->havingRaw('count(id) > ?', [1])
->pluck("id");
// Now delete and exclude those min ids.
DB::table("table")
->whereNotIn("id", $duplicateIds)
->havingRaw('count(id) > ?', [1])
->delete();
|
[
"stackoverflow",
"0050609082.txt"
] | Q:
How to use Yelp api v3 in swift
So long story short I want to be able to get reviews, images, etc. about locations and add them to a map. Using Yelp's api v3 seemed to be the best way to do this but i'm having trouble finding decent/updated/working documentation.
I looked here:
https://github.com/codepath/ios_yelp_swift/tree/master/Yelp
but it is outdated(both version of api and swift)
I did manage to find this updated doc. on v3:
https://github.com/Yelp/yelp-fusion/tree/master/fusion/swift
but the code doesn't work.
I also looked through just about ever question/thread on here about yelp's api but most question are outdated or never answered.
But from my understanding of looking through other questions, in order to use the api I have to create a HTTP GET request, change authorization, and decode the data with the url: https://api.yelp.com/v3 (but with my desired terms and such) but the documentation yelp provides doesn't include any of that?
My question is, can anyone provide a full example (or link) of using the v3 api in swift properly or provide some clarity about how to use it?
Any help would be appreciated
A:
It took a bit of hacking around to get it.
fileprivate func fetchYelpBusinesses(latitude: Double, longitude: Double) {
let apikey = "YourAPIKey"
let url = URL(string: "https://api.yelp.com/v3/businesses/search?latitude=\(latitude)&longitude=\(longitude)")
var request = URLRequest(url: url!)
request.setValue("Bearer \(apikey)", forHTTPHeaderField: "Authorization")
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request) { (data, response, error) in
if let err = error {
print(err.localizedDescription)
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
print(">>>>>", json, #line, "<<<<<<<<<")
} catch {
print("caught")
}
}.resume()
}
|
[
"stackoverflow",
"0022223708.txt"
] | Q:
Putting the image behind the background
I have a simple html, but I'm not sure if what I want to do (the way I want to do it) is possible..
<div class="container">
<img src="..." />
</div>
.container has some sort of gradient background, in this case a common black bottom for text
background: -webkit-linear-gradient(top, rgba(255, 255, 255, 0) 65%, rgba(47, 39, 39, 0.7));
this is simulated in http://jsfiddle.net/9WQL6/
I want the dark bottom to be in front of the picture, not behind it.
I can't use a background-image for the image because the css is precompiled.
Is this possible?
A:
Another way to go is with a pseudo-element (IE8+)
JSfiddle Demo
CSS
.container{
max-width: 200px;
border: 1px solid black;
position: relative;
}
.container img{
max-width: 200px;
}
.container:after {
position: absolute;
content:" ";
top:0;
left:0;
height:100%;
width:100%;
background: -webkit-gradient(top, from(rgba(255, 255, 255, 0)), color-stop(0.65, rgba(255, 255, 255, 0.7)), color-stop(1, rgba(47, 39, 39, 0.5)));
background: -webkit-linear-gradient(top, rgba(255, 255, 255, 0) 65%, rgba(47, 39, 39, 0.7));
background: -moz-linear-gradient(top, rgba(255, 255, 255, 0) 65%, rgba(47, 39, 39, 0.7));
background: -ms-linear-gradient(top, rgba(255, 255, 255, 0) 65%, rgba(47, 39, 39, 0.7));
background: -o-linear-gradient(top, rgba(255, 255, 255, 0) 65%, rgba(47, 39, 39, 0.7));
background: linear-gradient(top, rgba(255, 255, 255, 0) 65%, rgba(47, 39, 39, 0.7));
}
|
[
"stackoverflow",
"0039789990.txt"
] | Q:
Pandas dataframe comparison hangs without error message
This is my first pandas attempt, so I was wondering what is the problem. I am trying to compare two dataframe of about 30.000 rows each. My first intuition led me to iterate both dataframes, so for every entry in the df1, we iterate all the rows in the df2 to see if it´s there.
Maybe is not necessary at all and there are easier alternatives. Here is what I did. The problem is, it simply hangs without outputting any error message, but I cannot identify what is making it hang...
import pandas as pd
dfOld = pd.read_excel("oldfile.xlsx", header=0)
dfNew = pd.read_excel("newfile.xlsx", header=0)
columns = ["NAME","ADDRESS","STATUS","DATE"]
result = pd.DataFrame(columns=columns)
for index, rowOld in dfOld.iterrows():
for index, rowNew in dfNew.iterrows():
if rowOld.all() != rowNew.all():
result.loc[len(result)] = rowOld.all()
writer = pd.ExcelWriter('Deletions.xlsx', engine='xlsxwriter')
result.to_excel(writer, sheet_name='Deleted')
writer.save()
Sample data for each dataframe:
$1 & UP STORE CORP.142A | N FRANKLIN ST | 409 408 | 31/07/2014
$1 store | 110 n martin ave | 408 | 07/01/2015
0713, LLC | 1412 N. County Road West | 405 408 413 | 16/07/2015
1 2 3 MONEY EXCHANGE LLC | 588 N MAIN ST | 405 409 408 | 22/05/2015
$1 store premium | 110 n martin ave | 408 | 07/01/2015
0713, LLC | 1412 N. County Road West | 405 408 413 | 16/07/2015
1 2 3 MONEY EXCHANGE LLC | 588 N MAIN ST | 405 409 408 | 22/05/2015
1145 Parsons Inc | 1145 Parsons Ave | 405 408 | 19/11/2013
The desired output is that the dataframe results gets populated with the rows from dfOld that do not exist in dfNew. So, the new results dataframe would be comprised of:
$1 & UP STORE CORP.142A | N FRANKLIN ST | 409 408 | 31/07/2014
$1 store | 110 n martin ave | 408 | 07/01/2015
The problem is that it doesn't work with a large amount (30.000 entries per dataframe), so even if it can work with a smaller sample, I wonder if this is the way to proceed with that many entries.
A:
You can use merge with parameter indicator=True and then filter by boolean indexing:
df = pd.merge(dfOld, dfNew, how='outer', indicator=True)
print (df)
NAME ADDRESS STATUS \
0 $1 & UP STORE CORP.142A N FRANKLIN ST 409 408
1 $1 store 110 n martin ave 408
2 0713, LLC 1412 N. County Road West 405 408 413
3 1 2 3 MONEY EXCHANGE LLC 588 N MAIN ST 405 409 408
4 $1 store premium 110 n martin ave 408
5 1145 Parsons Inc 1145 Parsons Ave 405 408
DATE _merge
0 31/07/2014 left_only
1 07/01/2015 left_only
2 16/07/2015 both
3 22/05/2015 both
4 07/01/2015 right_only
5 19/11/2013 right_only
print (df[df._merge == 'left_only'])
NAME ADDRESS STATUS DATE _merge
0 $1 & UP STORE CORP.142A N FRANKLIN ST 409 408 31/07/2014 left_only
1 $1 store 110 n martin ave 408 07/01/2015 left_only
Last delete helper column _merge:
print (df[df._merge == 'left_only'].drop('_merge', axis=1))
NAME ADDRESS STATUS DATE
0 $1 & UP STORE CORP.142A N FRANKLIN ST 409 408 31/07/2014
1 $1 store 110 n martin ave 408 07/01/2015
|
[
"stackoverflow",
"0050798192.txt"
] | Q:
Spark Java java.lang.NoClassDefFoundError in using classes in artifacte jar
I have created some classes in my maven project and I created a jar file using IntelliJ IDEA artifact. Here is the structure of project:
+ProjectName:
----src
-----main
------java
------A.B (packages)
--------DB
BP
SP
In creating a jar file I just included class BP.
Importing the jar file in a new project and run the following simple code in the main function:
import A.B.BP;
public class Test {
public static void main(String[] args) throws Exception {
BP temp = new BP("Test");
}
}
It build without error but I got the following error at the runtime:
Exception in thread "main" java.lang.NoClassDefFoundError: A/B/BP
at Test.main(Test.java:8)
Caused by: java.lang.ClassNotFoundException: A.B.BP
I seemed the classes are not available in the classpath at the runtime.
Point I did the same for the classes SP and DFS. I create a jar file and imported into a new project, it ran without any error!
Here is my maven pom.xml file:
<dependency>
<groupId>com.datastax.spark</groupId>
<artifactId>spark-cassandra-connector_2.11</artifactId>
<version>2.0.8</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.11</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
<scope>provided</scope>
</dependency>
I commented dependencies of other classes.
How can I solve the problem?
A:
It was because of lack of needed dependencies in runtime. The story was, I added spark-sql dependency in my current Maven project's pom.xml file. It implicitly needed some other spark dependencies like spark-catalyst and will get them automatically from Maven reps. So When I run my Spark-SQL code in the current project, it worked. When I built my classes as an artifact jar and tried to use them in another new project, in exported jar file it just contains spark-sql dependency, not other nested dependencies like spark-catalyst! In the compile time Java just checked the first level of dependencies and it saw spark-sql is provided and my code compiled successfully. But in the runtime in addition to first level dependencies, Java needed nested dependencies like spark-catalyst and they were not provided! so it caused the error! I imported those nested dependencies to the test project in addition to the fat jar and it solved the error!
|
[
"stackoverflow",
"0046918553.txt"
] | Q:
How can I attempt to load a script from a CDN and fall back to a mirror?
I am in the process of setting up a simple web app on an ESP8266. And it works like a charm. For the UI I am using Bootstrap, which is a quite large framework. This means that it is a bit slow when serving the css file, as the storage is not that fast.
Is there a way I can on the html-page (with or without JavaScript), first try to fetch bootstrap from CDN, and if we don't have network access, fetch the mirror on the ESP?
I have no clue where to start with this. I also think it would be hard to do this using JavaScript as this will be done after the DOM is ready. So adding a stylesheet after loading, which won't work?
Do anyone have any suggestions on how to do this?
A:
Use a https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest to request the css file. If it can't be loaded, reload the page to a new one that doesn't use any external resources.
Edited to add an explanation:
First, there is no trivial way to detect if a link element has finished loading a css file or if it failed. So, the easiest way for your case is to do as I mentioned, you do the XHR, if the file successfully loads, then you have network access, else you don't. There is no problem in loading 2 times, one from the XHR and other from the link tag, because, if your script loads it first, then it will be cached for the link tag, and if the link tag loads it first, then it will be cached for the XHR. So all good.
After this, if it failed to load, you would want to load it from a different location. Dynamically loading css is possible, but I thought that the simplest solution would be to just load a different page. This way, even if in the future you add more resources, more css files or some external libraries, you will always have the 2 versions of the page, the local and the network one, and no changes to do to the network not available system.
|
[
"stackoverflow",
"0024066877.txt"
] | Q:
Adding a Next and Previous button that reset the timer on a Jquery image slider
I've been working on this slider for a bit, and I've got it to auto play with some nice simple Jquery markup. I decided I wanted to have the option to go to previous and next on the slider, but I'm not sure if it's possible with the set up I have. I've got a "Next" Button set up that moves to the next image. My problem lies in getting the timer to restart after you hit next in the code. Is this possible to do, am I just overlooking something? I also am wondering how to I create the equivalent of the "next" button for a "previous" button. Any help would be appreciated, since I've been banging my head against this one for while.
Here is the Jquery I'm using:
var time = 6000;
function play() {
setInterval(function(){
var next = $(".slideshow .active").removeClass("active").next(".image");
if (!next.length) {
next = $(".slideshow .image:first");
}
next.addClass("active");
}, time);
}
play();
/*Start of function for next button */
function forward() {
$('.forward').click(function() {
var go = $(".slideshow .active").removeClass("active").next(".image").addClass("active");
if (!go.length) {
go = $(".slideshow .image:first");
}
go.addClass("active");
});
}
forward();
I've created a CodePen(http://codepen.io/Develonaut/pen/lLmkc) to try and work this out. I will gladly give credit on the CodePen for whoever helps. Thanks so much!
A:
Check out clearInterval.
You need to set the return value of your setInterval to a variable, then pass that variable to clearInterval to reset your timer. Do that on each press of your previous/next buttons, then call the play function again to start the timer from the beginning.
Here's an updated version of your CodePen example.
|
[
"stackoverflow",
"0056265265.txt"
] | Q:
could not fetching rows content for more then 1000 rows on Azure Table
i'm trying to catch content on rows more than 1000.
So i have tried to append each content on list to be able to use it then.
coding:utf-8
import os
import json
from azure import *
from azure.storage import *
from azure.storage.table import TableService, Entity
import datetime
def Retrives_datas():
twenty_hours_before_now = datetime.datetime.now() - datetime.timedelta(days=1)
now = twenty_hours_before_now.isoformat()
filter = "Timestamp gt datetime'" + now + "'"
maker = None
i=0
table_service = TableService(account_name='MyAccount', sas_token='MySAS')
while True:
tasks = table_service.query_entities('MyTable', filter = filter, timeout=None, num_results=1000, marker=maker)
for task in tasks:
i += 1
print(i,tasks.items[i]['Status'])
if tasks.next_marker != {}:
maker = tasks.next_marker
else:
break
i get the below error :
999 Success
Traceback (most recent call last):
print(i,tasks.items[i]['Status']) IndexError: list index out of range
knowing that i when i replace
print(i,tasks.items[i]['Status'])
by
print(i)
I get more than 2770 rows.
A:
The common error list index out of range because that you want to access the list[1000] even though it only has 1000 items(you set num_results=1000 ). You could only access list[999] because the index starts with 0.
Just move down i += 1 line.
for task in tasks:
print(i,tasks.items[i]['Status'])
i += 1
My sample data:
Output:
For summary, the length of the tasks.item takes the size of the next list that will be returned instead incrementation.
Solution: Added if i == <num_results>: i = 0
|
[
"stackoverflow",
"0062767358.txt"
] | Q:
SQL group by count unique values into separate columns
I have two columns, a and b, and both have categorical values. Say the database looks like this,
a b
a1 b1
a2 b2
a3 b1
......
I want to group by a and count unique values of b into separate columns, for example,
Value b1 b2 b3
a1 5 10 3
a2 4 6 7
....
I tried SELECT a, b, count(b) FROM table GROUP BY a, b and got something similar like this:
a1 b1 5
a1 b2 10
....
What's the SQL query to produce the desired output? Thanks.
A:
Below is for BigQuery Standard SQL
SELECT
a,
COUNTIF(b = 'b1') AS b1,
COUNTIF(b = 'b2') AS b2,
COUNTIF(b = 'b3') AS b3
FROM t
GROUP BY a
-- ORDER BY a
|
[
"stackoverflow",
"0008792556.txt"
] | Q:
SQL UPDATE and SET with float numbers
I have a field radius in my database of the type float and of value 0.0.
Through a PHP sript I change it's value to the content of d2, with this statement, to 32.422:
$res=mysql_query("UPDATE `astros` SET `radius` = `radius` + ".$d2." WHERE `index` = '".$index."'");
If later I use another PHP script to reduce the value of the radius in the same amount:
$res=mysql_query("UPDATE `astros` SET `radius` = `radius` - ".$d2." WHERE `index` = '".$index."'");
the final value isn't 0, like it should be, but 1.4988E-9... almost zero.
Can anyone tell me what am I doing wrong?
Thanks,
Direz
A:
There is nothing wrong, you are just seing the limitation of the floating point numbers.
What you think is the exact value 32.422 isn't so. When converted from the textual representation in the query into a floating point number used by the database, it becomes the closest number that is possible to represent using that data type. It could be something like 32.421999995662, very close to 32.422 but not exactly.
Each floating point value may contain such a deviation from the value that you intended, and when you do calculations with them the deviations add up, and after a while you see the difference.
Normally the small differences isn't visible, as the numbers are rounded to a reasonable number of digits when you display them. If you for example subtracted 31.422 in the second query, you would end up with something that is very close to 1, for example 1.00000000014988, which would be rounded to 1.000000000 when you display it. As you are getting a value close to zero, there is no value substantially larger than the deviation that it could round to, so you see only the deviation.
|
[
"english.meta.stackexchange",
"0000013247.txt"
] | Q:
Vote to close! I will delete the question right away, I'm sorry. Please, can someone tell me what not to do next time?
My question. I followed the requirements, I thought. Thanks for any help. I guess I should wait a while before I delete it, so someone can look at it. Cheers
A:
Do not worry so much about it next time. If you did anything so bad as to merit outright deletion of the question and profuse apologies, then it probably would have been flagged by the user and deleted for you for some major rules violation such as spam, rudeness or plagiarism. Also, keep in mind that if you want to delete a question, that you usually only have the option to do so before people start answering it, because de-publishing their answers on another person's whim usually is not fair.
Voting to close a question is different. Most of the time when people are voting to close it is for a minor infraction that is held against the question, rather than the questioner, and what we aim to do is to have any outstanding issues with the question fixed so that we can appropriately address it. You can read The War of the Closes for some information regarding the purpose of closure and what we hope for it to achieve. These sorts of minor infractions are only something that might be held against you if you showed a regular pattern of such infractions.
You should also note that Stack Exchange is not quite like other websites. Enforcement of the rules is typically a responsibility which is communally shared by people who have earned enough reputation points to have the requisite privileges. This can lead to some rather inconsistent enforcement in practice:
Some questions that should be closed remain open, and more relevantly some questions which should be open get closed, in which case there is an appeals proceedure. One vote to close is not indicative that you have actually violated any policies. The person who voted to close your question is not a formal moderator, or else the question would have been closed immediately rather than being left open for further peer review.
Indeed, the one vote to close you got so far was labeled as "unclear what you are asking", and because you were observant of the Single Word Request requirement all that really means is that you have managed to confuse somebody regarding the nature of your problem. That could mean your post is genuinely confusing and should not be addressed until it is understandable, or it could mean that the voter lacks the cognitive skills to comprehend your post, which would not be your fault in any case.
I am not going to cast judgement one way or the other on that, but if it is your error, rather than the voter's, then you might want to see if there is anything you can do to make the post easier for other people to understand. It looks like you have already tried though, so there is not much to do other than wait and see if other posters agree with the closure rationale, or observe if the question has other defects which may merit a closure vote.
If the question is closed, you will get a message informing you as to what is wrong with the question and what you might try to do to get it reopened. You can also ask for advice regarding closed questions here on meta, as you seem to be aware.
You tried to do everything right from the onset though, so it should probably be fine.
|
[
"stackoverflow",
"0050534147.txt"
] | Q:
How do I push value into Angular defined variable from PHP?
I am writing an Angular 4 application, and I am getting back some JSON based upon an id value to a PHP script. I would think that with my code, I have a value being passed into this.PropertiesList below:
examineProperties(id) {
let currentTestIDToFindProperties = this.testScheduleSet[id];
this.allProperty = this.httpClient.get(this.currentTestIDToFindPropertiesUrl + "?testID=" + currentTestIDToFindProperties.value).subscribe((data: any) => {
this.testPropertiesList = data;
console.log("List",this.testPropertiesList);
});
console.log("List After Loop",this.testPropertiesList);
}
I'm not exactly certain why, but I am getting a response where the console.log for "List After Loop" shows up before the "List" console.log, and shows up as undefined, as follows:
How do you have this.testPropertiesList persist outside of the subscribe function? Why is it that the "List After Loop" is showing up in the console before "List"?
A:
You are working with async programming you cannot pause the execution of the code and your subscription will be resolved in future but you cannot predict when. console.log() outside the subscribe is executed before your subscription is resolved that's why it's undefined and console.log() inside subscribe call back is invoked when only subscription is resolved.Refer this for better understanding.
|
[
"stackoverflow",
"0016845980.txt"
] | Q:
Metro App OnSearchActivated ProgressRing not displaying
I am implementing searching within my Metro application. The search works well, results and UI come up as expected with one problem though.
I try to display a ProgressRing before the search and hide it after the search completes, but it never gets displayed.
What am I missing, code snippet below:
protected override void OnSearchActivated(Windows.ApplicationModel.Activation.SearchActivatedEventArgs args)
{
// Some Metro designer generated code here
// Show progress ring
MainPage.Current.ResetProgressRingState(true);
// Bind search results
MainPage.Current.BindSearchResults(args.QueryText);
// Ensure the current window is active
Window.Current.Activate();
// Hide progress ring
MainPage.Current.ResetProgressRingState(false);
}
I suspect that the BindSearchResults method needs to be awaited in order for the ProgressRing to work correctly. If so, what's the easiest way to make that method awaitable, if not please advise what I am missing here.
A:
If so, what's the easiest way to make that method awaitable, if not please advise what I am missing here.
Mark it as async and have it return Task. Within that method, use await on other asynchronous operations.
|
[
"stackoverflow",
"0056806557.txt"
] | Q:
Search in a multi-select
I want to create a search for a multi-select but i have no idea where to start.
I'd want the search to remove all the other options and only show the one that matches the search(the search would go through each word(first name, last name, and also username) excepting email.
I'd create the event listener on the keyup but after that I literally have no idea on how to continue.
This is how my select looks like:
$("#addselect_searchtext").keyup(function() {
alert("do_search?");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="span5">
<label for="addselect">Users</label>
<div class="userselector" id="addselect_wrapper">
<select name="addselect" id="addselect" size="20" class="form-control" style="">
<optgroup id="toexec" label="All Students (2)">
<option value="2">Admin User (admin, [email protected])</option>
<option value="3">Student Test (student, [email protected]</option>
</optgroup>
</select>
<div class="form-inline">
<label for="addselect_searchtext">Search</label><input type="text" name="addselect_searchtext" id="addselect_searchtext" size="15" value="" class="form-control"><input type="button" value="Clear" class="btn btn-secondary m-x-1" id="addselect_clearbutton"
disabled=""></div>
</div>
</div>
A:
Like this?
Tested in Chrome and Edge - it does not work in IE11
I added a workaround - it is a bit hard to test since stacksnippets don't run in IE so I have made a fiddle
For some reason the disable/enable does not show until you mouse over the select in IE11
$("#addselect_searchtext").on("input",function() {
var val = this.value.toLowerCase()
$("#toexec option").each(function() {
var show = $(this).text().toLowerCase().indexOf(val) !=-1;
$(this).toggle(show)
$(this).prop("disabled",!show)
})
$("#addselect_clearbutton").prop("disabled",this.value=="")
});
$("#addselect_clearbutton").on("click",function() {
$("#addselect_searchtext").val("").trigger("input")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="span5">
<label for="addselect">Users</label>
<div class="userselector" id="addselect_wrapper">
<select name="addselect" id="addselect" size="5" class="form-control" style="">
<optgroup id="toexec" label="All Students (2)">
<option value="2">Admin User (admin, [email protected])</option>
<option value="3">Student Test (student, [email protected]</option>
</optgroup>
</select>
<div class="form-inline">
<label for="addselect_searchtext">Search</label><input type="text" name="addselect_searchtext" id="addselect_searchtext" size="15" value="" class="form-control"><input type="button" value="Clear" class="btn btn-secondary m-x-1" id="addselect_clearbutton"
disabled=""></div>
</div>
</div>
|
[
"math.stackexchange",
"0003405019.txt"
] | Q:
Find the equation of a term in function of the second
I want to write A(n) in terms of B(n) but nothing seems to work I can find the appropriate pattern.
n A(n) B(n)
1 1 0
1 1 1
2 3 1
3 5 2
4 9 3
5 15 5
6 25 8
7 41 13
8 67 21
A:
Hint If $A(8)$ is $67$ and not 61, as in your table, compare
$$A(n+1)-A(n) \mbox{ with } 2B(n)$$
Hint 2 $\sum_{k=1}^n A(k+1)-A(k)$ is telecopic. Use
$$\sum_{k=1}^n A(k+1)-A(k)=2 \sum_{k=1}^n B(k)$$
|
[
"stackoverflow",
"0061167250.txt"
] | Q:
Exported object returns undefined
I have the following singleton inside my app.js code:
const TodoManager = (function () {
const allTodos = [];
return {
addNewTodo: function (title, color) {
allTodos.push(new Todo(title, color));
},
};
})();
and I would like to export the addNewTodo function to another .js file, so I attached this to end of app.js:
module.exports = TodoManager
then, on my dom.js file (the file I want to use the addNewTodo function), I imported it:
import TodoManager from './app.js';
However, everytime I try to access any of its objects, it returns undefined. Am I doing something stupidly wrong?
(I am using Parcel.js as a bundler)
A:
You have:
// app.js
require("./dom.js");
const TodoManager = (function () {
// ...
You also have
// dom.js
import TodoManager from './app.js';
const MenuBar = (function(){
// ...
This is a circular dependency. When one of the files runs, it sees that it needs to import the other, so control flow switches to the other. Then, the other sees that it needs to import the first file. But the first file is already being in the process of getting created, so it doesn't switch back. The interpreter understands you have a potential issue, but it doesn't throw an error, it tries to run the script the best it can, by setting the export of the original file to an empty object initially. But this results in bugs.
But, in your code, app.js does not actually do anything with the require("./dom.js"); - there's no need for app.js to depend on dom.js. So, all you really need to do is remove require("./dom.js"); from app.js.
|
[
"stackoverflow",
"0038472025.txt"
] | Q:
ASP.NET Core Model null error in the Index view
Please see the Error section below. Other related code is as follows:
Model:
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
BlogPostController
public IActionResult Index()
{
return View("~/Views/BlogsTest/Index.cshtml");
}
View [Index.cshtml]:
@model IEnumerable<ASPCoreCodeFirstApp.Models.Blog>
<p>
<a asp-controller="BlogPost" asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Url)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Url)
</td>
<td>
<a asp-controller="BlogPost" asp-action="Edit" asp-route-id="@item.BlogId">Edit</a>
</td>
<td>
<a asp-controller="BlogPost" asp-action="Create" asp-route-id="@item.BlogId">Edit</a>
</td>
</tr>
}
</tbody>
</table>
Error at @foreach (var item in Model)....line:
I can see the Index method gets called and when I put the breakpoint at the @foreach (var item in Model) line of Index.cshtml file I get Model as null and the browser throws the following error. Blogs table does have data. Even if it did not have data the foreach loop should have returned empty result instead of an NULL exception error. The view relative path in the Index action method seems write since Index.cshtml view does get called. What I may be missing?:
NullReferenceException: Object reference not set to an instance of an object.
MoveNext in Index.cshtml, line 22
Folder Hierarchy:
Model above is in Model.cs file highlighted below:
A:
Your view is a strongly typed view requiring a list (to be precise, IEnumerable) of Blog objects :
@model IEnumerable<ASPCoreCodeFirstApp.Models.Blog>
For strongly typed views, you have to pass an object of the type that the view requires from your controller action for the view engine to be able to render the view ( Even if it's just an empty list ) :
View("ViewName", new List<Blog>())
|
[
"stackoverflow",
"0063497102.txt"
] | Q:
Elixir macros to pack and unpack arbitrary structures and bitstrings
I'm trying to write a macro to save manually typing serialization/deserialization functions for data structures.
The goal is to be able to call the macro
Macros.implement_message(TheMessage, {:field_1, 0, unsigned-size(8)}, {:field_2, 0, unsigned-size(32)})
And have code that looks like this generated at the macro call site:
defmodule TheMessage do
defstruct [
field_1: 0,
field_2, 0,
]
def serialize(%TheMessage{field_1: field_1, field_2: field_2}) do
<<field_1::unsigned-size(8), field_2::unsigned-size(32)>>
end
def deserialize(<<field_1::unsigned-size(8), field_2::unsigned-size(32)>>) do
%TheMessage{field_1: field_1, field_2: field_2}
end
end
This is what I've got, and need some help filling out the serialize and deserialize functions:
defmodule Macros do
@moduledoc false
@doc """
Implement a serializable structure, including serialize and a deserialize functions. This
will defmodule the module, defstruct the fields and their defaults, and generate serialize
and deserialize functions that function-head-match the module.
defmodule MyModule do
Macros.implement_message(TheMessage, [
{:field_1, 0, unsigned-size(8)},
{:field_2, 0, unsigned-size(32)},
])
end
# Equivalent code:
defmodule MyModule do
defmodule TheMessage do
defstruct [
field_1: 0,
field_2, 0,
]
def serialize(%MyModule{field_1: field_1, field_2: field_2}) do
<<field_1::unsigned-size(8), field_2::unsigned-size(32)>>
end
def deserialize(<<field_1::unsigned-size(8), field_2::unsigned-size(32)>>) do
%MyModule{field_1: field_1, field_2: field_2}
end
end
end
## Parameters
- module The module atom
- field_tuples [{field_atom, default_value, bin_rep}]
"""
defmacro implement_message(module, field_tuples) do
module_def_kwl = Enum.map(field_tuples, fn({field_atom, default_value, _bin_rep}) -> {field_atom, default_value} end)
fields_assignments = Enum.map(module_def_kwl, fn({field_atom, _default_value}) -> {field_atom, Atom.to_string(field_atom)} end)
ast = quote do
defmodule unquote(module) do
defstruct unquote(module_def_kwl)
def serialize(%unquote(module){unquote(fields_assignments)}) do
# ?
end
def deserialize(_how_to_pattern_match?) do
# ?
end
end
end
[ast]
end
end
A:
The key is to using unquote_splicing and Macro.var.
defmodule Serializer do
defmacro defserialize(_, fields) do
map_fields =
fields
|> Keyword.keys()
|> Enum.map(&{&1, Macro.var(&1, nil)})
binary_fields =
fields
|> Enum.map(fn {name, bits} ->
var_name = Macro.var(name, nil)
quote do
unquote(var_name) :: unquote(bits)
end
end)
quote do
def serialize(%{unquote_splicing(map_fields)}) do
<<unquote_splicing(binary_fields)>>
end
def deserialize(<<unquote_splicing(binary_fields)>>) do
%{unquote_splicing(map_fields)}
end
end
end
end
defmodule Foo do
import Serializer
defserialize Bar, [
x: 4,
y: 5,
z: 7
]
end
|
[
"stackoverflow",
"0009995321.txt"
] | Q:
Makefile - Make a executable for each .c in the folder
My question is deceptively simple, but I have lost several hours of study trying to get the solution. I'm trying to create a Makefile that builds an executable for each .c file in a directory.
I have tried the following:
CC = gcc
SRCS = $(wildcard *.c)
OBJS = $(patsubst %.c,%.o,$(SRCS))
all: $(OBJS)
$(CC) $< -o $@
%.o: %.c
$(CC) $(CPFLAGS) -c $<
but this way it is creating only .o files, and not any executables. I need a rule that makes an executable for each of these .o files. Something like the following:
gcc src.o -o src
A:
rob's answer doesn't seem to work on my machine. Perhaps, as the complete Makefile:
SRCS = $(wildcard *.c)
all: $(SRCS:.c=)
.c:
gcc $(CPFLAGS) $< -o $@
(The last two lines, are on my machine, unnecessary, as the default rules are adequate.)
|
[
"stackoverflow",
"0006196413.txt"
] | Q:
How to recursively print the values of an object's properties using reflection
To aid in debugging some code I'm working on, I started to write a method to recursively print out the names and values of an object's properties. However, most of the objects contain nested types and I'd like to print their names and values too, but only on the types I have defined.
Here's an outline of what I have so far:
public void PrintProperties(object obj)
{
if (obj == null)
return;
Propertyinfo[] properties = obj.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
if ([property is a type I have defined])
{
PrintProperties([instance of property's type]);
}
else
{
Console.WriteLine("{0}: {1}", property.Name, property.GetValue(obj, null));
}
}
The parts between the braces are where I'm unsure.
Any help will be greatly appreciated.
A:
The code below has an attempt at that. For "type I have defined" I chose to look at the types in the same assembly as the ones the type whose properties are being printed, but you'll need to update the logic if your types are defined in multiple assemblies.
public void PrintProperties(object obj)
{
PrintProperties(obj, 0);
}
public void PrintProperties(object obj, int indent)
{
if (obj == null) return;
string indentString = new string(' ', indent);
Type objType = obj.GetType();
PropertyInfo[] properties = objType.GetProperties();
foreach (PropertyInfo property in properties)
{
object propValue = property.GetValue(obj, null);
if (property.PropertyType.Assembly == objType.Assembly && !property.PropertyType.IsEnum)
{
Console.WriteLine("{0}{1}:", indentString, property.Name);
PrintProperties(propValue, indent + 2);
}
else
{
Console.WriteLine("{0}{1}: {2}", indentString, property.Name, propValue);
}
}
}
A:
Is there any particular reason why you want to use reflection?
Instead you can use JavaScriptSerializer like this:
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
string json = serializer.Serialize(obj);
Console.WriteLine(json);
It will recursively include all properties in string, and throw exception in case if circular reference will appear.
A:
Leverage from Leonid's answer, the below code is what I used to create a readable Json dump of any object. It ignores null field and add indentation for better view (especially good for SOAP objects).
public static string SerializeToLogJson(this object obj)
{
try
{
var json = JsonConvert.SerializeObject(obj,
Newtonsoft.Json.Formatting.None,
new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.Indented
});
return json;
}
catch (Exception e)
{
log.ErrorFormat(e.Message, e);
return "Cannot serialize: " + e.Message;
}
}
|
[
"stackoverflow",
"0008938461.txt"
] | Q:
Implicit method group conversion gotcha
I am wondering why the output of the given code (execute it in LinqPad)
void Main() {
Compare1((Action)Main).Dump();
Compare2(Main).Dump();
}
bool Compare1(Delegate x) {
return x == (Action)Main;
}
bool Compare2(Action x) {
return x == Main;
}
is always:
False
True
I have naively expected it to be True in both cases.
A:
This is how it looks when compiled to IL and then decompiled back to C#. Note that in both cases there's new Action(Main) - a new reference object (delegate) with pointer to actual method stored inside.
private static void Main()
{
Program.Compare1(new Action(Program.Main)).Dump();
Program.Compare2(new Action(Program.Main)).Dump();
Console.ReadLine();
}
private static bool Compare1(Delegate x)
{
return x == new Action(Program.Main);
}
private static bool Compare2(Action x)
{
return x == new Action(Program.Main);
}
If then we take a look into CIL, the former uses ceq (reference comparison) and the latter uses call bool [mscorlib]System.Delegate::op_Equality(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) to compare delegates.
First returns false because actions wrapping your delegates are two distinct reference objects.
Second returns true as the equality operator implemented on the Delegate class compares actual targets inside wrappers (actions).
A:
The false result is related to the fact that the Compare1() method performs reference comparison on two different object (compilator shows the corresponding warning):
IL_0001: ldarg.0
IL_0002: ldnull
IL_0003: ldftn instance void ConsoleApplication1.Test::Main()
IL_0009: newobj instance void [System.Core]System.Action::.ctor(object,
native int)
IL_000e: ceq <<reference comparison
You can avoid the issue using the following code:
bool Compare1(Delegate x) {
return x == (Delegate)((Action)Main);
}
|
[
"es.stackoverflow",
"0000026374.txt"
] | Q:
Haskell, division sin div
Hola buenas tengo un problema en mano trata de hacer un código en Haskell con las siguientes condiciones:
Le introducimos dos numeros a y b para que se divida a/b de tipo Integer , de forma que nos duevleva su modulo y su cocciente
Con las siguientes restrinciones solo se pueden usar sumas , restas y comparadores no se puede usar ni div, ni mod, ni nada
//Editado apartir de aqui
cocienteYResto:: Integer -> Integer -> (Integer, Integer)
cocienteYResto x y
| x < y = (x,?????)
| otherwise = ((cocienteYResto (x - y) y))
bien aqui como vemos cuando x< y estoy devolviendo el resto, pero no tengo forma, bueno mas bien no se como conseguir ese cocciente (esto ahora mismo ni observa de que se divida entre 0, ni de que x<y en un caso base
simplemente tiene que dividir cosas como 3/2 10/4, pero nada de 3/8 .
Se aceptan sugerencias de todo tipo, estoy empezando y toda ayuda me es buena.
Un saludo y gracias
A:
Se podría hacer introduciendo una función auxiliar que fuera arrastrando el valor del cociente en cada iteración recursiva.
cocienteYResto :: Integer -> Integer -> (Integer, Integer)
cocienteYResto = aux 0
where aux c x y
| x >= y = aux (c+1) (x-y) y
| otherwise = (c,x)
Pero, puesto que estamos tratando de programación-funcional, podemos aprovechar lo que tenemos para hacerlo más elegante:
import Data.List (span, genericLength)
cocienteYResto :: Integer -> Integer -> (Integer, Integer)
cocienteYResto x y = (genericLength l, head r)
where (l,r) = (span (>=y) . iterate (-y+)) x
Editado el 2016-10-07
Una versión mejor:
cocienteYResto :: Integer -> Integer -> (Integer,Integer)
cocienteYResto x y = head . dropWhile ((>=y).snd)
$ zip [0..] (iterate (-y+) x)
|
[
"ru.stackoverflow",
"0000552639.txt"
] | Q:
Замена страницы New Tab/ Новая вкладка
Как заменить cтраницу открывающуюся при нажатии на кнопку New Tab/ Новая вкладка, которая так же доступна по адресу chrome://newtab?
A:
Всё разобрался, почитал подробнее про manifest.json. Нужно было добавить в manifest
"chrome_url_overrides": {
"newtab": "main.html"
},
|
[
"stackoverflow",
"0062333243.txt"
] | Q:
Adding Woocommerce categories below the shop images
I was working on adding the product categories to under the shop image on my site. I have it working using the code below, but the categories do not have spaces between them. I am a bit of a novice here so wondered if someone can help me where I could add a space of comma between each category listing that would be great! Thanks in advance.
add_action( 'woocommerce_after_shop_loop_item', 'after_shop_loop_item_title', 1 );
function after_shop_loop_item_title() {
global $post;
$terms = get_the_terms( $post->ID, 'videocategories' );
$text = "<h3>Category: ";
foreach ($terms as $term) {
$text .= $term->name;
}
$text .= "</h3>";
echo $text;
}
A:
You can use the PHP implode() function. This will create a string from an array and separate them with a separator of your choosing.
In the example below I first created an array of the categories and then used the implode() function in combination with the printf() function to print a comma separated list enclosed by h3 tags:
add_action( 'woocommerce_after_shop_loop_item', 'after_shop_loop_item_title', 10 );
function after_shop_loop_item_title() {
global $post;
$terms = get_the_terms( $post->ID, 'videocategories' );
$product_cats = array();
if ( !empty( $terms ) ) {
// Get an array of the categories
foreach ( $terms as $key => $term ) {
$product_cats[] = $term->name;
}
// Convert product category array into comma separated string
printf( '<h3>Category: %s</h3>', implode( ', ', $product_cats ) );
}
}
|
[
"math.stackexchange",
"0001155062.txt"
] | Q:
Arzela-Ascoli: Proof?
Problem
Given a compact domain.
Regard the function space:
$$\mathcal{C}(\Omega):=\{f:\Omega\to\mathbb{C}:f\text{ continuous}\}$$
Consider a bounded family:
$$\mathcal{F}\subseteq\mathcal{C}(\Omega):\quad\|f\|_{f\in\mathcal{F}}<\infty$$
Then Arzela-Ascoli states:
$$\mathcal{F}\text{ precompact}\iff\mathcal{F}\text{ equicontinuous}$$
How to prove this from scratch?
Attempt
For a precompact family one finds:
$$\mathcal{F}\subseteq\mathcal{B}_\delta(g_1)\cup\ldots\cup\mathcal{B}_\delta(g_I)$$
So one can always pick one close enough:
$$f\in\mathcal{F}:\quad|f(x)-f(z)|\leq|f(x)-g_f(x)|+|g_f(x)-g_f(z)|+|g_f(z)-f(z)|<\varepsilon\quad(x\in B_\delta(z))$$
Conversely, prove for a sequence:
$$f_n\in\mathcal{F}:\quad\|f_{m'}-f_{n'}\|\to0$$
For a compact domain one finds:
$$\Omega\subseteq B_\delta(a_1)\cup\ldots\cup B_\delta(a_I)$$
Bolzano-Weierstrass gives a subsequence:
$$|f_n(a_i)|_{n\in\mathbb{N}}<\infty:\quad|f_{m'}(a_i)-f_{n'}(a_i)|\to0$$
Take as threshold:
$$m',n'\geq N':=\max_{i=1\ldots I}N'_i$$
So one can again always pick one close enough:
$$x\in\Omega:\quad|f_{m'}(x)-f_{n'}(x)|\leq|f_{m'}(x)-f_{m'}(a_x)|+|f_{m'}(a_x)-f_{n'}(a_x)|+|f_{n'}(a_x)-f_{n'}(x)|<\varepsilon$$
Is this proof correct or do I miss something?
Discussion
Moreover, why does the usual proof exploit separability before?
(For example see wiki: Arzela-Ascoli: Proof)
Sure for a proposition on its own:
$$\Omega\text{ separable}:\quad|f_n(x)-f(x)|\to0$$
$$\Omega\text{ precompact}:\quad\|f_n-f\|\to0$$
But why both together in a single proof?
A:
Consider any separable metric space $X$ and a complete metric space $Y$. Then endow $C(X,Y)$ with the compact convergence topology: a sequence $(f_n)$ converges to $f\in C(X,Y)$ if and only if for every compact subset $K$ of $X$, $f_n\mid K$ converges uniformly to $f\mid K$. You can show this is actually metrizable, so that compact and and sequentially compact are equivalent properties, and hence precompact and sequentially precompact are too.
What Arzela-Ascoli says is that a family $\mathscr F$ of $C(X,Y)$ is precompact if and only if it is locally uniformly equicontinuous -- every point $x\in X$ has a neighborhood $V$ where $\mathscr F\mid V$ is uniformly equicontinuous, and pointwise bounded, i.e. every set ${\rm ev}_x(\mathscr F)$ is bounded in $Y$ for each $x\in X$.
It seems to me that when one puts it in this way, the proof is very natural and easy to remember.
Consider a sequence $(f_n)$ in $\mathscr F$. First, take a dense countable subset $A=\{a_1,\ldots\}$. The general diagonal argument gives a subsequence $g_j=f_{i_j}$ such that $g_j(a_i)$ converges for each $a_i$ as $j\to\infty$. Now pick a compact set $K$, and take $\varepsilon >0$.
Since $\mathscr F$ is locally uniformly equicontinuous, each point $x$ in $K$ has a neighborhood $V_x$ where $\mathscr F \mid V_x$ is is uniformly equicontinuous. Since $K$ is compact, we can find finitely many $V_1,\cdots ,V_s$ that cover $K$, and where $z,y\in V_x$ implies $d(f(z),f(y))<\varepsilon$ for any $z,y\in V_x$ and $f\in\mathscr F$.
Since $A$ is dense, we can find $a'_i=a_{i_j}\in V_j$ for each $j$. I claim that $(g_j)$ converges uniformly in $K$. Indeed, pick any $z\in K$. If $z$ is in $V_i$ we have that
$$d(g_n(z),g_m(z))\leqslant d(g_n(z),g_n(a_i))+d(g_n(a_i),g_m(a_i))+d(g_m(a_i),g_m(z))<3\varepsilon$$
Since $a_i,z\in V_i$, we have that $d(g_n(z),g_n(a_i))$ and $d(g_m(a_i),g_m(z))$ are both $<\varepsilon$ and since $g_j(a_i)$ converges we can pick $N$ so that $n,m>N$ gives $d(g_n(a_i),g_m(a_i))<\varepsilon$. This means that if $n,m>N$ and $z\in K$, $$d(g_n(z),g_m(z))<3\varepsilon$$
Which means $(g_n)$ converges uniformly in $K$.
|
[
"mathematica.stackexchange",
"0000089064.txt"
] | Q:
The most simple Manipulate freezes the notebook on v10.1
I realize this won't be a particularly clear question. As I'm not able myself to find a pattern for the problem I'm talking about I won't be able to give enough informations to make it fully reproducible, either. What I'm hoping for is that this is common enough that someone else has already encountered it and found a solution/workaround.
Quite often, Manipulate objects make the notebook freeze, until a message appears notifying me that the Kernel is not responding to Dynamic Evaluation, as you can see in the following snapshot:
This doesn't happen on direct evaluation of the Manipulate function, but as soon as I try to modify a dynamic parameter. In the example above, it happened as soon as I tried to move the x slider.
Aborting evaluation, re-enabling dynamic updating, and re-evaluating the Manipulate statement doesn't solve the issue: the kernel just freezes again.
Even restarting the PC doesn't always solve it.
I said always, because sometimes closing and re-opening Mathematica brings things back to normal. Sometimes even just quitting the kernel and retrying the evaluation is enough.
And this is the main problem: I'm not able to find a pattern. What I understood is that when this problem starts to appear, any Manipulate statement stops working. I think there is a trend on this problem coming up mainly on big, complicated notebook, but then it will be present on any notebook.
Does someone have any solution, or even just some tips to find out why such a problem may arise?
I'm using Mathematica 10.1 on a Windows 7 machine, and the problem doesn't show up with Mathematica 10.0 (identical notebooks give the problem on 10.1 and work fine on 10.0).
A:
I had this problem and the solution was to turn off the Suggestions Bar in the preferences.
|
[
"stackoverflow",
"0048676285.txt"
] | Q:
Calling erase() on an iterator, but not deleting correct element
I am learning c++ and I am working my way double linked lists, but I noticed something very peculiar when I was trying to delete elements from my list.
Problem: I am inserting an element before the value of 2 in my list , numbers, and then I am trying to delete any element that has the value 1.
Expected: After I call erase() in my conditional statement in my first loop my list, numbers, should get adjusted. The only values that numbers should should contain 0,1234,2,3.
Observed: My list numbers contains the values 0,1,1234,2,3. It is as if nothing was erased.
Code Example:
#include "stdafx.h"
#include <iostream>
#include <list>
using namespace std;
int main()
{
list<int> numbers;
numbers.push_back(1);
numbers.push_back(2);
numbers.push_back(3);
numbers.push_front(0);
list<int>::iterator it = numbers.begin();
it++;
numbers.insert(it, 100);
cout << "Element: " << *it << endl;
list<int>::iterator eraseIt = numbers.begin();
eraseIt++;
eraseIt = numbers.erase(eraseIt);
cout << "Element: " << *eraseIt << endl;
for (list<int>::iterator it = numbers.begin(); it != numbers.end(); it++)
{
if (*it == 2)
{
numbers.insert(it, 1234);
}
if (*it == 1)
{
it = numbers.erase(it);
}
else
{
it++;
}
}
for (list<int>::iterator it = numbers.begin(); it != numbers.end(); it++)
{
cout << *it << endl;
}
return 0;
}
I would greatly appreciate any assistance with this problem. Thank you for your time.
A:
You should remove the it++ at the end of the for loop declaration, because it might be increased inside the for loop too; when it gets inscreased twice some elements will be skipped. i.e.
for (list<int>::iterator it = numbers.begin(); it != numbers.end(); )
LIVE
|
[
"stackoverflow",
"0053761080.txt"
] | Q:
Accessing external (DSPF) fields using arrays in RPGLE free
In the old RPG III and the non-free RPGLE/RPG IV you could "rename" fields you get from either a record of a PF/LF or a record from a DSPF.
This lead to possibilities like grouping several lines of input (additional order text) into a array. So I didn't have to MOVEL or EVAL ottxt1 to the external described field x1txt1, ottxt2 to x1txt2 and so on.
I'd only had to rename the LF record and the DSPF record fields to the array-fields, read the record and shift them from the one array to the other and display my DSPF record
H DECEDIT('0,') DATEDIT(*DMY.) dftactgrp(*no)
Fsls001 cf e workstn
Fordtxtl0 if e k disk
D ot s 20a dim(6)
D x1 s 20a dim(6)
Iordtxtr
I ottxt1 ot(1)
I ottxt2 ot(2)
I ottxt3 ot(3)
I ottxt4 ot(4)
I ottxt5 ot(5)
I ottxt6 ot(6)
Isls00101
I x1txt1 x1(1)
I x1txt2 x1(2)
I x1txt3 x1(3)
I x1txt4 x1(4)
I x1txt5 x1(5)
I x1txt6 x1(6)
C k$or00 klist
C kfld otonbr
C kfld otopos
C eval otonbr = 2
C eval otopos = 2
C k$or00 chain ordtxtr
C if %found(ordtxtl0)
C eval x1 = ot
C endif
C
C exfmt sls00101
C
C move *on *inlr
But is this also possible in *FREE RPGLE? And if so, how?
A:
You can define data structures containing the fields from the files, and overlay them with an array.
Replace your I specs and array definitions with these data structures. You don't have to specify anything besides the field names for the fields from the externally-described file.
dcl-ds otDs;
ottxt1;
ottxt2;
ottxt3;
ottxt4;
ottxt5;
ottxt6;
ot like(ottxt1) dim(6) pos(1);
end-ds;
dcl-ds x1Ds;
x1txt1;
x1txt2;
x1txt3;
x1txt4;
x1txt5;
x1txt6;
x1 like(x1txt1) dim(6) pos(1);
end-ds;
|
Subsets and Splits