mardi 31 mars 2015

javascript regex to replace space with a hyphen

I need a regex which should read a string :



  1. with a 1 to unlimited numbers (say upto 10)

  2. read a space in between

  3. with a 1 to unliimited numbers (say upto 10)


then replace the space in the string with a '-'


for ex: 123 456 should be replaced with 123-456.


there are no any other characters apart from numbers in the string.


How to split a string in two conditions? [duplicate]


This question already has an answer here:




I have a string entered like this



http://ift.tt/1mBHdad,
http://ift.tt/1ltHaMk


here I want to split this on "\n" and also on ",". How to do this?. Can I use split key word to achieve this?


func return does notReturn String from my conform to protocol StringLiteralConvertible error

I have class which has the func of return path to some file:



func getArchivePathFor(fileName: String!) -> String {
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
var path: String = paths.stringByAppendingPathComponent(fileName!)
return path
}


But when I try to use it in my code like:



let val = Helpers.getArchivePathFor("MyList.plist")


I get the error: "Return String from my func return does not conform to protocol StringLiteralConvertible error". Why so?


how to get all the positions of the set bits of a binary string in java?

For example if the binary string is 10100010 then the program must return 1st,3rd and 7th i.e the positions of the 1's.


Remove time zones from a string or format HTTP TIME STRING in coldfusion

I am formatting a normal string containing 11:00 PM or 23:00:00 using timeFormat() like this:



<cfset local.timeString = "11:00 PM">
<cfdump var="#local.timeString#">
<cfset local.newTimeString = timeFormat(local.timeString, "HH:mm:ss")>
<cfdump var="#local.newTimeString#">


Output:



11:00 PM 23:00:00



But in one case I came across a time string which also contains a time zone like this: 11:00 PM EDT, so when I was trying to format this string using timeFormat then I was getting error which is correct.



11:00 PM EDT is an invalid date or time string



This type of string can be generated using GetHttpTimeString.


Do I need to use something like this? It is not a correct way. Just thought this as found no other solution.



<cfset local.newTimeString = left(local.timeString
, len(local.timeString) - len(listLast(local.timeString," "))
)>


Is there any other function to format a string like this.


Please help. Thanks in advance.


comparison of two files in perl [on hold]

I have two files list.txt and list1.txt where as list.txt contains a line form1-data and list1.txt contains a line data I want to compare these two files and output should be printed as form1-data (form1 represents list1.txt first column and data represents list1.txt first column). I want to compare these two files for 100 lines.



my $f1 = '<',"/home/httpd/cgi-bin/u/r/list.txt";
my $f2 = '<',"/home/httpd/cgi-bin/u/r/list1.txt";
my $outfile = "";
my %results = ();
open FILE1, "$f1" || die "error \n";
while(my $line = <FILE1>){
$results{$line}=1;
}
close(FILE1);
open FILE2, "$f2" || die "error \n";
while(my $line =<FILE2>) {
$results{$line}++;
}
close(FILE2);

open (OUTFILE, '>',"/home/httpd/cgi-bin/u/r/outfile") || die" error \n";
foreach my $line (keys %results) {
print OUTFILE $line if $results{$line} == 1;
}
close OUTFILE;`


file.txt(UP-Myco sme UP-Myco tube UP-Myco abs UP-Myco absces) file1.txt contains(Myco absces Myco afri Myco avi Myco bovis) expected output:UP-Myco absces(by comparing two files need to print the ABOVE OUTPUT)


How to track a string-variable in JavaScript

Requirement : To be able to track a string variables in javascript by assigning a unique ID to each variable.


Example:



var a = 'alkd';
var b = 'iquwq';
console.log(a.id); # 1234
console.log(b.id); # 5678


What I have tried : I have tried extending string object by adding a new method or property to 'String.prototype'


Output :



console.log(a.id); #1234
console.log(b.id); #1234 (returning same id as above)


What i have observed : Ever instance of a string is inherited from String.prototype. Changes to String.Prototype object are propagated to all String instances.


Example :



a.id = 8783; # setter
console.log(b.id)# returns 8783


My Questions :



  1. Is it actually possible to get required functionality by extending String Object ?

  2. Is there any alternative way to do this ?

  3. Are there any plans to add such functionality to future editions of ECMAScript ?


java list addAll function [duplicate]


This question already has an answer here:




New to java. I created two List objects and tried to add the second list to the first one, code as below.



import java.util.*;

public class t {
public static void main(String[] args){

String[] things = {"a", "b", "c", "d", "e", "f"};
List<String> list1 = Arrays.asList(things);

String[] things2 = {"g", "h", "i", "j"};
List<String> list2 = Arrays.asList(things2);

list1.addAll(list2);
}
}


it can successfully compile, but when I run it, error information as below:enter image description here


I am wondering what has happened here. Why I cannot use addAll function. Since two lists are both declared to hold String types.


Extract information and transform true to 1

I got this code :



foreach($data['matches'] as $matches){
$win += $matches['participants'][0]['stats']['winner'];
if ($win == true){
$winner+= '1';
}
}


This code extract information from an API, and what I want is how much the value "true" is in the API, soo i've tried to convert "true" to 1, but still not working well.

In the api there are 8 "true" but when i've tried to print $winner i got just 2.

What to do please to correct the code ?


Storing strings from a text file into a two dimensional array

I'm working on a project using C and for the project I must read in a text file and store each word into an array. I also have to remove the punctuation off the words, so I need to use a 2-Dimensional array in order to edit the words. I am having trouble figuring out how to get the words in the 2-D array it self. This is what I have done so far:



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 1001
#define LINES 81

int main(void) {
int stringSize;
char *x[MAX][LINES];
FILE *fp;
char str[MAX];
int i =0;
char y[MAX];
fp = fopen("TwoCitiesStory.txt","r");
if(fp == NULL) {
printf("Cannot open file.\n");
exit(1);}

while(!feof(fp)) {
for(i=0;i<MAX;i++){
fscanf(fp,"%s",x[i][LINES]);
}
}

return 0;
}

How to split a string without losing any word?

I was using eclipse for Java.


I want to split an input line without losing any char.


For example input line is:

IPOD6 1 USD6IPHONE6 16G,64G,128G USD9,USD99,USD999MACAIR 2013-2014 USD123MACPRO 2013-2014,2014-2015 USD899,USD999


output:

IPOD6 1 USD6

IPHONE6 16G,64G,128G USD9,USD99,USD999

MACAIR 2013-2014 USD123

MACPRO 2013-2014,2014-2015 USD899,USD999



I was using split("(?<=\bUSD\d{1,99}+)")

but it does't work


Getting failed to open stream: HTTP request failed error with names with symboles

Why I got this error :



failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found



Code :



$Name = 'Teàst';
$result = file_get_contents('http://ift.tt/1DjDRBF' . $Name . );


But when I try echo $result; I got the link and its work fine. And when I try $Name = 'Teast'; (without "à" symbole) its work fine. Soo the problem is names with symboles (é è à ...). How to fix it please ?


Use double quote in sql querys c#

I'm developing an application that executes queries in a Sqlserver database. One of these queries needs double quotes.



select ....soapenv="http://ift.tt/sVJIaE"...from...where...


I put the query in a string type variable. I use inverted bar to scape to scape the double quote and define them in the string. But when I execute my app, I get a error when my app execute this query.


This is the error message:



Incorrect syntax near the keyword 'declare'.

'soapenv' is not a recognized CURSOR option.


How could define my query?


Thanks in advance! Regards


Boo string interpolation not working

I downloaded the latest build of Boo this morning, and I'm trying to get started with the language. One of the features I need for my use case is Boo's string interpolation. However, I haven't been able to get it to work at all.


Here's my test code (some of which was copied directly from the Boo website):



print System.DateTime.Now

title = "My Demo Site"
print title
print "$(title)"

print """
<html>
<header> $title </header>
</html>
"""
name = "Santa Claus"
print "Hello, $name!"

now = "IMPORTANT"
print("Tomorrow will be $now")

print("""
----
Life, the Universe and Everything: $(len('answer to life the universe and everything')).
----
""")


and my output:



3/31/2015 10:25:37 AM
My Demo Site
$(title)

<html>
<header> $title </header>
</html>

Hello, $name!
Tomorrow will be $now

----
Life, the Universe and Everything: $(len('answer to life the universe and everything')).
----


What am I doing wrong?


a regular expression for substring or exact match

example string "hello" I need an express for validating user input, in this context valid and invalid input are as follows:


valid: "hello", "hell", "lol" .... etc.


invalid: "heel", "loo"... etc.


I have tried the likes of "(.)([hello])(.)" and "[hello]+" but they don't sort the invalid ones.


Any help would be appreciated thank you


Splitting a string into multiple Arrays

For my program, the input from the user will be something like this:



{1,2,3} {1,2} {4,5,6}


There can be multiple { } with any number of ... numbers inside.


I already made a 2 dimensional array with an array for each sequence of numbers: {}


I am having troubling splitting them into their respective arrays so it will be something like this:



Array[0] = ["1","2","3"]
Array[1] = ["1","2"]
Array[2] = ["4","5","6"]


How would i split it like that? i dont know if i can split this string into n number of strings since the number of sequences depends on user.


What is the space complexity of this binary addition solution?

I am working on an interview problem from Facebook Software Engineer


The Problem: Write a function which given two binary numbers as strings returns the sum of them in binary


Here is my solution in Java(Tested it, It works!!!)



private static String sum(String bin1, String bin2)
{
int dec1 = binToDec(bin1);
int dec2 = binToDec(bin2);
int sumTo = dec1 + dec2;

do {
bin = sumTo%2 + bin;
sumTo = sumTo/2;
}while(sumTo > 0);

return bin;
}
private static int binToDec(String bin)
{
int result = 0;
int len = bin.length();
for(int rep = len-1; rep >= 0; rep--) {
int multiplyBy = bin.charAt(rep) == '1' ? 1 : 0;
result += multiplyBy * Math.pow(2, len-1-rep);
}
return result;
}


I am trying to analyze the time and space complexity of the sum. I know that the time complexity of my algorithm would just be O(logn) because of the binary conversion.


Like usual, I am having a hard time with space complexity. I know that the space complexity would just depend on the memory I allocated from the heap, in this case the string to represent the binary sum result


I know that String concatenation is an expensive operation because it requires copying 1 chars, then 2 chars, then finally logn chars. I know that traditional String concatenation runs in O(n2) space. Would it be the same here?


I tried doing the calculations myself



1 + 2 + 3 +.... logn-1 + logn <BR>
logn + logn-1 + ....1<BR>
logn(logn + 1)/2


and got the final result of logn(logn + 1)2 which would be O((logn)2). Is that the right space complexity for this algorithm? Or is it just O(n2) because the two functions are in the same family?


How to convert int to string [duplicate]


This question already has an answer here:




I this a good way to convert int to string?



int a = 123456789;
string str = static_cast<ostringstream*>(&(ostringstream()<<a))->str();

Iterative procedure naming

I have a process running multiple times over a picture. I would like to save each intermediate picture result using a increasing name;


Ie iteration1.png, iteration2.png, etc. The number of iterations may change between each execution.


I am having trouble creating the name.


I am using char strings and not strings for the name (thats just the way it is, I have received functions that use it like this).


How would I code name = "iteration"+iter+".png"?


I have tried strcat, I have tried with addition (+).


Thanks


How to find a sentence spread over mutltiple lines in a multiline string

As the title says. I have this string read from a file into a string



"has anyone really been far even as decided to
use even go want
to do look more like"


When I do this, it writes hello world.



if (string.Contains(@"use even go want
to do look more like"))
{
Console.Write("Hello world!");
}


but when I do this, it won't work.



if (string.Contains(@"use even go want\nto do look more like"))
{
Console.Write("Hello world!");
}


Isn't there a better way to find a sentence spread over multiple lines in a string instead of just planting a return in the middle of the code?


(I've also already tried \n\r, \r\n and \r)


Java printing string with fixed width

I have to write a code in Java that will take a String and put a certain number of characters on each line (the fixed width). I will also have to put extra spaces in to fill in any extra spots, like if four words only equal 23 characters and the line calls for 25, so I'd need to input two extra spaces. This is for a beginning class, so it just needs to be as basic as possible. So far, what I have is:



public static void print (String[] theWords, int width) {

int start = 0, end = 0, lineCounter = 0;
int[] gaps;


Where do I go from here?


Core Java on division by 0.0

I heard one twist in java. If anyone know proper reason you're asked to share it. Question is:



double result1 = 1.0/0.0;
sop(result1); // output Infinity
double result2 = 0.0/0.0;
sop(result2); // output NaN


the same is happening for float variable also. but for int type its raising ArithmeticException. Why?


Note: I am using jdk 1.7


Cannot convert from UTF8 to ASCII

I used some online encoding detection so all of them are saying that


2015%2d03%2d31


is encoded by UTF8.


So I used this code to decode it and to see


2015-03-31


But it doesn't work.



private static string UTF8toASCII(string text)
{
System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
Byte[] encodedBytes = utf8.GetBytes(text);
Byte[] convertedBytes =
Encoding.Convert(Encoding.UTF8, Encoding.ASCII, encodedBytes);
System.Text.Encoding ascii = System.Text.Encoding.ASCII;

return ascii.GetString(convertedBytes);
}


Any clue?


Fastest way to search for string within a string, given a set of constant factors

I see there are a lot of questions on the topic, but please bare with me.


I have a long string, in which I need to determine whether there is an occurrence of a short string. It sounds very simple, and it is, using strpos I can perform



strpos($longstr, $shortstr);


Which would get the job done, however there are some facts that I know for certain:



  • the short string will always start on a new line

  • the short string will always be 10 characters long (multibyte)

  • the short string will always start with the characters "чь"

  • the short string will always end with a new line after the 10th character

  • the short string can only occur once, further occurrences are meaningless and disregarded


Having the above conditions in mind, it makes no sense to search for the string in question in any position other than 0 on a new line, however, how can I know where the new lines are if I don't go through the whole long string.


Is there anything that can be improved in getting the job done, performance-wise, compared to strpos?


How to replace the last HTML list item?

How do I replace the last li element in this string?


Before:



$var =
'<li>anything<li/>
<li>anything<li/>
<li>anything<li/>
<li>anything<li/>
<li>anything<li/>';


After:



$var =
'<li>anything<li/>
<li>anything<li/>
<li>anything<li/>
<li>anything<li/>
<li class="foo">anything<li/>';


I tried with preg_replace():



preg_replace('<li>', '<li class="foo">', $var);


But it isn't the expected output. How do I change the code to get the expected output?


Is there a portable function like g_printf_string_upper_bound?

In order to generate filenames I need to provide some buffer memory for sprintf. The size of these buffers was chosen rather arbitrarily in the past. This can easily lead to very nasty stack overflow bugs in the future, when e.g. int becomes 64bit long but the string buffer size was chosen to be 10 characters only as this is the maximum amount of digits a 32 bit int can hold.


Some MWE:



for (int i = 0; i < mpi_size; i++) {
//magic number: 32bit integer has 10 digits,
//+6 for "/rank_", +1 for null termination
char path2[strlen(path) + 17];
//This can possibly be an access violation, or a very hard to
//find bug:
sprintf(path2, "%s/rank_%d", path, i);
//Using path2 to access some file
}


Completely different sizes where chosen in other places, were people were very sure, that the int will not be bigger than e.g. 3 digits. This can lead to problems much easier.


What would be a perfect and portable solution?


I found the function g_printf_string_upper_bound in the gnome library which would solve this problem elegantly and reliably.


Is there anything like this in the C standard, in POSIX or somewhere else?


Unable to display contents of node from XML online

I have a XML document online which I'm trying to obtain and display the value of a particular node in a label.


XML:



<h1 class="contents-header">Upper Limit Management</h1>
<div class="contents-body">
<table class="data-table" width="500px">
<tr>
<th scope="col" width="165px">Max. Allowance Set</th>
<th scope="col" width="165px">Max. Allowance</th>
<th scope="col" width="170px">Meter Count</th>
</tr>
<tr>
<td>Disable</td>
<td>0</td>
<td>32</td>
</tr>
</table>
</div>
<hr class="contents-end" title="">
</div>


And here's the C# code I've tried to obtain and display it. I'm trying to display the node "Meter Count" which has a value of 32.



private void loadxmlbtn_Click(object sender, EventArgs e)
{
string myXmlString = new WebClient().DownloadString("http://ift.tt/1xvjUqp");

XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString);

XmlNodeList xnList = xml.SelectNodes("/Upper Limit Management/Meter Count");
foreach (XmlNode xn in xnList)
{
string count = xn["td"].InnerText;

countlbl.Text = "Your current count is: " + count;
}
}


However, on the button click, nothing is happening. Is anyone able to point out what might be going wrong?


Python printing a stringon two lines if string beginns with 'l'

so I have some code such as:



print(csv[0])
Genes = csv[0]
OutPut.write(Genes)
OutPut.write(',')
OutPut.write(csv[1])
OutPut.write(',')
try:
OutPut.write(csv[2])
except IndexError:
print("No Lethality")
OutPut.write('\n')


Basically csv has 3 objects and they should print out as this:


atp,10101010,lethal


But for some reason, if csv[0] so the first value, begining with an 'l' it is printed as:


l


sfsf,1010101010,Lethal


I have tried using a for loop etc but I always get the same issue and all the other lines which start without an 'l' work perfectly.


Thanks


Regex to find some text in a string c#

Its like a filtering, i have a list of string and a text box. Text that is entered in the textbox, should be filtered. Am planning to use Regex for this.


so am looping the strings and it should be check the textbox text is contains in this strings are not.


Please suggest the regex format to achieve this.


Please don't suggest a better way, since i need to be strict with this flow.


Update: What exactly am looking for is, "%"+searchTextBox.Text+"%" Regex for this statement


Swift : JSON into string into NSData Error unrecognized selector sent to instance

I'm a little stuck here. I'm creating an NSMutableDictionnary that I'm converting into JSON with SwiftyJSON, and then I want to collect that json into a string, transform into NSData in order to send it into a post request.


Here is my code



var dict:NSMutableDictionary = NSMutableDictionary()
dict.setValue(flight.id, forKey: "id")
dict.setValue(nil , forKey: "registration")
dict.setValue(60 , forKey: "duration")
dict.setValue(comment , forKey: "comment")

var json = JSON(dict).rawValue

let urlPath: String = "myawseomeurl"
var url: NSURL = NSURL(string: urlPath)!

var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)

request.HTTPMethod = "POST"

let data = json.dataUsingEncoding(NSUTF8StringEncoding)

request.timeoutInterval = 60
request.HTTPBody=data
request.HTTPShouldHandleCookies=false

let queue:NSOperationQueue = NSOperationQueue()

NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in

var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

})


And I get the following error:



[__NSDictionaryM dataUsingEncoding:]: unrecognized selector sent to instance 0x7fc9605e8ad0
2015-03-31 14:36:08.891 LearnToFly[18631:5221809] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryM dataUsingEncoding:]: unrecognized selector sent to instance 0x7fc9605e8ad0'

file reading in c++: for and while nested loop are not working as expected: serially?

I expect the nested for loops to work in a serial order for example consider the following code:



int main ()
{
string mainstr;
ifstream infile;
ifstream infile1;
infile.open ("27032015.log");
infile1.open("Exordernumber");
for (unsigned int curLine = 0; getline(infile1,exordernum); curLine++)
{
cout << "curLine:" << curLine << endl;
{
for (unsigned int curLine1 = 0; getline(infile,mainstr);curLine1++)
cout << "curLine1:" << curLine1 << endl;
if (mainstr.find(exordernum) != std::string::npos)
{
cout << "exordernum:"<<exordernum << ":" << endl;
}
}
}


I expect it to first print curLine: 1

then curLine1: {all the values}

then curLine: 2

then curLine1: {all the values}

then curLine: 3

then curLine1: {all the values}


so on ..


but it prints the things:

curLine: 1

then curLine1: {all the values}

curLine: 2

curLine: 3

curLine: 4


so on ..


Where is the mistake ?

Even if I use the while loops the same things gets printed.

I can't figure out the problem.


Now as the problem has been solved, I would like to know the python code for the same thing: Here is what I have written it gives an error.



#!/usr/bin/env python

import sys
import re

hand = open('Exordernumber')
for line1 in hand:
with open('27032015.log') as f:
for line in f:
if re.search(line,line1):
print line
f.close()


Kindly suggest the correct python code.


weird behavior of string.Format method [duplicate]


This question already has an answer here:




Why am I getting runtime exception at line



Console.WriteLine(string.Format("Hello World {0}", null)); //Runtime


while line



Console.WriteLine(string.Format("Hello World {0}", a));


works fine even though string a is null?



using System;

public class Program
{
public static void Main()
{
string a = null;

Console.WriteLine(string.Format("Hello World {0}", a));
Console.WriteLine(string.Format("Hello World {0}", null)); //Runtime exception! Why?
}
}


Here is DotNetFiddle


Array to more than one string

I have a JavaScript array:



cities = ["LA", "NYC", "Riyadh", "Frankfurt"]


The cities.toString() function will give me



"LA, NYC, Riyadh, Frankfurt"


How do I get



"LA", "NYC", "Riyadh", "Frankfurt"

C, how to put number split over an array, into int

Lets say I have char array[10] and [0] = '1', [1] = '2', [2] = '3', etc.


How would i go about creating (int) 123 from these indexes, using C?


I wish to implement this on an arduino board which is limited to just under 2kb of SRAM. so resourcefulness & efficiency are key.


How to split a integer string based on the character present in it

So I will have list of integer strings, I mean, integers converted to strings in my DB like below:



66S12345, 623T4785, 784D3212


So there will be only one occurance of character in the above string.


Now I want to split the string based on the character position and obtain it as S12345, T4785, D3212. But no idea how to get it.


I obtain list of strings as below



using(var context=new ATMAccountEntities()){
List<string> accountNumbers = new List<string>();
accountNumbers = (from n in context.Students select n.stdUniqueID).ToList();
foreach(var acc in accountNumbers) // acc can be 66S12345, 623T4785, 784D3212
{
string accNum= //Any way to split the string and obtain later part after character
}
};

Declaring an array of type String containing numbers with padding

I am trying to create an array of String that contain numbers. These numbers are the names of folders that I need to access. Currently I am declaring it as shown below:



String str1[] = { "001", "002", "003", "004", "005", "006", "007", "008", "009", "010", "011", "012", "013", "014", "015", "016", "017", "018", "019", "020", };


I have 124 folders and naming them in such fashion is tedious. Is there a better way to do this? I am working with C++.


Understanding char array[] and string

I am new to programming world. Now I am learning C as my first programming language. I found something strange to understand.


I have learned in C we can represent a String as a sequence of character like this (using char array)-



char status[10] = "Married";


I have learned that the problem of this approach is - we have to tell the size of the status array during compilation.


But now I have learned we can use a char pointer to denote an string like -



char status[10] = "Married";
char *strPtr;
strPtr = status;


I did not understand it properly. My questions are -


1. How can I get char at index 4 (that is i in Married) using the strPtr?


2. In status there is a null character (\0) at the end of the string represented by the char array - M->a->r->r->i->e-d->\0. So by using the null character (\0) we can understand the end of the string. When we use strPtr How can we understand the end of the string?


Thanks in Advance.


Incorrect output while comparing two strings C++

I have class CPerson that in simple looks like this:



CPerson
{
public:
CPerson();
pair<string, string> CP_surname_name;
vector<CCar> CP_CarList;
};


then I have a vector<CPerson> CR_people It's sorted vector by pair CP_surname_name. The problem is, when I need to compare surname and name, inputted by user firstly I go throug vector, if there is already the person I am looking for.



auto it = lower_bound(CR_people.begin(), CR_people.end(), surname_name);


I have overriden operator< so sorting is fine. But when I need to check, if the surname_name is exact the same as CP_surname_name by:



if(surname_name == (*it).CP_surname_name){...}


it gives me falseeven they are same. I already tried:



if(surname_name.first == (*it).CP_surname_name.first && surname_name.second == (*it).CP_surname_name.second){...}


and it works the same. I also tried strcmp() but it gives me errors, because I am using string, not char* so I tried append .c_str() to retype it, and that gave me also wrong results. The compare() in String class did not work as well. Thanks for any help, and sorry for my bad english.


Action link with string id returning HTTP Error 404.0 - Not Found..

I would like to receive a string as the id passed from action link in a view. But for some reason I always get the error HTTP Error 404.0 - Not Found The resource you are looking for has been removed, had its name changed, or is temporarily unavailable. When I was debugging the delete code in the controller never gets executed it just throws an error. I do not understand why I cannot achieve it with the following code.



//action link passing id (string)

<td>
@Html.ActionLink("Delete Room", "Delete", new {id=item.RoomName})|

</td>



//controller method Delete
public ActionResult Delete(string id)
{
Room room = db.Rooms.Find(id);
if (room == null)
{
return HttpNotFound();

}
return View(room);
}



//RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}

how to filter out a pattern in python regular expressions, till the input word

In python, i want to extract a particular sub string till the input word provided.


Consider the following string:-



"Name: abc and Age:24"


I want to extract the string "Name : abc and" änd "Age:24"seperately. I am currently using the following pattern:



re.search(r'%S+\s*:[\S\s]+',pattern).


but o/p is the whole string.


Java String-Collection: Longest common prefixes

I got a collection of String (directory paths). How can I get the longest common prefixes of ALL strings?


Example: ["e:/users/test", "e:/users/test/abc/", "c:/programs", "e:/data", "/test"]


the solution has to be than: ["e:/", "c:/programs", "/test"]


I have no idea how to realize this ...


thanks for your help, greetings


Sharing values through namespaces

My question is probably stupid, but I can't share a value through namespaces.



namespace AceEngine
{
namespace Graphics
{
namespace Interface
{
void drawDebugScreen()
{
// I want to access AceEngine::System::Version from here.
}
}
}

namespace System
{
string Version("DEBUG");
}
}


How can I access this string?


EDIT:


ae.cpp



#include "stdafx.h"
#include "sha256.h"
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::getline;
using std::string;

namespace AceEngine
{
namespace Graphics
{
namespace Interface
{
void drawDebugScreen()
{
cout << "Version: " << AceEngine::System::Version << endl;
}
class Window{};
}
}
namespace System
{
class User{};
void pause(){cin.get();}
extern string Version("DEBUG");
}
}


ae.h



#pragma once
#include "stdafx.h"
#include <string>
using std::string;

namespace AceEngine
{
namespace Graphics
{
namespace Interface
{
void drawDebugScreen();
class Window{};
}
}

namespace System
{
class User{};
void pause();
extern string Version;
}
}


I removed the useless parts (I left some classes to show there are stuff in the namespaces and it's not useless)


Scala convert list of Strings to multiple variables

I'm trying to convert a list of strings to multiple variables so that I can asign attributes to the conent of list.


MyCode:



val list = List("a", "b", "c", "d", "e", "f")
val attributes = Attributes(#SomeAwesomeScalaCode#)

case class Attributes(input:(String, String, String, String, String, String)) {
val a, b, c, d, e, f = input
}

Remove time zones from a string or format HTTP TIME STRING in coldfusion

I am formatting a normal string containing 11:00 PM or 23:00:00 using timeFormat() like this:



<cfset local.timeString = "11:00 PM">
<cfdump var="#local.timeString#">
<cfset local.newTimeString = timeFormat(local.timeString, "HH:mm:ss")>
<cfdump var="#local.newTimeString#">


Output:



11:00 PM 23:00:00



But in one case I came across a time string which also contains a time zone like this: 11:00 PM EDT, so when I was trying to format this string using timeFormat then I was getting error which is correct.



11:00 PM EDT is an invalid date or time string



This type of string can be generated using GetHttpTimeString.


Do I need to use something like this? It is not a correct way. Just thought this as found no other solution.



<cfset local.newTimeString = left(local.timeString
, len(local.timeString) - len(listLast(local.timeString," "))
)>


Is there any other function to format a string like this.


Please help. Thanks in advance.


Replace the " character with a space

I have a CSV file, where each comma delimited field is enclosed in " - eg. "fred", "bert", "blah". I am trying to use the replace function but can't seem to have it recognize the " character. example, if the record is in a string called buffer:



buffer.replace('\"','')

Alignment of text according to bullet

I have json with html format , i have set the data but problems is that,


after first there is a bullet , the next line start below the bullet , but i have to set below the text(its long). can anyone help me please , thanks in advance


Adapter



t.setText(Title[position]);
t1.setText(Html.fromHtml("<div style='text-align:justify;'>"+info_des[position].replace("<p>",
"<div style='height=5px;clear:both;'></div>")
.replace("</p>", "").replace("\r\n\t", "<li>")
.replace("<ul>", "").replace("</ul>", "").replace("</li>", "").replace("<li>",
"<div style='clear:both;'></div>")+"</div>"));


**Json data**
<body_value><p>La Politica Agricola Comune (PAC) rappresenta l'insieme delle regole riferite al comparto agricolo che l'Unione europea ha definito sin dalla sua&nbsp; nascita per uno sviluppo equo e stabile dei Paesi membri.</p><p>Avviata nel 1962, ai sensi dell'articolo 39 del Trattato sul Funzionamento dell'Unione europea, la PAC persegue i seguenti obiettivi:</p><ul>&#8226; incrementare la produttività dell'agricoltura;</li>&#8226; assicurare un tenore di vita equo alla popolazione agricola;</li>&#8226; stabilizzare i mercati;</li>&#8226; garantire la sicurezza degli approvvigionamenti;</li>&#8226; assicurare prezzi ragionevoli ai consumatori.</li></ul><p>Oggigiorno,&nbsp; l’Unione europea deve affrontare altre sfide tra cui anche:</p><ul>&#8226; la sicurezza alimentare — a livello mondiale, la produzione di alimenti dovrà raddoppiare per alimentare una popolazione mondiale di 9 miliardi di persone nel 2050,</li>&#8226; i cambiamenti climatici e la gestione sostenibile delle risorse naturali,</li>&#8226; la tutela delle campagne nell’UE e il mantenimento in vita dell’economia rurale.</li></ul><p>La PAC è una politica comune a tutti gli Stati membri dell’Unione europea, gestita e finanziata a livello europeo con risorse del bilancio annuale dell’UE. È una delle politiche comunitarie di maggiore importanza, impegnando circa il 34% del bilancio dell'Unione europea.</p><p>L'articolo 3 del Trattato di Roma afferma che la Comunità ha il compito di promuovere, mediante l'instaurazione di un mercato comune e il graduale riavvicinamento delle politiche economiche degli stati membri, uno sviluppo armonioso delle attività economiche. Per raggiungere tale scopo, occorreva:</p><ol>&#8226; Abolire i dazi doganali tra gli stati membri;</li>&#8226; Istituire tariffe doganali e politiche commerciali nei confronti degli stati terzi;</li>&#8226; Eliminare gli ostacoli tra gli stati membri di capitali, servizi e persone;</li>&#8226; Instaurare una politica comune nel settore dei trasporti e in quello dell'agricoltura;</li>&#8226; Creare un Fondo sociale europeo e una Banca europea, per promuovere gli investimenti.</li></ol><p>La PAC (Politica Agricola Comune o Comunitaria), fin dal suo inizio si era prefissata due obiettivi:</p><ol>&#8226; Soddisfare gli agricoltori grazie al prezzo di intervento. Questo era il prezzo minimo garantito per i prodotti agricoli stabilito dalla Comunità Europea. Il prezzo delle produzioni non poteva scendere al di sotto di questo;</li>&#8226; Orientare le imprese agricole verso una maggiore capacità produttiva (limitando i fattori della produzione, aumentando lo sviluppo tecnologico e utilizzando delle migliori tecniche agronomiche).</li></ol><p>Per perseguire gli obiettivi richiamati nel presente documento,&nbsp; fu istituito il FEOGA (Fondo Europeo di Orientamento e Garanzia Agricola); questo ente finanziario aveva il compito di raggiungere questi due obiettivi. Il mantenimento dei prezzi fu assicurato dalla CEE, grazie ad apposite aziende che si preoccupavano dell’acquisto delle eccedenze di produzione; queste venivano acquistate ad un prezzo d’intervento leggermente inferiore a quello indicativo. Le eccedenze venivano in seguito vendute a Paesi terzi con esportazioni sottocosto. Nel peggiore dei casi, le eccedenze venivano tolte dal mercato e quindi letteralmente distrutte. A causa dei prezzi dei prodotti agricoli dei Paesi extracomunitari, troppo bassi rispetto a quelli della Comunità Europea, furono erette delle vere e proprie barriere doganali, che imponevano dazi sulle merci in ingresso, facendone crescere il prezzo e scoraggiandone, quindi, l’importazione.<br /> Parallelamente, le esportazioni verso i Paesi dell’area extracomunitaria, furono incoraggiate con sovvenzioni (restituzioni) agli esportatori; tali restituzioni, compensavano la differenza tra prezzi comunitari più alti e prezzi esterni, più bassi. In tal modo, si ridussero le eccedenze che, altrimenti, sarebbero dovute essere acquistate dalle aziende incaricate dal FEOGA.</p></body_value>

How to check if a input is a string and show validation

I'm making a program in which the user inputs numbers into an entry box. I want to check its a number and if a letter has been entered show an error message however the program crashes instead of shows the error message. This is my code, any help?



def BreakEven(): #makes the breakeven chart
print("break even code goes here")

global e1text
if int(e1text) >= 101 or e1text.isdigit()== False:
tkinter.messagebox.showerror('Break Even','Total Revenue Invalid input')#makes error messages when no number is entered or more than 100
command = closewindow()
print(e1text)

Can't create a public static final String in java

This code:



public class CommandPrompt {
public static void main(String[] args) {
public static final String prompt = System.getProperty("user.name")+">";
System.out.println(prompt);
}
}


Returns this error message:



CommandPrompt.java:5: error: illegal start of expression
public static final String prompt = System.getProperty("user.name")+">";
^
CommandPrompt.java:5: error: illegal start of expression
public static final String prompt = System.getProperty("user.name")+">";
^
CommandPrompt.java:5: error: ';' expected
public static final String prompt = System.getProperty("user.name")+">";
^
3 errors


I have seen public static final String been used before, why can't I use it here?


Adding a space inbetween a user inputed string

I want a user to enter a String and then add a space in between a character at a chosen interval.


example: user enters: hello then asks for a space every 2 letters. output = he_ll_o_



import java.util.Scanner;

public class stackOverflow {


public static void main(String[] args) {


System.out.println("enter a string");
Scanner input = new Scanner(System.in);
String getInput = input.nextLine();

System.out.println("how many spaces would you like?");
Scanner space = new Scanner(System.in);
int getSpace = space.nextInt();


String toInput2 = new String();

for(int i = 0; getInput.length() > i; i++){

if(getSpace == 0) {
toInput2 = toInput2 + getInput.charAt(i);
}
else if(i % getSpace == 0) {
toInput2 = toInput2 + getInput.charAt(i) + "_"; //this line im having trouble with.
}

}


System.out.println(toInput2);

}



}


Thats my code so far, it might be the completely wrong way of solving it, so correct me if im wrong. thanks in advance :)


How to make a string uppercase (extended ASCII)?

I wrote this function to make a string all uppercase. Unfortunately, it does not work with the extended ASCII characters, like ä, ö, ü, é, è and so on. How can I convert the string to uppercase and convert these characters also (Ä, Ö, Ü, É, È)?



void toUppercase(string & strInOut)
{
std::locale loc;
for (std::string::size_type i=0; i<strInput.length(); ++i)
{
strInput.at(i) = std::toupper(strInput.at(i),loc);
}
return;
}

Object to String in PHP

One of my class' function outputs a text, something from my mysql db. But i couldn't explode() it since explode needs a string parameter. How to change it to a string.



class admin{

//constructor code

public function department_retrieve(){

//some code to retreive $this->old_department

echo $this->old_department;

}
}

$obj = new admin();
$obj->department_retrieve();


$obj->department_retrieve() outputs a text. I want something to explode the text by spaces. What i miss? How to make it a string? Please help.


Getting failed to open stream: HTTP request failed error with names with symboles

Why I got this error :



failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found



Code :



$Name = 'Teàst';
$result = file_get_contents('http://ift.tt/1DjDRBF' . $Name . );


But when I try echo $result; I got the link and its work fine. And when I try $Name = 'Teast'; (without "à" symbole) its work fine. Soo the problem is names with symboles (é è à ...). How to fix it please ?


Groovy String evaluation runtime

Hi I have a String value that is populated runtime and I want to use it to construct another String.



static value= ''
static construct = "${-> value - '/'}"


So when I value = "/http://ift.tt/fyw30c" , construct is equal to "http://ift.tt/fyw30c"


but when I do



static value= ''
static construct = {-> value - '/'}


construct is equals to some closure name. I am wondering what is the purpose of this? Why using closure,GString everything is ok? And why when use only closure nothing happens?


encoding/hex: invalid byte: U+0068 'h' Golang

I'm trying to convert a string into a byte array containing its hexadecimal values, here is the code I've written:



package main

import (
"encoding/hex"
"fmt"
"os"
)

func main() {
str :="abcdefhijklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ123456789"

b, err := hex.DecodeString(str)

if err != nil {
fmt.Println(err)
os.Exit(1)
}

fmt.Printf("Decoded bytes %v \n ", b)
}


Here is the link from Go PlayGround: http://ift.tt/1BGzif7


But it's giving me the error *encoding/hex: invalid byte: U+0068 'h' Golang *. What's the problem here? I want to convert my string into byte array containing hexadecimal values of each character in the string. I want b[n] to contain hexadecimal value of str[n].


lundi 30 mars 2015

search in textile C programming

I have to create a code where you ask the user what phrase they want to search in a textile to be translated. The phrase they input is supposed to be stored into an array, each word in the phrase is added to the array separated by a space. The program then searches the textfile to find the matching phrase. If the exact phrase is found, the exact phrase is translated. If the exact phrase is not found, it is broken into individual words and is translated individually. The words not found are left as is and the entire translated phrase is printed.


The phrases are stored in a textfile like this one:



hello
ey
how are you
hw u doin
what
wut
laugh out loud
lol


The first word is the word we will translate, meaning the translation is the line after.


I'm also using structs to do this. This is what I have so far, but it is not searching the file I want properly.



#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXL 128


typedef struct
{
char *English;
char *TextSpeak;
}Pair;

void main() {

FILE *infile=fopen("dictionary.txt","r");

int line_num = 1;
char inputArrray[];
int find_result = 0;
char temp[512];

printf("Enter the English phrase to search in dictionary: \n");
scanf(" %d", &inputArray[i]);

while(fgets(inputArray, 512, infile) != NULL) {
if((strcmp (inputArray, str)) != NULL) {
printf("A match found on line: %d\n", line_num);
printf("\n%s\n", inputArray[i]);

}
line_num++;
}

}


Now how would I associate my struct into this, and should I use strcmp or something like starts..


Any help would be appreciated for this program..


Attribute or Array - PHP

I need to find out, if a function parameter in my php-script is a regular string attribute or an array. How would I do that?



if(gettype($array) == "string"){return $array;}


...doesn't work. Or is there an error in this line? I'm new to php.


Concatenating strings having dot(period) in php [duplicate]


This question already has an answer here:




Googled but couldn't find an answer.


I have



echo "<input type = 'text' value = ".$value." name = ".$input_id."/>";


$value or $input_id contains a dot which is conflicting with the dot used for concatenation. How do I escape it?


Thanks!


How to get rid of garbage characters in this program?

This program is supposed to print an input string backwards. Every single time it happens, though, I get garbage characters such as \340 or of the like. Why is it doing that? Here's my code:



#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char mattsentence[51];
mattsentence[50] = '\0';
gets(mattsentence);
char mask[sizeof(mattsentence)];
int i, j;
j = sizeof(mattsentence);
for (i = 0; i < sizeof(mask); i++)
{
j = j - 1;
mask[i] = mattsentence[j];
printf("%c", mask[i]);
}
printf("\n");
}

Java fixed character width printing


import java.util.Scanner;
public class FixedWidthPrinting {

public static void print(String[] theWords, int width) {
/////////////////////////////////////////////////////////
//-- start is the beginning position of the current line
//-- end is the end position of the current line (exclusive)
//-- lineCounter is the number of lines
/////////////////////////////////////////////////////////
int start = 0, end = 0, lineCounter = 0;
int[] gaps;
/////////////////////////////////////////////////////////
//-- the loop is executed until start becomes theWords.length
/////////////////////////////////////////////////////////
while (start < theWords.length) {
//////////////////////////////////////////////////////
// this is the print length with the current position only
//////////////////////////////////////////////////////
// FILL
//////////////////////////////////////////////////////
// the end position is set to the start position + 1
//////////////////////////////////////////////////////
// FILL
//////////////////////////////////////////////////////
// test whether the word at the end position can be added
// to the group, if so, add and move the position by 1
//////////////////////////////////////////////////////
// FILL
//////////////////////////////////////////////////////
// if there is only one word, just print it
//////////////////////////////////////////////////////
// FILL
//////////////////////////////////////////////////////
// other, if this is the last line, print flushed to the left
//////////////////////////////////////////////////////
// FILL
//////////////////////////////////////////////////////
// otherwise, compute the gaps and print
//////////////////////////////////////////////////////
// FILL
////////////////////////////////////////////////////
// update lineCounter and start
////////////////////////////////////////////////////
lineCounter ++;
start = end;
}
}
public static void main(String[] args) {
int width = Integer.parseInt(args[0]);
String[] text = {
"Well,", "I", "woke", "up", "to",
"get", "me", "a", "cold", "pop",
"and", "then", "I", "thought", "somebody",
"was", "barbecuing.", "I", "said,", "\"Oh,",
"Lord,", "Jesus,", "It's", "a", "fire!\"",
"Then", "I", "ran", "out.", "I",
"didn't", "grab", "no", "shoes", "or",
"nothin',", "Lord", "Jesus.", "I", "ran",
"for", "my", "life.", "And", "then",
"the", "smoke", "got", "me.", "I",
"got", "bronchitis.", "Ain't", "nobody", "got",
"time", "for", "that."
};
print(text, 15);
}


}


I have to write a code in Java that prints texts in a fixed character width per line. It's basically a big while loop where the number of words to place in the next line is computed, then the sizes of the gaps are computed,and the line is produced, and then the starting position is updated.


The main is already written, I just have to write the print method. It should consist of two parts, a String array to be printed and an int that specifies the character width, which can be changed.


I've included all my notes about what should happen where, but I just am not sure what exactly I should be writing for the code.


Search column for a string in every space separated value

Suppose I have a column named CustomerNames in database with values:



  1. Vins et alcools Chevalier

  2. Magazzini Alimentari Riuniti

  3. Hungry Owl All-Night Grocers

  4. Split Rail Beer & Ale

  5. Alfreds Futterkiste


I want to make a query which will search only for the first letters of FIRSTNAME and LASTNAME, and list the names in ASC order based on FIRSTNAME then LASTNAME. for example if I search for "al" in above table, it should return me something like below:



  1. Alfreds Futterkiste

  2. Vins et alcools Chevalier

  3. Split Rail Beer & Ale

  4. Magazzini Alimentari Riuniti

  5. Hungry Owl All-Night Grocers


I have used below query.



SELECT * FROM Customers where CustomerName LIKE 'al%' OR CustomerName LIKE '% al%' ORDER BY CustomerName


Output:



  1. Alfreds Futterkiste

  2. Hungry Owl All-Night Grocers

  3. Magazzini Alimentari Riuniti

  4. Split Rail Beer & Ale

  5. Vins et alcools Chevalier


Which is orderingt results only on the basis of firstnames. But I want a query which gives output using firstnames and then lastnames. Thanks.


How do I output a block text in coffeescript with spaces BEFORE everything


redditFunny = """
TEST TEST
"""
console.log redditFunny


compiles into



var redditFunny;

redditFunny = "TEST TEST";

console.log(redditFunny);


I just want to output it as is


Undefined variable when declaring with concatenation

I get an undefined variable $ar, $pr and $af.



$sql = mysqli_query($connection, "Select empno, username, password, access_level from personaltab where access_level='ADMIN'");

$cnt = mysqli_num_rows($sql);
$i=0;

while ($r=mysqli_fetch_array($sql)){
$md = md5($r['username']."!@#$%^&*()_+|");
$ar .= $md.", ";
$mdp = md5($r['password']."|+_)(*&^%$#@!<>?:{}[]=-");
$pr .= $mdp.", ";
$af .= $r['empno'].", ";
}

passing a string to a function using character pointer

hey guys please have a look at this code.



class person
{
char name[20];
float age;

public:
person(char *s,float a)
{
strcpy(name,s);
age=a;
}
};

int main()
{
person P1("John",37.50);
person p2("Ahmed",29.0);
}


So in this class,the parametrized constructor takes a character pointer as an argument,and then passes the same to the strcpy function which copies the string to the character array name. If there is an integer array,like int arr[10]; then arr is a pointer to the first element. If there is a character array that is a string,like char str[]="Hello"; then str is a pointer to the first element,h in this case.So shouldn't we be passing something like str to the constructor?Why are we passing the character array elements,like "john","ahmed" to the constructor. Shouldn't we be doing - char str[]="ahmed"; person p1=(str,23);


how to replace a string in a cell with multi row character in matlab

i am using a template and regexprep to replace character. my template is huge so i can't post it here. so consider that my template name is templateGetC. I use



regexprep(templateGetC,'<final_bus_name>',component_name);


to replace the 'final_bus_name' in my template with the component_name which has the value 'machine'. but what if i want to replace it with a multi row string. like if



a= ' start the experiment
analyse the content
end the experiment'


and if i want to replace 'final_bus_name' with 'a' it throws me an error that 'The third argument (REPLACE) must be a one-dimensional array of char or cell arrays of strings.'


is there any other way to replace it. i tried num2cell but it's horrible and just messes up the data.


i also tried strrep but it throws the error 'Input strings must have one row.'


Unexpected output for looping through a string and using str.replace

I am going through the CodingBat exercises for Java. I have got up to this problem which asks:



Given a string, return a version where all the "x" have been removed. Except an "x" at the very start or end should not be removed.



I wanted to solve this by checking each character from the second up to the penultimate of the string. If the character is x, replace it with an empty character. Here is my code:



public String stringX(String str) {
String newStr = "";
for (int i = 1; i < str.length()-1; i++) {
if (str.indexOf('x') == i) {
newStr += str.replace('x', '\u0000');
}
}
return newStr;
}


The result of this is that it doesn't seem to return any of the string passed in, if the string begins with x:



System.out.println(test.stringX("xxHxix"));


returns (blank)



System.out.println(test.stringX("abxxxcd"));


returns abcd



System.out.println(test.stringX("xabxxxcdx"));


returns (blank)


I really can't figure out what's going on but I want to be able to understand it before just looking at the answer.


Is it problematic to concatenate a char into a string? Should I use substring instead?


Android create custom language and set it on runtime

I wan't to use a custom language (like pirate language on minecraft) on my app that the user can select through the settings menu. Normally I would put the strings.xml file into a values-en or so folder. Then I would load it at runtime using this code:



Resources res = context.getResources();
// Change locale settings in the app.
DisplayMetrics dm = res.getDisplayMetrics();
android.content.res.Configuration conf = res.getConfiguration();
conf.locale = new Locale("xy");
res.updateConfiguration(conf, dm);


If I was to create a language in a values-xy folder and then load it using the code and choosing the language xy it does not load it. Is something like that even possible? Creating a custom languag using a non existant language code and use that? Id did not work using the code above.


Create array from string using php

I have a string like below



Final-Recipient: rfc822;test@example.com
Action: failed
Status: 5.1.1
Diagnostic-Code: smtp;550 5.1.1 RESOLVER.ADR.RecipNotFound; not found


I need to get each value as an associative array like



array('Final-Recipient'=>'rfc822;test@example.com',
'Action'=>'failed',
'Status'=>'5.1.1',....)


I was try with explode function,But it don't give result expected.



$result = array();
$temp = explode(';',$message);
foreach($temp as $value)
{
$temp2 = explode(':',$value);
$result[$temp[0]] = $result[$temp[1]];
}
print_r($result);

Python - pdsend datastream

First of all some context: Four MPR121 Breakout Boards (http://ift.tt/1nKbVNI) connected via i2C to a Raspberry Pi 2. A python script reads the data from the four boards and sends it to pure data with pdsend.


At the moment I have managed to get all the data I need to print nicely on the terminal. However, I am not sure how to get the same in pure data as I am getting text messages only (something like "print: .join(map(str print: diff3))")


I am pretty sure I need to change the os.system line to accomodate for the variables but I can't find how to do this.


Thank you very much in advance.



def send2Pd (message=' '):
os.system("echo '" + message + "' | pdsend 3000");

while True:

diff1 = [cap1.baseline_data(i)-cap1.filtered_data(i) for i in range(12)]
print 'Diff1:', '\t'.join(map(str, diff1))
send2Pd ('.join(map(str, diff1));')

diff2 = [cap2.baseline_data(i)-cap2.filtered_data(i) for i in range(12)]
print 'Diff2:', '\t'.join(map(str, diff2))
send2Pd ('.join(map(str, diff2));')

diff3 = [cap3.baseline_data(i)-cap3.filtered_data(i) for i in range(12)]
send2Pd ('.join(map(str, diff3));')
print 'Diff3:', '\t'.join(map(str, diff3))

diff4 = [cap4.baseline_data(i)-cap4.filtered_data(i) for i in range(12)]
print 'Diff4:', '\t'.join(map(str, diff4))
send2Pd ('.join(map(str, diff4));')

time.sleep(0.1)

Podio issue: Can't convert string to number

I know how to convert a string to a number (parseInt, parseFloat, Math., + Number() etc.).


But this all doesn't work in a PODIO calculation field with a string from a PODIO text field (single line and multi line, and also not from a text type calculation field). Text in textfield: 123



var str = @textfield;
Number(str)


Also when I tried with parseInt(str) etc. result is always the error msg.: Not a valid number.


It works e.g when str = "123", but not when I want to use the token @textfield. It works also when str is a category field token (and categorie is 123).


Any suggestion how I can convert a string to a number using a @textfield token?


TIA Rainer


How to get string between two commas

I have some numbers string which is:



var _ids = 130,131,240;


i need to get some number from this string which is 131, i cant use .split() method because numbers between comas can be more, instead of this i know actual id which is number 130 (in this example), so i'am doing this:



var _id = 130;
var id = _ids.substring(_ids.lastIndexOf((_id + ',') + 1), _ids.lastIndexOf(','));


in result i have 130,136... What i'm doing wrong? Can anybody help?


String.split method to split a string by dot and save it as arraylist

Am Fetching few lines from remote server and saving each line as an arraylist element by setting dot as a separator. Everything works fine. I just don't understand why a strange rn value gets appended to every new line.


E.g.:



I am going to School. I am feeling hungry



gets split and displayed as



I am going to School


rnI am feeling hungry



What does that rn stands for?


I am using String.split to separate. My code is below.



List<String> po= new ArrayList<String>();

separated_q = Arrays.asList(prdesc.split(Pattern.quote(".")));

for(int k=0;k<separated_q.size();k++) {
po.add(separated_q.get(k));
}


Please help me point out where am wrong.


Identify Random Strings in Python

I'm trying to identify random strings from list of strings in python, I want to read each word and be able to say if it is random or if it is a meaningful word.


ex - rrstm asdfsa qmquas


Other than storing all the english words in a file and comparing them, are there any solution or existing code library already present ?


Wrong array input

So I wanted to take the user input into a variable and then add it to the array but instead the character goes straight into the array and skips like 3 lines of code. The Code here



import java.util.*;
public class Hangman{

public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your word and press enter: ");
String word = sc.nextLine();
System.out.println("Please enter a relevant category and press enter: ");
String category = sc.nextLine();
word.toUpperCase();
char charArray[] = new char[word.length()];


for(int i = 0; i<=word.length(); i++){
System.out.println("Category: " + category);
System.out.println("Letters Guessed: " + Arrays.toString(charArray));
System.out.println("Your guess: ");
char guess = sc.nextLine().charAt(0);
compare(guess, word);
charArray[i] = guess;


}
}
public static boolean compare(char guess, String word){
for(int i = 0; i<word.length(); i++){
if(guess == word.charAt(i)){
return true;
}
}
return true;
}
}


Output :



Please enter your word and press enter:
hello
Please enter a relevant category and press enter:
test
Category: test
Letters Guessed: [hi
Category: test
Letters Guessed: [h, l
Category: test
Letters Guessed: [h, l, m
Category: test
Letters Guessed: [h, l, m, o
Category: test
Letters Guessed: [h, l, m, o, n
Category: test
Letters Guessed: [h, l, m, o, n]
Your guess:


can someone give some tips


hyphenate only when the word is too long for one whole sentence

There are already many questions about hyphenating words, but I couldn't find a question about hyphenate only when one word is too long for one whole sentence.


example:


I like this to be intact (not trying to put the word "opportunities" in the upper line with hyphenates)


enter image description here


But I want to have a word that doesn't fit the whole line/div/page is hyphenated. Otherwise I can't see the text in full. (now it cuts off the last 3 characters)


enter image description here


All the solutions I have seen before on other questions does hyphenate on both examples instead of only in the last example.


I don't think I am the only one who counters this issue?


ejs string variable with space is not displayed properly

I am trying to display the search query in the search bar in HTML. But if the variable includes a space, the webpage is only going to display the first word.


Here is the code



app.get('/search', function(req, res) {
console.log(req.originalUrl,'oro')
console.log(req.query['search_query'],'aaaaaaa')
res.render('search.ejs', {
user : req.user,
query : req.query['search_query']
});
});


Here is the html code



<form action="/search" method="get">
<div class="form-group">
<input type="submit" class="btn btn-warning btn-lg" value = "search" style = "float: right"/>
<div style="overflow: hidden; padding-right: .5em;">
<input type="text" value = <%= query %> class="form-control" name="search_query" style = "width:100%;"/>
</div>
</div>
</form>


query is the variable collected from the last webpage and passed to /search.


If I type in "I want to find xx", the webpage will only display "I" in the search box. However, in the console, the printout result is the full query " I want to find xx". The corresponding url is also correct "/search?search_query=I+want+to+find+xx".


Anyone has an idea? Thanks a lot!


Reading strings on position basis from notepad

My requirement is to extract strings on positional basis from a string builder/notepad. There are quite a few strings that I am supposed to extract.


I am sure that we can split the string using Sub string method.


But I would like to use some efficient libraries to extract?


Please let me know for more information


Cmd String to PAnsiChar in delphi

I am relatively new to Delphi and I want to make a quick application the uses the ShellExecute command.


I want to use string values in edit boxes to add to the command line for doing the processing job outside of the application.


Everything works fine, but I get the error :



"Incompatible types: String and PAnsiChar"



I have tried to convert it using: Variable := PAnsiChar(AnsiString(editbox.Text), but to no avail.


Can anyone assist me with this problem please.


How can I append to a string many times?

So I have a loop that generates a sting every time and I want to append this string to an existing variable.



char fullString[] = "start: ";

while(x < 200){

char someVar[] = "test "

//append someVar to fullString

x++;

}


So I would like to end up with a string like this:



start: test test test test test ...


I can do it easily on any other language, just not sure how to do it in c, any ideas?


hash from multilines strings

I have two lines of this type as output of a cli command:



Source | Status | Enable | IP address | Subnet mask
----------------------------------------------------------------------------
Static | Disabled | true | 2.2.2.2 | 255.255.0.0


I would like create a hash :



{"Source"=>"Static", "Status"=>"Disabled", "Enable"=>"true", "IP
address "=>"2.2.2.2", "Subnet mask"=>"255.255.0.0" }


Thank you


Android formatting xml string loses its html tags

I have a xml string below that contains html tags such as Bold and a hyperlink href.



<string name"example"><b>%1$s</b> has been added to your clipboard and is valid until <b>%2$s</b><a href="http://www.google.com">Please see our +T\'s and C\'s+ </a> </string>


when i format the string to dynamically add some values it removes the bolded text and href I defined.


code below:



SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yy");
Date date = new Date(text.getValidTo());
String text = String.format(getString(R.string_dialog_text), text.getCode(), simpleDateFormat.format(date), "£30");


I then apply it to a alert dialog



AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setNeutralButton(R.string.ok, onClickListener);
builder.setTitle(title);
builder.setMessage(text);


this worked fine if i dont format the text and directly use the string resource


WiFi fingerprinting - remove unwanted syntax in SSID

I have an Android app that gets the list of SSID's and their signal strength and returns them a server for classification. The problem I'm having is that someone in the building (sadly I've been unsuccessful in hunting them down) has an SSID called:


mark anderson's Network


As you can see he has an ' in his SSID which is causing the server program to throw a syntax error:



----------------------------------------
Exception happened during processing of request from ('193.61.149.72', 61234)
Traceback (most recent call last):
File "/usr/lib/python2.7/SocketServer.py", line 295, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 321, in process_request
self.finish_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python2.7/SocketServer.py", line 649, in __init__
self.handle()
File "LocationBuildingServer.py", line 37, in handle
input = ast.literal_eval(udpstring)
File "/usr/lib/python2.7/ast.py", line 49, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/usr/lib/python2.7/ast.py", line 37, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
[7,3,{'SERG J26':-45,'GlassWifi':-40,'SERG':-53,'Skynet':-62,'eng_j':-66,'Staff':-66,'eduroam':-66,'eduroam':-80,'Belkin_N+_2CD164':-66,'dlink_DWR-921':-58,'Visitor':-66,'dlink':-69,'Staff':-75,'eng_j':-80,'Staff':-76,'eng_j':-80,'eduroam':-77,'eduroam':-86,'Staff':-85,'Visitor':-75,'Visitor':-80,'Visitor':-79,'eng_j':-81,'eduroam':-83,'eng_j':-84,'Visitor':-81,'':-73,'eduroam':-84,'':-80,'Staff':-79,'eng_j':-86,'Staff':-84,'Visitor':-84,'eduroam':-86,'eng_j':-84,'Visitor':-85,'Staff':-87,'HP-Print-AC-Officejet 6600':-88,'HP-Print-D6-Photosmart 6520':-91,'eduroam':-77,'HP-Print-AB-Photosmart 7520':-88,'mark anderson's Network':-91}]
^
SyntaxError: invalid syntax
----------------------------------------
----------------------------------------
Exception happened during processing of request from ('193.61.149.72', 61234)
Traceback (most recent call last):
File "/usr/lib/python2.7/SocketServer.py", line 295, in _handle_request_noblock
self.process_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 321, in process_request
self.finish_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python2.7/SocketServer.py", line 649, in __init__
self.handle()
File "LocationBuildingServer.py", line 37, in handle
input = ast.literal_eval(udpstring)
File "/usr/lib/python2.7/ast.py", line 49, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
File "/usr/lib/python2.7/ast.py", line 37, in parse
return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
[7,3,{'SERG J26':-41,'GlassWifi':-40,'SERG':-49,'Skynet':-62,'eng_j':-68,'Staff':-66,'eduroam':-70,'eduroam':-80,'Belkin_N+_2CD164':-69,'dlink_DWR-921':-54,'Visitor':-68,'dlink':-69,'Staff':-75,'eng_j':-80,'Staff':-79,'eng_j':-80,'eduroam':-77,'eduroam':-86,'Staff':-85,'Visitor':-75,'Visitor':-79,'Visitor':-79,'eng_j':-80,'eduroam':-79,'eng_j':-84,'Visitor':-84,'eduroam':-84,'':-80,'Staff':-81,'eng_j':-86,'Staff':-84,'Visitor':-84,'eduroam':-88,'eng_j':-84,'Visitor':-85,'Staff':-87,'HP-Print-AC-Officejet 6600':-88,'HP-Print-D6-Photosmart 6520':-91,'eduroam':-77,'HP-Print-AB-Photosmart 7520':-88,'mark anderson's Network':-91,'':-65}]


A code snippet of where the SSID's are being sent from the app:



String message = "[" + xTxt.getText().toString() + "," + yTxt.getText().toString() + ",{";
myWifiMan.startScan();
List<ScanResult> wifiList = myWifiMan.getScanResults();
if (wifiList != null){
//Construct Clue
for(int i = 0; i < wifiList.size(); i++){
message = message + "'" + wifiList.get(i).SSID +"':" + Integer.toString(wifiList.get(i).level);
if((i+1) < wifiList.size())
message = message + ",";
}
message = message + "}]";


Snippet from Python server:



def handle(self):
udpstring = self.request[0].strip()
clientid = self.client_address[0]
input = ast.literal_eval(udpstring)
xcoord = input[0]
ycoord = input[1]
scan = input[2]
myFile = Settings.trainedFile %(xcoord,ycoord)
path = os.path.join(Settings.trainedDataFilepath,myFile)


Is there anyway I can get my program to either ignore this SSID or remove the ' character from any SSID? (Either from the app or the server)


Concern of a string conversion function

I made a conversion function from a proprietary text format to a simple text string with escaped unicode codepoints (in the form `\uXXXX' where XXXX is the unicode codepoint in hex format).



int wchar_to_utf16(wchar_t* strIn, char* strOut, int max_buf_len);


In this function I pass the pointer to the string to be converted, the pointer to the destination buffer (in which the converted string will be written) and the length of such buffer.


Inside the function there are buffer bound checks all over the place, if the space is not enough the function returns 1 otherwise 0.


My question is: is a concern of my function to know the buffer length and perform the checks or it's better to remove the length parameter and do the check on the caller? Problem: The minimum buffer length can only be determined looking at the input string and knowing the encoding (which should not be a concern of the caller)


Python: how to Insert value into table postgresql?

how to format the string to insert it into a table in postgresql? example I have the sql:



req="INSERT INTO table_a values('%s','%s','%s')"


and the values



values=["Socit d'Invest Variable", '6465', 'hg', 'fk_id']
cursor.execute(req,tuple(values))


I get the error :



psycopg2.ProgrammingError: syntax error at or near "Socit"
LINE 1: ...column0, column1, column2, column3) Values (''Socit d'Invest...


any Idea how to change the string from using a single quote ' to a double quote " ?


How to split a string without losing any word in JAVA

I was using eclipse for java.


I want to split an input line without losing any char.


For example input line is:



MAC 4 USD7MAIR 2014 USD1111IMAC 123 USD232MPRO 2-0-1-5


And the output should be :



MAC 4 USD7,MAIR 2014 USD1111,IMAC 123 USD232,MPRO 2-0-1-5


(If I split with "M" or etc. the char "M" itself will be remove.)


What should I do ?


Java: Regex not matching

I have comma separated string values. Every string may contain characters or numbers along with '-' or '/' or '.'.


My code looks like:



final String VALUES_REGEX = "^\\{([0-9a-zA-Z\\-\\_\\.])+,*([0-9a-zA-Z\\-\\_\\.])*\\}$";
final Pattern REGEX_PATTERN = Pattern.compile(VALUES_REGEX);
final String values = "{df1_apx.fhh.irtrs.d.rrr, ffd1-afp.farr.d.rrr.asgd}";
final Matcher matcher = REGEX_PATTERN.matcher(values);
if (null != values && matcher.matches()) {
// further logic
}
...
...


Here if condition always returns false value because regex match fails. I verified regex using regexper. It looks fine.


Can you please tell me what is wrong here?


Substituting multiple Strings in String

I know there are a lot of questions and answers related to similar questions but I couldn't find an answer to my question. This a small snippet of my code:



private String substitute(String text) {
List<Macro> macros = getMacros();

for (Macro macro : macros) {
text = StringUtils.replace(text, macro.getKey(), macro.getValue());
}
return text;
}



  1. Would this be a good way to substitute multiple macros variables in a text String? This creates a new String object on every loop so I am wondering if there's a better way to do this. Ideally I would have used Apache Commons StrSubstitutor class but I can't because of the format of the tokens/macros (different formats and not between a fixed prefix/suffix). I also don't want to use Regex because of performance issues.


  2. According to some coding rules at work I need to mark the argument as final. I wonder if that's indeed good practice here. I know that Strings are immutable and I know that whenever I call StringUtils.replace() it will return me a new String object. But I am wondering if the String argument here should be marked as final as suggested and in the method do something like this:



    String result = text;
    for (Macro macro : macros) {
    result = StringUtils.replace(result, macro.getKey(), macro.getValue());
    }


    I just don't like this.




Any help would be appreciated. Thanks.


encryption program. how to reverse my encryption of a string

I have to write a program that uses letter displacement to encrypt a string that is entered by the user. The code for encryption looks like:



for (int j = 0; j<key; j++){
for (i = j; i <length; i += key)
{
password += phrase.charAt(i);
}
}


This does what I want it to do. For example it will change Testing1234567890ABCDEF to Ttg369BEei1470CFsn258AD when I use a key length of 3.


My issue is when I try to undo it.



for (int j = 0; j<=Math.ceil(phrase.length()/key); j++){
for (int i = j; i < phrase.length(); i += Math.ceil((phrase.length()/key))+1)
{
password += phrase.charAt(i);
}
}


This works for this phrase at this key but does not work if I use a different phrase or different key.


What am I missing?


get data from two different files using TCL

i have two files


file1



10 123
9 456
8 789
7 111


and file2



10 687
8 265
7 698
6 222


I want the final output to be like



10 123 687
9 456 0
8 789 265
7 111 698
6 0 222


Any help will be highly appreciated!


P.S i tried using sort, unique, awk but still couldn't figure it out


Convert String to Image in Android?

So, here is the thing. I am receiving an imagepath through WebService. I am storing the imagepath in a String. Now I want to convert the String to Bitmap and display the image in an imageView. I tried many codes from the examples in the internet but are not working.


Try 1:



Bitmap bm = BitmapFactory.decodeFile(imagelogo);
imageView2 = (ImageView) findViewById(R.id.imageView2);
imageView2.setImageBitmap(bm);


Try 2: First I am converting String to string Base64 and then string Base64 to Bitmap.



byte[] data;
String base64;
{
try {
data = imagelogo.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, Base64.DEFAULT);
Log.i("Base 64 ", base64);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

public Bitmap StringToBitMap(String encodedString){
try {
byte [] encodeByte=Base64.decode(base64 ,Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch(Exception e) {
e.getMessage();
return null;
}
}


Any help would be appreciated. Thanks in advance.