text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
How do I do a proper situp?
What should I be focusing on when doing a situp?
Are there ways to reduce strain on muscle groups that should not be getting strained?
A:
What should I be focusing on when doing a situp?
The primary thing you should focus on is contracting (tightening) your abdominals as you bring your chest to your knees.
Are there ways to reduce strain on muscle groups that should not be getting strained?
I never do the traditional sit-up anymore because it puts so much strain on other areas, and there are safer and more effective exercises to focus on. That said, here are some ways you can reduce the strain on your body during a sit-up:
Support your head with your neck. Have your hands cupped behind your head during the exercise, gently supporting your neck so it is in alignment with the spine.
Don't lift with your head. There is a tendency in some to use their hands to lift their head up through the movement, making the head the primary driver. Avoid this and use the form described above.
Don't swing. It is very tempting to use body momentum when exercising to squeeze out a last rep or two, but avoid this because at best you aren't working out the muscle and at worst you are straining other muscle groups. Keep the feet firmly planted, and use steady, controlled movements.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Multiple bluetooth connection
I want to connect 3 devices via bluetooth (My Droid must connect to 2 bluetooth devices). I 've connected my Droid to 1 device using Bluetooth chat How should I modify it for multiple bluetooth devices? Could you help me please?
A:
I was searching a way to connect 4 devices with bluetooth and I found the following.
http://groups.google.com/group/android-developers/browse_thread/thread/69d7810f6ef9bb7d
I'm not sure that this is what you want.
But in order to connect more than 2 devices using bluetooth you have to create a different UUID for each device you want to connect.
Follow the link to see code examples and a better explanation.
A:
You can try my lib for multiple bluetooth connection :
http://arissa34.github.io/Android-Multi-Bluetooth-Library/
A:
Have you looked into the BluetoothAdapter Android class? You set up one device as a server and the other as a client. It may be possible (although I haven't looked into it myself) to connect multiple clients to the server.
I have had success connecting a BlueTooth audio device to a phone while it also had this BluetoothAdapter connection to another phone, but I haven't tried with three phones. At least this tells me that the Bluetooth radio can tolerate multiple simultaneous connections :)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Problema pasar argumento a función postgres
Tengo esta función en el servidor postgres
CREATE OR REPLACE FUNCTION get_lastdata_id_test(_sensor text)
RETURNS TABLE (id uuid, sid text,ts timestamp without time zone, measure double precision) AS
$func$
SELECT id,sensor_id, date, measure
FROM measures
WHERE sensor_id = $1
ORDER BY date
DESC LIMIT 13
$func$ LANGUAGE sql;
y una API para obtener los datos desde el servidor postgres
app.get('/last/:id', (request, response) => {
const sid = parseInt(request.params.id)
pool.query("SELECT * FROM get_lastdata_id_test($1)",[sid], (error, results) => {
if (error) {
throw error
}
response.status(200).json(results.rows)
})
})
Si pruebo la función en el servidor postgres select * from get_lastdata_id_test('sen-01') Obtengo lo siguiente:
"f2c9fc2d-7ef8-49ee-9b72-a018e12c33a1" "sen-01" "2019-08-29 23:59:07" "1021.57"
"d381cd44-b017-4531-aa23-b4b7bb81138e" "sen-01" "2019-08-29 23:55:59" "1005.95"
"345c8073-edc1-4e4a-9950-1a0bfb661b38" "sen-01" "2019-08-29 14:47:31" "1005.95"
"841e6a43-0756-4ef5-ae77-e8ff3f9a3638" "sen-01" "2019-08-29 13:20:16" "994.23"
"caba2781-ec9a-49e5-a190-72a7fd47b292" "sen-01" "2019-08-29 13:16:24" "988.37"
"99b40219-fb2a-4534-9b49-0a4ecce92cba" "sen-01" "2019-08-29 13:08:28" "984.46"
"d16e805b-3a83-4b87-a414-fe05b03ecfbe" "sen-01" "2019-08-29 12:57:30" "978.6"
"80f0d046-8c43-46bf-9200-dc58465f5163" "sen-01" "2019-08-29 12:48:42" "988.37"
"b6eed4dc-301e-44d4-962b-d7d4b1b6dc8b" "sen-01" "2019-08-29 12:44:48" "998.13"
"15e82547-6b89-41eb-b427-f0659dd0c9e0" "sen-01" "2019-08-29 12:36:47" "990.32"
"735ae26a-78a0-4fe0-af67-9baaa8902f14" "sen-01" "2019-08-29 12:32:49" "992.28"
"cf82c4ad-128d-44a5-8c28-9ac4f552eca5" "sen-01" "2019-08-29 12:21:16" "986.42"
"eafe87ac-9e17-448c-a7e6-ff96e4191243" "sen-01" "2019-08-29 12:09:08" "968.84"
Pero usando la url de la API http://localhost:3000/last/sen-01 No obtengo datos:
[ ]
Cómo puedo pasar correctamente el argumento a la función a través de la URL de la API 'quote'?
A:
Estas enviando un entero como parametro y la funcion segun su definicion recibe un parametro de tipo text
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mixing Zend and Old Procedural code
We have a really old legacy code base that uses globals like they're going out of fashion - nearly all of the inter-page communication is done via globals and sessions or both. This could be changed as a last resort but ideally I don't want to touch any of it as everything I touch could introduce more bugs :-p.
Anyway, We're incorporating a new "module" into the application which was written completely in zend and is really nice and modular. My aim is to get zend running as the backbone and the old legacy code to run as a sort of module/controller within zend and once it has control just execute normally and do whatever it wants.
The 2 issues I have:
I need to get Zend to see that I'm using legacy URL's (login.php, show.php, etc) and pass execution to a specific controller;
I'm embedding an entire application inside a function of another and this breaks the default behavuour of variables appearing in the global scope as globals - i.e. they're now just local variables of this method and thus can't be seen without first specifying that they are globals.
If there's another way this could be done I'd be happy to hear it :-p
Cheers,
Chris
A:
For the first issue I think you can use the Zend_Router class.
But nevertheles I dont think is a good idea to port a procedural application to the ZF concept which is a object oriented one.
I would either rewrite the application or just use separate classes as loose components, thing that is recommended by ZF creators as well.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mechanism of radical cyclisation to form hydroazulene core
Recent studies on radical-induced cyclisation reactions have led to a simple, one-step method for the preparation of hydroazulenes from appropriately substituted cyclopentanone precursors. Treatment of 1, for example, with triphenyltin hydride and AIBN in refluxing toluene gave 2 in 79% yield. Give a mechanism for this transformation. (TES = triethylsilyl, SiEt3)
(taken from: McKillop, A. Advanced Problems in Organic Reaction Mechanisms; Tetrahedron Organic Chemistry Series, Vol. 16; Pergamon Press: Oxford, U.K., 1997; p 1.)
I know that triphenyltin hydride, Ph3SnH, can act as a reducing agent but I have no idea of its reduction mechanism. And I know that AIBN is a radical initiator:
The given conditions strongly suggest a radical pathway. However, looking at the product I also feel like there is a carbocation intermediate, as there is a ring expansion, but I don't know whether or how that happens.
A:
This reaction is taken from Tetrahedron Lett. 1995, 36 (17), 3015. (DOI:
10.1016/0040-4039(95)00502-4)
The heat (provided by refluxing) is required to initiate the reaction by the decomposition pathway you have drawn. The cyanopropyl radical thus formed abstracts a hydrogen atom from the tin hydride, a consequence of the weak Sn–H bond:
The triphenylstannyl radical is the one that actually does interesting chemistry. Generally, there are a few options for radicals at this stage. One common pathway is to abstract a halide or chalcogenide from the starting material, but there is no such atom here (C–F and C–O bonds are stronger and rarely broken, so the OTES group is out of bounds). The other common pathway is to add to a π-bond. In this case the best place to add is the terminal carbon of the alkyne, which is least sterically hindered.
After this, the remainder is a series of addition-elimination steps. Note that in each case the ring size formed is 3, 5, or 6: these are all kinetically fast cyclisations.
In particular, note that:
Intermediate 4 is stabilised by electron donation from adjacent oxygen (similar to carbocations, radicals - which are also electron-deficient species - can be stabilised by adjacent lone pairs).
You are correct that a ring expansion is needed – in fact, two are needed – but this does not require a Wagner–Meerwein shift in a carbocation. Radicals are perfectly capable of doing this job, usually by a sequence of cyclisation (5 to 6) and retro-cyclisation (6 to 7). See also J. Org. Chem. 2012, 77 (19), 8634–8647 for another example of this motif, which is very common in radical chemistry.
There isn't tin in the final product, so we will eventually have to kick it back out again: this can be achieved via a β-scission mechanism, so we have to work towards an intermediate which has a radical β to SnPh3, i.e. 7.
The original paper supports this mechanism (although they skipped some steps, as is usual in journals):
|
{
"pile_set_name": "StackExchange"
}
|
Q:
getActivity() returns null in AsyncTask when called from another class
I have an AsyncTask to perform a task.I call this from the same class where the AsyncTask is written and from another class.
I have this statement in the code snippet for fetching user's current location:
GPSTracker gps = new GPSTracker(getActivity());
When called from same class, getActivity() has value but when called from another class, getActivity() returns null.
I tried using passing the context through constructor also:
Context mContext;
AsyncDataUpdate(Context context){
this.mContext = context;
}
GPSTracker gps = new GPSTracker(mContext);
which isn't working either.
What might be the reason?
Any help will be greatly appreciated.
A:
Use mContext variable after calling of AsyncDataUpdate class constructor as:
GPSTracker gp;
Context mContext;
private AsyncDataUpdate(Context context){
this.mContext = context;
this.gps = new GPSTracker(this.mContext);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Tweening variable on mouseleave not functioning
I am attempting to tween a variable down to zero on mouseleave, but nothing happens when the mouse leaves the container.
I have tried various things. What am I doing incorrectly?
Here is the code:
function ondocumentMouseLeave ( event ){
new TWEEN.Tween( mouseY )
.to ( 0 , 500 )
.easing( TWEEN.Easing.Linear.None)
.start();
new TWEEN.Tween( mouseX )
.to ( 0 , 500)
.easing( TWEEN.Easing.Linear.None)
.start();
}
Here is the jsfiddle:
https://jsfiddle.net/cxp8rex2/16/
I apologize if this is a simple question, I am a bit new to this.
A:
You need to use an Object and tween its properties like:
function ondocumentMouseLeave ( event ) {
var mouse = {x: mouseX, y: mouseY};
new TWEEN.Tween( mouse ).to ( { x: 500, y: 500 }, 1000 )
.easing( TWEEN.Easing.Linear.None )
.onUpdate(function() {
mouseX = this.x;
mouseY = this.y;
})
.start();
}
have a look on tween.js user guide.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Tkinter CPU activity after inserting text from file
If I take a 25MB/190,000 line text file and dump it into a text widget the process finishes quickly but I still see python.exe using 50%CPU for another minute or so afterwards. The bigger the file, the longer it takes for the CPU to drop off to 0% usage. When I start loading multiple files into different text widgets they load into the widget instantly but the CPU stays at 50% and the GUI runs horribly slow until it finishes whatever its doing in the backend. Can someone explain to me why the CPU is still being used and why its impacting performance if the text is already in the widget? What is it needing to do? Any way around this?
from tkinter import *
file = r"C:\path\to\large\file.txt"
def doit():
with open(file, 'r') as f:
txt.insert('end', ''.join(f))
f.close()
main = Tk()
txt = Text(main)
txt.grid(row=0)
btn = Button(main, text="click here", command=doit)
btn.grid(row=1, columnspan=2)
main.mainloop()
I thought maybe it was because im handling the file line by line instead of loading the entire file into RAM. I tried readlines() but I get the same results.
A:
Most likely it is calculating where the line breaks go, for lines past the area currently visible on the screen. With the numbers you gave, the lines average over 130 characters long; if some of them are considerably over that, this is a situation that Tkinter is known to be slow in.
You could perhaps turn off word-wrap (by configuring the Text with wrap=NONE), which would probably require that you add a horizontal scroll bar. If that is unacceptable, it's possible that adding newlines of your own could help, if there's some natural point at which to insert them in your data.
Note that ''.join(f) is a rather inefficient way to read the entire file into a single string - just use f.read() for that.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Coqide Error: Compiled library Basics.vo makes inconsistent assumptions over library
i'm using CoqIDE_8.4pl5 on mac os X.
This error message pops up when CoqIDE forwards to this command: Require Import Basics.
Error: Compiled library Basics.vo makes inconsistent assumptions over library
Coq.Init.Notations
I didn't get this problem on my old Macbook Air when i was using CoqIDE_8.4pl5, but when i got a new macbook pro, and i downloaded it again from the same website.
But this time on this macbook pro, i used brew cask install coq to get it installed... but it seemed to not work, so i downloaded it from the website and set my coqide path to the same path it was in my old macbook air.. and when i try forwarding my assignments, i get this problem. Is there anyway to fix this? or do i have to remove coq and copied and reinstall it?
A:
This is usually a case of Coq telling you that the compiled version of Basics.v (Basics.vo) has been compiled with a different version of Coq than the one you are currently using.
For safety reasons, each version of Coq only wants to use files compiled with that same version.
The fix is usually to delete the incriminating Basics.vo file and reproduce the compilation step that created it.
If the error happens again, then it might be a case of your system having two versions of Coq installed, one of which is reached by your building script, while the other one is use by CoqIDE.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Redirect to Named Route from RouteConfig or Controller Action Method
I have the following named route in ASP.NET MVC:
[Route("build", Name = "Build")]
public ActionResult Build()
{
return View();
}
I have a situation where this app no longer has a Home page, no need for /Home/Index.cshtml. However, I do not want to deleted Index.cshtml nor do I want to move Build.cshtml code to Index.cshtml
I simply want the default route to be my Build route. Unfortunately, having the named Build route, [Route("build", Name = "Build")], which I use places throughout the application, @Html.RouteLink("GET BUILDING", "Build") is making it so I can not do a simple redirect from http://www.mywebsite.com to http://www.mywebsite.com/build with either of the following ways:
In my RouteConfig, this does not work, the resource cannot be found when you go to http://wwww.mywebsite.com:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Build", id = UrlParameter.Optional }
);
Also, and this is more surprising, this does not work either, also results in the resource cannot be found when you go to http://wwww.mywebsite.com:
public ActionResult Index()
{
return RedirectToRoute("Build");
}
I comment out my named Route like so:
//[Route("build", Name = "Build")]
public ActionResult Build()
{
return View();
}
Then my RouteConfig way above works.
I would prefer to Redirect to the named route in my RouteConfig though it is fine to if I can Redirect to named route from my /home/index Action method
A:
The RouteLink takes the route name, not the route pattern/template, so you can simply change the route pattern to "" (empty string)
[Route("", Name = "Build")]
public ActionResult Build()
{
return View();
}
When a request comes for yourSiteName.com, it will be handled by Build action method ,because it matches with the route pattern (nothing after the baseurl)
All your existing code which uses the route name in the RouteLink helper method will still work as we did not change that.
@Html.RouteLink("GET BUILDING", "Build")
If you want to have yourSiteName/Build to also work, you can add another route with the route pattern "" along with your current route definition.
[Route("")]
[Route("build", Name = "Build")]
public ActionResult Build()
{
return View();
}
Now when a request comes for yourSiteName.com or yourSiteName.com/build, it will be handled by Build action method
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to return a variable from a function using subprocess?
I have a very beginner question. I'm trying to do the following where I need to get a list from another Python script using subprocess.
level 1 :
#!/usr/bin/python
import sys
import os
def run(a):
print "running"
return a
#if __name__ == "__main__":
run(str(sys.argv[1]))
level 0 :
import sys
import os
import subprocess
output = subprocess.check_output(['python','level1.py','test'])
print output
However, when I run this, the output prints out "running" instead of the value stored in variable a.
I was wondering how I can get the value of a instead of all the print statements.
A:
Take a look at https://stackoverflow.com/a/7975511/3930971
You are using another system process to run the script, it does not tell the rest of your system of the value returned the call to run(). All the rest of the system sees is what is directed to output (stdout, stderr), your current script only sends "running" to output, so that is what subprocess sees.
If you decided to treat it as module and import it, you could get return values of functions.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Debugging a PL/pgSQL function
I am trying to get this PL/pgSQL function to work :
CREATE OR REPLACE FUNCTION loopcolumns2(tableName TEXT, pourcentage real)
RETURNS void AS $$
DECLARE
_name text;
missing_percentage real;
BEGIN
FOR _name IN SELECT column_name from information_schema.columns where table_name=tableName LOOP
SELECT 100 - (count(_name) * 100) / count(*) INTO missing_percentage FROM tableName;
IF (missing_percentage > pourcentage)
THEN ALTER TABLE tableName DROP COLUMN _name;
END IF;
END LOOP;
END; $$ LANGUAGE plpgsql;
The goal of the function is to loop through all the columns of a table, a delete the columns where the percentage of missing values is bigger than an input percentage.
I get the following error :
SELECT 100 - (count( $1 ) * 100) / count(*) FROM $2
^
CONTEXT: SQL statement in PL/PgSQL function "loopcolumns2" near line 6
A:
You're trying to SELECT from text stored by tableName vaiable. You cannot do that because Postgres think you want him to select from table named tableName, but probably such table doesn't exist.
You nead to create dynamic query in string and use EXECUTE ... INTO ... statement. Like this:
DECLARE query TEXT;
...
query := 'SELECT 100 - (count(' || _name::TEXT || ') * 100) / count(*) FROM '
|| tableName::TEXT;
EXECUTE query INTO percentage ;
...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JavaFX: creating a Media Object causes java.lang.reflect.InvocationTargetException Error
I'm currently working on a simple game and I'm trying to implement sound with JavaFX and I get a java.lang.reflect.InvocationTargetException error when creating a Media object.
I have tried:
Media media = new Media("file:sounds/test.mp3");
Media media = new Media(new File("file:sound/test.mp3").toURI().toString());
and also both with the complete file path on my PC.
This is the error I'm getting:
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.lang.NoClassDefFoundError: javafx/scene/media/Media
at application.Main.start(Main.java:14)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
... 1 more
Caused by: java.lang.ClassNotFoundException: javafx.scene.media.Media
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 10 more
Exception running application application.Main```
A:
The error message says NoClassDefFoundError: javafx/scene/media/Media which means that it is not finding the Media classes.
The solution is to add vm arguments to your project.
Right click project > Run As > Run configurations ...
Click on Arguments and paste the following in vm arguments:
--module-path "/path/to/javafx-sdk/lib" --add-modules javafx.media
Depending on your project, you may have to add javafx.controls and javafx.fxml as well.
--module-path "/path/to/javafx-sdk/lib" --add-modules javafx.controls,javafx.fxml,javafx.media
Replace /path/to/javafx-sdk/lib with the actual path of the lib folder in your system.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Array variable initialization error in Java
I am trying to write a Java program that reads an input file consisting of URLs, extracts tokens from these, and keeps track of how many times each token appears in the file. I've written the following code:
import java.io.*;
import java.net.*;
public class Main {
static class Tokens
{
String name;
int count;
}
public static void main(String[] args) {
String url_str,host;
String htokens[];
URL url;
boolean found=false;
Tokens t[];
int i,j,k;
try
{
File f=new File("urlfile.txt");
FileReader fr=new FileReader(f);
BufferedReader br=new BufferedReader(fr);
while((url_str=br.readLine())!=null)
{
url=new URL(url_str);
host=url.getHost();
htokens=host.split("\\.|\\-|\\_|\\~|[0-9]");
for(i=0;i<htokens.length;i++)
{
if(!htokens[i].isEmpty())
{
for(j=0;j<t.length;j++)
{
if(htokens[i].equals(t[j].name))
{ t[j].count++; found=true; }
}
if(!found)
{
k=t.length;
t[k].name=htokens[i];
t[k].count=1;
}
}
}
System.out.println(t.length + "class tokens :");
for(i=0;i<t.length;i++)
{
System.out.println(
"name :"+t[i].name+" frequency :"+t[i].count);
}
}
br.close();
fr.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
But when I run it, it says: variable t not initialized.. What should I do to set it right?
A:
Arrays in Java are fixed length, so I think what you really want to do is use a List<Tokens>
e.g.
List<Tokens> t = new ArrayList<Tokens>();
and
t.add(new Tokens(...))
unless you know in advance the number of items you'll have.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Magento not executing my module install script
I am trying to create a local module. Here regarding this there are lot of question. I have almost all of them followed. But it is never working.
Atlast I followed this: http://devdocs.magento.com/guides/m1x/magefordev/mage-for-dev-6.html
But this is als not working. Here is my structure:
app/code/local/Mycompany/Hello/Model/Resource/Setup.php
<?php
class Mycompany_Hello_Model_Resource_Setup extends Mage_Core_Model_Resource_Setup {
}
in app/code/local/Mycompany/Hello/sql/mycompany_hello_setup/install-0.1.0.php
<?php
echo 'Running This test: '.get_class($this)."\n <br /> \n";
die("Exit for now");
app/code/local/Mycompany/Hello/etc/config.xml
<?xml version="1.0"?>
<config>
<modules>
<Mycompany_Hello>
<version>0.1.0</version>
</Mycompany_Hello>
</modules>
<frontend>
<routers>
<hello>
<use>standard</use>
<args>
<module>Mycompany_Hello</module>
<frontName>hello</frontName>
</args>
</hello>
</routers>
</frontend>
<global>
<resources>
<Mycompany_Hello_setup>
<setup>
<module>Mycompany_Hello</module>
<class>Mycompany_Hello_Model_Resource_Setup</class>
</setup>
</Mycomapny_Hello_setup>
</resources>
</global>
Here the only issue I am facing is it never executes install script.
My approches till now:
Renamed app/code/local/Mycompany/Hello/sql/mycompany_hello_setup/install-0.1.0.php to following names on each attempt app/code/local/Mycompany/Hello/sql/hello_setup/install-0.1.0.php,
app/code/local/Mycompany/Hello/sql/hello_setup/mysql4-install-0.1.0.php, app/code/local/Mycompany/Hello/sql/mycompany_hello_setup/install-0.1.0.php,
app/code/local/Mycompany/Hello/sql/Mycompany_hello_setup/mysql4-install-0.1.0.php
During every attempt I flush cache and delete the entry from core_resources table.
All my file permisson is 777 (for debugging purpose, later I will change it to 755). Actaully I placed a debugging code in install. Once it executed, I will replace this with my actual installer script.
But it seems something, I am missing something, as a result it is not working.
Please help. Thank you in advance.
A:
The XML node
<Mycompany_Hello_setup>
must match the path
sql/mycompany_hello_setup/install-0.1.0.php
^^^^^^^^^^^^^^^^^^^^^
It looks like you got the capitalization wrong.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a Form event that gets called right before anything is drawn to the screen?
I've tried overriding the OnLoad event, but the form is getting drawn before this method finishes. I am calling the base.OnLoad method. But, the form is partially getting drawn (artifacts are seen) during the event. I notice this because I'm hitting the database and it is taking some time. In the event, I'm getting some data and binding it to the form's controls. Please don't tell me to use a separate thread. For simplicity, I would rather just show a busy cursor while the data is being loaded.
UPDATE:
Ok, I think you guys/gals have convinced me. I'll use a separate thread. I wasn't aware of the BackgroundWorker and it was very easy to implement. Now my form is loading quickly. And then, all of a sudden my combo boxes are populated. But, I'd like prevent the user from clicking on the combos before they're populated. What is the best way/standard way of doing this using Winforms? Is there a way to turn off input events in the form until the background worker is finished?
A:
You could try doing your expensive operations in the form's constructor, so that when it's time to show the form, it already has the data it needs to render. Also look into SuspendLayout/ResumeLayout methods.
But none of these solutions will be as graceful as using a different thread to perform expensive operations.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why does rand seem more random than mt_rand when only doing (1, 2)?
I have some elements that I'm trying to randomize at 50% chance of output. Wrote a quick if statement like this.
$rand = mt_rand(1, 2);
if ( $rand == 1 ) {
echo "hello";
} else {
echo "goodbye";
}
In notice that when using mt_rand, "goodbye" is output many times in a row, whereas, if I just use "rand," it's a more equal distribution.
Is there something about mt_rand that makes it worse at handling a simple 1-2 randomization like this? Or is my dataset so small that these results are just anecdotal?
A:
To get the same value "many times in a row" is a possible outcome of a randomly generated series. It would not be completely random if such a pattern were not allowed to occur. If you would continue taking samples, you would also find that the opposite value will sometimes occur several times in a row, provided you keep going long enough.
One way to test that the generated values are indeed quite random and uniformly distributed, is to count how many times the same value is generated as the one generated before, and how many times the opposite value is generated.
Note that the strings "hello" and "goodbye" don't add much useful information; we can just look at the values 1 and 2.
Here is how you could do such a test:
// $countAfter[$i][$j] will contain the number of occurrences of
// a pair $i, $j in the randomly generated sequence.
// So there is an entry for [1][1], [1][2], [2][1] and [2][2]:
$countAfter = [1 => [1 => 0, 2 => 0],
2 => [1 => 0, 2 => 0]];
$prev = 1; // We assume for simplicity that the "previously" generated value was 1
for ($i = 0; $i < 10000; $i++) { // Produce a large enough sample
$n = mt_rand(1, 2);
$countAfter[$prev][$n]++; // Increase the counter that corresponds to the generated pair
$prev = $n;
}
print_r($countAfter);
You can see in this demo that the 4 numbers that are output do not differ that much. Output is something like:
Array (
[1] => Array (
[1] => 2464
[2] => 2558
)
[2] => Array (
[1] => 2558
[2] => 2420
)
)
This means that 1 and 2 are generated about an equal number of times and that a repetition of a value happens just as often as a toggle in the series.
Obviously these numbers are rarely exactly the same, since that would mean the last couple of generated values would not be random at all, as they would need to bring those counts to the desired value.
The important thing is that your sample needs to be large enough to see the pattern of a uniform distribution confirmed.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Commenting/skipping markup with Smarty
Is there a smarty tag that allows skipping content in a template without the enclosed code showing up in the rendered HTML page?
A:
Do you mean something like the Comment Tag?
{* Comment *}
Your question is a bit difficult to understand or do you mean a minifying?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
trim all whitespace around string
So I have this output:
Line 1.
Line 2.
Line 3.
Line 4. Data
Line 5.
Line 6.
I want to have:
Line1. Data
What I do:
trim($dom->saveHTML(), "\n");
What I get (6th line removed, I want line 1, 2, 3, 5 to be removed as well):
Line 1.
Line 2.
Line 3.
Line 4. Data
Line 5.
What I get literally:
A:
Your string is equal to \r\n\r\n\t\r\ndata\r\n\t which is CR LF CR LF TAB CR LF "data" CR LF TAB. You're only trimming LF (\n) in your trim() call, which is why you don't trim CR (\r) and TAB (\t) also present in your string.
Try removing the second parameter (which specifies what characters should be trimmed), it will take care all of the whitespace characters.
As of Docs:
This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:
" " (ASCII 32 (0x20)), an ordinary space.
"\t" (ASCII 9 (0x09)), a tab.
"\n" (ASCII 10 (0x0A)), a new line (line feed).
"\r" (ASCII 13 (0x0D)), a carriage return.
"\0" (ASCII 0 (0x00)), the NUL-byte.
"\x0B" (ASCII 11 (0x0B)), a vertical tab.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Materialize grid with unequal heights
I have a grid system built using Materialize with cols of unequal heights (dynamic content).
Each row should have 3 cols. I want each row to start on a new line. However, this is the result I am getting - https://codepen.io/anon/pen/QaVKyG. As you can see, the 4th card seem to start at a weird place, leaving lots of white space on the left.
I've tried using flexbox as seen here - https://codepen.io/anon/pen/rpqLgy
.row { display:flex; flex-wrap: wrap; }
However, the problem with this method is that the cols on the last row does not seem to be aligning to the left.
In short, I want the grid to work the same way as it does if I use bootstrap (like this https://codepen.io/anon/pen/vpVvKv). As you can see, for bootstrap, cols on the next row starts on the next line, even if the cols have unequal heights. I can't seem to achieve that with Materialize.
Would appreciate any help with either solution (with flexbox or no flexbox). Thanks!
A:
I am not sure if this is what you want to achieve ..
What I did is I create a cardHolder and then inside it are the cards
<div class="cardHolder">
<div class="card"></div>
<div class="card2"></div>
<div class="card3"></div>
</div>
Then I did a flex box style for the parent of the cards..
.cardHolder{
display:flex;
align-items:flex-start;
justify-content:flex-start;
flex-flow: row wrap;
width:100%;
}
after that I set the width of the cards since you wanted each row to have 3 column. I did a calc function to initialize the width of the cards
.cardHolder div{
width:calc(100% / 3);
padding:0;
margin:0;
}
and then create a media query to initialize the full width of the cards when the size of the screen is less than 600 pixels..
@media only screen and (max-width: 600px){
.cardHolder div{
width:100%;
}
}
Please see link for the sample code..
https://codepen.io/deibu21/pen/jYedep/?editors=1100
Hope this helps.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Replace the value of a variable using SED
I have a variable in multiple files that looks like this:
localparam SOME_VARIABLE = 2'h1; // some comments
I'm looking for a way to replace the value of this variable after that 'h'. For example in this case I want to search for "SOME_VARIABLE" pattern and change its value after h (1 in this case but might be something else) to 0 using SED. Note the space between the name of the variable and the = sign might vary and I want to keep it as it is, I only need to change that number after h.
I know how to find the line that matches a pattern and replace it by another value but I want to keep it as it is and replace only the number after h.
A:
Assuming ; can occur only once before possible ; in comments
$ echo "localparam SOME_VARIABLE = 2'h1; // some 23; comments" | sed '/SOME_VARIABLE/ s/[0-9]*;/0;/'
localparam SOME_VARIABLE = 2'h0; // some 23; comments
/SOME_VARIABLE/ line to match
s/[0-9]*;/0;/ replace first occurrence of numbers followed by ; to 0;
If there can be space between number and ; use [0-9 ]* or [0-9 \t]* as needed
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do you manage the pushing of screens in your BlackBerry app?
I was wondering how the people who develop for here BlackBerry go about managing the screens in their app. The most common practice (and the one I'm using) seems to be just to instantiate and push the new screen from the current one. The other option I've seen is using actions in the Main Application class to do the transitions. How do you guys manage?
A:
We have a ScreenManager class manages the display of screens. It contains a Hashmap which has Screen name -> MainScreen pairs,public methods for adding and showing a screen.
When our application starts up all the screens required are created and added to the ScreenManager class.
In the showScreen() method we get the reference to the appropriate MainScreen class. Then we use UiApplication.getUiApplication().popScreen(screen) to hide the current screen. If the screen has already been shown we simply use popScreen() to remove screens until we reach the screen we want. Otherwise we just pushScreen() to move the screen to the top of the pile.
Calls to using the UiApplication are contained within a synchronized(UiApplication.getEventLock()) block
This approach does the job for us. We can create all the screens once at the application startup so it does not need to be done over and over again during the course of the application.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jquery mobile. add class when tapping button
Hi i'm making hybrid app with JQM.
I want to add class when i am pressing or tapping(Holding) the button .
Here is my codes...
<a href='btnWhite on'>button</a>
CSS
.btnWhite { background:gray }
.btnWhite.on { background:black }
jQuery Mobile
$('.btnWhite').bind('touchstart', function() {
$(this).addClass("on");
});
$('.btnWhite').bind('touchend', function() {
$(this).removeClass("on");
});
A:
Working example: http://jsfiddle.net/Gajotres/LvhdG/
In this example I have used vmousedown, vmouseup and vmousecancel events so I can test it on desktop / mobile devices alike. Just replace them with touchstart, touchend and touchcancel if you want, but it will also work with vmouse events.
HTML :
<!DOCTYPE html>
<html>
<head>
<title>jQM Complex Demo</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=no; target-densityDpi=device-dpi"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
<!--<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>-->
<script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
</head>
<body>
<div data-role="page" id="index">
<div data-theme="b" data-role="header">
<h1>Index page</h1>
</div>
<div data-role="content">
<a data-role="button" class="btnWhite">button</a>
</div>
</div>
</body>
</html>
Javascript :
$(document).on('pagebeforeshow', '#index', function(){
$(document).on('vmousedown','.btnWhite' ,function(){
$(".btnWhite").addClass('on');
}).on('vmouseup', function(){
$(".btnWhite").removeClass('on');
}).on("vmousecancel", function() {
$(".btnWhite").removeClass('on');
});
});
CSS :
.btnWhite {
background:gray !important;
}
.on {
background:black !important;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Move a cursor position in iframe via javascript
i want some code to move the cursor position in an IFrame via Javascript or jquery.
Really it will help me a lot.
A:
Not possible. To answer why that's impossible, imagine:
I include an iframe to some very important business (let's suppose for a moment this business does not have frame-busting code)
When the user reaches my page, it begins manually controlling the cursor's position to highlight the "Delete Account" button, and simulates a click.
User's account is deleted on a completely different site, through none of their input.
Javascript allows you many UI-coding capabilities, but ultimately the user is in control. Even events like the "onpageunload" are very much restricted in what they can do, and browsers will often include 'escape' options even there. Furthermore, even in the instance that you CAN find a way around these chains, it will frustrate and quite possibly even panic many of your users. I try to warn people that any instance in which you're "re-coding the browser" may lead to all sorts of unpredictable issues, and may even prevent handicapped accessibility to your site.
It might help us to know if there's some specific reason you'd like to do this - possibly the solution is not what you think it is. For instance, if you are trying to make an FPS using WebGL, I seem to remember Chrome including some function to allow for mouse control inside of a window (possibly taking a browser confirmation dialog)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
escaping "$_" in php string
I am trying to load VCARD information into a database field as a long text string. In some cases the vcard information comes with a parameter that ends in "$_" (see second to last line). i cannot get php to bring this into the variable as string to escape it.
`$vcard = mysqli_real_escape_string($connection, "BEGIN:VCARD
VERSION:3.0
FN:Your Name
N:Name;Your;;;
EMAIL;TYPE=INTERNET;TYPE=WORK:[email protected]
TEL;TYPE=CELL:
ADR;TYPE=HOME:;;I am here;;;;
ORG:Your organization
TITLE:Owner and Co-Creator
item1.URL:https\://yoursite.com
item1.X-ABLabel:_$!<HomePage>!$_
END:VCARD");`
i get a "Notice: Undefined variable: _ in C:" error. I can manually escape the second $ but that defeats the purpose. I tried metaquote() and that does not work either. Any help on how I can circumvent this error?
A:
Replace your double quotes by a single quotes. Variables within double quotes are interpolated while they are not when they are within single quotes.
$vcard = mysqli_real_escape_string($connection, 'BEGIN:VCARD
VERSION:3.0
FN:Your Name
N:Name;Your;;;
EMAIL;TYPE=INTERNET;TYPE=WORK:[email protected]
TEL;TYPE=CELL:
ADR;TYPE=HOME:;;I am here;;;;
ORG:Your organization
TITLE:Owner and Co-Creator
item1.URL:https\://yoursite.com
item1.X-ABLabel:_$!<HomePage>!$_
END:VCARD');
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Preserve formula references when printing a single Google Sheets sheet to PDF
I want to accomplish the following:
Make a menu with a print to PDF button.
Have that button export a PDF to with the same name and same destination as the google sheet.
This works well, but the script I found I need to change, because most people print to PDF by making a temporary copy of the sheet, printing, and finally deleting the temporary copy.
I have references from other sheets in my original document that ends up printed as #REF! values because only the one sheet gets copied and printed, not my whole document.
How can i make this process include baking the formulas as text?
CODE FOR PRINTING:
function onOpen() {
var submenu = [{name: "Save PDF", functionName: "generatePdf"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu('Export', submenu);
}
function generatePdf() {
// Get active spreadsheet.
var sourceSpreadsheet = SpreadsheetApp.getActive();
// Get active sheet.
var sheets = sourceSpreadsheet.getSheets();
var sheetName = sourceSpreadsheet.getActiveSheet().getName();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
// Set the output filename as sheetName.
var pdfName = sheetName;
// Get folder containing spreadsheet to save pdf in.
var parents = DriveApp.getFileById(sourceSpreadsheet.getId()).getParents();
if (parents.hasNext()) {
var folder = parents.next();
}
else {
folder = DriveApp.getRootFolder();
}
// Copy whole spreadsheet.
var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy("tmp_convert_to_pdf", folder))
// Delete redundant sheets.
var sheets = destSpreadsheet.getSheets();
for (i = 0; i < sheets.length; i++) {
if (sheets[i].getSheetName() != sheetName){
destSpreadsheet.deleteSheet(sheets[i]);
}
}
var destSheet = destSpreadsheet.getSheets()[0];
// Replace cell values with text (to avoid broken references).
var sourceRange = sourceSheet.getRange(1, 1, sourceSheet.getMaxRows(), sourceSheet.getMaxColumns());
var sourcevalues = sourceRange.getValues();
var destRange = destSheet.getRange(1, 1, destSheet.getMaxRows(), destSheet.getMaxColumns());
destRange.setValues(sourcevalues);
// Save to pdf.
var theBlob = destSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);
var newFile = folder.createFile(theBlob);
// Delete the temporary sheet.
DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);
}
CODE FOR CONVERTING FORMULAS TO TEXT:
function formulasAsText() {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for (var k = 0; k < sheets.length; k++) {
var range = sheets[k].getDataRange();
var values = range.getValues();
var formulas = range.getFormulas();
for (var i = 0; i < values.length; i++) {
for (var j = 0; j < values[0].length; j++) {
values[i][j] = formulas[i][j] ? "'" + formulas[i][j] : values[i][j];
}
}
range.setValues(values);
}
}
A:
To maintain formula references, you need to modify the formulasAsText() function to accept an input, and also not worry about writing a formula if one is found. This input could be a spreadsheet ID - i.e. the id of the temporary copy - or it could be an array of Sheet objects.
Once you have made these two modifications, you would call the function prior to deleting the non-desired sheets in the temporary copy:
/**
* @param Sheet[] wbSheets An array of Sheets to operate on.
* @param String toPreserve The name of the sheet which should be preserved.
*/
function preserveFormulas(wbSheets, toPreserve) {
if(!wbSheets || !wbSheets.length || !toPreserve)
throw new Error("Missing arguments.");
wbSheets.forEach(function (sheet) {
if ( sheet.getName() === toPreserve ) {
var range = sheet.getDataRange();
// Serialize the cell's current value, be it static or derived from a formula.
range.setValues(range.getValues());
}
});
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Custom Labels and tests
Can I access the value of a custom label during an Apex test? Do I have to use "SeeAllData=true" to get the value? If so, what value do I get back when not using "SeeAllData=true"?
The documentation is silent on these points.
https://help.salesforce.com/apex/HTViewHelpDoc?id=cl_about.htm&language=en_US
A:
Just tested, Test class can access custom label. No need to enable seeAllDate=true.
A:
Custom labels should be accessable during test methods just like custom fields, etc are. I would think a great way to confirm this would be to try it out
This will take 1 minute to test:
@isTest
private class testLabel{
private static testmethod void basicTest(){
String testLbl = Label.<custom label name>;
system.debug(logginglevel.error,testLbl);
}
}
I would but I am not able to get in an org at the moment.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ajax strange error with sending multiple parameter
please check with me where is the error in this ajax code to send 2 parameters:
var xhr = getXhr();
// On défini ce qu'on va faire quand on aura la réponse
xhr.onreadystatechange = function(){
// On ne fait quelque chose que si on a tout reçu et que le serveur est ok
if(xhr.readyState == 4 && xhr.status == 200)
{
selects = xhr.responseText;
// On se sert de innerHTML pour rajouter les options a la liste
//document.getElementById('prjsel').innerHTML = selects;
}
};
xhr.open("POST","ServletEdition",true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
id=document.getElementById(idIdden).value;
fu=document.getElementById("formUpdate").value;
//alert(fu);
var i=1;
xhr.send("id=" +id+", fu="+i);
i cant got the value of fu i don't know why.
thanks
A:
The contents of your xhr.send() need to be URL encoded. For example:
xhr.send("id=1&fu=2");
Basicallly, anything that goes inside the xhr.send() would be the same as the query string you'd set with a GET. In other words, what you have inside send should also work on the end of a URL:
http://www.mysite.com/path/to/script?id=1&fu=2
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get last element between slashes with .htaccess
Assuming a string like http://domain.com/aaaa/bbb/ccc/ddd/
I want to use a .htaccess file to get the last element between slashes, in this case ddd.
I am using:
RewriteRule (.*)/$ ?pt=$1 [L]
But it is not working.
A:
Try this regex:
([^/]+)/$ ?pt=$1 [L]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it possible to declare a method as a parameter in C#?
For example the main method I want to call is this:
public static void MasterMethod(string Input){
/*Do some big operation*/
}
Usually, I would do something like this this:
public static void StringSelection(int a)
{
if(a == 1)
{
return "if";
}
else
{
return "else";
}
}
MasterMethod(StringSelection(2));
But I want to do something like this:
MasterMethod( a = 2
{
if(a == 1)
{
return "if";
}
else
{
return "else";
}
});
Where 2 is somehow passed into the operation as an input.
Is this possible? Does this have a name?
EDIT:: Please note, the MasterMethod is an API call. I cannot change the parameters for it. I accidentally made a typo on this.
A:
You can do this via delegates in C#:
public static string MasterMethod(int param, Func<int,string> function)
{
return function(param);
}
// Call via:
string result = MasterMethod(2, a =>
{
if(a == 1)
{
return "if";
}
else
{
return "else";
}
});
A:
You can do this with anon delegates:
delegate string CreateString();
public static void MasterMethod(CreateString fn)
{
string something = fn();
/*Do some big operation*/
}
public static void StringSelection(int a)
{
if(a == 1)
{
return "if";
}
else
{
return "else";
}
}
MasterMethod(delegate() { return StringSelection(2); });
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get specific version dependencies jars from maven artifactory repository who has "Provided" scope
Is it possible to get specific version dependencies jars from maven artifactory repository who has "Provided" scope after the build.Due to so many webapps and most of them having common dependencies, thought of making all dependencies as "Provided" (So that WEB-INF/lib would be empty) and getting all "provided" jars of specific version from the artifactory repository during deployment (Very first step of deployment is copying the jars in to Tomcat common lib followed by war deployment).If possible please help me by giving model script to do the copy from repository to tomcat common lib before deployment.
Assume app having 3 webapp (webapp1,webapp2 and webapp3) and all using abc1.jar,abc2.jar,abc3.jar.each webapp classloader loading all these 3 for each war to deploy.Instead making them as provided and keeping 3 jars in Tomcat common lib would be appropriate i feel.Now my question is after the maven build, can i get provided jars from repository to copy them from repository to tomcat lib using shell script
Sample pom.xml (Without provided scope)
http://maven.apache.org/maven-v4_0_0.xsd">
4.0.0
com.group.groupid
mSampleJDBCTempPrj
war
0.0.1-SNAPSHOT
mSampleJDBCTempPrj Maven Webapp
http://maven.apache.org
org.springframework
spring-context
3.1.1.RELEASE
cglib
cglib
2.2.2
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901-1.jdbc4</version>
</dependency>
</dependencies>
<build>
<finalName>mSampleJDBCTempPrj</finalName>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.9</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<!-- <includeScope>provided</includeScope> -->
<outputDirectory>/Users/venugopal/Documents/providedDependencies</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
A:
When the idea is, to create an archive, which contains the jars, that are marked with the scope provided in the pom.xml. So if multiple web-apps use these same jars, they can be deployed to the central place in the wen container provider (Tomcat / Jetty / JBoss / etc).
For as far as I know there is no option in Maven to create an archive, for these provided dependencies. Or some other way to extract them easily from the Maven repository.
A question rises Why would you do so? Many projects move these days to Docker or similar solutions. Which deploy just one web-app in one container. So no need for the complexity of searching for commin libraries and placing them upfront on the web container. Etc etc.
Another question Why add complexity. An easier set-up is to add all depended jars to the web-app. As disk space and network speed / capacity, is most of the time not an issue.
Seems the answer Getting jars from scope provided maven web project is already provided
TIP The above sample, shows the usage of the maven-dependency-plugin. It is configured to run during the phase package (<phase>package</phase>).
Use mvn clean package, to let it do it's task.
The pom.xml needed a few small modifications:
This is just a small pom.xml, so package should be pom, as there is no web-app content, Java classes, configuration etc.
In build, the finalName is not needed.
Updated dependency postgresql it's scope with value provided, so at least one dependency is resolved, by the plug-in
Removed pluginManagement which should be used in parent-pom cases, not here. Here it just hides the plug-in. In cases where it is used, the parent-pom defines the plugin configuration for multiple Maven projects. All projects which use the same parent-pom, can include a plugin, with the same version number and configuration, as given in the parent-pom.
Addition
The corrected pom.xml, from the question:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.group.groupid</groupId>
<artifactId>mSampleJDBCTempPrj</artifactId>
<packaging>pom</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>mSampleJDBCTempPrj Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.1-901-1.jdbc4</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.9</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<includeScope>provided</includeScope>
<outputDirectory>${project.build.directory}/providedDependencies</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use :value and v-model on the same element in Vue.js
I would like to update some input fields
so I created an input element:
new Vue({
el: '#app',
data: {
record: {
email: '[email protected]'
},
editing: {
form: {}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input type="text" :value="record.email" v-model="editing.form.email">
<pre>{{ editing.form.email }}</pre>
</div>
In this input element I added :value attr and a v-model
Unfortunately I get an error:
conflicts with v-model on the same element because the latter already
expands to a value binding internally
What is the best solution to fill the input field with data and then update it?
I also tried to add :name="..." instead of :value="..."
http://jsfiddle.net/to9xwL75/
A:
Don't use :value with v-model together.
Use mounted() to update your model and pre-fill input value:
data() {
return {
record: {
email: ''
}
}
},
mounted() {
setTimeout(() => {
this.record.email = '[email protected]'
}, 500)
}
A:
You may want to put the initial/default value on the data object, and two-way binding should work with v-model. Just remove the editing.form.email and try this:
<div id="app">
<input type="text" v-model="record.email">
<pre>{{ record.email }}</pre>
</div>
new Vue({
el: '#app',
data() {
return {
record: {
email: '[email protected]'
}
}
}
})
If you need to populate this field with dynamic values, you could add a handler method and update the input element as the data is fetched:
methods: {
getData() {
axios.get('/some-url')
.then(data => {
this.record.email = data.email;
});
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I launch a new browser window with no toolbars?
I want a hyperlink on my main page to launch an HTML help page in a new browser window. However I want the new window to only have an address bar, i.e. not have a menu, toolbars or status bar, and better still not even have an editable address bar.
I have seen this done on quite a few sites but can't figure out what I need to do to launch the new window in that state.
Any clues?
A:
To expand a little on what ocdecio has above, you can place the window.open call a function accessed from your various hyperlinks, allowing different links to pop up new windows by passing in a different argument to the function.
<a href="#" onclick="openWindow('faq.html');">FAQ</a>
<a href="#" onclick="openWindow('options.html');">Options</a>
<script language='Javascript'>
<!--
// Function to open new window containing window_src, 100x400
function openWindow(window_src)
{
window.open(window_src, 'newwindow', config='height=100, width=400, '
+ 'toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, '
+ 'directories=no, status=no');
}
-->
</script>
A:
<SCRIPT LANGUAGE="javascript">
<!--
window.open ('titlepage.html', 'newwindow', config='height=100,
width=400, toolbar=no, menubar=no, scrollbars=no, resizable=no,
location=no, directories=no, status=no')
-->
</SCRIPT>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Child element of body not taking 100% space when body has min-height 100%
The following code works properly
<!DOCTYPE html>
<html>
<head>
<title>Working</title>
<style type="text/css">
html {
height: 100%;
}
body {
height: 100%; /* !!!!! difference in here */
}
div#main {
min-height: 100%;
background-color: red;
}
</style>
</head>
<body>
<div id="main"></div>
</body>
while a code using min-height instead of height for body prevents #main from occupying space
<!DOCTYPE html>
<html>
<head>
<title>Not working</title>
<style type="text/css">
html {
height: 100%;
}
body {
min-height: 100%; /* !!!!! difference in here */
}
div#main {
min-height: 100%;
background-color: red;
}
</style>
</head>
<body>
<div id="main"></div>
</body>
Weird thing is when doing an inspect in chrome, in both cases body properly takes up 100% space. In min-height case however the child element min-height: 100%; translates to 0. Why does it happen and is there any workaround? I would like the min-height for my web page for background to work properly and expand as needed.
A:
As to "Why does it happen?"
The min-height property only works if an explicit height is set. The spec reads for a percentage:
Specifies a percentage for determining the used value. The percentage
is calculated with respect to the height of the generated box's
containing block. If the height of the containing block is not
specified explicitly (i.e., it depends on content height), and this
element is not absolutely positioned, the percentage value is treated
as '0' (for 'min-height') or 'none' (for 'max-height').
The key point in that is that "If the height of the containing block is not
specified explicitly (i.e., it depends on content height)." When body is set with min-height, it is still depending on content height for calculation, only it does not allow it to fall below the specified size (in your case, 100% of html height which is explicitly set). However, because body is still depending on content to set its height, then div#main cannot calculate min-height because body does not have an explicit height set.
Is a "Workaround" Needed?
It seems that setting body to height: 100% achieves all you want. Whether content is long or content is short.
Response to Comment on html change of background-color
I suspect the reason your fiddle with html having background-color set changes things is because of the notations in this spec (quoted below). By setting that on html it changes the canvas rendering itself:
The background of the root element becomes the background of the
canvas and covers the entire canvas, anchored (for
'background-position') at the same point as it would be if it was
painted only for the root element itself. The root element does not
paint this background again.
For HTML documents, however, we recommend that authors specify the
background for the BODY element rather than the HTML element. For
documents whose root element is an HTML "HTML" element or an XHTML
"html" element that has computed values of 'transparent' for
'background-color' and 'none' for 'background-image', user agents must
instead use the computed value of the background properties from that
element's first HTML "BODY" element or XHTML "body" element child when
painting backgrounds for the canvas, and must not paint a background
for that child element. Such backgrounds must also be anchored at the
same point as they would be if they were painted only for the root
element.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
iPhone MKMapView: set span/region value to show all pins on map
I'm working on a project (platform iOS 7) in which i required current location with stores around 5km, so how to calculate the span/region value to display all stores with current location on map.
MKMapRect zoomRect = MKMapRectNull;
double inset;
for (id <MKAnnotation> annotation in mapVW.annotations)
{
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
MKMapRect pointRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1);
zoomRect = MKMapRectUnion(zoomRect, pointRect);
inset = -zoomRect.size.width * 20;
}
[mapVW setVisibleMapRect:MKMapRectInset(zoomRect, inset, inset) animated:YES];
this is what I'm trying
Thanks
A:
It's not clear what your exact issue is but the following may help:
The calculation of the inset looks wrong. It's setting the inset (padding on the sides) to 20 times the width of the whole zoom area. What you probably want is to set the inset to a small fraction of the entire width. Maybe you meant 0.20 instead of 20.0:
inset = -zoomRect.size.width * 0.20;
You also don't need to repeatedly set the inset inside the for loop since it only depends on the final width. You can move the above line after the for loop before calling setVisibleMapRect.
You mention some issue with the current location. It's not clear what the issue is but maybe you mean that this zooming code doesn't include the current location? If so, maybe the current location hasn't been determined yet when this code is called. Try moving this code to (or also call it from) the didUpdateUserLocation delegate method. Make sure showsUserLocation is YES and that the map view's delegate is set.
By the way: iOS 7 includes the new method showAnnotations:animated: which automatically determines the bounding rectangle for some given annotations and sets the map's visible region for you. It doesn't let you specify a custom inset like you are doing (though the default isn't bad). So instead of the above loop, you would do:
[mapVW showAnnotations:mapVW.annotations animated:YES];
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What are some common C libraries in Linux to use a CD burning device?
I am interested in creating software that uses a CD burning device. I will be writing this code in C under Linux and compiling using GCC.
A:
libburn as the name suggests ;) (and other friend-libraries from the same site). It's used in brasero (GNOME), xfburn (xfce) and cdw.
And well, that's it. Really, I'm not aware of any more libraries.
In fact, it was more common to wrap command-line cdrecord (from cdrtools or cdrkit) but they never provided a shared library; it was just an old unix practice on running external executables (and then parsing their output, ugly). AFAIK it's still used in k3b and a few minor tools but the general trend is migration towards libburn.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jQuery validation, disabling onkeyup for an element
I'm using jQuery validation, I want to disable keyup validation for a certain element so I'm using the code below : -
$("form").validate({
onkeyup: function (element) {
if (element.id == 'tx_username') {
return false;
}
}
This just disables it for everything and not just the desired element. Does anyone know how I can disable the keyup validation for just the element specified. 'tx_username' in this case
A:
Try Something like below.
onkeyup: function (element, event) {
if (event.which === 9 && this.elementValue(element) === "") {
return;
} else {
if (element.id != 'tx_username') {
this.element(element);
}
Referred link - jQuery.validate.js onkeyup = true error
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jQuery - Div follow touchmove/mousemove + autoalign
I want to make a very simple function in my jQuery script. When the finger/cursor touches/clicks on the screen, I want the pages to slide horizontally following the movements of the finger/cursor. I know there is a lot of plugins created by so many people, but I really don't need everybody else's solutions. The image is a visual view of how my HTML looks like. it is really simple.
The jQuery sciprt is obviously not correct, but I hope it would give you an idea about the simple function I need. I don't extra classes or fade-functions or anything.
$(document).live('touchmove' or 'mousemove', function() {
$('div[class=page_*], div[class=page_^]').[follow movements horizontally, and auto align to nearest edge when let go.];
});
Also I want to be able to do the same with one big div, so probably the width-variable of the element moving should be equal to $(window).width();. Actually I think that would be the best idea. I can always put more content inside the big div and make it larger, so keep it with that. It should be more simple to do and to focus on one element only.
A:
So, here is my solution. I've made some changes so that now you can have more than 3 pages.
Also, I've defined a variable named threshold set to the half of a page. If you want to have a threshold bigger or smaller than the hakf of the page you will have to make some more changes.
HTML CODE:
<div class="container">
<div class="wrap">
<div class="page page1"></div>
<div class="page page2"></div>
<div class="page page3"></div>
<div class="page page4"></div>
</div>
</div>
CSS CODE:
.container, .page, .wrap {
width: 300px;
height: 400px;
}
.container {
background: #efefef;
box-shadow: 0px 0px 10px black;
overflow: hidden;
position: relative;
margin: 5px auto;
}
.wrap {
width: 1200px;
position: absolute;
top: 0;
left: 0;
}
.page {
float: left;
display: block;
-moz-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
-o-user-select: none;
}
.page1 {
background: yellow;
}
.page2 {
background: green;
}
.page3 {
background: blue;
}
.page4 {
background: red;
}
As for the CSS code keep in mind that if you want to change the page size you will also have to change the container and wrap size.
JS CODE:
var mouseDown = false, right;
var xi, xf, leftX = 0;
var nPages = $(".page").size();
var pageSize = $(".page").width();
var threshold = pageSize/2;
var currentPage = 0;
$(".container").on("mousedown", function (e) {
mouseDown = true;
xi = e.pageX;
});
$(".container").on("mouseup", function (e) {
if (mouseDown) {
mouseDown = false;
xf = e.pageX;
leftX = parseInt($(".wrap").css("left").split("px")[0]);
if ((e.pageX - xi) < -threshold || (e.pageX - xi) > threshold) {
setFocusedPage();
} else {
restore();
}
}
});
$(".container").on("mouseleave", function (e) {
if (mouseDown) {
mouseDown = false;
xf = e.pageX;
leftX = parseInt($(".wrap").css("left").split("px")[0]);
if ((e.pageX - xi) < -threshold || (e.pageX - xi) > threshold) {
setFocusedPage();
} else {
restore();
}
}
});
$(".container").on("mousemove", function (e) {
if (mouseDown) {
$(".wrap").css({
"left": (leftX + (e.pageX - xi))
});
right = ((e.pageX - xi) < 0) ? true : false;
}
});
function restore() {
$(".wrap").stop().animate({
"left": -(currentPage * pageSize)
}, 200, function () {
leftX = parseInt($(".wrap").css("left").split("px")[0]);
});
}
function setFocusedPage() {
if (leftX >= (-threshold)) { // First Page
currentPage = 0;
} else if (leftX < (-threshold) && leftX >= (-(nPages + 1) * threshold)) { // Second to N-1 Page
(right) ? currentPage++ : currentPage--;
} else if (leftX < -((nPages + 1) * threshold)) { // Third Page
currentPage = nPages - 1;
}
$(".wrap").stop().animate({
"left": -(currentPage * pageSize)
}, 200, function () {
leftX = parseInt($(".wrap").css("left").split("px")[0]);
});
}
Remember here that if you want a different threshold you will have to make some changes especially in the setFocusedPage() function.
Here is my last DEMO
|
{
"pile_set_name": "StackExchange"
}
|
Q:
'undefined reference to 'function'
I have downloaded the library libcomplearn and want to test it in a small example program. But when I link it I get the error undefined reference to ‘function’.
I installed the library to a specific path.
OS: Debian
test.c
#include <stdio.h>
#include "complearn.h"
#include "complearn/complearn-ncd.h"
int main(const int argc, const char * const argv[])
{
printf("Number from my library\n");
CompLearnNcd *ncd = complearn_ncd_top();
return 0;
}
Makefile
FILES = test
LIBPATH = /try/libcomplearn/lib/pkgconfig
OUTPUT = TK_1
LIBNAME = complearn
#--------------------------------------------------
CC = gcc
CFLAGS = -c -Wall `export PKG_CONFIG_PATH=$(LIBPATH) && pkg-config --cflags $(LIBNAME)`
LDFLAGS = -static `export PKG_CONFIG_PATH=$(LIBPATH) && pkg-config --libs --static $(LIBNAME) -llzma`
all: Release
Debug: CFLAGS += -g
Debug: $(OUTPUT)
Release: $(OUTPUT)
$(OUTPUT): $(OUTPUT).o
@echo "started...."
$(CC) -o $(OUTPUT) $(OUTPUT).o $(LDFLAGS)
@echo "done...."
$(OUTPUT).o: $(FILES).c
$(CC) $(CFLAGS) $(FILES).c -o $(OUTPUT).o
clean:
rm -f $(OUTPUT).o $(OUTPUT)
Output
gcc -c -Wall `export PKG_CONFIG_PATH=/try/libcomplearn/lib/pkgconfig &&
pkg-config --cflags complearn` test.c -o TK_1.o
test.c: In function ‘main’:
test.c:9:19: warning: unused variable ‘ncd’ [-Wunused-variable]
CompLearnNcd *ncd = complearn_ncd_top();
^~~
started....
gcc -o TK_1 TK_1.o -static `export
PKG_CONFIG_PATH=/try/libcomplearn/lib/pkgconfig && pkg-config --libs --
static complearn -llzma`
Unknown option -llzma
/usr/bin/ld: TK_1.o: in function `main':
test.c:(.text+0x1c): undefined reference to `complearn_ncd_top'
collect2: error: ld returned 1 exit status
make: *** [makefile:28: TK_1] Error 1
I also tried with the command:
gcc test.c `-L/try/libcomplearn/lib/ -llzma` `pkg-config --cflags --libs glib-2.0`
A:
You say:
I also tried with the command:
gcc test.c `-L/try/libcomplearn/lib/ -llzma` `pkg-config --cflags --libs glib-2.0`
which indicates that you do not understand back-ticks,
since:
`-L/try/libcomplearn/lib/ -llzma`
is not a meaningful use of them. Take the time now to learn their use.
The cause of your linkage failure is the setting:
LDFLAGS = -static `export PKG_CONFIG_PATH=$(LIBPATH) && pkg-config --libs --static $(LIBNAME) -llzma`
in the makefile.
Here you have -llzma within the back-tick expansion:
`export PKG_CONFIG_PATH=$(LIBPATH) && \
pkg-config --libs --static $(LIBNAME) -llzma`
To expand this, the shell executes:
export PKG_CONFIG_PATH=$(LIBPATH)
pkg-config --libs --static $(LIBNAME) -llzma
-llzma is a meaningless option to the pkg-config command, so it fails,
as you see it complain in the make output:
Unknown option -llzma
Just like:
$ pkg-config --cflags --libs zlib -llzma
Unknown option -llzma
As a result, the required linkage options that should be output by:
pkg-config --libs --static $(LIBNAME)
are not output and are not interpolated into the value of LDFLAGS. So the linkage
fails:
test.c:(.text+0x1c): undefined reference to `complearn_ncd_top'
because libcomplearn has not been linked. Correct the setting of your LDFLAGS
to:
LDFLAGS = -static `export PKG_CONFIG_PATH=$(LIBPATH) && pkg-config --libs --static $(LIBNAME)` -llzma
with -llzma following after the back-tick expansion.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Adding my button to google sites
I click edit page on my google site and then add html box where i add this code
<button type="button" onclick="window.open('http://www.google.com','_blank','resizable=yes')" >Click to open Google</button>
But for some reason it doesn't work, although i tested it on some html editors and it worked.
Any ideas?
A:
you can also try this
<a href="www.google.com" targer="_blank"><input type="button" value="Click to open Google" /></a>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it possible to use the same arguments to both decorator and function
I need to understand how I can access the variable that was passed to the function in the decorator.
Let me explain with an example, is it possible to do something like this:
class test(object):
....
@DecoratorClass(myWrapper(self, x))
def myFunction(self, x):
print x
print self.y
At some point an instance of the test-class is created, and myFunction is called from somewhere. I need to path the same argument to myWrapper.
I hope that this is clear enough.
A:
The decorator replaces the function with a callable that wraps it, so the callable will be passed the same parameters as the original function. So, for example:
def Decorator(original_function):
def replacement_function(x):
# You now have 'x' here... do what you want with it.
return replacement_function
@Decorator
def MyFunction(x):
# ...
Note that you will need to delay construction of "myWrapper" until the function is executed (because you will not have the function parameter until then).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
editing 2d lists based on contents in the 2d list
For a homework assignment I have to make a text-based Conway's game of life in python. The rules for it are this.
Any live cell with fewer than two live neighbors dies
Any live cell with two or three live neighbors lives on to the next generation.
Any live cell with more than three live neighbors dies.
Any dead cell with exactly three live neighbors becomes a live cell.
I put the board in a 2d list and i'm having trouble finding out how to loop over each individual element in the list(each cell in the game, dead or alive, '0' or 'X') and check conditions based on the cells around it.
An example of a starting board would be
00000
00000
000X0
000X0
000X0
To start out I am now trying to loop over each element, and check if cell to the right of the current cell is an X or not.
This is the code I made to try and do this. The function next iteration is supposed to return the board with what the next iteration of conway's game of life would be, but for now to figure things out I just want to get it to check the cell to the right of it and change the current cell to an X if the one to the right of it is.
def nextIteration(board):
newBoardTemp = board[:]
newBoard = [board[:] for board in newBoardTemp]
column = 0
for row in newBoard:
column = 0
for item in range(len(row)):
column += 1
item2 = row[column + 1]
if item == item2:
board[item][column] = 'X'
def printBoard(board):
for row in board:
for item in row:
print(item, end="")
print()
def main():
rows = input("Please enter number of rows: ")
columns = input("Please enter number of columns: ")
print()
cellRow = 0
cellRows = []
cellColumns = []
total = 0
#the cellRow and cellColumn will contain all of the inputted rows
#and columns connected by the index value
while cellRow != "q":
cellRow = input("Please enter the row of a cell to turn on (or q to exi\
t): ")
if cellRow != "q":
cellColumn = input("Please enter a column for that cell: ")
cellRows.append(cellRow)
cellColumns.append(cellColumn)
total = total + 1
print()
else:
print()
board = []
#boardTemp will hold a list that contains one row of the entire board
boardTemp = []
for i in range(int(rows)):
boardTemp.append("0")
for i in range(int(columns)):
board.append(boardTemp[:])
for i in range(total):
temp = i
board[int(cellRows[temp - 1])][int(cellColumns[temp - 1])] = "X"
iterations = input("How many iterations should I run? ")
print()
print("Starting Board:")
print()
printBoard(board)
for i in range(int(iterations)):
iterationNumber = 1
nextIteration(board)
print("Iteration", iterationNumber,":")
printBoard(board)
main()
This is the error I get with the starting board that I showed earlier.
File "hw7.py", line 9, in nextIteration
item2 = row[column + 1]
IndexError: list index out of range
A:
for item in range(len(row)):
column += 1
item2 = row[column + 1]
if item == item2:
board[item][column] = 'X'
In fourth iteration of this loop you set item2 to row[5], which is out of range.
If you want to compare two adjacent cells, you should increment column later (in first iteration item == row[0] and item2 == row[2]).
You should also stop a loop earlier.
The following should help with your error:
for item in range(len(row) - 1):
item2 = row[column + 1]
if item == item2:
board[item][column] = 'X'
column += 1
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What might cause a tangy flavor in hummus?
I'm pretty sure that this is an intended flavor; there's a great and authentic middle eastern restaurant nearby and their hummus tastes noticeably tangy. Others in the Yelp reviews have commented on the same flavor, so it's not a bad batch. It's almost as if there's a fermented ingredient that has the same kind of "tang" as kimchi. Their babaganoush doesn't have this same tang.
Is there a secret fermented ingredient in some hummus recipes that might give off this flavor?
A:
[not a definitive answer]
Making good hummus is non-trivial. I think roasting sesame seeds is as volatile as roasting coffee beans with a few seconds or degrees changing the flavour drastically.
It's quite possible the tangy flavour comes from the way they process their sesame seeds. I've had Israeli hummus (from Jerusalem) and it tasted very different from the stuff you get elsewhere. Much smoother and more 'settled' flavour, and likely similar to the tang you describe (almost umami). The ingredients didn't have anything specific listed that could do that. It also could be the lemons or the zest.
Anecdotally, a local hummus manufacturer told me he gets his sesame seeds from that part of middle east because they lead to better tasting hummus.
Next time you're there, please ask the chef. most of the time, they'll share something new with you. (I've been curious as well ever since tasting that particular hummus).
A:
The recipes I've seen include both lemon juice as yogurt. I suppose the tangy flavor comes from the lemon.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is a good tool for unit testing javascript in a maven webapp / liftweb project?
I want to unit test the javascript I have embedded in the webapp portion of my liftweb project. Liftweb is a subset of the maven webapp archetype, so my question applies to that framework as well.
By 'good', I mean that the tests can be integrated into the maven automated testing.
I understand that different browsers support different versions of ecmascript, so I am okay with a testing solution that restricts itself to one specific version.
A:
JSUnit might help with JavaScript testing.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to prevent a secondary HDD from spinning down?
First off I did try the power options setting and it's on 'Never' but that did nothing. The drive still spins down after 15-20 seconds of not being used. I need it to spin all the time because it's more efficient with my way of using it. Also listening to music from that drive is absolutely destroying the drive making it spin up and down all the time causing immense wear and tear. Any ideas on how to stop it from spinning down? Please don't suggest bat files that keep creating editing a file.
Oh and here is the model of the drive: wdc wd10jpvx-22jc3t0 and my OS is Windows 10 64 bit.
A:
You need to change APM settings to max. performance.
CrystalDiskInfo can do a great job at handling APM issues. Under advanced features, you can open a control that handles both AAM/APM settings. In my case, I did not disable the APM features of the drive, a laptop/mobile WD500GB Blue Scorpio that I am using in a tower setup, but I did adjust the APM to "Maximum performance" by setting the control slider to the proper code. This way, no head parking, etc., but of course you could always disable if desired. The APM control is very flexible, a lot of settings in which you can read about here
Additional instructions can be found here
Since I set the APM to 'max performance', adjusting slide control to "FEh", then click 'Enable', the drive now performs as I desire it to, without constantly parking heads and causing delays of program launch, etc. I noticed better performance immediately with my drive, no more delays while waiting for drive to respond from a parked state.
The only thing is that you need to put CrystalDiskInfo to startup so it can change the settings at every start. On recent drives (Western Digital and HGST) modifying the APM fix the problem until you reboot or unplug the drive. After the reset, at least the 2.5 inch drives that I'm testing, APM reverts to default settings and needs to be modified again. Each drive handles APM a bit differently.
On some disks disabling and max (FEh or 254 on some programs) is the same thing, on other drives disabling causes the platters to never spin down and on some drives neither max nor disabling prevents the load/unload of the heads to occur.
So personally I prefer to test the drives APM setting and to put it to the lowest possible that will prevent the head parking from occurring often. I go first with max 254 FEh and check the SMART status, then go to 240 F0h and check the SMART again, to 239 EFh check again, 223 DFh, 207 CFh, and so on (every step is down by 16) until when I check the smart I see the load/unload cycle to be increased by 1. Then I put it to the previous lowest setting where checking the smart did not cause an increase of the parking number. So the disk will keep cool when not in use and won't spin to the max all the time.
P.S. On most Hitachi, Western Digital, HGST drives the lowest setting that does not allow the parking of the heads is C0h / 192.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Difference between Probability Distributions Chi^2 and F (with applications)
My question is, is there anybody that can explain and dumb down the differences of the two different distributions (Chi-squared and F). I have tried doing research on the internet but I can't seem to understand what is being conveyed.
Basically what is the difference in Chi-Squared and F and how are they used in industry.
Now I know that this question is not super clear but I am just trying to gather as much information from experts on here so that I can advance my statistical knowledge.
Any help will be very much appreciated.
Thank you!
A:
F distribution is the distribution of the ratio of two $\chi^2$ distribution variables, as shown in Wiki page. They're both widely used by practitioners. Look up $\chi^2$ test and F-test in Google.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Select subset of delimited string field
My table has a field with data formatted like this:
Term 1~Term 2~Term 3~Term 4~Term 5~Term 6~
All non-blank values contain 6 tilde-separated strings, which may be several words long.
I need to extract the last 2 substrings from this field as part of a query.I'm not interested in splitting the data into multiple records, and I don't have permissions to create a stored procedure.
Thanks in advance for any advice.
A:
DECLARE @Term VARCHAR(100)
SELECT @Term = 'abc~def~ghi~jkl~mno~pqr~'
SELECT RIGHT(@Term, CHARINDEX('~',REVERSE(@Term),CHARINDEX('~',REVERSE(@Term),2)+1)-1)
That will give the last two terms with ~ intact. Note you can wrap REPLACE() around that to put something other than the tilde in there.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to insert seven kind of ids in a column to all values
I have column data. I need to insert ids in another column. Total i have 7 ids. For first 7 values i have to insert these ids and next 7 values, i have to insert same ids and so on.. Can any one please help?
Pay_headID Pay_amount
16414 8000
16415 300
16416 0
16417 200
16418 500
16419 0
16420 0
16414 9000
16415 300
so on ...
A:
you can use CTE and ROW_NUMBER, i have used ordering by Pay_headId:
WITH cte_myTable
AS (SELECT
*,
(ROW_NUMBER() OVER (ORDER BY Pay_headID)) - 1 AS num
FROM myTable)
UPDATE cte_myTable
SET [Pay_headID] =
CASE
WHEN num % 7 = 0 THEN 16414
WHEN num % 7 = 1 THEN 16415
WHEN num % 7 = 2 THEN 16416
WHEN num % 7 = 3 THEN 16417
WHEN num % 7 = 4 THEN 16418
WHEN num % 7 = 5 THEN 16419
WHEN num % 7 = 6 THEN 16420
END
GO
If you want use ordering on how it was inserted, you can set Pay_headIds to null:
update myTable set Pay_headID=null;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pivot SQL Select Result to Desired Output
I am trying to convert a SQL result to desired output for analytic report.
Select statement and output is as follows:
SELECT QID, [Text], [Value] FROM TableA
OUTPUT SINGLE Question(QID)
OUTPUT MULTIPLE Question(QID)
Desired output result needed for report is as follows:
Can we achieve this result using Pivot table or similar way rather than using While and Cursor loop?
Thanks and regards,
Viju
A:
The Above query will not work using PIVOT id qid values are same for all the records as we have to use any aggregate function in pivot
check the below query for reference
DECLARE @TAB TABLE (QID INT,[TEXT] VARCHAR(255),VALUE VARCHAR(255))
INSERT INTO @TAB VALUES (1,'WEAG','SDARG'),(1,'NUM','1'),(1,'ID','1')
,(2,'WEAG','RSTHGEST'),(2,'NUM','2'),(2,'ID','2')
,(3,'WEAG','SREVFGWR'),(3,'NUM','3'),(3,'ID','3')
SELECT * FROM @TAB
SELECT * FROM
(
SELECT T.QID,t.[TEXT],T.VALUE
FROM @TAB T
)A
PIVOT (MAX(VALUE) FOR [TEXT] IN (WEAG,ID) ) AS P
OUTPUT
QID WEAG ID
1 SDARG 1
2 RSTHGEST 2
3 SREVFGWR 3
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JNA 4.2.1 call dll method without params
i use jna 4.2.1
I have a method in the dll which returns a pointer to an object (C++)
basic_hash* getAlgorithmInstance( int algorithm )
basic_hash has the following methods (C++):
void reset ();
void partial (const byte* data, uint64 size);
void finalize (vector_byte& hash);
void hash (const byte* data, uint64 size, vector_byte& hash).
i have interface (java)
public interface HAL extends Library {
HAL INSTANCE = (HAL) Native.loadLibrary(
(Platform.isWindows() ? "HAL" : "libHAL"), HAL.class);
BasicHash getAlgorithmInstance(int i);
}
public static class BasicHash extends Structure {
public BasicHash() {}
public BasicHash(Pointer p) {
super(p);
read();
}
@Override
protected List getFieldOrder() {
return Arrays.asList(new String[] { "reset", "hash", "partial", "finalize" });
}
public interface Reset extends Callback { public void invoke();}
public Reset reset;
public interface Hash extends Callback {public void invoke(byte[] data, long size, byte[] hash);}
public Hash hash;
public interface Partial extends Callback {public void invoke(Pointer data, long size);}
public Partial partial;
public interface Finalize extends Callback {public void invoke(byte[] hash);}
public Finalize finalize;
}
and when I use the method without parameters in main()
HAL lib = HAL.INSTANCE;
BasicHash b = lib.getAlgorithmInstance(0);
b.reset.invoke();
I get an error:
Exception in thread "main" java.lang.Error: Invalid memory access
at com.sun.jna.Native.invokeVoid(Native Method)
at com.sun.jna.Function.invoke(Function.java:374)
at com.sun.jna.Function.invoke(Function.java:323)
at com.sun.jna.Function.invoke(Function.java:275)
at com.sun.jna.CallbackReference$NativeFunctionHandler.invoke(CallbackReference.java:646)
at com.sun.proxy.$Proxy1.invoke(Unknown Source)
at net.erver.ItServer.main(ItServer.java:79)
Why did I receive this error if the method resets the variables within the library? the method itself fulfills without problems (according to developers dll)
EDIT:
vector_byte has definition:
typedef unsigned char byte;
typedef std::vector< byte > vector_byte
and basic_hash has definition:
namespace HAL { namespace algorithms {
HAL_HASH_API enum class State : byte {
Normal,
Finished,
};
class HAL_HASH_API basic_hash
{
public:
virtual ~basic_hash() {}
virtual void reset() = 0;
virtual void partial( const byte*, uint64 ) = 0;
virtual void finalize( vector_byte& ) = 0;
virtual void hash( const byte*, uint64, vector_byte& ) = 0;
bool isFinished() {
return ( _state == State::Finished ? true : false );
}
protected:
State _state;
};
}
}
A:
You need to use plain vanilla struct to pass data between JNA and your library. A C++ class (including a vector template) has a much different memory layout than does a simple C struct.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to achieve smooth drawing with C# (like Paint .NET)?
How Paint .NET can draw so fast using C#? Sample: The ellipse perimeter is drawn while the mouse is being dragged without any visible delay. At a simple windows form application in C# If you use the MouseMove event of a Picturebox and draw an ellipse based on the mouse position, there will be a lot of delay and flickering! So, how they do it so smoothly?
A:
I have no special knowledge of the Paint.Net code, but most likely it's using Double Buffering, and probably implemented by hand on a custom drawing surface rather than the simplistic implementation in the pre-packaged controls.
A:
Paint.NET calls Update() after calling Invalidate() which forces an immediate, synchronous WM_PAINT.
A:
They probably use WPF. It is much much faster than forms.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Putnam Pigeonhole principle problem regarding a 20 person college and 6 courses
Question: A certain college has 20 students and offers 6 courses. Each student can enroll in any or all of the 6 courses, or none at all. Prove or disprove: there must exist 5 students and 2 courses, such that either all 5 students are in both courses, or all 5 students are in neither course.
What I have tried so far: I noticed that $\binom{6}{3} = 20$ which means that each students can pick 3 of the 6 courses.
However, from here I don't know how to proceed. Any hints would be highly appreciated.
A:
The assertion is false. There are, as you saw, $\binom63=20$ ways to choose a set of $3$ of the $6$ courses. Suppose that each student chooses a different set of $3$ courses. Consider any particular pair of courses, say $C_1$ and $C_2$: there are just $4$ other courses, so there are precisely $4$ sets of $3$ courses containing both $C_1$ and $C_2$. Thus, there are only $4$ students taking both $C_1$ and $C_2$. And there are only $\binom43=4$ students taking $3$ of the other $4$ courses, so there are only $4$ students who are taking neither of $C_1$ and $C_2$. In short, for any pair of courses, there are just $4$ students taking both and $4$ students taking neither.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Change column class of div in bootstrap
I've found a number of similar questions but cannot seem to get their solutions to work for me so hopefully posting the specific code will help.
I use Caspio datapages deployed on html pages. On an html page I have a full 12 column div that I need to change to a 9 column div when a link is clicked on. This is because I have a collapsed 3 column div that is opened when the link is clicked.
So what i need:
1) upon page load 3 column div collapsed, 12 column div visible.
2)user clicks link and 3 column div is visible and 12 column div changes
to 9 column div so it is moved to the right of the 3 column div
instead of below it.
The Caspio datapages can get messed up if the css is intense (is random when it happens so I can't describe it in detail) so I need to keep it as simple as possible. If I could change div class="col-md-12" to div class="col-md-9" on the link click that would be great. I've seen other posts with changing column classes but I cannot seem to get them to work.
Here's the main code I'm working with:
<div class="col-md-3" style="overflow-x:hidden;overflow=y:hidden;">
<div id="newcomment" class="collapse">
<caspio deploy code for datapage1>
</div>
</div>
<div class="col-md-12">
<div>
<caspio deploy code for datapage2>
</div>
</div>
<a class="btn page-action" href="#newcomment" style="color:green;" data-toggle="collapse"><i class="fa fa-plus" aria-hidden="true"></i> Add Comment</a>
So if I can change div class="col-md-12" to div class="col-md-9" upon the #newcomment link click that should probably do it. Many thanks in advance-
A:
There are several ways you can do this. Here is one...
$('#btnSwitch').click(function(){
$('.col-md-3').toggleClass('hide');
$('#right').toggleClass('col-md-12 col-md-9');
})
HTML
<div class="container-fluid">
<div class="row">
<div class="col-md-3">
page1
</div>
<div class="col-md-9" id="right">
page2
</div>
</div>
<br>
<button class="btn btn-lg" id="btnSwitch">Switch</button>
</div>
http://www.codeply.com/go/pFNLZqoZUV
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Text indented by 4 spaces isn't completely shown as code
I have recently asked this question: Error while loading custom Android View: Resources$NotFoundException: Resource ID #0x7f060007 type #0x12 is not valid
I have copied the exception's stack trace from InteliJ Console, and I've made sure that it is correctly indented with at least 4 spaces. However, only the first part is shown as code, the rest as normal text:
A:
The lines are using non-breaking spaces in the first column rather than regular spaces:
>>> u'''\
... at myapp.music.organizer.SmallPlayerView.<init>(SmallPlayerView.java:46)
... at java.lang.reflect.Constructor.constructNative(Native Method)
... at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
... '''.splitlines()[1]
u'\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0 at java.lang.reflect.Constructor.constructNative(Native Method)'
Those are U+00A0 NON-BREAK SPACE characters, and those are not recognised as indentation for Markdown purposes.
Remove those and use actual spaces to fix this; I've done so now.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
update failed during plugin installation of wordpress
I'm trying to install a woocommerce plugin on my wordpress website(locally) it is giving such error 'update failed' as you can see in picture,
how to fix this?
A:
Go to wp-content/upgrade directory and change folder permission to 777 (chmod) or in windows make sure that the read only box is uncheck.
That only means you allow that directory to read write and execute without any restrictions.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to pass an array to service stack service from client side using jquery
I have an Array in the javascript object. I am using jquery ajax call to process the object. Using KnockoutJS,{ko.toJSON} I am getting the json string of the javascript object. Then using Json.parse() Passing the string to the ajax call which calls the service stack service. I am using service stack to process the object.
I am getting nothing in testArray in the service
Please guide me to solve this issue. the code snippet is as follows
Why it is giving nothing in test array
//View Model
vmSaveCompanySettings = function () {
var self = this;
self.ClientName = ko.observable("");
self.CompanyContact = ko.observable("");
self.testArray=["1","2"];
};
//Ajax call
function SaveCompanySettings() {
var jsondata = ko.toJSON(objvmSaveCompanySettings, ['ClientName', 'CompanyWebsite','testArray'])
$.ajax({
crossDomain: true,
type: "GET",
dataType: "jsonp",
data: JSON.parse(jsondata),
processdata: true,
success: function (msg) {
if (msg.ErrorMsg == "") {
GetCompanySettings();
}
},
error: function (result) {
}
});
}
'Service Request method in the service stack
Public Class UpdateCompanySettingsRequest
Implements IReturn(Of UpdateCompanySettingsResponse)
Public Property ClientName As String
Public Property CompanyWebsite As String
Public Property testArray As List(Of String)
End Class
A:
In your jQuery ajax call, for the data property, try:
data: JSON.stringify(jsondata),
This has solved issues for me in normal MVC3/4 sites when passing arrays up.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What does "$.something" mean in jquery?
i find it everywhere, like this.
function($) {
$.test = { some code }
}
what does it mean?
A:
Think of $ just like any other variable. For jQuery, it's the jQuery object, which is pretty powerful. But it's just like any other variable; you could write your own $ if you wanted to, for example.
It's an unusual variable name, yes, but there's nothing magical about it. The .something is just a property of the variable $. It's no different than writing obj.something, except the variable name is $ instead.
The other non-alphanumeric character you can use in JavaScript as a variable name is _ (the underscore). It's used in some other libraries, like underscore.js . But again, there's nothing special about using _.
A:
You should think about jQuery code as a division between two ways of calling functions:
Methods on selections. This is the standard "find some elements, do something with them" technique. It's code like $('p').val(), $('div').prepend(), etc.
Methods without selections. These are functions that don't require you to do a selection before calling a function. These are functions like $.ajax, $.param, $.each. For the sake of convenience, they are properties of the global variable $, which is the jQuery library. Often, they aren't jQuery-specific, but are useful pieces of code to include in the library.
A:
the $ variable is an alias to the jQuery object / 'namespace'. So you when you see $.function() you are actually calling a method named 'function' on the jQuery object. In your example code provided an object named test is being attached to the jQuery object. if you wrote $.test = function() { } you would be attaching a function (method) instead of an object.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pysvn installer fails to detect Python installation
I have Python 2.7.2 installed in the default location, C:\Python27.
I've downloaded pysvn 2.7 from http://pysvn.tigris.org/project_downloads.html > Windows installation kits. Pysvn Windows installer aborts on
pysvn requires Python 2.7 to be installed.
Quitting installation
I've tried both installer files, py27-pysvn-svn1612-1.7.4-1321.exe and py27-pysvn-svn1615-1.7.5-1360.exe. Neither of them works.
How can I convince the installer that I have Python 2.7 installed?
How is the installer determining whether pysvn is installed or not?
A:
Did u perhaps install the 64-bit version of Python? If yes: Try the 32-bit installer.
Background: It seems like the 64-bit installer doesn't properly set the correct values in the windows registry (which is the place where PySVN tries to find Python).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
I'm getting KeyError while parsing a data file in python
def loadMovieLens(path='C:\Users\karan\Desktop\ml-100k'):
# Load data
prefs={}
for line in open(path+'/new1.data'):
(user,title,rating,ts)=line.split('\t')[0:4]
prefs[user][title]=float(rating)
return prefs
I'm getting a KeyError while parsing the file.
A:
Your dictionary has no keys yet, so data[user] won't exist. You can have Python add a default value for missing keys by using the dict.setdefault() method:
prefs.setdefault(user, {})[title] = float(rating)
The above tells prefs to add {} (an empty dictionary) as a value for the key named in user if that key doesn't exist yet. Either way, the existing or new value is then returned.
With a few small improvements, the complete function then becomes:
def loadMovieLens(path='C:\Users\karan\Desktop\ml-100k'):
prefs = {}
with open(os.path.join(path, 'new1.data')) as f:
for line in f:
user, title, rating, ts = line.split('\t', 4)[:4]
prefs.setdefault(user, {})[title] = float(rating)
return prefs
I added a with statement (so the file is closed properly when reading is done), used os.path.join() to build the path (so it handles path separators independent of the current operating system) and limited splitting to 4 times.
You could switch to the csv module to handle splitting on tabs too.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Example of linearization for GIT
Take a vector space $V$ (finite dimensional, over the complex numbers), let $G=SL(V)$. The group $G$ acts on $\mathbb{P}V$ and we can linearize its action to an action on the line bundle $\mathcal{O}(1)$. This gives an action on $H^0(\mathbb{P}V,\mathcal{O}(1))$. My question is
as $G$-module, is $H^0(\mathbb{P}V,\mathcal{O}(1))$ isomorphic to $V$ or to $V^{\vee}$?? and why??
A:
By definition $\mathbb{P} V = \mathrm{Proj}\ \mathrm{Sym}(V^\vee)$. Quasi-coherent sheaves on the $\mathrm{Proj}$ are identified with graded modules over the graded ring (modulo torsion). Under this correspondence the sheaf $\mathcal{O}(1)$ goes to the graded module $\mathrm{Sym}(V^\vee)[1]$ (the ring shifted down by 1). The functor of global sections corresponds to taking the degree 0 part of the module, which is just $V^\vee$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
each_with_index desired column output Rails
<% source.strains.each_with_index do |strain, j| %>
<% if (j == (source.strains.size - 1)) %>
<font size="3">Strain <%= strain[0].appendix %> </font>
<% end %>
<% end %>
I need to get output as
If j value is last one of a loop, then i need to print first value of loop (j[0]). Kindly suggest me or correct above script.
A:
Looks like your code is the same as
<font size="3">Strain <%= source.strains.last[0].appendix %> </font>
(Without any loop)
Check out Array#last
But even if you didn't know about last method, making a loop to access last element in collection is kinda weird. You can, at least, do collection[collection.size - 1].
on comment
Then why're you doing strain[0] instead of source.strains[0]? source.strains is your collection and strain is just a current element in the loop. I thought strain is some kind of array too.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
soft delete common attributes with regards to cascade recovery
What type of fields are generally used to accompany soft delete? Any of these, any others?
bool IsDeleted // nice because the default value is 0 (no) just in case
date DateDeleted // is this a common one?
date DateCreated // more of a temporal db aspect
date DateModified // same with respect to created
The reason I ask is that when using soft-deletes, cascading must still be implemented in order to maintain integrity. However, the real trick is not cascade deleting, which is rather easy.
The trick is cascade restoring. On cascade delete, with a soft-delete scenario, all records in the relational graph are flagged as deleted, inactive, whatever the flag is, perhaps the difference is to change the datedeleted to a value from null. On cascade restore, record references must be evaluated to see if the reason they were deleted was a result of a cascade delete related to the record being restored, reactiviated, undeleted.
How are cascade restore operations handled with regards to stored data?
A:
In a case where you want to track not only the results of what has happened, but also when it happened and why, people often use a transaction log.
A transaction log table typically has columns such as: date/time of the event, nature of the event (insert, update, delete,...), and the user and/or process that performed the action. There is also a link between the transaction log and the affected record in the base table. This can be done with a foreign key on the base table to the transaction log table, but it is more common to have the transaction log contain a foreign key to the base table. If the transaction log table is shared amongst various base tables, you'd need a base table indicator plus a base table foreign key.
In your case, if deletions are the main concern, you could restrict log entries to deletions and make a distinction between a cascade delete vs. other deletes. You could (should) also consider using transaction wrappers to write all of the soft deletes (primary plus cascading) at one time. You can include some kind of identifier, like an identity value or a GUID as a "business transaction ID" in your log and place this ID into every entry that is part of the same operation. This gives you a clear indication of what happened, when it happened, why it happened, and which records it happened to. You'll be able to use this information to decide how to reverse any particular transaction, including performing a cascade restore.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
NSData initWithContentsOfURL: options: errorPtr: delegate object?
Is there a way to assign some sort of delegate object when
[[NSData alloc] initWithContentsOfUrl:... options:... errorPtr:...]
is called so that I can monitor percentage complete of a download or is the best way to handle this sort of thing through the use of the asynchronous NSURLConnection stuff?
A:
NSData initWithContentsOfUrl is a synchronized call that is not meant to provide progress info. You should use NSURLConnection asynchronized call instead.
If you want to animate a UIProgressView, you should consider using ASIHTTTPRequest library. It's a very neat library.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jquery CSS calc() function
i came across this page CSS LINK
i could't help but love the idea of that to calculate the outcome of different units...
however i tried this :
$('selector').css({'width':'calc(100%-20px)'});
but it doesn't work... anyone has any ideas how this works , or why doesn't this work?
A:
jQuery supports the calc(). I have used this so many times:
$(".content-section").css('width','calc('+contentSectionWidth+'% - 15px)');
$(".content-section").css('width','calc(100% - 15px)');
A:
jQuery does not support the calc() value, and neither does any of the current browsers.
See a comparison here: http://en.wikipedia.org/wiki/Comparison_of_layout_engines_%28Cascading_Style_Sheets%29
In your example, yo can just use margins on the inner element instead:
<div class="parent"><div class="elem"></div></div>
.parent{
width:100%;
background:green;
}
.elem{
margin: 0 10px;
background:blue;
}
This way, .elem will be 100% - 20px wide.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Symfony2 sql query with DATE_SUB in hours
I want to get from database records from last 12 hours.
I have this in my controler:
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery("SELECT e FROM MainCoreBundle:Event e WHERE e.date >= DATE_SUB(CURRENT_DATE() , 1, 'DAY')");
$statement = $query->getResult();
But i want to make it for 12 hours and now is for 1 day. And when i change it like this:
DATE_SUB(CURRENT_DATE() , 12, 'HOUR')")
I get an error that this method DATE_SUB is only for DAYS and MOUNTHS.
How to get hours? Any other method?
A:
You do not need to register a custom DQL function!
This can be done with standard doctrine but using a better approach.
$em = $this->getDoctrine()->getManager();
$qb = $em->createQueryBuilder();
$results = $qb->select('e')
->from('MainCoreBundle:Event', 'e')
->where('e.date >= :date')
->setParameter('date', new \DateTime('-12 hours'))
->getQuery()
->getOneOrNullResult();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
cron expression to run a webjob at 8 am everyday in azure
I actually require an cron expression to automatically restart an app at 8 am every day. for that I have to create an scheduled webjob in azure but i'm not getting the exact cron expression.
A:
According to your description, if you want to created a scheduled WebJob which will fired at 8:00 AM.
I suggest you could try to use below cron.
At 8:00 AM every day: 0 0 8 * * *
More details about how to set the cron, you could refer to this article.
Result:
Besides, if you want to make sure your web jobs will continue worked. I suggest you should enable the "Always On" setting to be enabled on the app.
About how to enable it, you could refer to below steps:
Notice: This technique is available to Web Apps running in Basic, Standard or Premium mode
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ntldr.mod missing from GRUB2
I use Debian Wheezy on EFI motherboard and need ntldr module in GRUB2 to load bootmgr of Windows 7 installer, because the way it starts on its own (apparently, using the boot sector of the USB flash drive the installer is on) it only installs Windows on MBR-formatted disk. When I install GRUB using grub-install it won't add ntldr.mod to the GRUB modules folder and can't insmod it.
Why? When I only download GRUB package without installation (apt-get download...), the module can be found there. If I add the .mod file from the downloaded package to the installed GRUB's modules folder and then "insmod ntldr" from the GRUB command line, it says something about wrong "ELF magic" (?).
How to do it forcibly?
Is there another way to boot the Windows installer in the "GPT-mode", as
I don't want to format the whole disk into MBR.
A:
You downloaded the grub-pc package, which is for bios booting machines, so the module will not load in the efi version of grub. That module does not exist in the EFI version of grub because it relies on the bios.
If you want to boot the windows installer from a usb stick, then you shouldn't be doing anything with grub; just tell your firmware to boot that drive instead of your hd with grub on it.
A:
I figured out the correct bootloader of Windows is hidden somewhere in the large packed files that come on the installation image. It can be unpacked, put into right boot directory and then loaded with GRUB2 chainloader as usually. I don't get why despite having right loader Microsoft hides it somewhere deep and places the strange one into default boot dir.
It worked for me (though, I downloaded the file provided on the instructions page I found because it was quite some pain to unpack it). Unfortunately, I don't remember details, I found manual somewhere on the web, but the general idea is described.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sign jar with certificate but without private key
I have a basic question about signing a jar file with a provided certificate. I have a certificate(.pem file) that I wish to use to sign a jar. I do not have its private key.
The command that I used till now is: jarsigner -keystore /working/mystore -storepass <keystore password> -keypass <private key password> -signedjar sbundle.jar bundle.jar test. Is there a way to sign the jar without the private key?
A:
No, by definition you need the private key to sign, that's the whole idea. You cannot sign with just the public certificate containing the public key, you can only verify with it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get all users from Azure Portal
Is there an API existing, which gives me details about the users I have in Azure Portal including their profile details?: https://portal.azure.com/#blade/Microsoft_AAD_IAM/UsersManagementMenuBlade/AllUsers
This should be accessed via a script, so no user interaction at all.
Thanks!
A:
AFAIK it's possible using Azure AD Graph API to Get Users.
Related references that covers Graph API, PowerShell, C# ways are listed below:
https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-graph-api
https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-graph-api-quickstart
MVC5 How can I retrieve all users from Azure Active Directory
https://docs.microsoft.com/en-us/previous-versions/azure/ad/graph/api/api-catalog
https://social.msdn.microsoft.com/Forums/en-US/336b0228-d8de-4423-8b65-bdfc2c5665c5/c-pulling-a-list-of-all-azure-active-directory-users-using-graph-api-stuckerrortimeout?forum=WindowsAzureAD
https://docs.microsoft.com/en-us/powershell/module/azuread/get-azureaduser?view=azureadps-2.0
https://gallery.technet.microsoft.com/scriptcenter/Extract-user-list-from-6cb9a93c
https://docs.microsoft.com/en-us/office365/enterprise/powershell/view-user-accounts-with-office-365-powershell
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Compiler error: '.class' expected
String sAge = scan.nextLine();
Scanner scan = new Scanner( System.in );
System.out.print( "what year were you born? >");
int iAge = scan.nextInt (sAge);
final double Cyear = 2014;
final double LEmax = 77.9;
System.out.println( "\nThe percentage of your life you have lived is " + int LEmax );
When I compile this, I get these errors:
C:\Users\PracticeMethods.java:54: error: '.class' expected
System.out.println( "\nThe percentage of your life you have lived is " + int LEmax );
^
C:\Users\PracticeMethods.java:54: error: ';' expected
System.out.println( "\nThe percentage of your life you have lived is " + int LEmax );
What am I doing wrong? Can you help me resolve these errors?
A:
It's just a syntax error. Try this:
System.out.println( "\nThe percentage of your life you have lived is " + LEmax );
Notice that you do not have to say again that LEmax is an int, we specify the type of a variable only when we declare it, not when we use it. Or perhaps you intended to do a cast? if that's the case, then you should write it like this, surrounding the type between ():
System.out.println( "\nThe percentage of your life you have lived is " + (int) LEmax );
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Django orm filter is an element of dict
I'm trying to set a dict of filters for my ORM queryset.
here is my dict:
section = self.kwargs['section'] # hot or new or trending
threshold = {'hot': 'post_upvotes > 50', 'trending': 'post_upvotes__range=(20,50)', 'new': 'post_upvotes < 20'}
return Post.objects.filter(threshold[section])
But it doesn't work.
How can I achieve this ?
A:
Try this:
from django.db.models import Q
threshold = {
'hot': Q(post_upvotes__gt=50),
'trending': Q(post_upvotes__range=(20,50)),
'new': Q(post_upvotes__lt=20)
}
return Post.objects.filter(threshold[section])
Read more about Q objects: https://docs.djangoproject.com/en/1.8/topics/db/queries/#complex-lookups-with-q-objects
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Clause ORDER BY
I have a problem with a select in sql server, i have this table with 2 columns:
a 2
b 1
c 100
d 1
a 100
b 1
c 2
d 1
I want ordered it based on the first column,in this way:
a 2
a 100
b 1
b 1
c 2
c 100
d 1
d 1
But then j want the rows with secondcolumn=100 be moved at the bottom,so:
a 2
b 1
b 1
c 2
d 1
d 1
a 100
c 100
I have tried with clause ORDER BY column1 ASC, (column2=100) ASC,but it didnt work!
Thankyou and greetings.
A:
Actually, you want the rows with 100 in the second column moved to the bottom first, and then ordered by the first column:
order by (case when col2 = 100 then 1 else 0 end),
col1
A:
SELECT *
FROM table1
ORDER BY
CASE
WHEN col2>=100 THEN 1
ELSE 0
END,
col1,
col2
SQLFiddle Example
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Demystifying "chunked level of detail"
Just recently trying to make sense of implementing a chunked level of detail system in Unity. I'm going to be generating four mesh planes, each with a height map but I guess that isn't too important at the moment. I have a lot of questions after reading up about this technique, I hope this isn't too much to ask all in one go, but I would be extremely grateful for someone to help me make sense of this technique.
1 : I can't understand at which point down the Chunked LOD pipeline that the mesh gets split into chunks. Is this during the initial mesh generation, or is there a separate algorithm which does this.
2 : I understand that a Quadtree data structure is used to store the Chunked LOD data, I think i'm missing the point a bit, but Is the quadtree storing vertex and triangles data for each subdivision level?
3a : How is the camera distance usually calculated. When reading up about quadtree's, Axis-aligned bounding box's are mentioned a lot. In this case would each chunk have a collision bounding box to detect the camera or player is nearby? or is there a better way of doing this? (raycast maybe?)
3b : Do the chunks calculate the camera distance themselves?
4 : Does each chunk have the same "resolution". for example at top level the mesh will be 32x32, will each subdivided node also be 32x32. Example below:
A:
1 : I can't understand at which point down the Chunked LOD pipeline that the mesh gets split into chunks. Is this during the initial mesh generation, or is there a separate algorithm which does this.
It does not matter. For example, you can integrate the chunking into your mesh generation algorithm. You can even do this dynamically, so that lower levels are added dynamically (e.g. as player moves closer) using a plasma-like refinement algorithm. You can also generate a high-resolution mesh from artist input or elevation measurement data and aggregate it up into all the LOD chunks at asset finalization time. Or you can mix-and-match. It really depends on your application.
2 : I understand that a Quadtree data structure is used to store the Chunked LOD data, I think i'm missing the point a bit, but Is the quadtree storing vertex and triangles data for each subdivision level?
Not necessarily. The tree just stores information about the geometry and how to render it. This could mean having an vertex/face list at every tree node. More realistically in this day and age, you would store the handles of the meshes/instances in GPU memory.
3a : How is the camera distance usually calculated. When reading up about quadtree's, Axis-aligned bounding box's are mentioned a lot. In this case would each chunk have a collision bounding box to detect the camera or player is nearby? or is there a better way of doing this? (raycast maybe?)
A very cheap and easy option is to use the distance to the centre point of the chunk and then correct it. You know that this distance is always an underestimation: if the centre point is at distance Z, this means that half the chunk is closer than that. What we do not know however is the orientation. If we are viewing a chunk of width w edge-on, the closest bit of the chunk will be at distance Z-w. However, if we are viewing the chunk corner-first, the closest bit will be at distance Z-sqrt(2)*w. If you can live with this uncertainty (you almost always can), you are done. Note that you could also correct for the viewing angle using basic trigonometry.
I prefer to calculate the absolute minimum distance from the camera to the chunk to minimize artifacts. In practice, this means doing a point-square distance test. It's a bit more work then calculating distances to the centre points, but it's not like you'll do a zillion of these every frame.
If you can leverage your physics engine to do this then by all means do so, but you really want to think about it more in terms of "distance query" than "collision".
3b : Do the chunks calculate the camera distance themselves?
It really depends on the design of your engine. I would recommend keeping the leaves relatively light-weight though. Depending on your platform, just the call overhead of having a few thousand terrain-chunks perform their own update every frame can seriously impact performance.
4 : Does each chunk have the same "resolution". for example at top level the mesh will be 32x32, will each subdivided node also be 32x32.
They do not have to, but it's convenient if all chunks take up the same amount of space. Then you can do your (GPU) memory management in units of "chunks". It's also easier to remove / hide the seams between two chunks of different sizes if one resolution is a multiple of the other because they share more vertices. (e.g.: 32x32 and 64x64 is easier to manage than 32x32 and 57x57) (thanks Guiber!). If you have a good reason to vary the chunk geometry size, by all means go for it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
iOS - NSMutableDictionary writeToFile returns YES but plist is not modified
I am trying to save data in a NSMutableDictionary to a plist. Plist is already in the Resources folder. When I am trying to save the data to the plist using following code it returns YES which means data was successfully saved. But when I check the file data is not saved to it.
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"userInfo.plist"]; //3
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]){ //4 {
NSString *bundle = [[NSBundle mainBundle] pathForResource:@"userInfo" ofType:@"plist"]; //5
[fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
}
BOOL b = [self.userInfoArray writeToFile:path atomically: YES];
NSLog(@"status %i ", b);
Anyone have solution of this ?
A:
I think I was looking at the wrong file. Plist file in the Xcode does not change after saving the data. Instead, plist in the simulator is changing.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why different activities appear as separate application in android
I am creating a Jigsaw Puzzle application in android. I have created two activites, activity_jigsaw.xml and activity_level.xml. One activity is created by default (Displaying Hello World!) which I modified and created a new activity by following these steps:
File -> New -> Other -> Android Activity
But when I install the application these two files (and all other activities of the application) are installed as a separate project. But at the same time they are also interlinked. The Java code of the files as follows:
Jisaw.java file contains:
public class Jigsaw extends Activity {
Intent intent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jigsaw);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_jigsaw, menu);
return true;
}
public void play(View v)
{
try
{
intent = new Intent(this, Level.class);
startActivity(intent);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Here Play is a function which is called when an image is clicked.
Level.java file contains:
public class Level extends Activity {
Intent intent;
String level = "";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_level, menu);
return true;
}
public void easy(View v)
{
level = "easy";
intent = new Intent(this, Play.class);
intent.putExtra("level", level);
startActivity(intent);
}
public void medium(View v)
{
level = "medium";
intent = new Intent(this, Play.class);
intent.putExtra("level", level);
startActivity(intent);
}
public void hard(View v)
{
level = "hard";
intent = new Intent(this, Play.class);
intent.putExtra("level", level);
startActivity(intent);
}
}
Functions easy, medium and hard are called when a corresponding image is clicked.
Can somebody please tell me that what I am doing wrong?
Thanks in advance..
Here is the manifest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.maju.jigsawpuzzle"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".Jigsaw"
android:label="@string/title_activity_jigsaw" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Level"
android:label="@string/title_activity_level" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Play"
android:label="@string/title_activity_play" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".PlayBoard"
android:label="@string/title_activity_play_board" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
A:
You probably are defining android.intent.category.LAUNCHER intent category to all the activities in your AndroidManifest.xml, it creates an icon in the app launcher. Activities other than main should not have this intent filter.
Do something like this:
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity android:name=".JigSaw" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Level" />
<activity android:name=".Play" />
<activity android:name=".Playboard" />
</application>
EDIT:
As you just posted, you are indeed doing that, just remove the intent filter from other activities.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Instrument looks strange when I use malloc
I have created a project and use Instrument to watch the live bytes.
I've done the following:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
char *byte = (char *)malloc(10000000);
}
The live bytes in Instruments was keep in 650KB.
The Instrument cannot observe the allocation of malloc methods?
Or apple doesn't limit the size of this allocation?
Thanks!
A:
If you never use the memory malloc allocated, the compiler can optimize away the allocation completely.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Redirect any directory URL to a file in that directory, using htaccess
Writing a little CMS.
http://mydomain.com/(somefolder)/ should become
http://mydomain.com/(somefolder)/filename
and
http://mydomain.com/(somefolder)/(somefolder2)/ should become
http://mydomain.com/(somefolder)/(somefolder2)/filename
and so on recursively. If recursion is too involved, I'd be happy with the two example directory levels.
filename is some fixed string I'll type into .htaccess when I decide what it should be :)
A bonus would be if I can save one redirect if the directory url is lacking a trailing /. Possible?
A:
You can use this rule in your root .htaccess:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+?)/$ /$1/filename [L]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Problem with lxfonts
When I compile this
\documentclass{article}
\usepackage{lxfonts}
\begin{document}
$\mathcal{A}$
\end{document}
I get
an "incomplete" calligraphic "A".
If I use other fonts, everything seems fine.
Any idea about this?
A:
It is just as it is designed; you may consier it a bug or a feature, but that one is the shape of the calligraphic A of the LX fonts I designed.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Mantel Test Z-statistic
I am using the mantel.test() function in the "ape" package in R to compare the similarity of two matrices. The function returns a p-value and Z-statistics. While the p-value is understandable, but I am not sure what the significance of the Z-statistics is. i.e Does positive high Z-statistic value means that both matrices are similar, or the similarity can only be described if the p-value is <0.001 and is independent of Z-statistic?
http://svitsrv25.epfl.ch/R-doc/library/ape/html/mantel.test.html
A:
For the Mantel test, the z score is the sum of the products of the corresponding elements of the matrices...so don't confuse it with the standard z-score based on the normal distribution.
The problem with the z-score (sensu Mantel) is that the value depends on the magnitude of your measured variables (kind of like covariance) and is, thus, hard to interpret. So one usually uses a normalized Mantel cofficient, rM, [calculated in the same way as Pearson's product moment correlation coefficient, r,...and interpreted in the same way (on a scale from -1 to 1...albeit the magnitude tends to be downward biased relative to a standard correlation coefficient)]. A positive rM would indicated positive correspondence and a negative rM would indicate a negative correspondence, but be sure to look at the P-value to determine if the value is greater (or less) than would be expected based on the randomized matrices.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How delete row without deleting its _ID column value?
i want save number of _ID column in sqlite if its row deleted
if( deleting row in sqlite table without delete _ID column if it "_ID" declared as `INTEGER PRIMARY KEY`== true)
{How() ;}
else{do_not_vote_this_question_down();} .
thanks in advance !
A:
Using this as a guide to how to use SQL updates in SQLite, you shouldn't delete the row, instead update the values of all other columns to be null.
The SQL to achieve this would look like the below:
UPDATE YourTable SET column1 = null, column2 = null WHERE someCondition = 'value'
Update is used because the ID column of a row represents the unique identifier of a record. If you need to keep this value, you are updating that row, as deleting the row by design will remove all references to that ID.
I question why you need to clear out the data but keep the ID - if you are looking to mark something as "deleted" but keep it for historical purposes, a column should be added called "deleted" that is default false, and then set to true (if you do need to re-access this row).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is my JSON created via the `Factory` different from the one i am getting from `API`.
My mock stub get's escaped properly, but the API response
one is not getting escaped.
Below is my Mock stub factory.
require 'faker'
FactoryGirl.define do
factory :account do |f|
f.name {Faker::Name.name}
f.description {Faker::Name.description}
end
factory :account_json, class: OpenStruct do
send :'@type' , "accountResource"
createdAt "2014-08-07T14:31:58"
createdBy "2"
updatedAt "2014-08-07T14:31:58"
updatedBy "2"
accountid "2055"
name "Test"
description "Something about Test"
disabled "false"
end
end
Below is spec where i am building my Factory stub and trying to compare it with API response.
it "can find an account that this user belongs to" do
account = Account.find( id: 2055, authorization: @auth )
hashed_response = FactoryGirl.build(:account_json).marshal_dump.to_json
expect(account.to_json).to eq(hashed_response.to_json);
end
API Response and Stub
FactoryGirl Stub
expected: "\"{\\\"@type\\\":\\\"accountResource\\\",\\\"createdAt\\\":\\\"2014-08-07T14:31:58\\\",\\\"createdBy\\\":\\\"2\\\",\\\"updatedAt\\\":\\\"2014-08-07T14:31:58\\\",\\\"updatedBy\\\":\\\"2\\\",\\\"accountid\\\":\\\"2055\\\",\\\"name\\\":\\\"Test\\\",\\\"description\\\":\\\"Something about Test\\\",\\\"disabled\\\":\\\"false\\\"}\"
API response
got: "{\"@type\":\"accountResource\",\"createdAt\":\"2014-08-07T14:31:58\",\"createdBy\":2,\"updatedAt\":\"2014-08-07T14:31:58\",\"updatedBy\":2,\"accountid\":2055,\"name\":\"Test\",\"description\":\"Something about Test\",\"disabled\":false}"
Why is my JSON created via the Factory different from the one i am getting from API.
A:
You are converting hashed_response to_json twice - once in the second and once in the third line of your spec. Remove one of the to_json method calls.
For example:
2.0.0-p247 :005 > {"@type" => "accountResource"}.to_json
=> "{\"@type\":\"accountResource\"}"
2.0.0-p247 :006 > {"@type" => "accountResource"}.to_json.to_json
=> "\"{\\\"@type\\\":\\\"accountResource\\\"}\""
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Grails how to change the current locale
How can I change the current locale ?
I tried to put controller/action?lang=de but my locale is still en_US
I tried to override the value using this piece of code:
def key = "org.springframework.web.servlet.DispatcherServlet.LOCALE_RESOLVER"
def localeResolver = request.getAttribute(key)
localeResolver.setLocale(request, response, new Locale("de","DE"))
Nothing changed.
I tried to override the value using this piece of code:
import org.springframework.web.servlet.support.RequestContextUtils as RCU;
RCU.getLocaleResolver(request).setLocale(request, response, new Locale("de","DE"))
And... nothing happened. i still got my locale set to en_US.
Any idea to change the locale ?
A:
According to the chapter 10. Internationalization of the Grails documentation, Grails supports i18n out of the box and you should indeed be able to change the locale using the lang parameter:
By default the user locale is detected
from the incoming Accept-Language
header. However, you can provide users
the capability to switch locales by
simply passing a parameter called lang
to Grails as a request parameter:
/book/list?lang=de
Grails will automatically switch the
user locale and store it in a cookie
so subsequent requests will have the
new header.
But sometimes you may want to preset the default language because not all your applications will be in english. To do this, all you have to do is to set your localeResolver in your resources.groovy spring configuration file as shown below:
beans = {
localeResolver(org.springframework.web.servlet.i18n.SessionLocaleResolver) {
defaultLocale = new Locale("de","DE")
java.util.Locale.setDefault(defaultLocale)
}
}
Now, without more details, I can't say why using the lang parameter isn't working in your case. Just in case, how do you know that the locale is still en_US?.
A:
Do you try to change locale in application root url (eg. http://localhost:8080/myapp/?lang=de)?
In Grails basic setup trying to change locale in application root url does not work. Grails change locale in localChangeInterceptor which is called before all controllers are called. When you access application root url, no controller is called as can be seen in default UrlMappings.
That's why changing locale in application root url does not work. If you try to change url in some controller, it works.
Current locale is stored under key org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME in http session. You can check it there.
Correct solution is to map root url to some controller in UrlMappings.
A:
As far as I understand the way you are checking the locale "request.locale" is wrong, it gives the locale of browser, not the locale of grails applciation.
You should use "LocaleContextHolder.locale".
In 2.0.3 it changes the locale by simply passing parameter lang=someLocale.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I insert a decimal point before the last three digits of a number?
I have a number and need to add a decimal to it for formatting.
The number is guaranteed to be between 1000 and 999999 (I have covered the other possibilities in other ways, this is the one I can't get my head around). I need to put a decimal before the last 3 digits, for example:
1000 -> 1.000
23513 -> 23.513
999999 -> 999.999
How can I do this?
A:
And yet another way for fun of it ;-)
my $num_3dec = sprintf '%.3f', $num / 1000;
A:
Here is another solution just for the fun of it:
In Perl substr() can be an lvalue which can help in your case.
substr ($num , -3 , 0) = '.';
will add a dot before the last three digits.
You can also use the four arguments version of substr (as pointed in the comments) to get the same effect:
substr( $num, -3, 0, '.' );
I would hope it is more elegant / readable than the regexp solution, but I am sure it will throw off anyone not used to substr() being used as an lvalue.
A:
$num =~ s/(\d{3})$/.$1/
That says: Take a block of 3 digits (that must be anchored at the END of the string) and replace them with a "." followed by whatever was just matched.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Linq with optional WHERE options
I have a .Net function that accepts 3 parameters, all optional. Something like this:
public List<MyObject> Search(string colour, string size, string name)
{
var result = (from c in MyTable where .... select c).ToList();
}
My question is, what is the best way to do the where part. Would the best be to create dynamic linq? What's the best pattern, within linq, to have optional where parameters?
So, in SQL, something like this:
SELECT *
FROM MyTable
WHERE (@colour <> '' AND colour = @colour)
AND (@size <> '' AND size = @size)
AND (@name <> '' AND name = @name)
But I am hoping there a neater, more acceptable pattern for doing this within linq.
A:
Simply chain Where clauses with checking for null
var result = context.MyTable
.Where(t => color == null || color == t.Color)
.Where(t => size == null || size == t.Size)
.Where(t => name == null || name == t.Name)
.ToList()
A:
In such cases, I would advise you to use the PredicateBuilder to generate your queries. You can copy the code from here or you could install the LinqKit Nuget Package.
Using this code will allow you to generate dynamic queries on the fly and will prevent you from writing tons of if/else statements.
Statements like...
p => p.Price > 100 &&
p.Price < 1000 &&
(p.Description.Contains ("foo") || p.Description.Contains ("far"))
will be generated by this kind of code:
var inner = PredicateBuilder.False<Product>();
inner = inner.Or (p => p.Description.Contains ("foo"));
inner = inner.Or (p => p.Description.Contains ("far"));
var outer = PredicateBuilder.True<Product>();
outer = outer.And (p => p.Price > 100);
outer = outer.And (p => p.Price < 1000);
outer = outer.And (inner);
I think this is fairly neat and it will also give you an understanding on how powerful expressions can be.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Protractor E2E angular "angular could not be found on the window"
I have a strange error after running my tests in angular project Error: Error while waiting for Protractor to sync with the page: "angular could not be found on the window". My Protractor configuration looks like this:
require('coffee-script').register();
exports.config = {
seleniumServerJar: './node_modules/protractor/selenium/selenium-server-standalone-2.39.0.jar',
seleniumAddress: 'http://localhost:4444/wd/hub',
capabilities: {
browserName: 'chrome'
//'chromeOptions': {
// 'args': ['--disable-extensions']
//}
},
specs: [
'*_spec.coffee'
],
allScriptsTimeout: 10000000000,
baseUrl: 'http://localhost:9003/',
jasmineNodeOpts: {
isVerbose: false,
showColors: true,
includeStackTrace: true,
defaultTimeoutInterval: 10000000000
}
};
And test:
loginPage = require './pages/log_in_page'
describe 'Log In', ->
it 'shows after login', ->
loginPage()
.setEmail('[email protected]')
.setPass('a46s75d4as765d4a6s7d54as76d5as74das76d5')
Get info from page:
module.exports = ->
@email = element By.css '.test-i-login'
@password = element By.css '.test-i-password'
@setEmail = (name) =>
@email.sendKeys(name)
this
@setPass = (number) =>
@password.sendKeys(number)
this
this
There're some similar issues on github, but there I didn't find a solution working for me. Thx for answering.
A:
Changing framework option in Protractor config to 'jasmine2' fixed this issue for me.
See this thread for further information.
A:
In my scenario, login page is non angular, tried the below way, worked out for me
browser.driver.findElement(By.id('username')).sendKeys('binnu');
A:
Protractor is built to test Angular applications, meaning web pages that have an ng-app tag in the body of the HTML and controllers that correspond to Angular code in a Javascript file.
The reason Protractor is so useful is that Angular applications run asynchronously, meaning that they're not always finished loading when the web page loads. Most testing frameworks would try to click things, type things, etc. before the page is completely ready. Protractor detects all the Angular processes running in the background so that you don't accidentally do something before everything is ready.
What Protractor is telling you is that it didn't find any Angular processes running on the page. Your page might work fine, but it just doesn't rely on Angular in a way that Protractor can recognize.
That doesn't mean Protractor can't test the page. You can access regular WebDriver commands using browser.driver.any_webdriver_command_here(). You'll just be missing out on the fantastic synchronizing capabilities that Protractor offers.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
OSX "open" command to create new files with an app
So, I like to use TextWrangler for editing code in OSX, and I tend to use a terminal to control my workflow. Generally, I use a bash alias:
alias text='open -a /Applications/TextWrangler.app'
However, this method doesn't allow me to open new files on the fly from the prompt. For example, if I typed emacs newfile.py it would temporarily create a new file, but not touch it until I actually saved the file. With my alias, though, if newfile.py doesn't exist, then I get an error, and have to manually touch the file then open it.
Any suggestions on hidden ways to use open that solve this? Or third-party alternatives to the open command? Or is this just a fundamental limitation of GUI-based editors?
A:
I think you want a full-fledged shell script rather than just an alias. Make a file with these contents:
if [ -e "$1" ]; then
open -a TextWrangler -- "$1"
else
touch "$1"
open -a TextWrangler -- "$1"
fi
Save it as text somewhere in your PATH and chmod it to be executable and you're golden.
If you really want to make it so that the file doesn't exist if you don't save it, that's trickier. I think you'll have to do something like this:
if [ -e "$1" ]; then
open -a TextWrangler -- "$1"
else
touch "$1"
open -a TextWrangler -- "$1"
sleep 1
rm "$1"
fi
This will actually create the file and then delete it one second later. The app will still have the file open, though, so that when you save it will be recreated.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it possible to solve a PDE that depends on explicit evaluations of only 1 parameter, and if so, how?
A while back, I asked how to solve a very ugly little duckling of a PDE, and if it could be done. No response. This is a better way repeating the question - if I have a PDE, where inside the equation itself, I have a term that is fixed in one parameter, but not the other, is the PDE solvable, and if so, how?
Say I have,
$$
G_{t}(t,x) = a(x)G_{x}(t,0)+b(x)G_{x}(t,1)+c(x)G_{x}(t,x);\\
G(\infty,x)=0; \quad G(0,x)=f(x),
$$
where $f$ is some polynomial. Is there any way to solve this, or is it a lost cause?
Now, I understand one may be tempted to say
$$\frac{\text{d}u}{\text{d}x}(1,t)=g(t),$$
for some arbitrary function, $f$, but what then? It is certainly the case that $f(t)$ is in no way arbitrary, so how could one justify treating it as such?
EDIT: Upon having it pointed out that a PDE without boundary conditions can be nearly anything, I have decided to write a simplification of the problem that spawned this, to which I know the conditions constraining it. There aren't many.
A:
In the original wording of the question was :
$$u_t(x,t)=ax\frac{\partial u}{\partial x}(x,t)+bx^2\frac{\partial u}{\partial x}(1,t), \tag 1$$
Let $\quad\frac{\partial u}{\partial x}(1,t)=f(t).\quad$ Of course, at this point $f(t)$ is an unknown function which has to be determined later.
Rearranging :
$$-ax\frac{\partial u}{\partial x}+\frac{\partial u}{\partial t}=bx^2f(t)\tag 2$$
The method of characteristic consists in solving the system of ODEs :
$$\frac{dx}{-ax}=\frac{dt}{1}=\frac{du}{bx^2f(t)}$$
A first family of characteristic curves comes from $\quad \frac{dx}{-ax}=\frac{dt}{1}.\quad$ Solving it leads to :
$$xe^{at}=c_1$$
A second family of characteristic curves comes from $\quad \frac{dt}{1}=\frac{du}{bx^2f(t)}$.
$du=bx^2f(t)dt=b\left(c_1e^{-at} \right)^2f(t)dt$
$$u-bc_1^2 \int_0^t e^{-2a\tau}f(\tau)d\tau =c_2$$
The general solution of Eq.$(2)$ comes from $\quad c_2=F(c_1)$
where $F$ is an arbitrary function to be determined according to some boundary or initial condition.
$$u-bc_1^2 \int_0^t e^{-2a\tau}f(\tau)d\tau =F\left(xe^{at}\right)$$
$$u(x,t)=bx^2e^{2at} \int_0^t e^{-2a\tau}f(\tau)d\tau +F\left(xe^{at}\right)$$
$\frac{\partial u}{\partial x}=2bxe^{2at} \int_0^t e^{-2a\tau}f(\tau)d\tau +e^{at}F'\left(xe^{at}\right)$
$f(t)=\left(\frac{\partial u}{\partial x}\right)_{x=1}=2be^{2at} \int_0^t e^{-2a\tau}f(\tau)d\tau +e^{at}F'\left(e^{at}\right)$
So, we have to solve for $f(t)$ the integral equation :
$$f(t)=2be^{2at} \int_0^t e^{-2a\tau}f(\tau)d\tau +e^{at}F'\left(e^{at}\right)$$
Thus $f(t)$ depends on the arbitrary function $F$. This makes difficult the solving in the general case. That is why if a boundary or initial condition is specified, the problem becomes simpler.
For example, if the initial condition is :
$$u(x,0)=u_0(x),$$
we have $u(x,0)=bx^2e^{2at} \int_0^0 e^{-2a\tau}f(\tau)d\tau +F\left(xe^{0}\right)=F(x).$
The function $F$ is determined : $\quad F(x)=u_0(x)\quad$ which is a given function.
$$u(x,t)=bx^2e^{2at} \int_0^t e^{-2a\tau}f(\tau)d\tau +u_0\left(xe^{at}\right)$$
and the integral equation becomes :
$$f(t)=2be^{2at} \int_0^t e^{-2a\tau}f(\tau)d\tau +e^{at}u_0'\left(e^{at}\right)$$
$e^{-2at}f(t)= \int_0^t e^{-2a\tau}f(\tau)d\tau +e^{-at}u_0'\left(e^{at}\right)$
Differentiating leads to :
$-2ae^{-2at}f(t)+e^{-2at}f'(t)=e^{-2at}f(t)-ae^{-at}u_0'\left(e^{at}\right)+au_0''\left(e^{at}\right)$
Thus, $f(t)$ is solution of the differential equation :
$$f'(t)-(1+2a)f(t) =-ae^{at}u_0'\left(e^{at}\right)+ae^{2at}u_0''\left(e^{at}\right)$$
This is a first order linear ODE. Since $u_0(t)$ is a known function, this ODE can be solved. The solution includes an arbitrary constant. Putting back the solution into the integral equation allows to determine the constant.
So, the function $f(t)$ is known now. With this, the solution of the PDE according to the initial condition is :
$$u(x,t)=bx^2e^{2at} \int_0^t e^{-2a\tau}f(\tau)d\tau +u_0\left(xe^{at}\right)$$
Meanwhile, the wording of the question has change which makes it much more complicated because it involves some non-explicit functions $a(x)$ , $b(x)$ and $c(x)$. The integrals of those functions will appear into the calculus thanks to the method of characteristics. Probably an explicit solution will no longer be obtained for all kind of functions $a(x)$ , $b(x)$ and $c(x)$. Nevertheless, the simpler case above shows the method to tackle the problem.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
mongoose / mongodb date save castError
I am getting this error when just getting a document from the database and then immediately saving it. It is accepted on the initial insert though, and looks like the date fields are empty even though they are required.
{ stack: [Getter/Setter],
message: 'Cast to date failed for value "[object Object]"',
name: 'CastError',
type: 'date',
value:
{ millisecond: 0,
second: 0,
minute: 0,
hour: 0,
day: 21,
week: 38,
month: 8,
year: 2011 } }
This is the schema and query code that fails:
var Event = new Schema({
id : { type: String, index: true }
, msg : { type: String, lowercase: true, trim: true }
, triggerOn : { type: Date, required: true }
, createdOn : { type: Date, required: true }
, triggered : { type: Boolean, required: true }
});
exports.pullAndUpdateTest = function(){
var Model = mongoose.model('Event');
Model.find({ triggered: false }, function (err, docs) {
if (err){
console.log(err);
return;
}
docs.forEach(function(doc, index, array){
//date both appear to be null here
console.log(doc.triggerOn); //=> null / prints blank
console.log(doc.createdOn); //=> null / prints blank
doc.triggered = true;
doc.save(function(err){ console.log(err)});
});
});
}
A:
Date.js is a very cool library, however the default implementation will create a mess in Node.js applications when working with MongoDB. I'd recommend you to use safe_datejs. You will be able to use Date.js function but you're gonna have to convert the Date values to a Date.js object before calling any of the Date.js magical functions.
Example:
var safe_datejs = require('safe_datejs');
var today = new Date();
var unsafeToday = today.AsDateJs(); // Converting to Date.js object
var unsafeTomorrow = unsafeToday.clone().add({days:1}); // Work with Date.js a little
var tomorrow = unsafeTomorrow.AsRegularDate(); //converted back safe to be used with MongoDB
To change culture specific attributes, use safe_datejs.DateType.CultureInfo
More info: https://github.com/firebaseco/safe_datejs
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Symbol of a partition
I have a series of subsets that form a set however each subset is actually a partition. Currently I use the conventional subset symbol when writing the appropriate notation and then note the subsets are partitions in the following (or preceding) text. However, it would be good to have a symbol that refers to a partition naturally just like any other set theory notion. Yet, despite looking in various sources and I haven't come across anything so far. So is there a conventionally accepted maths notation/symbol for a partition? Personally have no problem allocating a suitable symbol if none currently exists but I don't want to 'reinvent the wheel' if I can avoid it.
A:
When you don't want to overload your text with long notations, you can define your own notations.
For instance
Let ${\mathbf{Part}}(X)$ be the set of partitions of $X$.
And later,
Let $(X_i)_{i\in I} \in \mathbf{Part}(X)$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Spring 5 WebFlux Mono and Flux
In Spring 5 I just know Spring WebFlux Handler method handles the request and returns Mono or Flux as response.
@Component
public class HelloWorldHandler {
public Mono<ServerResponse> helloWorld(ServerRequest request) {
return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN).body(BodyInserters.fromObject("Hello World"));
}
}
But I have no idea what means Mono and Flux and how it works with the WebFlux Handler.
Can any one simply explain
1.What means Mono and Flux.
2.How it works with the WebFlux Handler.
Thanks in advance.
A:
Webflux is all about reactive programming, which in summary means that business logic is only executed as soon as the data to process it is available (reactive).
This means you no longer can return simple POJO's, but you have to return something else, something that can provide the result when it's available. Within the reactive streams initiative, this is called a Publisher. A Publisher has a subcribe() method that will allow the consumer to get the POJO when it's available.
A Publisher (for example Publisher<Foo>) can return zero or multiple, possibly infinite, results. To make it more clear how many results you can expect, Project Reactor (the reactive streams implementation of Pivotal) introduced two implementations of Publisher:
A Mono, which will complete after emitting a single result.
A Flux, which will emit zero or multiple, possibly infinite, results and then completes.
So, basically you can see Mono<Foo> as the reactive counterpart of returning Foo and Flux<Foo> as the reactive counterpart of Collection<Foo>.
For example:
Flux
.just(1, 2, 3, 4)
.map(nr -> nr * 2)
.subscribe(System.out::println);
Even though the numbers are already available (you can see them), you should realize that since it's a Flux, they're emitted one by one. In other cases, the numbers might come from an external API and in that case they won't be immediately available.
The next phase (the map operator), will multiply the number as soon as it retrieves one, this means that it also does this mapping one by one and then emit the new value.
Eventually, there's a subscriber (there should always be one, but it could be the Spring framework itself that's subscribing), and in this case it will print each value it obtains and print it to the console, also, one by one.
You should also realize that there's no particular order when processing these items. It could be that the first number has already been printed on the console, while the third item is hasn't been multiplied by two yet.
So, in your case, you have a Mono<ServerResponse>, which means that as soon as the ServerResponse is available, the WebFlux framework can utilize it. Since there is only one ServerResponse expected, it's a Mono and not a Flux.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jQuery resource for Win32 programmer
I know programming in general but always been doing either Delphi, VB 6 or C#.net! Now I must do web-dev and must do it fast! I haven't written a hello world in JavaScript yet and must learn jQuery because there are some charts that I must show in my web-app and looks like I must know JavaScript and jQuery to do that.
So I am looking for a jQuery resource that during its course or maybe at the first chapter gives us also a jump start on minimum JavaScript knowledge too. Some book or resource that I can hopefully sit and read through it in one day like 12 hours and after then learn enough to be able to use it and embed those darn charts and graphs into my web-app.
What do you suggest ?
A:
The basics of Javascript as a language are actually fairly straightforward, particularly if you've got a background in several other languages as you have. You'll find it immediately familiar with curly braces and other syntax that you'll recognise from elsewhere.
If you've worked with C#, you will hopefully have been exposed to lambda functions or closures. These are very important in Javascript, where they are key for the event-driven code that drives most websites, and in particular if you're using a library like jQuery, where they are used for virtually everything. You need to get a strong handle on how these functions work if you're going to make head or tail of jQuery.
The other thing to be aware of is that Javascript's object handling works a bit differently to the other languages you's used to. There are similarities, but if you try to write your classes and objects in the way you're used to, you will get some unexpected results. See What type of language is JavaScript for more info on this.
Beyond that, I don't think you'll have a problem with the syntax.
The other thing to worry about is the DOM -- ie the browser's API which is accessed via Javascript. The DOM is not technically part of the Javascript language, but it is inextricably linked to it, and is as much part of the learning challenge as the language itself. jQuery abstracts a fair amount of the DOM away from you, but it still helps to know it.
Hope that helps get you started.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to digitize polygons from georeferenced raster file
I used QGIS to georeference a raster file of a custom US map. The map has features which are not strictly defined by state borders. I would like to digitize the map by creating contiguous borders for each feature. I tried that a few different way, but none of them really worked:
traced the borders with polylines, and digitizing with the Polygonizer plugin. The plugin kept crashing.
used Conversion > Raster > Vectorize (Raster to Vector). That one worked, but the result was many overlapping polygons for each feature, each with slightly different borders.
I have somewhere between 50-100 different raster images to process, which is why any automated solution is highly preferred. I'm new to GIS software, but could easily pre-process the images if needed, either manually or with a custom script (using Python/PIL, ImageMagick, Photoshop batch processing or similar tools).
Thanks for any pointers!
Original
Georeferenced image
A:
What you could do is:
In the original image, fill each area with a unique color, e.g. with Gimp
Georeference
Run Raster to Vector
Clean up the polygon geometries manually
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Best/more standard graph representation file format? (GraphSON, Gexf, GraphML? )
What's the standard graph representation file format or otherwise the most used one?
I would say one of these three:
GraphSON
GEXF
GraphML
but it would be great if anyone could point out the advantages/weaknesses from each of them.
A:
The answer ultimately lies with the size of your problem and what your are trying to achieve.
For example, none of those formats can handle billions of vertices whereas some dedicated large-scale graph analytics frameworks such as Spark or GraphLab-Create can.
GraphML and GEXF are roughly equivalent, both XML based. GraphML is standard and supported in a lot of graph librairies such as NetworkX, igraph, Boost Graph Library, Graph-tool, JGraphT, Gephi. GraphSon is not popular.
To draw your GraphML or GEXF graphs, you can use Gephi or Tulip (GEXF only).
A:
I think JGF is a good candidate here too.
I evaluated a lot for a recent project and this came out on top. Specifically, I liked:
Trivial to parse and generate
Able to include arbitrary extra data for any node, edge, or graph.
Well specified, and can be parsed by more than one existing project.
http://jsongraphformat.info/
https://github.com/jsongraph/json-graph-specification
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to build an installer to update an ASP.NET's web.config, DLL, files, etc
I have an add-on for a commercial ASP.NET website. My add-on requires people to merge entries into their web.config, add/overwrite existing files, and add some DLL files to the bin folder.
Is there a good and safe way to create an installer than can do this with a wizard type of installation? It would really help non-technical people install the add-on easily. Maybe even a web-based installer would be good?
Any help or suggestions would be greatly appreciated.
A:
Had a similar problem...
Web.Config
Created a .NET command line program that you can call from your installer passing it the web.config path and other args to match what I'm trying to do
In the command line program you can then modify the web.config to your needs... Below is an example of setting a connection string & the stmp from address in a web.config
public static void SetConnectionString(string name, string connString, string webConfigPath)
{
string directory = System.IO.Path.GetDirectoryName(webConfigPath);
VirtualDirectoryMapping vdm = new VirtualDirectoryMapping(directory, true);
WebConfigurationFileMap wcfm = new WebConfigurationFileMap();
wcfm.VirtualDirectories.Add("/", vdm);
System.Configuration.Configuration webConfig = System.Web.Configuration.WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
webConfig.ConnectionStrings.ConnectionStrings[name].ConnectionString = connString;
webConfig.Save();
}
public static void SetFromAddress(string email, string webConfigPath)
{
string directory = System.IO.Path.GetDirectoryName(webConfigPath);
VirtualDirectoryMapping vdm = new VirtualDirectoryMapping(directory, true);
WebConfigurationFileMap wcfm = new WebConfigurationFileMap();
wcfm.VirtualDirectories.Add("/", vdm);
System.Configuration.Configuration webConfig = System.Web.Configuration.WebConfigurationManager.OpenMappedWebConfiguration(wcfm, "/");
System.Net.Configuration.MailSettingsSectionGroup mailSettings = (System.Net.Configuration.MailSettingsSectionGroup)webConfig.GetSectionGroup("system.net/mailSettings");
mailSettings.Smtp.From = email;
webConfig.Save();
}
Installer
I used NSIS (http://nsis.sourceforge.net/Main_Page). Use HM NIS Edit as a good starting point as it has a wizard that will generate scripts for you. From there you can modify up the scripts to your needs. In my case I called my command line program after the files where installed. Example NSIS script below.
Section "My Config Wizard" SecWizard
ExecWait '"$INSTDIR\Bin\My.Config.Wizard.exe" "$INSTDIR"'
Return
SectionEnd
Good luck! Need more examples just hit me up. :P
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pattern problem, It includes the text outside (.*?)
I need to get the link out of a bunch of HTML and im using patterns for that. The problem is that the pattern includes the text before and after (.*?). Should it do that? I thought it only includes the text between boundaries.
Ive modified the code a little bit and now it only includes the quote.
Pattern p = Pattern.compile("http://cdn.posh24.se/images/:profile(.*?)");
Matcher m = p.matcher(splitStrings[0]);;
[http://cdn.posh24.se/images/:profile/088484075fb5b4418f5cb8814728decab",...
that is the output, this is the expected: [http://cdn.posh24.se/images/:profile/088484075fb5b4418f5cb8814728decab
A:
You can do something like this:
Pattern p = Pattern.compile("http://cdn.posh24.se/images/:profile(.*?)(?=\")");
This sequence is called Positive Look Ahead. You can find a good explanation here.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
iOS WebTryThreadLock crash
I have a crash in my app that I cannot debug for the life of me. When plugged in and debugging from Xcode on a device and NSZombieEnabled on, I do not receive the crash. When I unplug and run the app on its own, or turn of NSZombieEnabled, it crashes every time.
Here is what I get when I turn off NSZombieEnabled: EXC_BAD_ACCESS
bool _WebTryThreadLock(bool), 0x58a260: Multiple locks on web thread not allowed! Please file a bug. Crashing now...
1 _ZL17_WebTryThreadLockb
2 _ZL14WebRunLoopLockP19__CFRunLoopObservermPv
3 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__
4 __CFRunLoopDoObservers
5 __CFRunLoopRun
6 CFRunLoopRunSpecific
7 CFRunLoopRunInMode
8 _ZL12RunWebThreadPv
9 _pthread_start
10 thread_start
Here is the stack trace from the test flight:
0 App 0x001ff492 testflight_backtrace + 142
1 App 0x001fffac TFSignalHandler + 212
2 libsystem_c.dylib 0x349e9538 _sigtramp + 48
3 JavaScriptCore 0x34b66aee WTFReportBacktrace + 146
4 WebCore 0x33ed5676 _ZL14WebRunLoopLockP19__CFRunLoopObservermPv + 30
5 CoreFoundation 0x33b39b4a __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 18
6 CoreFoundation 0x33b37d86 __CFRunLoopDoObservers + 258
7 CoreFoundation 0x33b3804e __CFRunLoopRun + 614
8 CoreFoundation 0x33abb4dc CFRunLoopRunSpecific + 300
9 CoreFoundation 0x33abb3a4 CFRunLoopRunInMode + 104
10 WebCore 0x33f7712e _ZL12RunWebThreadPv + 402
11 libsystem_c.dylib 0x349a0c1c _pthread_start + 320
12 libsystem_c.dylib 0x349a0ad7 thread_start + 7
I have had this crash before, and I have resolved it by throwing in the line to my viewDidLoad method on one of the view controllers where the crashing was occurring:
[[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow:0.01]];
This line is not helping now.
The process that causes the app to crash is:
Present share view controller,
Dismiss share view controller,
Switch tab view on tabViewController,
Press button which presents share2 view controller
I am not doing any background processing or changing any UI, the crash happens RIGHT when you hit the button that presents the share2 view controller. This crash was not happening a few days ago and I have tried to revert all of my changes to find the cause of the issue, but I had no luck.
I have also scoured the internet for this error, and none of the info I found has helped me.
Any advice to point me in the right direction would be greatly appreciated, thanks!
A:
I ended up re-doing the navigation between the 2 problem screens and I have not had the problem since.
My answer: always use Apples navigation and don't try to build your own :P
|
{
"pile_set_name": "StackExchange"
}
|
Q:
File With Same Name From different folder in ios
I am using "xcode 6.1.1" and "cocos2dx-3.2".
I need to access same file name from different folder.
In Resource i have 3 folder "A,B and C" and all this folder contain image with same name "1.png".
If i need to access 1.png of folder "A" ,How i can do this in cocos2dx please help?
following code is working fine in Android but not working in iOS
helpImage->setTexture("A/1.png");
Thanks.
A:
Didn't used cocos for some time now, but it is pretty easy to do.
Do this:
Prepare directory with your game data. Here lets call it "GameData". Pick name you like.
Drag and drop that directory to the xcode, probably best location is Supporting files. Dialog will show up. Select "Create folder references", deselect copy if needed.
And basically you are done. During build process all resources will be copied to bundle with paths as is in that directory "GameData". So you can have files with same name without problems.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Interest of double licenses CC-BY-SA + ODbL for SVG maps
This is a split refactored from an older post containing too many questions about licenses in SVG Tiny 1.2 using RDFa as suggested by Patrick Hoefler. See also question Embed two licenses within SVG.
Introduction
LittleMap.org aims to allow anyone editing maps for blinds. I think the best way to share maps is as SVG files.
CC-BY-SA + ODbL
I also think providing two licences is fine for derivative work: user can choose the licence he/she prefers.
ODbL v1.0 to allow insertion of our data into OpenStreetMap database.
CC-BY-SA-4.0 because:
CC-BY is a well-known license.
SA to insure the derivative data will still stay open (as for ODbL).
4.0 is the latest version and should be better than previous versions (?)
Questions
To allow people inserting our data into OSM, do we require to use ODbL?
Is CC-BY-SA enough for OSM compatibility?
Else, what could be the advantage of CC-BY-SA in our case?
Does CC-BY-SA prevent OSM data to be inserted within our maps?
Is it correct to license XML file (SVG) under a Database license?
What about SVG file generated from OSM data?
A:
Let's give this a try then.
1. To allow people inserting our data into OSM, do we require to use ODbL?
Not necessarily. This is what OSM has to say on the topic:
We are only interested in 'free' data. We must be able to release the data with our OpenStreetMap License. Obviously we are allowed to use public domain data sources, of which there are quite a few, but beyond that, it gets more complicated.
So as long as your license is either very liberal (e.g. CC0) or compatible with the ODbL, it should be fine. Which brings us to your next question.
2. Is CC-BY-SA enough for OSM compatibility?
According to this discussion on the OSM wiki, I'm going to say no. The main problem seems to be the attribution requirement, although I don't quite understand why. However, when you license your data under both CC-BY-SA as well as ODbL, there should be no problem.
3. Else, what could be the advantage of CC-BY-SA in our case?
As you pointed out yourself, Creative Commons licenses are currently the best-known open licenses. A lot of time has gone into refining them over time, and since version 4.0 they are perfectly suited to cover data and not just content.
4. Does CC-BY-SA prevent OSM data to be inserted within our maps?
This is where things start to get interesting.
OSM state on their copyright page:
If you alter or build upon our data, you may distribute the result only under the same licence.
However, the ODbL states:
4.4 Share alike.
a. Any Derivative Database that You Publicly Use must be only under the terms of:
i. This License;
ii. A later version of this License similar in spirit to this License; or
iii. A compatible license.
So as long as CC-BY-SA 4.0 is deemed a "compatible license", all is well.
5. Is it correct to license XML file (SVG) under a Database license?
Well, I guess it depends. If your SVG is a creative work (such as a painting or drawing), then no. If it is just simple geometric shapes, then yes.
What about SVG file generated from OSM data?
If they are generated automatically, there's probably no creative process involved, so it should be fine to assume that a database license always fits.
This last question is actually a great example of one of the big advantages of CC-BY-SA 4.0: You simply don't have to care if your content is a database or a creative work, because the license covers both.
Disclaimer: I am not a lawyer, this is just my own personal assessment. I'm happy about any input and feedback :)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Obtain rendered grayscale image of text as a matrix
I want to render a given string as a grayscale image and subsequently perform some simple manipulations on it. I am aware of the text() function. Unfortunately this requires opening a graphical device. For my purpose it would be a lot more convenient and efficient to directly store the grayscale image in a matrix instead.
What is an efficient way of obtaining a matrix representation of the rendered grayscale image of a given string?
A:
The magick package as suggested by Richard Telford was key to solving the question:
# Load the package
require(magick)
# Create white canvas initializing magick graphical device
img <- image_graph(width = 140, height = 40, bg = "white", pointsize = 20,
res = 120, clip = TRUE, antialias = TRUE)
# Set margins to 0
par(mar = c(0,0,0,0))
# Initialize plot & print text
plot(c(0,1), axes = FALSE, main = "", xlab = "", ylab = "", col = "white")
text(0.95, 0.42, "Test", pos = 4, family = "mono", font = 2)
# Close the magick image device
dev.off()
# Convert to grayscale & extract pixelmatrix as integers
img <- image_convert(img, colorspace = "gray")
target <- drop(as.integer(img[[1]]))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I find out the name of this street?
The image below comes from a page from the 1940 US Census:
(Full size image here.)
The page header from the Census is a poor scan. While I can make out the location as Washington DC, I'm unsure as to the ward:
(Full size image here.)
Can anyone decipher the street, either from the scan or deductively based on the information in the Census header?
A:
Have you tried looking on nearby census sheets? The same street name often appears on multiple sheets, where it might be clearer.
UPDATE
I looked on the DC map near 8th and Underwood (some of the first streets in the enumeration district of your image) and spotted Rittenhouse street. I bet that's what that is.
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.