PHP str_replace not working, single qoute
my problem is frustrating, i'm taking cover art from itunes' API. This is
the code to take the song's artist and name and to retrieve the artwork:
$str = $song[0];
$artist_name = $song[0];
$posted = preg_replace('/ -.*/', '', $artist_name);
$manual_referer = 'http://itunes.com/';
$itunes_song = str_replace("'", '', $str);
$args = array(
'term' => $itunes_song,
'entity' => 'song',
'limit' => '1',
);
echo $song_itunes;
$url = "https://itunes.apple.com/search?";
foreach ($args as $key => $val) {
$url .= $key . '=' . rawurlencode($val) . '&';
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $manual_referer);
$body = curl_exec($ch);
curl_close($ch);
$json = json_decode($body, true);
$results = $json['results'];
foreach ($results as $result) {
$res = $result['artworkUrl100'];
}
now, my problem is: Let's say the song's name is: T Pain - 5 O'Clock,
because the system have a problem with songs with the single quote, i did
these two lines:
$itunes_song = str_replace("'", '', $str);
and
'term' => $itunes_song,
but the output of $itunes_song is: T Pain - 5 O'Clock when it's need to be
T Pain - 5 OClock (without the single quote).
i have no idea what i'm doing wrong here, can anyone help me please? :(
Saturday, 31 August 2013
Servlets beginner
Servlets beginner
I am studying a JEE course at the moment and I am on the module with
servlets.
Included in the course are simple sample servlets.
This may sound dumb but I cant get any of them to work either by
themselves or in netbeans on the glassfish server. I have tried dropiing
them in the web pages folder in the project and also I replaced the
content of the index.jsp file with WelcomeServlet.html content. The
example I will use her is the first one and the most simple called
WelcomeServlet.
The function of the servlet is that when the user pressed the "get html
document" button the program should retrieve the document from the .java
file. However when I press the button I get this error
HTTP Status 404 - Not Found type Status report
messageNot Found
descriptionThe requested resource is not available.
GlassFish Server Open Source Edition 4.0
Here is the code in question. WelcomeServlet.html
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Fig. 17.6: WelcomeServlet.html -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Handling an HTTP Get Request</title>
</head>
<body>
<form action = "/advjhtp1/welcome1" method = "get">
<p><label>Click the button to invoke the servlet
<input type = "submit" value = "Get HTML Document" />
</label></p>
</form>
</body>
</html>
WelcomeServlet.java
// Fig. 16.5: WelcomeServlet.java
// A simple servlet to process get requests.
package com.deitel.advjhtp1.servlets;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class WelcomeServlet extends HttpServlet {
// process "get" requests from clients
protected void doGet( HttpServletRequest request,
HttpServletResponse response )
throws ServletException, IOException
{
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
// send XHTML page to client
// start XHTML document
out.println( "<?xml version = \"1.0\"?>" );
out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
"XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
"/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );
out.println(
"<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
// head section of document
out.println( "<head>" );
out.println( "<title>A Simple Servlet Example</title>" );
out.println( "</head>" );
// body section of document
out.println( "<body>" );
out.println( "<h1>Welcome to Servlets!</h1>" );
out.println( "</body>" );
// end XHTML document
out.println( "</html>" );
out.close(); // close stream to complete the page
}
}
If anyone out there can get this code running please help me to do the same.
I am studying a JEE course at the moment and I am on the module with
servlets.
Included in the course are simple sample servlets.
This may sound dumb but I cant get any of them to work either by
themselves or in netbeans on the glassfish server. I have tried dropiing
them in the web pages folder in the project and also I replaced the
content of the index.jsp file with WelcomeServlet.html content. The
example I will use her is the first one and the most simple called
WelcomeServlet.
The function of the servlet is that when the user pressed the "get html
document" button the program should retrieve the document from the .java
file. However when I press the button I get this error
HTTP Status 404 - Not Found type Status report
messageNot Found
descriptionThe requested resource is not available.
GlassFish Server Open Source Edition 4.0
Here is the code in question. WelcomeServlet.html
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- Fig. 17.6: WelcomeServlet.html -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Handling an HTTP Get Request</title>
</head>
<body>
<form action = "/advjhtp1/welcome1" method = "get">
<p><label>Click the button to invoke the servlet
<input type = "submit" value = "Get HTML Document" />
</label></p>
</form>
</body>
</html>
WelcomeServlet.java
// Fig. 16.5: WelcomeServlet.java
// A simple servlet to process get requests.
package com.deitel.advjhtp1.servlets;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class WelcomeServlet extends HttpServlet {
// process "get" requests from clients
protected void doGet( HttpServletRequest request,
HttpServletResponse response )
throws ServletException, IOException
{
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
// send XHTML page to client
// start XHTML document
out.println( "<?xml version = \"1.0\"?>" );
out.println( "<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
"XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
"/TR/xhtml1/DTD/xhtml1-strict.dtd\">" );
out.println(
"<html xmlns = \"http://www.w3.org/1999/xhtml\">" );
// head section of document
out.println( "<head>" );
out.println( "<title>A Simple Servlet Example</title>" );
out.println( "</head>" );
// body section of document
out.println( "<body>" );
out.println( "<h1>Welcome to Servlets!</h1>" );
out.println( "</body>" );
// end XHTML document
out.println( "</html>" );
out.close(); // close stream to complete the page
}
}
If anyone out there can get this code running please help me to do the same.
C# UnauthorizedAccessException in File.Copy
C# UnauthorizedAccessException in File.Copy
I am brushing up on my C# so I decided to write a program that I can use
to easily import photos that I take. A little background...I shoot photos
in JPEG and RAW and then go through and pick through the JPEGs since they
are smaller and easier to handle/preview. I then import only those RAW
files that are worth messing with in post production.
I wanted to write a simple program to copy the RAW files from one
directory that match the JPEGs that I've sifted through in another.
Here is the code:
static void Main(string[] args)
{
Console.WriteLine("Enter the JPEG Origin Directory: ");
string originDirectory = @"C:\Users\Greg\Pictures\Summer 2013\Back
Bay\testJPEG";
Console.WriteLine("Enter the RAW Origin Directory: ");
string copyDirectory = @"C:\Users\Greg\Pictures\Summer 2013\Back
Bay\testRAW";
Console.WriteLine("Enter the RAW Import Directory: ");
string rawCopyDirectory = @"C:\Users\Greg\Pictures\Summer
2013\Back Bay\testRAWImport";
char[] delimiterChars = { '_', '.' };
List<string> filesToCopy = new List<string>();
List<string> CopiedFiles = new List<string>();
foreach (var filePath in Directory.GetFiles(originDirectory))
{
Console.WriteLine("Filepath: '{0}'", filePath);
string[] words = filePath.Split(delimiterChars);
filesToCopy.Add(words[1]);
}
filesToCopy.ForEach(Console.WriteLine);
foreach (var copyFilePath in Directory.GetFiles(copyDirectory))
{
string[] delimited = copyFilePath.Split(delimiterChars);
if (filesToCopy.Contains(delimited[1]))
{
Console.WriteLine("Copied: '{0}'", copyFilePath);
string fileName = Path.GetFileName(copyFilePath);
string sourcePath = Path.GetDirectoryName(copyFilePath);
string targetPath = rawCopyDirectory;
string sourceFile = System.IO.Path.Combine(sourcePath,
fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(sourcePath, destFile, true);
}
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
Everything seems to be working as I'd expect when I write all the
variables to the console, however I'm getting an exception on Copy.File
that indicates the files are read only. I checked, and they aren't,
however the folder itself is, and despite my best efforts I cannot unflag
my test folders as readonly. Any help would be appreciated, I've pasted
the exception log below.
System.UnauthorizedAccessException was unhandled
HResult=-2147024891
Message=Access to the path 'C:\Users\Greg\Pictures\Summer 2013\Back
Bay\testRAW' is denied.
Source=mscorlib
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalCopy(String sourceFileName, String
destFileName, Boolean overwrite, Boolean checkHost)
at System.IO.File.Copy(String sourceFileName, String destFileName,
Boolean overwrite)
at ConsoleApplication1.Program.Main(String[] args) in
C:\Users\Greg\documents\visual studio 2010\Projects\Photo
Importer\Photo Importer\photoImporter.cs:line 56
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly,
String[] args)
at System.AppDomain.nExecuteAssembly(RuntimeAssembly assembly,
String[] args)
at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
at
System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext
activationContext, String[] activationCustomData)
at
System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext
activationContext)
at System.Activator.CreateInstance(ActivationContext
activationContext)
at
Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
I am brushing up on my C# so I decided to write a program that I can use
to easily import photos that I take. A little background...I shoot photos
in JPEG and RAW and then go through and pick through the JPEGs since they
are smaller and easier to handle/preview. I then import only those RAW
files that are worth messing with in post production.
I wanted to write a simple program to copy the RAW files from one
directory that match the JPEGs that I've sifted through in another.
Here is the code:
static void Main(string[] args)
{
Console.WriteLine("Enter the JPEG Origin Directory: ");
string originDirectory = @"C:\Users\Greg\Pictures\Summer 2013\Back
Bay\testJPEG";
Console.WriteLine("Enter the RAW Origin Directory: ");
string copyDirectory = @"C:\Users\Greg\Pictures\Summer 2013\Back
Bay\testRAW";
Console.WriteLine("Enter the RAW Import Directory: ");
string rawCopyDirectory = @"C:\Users\Greg\Pictures\Summer
2013\Back Bay\testRAWImport";
char[] delimiterChars = { '_', '.' };
List<string> filesToCopy = new List<string>();
List<string> CopiedFiles = new List<string>();
foreach (var filePath in Directory.GetFiles(originDirectory))
{
Console.WriteLine("Filepath: '{0}'", filePath);
string[] words = filePath.Split(delimiterChars);
filesToCopy.Add(words[1]);
}
filesToCopy.ForEach(Console.WriteLine);
foreach (var copyFilePath in Directory.GetFiles(copyDirectory))
{
string[] delimited = copyFilePath.Split(delimiterChars);
if (filesToCopy.Contains(delimited[1]))
{
Console.WriteLine("Copied: '{0}'", copyFilePath);
string fileName = Path.GetFileName(copyFilePath);
string sourcePath = Path.GetDirectoryName(copyFilePath);
string targetPath = rawCopyDirectory;
string sourceFile = System.IO.Path.Combine(sourcePath,
fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(sourcePath, destFile, true);
}
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
Everything seems to be working as I'd expect when I write all the
variables to the console, however I'm getting an exception on Copy.File
that indicates the files are read only. I checked, and they aren't,
however the folder itself is, and despite my best efforts I cannot unflag
my test folders as readonly. Any help would be appreciated, I've pasted
the exception log below.
System.UnauthorizedAccessException was unhandled
HResult=-2147024891
Message=Access to the path 'C:\Users\Greg\Pictures\Summer 2013\Back
Bay\testRAW' is denied.
Source=mscorlib
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalCopy(String sourceFileName, String
destFileName, Boolean overwrite, Boolean checkHost)
at System.IO.File.Copy(String sourceFileName, String destFileName,
Boolean overwrite)
at ConsoleApplication1.Program.Main(String[] args) in
C:\Users\Greg\documents\visual studio 2010\Projects\Photo
Importer\Photo Importer\photoImporter.cs:line 56
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly,
String[] args)
at System.AppDomain.nExecuteAssembly(RuntimeAssembly assembly,
String[] args)
at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
at
System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext
activationContext, String[] activationCustomData)
at
System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext
activationContext)
at System.Activator.CreateInstance(ActivationContext
activationContext)
at
Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
CKEditor 4 and nonstandard HTML element
CKEditor 4 and nonstandard HTML element
Here is a nonstandard HTML element that I defined (AngularJS makes this
easy):
<exercise id="Sample Exercise" language="Scala" lectureId="5437"> This is
the text of the lecture </exercise>
If I use this element in an HTML document, each time I switch from
CKEditor's rendered mode to source mode a new empty paragraph is added
between each of the block elements in the document:
<p> </p>
The 2nd time I switch, I get two insertions:
<p> </p>
<p> </p>
The 3rd time I switch, I get three insertions between each block-level
element, etc:
<p> </p>
<p> </p>
<p> </p>
Can anyone suggest a workaround?
Here is a nonstandard HTML element that I defined (AngularJS makes this
easy):
<exercise id="Sample Exercise" language="Scala" lectureId="5437"> This is
the text of the lecture </exercise>
If I use this element in an HTML document, each time I switch from
CKEditor's rendered mode to source mode a new empty paragraph is added
between each of the block elements in the document:
<p> </p>
The 2nd time I switch, I get two insertions:
<p> </p>
<p> </p>
The 3rd time I switch, I get three insertions between each block-level
element, etc:
<p> </p>
<p> </p>
<p> </p>
Can anyone suggest a workaround?
What "encoding" POI supports ?
What "encoding" POI supports ?
What "encoding" POI supports ?
I am using POI XSLF API to convert PPTX file to PNG image. My PPTX file
contain some UNICODE characters like - inəˈvâSHən but when
PPTX is converted to image it just make those UNICODE characters as
rectangle boxes after converting to image. Any thought please ? I really
need to get this done.
Does not look like it supports - UTF8 otherwise would have properly
converted those UNICODE characters properly.
Not sure what encoding is used by POI.
What "encoding" POI supports ?
I am using POI XSLF API to convert PPTX file to PNG image. My PPTX file
contain some UNICODE characters like - inəˈvâSHən but when
PPTX is converted to image it just make those UNICODE characters as
rectangle boxes after converting to image. Any thought please ? I really
need to get this done.
Does not look like it supports - UTF8 otherwise would have properly
converted those UNICODE characters properly.
Not sure what encoding is used by POI.
Trouble using cuechange event and track metadata (HTML5 video)
Trouble using cuechange event and track metadata (HTML5 video)
I've Googled and search for a few days, but I can only find HTML5 video
track examples that talk about subtitles, and the ones I've found aren't
really complete. Basically, what I would like to do is the following:
-When I enter a cue, I need to access the data for the cue.
-The text data (at least I think it's the text...) contains a number. That
number corresponds to an img id elsewhere in my document. I do something
to the image then.
This seems like it should be really simple, but I'm not exactly sure where
to start. I'm using Jquery.
Here are some snippets of my code:
In my $(document).ready function, I have the following...
var t = $("#track1")[0];
t.addEventListener("cuechange", function () {
var mycue = this.track.cues[0];
var imgnum = mycue.text;
var image = $("img#" + txt);//I'm not worried about this part yet...I
never get here
//perform actions on image...
});
My html video tag looks like this:
<video id="Video1" controls='controls' width="100%" autoplay>
<source src="videos/video-part1.mp4" type="video/mp4" >
<track id="track1" kind="metadata" src="test.vtt" srclang="en-us" />
HTML5 Video is required for this example. </video>
And my Webvtt file looks like this (The numbers below the time ranges are
the slide numbers I need to use)
WEBVTT
Test1
00:00:00.000 --> 00:00:23.999
00001
Test2
00:00:24.000 --> 00:01:19.999
00121
Test3
00:01:20.000 --> 00:01:39.999
00793
When I debugged my code in Chrome the first few times, there didn't appear
to be any cue data associated with the track (I checked the cues elsewhere
in the code and they were empty). The cuechange event is also not being
hooked. After a while, Chrome started giving me the error about
referencing text tracks across domains. I don't know why it suddenly
started doing that.
But anyway, in short...
-I don't know how to bind something to the cuechange event correctly
(apparently), or the event where you enter a cue either for that matter.
-I don't know how to access the data I need to use.
Just so you know, I also tried kind="captions" and kind="subtitles".
Neither one of those worked for me either. Some help would be lovely. :)
I've Googled and search for a few days, but I can only find HTML5 video
track examples that talk about subtitles, and the ones I've found aren't
really complete. Basically, what I would like to do is the following:
-When I enter a cue, I need to access the data for the cue.
-The text data (at least I think it's the text...) contains a number. That
number corresponds to an img id elsewhere in my document. I do something
to the image then.
This seems like it should be really simple, but I'm not exactly sure where
to start. I'm using Jquery.
Here are some snippets of my code:
In my $(document).ready function, I have the following...
var t = $("#track1")[0];
t.addEventListener("cuechange", function () {
var mycue = this.track.cues[0];
var imgnum = mycue.text;
var image = $("img#" + txt);//I'm not worried about this part yet...I
never get here
//perform actions on image...
});
My html video tag looks like this:
<video id="Video1" controls='controls' width="100%" autoplay>
<source src="videos/video-part1.mp4" type="video/mp4" >
<track id="track1" kind="metadata" src="test.vtt" srclang="en-us" />
HTML5 Video is required for this example. </video>
And my Webvtt file looks like this (The numbers below the time ranges are
the slide numbers I need to use)
WEBVTT
Test1
00:00:00.000 --> 00:00:23.999
00001
Test2
00:00:24.000 --> 00:01:19.999
00121
Test3
00:01:20.000 --> 00:01:39.999
00793
When I debugged my code in Chrome the first few times, there didn't appear
to be any cue data associated with the track (I checked the cues elsewhere
in the code and they were empty). The cuechange event is also not being
hooked. After a while, Chrome started giving me the error about
referencing text tracks across domains. I don't know why it suddenly
started doing that.
But anyway, in short...
-I don't know how to bind something to the cuechange event correctly
(apparently), or the event where you enter a cue either for that matter.
-I don't know how to access the data I need to use.
Just so you know, I also tried kind="captions" and kind="subtitles".
Neither one of those worked for me either. Some help would be lovely. :)
How to run a secondary query within a primary query inside a for each loop
How to run a secondary query within a primary query inside a for each loop
How can I modify my code to allow me to run a second query in the for each
loop?
For now I have commented out the second query, as Im sure I need to make
some changes prior to removing the slashes.
<?php
$mysqli = new mysqli('LOGIN DETAILS HERE');
if ($mysqli->connect_error) {
die('Connect Error: ' . $mysqli->connect_error);
}
$query = "SELECT * FROM toptips WHERE userid = 2";
$result = $mysqli->query($query);
while($row = $result->fetch_array())
{ $rows[] = $row; }
foreach($rows as $row) {
$id = $row['id'];
echo $row['time'] . " " . $row['course'] . " - " . $row['horse'] . " "
. $row['description'] ."<br/>";
// second query here
// $query2 = "SELECT likes FROM Likes_table WHERE id = $id";
// $result = $mysqli->query($query2);
// while($row = $result->fetch_assoc()){
// echo $row['likes'] . '<br />';
// }
}
?>
How can I modify my code to allow me to run a second query in the for each
loop?
For now I have commented out the second query, as Im sure I need to make
some changes prior to removing the slashes.
<?php
$mysqli = new mysqli('LOGIN DETAILS HERE');
if ($mysqli->connect_error) {
die('Connect Error: ' . $mysqli->connect_error);
}
$query = "SELECT * FROM toptips WHERE userid = 2";
$result = $mysqli->query($query);
while($row = $result->fetch_array())
{ $rows[] = $row; }
foreach($rows as $row) {
$id = $row['id'];
echo $row['time'] . " " . $row['course'] . " - " . $row['horse'] . " "
. $row['description'] ."<br/>";
// second query here
// $query2 = "SELECT likes FROM Likes_table WHERE id = $id";
// $result = $mysqli->query($query2);
// while($row = $result->fetch_assoc()){
// echo $row['likes'] . '<br />';
// }
}
?>
Mozilla Add-on: Google Translator returns null
Mozilla Add-on: Google Translator returns null
I just started to build Mozilla add-ons, and I am trying to run the
example (Google Translate & replace the selected text) shown in the
official introduction video. But it is failing with "TypeError:
response.json.responseData is null". Can anyone help me to fix the
"Translator" code. I tried the code in both Add-on SDK and Add-on Builder.
Link to the tutorial video:
https://addons.mozilla.org/en-US/developers/builder
Regards, Mohan
I just started to build Mozilla add-ons, and I am trying to run the
example (Google Translate & replace the selected text) shown in the
official introduction video. But it is failing with "TypeError:
response.json.responseData is null". Can anyone help me to fix the
"Translator" code. I tried the code in both Add-on SDK and Add-on Builder.
Link to the tutorial video:
https://addons.mozilla.org/en-US/developers/builder
Regards, Mohan
Friday, 30 August 2013
Checkstyle equivalent for Objective-C
Checkstyle equivalent for Objective-C
Is there a checkstyle equivalent for Objective-C?
This question has been attempted before, but either the wasn't clear in
what was being asked, or the answers were not satisfactory.
I do not want a code formatting tool. (There's lots of options here. I use
AppCode).
I do want a tool that can identify code smells, and fail the build for me.
Here's some checks that would be useful:
Class too long.
Method too long.
Method has too many parameters.
Cyclomatic complexity - class has too many dependencies.
I've found that doing these continuous, automated code audits really helps
in a team environment.
Is there a checkstyle equivalent for Objective-C?
This question has been attempted before, but either the wasn't clear in
what was being asked, or the answers were not satisfactory.
I do not want a code formatting tool. (There's lots of options here. I use
AppCode).
I do want a tool that can identify code smells, and fail the build for me.
Here's some checks that would be useful:
Class too long.
Method too long.
Method has too many parameters.
Cyclomatic complexity - class has too many dependencies.
I've found that doing these continuous, automated code audits really helps
in a team environment.
Thursday, 29 August 2013
Sublime theme regex not working when the line doesn't start with a white space
Sublime theme regex not working when the line doesn't start with a white
space
I'm trying to customize a SublimeText theme for pandoc's markdown syntax.
I want to highlight footnotes references inside paragraphs.
The syntax for footnotes is : [^foo]
I have the following regex : \[\^(.*)\] in my tmLanguage file :
<dict>
<key>comment</key>
<string>Footnotes references</string>
<key>match</key>
<string>\[\^(.*)\]</string>
<key>name</key>
<string>meta.paragraph.markdown.footnote</string>
</dict>
Here's the result :
https://dl.dropboxusercontent.com/u/483488/stackoverflow/sublregex.png
(sorry, I can't insert images...)
Line 149: just the reference. It works.
Line 150: white space and the reference. It works.
Line 151: white space, random text, the reference. It works
Line 152: white space, random text, white space, the reference, white
space, random text. It works.
Line 153: white space, random text, the reference, random text. It works.
Line 154: NO white space, the reference. IT FAILS.
Line 155: same as line 149, it should work but it fails... I guess because
of line 154.
Line 156: blank
Line 157: same as line 149 and 155, it works again...
It seems that my regex or Sublime or something needs a leading white
space. Adding the multiline option (?w) doesn't help.
Do you have any idea of what's going wrong here and how to fix it ?
space
I'm trying to customize a SublimeText theme for pandoc's markdown syntax.
I want to highlight footnotes references inside paragraphs.
The syntax for footnotes is : [^foo]
I have the following regex : \[\^(.*)\] in my tmLanguage file :
<dict>
<key>comment</key>
<string>Footnotes references</string>
<key>match</key>
<string>\[\^(.*)\]</string>
<key>name</key>
<string>meta.paragraph.markdown.footnote</string>
</dict>
Here's the result :
https://dl.dropboxusercontent.com/u/483488/stackoverflow/sublregex.png
(sorry, I can't insert images...)
Line 149: just the reference. It works.
Line 150: white space and the reference. It works.
Line 151: white space, random text, the reference. It works
Line 152: white space, random text, white space, the reference, white
space, random text. It works.
Line 153: white space, random text, the reference, random text. It works.
Line 154: NO white space, the reference. IT FAILS.
Line 155: same as line 149, it should work but it fails... I guess because
of line 154.
Line 156: blank
Line 157: same as line 149 and 155, it works again...
It seems that my regex or Sublime or something needs a leading white
space. Adding the multiline option (?w) doesn't help.
Do you have any idea of what's going wrong here and how to fix it ?
How to compare two tables on two different servers, in SSIS within one package
How to compare two tables on two different servers, in SSIS within one
package
I need to compare two tables on two different servers. Could someone help
me ? Easily I need get rows from two tables (based on same keys), which
exists into first table and not exist in second table(based on binary
checksum(hashKey)). After that I need to load them into stage table.
server1.database1.table1.HashKey<>server2.database2.table2.HashKey2 -->
this rows I need to received and insert them to table.
Thank in advance
package
I need to compare two tables on two different servers. Could someone help
me ? Easily I need get rows from two tables (based on same keys), which
exists into first table and not exist in second table(based on binary
checksum(hashKey)). After that I need to load them into stage table.
server1.database1.table1.HashKey<>server2.database2.table2.HashKey2 -->
this rows I need to received and insert them to table.
Thank in advance
Wednesday, 28 August 2013
Facebook post comment count from Graph API
Facebook post comment count from Graph API
In July 2013 Facebook removed the comment count from posts in the graph
API. Is there an alternative, currently working way to retrieve the number
of comments for a specific post, without having to download all of them?
Thanks.
In July 2013 Facebook removed the comment count from posts in the graph
API. Is there an alternative, currently working way to retrieve the number
of comments for a specific post, without having to download all of them?
Thanks.
Mobile phone integration with symfony2 framework
Mobile phone integration with symfony2 framework
I would like to know what minimum requirements are for mobile phones to be
supported by symfony2.2 framework. Do I need to do something specifically
so it can run on mobile phone, or everything is the same? Thanks for your
answers :)
I would like to know what minimum requirements are for mobile phones to be
supported by symfony2.2 framework. Do I need to do something specifically
so it can run on mobile phone, or everything is the same? Thanks for your
answers :)
Idea on building a live, serverless multi-user local-network-shared database with SQLite
Idea on building a live, serverless multi-user local-network-shared
database with SQLite
I need some input on a idea I had. If you're interested/experienced in
SQLite and lowest-budget-high-end-solutions (Win only for now ;)) this is
for you. While fleshing out this question I have gotten pretty excited
about this idea, so bear with me. There's a TL;DR below
I have developed a VB.NET (3.5) Desktop application with SQLite. The data
is structured in an EAV-model, because I need that flexibility (the
semantic structure of the data is stored separately in an XML File). The
application actually performs very well above my expectations, even with a
- for the scenario at hand - large database (about 120MB for the main
file).
As expected performance is abysmal when the SQLite file(s) are on a
network folder. It's bearable but I have higher goals. Expected scenarios
(for now) are max. 10 users that need to access the database concurrently
within a local windows network. 98% of the concurrence is required for
heavy read-access, inserts and updates are sparse and small.
The software is used almost exclusively within environments with low
budget and the technical infrastructure (support and hardware) even lower,
so my goal is to avoid using a database server. I also do not want to
implement my own SQLite "Server" a la SQLitening (i.e. tell one instance
of the application to automagically "share" the database in the network)
because i want the database to be able to reside on an independent network
drive.
My first impulse after realizing the situation cannot be amended by
optimizing queries, was a "lazy synchronization" approach which would be
mostly painless to implement. The database is "wiki-esque" with (almost)
only inserts, so there won't be any (much) conflict issues at all: whoever
comes "last" wins, each field has a change history with timestamp and
userid and can be rolled back individually. Entries are "marked as
deleted" and can be discarded upon a "cleanup"-action. Though it comes at
the cost of never being "live" with the data other users change or enter
during a session, and also the synching process might take a while, with
the users potentially blocking each other at "rush-hour". We're talking
maybe a couple of minutes worst-case, which wouldn't be a big deal but it
wouldn't be cool, either.
TL;DR: How to implement a live, serverless, local-network-shared Database
with SQLite for a end-user application that already performs very well on
a local datafile within a scenario with
many SELECTs
few INSERTs
no DELETEs and
hardly any UPDATEs per user session.
Let's assume furthermore
there is always sufficient hard drive space available
due to archive mechanisms (and data privacy constraints) the database
never grows above 200MB
we can efficiently tell whether a file has been changed and by whom in the
"shared directory" where the database files reside
we can copy files sufficiently fast from the shared directory
Now what i had in mind was implementing differencing files for each
session that will be locally cached for read access.
At the start of a client-session:
check the big file and session-specific (see below) files in the shared
directory for changes since the last session (CRC+logfile in the shared
directory)
copy the big (200MB) current database file to a local path before each
session if changed or not cached
also copy all session-specific files (see below) if changed or not cached
all INSERTs during a session are written to a small, session-specific file
in the shared directory
this could be limited to a suitable size like 2MB per file or something
even smaller, then a new file is created
read-access (SELECTs) is then performed sequentially
in the local copy of the main file
in the local copies of the session files
in all current (ie. new) session files in the shared cache
on detection of a new session file, session files will by copied to the
local cache again
finally, the session files are periodically merged into the big file
this could be at the end of every session, but if I am not mistaken, it
could be whenever.
This would
eliminate all write concurrency
eliminate read concurrency on the big file and all local session files
reduce the needed concurrency to the reads on the small session files
minimize the network usage to accessing the most current session files
(2MB per concurrent user)
preserve a live view of the current data state for every client
This sounds beyond awesome to me.
Questions: Is there a name for this "protocol" that i am outlining so I
can do further research?
Would you consider this is a viable approach with SQLite or is this a wild
goose chase - am I overlooking obvious drawbacks?
If you're on board, what would be a good size for the session files (n *
page_size?)?
Thank you for your input!
Christoph
database with SQLite
I need some input on a idea I had. If you're interested/experienced in
SQLite and lowest-budget-high-end-solutions (Win only for now ;)) this is
for you. While fleshing out this question I have gotten pretty excited
about this idea, so bear with me. There's a TL;DR below
I have developed a VB.NET (3.5) Desktop application with SQLite. The data
is structured in an EAV-model, because I need that flexibility (the
semantic structure of the data is stored separately in an XML File). The
application actually performs very well above my expectations, even with a
- for the scenario at hand - large database (about 120MB for the main
file).
As expected performance is abysmal when the SQLite file(s) are on a
network folder. It's bearable but I have higher goals. Expected scenarios
(for now) are max. 10 users that need to access the database concurrently
within a local windows network. 98% of the concurrence is required for
heavy read-access, inserts and updates are sparse and small.
The software is used almost exclusively within environments with low
budget and the technical infrastructure (support and hardware) even lower,
so my goal is to avoid using a database server. I also do not want to
implement my own SQLite "Server" a la SQLitening (i.e. tell one instance
of the application to automagically "share" the database in the network)
because i want the database to be able to reside on an independent network
drive.
My first impulse after realizing the situation cannot be amended by
optimizing queries, was a "lazy synchronization" approach which would be
mostly painless to implement. The database is "wiki-esque" with (almost)
only inserts, so there won't be any (much) conflict issues at all: whoever
comes "last" wins, each field has a change history with timestamp and
userid and can be rolled back individually. Entries are "marked as
deleted" and can be discarded upon a "cleanup"-action. Though it comes at
the cost of never being "live" with the data other users change or enter
during a session, and also the synching process might take a while, with
the users potentially blocking each other at "rush-hour". We're talking
maybe a couple of minutes worst-case, which wouldn't be a big deal but it
wouldn't be cool, either.
TL;DR: How to implement a live, serverless, local-network-shared Database
with SQLite for a end-user application that already performs very well on
a local datafile within a scenario with
many SELECTs
few INSERTs
no DELETEs and
hardly any UPDATEs per user session.
Let's assume furthermore
there is always sufficient hard drive space available
due to archive mechanisms (and data privacy constraints) the database
never grows above 200MB
we can efficiently tell whether a file has been changed and by whom in the
"shared directory" where the database files reside
we can copy files sufficiently fast from the shared directory
Now what i had in mind was implementing differencing files for each
session that will be locally cached for read access.
At the start of a client-session:
check the big file and session-specific (see below) files in the shared
directory for changes since the last session (CRC+logfile in the shared
directory)
copy the big (200MB) current database file to a local path before each
session if changed or not cached
also copy all session-specific files (see below) if changed or not cached
all INSERTs during a session are written to a small, session-specific file
in the shared directory
this could be limited to a suitable size like 2MB per file or something
even smaller, then a new file is created
read-access (SELECTs) is then performed sequentially
in the local copy of the main file
in the local copies of the session files
in all current (ie. new) session files in the shared cache
on detection of a new session file, session files will by copied to the
local cache again
finally, the session files are periodically merged into the big file
this could be at the end of every session, but if I am not mistaken, it
could be whenever.
This would
eliminate all write concurrency
eliminate read concurrency on the big file and all local session files
reduce the needed concurrency to the reads on the small session files
minimize the network usage to accessing the most current session files
(2MB per concurrent user)
preserve a live view of the current data state for every client
This sounds beyond awesome to me.
Questions: Is there a name for this "protocol" that i am outlining so I
can do further research?
Would you consider this is a viable approach with SQLite or is this a wild
goose chase - am I overlooking obvious drawbacks?
If you're on board, what would be a good size for the session files (n *
page_size?)?
Thank you for your input!
Christoph
Tuesday, 27 August 2013
Java class will not run (command prompt)
Java class will not run (command prompt)
I have been fighting with this program for a little while now and cannot
figure out what is wrong. Any help would be greatly appreciated.
So here's the issue. I have three classes one is for logging onto a mysql
database, the other is to output data from the database, and the last one
holds method main. I was having a huge issue with getting them to compile
getting errors about not finding a symbol for a method in a different
class. I finally got them to all compile by using command "javac -d
bin/cdtPack src/CDT.java src/login.java src/ClientBase.java"
But, now when I try to run the class with method main I get error:
"Exception in thread "main" java.lang.noClassDefFoundError: CDT (wrong
name: cdtPack/CDT)" then a list of at java....
Anyone have an idea what could be going wrong?
I have been fighting with this program for a little while now and cannot
figure out what is wrong. Any help would be greatly appreciated.
So here's the issue. I have three classes one is for logging onto a mysql
database, the other is to output data from the database, and the last one
holds method main. I was having a huge issue with getting them to compile
getting errors about not finding a symbol for a method in a different
class. I finally got them to all compile by using command "javac -d
bin/cdtPack src/CDT.java src/login.java src/ClientBase.java"
But, now when I try to run the class with method main I get error:
"Exception in thread "main" java.lang.noClassDefFoundError: CDT (wrong
name: cdtPack/CDT)" then a list of at java....
Anyone have an idea what could be going wrong?
Why do use webApps userID + password instead of a password only?
Why do use webApps userID + password instead of a password only?
Just out of curiosity, I wonder why web apps typically user a userID and a
password.
I don't see reasons, why a sufficiently long password doesn't fit too. For
example, a password generated by a server-application.
Are there reasons an app ultimately has to use a userID too?
As long as password are unique and long, it perfectly allows to identify a
user.
Just out of curiosity, I wonder why web apps typically user a userID and a
password.
I don't see reasons, why a sufficiently long password doesn't fit too. For
example, a password generated by a server-application.
Are there reasons an app ultimately has to use a userID too?
As long as password are unique and long, it perfectly allows to identify a
user.
proper calculation for javascript time differences from server roundtrip
proper calculation for javascript time differences from server roundtrip
trying to get difference in time handled for a game, but I haven't been
able to get the math right (My weak point). Heres what I have so far:
function(timeSentToServer, difference, serverTime) {
var roundTripTime = Date.now()-timeSentToServer;
var responseTime = roundTripTime-difference;
timeDifference = responseTime;
}
timeSentToServer is the Date.now() when the request was sent difference is
serverTime-timeSentToServer serverTime is the time when the server
received the request
the timeDifference should be a value that I can add to Date.now() to match
it up with the current serverTime (probably a few milliseconds off, but
thats acceptable)
however, I am running into an issue where one device Im testing against is
just one second ahead of the server, and its throwing the whole
calculation out of whack
e.g.: currentTime: 968952 sentTime: 968834 serverTime: 967742 difference:
1210
which results in being even more ahead of the server.
will Date.now()-difference be the solution I'm looking for? and also, is
there any other articles I can read on the subject, and any different
solutions?
trying to get difference in time handled for a game, but I haven't been
able to get the math right (My weak point). Heres what I have so far:
function(timeSentToServer, difference, serverTime) {
var roundTripTime = Date.now()-timeSentToServer;
var responseTime = roundTripTime-difference;
timeDifference = responseTime;
}
timeSentToServer is the Date.now() when the request was sent difference is
serverTime-timeSentToServer serverTime is the time when the server
received the request
the timeDifference should be a value that I can add to Date.now() to match
it up with the current serverTime (probably a few milliseconds off, but
thats acceptable)
however, I am running into an issue where one device Im testing against is
just one second ahead of the server, and its throwing the whole
calculation out of whack
e.g.: currentTime: 968952 sentTime: 968834 serverTime: 967742 difference:
1210
which results in being even more ahead of the server.
will Date.now()-difference be the solution I'm looking for? and also, is
there any other articles I can read on the subject, and any different
solutions?
initializing struct while using auto causes a copy in VS 2013
initializing struct while using auto causes a copy in VS 2013
In the following code the line that creates nested object prints only
"constructor" with gcc, but not with VS 2013:
#include <iostream>
using namespace std;
struct test {
test() { cout << "constructor" << endl; }
test(const test&) { cout << "copy constructor" << endl; }
test(test&&) { cout << "move constructor" << endl; }
~test() { cout << "destructor" << endl; }
};
struct nested {
test t;
// nested() {}
};
auto main() -> int {
// prints "constructor", "copy constructor" and "destructor"
auto n = nested{};
cout << endl;
return 0;
}
So I guess what happening here is that a temporary object gets copied into
n. There is no compiler-generated move constructor, so that's why it's not
a move.
I'd like to know if this is a bug or an acceptable behaviour? And why
adding a default constructor prevents a copy here?
In the following code the line that creates nested object prints only
"constructor" with gcc, but not with VS 2013:
#include <iostream>
using namespace std;
struct test {
test() { cout << "constructor" << endl; }
test(const test&) { cout << "copy constructor" << endl; }
test(test&&) { cout << "move constructor" << endl; }
~test() { cout << "destructor" << endl; }
};
struct nested {
test t;
// nested() {}
};
auto main() -> int {
// prints "constructor", "copy constructor" and "destructor"
auto n = nested{};
cout << endl;
return 0;
}
So I guess what happening here is that a temporary object gets copied into
n. There is no compiler-generated move constructor, so that's why it's not
a move.
I'd like to know if this is a bug or an acceptable behaviour? And why
adding a default constructor prevents a copy here?
How to validate form & send email with PHP
How to validate form & send email with PHP
I've done a tiny bit, but it is not so good. I would like to check if
email is valid in proper format, name containing no numbers & also how do
I add validation to check if the Math question is right. Can anyone please
help?
<?php
$submitted = $_POST["submitted"];
if($submitted == "true")
{
$name = trim($_POST["name"]);
$email = trim($_POST["email"]);
$subject = trim($_POST["subject"]);
$message = trim($_POST["message"]);
$answerbox = trim($_POST["answerbox"]);
if($name == "") print "<p>Please type your name.</p>";
if($subject == "") print "<p>Please type a subject.</p>";
if($email == "") print "<p>Please type a valid email address.</p>";
if($message == "") print "<p>Please type your message.</p>";
if($answerbox == "") print "<p>Please answer the math question.</p>";
}
?>
<form name="contact" action="form2.php" method="post">
<input type="hidden" name="submitted" value="true"/>
<label for="YourName">Your Name:</label>
<input type="text" name="name" class="required" />
<label for="YourEmail">Your Email:</label>
<input type="text" name="email" class="required"/>
<label for="Subject">Subject:</label>
<input type="text" name="subject" class="required" />
<label for="YourMessage">Your Message:</label>
<textarea name="message" class="required"></textarea>
<p class="c3">10 + 5 =<input type="text" name="answerbox"
id="answerbox" /></p>
<fieldset>
<input type="submit" name="submit" id="submit" value="Send"
class="required"/>
<input type="reset" id="reset" value="Reset"/>
</fieldset>
</form>
I've done a tiny bit, but it is not so good. I would like to check if
email is valid in proper format, name containing no numbers & also how do
I add validation to check if the Math question is right. Can anyone please
help?
<?php
$submitted = $_POST["submitted"];
if($submitted == "true")
{
$name = trim($_POST["name"]);
$email = trim($_POST["email"]);
$subject = trim($_POST["subject"]);
$message = trim($_POST["message"]);
$answerbox = trim($_POST["answerbox"]);
if($name == "") print "<p>Please type your name.</p>";
if($subject == "") print "<p>Please type a subject.</p>";
if($email == "") print "<p>Please type a valid email address.</p>";
if($message == "") print "<p>Please type your message.</p>";
if($answerbox == "") print "<p>Please answer the math question.</p>";
}
?>
<form name="contact" action="form2.php" method="post">
<input type="hidden" name="submitted" value="true"/>
<label for="YourName">Your Name:</label>
<input type="text" name="name" class="required" />
<label for="YourEmail">Your Email:</label>
<input type="text" name="email" class="required"/>
<label for="Subject">Subject:</label>
<input type="text" name="subject" class="required" />
<label for="YourMessage">Your Message:</label>
<textarea name="message" class="required"></textarea>
<p class="c3">10 + 5 =<input type="text" name="answerbox"
id="answerbox" /></p>
<fieldset>
<input type="submit" name="submit" id="submit" value="Send"
class="required"/>
<input type="reset" id="reset" value="Reset"/>
</fieldset>
</form>
how to make incoming call in android emulator without commad code
how to make incoming call in android emulator without commad code
I'm trying to develop small app that will be registered on
PhoneStateListener and do some magic over incoming and outgoing calls
moniter. For debugging purposes I need to trigger onCallStateChanged(...)
event from outside of phone, not perform real incoming voicecall.
Is it possible to do this somehow with sending phone number to debugged
app without command line code ?
I'm trying to develop small app that will be registered on
PhoneStateListener and do some magic over incoming and outgoing calls
moniter. For debugging purposes I need to trigger onCallStateChanged(...)
event from outside of phone, not perform real incoming voicecall.
Is it possible to do this somehow with sending phone number to debugged
app without command line code ?
Monday, 26 August 2013
import module or any component in python
import module or any component in python
during code implementation, I got suggestion we should import only
specific feature which will reduce time but I got some different result.
Am I doing some thing wrong.
python -m timeit "from subprocess import call" (suggested method which is
taking more time)
1000000 loops, best of 3: 1.01 usec per loop
python -m timeit "import subprocess"
1000000 loops, best of 3: 0.525 usec per loop
during code implementation, I got suggestion we should import only
specific feature which will reduce time but I got some different result.
Am I doing some thing wrong.
python -m timeit "from subprocess import call" (suggested method which is
taking more time)
1000000 loops, best of 3: 1.01 usec per loop
python -m timeit "import subprocess"
1000000 loops, best of 3: 0.525 usec per loop
Get specific objects from ArrayList when objects were added anonymously?
Get specific objects from ArrayList when objects were added anonymously?
I have created a short example of my problem. I'm creating a list of
Objects anonymously and adding them to an ArrayList. Once items are in the
ArrayList I later come back and add more information to each object within
the list. Is there a way to extract a specific object from the list if you
do not know it's index?
I know only the Object's 'name' but you cannot do a list.get(ObjectName)
or anything. What is the recommended way to handle this? I'd rather not
have to iterate through the entire list every time I want to retrieve one
specific object.
public class TestCode{
public static void main (String args []) {
Cave cave = new Cave();
// Loop adds several Parties to the cave's party list
cave.parties.add(new Party("FirstParty")); // all anonymously added
cave.parties.add(new Party("SecondParty"));
cave.parties.add(new Party("ThirdParty"));
// How do I go about setting the 'index' value of SecondParty for
example?
}
}
class Cave {
ArrayList<Party> parties = new ArrayList<Party>();
}
class Party extends CaveElement{
int index;
public Party(String n){
name = n;
}
// getter and setter methods
public String toString () {
return name;
}
}
class CaveElement {
String name = "";
int index = 0;
public String toString () {
return name + "" + index;
}
}
I have created a short example of my problem. I'm creating a list of
Objects anonymously and adding them to an ArrayList. Once items are in the
ArrayList I later come back and add more information to each object within
the list. Is there a way to extract a specific object from the list if you
do not know it's index?
I know only the Object's 'name' but you cannot do a list.get(ObjectName)
or anything. What is the recommended way to handle this? I'd rather not
have to iterate through the entire list every time I want to retrieve one
specific object.
public class TestCode{
public static void main (String args []) {
Cave cave = new Cave();
// Loop adds several Parties to the cave's party list
cave.parties.add(new Party("FirstParty")); // all anonymously added
cave.parties.add(new Party("SecondParty"));
cave.parties.add(new Party("ThirdParty"));
// How do I go about setting the 'index' value of SecondParty for
example?
}
}
class Cave {
ArrayList<Party> parties = new ArrayList<Party>();
}
class Party extends CaveElement{
int index;
public Party(String n){
name = n;
}
// getter and setter methods
public String toString () {
return name;
}
}
class CaveElement {
String name = "";
int index = 0;
public String toString () {
return name + "" + index;
}
}
Android - Open the Messages app programatically
Android - Open the Messages app programatically
Is it possible to open the Messages app programatically specifying the
number and the message?
Instead of sending the message directly, I want to do this to allow people
select a particular SIM before sending the message.
Is it possible to open the Messages app programatically specifying the
number and the message?
Instead of sending the message directly, I want to do this to allow people
select a particular SIM before sending the message.
iOS struct with NSArrays
iOS struct with NSArrays
I have four pieces of data I always want to keep together: 2 NSArrays and
2 ints. I thought a struct might be a good idea, but I get the "ARC does
not allow objects in structs" error. What would be the best way to
encapsulate the data? Using an NSDictionary?
I have four pieces of data I always want to keep together: 2 NSArrays and
2 ints. I thought a struct might be a good idea, but I get the "ARC does
not allow objects in structs" error. What would be the best way to
encapsulate the data? Using an NSDictionary?
Read string as variable RUBY
Read string as variable RUBY
I am pulling the following string from a csv file, from cell A1, and
storing it as a variable:
#{collector_id}
So, cell A1 reads #{collector_id}, and my code essentially does this:
test = #excel_cell_A1
However, if I then do this:
puts test
I get this:
#{collector_id}
I need #{collector_id} to read as the actual variable collector_id, not
the code that I am using to call the variable. Is that possible?
Thanks for the help. I am using ruby 1.9.3.
I am pulling the following string from a csv file, from cell A1, and
storing it as a variable:
#{collector_id}
So, cell A1 reads #{collector_id}, and my code essentially does this:
test = #excel_cell_A1
However, if I then do this:
puts test
I get this:
#{collector_id}
I need #{collector_id} to read as the actual variable collector_id, not
the code that I am using to call the variable. Is that possible?
Thanks for the help. I am using ruby 1.9.3.
Anonymous modules and classes garbage collection in Ruby
Anonymous modules and classes garbage collection in Ruby
I'd like to know why the following code apparently doesn't garbage collect
anonymous modules that are supposedly not referenced anywhere anymore (not
extended/included, not named, containing array set to nil).
I'd appreciate if anyone could clarify what's going on under the hood with
relatively simple/general programming words. Is there a special ruby way
to achieve this ? Can't anonymous modules/classes be garbage collected no
matter what ? Or was i simply mislead by the memory stats i got ?
NOTE : i'm using ruby 1.9.3 ; don't know if ruby 2.x would change anything
at all...
Thanks in advance.
puts("INITIAL OBJECT SPACE OBJECTS : #{ObjectSpace.count_objects}")
i = 100000
ms = []
i.times do
ms << Module.new do
def foo()
puts('foo method called')
end
end
end
puts("#{i} MODULES CREATED")
puts("OBJECT SPACE OBJECTS : #{ObjectSpace.count_objects}")
ms = nil
ObjectSpace.garbage_collect
puts("#{i} MODULES GARBAGE COLLECTED")
puts("WAITING TO END PROGRAM")
stop = gets
puts("FINAL OBJECT SPACE OBJECTS : #{ObjectSpace.count_objects}")
I say "apparently doesn't garbage collect" because my OS task manager
doesn't show any reduction in memory usage from the process, and calling
ObjectSpace.count_objects yields the following, which i read (wrongly so
?) as : no the memory used by your modules has not been freed.
INITIAL OBJECT SPACE OBJECTS : {:TOTAL=>14730, :FREE=>251, :T_OBJECT=>8,
:T_CLASS=>542, :T_MODULE=>21, :T_FLOAT=>7, :T_STRING=>6349, :T_REGEXP=>24,
:T_ARRAY=>1009, :T_HASH=>14, :T_BIGNUM=>3, :T_FILE=>10, :T_DATA=>408,
:T_MATCH=>108, :T_COMPLEX=>1, :T_NODE=>5956, :T_ICLASS=>19}
100000 MODULES CREATED
OBJECT SPACE OBJECTS : {:TOTAL=>311794, :FREE=>59829, :T_OBJECT=>6,
:T_CLASS=>542, :T_MODULE=>100021, :T_FLOAT=>7, :T_STRING=>3332,
:T_REGEXP=>22, :T_ARRAY=>23868, :T_HASH=>10, :T_BIGNUM=>3, :T_FILE=>3,
:T_DATA=>100324, :T_COMPLEX=>1, :T_NODE=>23807, :T_ICLASS=>19}
100000 MODULES GARBAGE COLLECTED WAITING TO END PROGRAM
FINAL OBJECT SPACE OBJECTS : {:TOTAL=>311794, :FREE=>107155, :T_OBJECT=>6,
:T_CLASS=>542, :T_MODULE=>100021, :T_FLOAT=>7, :T_STRING=>3335,
:T_REGEXP=>22, :T_ARRAY=>203, :T_HASH=>10, :T_BIGNUM=>3, :T_FILE=>3,
:T_DATA=>100324, :T_COMPLEX=>1, :T_NODE=>143, :T_ICLASS=>19}
Related questions :
Working with anonymous modules in ruby
Ruby GC using define method
I'd like to know why the following code apparently doesn't garbage collect
anonymous modules that are supposedly not referenced anywhere anymore (not
extended/included, not named, containing array set to nil).
I'd appreciate if anyone could clarify what's going on under the hood with
relatively simple/general programming words. Is there a special ruby way
to achieve this ? Can't anonymous modules/classes be garbage collected no
matter what ? Or was i simply mislead by the memory stats i got ?
NOTE : i'm using ruby 1.9.3 ; don't know if ruby 2.x would change anything
at all...
Thanks in advance.
puts("INITIAL OBJECT SPACE OBJECTS : #{ObjectSpace.count_objects}")
i = 100000
ms = []
i.times do
ms << Module.new do
def foo()
puts('foo method called')
end
end
end
puts("#{i} MODULES CREATED")
puts("OBJECT SPACE OBJECTS : #{ObjectSpace.count_objects}")
ms = nil
ObjectSpace.garbage_collect
puts("#{i} MODULES GARBAGE COLLECTED")
puts("WAITING TO END PROGRAM")
stop = gets
puts("FINAL OBJECT SPACE OBJECTS : #{ObjectSpace.count_objects}")
I say "apparently doesn't garbage collect" because my OS task manager
doesn't show any reduction in memory usage from the process, and calling
ObjectSpace.count_objects yields the following, which i read (wrongly so
?) as : no the memory used by your modules has not been freed.
INITIAL OBJECT SPACE OBJECTS : {:TOTAL=>14730, :FREE=>251, :T_OBJECT=>8,
:T_CLASS=>542, :T_MODULE=>21, :T_FLOAT=>7, :T_STRING=>6349, :T_REGEXP=>24,
:T_ARRAY=>1009, :T_HASH=>14, :T_BIGNUM=>3, :T_FILE=>10, :T_DATA=>408,
:T_MATCH=>108, :T_COMPLEX=>1, :T_NODE=>5956, :T_ICLASS=>19}
100000 MODULES CREATED
OBJECT SPACE OBJECTS : {:TOTAL=>311794, :FREE=>59829, :T_OBJECT=>6,
:T_CLASS=>542, :T_MODULE=>100021, :T_FLOAT=>7, :T_STRING=>3332,
:T_REGEXP=>22, :T_ARRAY=>23868, :T_HASH=>10, :T_BIGNUM=>3, :T_FILE=>3,
:T_DATA=>100324, :T_COMPLEX=>1, :T_NODE=>23807, :T_ICLASS=>19}
100000 MODULES GARBAGE COLLECTED WAITING TO END PROGRAM
FINAL OBJECT SPACE OBJECTS : {:TOTAL=>311794, :FREE=>107155, :T_OBJECT=>6,
:T_CLASS=>542, :T_MODULE=>100021, :T_FLOAT=>7, :T_STRING=>3335,
:T_REGEXP=>22, :T_ARRAY=>203, :T_HASH=>10, :T_BIGNUM=>3, :T_FILE=>3,
:T_DATA=>100324, :T_COMPLEX=>1, :T_NODE=>143, :T_ICLASS=>19}
Related questions :
Working with anonymous modules in ruby
Ruby GC using define method
Jquery autocomplete change source
Jquery autocomplete change source
I have following code: http://jsfiddle.net/rdworth/EBduF/
And I need availabletags1 as source if it's choice1 choosen and
availabletags2 if choice2. And I need to change this dynamically by actual
user choice.
Thanks
PS: Sorry for my english :)
I have following code: http://jsfiddle.net/rdworth/EBduF/
And I need availabletags1 as source if it's choice1 choosen and
availabletags2 if choice2. And I need to change this dynamically by actual
user choice.
Thanks
PS: Sorry for my english :)
Possible to add a column to an ActiveRecord model that is a foreign key?
Possible to add a column to an ActiveRecord model that is a foreign key?
I can easily create a scaffold or model in Rails with a field that is a
reference (foreign key) to another model:
rails g model Cat owner:references
rails g scaffold Cat owner:references
But I can't seem to do the same for adding a column in a migration:
rails g migration AddOwnerToCats owner:references
What the above does is produce a migration file like this:
class AddOwnerToCats < ActiveRecord::Migration
def change
add_column :cats, :owner, :references
end
end
And when I try and run it with rake db:migrate, I get this:
SQLite3::SQLException: near "references": syntax error: ALTER TABLE "cats"
ADD "owner" references
So is there a way to add a column that is a reference to another model? Or
do I just have to do:
rails g migration AddOwnerToCats owner_id:integer
And then go into the migration and add an index for owner_id?
I can easily create a scaffold or model in Rails with a field that is a
reference (foreign key) to another model:
rails g model Cat owner:references
rails g scaffold Cat owner:references
But I can't seem to do the same for adding a column in a migration:
rails g migration AddOwnerToCats owner:references
What the above does is produce a migration file like this:
class AddOwnerToCats < ActiveRecord::Migration
def change
add_column :cats, :owner, :references
end
end
And when I try and run it with rake db:migrate, I get this:
SQLite3::SQLException: near "references": syntax error: ALTER TABLE "cats"
ADD "owner" references
So is there a way to add a column that is a reference to another model? Or
do I just have to do:
rails g migration AddOwnerToCats owner_id:integer
And then go into the migration and add an index for owner_id?
Sunday, 25 August 2013
Arranging characters in alphabetical order
Arranging characters in alphabetical order
I have written a code that asks the user for a word and then it arranges
that word in alphabetical order and stores it in another string.
#include<stdio.h>
main()
{
char in[100],out[100],ch;
int i,len,j=0;
//ask user for a word
printf("Enter a word: ");
scanf("%s",in);
//arrange that word in alphabetical order
for(ch = 'a'; ch <= 'z'; ++ch)
for(i = 0; i < strlen(in); ++i)
if(in[i] == ch)
{
out[j] = ch;
++j;
}
//print the word
printf("%s",out);
fflush(stdin);
getchar();
}
The problem is when word is stored in the other string, there are some
extra letters or symbols after that word. Can someone please tell me what
could be possibly wrong with my code.
I have written a code that asks the user for a word and then it arranges
that word in alphabetical order and stores it in another string.
#include<stdio.h>
main()
{
char in[100],out[100],ch;
int i,len,j=0;
//ask user for a word
printf("Enter a word: ");
scanf("%s",in);
//arrange that word in alphabetical order
for(ch = 'a'; ch <= 'z'; ++ch)
for(i = 0; i < strlen(in); ++i)
if(in[i] == ch)
{
out[j] = ch;
++j;
}
//print the word
printf("%s",out);
fflush(stdin);
getchar();
}
The problem is when word is stored in the other string, there are some
extra letters or symbols after that word. Can someone please tell me what
could be possibly wrong with my code.
Flask-Security CSRF token
Flask-Security CSRF token
I have a flask app that serves as REST API backend. I would like to
implement token based authentication for the backend but in order to do
that I need to retrieve the user token. Flask-Security documentation
clearly says that to retrieve the token one needs to perform an HTTP POST
with the authentication details as JSON data to the authentication
endpoint. Unfortunately I don't understand how to retrieve the CSRF token
needed to perform such request.
If I use the login page/template provided with the extension the CSRF
token is passed to the client in the hidden field in the form. The
question is:
how do I retrieve the CSRF token without accessing and parsing the login
page, like for example from an angularJS app using $http methods or a
mobile app?
Obviously I could avoid using Flask-Security and implement the pieces
myself but I'm relatively inexperienced with webapps and I feel I might be
approaching this the wrong way.
I have a flask app that serves as REST API backend. I would like to
implement token based authentication for the backend but in order to do
that I need to retrieve the user token. Flask-Security documentation
clearly says that to retrieve the token one needs to perform an HTTP POST
with the authentication details as JSON data to the authentication
endpoint. Unfortunately I don't understand how to retrieve the CSRF token
needed to perform such request.
If I use the login page/template provided with the extension the CSRF
token is passed to the client in the hidden field in the form. The
question is:
how do I retrieve the CSRF token without accessing and parsing the login
page, like for example from an angularJS app using $http methods or a
mobile app?
Obviously I could avoid using Flask-Security and implement the pieces
myself but I'm relatively inexperienced with webapps and I feel I might be
approaching this the wrong way.
Would someone please straighten me out with this Android voice recognition class?
Would someone please straighten me out with this Android voice recognition
class?
I'm analyzing this Voice Recognizer class and need help understanding this
line in the code. What is the role of the following line? Does it create a
list of all of the activities on the android platform loaded on the
device? I especially find the resolve info bit confusing...
List activities = pm.queryIntentActivities(new Intent(
Here is the code used in context
package com.example.voicerecognitionactivity;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
public class VoiceRecognitionActivity extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;
private EditText metTextHint;
private ListView mlvTextMatches;
private Spinner msTextMatches;
private Button mbtSpeak;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
metTextHint = (EditText) findViewById(R.id.etTextHint);
mlvTextMatches = (ListView) findViewById(R.id.lvTextMatches);
msTextMatches = (Spinner) findViewById(R.id.sNoOfMatches);
mbtSpeak = (Button) findViewById(R.id.btSpeak);
}
public void checkVoiceRecognition() {
// Check if voice recognition is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0) {
mbtSpeak.setEnabled(false);
Toast.makeText(this, "Voice recognizer not present",
Toast.LENGTH_SHORT).show();
}
}
public void speak(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// Specify the calling package to identify your application
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
.getPackage().getName());
// Display an hint to the user about what he should say.
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, metTextHint.getText()
.toString());
// Given an hint to the recognizer about what the user is going to
say
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
// If number of Matches is not selected then return show toast
message
if (msTextMatches.getSelectedItemPosition() ==
AdapterView.INVALID_POSITION) {
Toast.makeText(this, "Please select No. of Matches from spinner",
Toast.LENGTH_SHORT).show();
return;
}
int noOfMatches = Integer.parseInt(msTextMatches.getSelectedItem()
.toString());
// Specify how many results you want to receive. The results will be
// sorted where the first result is the one with higher confidence.
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, noOfMatches);
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
//If Voice recognition is successful then it returns RESULT_OK
if(resultCode == RESULT_OK) {
ArrayList<String> textMatchList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (!textMatchList.isEmpty()) {
// If first Match contains the 'search' word
// Then start web search.
if (textMatchList.get(0).contains("search")) {
String searchQuery =
textMatchList.get(0).replace("search",
" ");
Intent search = new Intent(Intent.ACTION_WEB_SEARCH);
search.putExtra(SearchManager.QUERY, searchQuery);
startActivity(search);
} else {
// populate the Matches
mlvTextMatches
.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
textMatchList));
}
}
//Result code for various error.
}else if(resultCode == RecognizerIntent.RESULT_AUDIO_ERROR){
showToastMessage("Audio Error");
}else if(resultCode == RecognizerIntent.RESULT_CLIENT_ERROR){
showToastMessage("Client Error");
}else if(resultCode == RecognizerIntent.RESULT_NETWORK_ERROR){
showToastMessage("Network Error");
}else if(resultCode == RecognizerIntent.RESULT_NO_MATCH){
showToastMessage("No Match");
}else if(resultCode == RecognizerIntent.RESULT_SERVER_ERROR){
showToastMessage("Server Error");
}
super.onActivityResult(requestCode, resultCode, data);
}
void showToastMessage(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
class?
I'm analyzing this Voice Recognizer class and need help understanding this
line in the code. What is the role of the following line? Does it create a
list of all of the activities on the android platform loaded on the
device? I especially find the resolve info bit confusing...
List activities = pm.queryIntentActivities(new Intent(
Here is the code used in context
package com.example.voicerecognitionactivity;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
public class VoiceRecognitionActivity extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;
private EditText metTextHint;
private ListView mlvTextMatches;
private Spinner msTextMatches;
private Button mbtSpeak;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
metTextHint = (EditText) findViewById(R.id.etTextHint);
mlvTextMatches = (ListView) findViewById(R.id.lvTextMatches);
msTextMatches = (Spinner) findViewById(R.id.sNoOfMatches);
mbtSpeak = (Button) findViewById(R.id.btSpeak);
}
public void checkVoiceRecognition() {
// Check if voice recognition is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0) {
mbtSpeak.setEnabled(false);
Toast.makeText(this, "Voice recognizer not present",
Toast.LENGTH_SHORT).show();
}
}
public void speak(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// Specify the calling package to identify your application
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
.getPackage().getName());
// Display an hint to the user about what he should say.
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, metTextHint.getText()
.toString());
// Given an hint to the recognizer about what the user is going to
say
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
// If number of Matches is not selected then return show toast
message
if (msTextMatches.getSelectedItemPosition() ==
AdapterView.INVALID_POSITION) {
Toast.makeText(this, "Please select No. of Matches from spinner",
Toast.LENGTH_SHORT).show();
return;
}
int noOfMatches = Integer.parseInt(msTextMatches.getSelectedItem()
.toString());
// Specify how many results you want to receive. The results will be
// sorted where the first result is the one with higher confidence.
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, noOfMatches);
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
//If Voice recognition is successful then it returns RESULT_OK
if(resultCode == RESULT_OK) {
ArrayList<String> textMatchList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (!textMatchList.isEmpty()) {
// If first Match contains the 'search' word
// Then start web search.
if (textMatchList.get(0).contains("search")) {
String searchQuery =
textMatchList.get(0).replace("search",
" ");
Intent search = new Intent(Intent.ACTION_WEB_SEARCH);
search.putExtra(SearchManager.QUERY, searchQuery);
startActivity(search);
} else {
// populate the Matches
mlvTextMatches
.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
textMatchList));
}
}
//Result code for various error.
}else if(resultCode == RecognizerIntent.RESULT_AUDIO_ERROR){
showToastMessage("Audio Error");
}else if(resultCode == RecognizerIntent.RESULT_CLIENT_ERROR){
showToastMessage("Client Error");
}else if(resultCode == RecognizerIntent.RESULT_NETWORK_ERROR){
showToastMessage("Network Error");
}else if(resultCode == RecognizerIntent.RESULT_NO_MATCH){
showToastMessage("No Match");
}else if(resultCode == RecognizerIntent.RESULT_SERVER_ERROR){
showToastMessage("Server Error");
}
super.onActivityResult(requestCode, resultCode, data);
}
void showToastMessage(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
Because I can think of this in chrome?
Because I can think of this in chrome?
I have a header with these properties:
position: fixed;
top: 0px;
left: 0px;
background: rgba(0, 0, 0, 0.5);
font-size: 20px;
width:100%;
height: 45px;
z-index:100000000000000000;
http://jsfiddle.net/GxH9D/
In all browsers it looks good, but in chrome only looks a header height
1px. I think it has to do with the slider images of wallpaper. But do not
know how to fix it. Any help?
I have a header with these properties:
position: fixed;
top: 0px;
left: 0px;
background: rgba(0, 0, 0, 0.5);
font-size: 20px;
width:100%;
height: 45px;
z-index:100000000000000000;
http://jsfiddle.net/GxH9D/
In all browsers it looks good, but in chrome only looks a header height
1px. I think it has to do with the slider images of wallpaper. But do not
know how to fix it. Any help?
Cannot Connect To SQL Within Azure Network
Cannot Connect To SQL Within Azure Network
I am having a real hard time establishing SQL connection between servers
within a Azure network. The really odd thing is that I can connect to SQL
from my home machine which is outside the VM network. It seems like some
type of network issue from within the VM domain which I have not been able
to identify yet.
My configuration is as follows:
I have three VM's (Active Directory, Sql Server, and an App Server)
I am trying to establish SQL connection from app server to sql server
Both VM's Windows Server 2012
All servers are on the same azure network, affinity group, domain
All servers connected to the domain and have IP's
I can see DNS is resolving because I can ping the sql server from the app
server using the sql server's computer name
I created Firewall rules allowing in/out on port 1433 on both servers
SQL Server is listening on the default port because of this command
executed on the SQL Server (i'm not understanding the 0.0.0.0 IP though
which may be a problem) (I can connect from home so I think this is ok)
netstat -an | find ":1433"
TCP 0.0.0.0:1433 0.0.0.0:0 LISTENING
TCP [::]:1433 [::]:0 LISTENING
I created public & private endpoints on SQL for default sql port 1433
I can actually connect to SQL Server from my home machine
I have temporarily turned off firewalls on both servers
tracert from the app server looks like this.
tracert spsql01
Tracing route to spsql01 [10.0.0.7]
over a maximum of 30 hops:
1 * * * Request timed out.
2 * * * Request timed out.
3 * * * Request timed out.
4 5 ms <1 ms 1 ms spsql01 [10.0.0.7]
Trace complete.
On the App Server i create a connection.udl file to test the connection to
my SQL Server but it never passes the connection test.
I am having a real hard time establishing SQL connection between servers
within a Azure network. The really odd thing is that I can connect to SQL
from my home machine which is outside the VM network. It seems like some
type of network issue from within the VM domain which I have not been able
to identify yet.
My configuration is as follows:
I have three VM's (Active Directory, Sql Server, and an App Server)
I am trying to establish SQL connection from app server to sql server
Both VM's Windows Server 2012
All servers are on the same azure network, affinity group, domain
All servers connected to the domain and have IP's
I can see DNS is resolving because I can ping the sql server from the app
server using the sql server's computer name
I created Firewall rules allowing in/out on port 1433 on both servers
SQL Server is listening on the default port because of this command
executed on the SQL Server (i'm not understanding the 0.0.0.0 IP though
which may be a problem) (I can connect from home so I think this is ok)
netstat -an | find ":1433"
TCP 0.0.0.0:1433 0.0.0.0:0 LISTENING
TCP [::]:1433 [::]:0 LISTENING
I created public & private endpoints on SQL for default sql port 1433
I can actually connect to SQL Server from my home machine
I have temporarily turned off firewalls on both servers
tracert from the app server looks like this.
tracert spsql01
Tracing route to spsql01 [10.0.0.7]
over a maximum of 30 hops:
1 * * * Request timed out.
2 * * * Request timed out.
3 * * * Request timed out.
4 5 ms <1 ms 1 ms spsql01 [10.0.0.7]
Trace complete.
On the App Server i create a connection.udl file to test the connection to
my SQL Server but it never passes the connection test.
Saturday, 24 August 2013
Should I include Sphinx and/or Nose in my module's requirements.txt?
Should I include Sphinx and/or Nose in my module's requirements.txt?
I've created a Python module on Github that uses Nose for unit testing and
Sphinx for generating documentation. I have two questions:
Should I include Sphinx and/or Nose in my module's dependencies in
setup.py (install_requires), as they are not required for basic module
functionality, only if you want to build the documentation/run tests
yourself?
Should I include Sphinx and/or Nose in my module's requirements.txt on
Github, for the same reasons but users that download my project from
Github might be more likely to build docs/run tests?
This is my first Python module, so a bit of best practices/standards
advice would be appreciated.
I've created a Python module on Github that uses Nose for unit testing and
Sphinx for generating documentation. I have two questions:
Should I include Sphinx and/or Nose in my module's dependencies in
setup.py (install_requires), as they are not required for basic module
functionality, only if you want to build the documentation/run tests
yourself?
Should I include Sphinx and/or Nose in my module's requirements.txt on
Github, for the same reasons but users that download my project from
Github might be more likely to build docs/run tests?
This is my first Python module, so a bit of best practices/standards
advice would be appreciated.
jQuery Table Search filter on a PHP generated table
jQuery Table Search filter on a PHP generated table
I have a MySQL table with less than a thousand rows and it's fetched by a
PHP script. I would like to be able to sort the tbody by ASC or DESC order
when clicking a link and still be able to use the search bar like in the
this demo here. However when I try to incorporate the coding in my PHP
generated table, my search bar doesn't filter. I must be doing something
wrong.
Here's my PHP script:
$result = mysql_query("SELECT * FROM table_name");
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['fruits'] . "</td>";
echo "<td>" . $row['colors'] . "</td>";
echo "</tr>";
}
mysql_close();
If possible I'd like to have some hint, snippet or even examples would be
great!
Thanks
I have a MySQL table with less than a thousand rows and it's fetched by a
PHP script. I would like to be able to sort the tbody by ASC or DESC order
when clicking a link and still be able to use the search bar like in the
this demo here. However when I try to incorporate the coding in my PHP
generated table, my search bar doesn't filter. I must be doing something
wrong.
Here's my PHP script:
$result = mysql_query("SELECT * FROM table_name");
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['fruits'] . "</td>";
echo "<td>" . $row['colors'] . "</td>";
echo "</tr>";
}
mysql_close();
If possible I'd like to have some hint, snippet or even examples would be
great!
Thanks
Will flat file database work with relation between two columns?
Will flat file database work with relation between two columns?
Database.txt
Field1-Field2
Field3-Field4
Field1-Field2
Field1-Field2
[Saved the above data into a txt file from a html form]
**www.site.com/?type=Field1** should output **Field2**
**www.site.com/?type=Field3** should output **Field4**
....... and so on
I want to check all the Field1's for the type and if it is found, I want
to display Field2. What would be the best way to store data for this need?
How do I check the first column for a string and display it's
corresponding string? All in PHP.
Database.txt
Field1-Field2
Field3-Field4
Field1-Field2
Field1-Field2
[Saved the above data into a txt file from a html form]
**www.site.com/?type=Field1** should output **Field2**
**www.site.com/?type=Field3** should output **Field4**
....... and so on
I want to check all the Field1's for the type and if it is found, I want
to display Field2. What would be the best way to store data for this need?
How do I check the first column for a string and display it's
corresponding string? All in PHP.
Arc 4 random on fetchresultscontroller with predicate - leave out all entries of one type
Arc 4 random on fetchresultscontroller with predicate - leave out all
entries of one type
I am using arc 4 random to choose a random entry from my
fetchresultscontroller but I need to leave out all entries of a certain
category. The column is "Category" and I dont want the random choice to
include the category "Category2". Below is my current code, any help would
be greatly appreciated!
- (NSIndexPath *)randomIndexPath
{
NSInteger randomSection =
arc4random_uniform([[fetchedResultsController sections] count]);
id <NSFetchedResultsSectionInfo> sectionInfo =
[[fetchedResultsController sections] objectAtIndex:randomSection];
NSInteger randomIndex = arc4random_uniform( [sectionInfo
numberOfObjects]);
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:randomIndex
inSection:randomSection];
return indexPath;
}
- (IBAction)displayRandomEntry:(id)sender {
if([[fetchedResultsController sections] count] <= 0)
return;
NSIndexPath *indexPath = [self randomIndexPath];
[self.myTableView selectRowAtIndexPath:indexPath animated:YES
scrollPosition:UITableViewScrollPositionMiddle];
id object = [fetchedResultsController objectAtIndexPath:indexPath];
RandomEntryDetailVC * controller;
controller = [self.storyboard
instantiateViewControllerWithIdentifier:@"ShowRandomEntryDetailVC"];
controller.currentItem = object;
[self.navigationController pushViewController:controller animated:YES];
}
entries of one type
I am using arc 4 random to choose a random entry from my
fetchresultscontroller but I need to leave out all entries of a certain
category. The column is "Category" and I dont want the random choice to
include the category "Category2". Below is my current code, any help would
be greatly appreciated!
- (NSIndexPath *)randomIndexPath
{
NSInteger randomSection =
arc4random_uniform([[fetchedResultsController sections] count]);
id <NSFetchedResultsSectionInfo> sectionInfo =
[[fetchedResultsController sections] objectAtIndex:randomSection];
NSInteger randomIndex = arc4random_uniform( [sectionInfo
numberOfObjects]);
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:randomIndex
inSection:randomSection];
return indexPath;
}
- (IBAction)displayRandomEntry:(id)sender {
if([[fetchedResultsController sections] count] <= 0)
return;
NSIndexPath *indexPath = [self randomIndexPath];
[self.myTableView selectRowAtIndexPath:indexPath animated:YES
scrollPosition:UITableViewScrollPositionMiddle];
id object = [fetchedResultsController objectAtIndexPath:indexPath];
RandomEntryDetailVC * controller;
controller = [self.storyboard
instantiateViewControllerWithIdentifier:@"ShowRandomEntryDetailVC"];
controller.currentItem = object;
[self.navigationController pushViewController:controller animated:YES];
}
adding php dropdown menu within li items
adding php dropdown menu within li items
With modification of the code below, I would like to display the following
html output (i.e class="more" and its dropdown menu. Can anyone please
suggest me a workaround?
<?php
$pages = array(
'0' => array('title' => 'Health', 'url' => 'health.php'),
'1' => array('title' => 'Weightl Loss', 'url' => 'weightloss.php'),
'2' => array('title' => 'Fitness', 'url' => 'fitness.php'),
'3' => array('title' => 'Sex', 'url' => 'sex.php'),
'4' => array('title' => 'Mind-Body', 'url' => 'mindbody.php'),
'5' => array('title' => 'Food', 'url' => 'food.php'),
'6' => array('title' => 'Beauty', 'url' => 'beauty.php'),
);
echo "<div id=\"nav-menu\" >\n";
// let's create a unordered list to display the items
echo "<ul>";
// here's where all the items get printed
foreach ($pages as $Listing) {
echo "<li>\n";
echo "<a href='" . $Listing["url"] . "'>" . $Listing["title"] . "</a>\n";
echo "</li>\n";
}
// closing the unordered list
echo "</ul>";
echo "</div>\n";
?>
Here is the desired html output.
<div id="nav-menu" >
<ul>
<li><a href='health.php'>Health</a></li>
<li><a href='weightloss.php'>Weightl Loss</a></li>
<li><a href='fitness.php'>Fitness</a></li>
<li><a href='sex.php'>Sex</a></li>
<li><a href='mindbody.php'>Mind-Body</a></li>
<li><a href='food.php'>Food</a></li>
<li><a href='beauty.php'>Beauty</a></li>
<li class="more"> <span>More <img src="w.png"
id="down-arrow-white"><img src="b.png"
id="down-arrow-dark-blue"></span>
<ul style="display: none;" id="more-menu">
<li><a href="blogs.php">Blogs</a></li>
<li><a href="horoscopes.php">Horoscopes</a></li>
</ul><!-- /more_menu -->
</li>
</ul>
</div>
With modification of the code below, I would like to display the following
html output (i.e class="more" and its dropdown menu. Can anyone please
suggest me a workaround?
<?php
$pages = array(
'0' => array('title' => 'Health', 'url' => 'health.php'),
'1' => array('title' => 'Weightl Loss', 'url' => 'weightloss.php'),
'2' => array('title' => 'Fitness', 'url' => 'fitness.php'),
'3' => array('title' => 'Sex', 'url' => 'sex.php'),
'4' => array('title' => 'Mind-Body', 'url' => 'mindbody.php'),
'5' => array('title' => 'Food', 'url' => 'food.php'),
'6' => array('title' => 'Beauty', 'url' => 'beauty.php'),
);
echo "<div id=\"nav-menu\" >\n";
// let's create a unordered list to display the items
echo "<ul>";
// here's where all the items get printed
foreach ($pages as $Listing) {
echo "<li>\n";
echo "<a href='" . $Listing["url"] . "'>" . $Listing["title"] . "</a>\n";
echo "</li>\n";
}
// closing the unordered list
echo "</ul>";
echo "</div>\n";
?>
Here is the desired html output.
<div id="nav-menu" >
<ul>
<li><a href='health.php'>Health</a></li>
<li><a href='weightloss.php'>Weightl Loss</a></li>
<li><a href='fitness.php'>Fitness</a></li>
<li><a href='sex.php'>Sex</a></li>
<li><a href='mindbody.php'>Mind-Body</a></li>
<li><a href='food.php'>Food</a></li>
<li><a href='beauty.php'>Beauty</a></li>
<li class="more"> <span>More <img src="w.png"
id="down-arrow-white"><img src="b.png"
id="down-arrow-dark-blue"></span>
<ul style="display: none;" id="more-menu">
<li><a href="blogs.php">Blogs</a></li>
<li><a href="horoscopes.php">Horoscopes</a></li>
</ul><!-- /more_menu -->
</li>
</ul>
</div>
Cmake and GLEW library
Cmake and GLEW library
I'm trying to compile a simple project on QT Creator. I decided to use
Cmake, so I have the following CMakeLists.txt
project(testopengl)
cmake_minimum_required(VERSION 2.8)
aux_source_directory(. SRC_LIST)
#==========================================================
# FIND GLUT
#==========================================================
find_package(GLUT REQUIRED)
include_directories(${GLUT_INCLUDE_DIRS})
link_directories(${GLUT_LIBRARY_DIRS})
add_definitions(${GLUT_DEFINITIONS})
if(NOT GLUT_FOUND)
message(ERROR " GLUT not found!")
endif(NOT GLUT_FOUND)
#==========================================================
# FIND OPENGL
#==========================================================
find_package(OpenGL REQUIRED)
include_directories(${OpenGL_INCLUDE_DIRS})
link_directories(${OpenGL_LIBRARY_DIRS})
add_definitions(${OpenGL_DEFINITIONS})
if(NOT OPENGL_FOUND)
message(ERROR " OPENGL not found!")
endif(NOT OPENGL_FOUND)
#==========================================================
#==========================================================
# FIND GLEW
#==========================================================
find_package(GlEW REQUIRED)
include_directories(${GLEW_INCLUDE_DIRS})
link_directories(${GLEW_LIBRARY_DIRS})
add_definitions(${GLEW_DEFINITIONS})
if(NOT GLEW_FOUND)
message(ERROR " GLEW not found!")
endif(NOT GLEW_FOUND)
#==========================================================
add_executable(${PROJECT_NAME} ${SRC_LIST})
target_link_libraries(${PROJECT_NAME} ${OPENGL_LIBRARIES} ${GLUT_LIBRARY}
${GLEW_LIBRARY})
But I obtained this output:
Could not find a package configuration file provided by "GlEW" with any of
the following names:
GlEWConfig.cmake
glew-config.cmake
O I tried compiling a previuos "running" project without GLEW functions,
so I added them to the project, and also added the flag -lGLEW but it
could not compile
"cmd": [ "g++ \"$file\" -o \"$file_base_name\" -lGLU -lGL -lglut &&
./\"$file_base_name\""],
I was using the last one on "sublime", then I added GLEW
"cmd": [ "g++ \"$file\" -o \"$file_base_name\" -lGLU -lGL -lglut -lGLEW &&
./\"$file_base_name\""],
So I decided to install GLEW from the official page:
http://glew.sourceforge.net/
I did:
sudo make
sudo make install
I tried the last two "solutions" they still not working.
What can I do?
I'm trying to compile a simple project on QT Creator. I decided to use
Cmake, so I have the following CMakeLists.txt
project(testopengl)
cmake_minimum_required(VERSION 2.8)
aux_source_directory(. SRC_LIST)
#==========================================================
# FIND GLUT
#==========================================================
find_package(GLUT REQUIRED)
include_directories(${GLUT_INCLUDE_DIRS})
link_directories(${GLUT_LIBRARY_DIRS})
add_definitions(${GLUT_DEFINITIONS})
if(NOT GLUT_FOUND)
message(ERROR " GLUT not found!")
endif(NOT GLUT_FOUND)
#==========================================================
# FIND OPENGL
#==========================================================
find_package(OpenGL REQUIRED)
include_directories(${OpenGL_INCLUDE_DIRS})
link_directories(${OpenGL_LIBRARY_DIRS})
add_definitions(${OpenGL_DEFINITIONS})
if(NOT OPENGL_FOUND)
message(ERROR " OPENGL not found!")
endif(NOT OPENGL_FOUND)
#==========================================================
#==========================================================
# FIND GLEW
#==========================================================
find_package(GlEW REQUIRED)
include_directories(${GLEW_INCLUDE_DIRS})
link_directories(${GLEW_LIBRARY_DIRS})
add_definitions(${GLEW_DEFINITIONS})
if(NOT GLEW_FOUND)
message(ERROR " GLEW not found!")
endif(NOT GLEW_FOUND)
#==========================================================
add_executable(${PROJECT_NAME} ${SRC_LIST})
target_link_libraries(${PROJECT_NAME} ${OPENGL_LIBRARIES} ${GLUT_LIBRARY}
${GLEW_LIBRARY})
But I obtained this output:
Could not find a package configuration file provided by "GlEW" with any of
the following names:
GlEWConfig.cmake
glew-config.cmake
O I tried compiling a previuos "running" project without GLEW functions,
so I added them to the project, and also added the flag -lGLEW but it
could not compile
"cmd": [ "g++ \"$file\" -o \"$file_base_name\" -lGLU -lGL -lglut &&
./\"$file_base_name\""],
I was using the last one on "sublime", then I added GLEW
"cmd": [ "g++ \"$file\" -o \"$file_base_name\" -lGLU -lGL -lglut -lGLEW &&
./\"$file_base_name\""],
So I decided to install GLEW from the official page:
http://glew.sourceforge.net/
I did:
sudo make
sudo make install
I tried the last two "solutions" they still not working.
What can I do?
Convert ISO-8859-2 to UTF-8 (Polish characters)
Convert ISO-8859-2 to UTF-8 (Polish characters)
I'm trying to parse an XML file (http://jstryczek.blox.pl/rss2) that says
its character set is ISO-8859-2. My database is in UTF-8, so I want to
convert it to UTF-8.
To do that I run the following on the string:
$content = iconv('ISO-8859-2', 'UTF-8//TRANSLIT', $content);
For some reason, I'm getting back an odd encoding, so that:
Gdzie s¹ ró¿nice
Comes through as:
Gdzie są róşnice
Is there an explanation for why the Polish characters aren't coming
through? Does UTF-8 not support them?
I'm trying to parse an XML file (http://jstryczek.blox.pl/rss2) that says
its character set is ISO-8859-2. My database is in UTF-8, so I want to
convert it to UTF-8.
To do that I run the following on the string:
$content = iconv('ISO-8859-2', 'UTF-8//TRANSLIT', $content);
For some reason, I'm getting back an odd encoding, so that:
Gdzie s¹ ró¿nice
Comes through as:
Gdzie są róşnice
Is there an explanation for why the Polish characters aren't coming
through? Does UTF-8 not support them?
click a button in JMeter
click a button in JMeter
I need to click an Add button.I have traversed to the page having the
Button,as verified from Response data in View Results Tree. I tried making
a get request (post button click URL)but that didn't work.
Below is the HTML of the Button
<button class="bigbutton ui-button ui-widget ui-state-default
ui-corner-all ui-button-text-only" onclick="var win =
this.ownerDocument.defaultView || this.ownerDocument.parentWindow; if (win
== window) {
window.location.href='?x=KOGI5TeEN-U*JE6roI7oZMd-OfKSr5oQnRTh7tHdN*Bh66LwE2vEHDjxo9WFuOf7Ti2zcBh-IaE';
} ;return false" style="float: right;" role="button"
aria-disabled="false">
Add
I need to click an Add button.I have traversed to the page having the
Button,as verified from Response data in View Results Tree. I tried making
a get request (post button click URL)but that didn't work.
Below is the HTML of the Button
<button class="bigbutton ui-button ui-widget ui-state-default
ui-corner-all ui-button-text-only" onclick="var win =
this.ownerDocument.defaultView || this.ownerDocument.parentWindow; if (win
== window) {
window.location.href='?x=KOGI5TeEN-U*JE6roI7oZMd-OfKSr5oQnRTh7tHdN*Bh66LwE2vEHDjxo9WFuOf7Ti2zcBh-IaE';
} ;return false" style="float: right;" role="button"
aria-disabled="false">
Add
How I can correctly use command "if" in Message Dialog?
How I can correctly use command "if" in Message Dialog?
I`m new in Java. I would like to ask how I can use "if" in Message Dialog?
If "age" under 15, add message to new line of Message Dialog-
"You`re so baby"
I wrote this codes but it was error.Please help.
import javax.swing.JOptionPane;
public class Isim {
public static void main(String[] args) {
// TODO Auto-generated method stub
String name, age, baby;
name = JOptionPane.showInputDialog(null, "Enter Your name");
age = JOptionPane.showInputDialog(null, "Enter Your Age");
int i = new Integer(age).intValue();
baby = "You`re so baby";
JOptionPane.showMessageDialog(null, "Your Name is: "+name+"\n"+"Your
Age is: "+age+"\n"+if (i < 15){baby});
}
}
I`m new in Java. I would like to ask how I can use "if" in Message Dialog?
If "age" under 15, add message to new line of Message Dialog-
"You`re so baby"
I wrote this codes but it was error.Please help.
import javax.swing.JOptionPane;
public class Isim {
public static void main(String[] args) {
// TODO Auto-generated method stub
String name, age, baby;
name = JOptionPane.showInputDialog(null, "Enter Your name");
age = JOptionPane.showInputDialog(null, "Enter Your Age");
int i = new Integer(age).intValue();
baby = "You`re so baby";
JOptionPane.showMessageDialog(null, "Your Name is: "+name+"\n"+"Your
Age is: "+age+"\n"+if (i < 15){baby});
}
}
Friday, 23 August 2013
Confusion related to gaussian integral
Confusion related to gaussian integral
What is the integral of the following function
$exp^{(-1/2y^T\Omega y - v^Ty)}$ with respect to dy.where $\Omega$ is a
positive definite matrix
What is the integral of the following function
$exp^{(-1/2y^T\Omega y - v^Ty)}$ with respect to dy.where $\Omega$ is a
positive definite matrix
Can a neighbourhood of a point be an singleton set?
Can a neighbourhood of a point be an singleton set?
Can a neighbourhood of a point be a singleton set containing that point
only ?
Can a neighbourhood of a point be a singleton set containing that point
only ?
No access to facebook fan page
No access to facebook fan page
I have a fan page link of the fan page
Since yesterday I have no access to this fan page. The content creators I
had also have no access, there were about 20 content creators. The fan
page just dont appear on pages in my facebook account. I emailed facebook
a few times and also many other people did. How can facebook shut a fan
page of 80000 likes down without giving me any infos? To build a fan page
on this level it takes a lot of work. If there would some content facebook
dont like I think they could tell me and I would fix it instantly. But if
it would be issue of content then the site should be not visible anymore.
Somebody any ideas of how to proceed or how to get in contact with
facebook? It seems that my emails to facebook are not helping because
facebook never responds.
I have a fan page link of the fan page
Since yesterday I have no access to this fan page. The content creators I
had also have no access, there were about 20 content creators. The fan
page just dont appear on pages in my facebook account. I emailed facebook
a few times and also many other people did. How can facebook shut a fan
page of 80000 likes down without giving me any infos? To build a fan page
on this level it takes a lot of work. If there would some content facebook
dont like I think they could tell me and I would fix it instantly. But if
it would be issue of content then the site should be not visible anymore.
Somebody any ideas of how to proceed or how to get in contact with
facebook? It seems that my emails to facebook are not helping because
facebook never responds.
How to display markers in groundOverlay map?
How to display markers in groundOverlay map?
I can manage to display my image overlay on the map. But a new problem
occurs - I can't add a marker on it. I googled it for a while but no luck.
Tried to search and mimic the example on documentation and nothing appears
to be right.
Here's my code :
<script
src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
function initialize() {
var newark = new google.maps.LatLng(xx.xxxxx,xx.xxxxx);
var imageBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(xx.xxxxx,xx.xxxxx),//SW
new google.maps.LatLng(xx.xxxxx,xx.xxxxx)//NE
);
var mapOptions = {
zoom: 20,
center: newark,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var oldmap = new google.maps.GroundOverlay(
'images/floor_plan_trans_rotated.gif',
imageBounds);
oldmap.setMap(map);
}
/*markers*/
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">Uluru</h1>'+
'<div id="bodyContent">'+
'<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a
large ' +
'sandstone rock formation in the southern part of the '+
'Northern Territory, central Australia. It lies 335 km
(208 mi) '+
'south west of the nearest large town, Alice Springs;
450 km '+
</p>'+
'<p>Attribution: Uluru, <a
href="http://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+
'http://en.wikipedia.org/w/index.php?title=Uluru</a> '+
'(last visited June 22, 2009).</p>'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString,
maxWidth: 400
});
var marker = new google.maps.Marker({
position: newark,
map: map,
title: 'Uluru (Ayers Rock)'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
/*markers*/
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map-canvas"></div>
For the code above. The map will not display unless I delete those lines
between /markers/.
Please suggest. Regards,
I can manage to display my image overlay on the map. But a new problem
occurs - I can't add a marker on it. I googled it for a while but no luck.
Tried to search and mimic the example on documentation and nothing appears
to be right.
Here's my code :
<script
src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
function initialize() {
var newark = new google.maps.LatLng(xx.xxxxx,xx.xxxxx);
var imageBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(xx.xxxxx,xx.xxxxx),//SW
new google.maps.LatLng(xx.xxxxx,xx.xxxxx)//NE
);
var mapOptions = {
zoom: 20,
center: newark,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var oldmap = new google.maps.GroundOverlay(
'images/floor_plan_trans_rotated.gif',
imageBounds);
oldmap.setMap(map);
}
/*markers*/
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">Uluru</h1>'+
'<div id="bodyContent">'+
'<p><b>Uluru</b>, also referred to as <b>Ayers Rock</b>, is a
large ' +
'sandstone rock formation in the southern part of the '+
'Northern Territory, central Australia. It lies 335 km
(208 mi) '+
'south west of the nearest large town, Alice Springs;
450 km '+
</p>'+
'<p>Attribution: Uluru, <a
href="http://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">'+
'http://en.wikipedia.org/w/index.php?title=Uluru</a> '+
'(last visited June 22, 2009).</p>'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString,
maxWidth: 400
});
var marker = new google.maps.Marker({
position: newark,
map: map,
title: 'Uluru (Ayers Rock)'
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
/*markers*/
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map-canvas"></div>
For the code above. The map will not display unless I delete those lines
between /markers/.
Please suggest. Regards,
Why are these other permissions being included in my Phonegap Android app?
Why are these other permissions being included in my Phonegap Android app?
I am using the Google Android Development Tools (Eclipse) with the
Phonegap plugin to create my Android app.
In my AndroidManifest.xml file, I only have these three permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.android.vending.BILLING" />
However, when I install my app on my Android phone, it shows a request for
the following permissions*
Storage(modify or delete the contents of your USB Storage
Network Communication (full network access)
Phone Calls (read phone status and identity)
Network Communication (Google Play billing service, view network connections)
Development Tools(test access to protected storage)
I definitely don't want Phone Calls, and I'm pretty sure I don't need
Development Tools or Storage.
Why are these permissions being included, and how do I remove them from my
app?
I am using the Google Android Development Tools (Eclipse) with the
Phonegap plugin to create my Android app.
In my AndroidManifest.xml file, I only have these three permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.android.vending.BILLING" />
However, when I install my app on my Android phone, it shows a request for
the following permissions*
Storage(modify or delete the contents of your USB Storage
Network Communication (full network access)
Phone Calls (read phone status and identity)
Network Communication (Google Play billing service, view network connections)
Development Tools(test access to protected storage)
I definitely don't want Phone Calls, and I'm pretty sure I don't need
Development Tools or Storage.
Why are these permissions being included, and how do I remove them from my
app?
Malware spaming from my site
Malware spaming from my site
Seomeone placed script in my site that send email, how I cant found this
script ? I use parallels and Linux CentOs.
I'm search keyword in site "mail(", but also cant be that code is like hash
Seomeone placed script in my site that send email, how I cant found this
script ? I use parallels and Linux CentOs.
I'm search keyword in site "mail(", but also cant be that code is like hash
Thursday, 22 August 2013
Not able to use Date filed in Parcelable class in android
Not able to use Date filed in Parcelable class in android
I am working in an android project and I want to pass a List of object
from once activity to another activity . In the object there are Date
fields too.. I have implemented my class with Parcelable to pass my List
of Object from one activity and I am not not to parse my Date field. So
please suggest me a solution.
This is the class I want to pass
public class Consumer {
public int BusClientLogID;
public int ClientID;
public String ClientName;
public int ClientStatus;
public int Client_GroupStatus;
public String EmployeeName;
public String ServiceCompletedCount;
public Date SignInTime;
public Date TimeArrive;
public Date TimeDepart;
public Date SignOutTime;
}
I am working in an android project and I want to pass a List of object
from once activity to another activity . In the object there are Date
fields too.. I have implemented my class with Parcelable to pass my List
of Object from one activity and I am not not to parse my Date field. So
please suggest me a solution.
This is the class I want to pass
public class Consumer {
public int BusClientLogID;
public int ClientID;
public String ClientName;
public int ClientStatus;
public int Client_GroupStatus;
public String EmployeeName;
public String ServiceCompletedCount;
public Date SignInTime;
public Date TimeArrive;
public Date TimeDepart;
public Date SignOutTime;
}
JavaScript Closures Manipulation
JavaScript Closures Manipulation
Im doing some Node and i want to use the closure representation to create
my objects. I think i'm missing something, because something simple like
this isn't working:
var Room = function(foo) {
this.name = foo;
this.users= [];
return {
getName : function() {
return this.name;
}
}
}
var room = new Room("foo");
console.log(room.getName());
I also tried without the parameter.. and still not working.
var Room = function() {
this.name = "foo";
this.users= [];
return {
getName : function() {
return this.name;
}
}
}
var room = new Room();
console.log(room.getName());
However, something like this works:
var Room = function(foo) {
this.name = foo;
this.users= [];
}
var room = new Room("foo");
console.log(room.name);
I can't understand why this isn't working.
Thanks for the help.
Im doing some Node and i want to use the closure representation to create
my objects. I think i'm missing something, because something simple like
this isn't working:
var Room = function(foo) {
this.name = foo;
this.users= [];
return {
getName : function() {
return this.name;
}
}
}
var room = new Room("foo");
console.log(room.getName());
I also tried without the parameter.. and still not working.
var Room = function() {
this.name = "foo";
this.users= [];
return {
getName : function() {
return this.name;
}
}
}
var room = new Room();
console.log(room.getName());
However, something like this works:
var Room = function(foo) {
this.name = foo;
this.users= [];
}
var room = new Room("foo");
console.log(room.name);
I can't understand why this isn't working.
Thanks for the help.
How can I enter Username & Password for API in a GET request?
How can I enter Username & Password for API in a GET request?
I have a simple API protected by a username & password. How do I enter the
username & password in a JSON get request?
like this?
http://ankur:secure1234@ankur1.local/index.php/api/example/users
Where ankur:secure1234 is username:password.
I have a simple API protected by a username & password. How do I enter the
username & password in a JSON get request?
like this?
http://ankur:secure1234@ankur1.local/index.php/api/example/users
Where ankur:secure1234 is username:password.
RESTful graphing application or web service
RESTful graphing application or web service
Problem
Have a server-side application that generates a large amount of logging
and statistical data that needs to be analyzed for the purposes of
monitoring and diagnostics.
Currently, we use a Javascript graphing library to request the information
from the server and graph it in a web browser. However, this requires a
lot of developer hours in designing the UX and implementing the graphing
functionality.
Question
Is there a better way to do this? Perhaps a web service or desktop
application that can request the information from our servers and display
it in the way that we need to see it?
Example of what we have now:
Problem
Have a server-side application that generates a large amount of logging
and statistical data that needs to be analyzed for the purposes of
monitoring and diagnostics.
Currently, we use a Javascript graphing library to request the information
from the server and graph it in a web browser. However, this requires a
lot of developer hours in designing the UX and implementing the graphing
functionality.
Question
Is there a better way to do this? Perhaps a web service or desktop
application that can request the information from our servers and display
it in the way that we need to see it?
Example of what we have now:
Route file doesn't route to the right controller, once updated
Route file doesn't route to the right controller, once updated
I have this problem :
I have my route file, containing a valid route to a controller. I compile,
I have no error. I send a request, it calls the right method on the right
controller, everything is working.
Then I changed the name of that controller and changed it in the route
file. I compile, I have no error. But when I send a request (I see it via
my proxy), the request is never transmitted to the controller.
If I change the name of the controller back to the first one, it works !!
I have reboot and clean-all, but nothing works, do you have an idea ?
I have this problem :
I have my route file, containing a valid route to a controller. I compile,
I have no error. I send a request, it calls the right method on the right
controller, everything is working.
Then I changed the name of that controller and changed it in the route
file. I compile, I have no error. But when I send a request (I see it via
my proxy), the request is never transmitted to the controller.
If I change the name of the controller back to the first one, it works !!
I have reboot and clean-all, but nothing works, do you have an idea ?
How to implement custom compar() for scandir()
How to implement custom compar() for scandir()
I've been reading the man pages of scandir(), alphasort() and have
evidently crammed them all. But still can't figure out how to implement a
custom comparision function.
Here's my code:
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
int mySort(char*, char*);
int (*fnPtr)(char*, char*);
int main(){
struct dirent **entryList;
fnPtr = &mySort;
int count = scandir(".",&entryList,NULL,fnptr);
for(count--;count>=0;count--){
printf("%s\n",entryList[count]->d_name);
}
return 0;
}
int mySort(const void* a, const void* b){
char *aNew, *bNew;
if(a[0] == '.'){
*aNew = removeDot(a);
}
else{
aNew = a;
}
if(b[0] == '.'){
*bNew = removeDot(b);
}
else{
bNew = b;
}
return alphasort(aNew, bNew);
}
Easy to see that am trying to alphabetically sort file names irrespective
of hidden and normal files (leading '.').
But a computer will always do what you tell it to but not what you want it
to.
I've been reading the man pages of scandir(), alphasort() and have
evidently crammed them all. But still can't figure out how to implement a
custom comparision function.
Here's my code:
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
int mySort(char*, char*);
int (*fnPtr)(char*, char*);
int main(){
struct dirent **entryList;
fnPtr = &mySort;
int count = scandir(".",&entryList,NULL,fnptr);
for(count--;count>=0;count--){
printf("%s\n",entryList[count]->d_name);
}
return 0;
}
int mySort(const void* a, const void* b){
char *aNew, *bNew;
if(a[0] == '.'){
*aNew = removeDot(a);
}
else{
aNew = a;
}
if(b[0] == '.'){
*bNew = removeDot(b);
}
else{
bNew = b;
}
return alphasort(aNew, bNew);
}
Easy to see that am trying to alphabetically sort file names irrespective
of hidden and normal files (leading '.').
But a computer will always do what you tell it to but not what you want it
to.
Unmet Dependency problem when installing Ubuntu One in 12.04
Unmet Dependency problem when installing Ubuntu One in 12.04
I just installed Ubuntu 12.04 and installed all the updates available. The
third step was I tried to install Ubuntu One using the ubuntuone-installer
and this is what I get:
The text says:
The following packages have unmet dependencies:
ubuntuone-control-panel-qt: Depends: python (< 2.8) but 2.7.3-0ubuntu2 is
to be installed Depends: python-ubuntuone-control-panel (= 3.0.1-0ubuntu1)
but 3.0.1-0ubuntu1 is to be installed Depends: ubuntuone-control-panel (=
3.0.1-0ubuntu1) but 3.0.1-0ubuntu1 is to be installed Depends:
ubuntuone-control-panel-common (= 3.0.1-0ubuntu1) but 3.0.1-0ubuntu1 is to
be installed
All attempts to run apt-get with --fixed-broken or dist-upgrade have failed
I just installed Ubuntu 12.04 and installed all the updates available. The
third step was I tried to install Ubuntu One using the ubuntuone-installer
and this is what I get:
The text says:
The following packages have unmet dependencies:
ubuntuone-control-panel-qt: Depends: python (< 2.8) but 2.7.3-0ubuntu2 is
to be installed Depends: python-ubuntuone-control-panel (= 3.0.1-0ubuntu1)
but 3.0.1-0ubuntu1 is to be installed Depends: ubuntuone-control-panel (=
3.0.1-0ubuntu1) but 3.0.1-0ubuntu1 is to be installed Depends:
ubuntuone-control-panel-common (= 3.0.1-0ubuntu1) but 3.0.1-0ubuntu1 is to
be installed
All attempts to run apt-get with --fixed-broken or dist-upgrade have failed
Wednesday, 21 August 2013
Work with Document Scanner in php
Work with Document Scanner in php
Is there any solution for manage document scanner connected to server with
php? in fact, we have a scanner that connected to server, we want scan
documents with php codes.
Is there any solution for manage document scanner connected to server with
php? in fact, we have a scanner that connected to server, we want scan
documents with php codes.
XEN Hypervisor migration
XEN Hypervisor migration
I know that there is no Type 2 hypervisor solution to run on an existing
OS, what I'm wondering is, is there a server or a way to spin up and image
localy on some sort of work station for devalopement then Migrate it over
to an Xen server?
Any information on this would be gratly appriciated.
Regards Tea
I know that there is no Type 2 hypervisor solution to run on an existing
OS, what I'm wondering is, is there a server or a way to spin up and image
localy on some sort of work station for devalopement then Migrate it over
to an Xen server?
Any information on this would be gratly appriciated.
Regards Tea
I see the three dots when texting but no message appears, why?
I see the three dots when texting but no message appears, why?
When I text another Iphone user I see the baloon with the three dots but
sometimes it looks like they are typing but no message appears. Is it
possible they are typing a text to a differant user?
When I text another Iphone user I see the baloon with the three dots but
sometimes it looks like they are typing but no message appears. Is it
possible they are typing a text to a differant user?
Custom default referances for Solution Visual C# 2010
Custom default referances for Solution Visual C# 2010
Is there a way to configure the current solution such that every new
project created (or imported possibly) has references that you can
configure rather than having to go through every project and add
reference?
Is there a way to configure the current solution such that every new
project created (or imported possibly) has references that you can
configure rather than having to go through every project and add
reference?
How to runCommand() of a bash script with redirected input from file in Mozilla Rhino?
How to runCommand() of a bash script with redirected input from file in
Mozilla Rhino?
Is it possible to execute external bash script and set another file as
input for it using Rhino? e.g. I need to rewrite bash script(exec.sh) with
following content:
somescript.sh <fileInput.txt
I've tried many ways but without success:
Reading fileInput.txt as input stream and passing to shell:
var inputStream = new java.io.InputStream(fileInput.txt);
runCommand( "somescript.sh", inputStream);
Writing "somescript.sh
message = new FileUtils.writeStringToFile(helpfulScript, "somescript.sh
runCommand("bash", helpfulScript.getCanonicalPath());
Sorry for pure highlight and thanks in advice for any ideas.
Mozilla Rhino?
Is it possible to execute external bash script and set another file as
input for it using Rhino? e.g. I need to rewrite bash script(exec.sh) with
following content:
somescript.sh <fileInput.txt
I've tried many ways but without success:
Reading fileInput.txt as input stream and passing to shell:
var inputStream = new java.io.InputStream(fileInput.txt);
runCommand( "somescript.sh", inputStream);
Writing "somescript.sh
message = new FileUtils.writeStringToFile(helpfulScript, "somescript.sh
runCommand("bash", helpfulScript.getCanonicalPath());
Sorry for pure highlight and thanks in advice for any ideas.
Where IN to JOINT how?
Where IN to JOINT how?
Writing down this using JOIN ..how? because this is very slow..
SELECT *
FROM table1
WHERE ID IN (SELECT ID
FROM table1
GROUP BY ID
HAVING COUNT(*) = 2
AND MAX(awaiting) = 1)
AND awaiting = 1
so, how can I write?
Writing down this using JOIN ..how? because this is very slow..
SELECT *
FROM table1
WHERE ID IN (SELECT ID
FROM table1
GROUP BY ID
HAVING COUNT(*) = 2
AND MAX(awaiting) = 1)
AND awaiting = 1
so, how can I write?
Is it possible to use coffee file system (as a library) in my project without the Contiki OS?
Is it possible to use coffee file system (as a library) in my project
without the Contiki OS?
So, for an embedded project with external NOR flash and existing
commercial RTOS, can I use the coffee filesystem in a form of a library,
i.e. to compile it in? From what I've seen it seems possible, only the
dependencies go quite deep in to Contiki. I'll surely dig in, but may be
someone have done something of the kind already? Thanks.
without the Contiki OS?
So, for an embedded project with external NOR flash and existing
commercial RTOS, can I use the coffee filesystem in a form of a library,
i.e. to compile it in? From what I've seen it seems possible, only the
dependencies go quite deep in to Contiki. I'll surely dig in, but may be
someone have done something of the kind already? Thanks.
Tuesday, 20 August 2013
wrong link displayed in vews page
wrong link displayed in vews page
I have a very strange problem with a link inside text storing in database :
the text is :
here is the link : <a href=\\"http://www.cnn.com\\">test
link</a></p>
in output or my html page I get :
here is the link : test link
but I get a wrong link : http://www.example.com/page/view/http://www.cnn.com
My question is how to remove my site link and get just the correct link
from database and show it correctly?
I have a very strange problem with a link inside text storing in database :
the text is :
here is the link : <a href=\\"http://www.cnn.com\\">test
link</a></p>
in output or my html page I get :
here is the link : test link
but I get a wrong link : http://www.example.com/page/view/http://www.cnn.com
My question is how to remove my site link and get just the correct link
from database and show it correctly?
Unsetting a value from local storage on click
Unsetting a value from local storage on click
I'm using local storage to save the id as seen below, it works as it's
suppose to. When I click on the anchor it sends the value to local
storage. The problem is when I click it again, it saves that same value
again. I would like to take that value out of storage on the second click.
So basically I want it to act as a toggle.
$(".favorites").click(function() {
var favorite = JSON.parse(localStorage.getItem( 'favorite' ));
if (favorite == undefined)
{
favorite = Array();
}
favorite.push($(this).attr('data-petid'));
localStorage.setItem( 'favorite', JSON.stringify(favorite) );
JSON.parse( localStorage.getItem( 'favorite' ) );
});
I'm using local storage to save the id as seen below, it works as it's
suppose to. When I click on the anchor it sends the value to local
storage. The problem is when I click it again, it saves that same value
again. I would like to take that value out of storage on the second click.
So basically I want it to act as a toggle.
$(".favorites").click(function() {
var favorite = JSON.parse(localStorage.getItem( 'favorite' ));
if (favorite == undefined)
{
favorite = Array();
}
favorite.push($(this).attr('data-petid'));
localStorage.setItem( 'favorite', JSON.stringify(favorite) );
JSON.parse( localStorage.getItem( 'favorite' ) );
});
ComboBoxModel - removeItem method for fireIntervalRemoved throws exception
ComboBoxModel - removeItem method for fireIntervalRemoved throws exception
I've created a ComboBoxModel class which extends AbstractListModel. I can
add item to the combobox, but when I try to remove, I get an exception
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException:
null source
at line
this.fireIntervalRemoved(selectedItem, itemIndex, itemIndex);
public class TComboBoxModel extends AbstractListModel implements
ComboBoxModel {
private int itemIndex;
private Object selectedItem = null;
private ArrayList<Object> itemList;
public TComboBoxModel() {
itemList = new ArrayList<>();
}
public void addItem(String item) {
this.itemList.add(item);
this.fireIntervalAdded(item, itemIndex, itemIndex);
}
public void removeItem() {
if (itemIndex >= 0 && itemIndex < getSize()) {
this.itemList.remove(itemIndex);
this.fireIntervalRemoved(selectedItem, itemIndex, itemIndex);
}
}
@Override
public void setSelectedItem(Object anObject) {
if ((selectedItem != null && !selectedItem.equals(anObject)) ||
selectedItem == null && anObject != null) {
this.selectedItem = anObject;
this.fireContentsChanged(anObject, -1, -1);
}
}
@Override
public Object getSelectedItem() {
return selectedItem;
}
@Override
public int getSize() {
return itemList.size();
}
@Override
public Object getElementAt(int index) {
return itemList.get(index).toString();
}
public int getItemIndex() {
return itemIndex;
}
public void increaseItemIndex() {
itemIndex++;
}
public void decreaseItemIndex() {
itemIndex--;
}
}
I've created a ComboBoxModel class which extends AbstractListModel. I can
add item to the combobox, but when I try to remove, I get an exception
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException:
null source
at line
this.fireIntervalRemoved(selectedItem, itemIndex, itemIndex);
public class TComboBoxModel extends AbstractListModel implements
ComboBoxModel {
private int itemIndex;
private Object selectedItem = null;
private ArrayList<Object> itemList;
public TComboBoxModel() {
itemList = new ArrayList<>();
}
public void addItem(String item) {
this.itemList.add(item);
this.fireIntervalAdded(item, itemIndex, itemIndex);
}
public void removeItem() {
if (itemIndex >= 0 && itemIndex < getSize()) {
this.itemList.remove(itemIndex);
this.fireIntervalRemoved(selectedItem, itemIndex, itemIndex);
}
}
@Override
public void setSelectedItem(Object anObject) {
if ((selectedItem != null && !selectedItem.equals(anObject)) ||
selectedItem == null && anObject != null) {
this.selectedItem = anObject;
this.fireContentsChanged(anObject, -1, -1);
}
}
@Override
public Object getSelectedItem() {
return selectedItem;
}
@Override
public int getSize() {
return itemList.size();
}
@Override
public Object getElementAt(int index) {
return itemList.get(index).toString();
}
public int getItemIndex() {
return itemIndex;
}
public void increaseItemIndex() {
itemIndex++;
}
public void decreaseItemIndex() {
itemIndex--;
}
}
Tkinter or PyGTK
Tkinter or PyGTK
I need to create a simple GUI application to display tabular data. Using
the LogParser utility
logparser -i:CSV "SELECT TOP 10 SERVER, STATUS, AVAILABILITY FROM data.csv
WHERE STATUS='OK' ORDER BY AVAILABILITY DESC" -o:DATAGRID
I was able to create a simple data-grid, but because the design/layout is
kind of hard coded, I was planning to learn a good API to create GUI
applications using Python. After reading a couple of links, it is obvious
that Tkinter or PyGTK are the best APIs/wrappers for this purpose.
Please, can anyone enlist the major differences between these toolkits, in
terms of:
Available UI Components
"Cross-Platformishness"
Available Design Options (Native vs. Custom)
Deploying the GUI Application as a Final Product (ease of bundling
binaries etc. with the final application)
Where does PyQt stand in this comparison?
Please do not suggest the following links, they've very poor quality:
PyGTK, wxPython or Tkinter?
Using Tk with C
I need to create a simple GUI application to display tabular data. Using
the LogParser utility
logparser -i:CSV "SELECT TOP 10 SERVER, STATUS, AVAILABILITY FROM data.csv
WHERE STATUS='OK' ORDER BY AVAILABILITY DESC" -o:DATAGRID
I was able to create a simple data-grid, but because the design/layout is
kind of hard coded, I was planning to learn a good API to create GUI
applications using Python. After reading a couple of links, it is obvious
that Tkinter or PyGTK are the best APIs/wrappers for this purpose.
Please, can anyone enlist the major differences between these toolkits, in
terms of:
Available UI Components
"Cross-Platformishness"
Available Design Options (Native vs. Custom)
Deploying the GUI Application as a Final Product (ease of bundling
binaries etc. with the final application)
Where does PyQt stand in this comparison?
Please do not suggest the following links, they've very poor quality:
PyGTK, wxPython or Tkinter?
Using Tk with C
How to run test scripts in parallel machine using Selenium Grid with pom and testNG
How to run test scripts in parallel machine using Selenium Grid with pom
and testNG
Totally i have 50 scripts in my testng.xml, now i want to run 25 in the
hub and the remaining 25 in node and both the machine are in same platform
windows. here i want to use testNG. and I referred the link
http://www.guru99.com/introduction-to-selenium-grid.html, when i follow
this link, i found how to use hub and node but all my script runs in
machine node only. how could i split it?
and testNG
Totally i have 50 scripts in my testng.xml, now i want to run 25 in the
hub and the remaining 25 in node and both the machine are in same platform
windows. here i want to use testNG. and I referred the link
http://www.guru99.com/introduction-to-selenium-grid.html, when i follow
this link, i found how to use hub and node but all my script runs in
machine node only. how could i split it?
Inserting zero-valued rows
Inserting zero-valued rows
I have the following structure. All I want to achieve is that if for some
reason one of the categories does not exist then rather than there being
no row for that category there should be a row with zeros for x/y/z.
The following seems a bit convoluted - what is the correct way to achieve
this?
TRUNCATE TABLE dbo.xxx;
INSERT INTO dbo.xxx
values
('cat_1',0.0,0.0,0.0),
('cat_2',0.0,0.0,0.0),
('cat_3',0.0,0.0,0.0),
('cat_4',0.0,0.0,0.0);
--:: category 1
INSERT INTO dbo.xxx
SELECT Category = 'cat_1',
x = SUM(x),
y = SUM(y),
z = SUM(z)
FROM dbo.yyy x
WHERE DateKey >= period1;
--:: category 2
INSERT INTO dbo.xxx
SELECT Category = 'cat_2',
x = SUM(x),
y = SUM(y),
z = SUM(z)
FROM dbo.yyy x
WHERE DateKey >= period2;
--:: category 3
INSERT INTO dbo.xxx
SELECT Category = 'cat_3',
x = SUM(x),
y = SUM(y),
z = SUM(z)
FROM dbo.yyy x
WHERE DateKey >= period3;
--:: category 4
INSERT INTO dbo.xxx
SELECT Category = 'cat_4',
x = SUM(x),
y = SUM(y),
z = SUM(z)
FROM dbo.yyy x
WHERE DateKey >= period4;
SELECT Category,
x = SUM(x),
y = SUM(y),
z = SUM(z)
INTO #temp
FROM dbo.xxx
GROUP BY Category;
TRUNCATE TABLE dbo.xxx;
INSERT INTO dbo.xxx
SELECT * FROM #temp;
I have the following structure. All I want to achieve is that if for some
reason one of the categories does not exist then rather than there being
no row for that category there should be a row with zeros for x/y/z.
The following seems a bit convoluted - what is the correct way to achieve
this?
TRUNCATE TABLE dbo.xxx;
INSERT INTO dbo.xxx
values
('cat_1',0.0,0.0,0.0),
('cat_2',0.0,0.0,0.0),
('cat_3',0.0,0.0,0.0),
('cat_4',0.0,0.0,0.0);
--:: category 1
INSERT INTO dbo.xxx
SELECT Category = 'cat_1',
x = SUM(x),
y = SUM(y),
z = SUM(z)
FROM dbo.yyy x
WHERE DateKey >= period1;
--:: category 2
INSERT INTO dbo.xxx
SELECT Category = 'cat_2',
x = SUM(x),
y = SUM(y),
z = SUM(z)
FROM dbo.yyy x
WHERE DateKey >= period2;
--:: category 3
INSERT INTO dbo.xxx
SELECT Category = 'cat_3',
x = SUM(x),
y = SUM(y),
z = SUM(z)
FROM dbo.yyy x
WHERE DateKey >= period3;
--:: category 4
INSERT INTO dbo.xxx
SELECT Category = 'cat_4',
x = SUM(x),
y = SUM(y),
z = SUM(z)
FROM dbo.yyy x
WHERE DateKey >= period4;
SELECT Category,
x = SUM(x),
y = SUM(y),
z = SUM(z)
INTO #temp
FROM dbo.xxx
GROUP BY Category;
TRUNCATE TABLE dbo.xxx;
INSERT INTO dbo.xxx
SELECT * FROM #temp;
Calling an SQL Server stored procedure with params in PHP
Calling an SQL Server stored procedure with params in PHP
this is my 1st post here and as a beginner in PHP so please tread lightly!!
I am using PHP 5.3 and SQL Server 2012 express
My problem is executing an SQL server stored procedure from PHP that has
parameters where the value of the parameter comes from a $_POST variable
from an HTML form.
My PHP code is as follows:
<?php
require_once("../includes/initialize.php");
//
global $database;
$username = "someone";
$params = array($username);
$conn = $database->connection;
$admin_set = sqlsrv_query($conn, "{call find_admin_by_username_p}",
$params);
if($admin = $database->fetch_array($admin_set)) {
var_dump($admin);
} else {
return null;
}
//
/* THIS WORKS
global $database;
$admin_set = $database->query("{call find_admin_by_username}");
if($admin = $database->fetch_array($admin_set)) {
var_dump($admin);
} else {
return null;
}
*/
?>
The code for the stored procedure is:
CREATE PROCEDURE [dbo].[find_admin_by_username_p]
@username nvarchar(55)
AS
BEGIN
SELECT * FROM dbo.users
WHERE username = @username
END
For the commented "THIS WORKS" section the procedure
find_admin_by_username works as this doesn't contain any parameters.
However I want to have the @username as a variable that is provided by a
$_POST form field.
My main reason for doing this is to help prevent SQL injection, also I
would be escaping the values once connected to the form.
This is a link to a lot of the info I have looked at so far
http://blogs.msdn.com/b/brian_swan/archive/2011/02/16/do-stored-procedures-protect-against-sql-injection.aspx
I have also searched through many other blogs but don't seem to be able to
find anything that works.
Please help!
this is my 1st post here and as a beginner in PHP so please tread lightly!!
I am using PHP 5.3 and SQL Server 2012 express
My problem is executing an SQL server stored procedure from PHP that has
parameters where the value of the parameter comes from a $_POST variable
from an HTML form.
My PHP code is as follows:
<?php
require_once("../includes/initialize.php");
//
global $database;
$username = "someone";
$params = array($username);
$conn = $database->connection;
$admin_set = sqlsrv_query($conn, "{call find_admin_by_username_p}",
$params);
if($admin = $database->fetch_array($admin_set)) {
var_dump($admin);
} else {
return null;
}
//
/* THIS WORKS
global $database;
$admin_set = $database->query("{call find_admin_by_username}");
if($admin = $database->fetch_array($admin_set)) {
var_dump($admin);
} else {
return null;
}
*/
?>
The code for the stored procedure is:
CREATE PROCEDURE [dbo].[find_admin_by_username_p]
@username nvarchar(55)
AS
BEGIN
SELECT * FROM dbo.users
WHERE username = @username
END
For the commented "THIS WORKS" section the procedure
find_admin_by_username works as this doesn't contain any parameters.
However I want to have the @username as a variable that is provided by a
$_POST form field.
My main reason for doing this is to help prevent SQL injection, also I
would be escaping the values once connected to the form.
This is a link to a lot of the info I have looked at so far
http://blogs.msdn.com/b/brian_swan/archive/2011/02/16/do-stored-procedures-protect-against-sql-injection.aspx
I have also searched through many other blogs but don't seem to be able to
find anything that works.
Please help!
Monday, 19 August 2013
how to register our windows mobile for test the app?
how to register our windows mobile for test the app?
I try to test my windows phone app on my mobile. for that i created a
developer account as company. i paid the amount. when i try to register my
mobile it tells that "Please check that the Zune software is running and
that Zune's sync partnership with your phone has been established". when i
check my developer account dashboard it tells that
"Validating your account. Learn more. You haven't completed your tax
profile. If you're interested in publishing paid apps, update your tax
info here. Learn more. We don't have a payment account for you. To add
this info, go here. Learn more."
Please guide me....
I try to test my windows phone app on my mobile. for that i created a
developer account as company. i paid the amount. when i try to register my
mobile it tells that "Please check that the Zune software is running and
that Zune's sync partnership with your phone has been established". when i
check my developer account dashboard it tells that
"Validating your account. Learn more. You haven't completed your tax
profile. If you're interested in publishing paid apps, update your tax
info here. Learn more. We don't have a payment account for you. To add
this info, go here. Learn more."
Please guide me....
python sys.path versus code hack
python sys.path versus code hack
in distributing some python from an automation-orchestration host to a
remote-client and a remote-server I found that hacking on the path is
better than moving modules. However, this did not click well with another
dev and we had interference. I chose a bad hack, he chose another perhaps
equivalent hack. I think now both are wrong:
hack #1:
# on remote systems the dir is flat, on local automation host it is less
flat!
try:
from process import call_process
except:
from common.process import call_process
hack #2
# in deployment steps
ssh qa$host
mkdir common
touch common/__init__.py
cp common/process.py $HOST:common/process.py
I think the better thing would be to leave it as a PYTHONPATH or syspath
solution:
add_path( TEST_ROOT+'/common')
from process import call_process
Constructive perspectives welcome! /Mike
in distributing some python from an automation-orchestration host to a
remote-client and a remote-server I found that hacking on the path is
better than moving modules. However, this did not click well with another
dev and we had interference. I chose a bad hack, he chose another perhaps
equivalent hack. I think now both are wrong:
hack #1:
# on remote systems the dir is flat, on local automation host it is less
flat!
try:
from process import call_process
except:
from common.process import call_process
hack #2
# in deployment steps
ssh qa$host
mkdir common
touch common/__init__.py
cp common/process.py $HOST:common/process.py
I think the better thing would be to leave it as a PYTHONPATH or syspath
solution:
add_path( TEST_ROOT+'/common')
from process import call_process
Constructive perspectives welcome! /Mike
Looking for a browser with a lower memory footprint
Looking for a browser with a lower memory footprint
I have a Samsung Galaxy Tab 2 10.1 (GT-P5110) running 4.1.2, and my
problem is that, when browsing with Google Chrome and Adblock Plus, the
device runs out of memory very often, so Adblock gets killed and I have to
restart it by hand; sometimes it happens so often that it crashes in every
URL I visit.
Looking at the Task Manager, the only apps I have running are Chrome and
Adblock Plus, and yet RAM usage is always around 680/759 Mb. (I thought
that the Galaxy Tab had 1 Gb. RAM?). Thus, I'm looking for a modern
browser that has a smaller memory footprint: Opera? Firefox? Something
else? I don't know much about the stock Android browser, since I've never
used it. How standards compliant (CSS3, Javascript, etc.) is it?
I have a Samsung Galaxy Tab 2 10.1 (GT-P5110) running 4.1.2, and my
problem is that, when browsing with Google Chrome and Adblock Plus, the
device runs out of memory very often, so Adblock gets killed and I have to
restart it by hand; sometimes it happens so often that it crashes in every
URL I visit.
Looking at the Task Manager, the only apps I have running are Chrome and
Adblock Plus, and yet RAM usage is always around 680/759 Mb. (I thought
that the Galaxy Tab had 1 Gb. RAM?). Thus, I'm looking for a modern
browser that has a smaller memory footprint: Opera? Firefox? Something
else? I don't know much about the stock Android browser, since I've never
used it. How standards compliant (CSS3, Javascript, etc.) is it?
Modification of Euler's Totient Function
Modification of Euler's Totient Function
Problem
If $\phi_2(n)$ is the number of integers $a \in \{0, \dots, n-1\}$ such
that $\gcd(a,n) = \gcd(a+1,n)=1$, I want to show that if $n = p_1^{e_1}
\cdots p_r^{e_r}$ is the prime factorization of $n$, then $\phi_2(n) = n
\prod_{i=1}^r(1-2/p_i)$.
Thoughts
I am not sure where to start with this, but looking at how Euler's totient
function works would it be reasonable to start by taking $n = p^{e}$ so
$n$ is just composed of a single prime raised to a power? In which case, I
believe I would be showing that $\phi_2(p^e) = p^{e-1}(p-2)$.
This makes sense to me in the case that $e=1$ as given any prime $p$,
every number in the set $\{0,\dots,p-1\}$ is relatively prime to $p$ but
$0$ and so we would be excluding $2$ values from the $\phi_2(p)$,
$\gcd(0,p) \neq \gcd(1,p)=1$ and $\gcd(p-1,p) = \gcd(p \equiv 0,p)=1$.
So for $p_e$, the $phi_2(p^e)$ would count these $p-2$ instances where
$\gcd(a,n) = \gcd(a+1,n)=1$ is true from $0,\dots p$ then from
$p,\dots,p^2$ and so on giving $p^{e-1}$ counts of $\phi(p)$.
Problem
If $\phi_2(n)$ is the number of integers $a \in \{0, \dots, n-1\}$ such
that $\gcd(a,n) = \gcd(a+1,n)=1$, I want to show that if $n = p_1^{e_1}
\cdots p_r^{e_r}$ is the prime factorization of $n$, then $\phi_2(n) = n
\prod_{i=1}^r(1-2/p_i)$.
Thoughts
I am not sure where to start with this, but looking at how Euler's totient
function works would it be reasonable to start by taking $n = p^{e}$ so
$n$ is just composed of a single prime raised to a power? In which case, I
believe I would be showing that $\phi_2(p^e) = p^{e-1}(p-2)$.
This makes sense to me in the case that $e=1$ as given any prime $p$,
every number in the set $\{0,\dots,p-1\}$ is relatively prime to $p$ but
$0$ and so we would be excluding $2$ values from the $\phi_2(p)$,
$\gcd(0,p) \neq \gcd(1,p)=1$ and $\gcd(p-1,p) = \gcd(p \equiv 0,p)=1$.
So for $p_e$, the $phi_2(p^e)$ would count these $p-2$ instances where
$\gcd(a,n) = \gcd(a+1,n)=1$ is true from $0,\dots p$ then from
$p,\dots,p^2$ and so on giving $p^{e-1}$ counts of $\phi(p)$.
Set MediaPlayer's timeout?
Set MediaPlayer's timeout?
Is there a way to set the timeout value of the MediaPlayer to so it
doesn't cause an error so soon if the video doesn't play?
The problem is that my videos are on a CDN. If the video hasn't been
cached on the CDN yet, then it may take a little bit to load the video
while the 1st person access the video. On other platforms (i.e. HTML5's
video tag) this is not a problem - the video plays just fine.
My theory is that the MediaPlayer times out from attempting to play the
video.
If this is true, then is it possible I can change when the time out
happens? If I cannot set this value, is there another proven method that
might work?
p.s. My app is built for the Google TV platform.
Is there a way to set the timeout value of the MediaPlayer to so it
doesn't cause an error so soon if the video doesn't play?
The problem is that my videos are on a CDN. If the video hasn't been
cached on the CDN yet, then it may take a little bit to load the video
while the 1st person access the video. On other platforms (i.e. HTML5's
video tag) this is not a problem - the video plays just fine.
My theory is that the MediaPlayer times out from attempting to play the
video.
If this is true, then is it possible I can change when the time out
happens? If I cannot set this value, is there another proven method that
might work?
p.s. My app is built for the Google TV platform.
Sunday, 18 August 2013
Forcing Julius to regenerate for each request
Forcing Julius to regenerate for each request
I am trying to post a form using Ajax and I generate the URL string in the
request based on the route. Like so:
$.ajax ({ type: "POST",
url: "@{MyHandlerR objectId}",
headers: {
Accept: "application/json; charset=utf-8",
"Content-Type": "application/x-www-form-urlencoded"
},
...
When I go to /path/1, the url is set properly to /newpath/1 in the above
Javascript code. However, when I go to /path/2 next, the javascript does
not get regenerated and as a consequence the path remains the same
/newpath/1.
Is there a way to force a regeneration of the Julius file? As a work
around, I can just grab the url from the html page but want to know if
there is a better way to deal with this issue.
Thanks!
I am trying to post a form using Ajax and I generate the URL string in the
request based on the route. Like so:
$.ajax ({ type: "POST",
url: "@{MyHandlerR objectId}",
headers: {
Accept: "application/json; charset=utf-8",
"Content-Type": "application/x-www-form-urlencoded"
},
...
When I go to /path/1, the url is set properly to /newpath/1 in the above
Javascript code. However, when I go to /path/2 next, the javascript does
not get regenerated and as a consequence the path remains the same
/newpath/1.
Is there a way to force a regeneration of the Julius file? As a work
around, I can just grab the url from the html page but want to know if
there is a better way to deal with this issue.
Thanks!
In Wordpress SQL database, where does it show which attachment(s) has been assigned to which post?
In Wordpress SQL database, where does it show which attachment(s) has been
assigned to which post?
I was able to tap into my wordpress database and pull all the rows from
the "wp_posts" table with "post_type=post" and display the content on
another page (not wordpress, just built from scratch). The problem I have
is the images (in the database "attachments") are in the same table with
"post_type=attachment". So I cannot pull the correct images into my site.
I can't find how they are related to the posts. I thought
"wp_term_relationships" was my answer but those are just category
relationships. In short, Where are the image relationships?
assigned to which post?
I was able to tap into my wordpress database and pull all the rows from
the "wp_posts" table with "post_type=post" and display the content on
another page (not wordpress, just built from scratch). The problem I have
is the images (in the database "attachments") are in the same table with
"post_type=attachment". So I cannot pull the correct images into my site.
I can't find how they are related to the posts. I thought
"wp_term_relationships" was my answer but those are just category
relationships. In short, Where are the image relationships?
change the size of row of listview in android
change the size of row of listview in android
I have these files(xml and java code).My listview rows are having a
default size.how can i change this size to smaller or larger uniformly on
each row.
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="30"
android:orientation="vertical"
>
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"
>
</ListView>
</LinearLayout>
javafile:
public class Detail extends Activity { private EditText etInput; private
Button btnAdd; private ListView lvItem,lvItem2; private ArrayList
itemArrey; private ArrayAdapter itemAdapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail);
setUpView();
}
private void setUpView() {
// TODO Auto-generated method stub
// etInput = (EditText)this.findViewById(R.id.editText_input);
btnAdd = (Button)this.findViewById(R.id.button1);
lvItem = (ListView)this.findViewById(R.id.listView1);
lvItem2 = (ListView)this.findViewById(R.id.listView2);
lvItem2.setVisibility(View.INVISIBLE);
itemArrey = new ArrayList<String>();
itemArrey.clear();
itemAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,itemArrey);
lvItem.setAdapter(itemAdapter);
lvItem2.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addItemList();
}
});
lvItem.setClickable(true);
lvItem.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
lvItem2.setVisibility(View.VISIBLE);
}
});
}
protected void addItemList() {
itemAdapter.insert("sdsds",0);
itemAdapter.insert("sdddsds",1);
itemAdapter.notifyDataSetChanged();
}
}
I have these files(xml and java code).My listview rows are having a
default size.how can i change this size to smaller or larger uniformly on
each row.
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="30"
android:orientation="vertical"
>
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0"
>
</ListView>
</LinearLayout>
javafile:
public class Detail extends Activity { private EditText etInput; private
Button btnAdd; private ListView lvItem,lvItem2; private ArrayList
itemArrey; private ArrayAdapter itemAdapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail);
setUpView();
}
private void setUpView() {
// TODO Auto-generated method stub
// etInput = (EditText)this.findViewById(R.id.editText_input);
btnAdd = (Button)this.findViewById(R.id.button1);
lvItem = (ListView)this.findViewById(R.id.listView1);
lvItem2 = (ListView)this.findViewById(R.id.listView2);
lvItem2.setVisibility(View.INVISIBLE);
itemArrey = new ArrayList<String>();
itemArrey.clear();
itemAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,itemArrey);
lvItem.setAdapter(itemAdapter);
lvItem2.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addItemList();
}
});
lvItem.setClickable(true);
lvItem.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
lvItem2.setVisibility(View.VISIBLE);
}
});
}
protected void addItemList() {
itemAdapter.insert("sdsds",0);
itemAdapter.insert("sdddsds",1);
itemAdapter.notifyDataSetChanged();
}
}
Storing very big files in database
Storing very big files in database
Do it's good idea to store in database big files? About 100gb in table.
Currently we thinking about saving data in folder using NBT format or
using mysql/posgresql database.
Do it's good idea to store in database big files? About 100gb in table.
Currently we thinking about saving data in folder using NBT format or
using mysql/posgresql database.
How to create method for withdrawal from store and deliverance to store
How to create method for withdrawal from store and deliverance to store
I am studying java by myself and I want to get help on exercise which i am
doing myself. The class is called Product which used for representing a
product that a small company sells. It should be possible to store the
following information about each product. The class should have the
following methods: • A constructor • A method that returns the units of
items in store • A method for deliverance to the store (increases the
units of this product) • A method for withdrawal from the store (decreases
the units of this product) Please note that if one of the methods changes
the stored items below the order point a message should be printed. It
should also be impossible to have a negative amount of items.
I HAVE PROBLEM WITH METHODS. PLEASE TAKE A LOOK MY CODE AND GIVE ME SOME
HINTS. I WILL APPRECIATE ALL RESPONDS. THANK YOU.
Here is my program:
public class Product {
private int productNumber;
private String productName;
private float price;
private int orderPoint;
private int unitsInStore;
private String proDescription;
public Product(int num, String name, float price, int order, int units,
String description){
this.productNumber = num;
this.productName = name;
this.price = price;
this.orderPoint = order;
this.unitsInStore = units;
this.proDescription = description;
}
public int getProductNumber() {
return productNumber;
}
public void setProductNumber(int productNumber) {
this.productNumber = productNumber;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getOrderPoint() {
return orderPoint;
}
public void setOrderPoint(int orderPoint) {
this.orderPoint = orderPoint;
}
// a method returns the units in store
public int getUnitsInStore() {
return unitsInStore;
}
public void setUnitsInStore(int unitsInStore) {
this.unitsInStore = unitsInStore;
}
public String getProDescription() {
return proDescription;
}
public void setProDescription(String proDescription) {
this.proDescription = proDescription;
}
public int deliveranceToStore(int store){
int unitsInStore = deliveranceToStore(unitsInStore) +store;
return unitsInStore ++;
}
}
I am studying java by myself and I want to get help on exercise which i am
doing myself. The class is called Product which used for representing a
product that a small company sells. It should be possible to store the
following information about each product. The class should have the
following methods: • A constructor • A method that returns the units of
items in store • A method for deliverance to the store (increases the
units of this product) • A method for withdrawal from the store (decreases
the units of this product) Please note that if one of the methods changes
the stored items below the order point a message should be printed. It
should also be impossible to have a negative amount of items.
I HAVE PROBLEM WITH METHODS. PLEASE TAKE A LOOK MY CODE AND GIVE ME SOME
HINTS. I WILL APPRECIATE ALL RESPONDS. THANK YOU.
Here is my program:
public class Product {
private int productNumber;
private String productName;
private float price;
private int orderPoint;
private int unitsInStore;
private String proDescription;
public Product(int num, String name, float price, int order, int units,
String description){
this.productNumber = num;
this.productName = name;
this.price = price;
this.orderPoint = order;
this.unitsInStore = units;
this.proDescription = description;
}
public int getProductNumber() {
return productNumber;
}
public void setProductNumber(int productNumber) {
this.productNumber = productNumber;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getOrderPoint() {
return orderPoint;
}
public void setOrderPoint(int orderPoint) {
this.orderPoint = orderPoint;
}
// a method returns the units in store
public int getUnitsInStore() {
return unitsInStore;
}
public void setUnitsInStore(int unitsInStore) {
this.unitsInStore = unitsInStore;
}
public String getProDescription() {
return proDescription;
}
public void setProDescription(String proDescription) {
this.proDescription = proDescription;
}
public int deliveranceToStore(int store){
int unitsInStore = deliveranceToStore(unitsInStore) +store;
return unitsInStore ++;
}
}
Can a writeable stream be piped to either a readable or wirtable stream
Can a writeable stream be piped to either a readable or wirtable stream
code:
a.pipe(b).pipe(c).pipe(d);
Im node newbie. I read that for piping, the source should be a readable
stream and destination should be a writeable stream.
If you see the above code, my assumption is that 'a' is readable stream,
'b' is writable stream. If 'b' is writable stream how is it possible to
pipe it further?
how the 'b' writeable stream is piped to 'c'?
Streams and Buffers is being difficult to understand. Any good
documentation to read?
code:
a.pipe(b).pipe(c).pipe(d);
Im node newbie. I read that for piping, the source should be a readable
stream and destination should be a writeable stream.
If you see the above code, my assumption is that 'a' is readable stream,
'b' is writable stream. If 'b' is writable stream how is it possible to
pipe it further?
how the 'b' writeable stream is piped to 'c'?
Streams and Buffers is being difficult to understand. Any good
documentation to read?
Saturday, 17 August 2013
UDP sending data=?iso-8859-1?Q?=2C_something_i_don=B4t_quite_understand?=
UDP sending data, something i don´t quite understand
Okay from my knowledge UDP works like this:
You have data you want to send, you say to the UDP client, hey send this
data.
The UDP client then says, sure why not, and sends the data to the selected
IP and Port.
If it get´s through or in the right order is another story, it have sent
the data, you didn´t ask for anything else.
Now from this perspective, it´s pretty much impossible to send data and
assemble it. for example, i have a 1mb image, and i send it.
So i send divide it in 60kb files (or something to fit the packages), and
send them one by one from first to last.
So in theory, if all get´s added, the image should be exactly the same.
But, that theory breaks as there is no law that tells the packages if it
can arrive faster or slower than another, so it may only be possible if
you make some kind of wait timer, and hope for the best that the arrive in
the order they are sent.
Anyway, what i want to understand is, why does this work:
void Sending(object sender, NAudio.Wave.WaveInEventArgs e)
{
if (connect == true && MuteMic.Checked == false)
{
udpSend.Send(e.Buffer, e.BytesRecorded,
otherPartyIP.Address.ToString(), 1500);
}
}
Recieving:
while (connect == true)
{
byte[] byteData = udpReceive.Receive(ref remoteEP);
waveProvider.AddSamples(byteData, 0, byteData.Length);
}
So this is basically, it sends the audio buffer through udp.
The receiving par just adds the udp data received in a buffer and plays it.
Now, this works.
And i wonder.. why?
How can this work, how come the data is sent in the right order and added
so it appears as a constant audio stream?
Cause if i would to this with an image, i would probably get all the data.
But they would be in a random order probably, and i can only solve that by
marking packages and stuff like that. And then there is simply no reason
for it, and TCP takes over.
So if someone can please explain this, i just don´t get it.
Okay from my knowledge UDP works like this:
You have data you want to send, you say to the UDP client, hey send this
data.
The UDP client then says, sure why not, and sends the data to the selected
IP and Port.
If it get´s through or in the right order is another story, it have sent
the data, you didn´t ask for anything else.
Now from this perspective, it´s pretty much impossible to send data and
assemble it. for example, i have a 1mb image, and i send it.
So i send divide it in 60kb files (or something to fit the packages), and
send them one by one from first to last.
So in theory, if all get´s added, the image should be exactly the same.
But, that theory breaks as there is no law that tells the packages if it
can arrive faster or slower than another, so it may only be possible if
you make some kind of wait timer, and hope for the best that the arrive in
the order they are sent.
Anyway, what i want to understand is, why does this work:
void Sending(object sender, NAudio.Wave.WaveInEventArgs e)
{
if (connect == true && MuteMic.Checked == false)
{
udpSend.Send(e.Buffer, e.BytesRecorded,
otherPartyIP.Address.ToString(), 1500);
}
}
Recieving:
while (connect == true)
{
byte[] byteData = udpReceive.Receive(ref remoteEP);
waveProvider.AddSamples(byteData, 0, byteData.Length);
}
So this is basically, it sends the audio buffer through udp.
The receiving par just adds the udp data received in a buffer and plays it.
Now, this works.
And i wonder.. why?
How can this work, how come the data is sent in the right order and added
so it appears as a constant audio stream?
Cause if i would to this with an image, i would probably get all the data.
But they would be in a random order probably, and i can only solve that by
marking packages and stuff like that. And then there is simply no reason
for it, and TCP takes over.
So if someone can please explain this, i just don´t get it.
Subscribe to:
Comments (Atom)