text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
html email template table header alignment
I have to float two header alignment left and right, the logo will be float left and navigation will be right but vertically center
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en" style="" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:v="urn:schemas-microsoft-com:vml">
<!--xmlns fix Outlook Scaling-->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="format-detection" content="telephone=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!--Fix Outlook Scaling-->
<!--[if gte mso 9]>
<xml>
<o:OfficeDocumentSettings>
<o:AllowPNG/>
<o:PixelsPerInch>96</o:PixelsPerInch>
</o:OfficeDocumentSettings>
</xml>
<![endif]-->
<link href="https://fonts.googleapis.com/css?family=Nunito:300,400,600,700|Nunito+Sans:300,400,600,700,900" id="google-fonts-css" media="all" rel="stylesheet" type="text/css" />
<title></title>
<!--[if mso]>
<style type="text/css">
body, table, td {
font-family: Arial, Helvetica, sans-serif !important;
}
</style>
<![endif]-->
<style type="text/css">
html,
body {
font-family: 'Nunito Sans', Helvetica, Arial;
margin: 0 !important;
padding: 0 !important;
text-size-adjust: none !important;
-ms-text-size-adjust: none !important;
-webkit-text-size-adjust: none !important;
-webkit-font-smoothing: antialiased;
background-color: #EEEEEE;
font-size: 16px;
}
body {
height: 100% !important;
width: 100% !important;
}
a {
text-decoration: none;
color: #002173;
}
h1 {
font-family: 'Nunito Sans', Helvetica, Arial;
}
.cus-pad {
padding-left: 20px;
padding-right: 20px;
}
.ReadMsgBody {
width: 100%;
}
.ExternalClass {
width: 100%;
}
.ExternalClass,
.ExternalClass span,
.ExternalClass td,
.ExternalClass div {
line-height: 100%;
}
#outlook a {
padding: 0;
}
table,
td {
mso-table-lspace: 0pt;
mso-table-rspace: 0pt;
}
body {
height: 100% !important;
margin: 0 !important;
padding: 0 !important;
width: 100% !important;
}
img {
-ms-interpolation-mode: bicubic;
}
img {
border: 0;
height: auto;
line-height: 100%;
outline: none;
text-decoration: none;
}
/*no linky*/
a[x-apple-data-detectors] {
color: inherit !important;
text-decoration: none !important;
font-size: inherit !important;
font-family: inherit !important;
font-weight: inherit !important;
line-height: inherit !important;
}
.link-hover:hover {
text-decoration: none !important;
}
table {
border-collapse: collapse;
margin: 0 auto;
padding: 20px;
}
.button:hover {
background-color: #ffd251 !important;
}
.button-2:hover {
background-color: #777671 !important;
}
tr.social-link td a img {
height: 20px;
width: auto;
}
@media only screen and (max-width: 481px) {
/**generic styles for content added through editor**/
table {
width: auto !important;
}
td {
display: block;
margin: 0 auto;
width: auto !important;
}
/**all tds added to template will wrap!**/
img {
float: none !important;
display: block;
padding: 0;
max-width: 100%;
height: auto !important;
}
/****/
.container {
padding: 0 !important;
}
.no-wrap {
width: 100% !important;
}
table.no-wrap td {
/**add class no-wrap to table to keep it from wrapping**/
display: table-cell !important;
}
table[class="resp"] {
width: auto !important;
padding: 5px !important;
}
.main-content-area {
-webkit-text-size-adjust: 90% !important;
line-height: 21px;
text-align: left;
}
.promo-code {
padding: 20px !important;
}
td[class="main-content-area"] h2 {
-webkit-text-size-adjust: 80% !important;
}
td[class="force-col"] {
/**add this class to any td you'd like to wrap in a one-column layout**/
display: block;
margin: 0 auto;
width: auto !important;
padding: 0;
}
img {
max-width: 100% !important;
height: auto !important;
}
/**hide content**/
*[class="hide-me"] {
display: none !important;
}
img[class="show-img"] {
display: block !important;
padding-top: 10px;
max-height: none !important;
width: auto !important;
height: auto !important;
}
}
.gf-e-header td a {
text-transform: uppercase;
font-weight: bold;
font-size: 14px;
}
</style>
</head>
<body style="background-color: #eeeeee;">
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="margin-top: 30px">
<tr>
<td class="container" style="" width="100%">
<table bgcolor="#FFFFFF" border="0" cellpadding="0" cellspacing="0" class="resp" width="600">
<tbody>
<tr>
<td class="cus-pad" style="padding-top: 20px">
<table align="left">
<tr class="gf-e-header">
<td class="gf-e-header">
<div style="float: left">
<a href="https://emfluence.com?emfl_e=916958C94AF9D49E069A3B6512D798B4&emfl_c=68E0D107B451EDAAC017E81290098F6D4F1A98D9FF722E2FE743BFB4C178E43F" target="_blank">
<img border="0" src="https://i.imgur.com/rczT2MV.png" width="130" />
</a>
</div>
</td>
<td valign="middle" align="right">
<a href="">Company</a>
<a href="">Services</a>
<a href="">Locations</a>
<a href="">Resources</a>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td style="padding-bottom: 25px;padding-top: 20px;padding-right: 20px;padding-left: 20px;">
<div style="border:1px solid #002173"></div>
</td>
</tr>
<tr>
<td class="cus-pad">
<h1 style="color:#002173">General information</h1>
<p style="color:#454545">The following information will provide you with an easy to navigate overview of what will happen with your personal data when you visit our website. The term „personal data“ comprises all data that can be used to personally identify you.
For detailed information about the subject matter of data protection, please consult our Data Protection Declaration, which we have included beneath this copy.</p>
</td>
</tr>
<tr>
<td align="left" bgcolor="#FFFfFF" class="hero cus-pad">
<img src="https://i.imgur.com/f1OWoqx.jpg" width="560px" />
</td>
</tr>
<tr>
<td class="cus-pad">
<h1 style="color:#002173">Data recording on our website</h1>
<h4 style="color:#454545">Who is the responsible party for the recording of data on this website (i.e. the„controller“)?
</h4>
</td>
</tr>
<tr>
<td align="left" class="main-content-area cus-pad"><span style="font-size: 15px; color:#454545">The data on this website is processed by the operator of the website, whose contact
information is available under section „Information Required by Law“ on this website.</span>
</td>
</tr>
<tr>
<td align="center" style="padding-bottom: 50px;padding-top:10px;">
<div>
<!--[if mso]>
<v:rect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word"
href="http://" style="height:40px;v-text-anchor:middle;width:150px;" stroke="f"
fillcolor="#70002c">
<w:anchorlock/>
<center>
<![endif]-->
<a href="http://" style="background-color:#70002c;color:#ffffff;display:inline-block;font-family:sans-serif;font-size:13px;font-weight:bold;line-height:40px;text-align:center;text-decoration:none;width:150px;-webkit-text-size-adjust:none;">Learn
More</a>
<!--[if mso]>
</center>
</v:rect>
<![endif]-->
</div>
</td>
</tr>
<tr>
<td class="cus-pad" style="padding-top: 40px;padding-bottom:40px">
<div style="border:1px solid #002173;"></div>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr>
<td align="center" style="padding: 0">
<table border="0" cellpadding="0" cellspacing="0" class="resp" style="background: #FFFFFF; padding-left: 15px; padding-right: 15px;" width="600">
<tbody>
<tr>
<td align="right" style="padding: 0 0 0px 15px;">
<table border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td align="center" style="padding: 0 0 30px 0;">
<a href="https://emfluence.com?emfl_e=916958C94AF9D49E069A3B6512D798B4&emfl_c=68E0D107B451EDAAC017E81290098F6D4F1A98D9FF722E2FE743BFB4C178E43F" target="_blank">
<img border="0" src="https://i.imgur.com/rczT2MV.png" width="100" />
</a>
</td>
</tr>
<tr class="social-link">
<td align="center" style="padding-bottom: 30px;">
<a style="margin-right: 10px;" href="">
<img height="18px" src="https://i.imgur.com/gWSZvGP.png" alt="">
</a>
<a style="margin-right: 10px;" href="">
<img height="18px" src="https://i.imgur.com/cCgx01J.png" alt="">
</a>
<a style="margin-right: 10px;" href="">
<img height="18px" src="https://i.imgur.com/HKXV4wh.png" alt="">
</a>
<a href="">
<img height="18px" src="https://i.imgur.com/Akw0TqM.png" alt="">
</a>
</td>
</tr>
<tr>
<td style=" color:#6C6C6C; font-size:14px;padding-bottom: 30px;">
<a style="color:#6C6C6C; border-right: 1px solid #6C6C6C; padding-right: 12px;font-weight: bold;line-height: 14px" href="">Privacy Policy</a>
<a style="color:#6C6C6C; padding-left: 10px;font-weight: bold; line-height: 14px " href="">Terms of
services</a>
</td>
</tr>
</tbody>
</table>
<table align="center" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr align="center">
<td style="padding-bottom: 30px;font-size: 10px">
This email was sent to <a href="">[email protected]</a> <br/> © 2004-2020 All rights reserved - Global Fairways®
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</table>
<br clear="all" />
</body>
</html>
And the responsive links will go down after the logo.
A:
Your header is currently not taking up the full width of the email, so first add width:100%; to this element. Next, just add either text-align:right; or just align="right" to the navigation section. See below:
<table align="left" style="width: 100%;">
<tbody>
<tr class="gf-e-header">
<td class="gf-e-header">
<a href="https://emfluence.com?emfl_e=916958C94AF9D49E069A3B6512D798B4&emfl_c=68E0D107B451EDAAC017E81290098F6D4F1A98D9FF722E2FE743BFB4C178E43F" target="_blank">
<img border="0" src="https://i.imgur.com/rczT2MV.png" width="130">
</a>
</td>
<td style="text-align: right;">
<a href="">Company</a>
<a href="">Services</a>
<a href="">Locations</a>
<a href="">Resources</a>
</td>
</tr>
</tbody>
</table>
JSFiddle
| {
"pile_set_name": "StackExchange"
} |
Q:
Dificuldades em buscar valores num array
O seguinte código é um código de incrementação num array.
No entanto, não tenho conseguido selecionar qualquer valor do array. Se der print_r nele, ele mostra todos mas se eu tentar aceder com $guarda_array[1] ele devolve Array e não o nome que pretendo. Algum trecho do código está mal?
$guarda_array = array();
$count_pub=mysqli_query($db, "SELECT nome FROM publicidades_sponsors");
$count_tudo=mysqli_num_rows($count_pub);
while($gu=mysqli_fetch_assoc($count_pub)){
array_push($guarda_array, $gu);
}
O print_r mostra o seguinte
Array ( [0] => Array ( [nome] => DIDAXIS1.png ) [1] => Array ( [nome] => DIDAXIS2.png ) [2] => Array ( [nome] => DIDAXIS3.png ) [3] => Array ( [nome] => DIDAXIS4.png ) )
A:
Se a intenção é ter como resultado um array com o campo "nome" do SELECT, você precisa fazer:
$guarda_array = array();
$count_pub=mysqli_query($db, "SELECT nome FROM publicidades_sponsors");
$count_tudo=mysqli_num_rows($count_pub);
while($gu=mysqli_fetch_assoc($count_pub)){
array_push($guarda_array, $gu["nome"]);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get most language learning benefits from frequent casual conversations with natives?
I know several languages on various levels:
Polish native
English C1-C2
German B2-C1
Russian B1
Spanish B1
I have tons of opportunities to speak to natives:
English - quite a few people at work (though very mixed origin: USA, Canada, UK)
German - I have been living in Germany for 8 years now
Russian - my wife speaks exclusively Russian at home (to me and our kids; I talk to all of them in Polish) and we spend ~1 month each year in her hometown
Spanish - every now and then I meet Spanish people where I live and there is a chance for a longer conversation
I can usually eventually communicate what I want in all of those languages. But I don't feel like I'm getting any better in neither language. I'm not taking a course or any other more structured approach as currently, I have other more pressing issues in my life. Still, I'd like to make the best use of the time I have with natives. Without turning the encounters into a lesson, that is.
If I had to narrow down the things I'd like to improve I'd go for:
grammar (e.g. prepositions and articles in German, declension in Russian)
vocabulary (nothing specialized, just every-day topics)
pronunciation (not perfect, just being consistent and sounding clear)
It's about improving confidence and fluency.
I don't have to work on everything at once. If there are any ideas to prioritize things, then I'm happy to hear them.
So, how to get most language learning benefits from frequent, casual conversations with natives?
Cheers!
A:
The most interesting approach I have seen so far is the FORCE Cycle, a strategy formulated by the Canadian linguist Keith Swayne. He described the strategy in a series of blog posts (with embedded YouTube videos) that start at http://fivearrows.ca/wp/2012/04/28/the-force-cycle-phase-1/. The strategy relies on speaking in your target language and preparing for this by anticipating certain things (vocabulary and grammar) that may come up in the conversation. The idea is that you work through a specific cycle while talking to native speakers of your target language. Each FORCE cycle should bring you closer to your long-term objectives in your target language. FORCE stands for Focus, Organise, Rehearse, Communicate, Evaluate.
The first phase, focus, is about things that you will need soon and often. These things should be part of your life and that you would also talk about in your native language, e.g. your family, your language learning, your work, your home country, your native language. There are two types of focus: a topic or theme to talk about, and a skill (e.g. how to order coffee, how to receive or accept an invitation). The focus should be specific; you should to yourself something like, “I am going to learn how to buy a hard drive for my computer in Spanish.” By limiting the focus, you make the preparation of the conversation more manageable.
The second phase, organise, is about collecting vocabulary, phrases and language patterns that you will use to talk about the topic that you selected from your focus. Memorising the vocabulary and grammar patterns is not sufficient to become bilingual, you also need to use them. You can collect the vocabulary and phrases from all kinds of sources: textbooks, phrase books, advertisements, Wikipedia articles, conversations you overhear, films, etcetera. Swayne recommends writing these things down by hand instead of using a smart phone or a computer. When you ask native speakers how do say certain things, you need to be careful about how you phrase your question. Don't ask for translations of sentences in your native languages, but ask questions like, “Tell me how you would shop for a smart phone in Spanish.” This will give much more authentic input. (A good dictionary will also provide sample phrases that you can use.) The amount of material you organise depends on the level of proficiency you have: at the beginner level, you should limit the materials to a single page; you can increase this as your proficiency increases.
The third phase, rehearse, is about rehearsing the materials you collected during the “organise” phase until you know that you can use them in conversation. You should not take on too much; the goal is to say much but to say it well. Make sure that you can pronounce the words and phrases well. You should say them out loud. Swayne recommends learning the International Phonetic Alphabet, which is used in many dictionaries. He also recommends Forvo, a site where you can find the pronunciation of words in many languages. If you have recordings, learn to imitate them as closely as you can. If you are confronted with long words or phrases, it is more efficient to start with the last syllable (or word) and gradually add the parts in front of it; this is more efficient than moving from the first syllable (or word) to the last.
The fourth phase, communicate, is about the actual conversations. Conversations are the most natural way of learning languages. Using a foreign language by communicating with people who know the language better than you will ensure steady progress. The goal of the conversation is not to dominate it but to keep it going so you get a lot of input in your target language. You should also be prepared for comments about how well (or badly) you speak the language. You need to be prepared for this, for example, by learning the culturally appropriate way to respond to compliments. (For example, in Chinese and Japanese, you are supposed to be humble or modest about your skills.) The conversations need not be too long, to avoid that you get tired or lose track. Swayne recommends 15 minutes or less at the beginning, and that you gradually build up to longer conversations later on. You will also need to get good at circumlocution and : if you don't know a certain word, try to describe the concept instead of relying on translations. Sometimes you will have to guess the meaning of words or phrases based on context, body language and other clues. It is also useful to learn to say, “I don't know yet how to say that in your language.”
In the last phase, evaluate, you take notes on a few specific questions. Swayne recommends that you do this using pen and paper instead of in your head. The questions are the following (quoted or paraphrased from the last video in the series):
Was your focus specific enough or broad enough? How could it have been better?
Was your speaking partner appropriate and was the location of the conversation suitable?
Was the conversation too long or too short? If you felt exhausted afterwards, it was too long.
Were the words and phrases you prepared for your cycle appropriate and sufficient?
Are there any learning resources that would help you prepare your organisation phase much better? (For example, books with vocabulary organised by theme.)
Were you understood completely, partly or just a little bit? What were the difficulties (on either side)? Did you rehearse enough? Did you anticipate the responses of the other person?
Did you understand what was said to you? How much did you understand? Did you have to guess a lot? Was your vocabulary adequate?
Were you confused by unfamiliar language patterns?
Did you have difficulty understanding words or sounds?
Was your FORCE cycle suitable for your proficiency level?
Did you exchange real information without using your native language (or another language that you know better)?
Did you handle misunderstandings effectively? (Strategies include clarification, repetition, confirmation, paraphrasing and guessing. You should use these strategies before falling back to your native language or another bridge language.)
Could your speaking partner offer any helpful feedback on how to communicate better?
Can you fix your earlier mistakes in your next cycle?
Were you courteous, friendly and culturally appropriate in your conversation? (For example, many languages have formal and informal forms of address, and these need to be used appropriately.)
Did you notice any new words, phrases or language patterns that you need to master? If yes, write them down so you can add them to a future cycle. (This is why the evaluation phase needs to be done immediately after the communication phase.)
What would have been helpful to you that you didn't know when you went into the communication phase?
What should be the focus of the next cycle? (This should be something that interests you.)
Did you learn anything new about the target language culture?
Evaluate your pronunciation, especially in the first six months of your study. Ask people to comment on your pronunciation. For example, ask whether your pronunciation is difficult to understand, fairly easy to understand most of the time, not a problem, or very good. If people talk to you without pausing or adjusting your language to you, that is probably a good sign.
Evaluate the level of understanding in both directions. Write down your successes, not just your mistakes.
| {
"pile_set_name": "StackExchange"
} |
Q:
Filter the strings which startswith (one or two) slashes in PowerShell
I'm trying to find out the strings which starts with one slash(/) and two slashes(//). For example, following is the array which have few strings:
Following is the code I'm trying:
$array = @("/website","//windows_service","/console_app","//windows","///IIS","test")
$arraysplit = $array.split(',');
Foreach ($string in $arraysplit)
{
if ($string.StartsWith("/"))
{
Write-Host "$string has one slash."
}
elseif($string.StartsWith("//"))
{
Write-Host "$string has two slashes."
}
else
{
#I want to exit only when below conditions meet
#1. if string doesnot have any slash or
#2. if string has more than two slashes
Write-Host "$string has more number of slashes or it doesnot have any slash. Exiting"
Exit -1
}
}
I dont want to write more if conditions to filter the things, but this is not working as expected. I think i should change the logic to achieve the requirement. Can someone please suggest me (I'm looking for dynamic method)
A:
I would write an if-test that matches any lines that doesn't start with one or two slashes using regex. Try:
$array = @("/website","//windows_service","/console_app","//windows","///IIS","test")
Foreach ($string in $array)
{
if ($string -notmatch '^\/{1,2}[^\/]')
{
Write-Host "$string has more number of slashes or it doesnot have any slash. Exiting"
Exit -1
}
}
A:
if ($string -match '^/*') { write-host $matches[0].length slashes }
is the answer posted by @wOxxOm. Thanks.
| {
"pile_set_name": "StackExchange"
} |
Q:
LightOpenID - how to retrieve e-mail from stored session?
I am storing $lightopenid->identity in a codeigniter session as follows:
$lightopenid = new Lightopenid;
$lightopenid->required = array('contact/email');
if ($lightopenid->validate()) {
$google_open_id = $lightopenid->identity;
$this->session->set_userdata('google_open_id', $google_open_id);
}
In a separate function in my controller I would like to retrieve the user's email.
print_r($this->session->userdata('google_open_id'));
will show me the identity link but how do I retrieve the email from it?
Do I need a new instance of lightopenid?
Any suggestions?
A:
You have to store the email in the session. LightOpenID doesn't store anything. You'd have to redo the whole authentication in order to retrieve the email address only from the identity.
So, something like that:
if($openid->validate()) {
$attributes = $openid->getAttributes();
$this->session->set_userdata('open_id', $openid->identity);
$this->session->set_userdata('email', $attributes['email']);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Why do these two linq queries return different numbers of results?
In a web application that I work with I found a slow piece of code that I wanted to speed up a bit. Original code below:
foreach (Guid g in SecondaryCustomersIds)
{
var Customer = (from d in Db.CustomerRelationships
join c in Db.Customers on
d.PrimaryCustomerId equals c.CustomerId
where c.IsPrimary == true && d.SecondaryCustomerId == g
select c).Distinct().SingleOrDefault();
//Add this customer to a List<>
}
I thought it might be faster to load this all into a single query, so I attempted to rewrite it as the query below:
var Customers = (from d in Db.CustomerRelationships
join c in Db.Customers on
d.PrimaryCustomerId equals c.CustomerId
where c.IsPrimary == true && SecondaryCustomersIds.Contains(d.SecondaryCustomerId)
select c).Distinct();
Which is indeed faster, but now the new query returns fewer records than the first. It seems to me that these two chunks of code are doing the same thing and should return the same number of records. Can anyone see why they would not? What am I missing here?
A:
It's possible for the first query to add a null object to the list (SingleOrDefault will return the default for the type, or null in this case, if it can't find a matching entity). Thus, for every Customer without a matching relationship, you could be adding a null object to that List<>, which would increase the count.
| {
"pile_set_name": "StackExchange"
} |
Q:
C# - Safe a Base64 as Gif, when the webRequest sends XML?
I sended a WebRequest, and got as Response a String with XML Code within my content.
WebRequest request = WebRequest.Create("...");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
byte[] bytes = Convert.FromBase64String(responseFromServer);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
image.Save("File", System.Drawing.Imaging.ImageFormat.Gif);
The Problem is that "Convert.FromBase64String(responseFromServer)" cant convert to base 64, because the response is:
"<string xmlns="*LINK*"> 'content' </string>"
Can I remove these Tags, or copy out the content?
I hope you got my problem:) Thanks for help and sorry for the bad english x)
A:
I'd recommend using XmlReader for this.
WebRequest request = WebRequest.Create("...");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
//StreamReader reader = new StreamReader(dataStream);
//string responseFromServer = reader.ReadToEnd();
//byte[] bytes = Convert.FromBase64String(responseFromServer);
using (var reader = XmlReader.Create(dataStream))
{
reader.Read();
reader.Read();
string base64 = reader.Value;
byte[] bytes = Convert.FromBase64String(base64);
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
image.Save("File", System.Drawing.Imaging.ImageFormat.Gif);
}
}
There is a method for converting from Base64 in the element value directly, but you'd need to know things that more or less require you to read your whole stream anyway to do that (you can look at the edit history to see me working through that ;).
| {
"pile_set_name": "StackExchange"
} |
Q:
Send mail to user about information
Is there any libary which can be implemented in C# Console App to send mail to user about some information. In my case, this will be send mail to user or admin whenever new has been added to ActiveDirectory domain ?
A:
add this to your console main function and it will do the work
class Program
{
static void Main(string[] args)
{
// make sure allow less secure apps on gmail https://myaccount.google.com/lesssecureapps
SmtpClient mySmtpClient = new SmtpClient("smtp.gmail.com");
// set smtp-client properties
mySmtpClient.UseDefaultCredentials = false;
System.Net.NetworkCredential basicAuthenticationInfo = new
System.Net.NetworkCredential("[email protected]", "YourGmailPassword");
mySmtpClient.Credentials = basicAuthenticationInfo;
mySmtpClient.EnableSsl = true;
mySmtpClient.Port = 587;
// add from,to mailaddresses
MailAddress from = new MailAddress("[email protected]", "IAMSender");
MailAddress to = new MailAddress("[email protected]", "IAMReceiver");
MailMessage myMail = new System.Net.Mail.MailMessage(from, to);
// set subject and encoding
myMail.Subject = "Test message";
myMail.SubjectEncoding = System.Text.Encoding.UTF8;
// set body-message and encoding
myMail.Body = "<b>Test Mail</b><br>using <b>HTML</b>.";
myMail.BodyEncoding = System.Text.Encoding.UTF8;
// text or html
myMail.IsBodyHtml = true;
mySmtpClient.Send(myMail);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Escape invalid XML characters in C#
I have a string that contains invalid XML characters. How can I escape (or remove) invalid XML characters before I parse the string?
A:
As the way to remove invalid XML characters I suggest you to use XmlConvert.IsXmlChar method. It was added since .NET Framework 4 and is presented in Silverlight too. Here is the small sample:
void Main() {
string content = "\v\f\0";
Console.WriteLine(IsValidXmlString(content)); // False
content = RemoveInvalidXmlChars(content);
Console.WriteLine(IsValidXmlString(content)); // True
}
static string RemoveInvalidXmlChars(string text) {
var validXmlChars = text.Where(ch => XmlConvert.IsXmlChar(ch)).ToArray();
return new string(validXmlChars);
}
static bool IsValidXmlString(string text) {
try {
XmlConvert.VerifyXmlChars(text);
return true;
} catch {
return false;
}
}
And as the way to escape invalid XML characters I suggest you to use XmlConvert.EncodeName method. Here is the small sample:
void Main() {
const string content = "\v\f\0";
Console.WriteLine(IsValidXmlString(content)); // False
string encoded = XmlConvert.EncodeName(content);
Console.WriteLine(IsValidXmlString(encoded)); // True
string decoded = XmlConvert.DecodeName(encoded);
Console.WriteLine(content == decoded); // True
}
static bool IsValidXmlString(string text) {
try {
XmlConvert.VerifyXmlChars(text);
return true;
} catch {
return false;
}
}
Update:
It should be mentioned that the encoding operation produces a string with a length which is greater or equal than a length of a source string. It might be important when you store a encoded string in a database in a string column with length limitation and validate source string length in your app to fit data column limitation.
A:
Use SecurityElement.Escape
using System;
using System.Security;
class Sample {
static void Main() {
string text = "Escape characters : < > & \" \'";
string xmlText = SecurityElement.Escape(text);
//output:
//Escape characters : < > & " '
Console.WriteLine(xmlText);
}
}
A:
If you are writing xml, just use the classes provided by the framework to create the xml. You won't have to bother with escaping or anything.
Console.Write(new XElement("Data", "< > &"));
Will output
<Data>< > &</Data>
If you need to read an XML file that is malformed, do not use regular expression. Instead, use the Html Agility Pack.
| {
"pile_set_name": "StackExchange"
} |
Q:
earning by getting involved in Springsource projects
Can one make any earning by getting involved in Springsource projects(by contributing code, submitting pull requests, testing features etc.)
A:
You can if you are a VMWare employee.
You probably can (indirectly) if you are a normal guy. Being an opensource contributor is something good employers are looking for and may help you get a better job / salary.
| {
"pile_set_name": "StackExchange"
} |
Q:
Complex Relation in Mongoose
I have a restaurant idea, that will have branches and every branch has a menu, and every menu has items with there specified price for this branch!
and my schema is:
var mongoose = require('mongoose');
var eaterySchema = mongoose.Schema({
name: String,
type: Number,
branches: [{type: Schema.Types.ObjectId, ref: 'Branch' }]
});
var branchSchema = mongoose.Schema({
id: Number,
name: String,
eatery: {type: Schema.Types.ObjectId, ref: 'Eatery'},
menu: {type: Schema.Types.ObjectId, ref: 'Menu'}
});
var menuSchema = mongoose.Schema({
branch: {type: Schema.Types.ObjectId, ref: 'Branch'},
items: [{type: Schema.Types.ObjectId, ref: 'Item'}]
});
var itemSchema = mongoose.Schema({
name: String,
description: String
});
var itemMenuSchema = mongoose.Schema({ //Many-To-Many Table
menu: {type: Schema.Types.ObjectId, ref: 'Menu'},
item: {type: Schema.Types.ObjectId, ref: 'Item'},
price: Number
});
var Eatery = mongoose.model('Eatery', eaterySchema);
var Branch = mongoose.model('Branch', branchSchema);
var Menu = mongoose.model('Menu', menuSchema);
var Item = mongoose.model('Item', itemSchema);
var ItemMenu = mongoose.model('ItemMenu', itemMenuSchema);
Does the query below written right to get the menu with the items and the item price for requested branch id ?
Branch
.findOne({id: '@GivenId'})
.populate('eatery menu')
.exec(function(err, doc){
doc
.populate('menu.items')
.exec(function(err, doc){
ItemMenu
.find({})
.where('menu._id').equals(doc.menu._id)
.exec(function(err, items){
doc.push(items);
res.send(docs);
})
})
};)
});
and does mongoose provides populate to deal with the last query that I have written in the last callback? and what the better solution to deal with this complex relation?
thanks a lot
A:
This schema is a bit too relational, and that query will be much slower than it needs to be. To get the most out of MongoDB, I'd recommend getting rid of ItemMenu entirely: since each menu has a list of items, its redundant, you can just store the corresponding price in Menu's list of items.
Furthermore, you may consider inlining items into each menu, and/or inlining menu into the branch document. This will make your query much simpler and much faster.
Generally, when designing a MongoDB schema, you want to structure your objects so its easy to answer your most common questions. This often means inlining one-to-one or one-to-few relationships. Don't get stuck in a relational mindset - trying to structure MongoDB documents like you would SQL rows is a surefire way to make your life more difficult than it has to be :)
| {
"pile_set_name": "StackExchange"
} |
Q:
Oracle 00932. 00000 - "inconsistent datatypes: expected %s got %s"
well i'm still new in oracle, i'm trying to query a table with a subquery..it looks like this
select id_user, count(*) as jumlah from (select * from users where username = 'usr' and pass = 'pwd' and company_id = 'PAN' and status = 1)
group by id_user;
the above code works. but when i try to put it inside a stored procedure i got some errors like this
here's the stored procedure
create type login_obj is object(jumlah integer);
create type login_table is table of login_obj;
create or replace function startLogin(u varchar, p varchar, cid varchar)
return login_table
is
tabel login_table := login_table();
the_count integer;
the_sql varchar(200);
begin
the_sql := 'select id_user, count(*) as jumlah from (select * from users where username = ''' || u || ''' and pass = ''' || p || ''' and company_id = ''' || cid || ''' and status = 1) GROUP BY id_user';
execute immediate the_sql into the_count;
if the_count IS NOT NULL
then
begin
tabel.extend;
tabel(1) := login_obj(the_count);
end;
end if;
return tabel;
end;
then executing it by
select * from table (startLogin('usr','pwd','PAN'));
and here are the errors
SQL Error: ORA-00932: inconsistent datatypes: expected - got -
ORA-06512: at "LUKI.STARTLOGIN", line 14
00932. 00000 - "inconsistent datatypes: expected %s got %s"
any idea?
A:
Add one more variable below the line
the_sql varchar(200);
as
yid_user users.id_user%TYPE;
and change your execute immediate as
execute immediate the_sql into yid_user, the_count;
Also some tips for using variable types in Oracle:
1. VARCHAR is obsolete, use VARCHAR2 instead.
2. Instead of using INTEGER type, use NUMBER.
| {
"pile_set_name": "StackExchange"
} |
Q:
VBA - Get website content created dynamically
I'm trying to write a macro which is getting on a particular website, pasting some input, clicking search button and then copying data from search results.
Unfortunatelly, as far as I understand, search results are prepared dynamically (in JavaScript?) and I don't know how to use any method such as getElementById if I don't know the id.
Here's the website: https://www.tracktrace.dsv.com/newtracking/login.jsp
Here's searched in left searchbar content: DSVAO72630
And I'm trying to catch anything that's shows up in results, eg. shipment id (on the very top of search results there's SHPTS ID: SMMA0019991). Here's my code so far:
Option Explicit
Sub Crawler()
Dim IE As InternetExplorerMedium
Dim URL As String
Dim HTMLDoc As HTMLDocument
Dim searchButton As Object
Dim searchBar As Object
Application.ScreenUpdating = True
Set IE = CreateObject("InternetExplorer.Application")
URL = "https://www.tracktrace.dsv.com/newtracking/login.jsp"
With IE
.Navigate URL
.Visible = True
End With
Do
DoEvents
Loop Until IE.readyState = READYSTATE_COMPLETE
Set HTMLDoc = IE.document
Set searchBar = HTMLDoc.getElementById("sid")
searchBar.Value = "DSVAO72630"
Set searchButton = HTMLDoc.getElementsByName("SEARCH")
searchButton.Item(0).Click
End Sub
A:
Here is one way...
Option Explicit
Sub Crawler()
Dim IE As Object, HTMLDoc As Object, searchButton As Object
Dim searchBar As Object, tbl As Object
Dim URL As String
Dim Ar As Variant
Dim i As Long
Set IE = CreateObject("InternetExplorer.Application")
URL = "https://www.tracktrace.dsv.com/newtracking/login.jsp"
With IE
.Navigate URL
.Visible = True
End With
Do: DoEvents: Loop Until IE.readyState = 4
Set HTMLDoc = IE.document
Set searchBar = HTMLDoc.getElementById("sid")
searchBar.Value = "DSVAO72630"
Set searchButton = HTMLDoc.getElementsByName("SEARCH")
searchButton.Item(0).Click
Wait 2
Set tbl = HTMLDoc.getElementsByTagName("TABLE")(2)
Ar = Split(tbl.Cells(1, 2).outertext, vbNewLine)
For i = LBound(Ar) To UBound(Ar)
If InStr(1, Ar(i), "SHPTS ID:") Then
Debug.Print Trim(Split(Ar(i), ":")(1))
Exit For
End If
Next i
IE.Quit
Set IE = Nothing
End Sub
Private Sub Wait(ByVal nSec As Long)
nSec = nSec + Timer
While nSec > Timer
DoEvents
Wend
End Sub
Screenshot
| {
"pile_set_name": "StackExchange"
} |
Q:
MySQL Grouping Issue
I would like to show data group by Continent.
I have the following table:
Table: Score
RegionID | RegionName | Continent | Score
----------+-------------+------------+-------
A001 | Hong Kong | Asia | 97
A002 | Macau | Asia | 94
A003 | Taiwan | Asia | 95
A004 | Seoul | Asia | 96
A005 | Tokyo | Asia | 95
A006 | Osaka | Asia | 93
E001 | London | Europe | 88
A007 | Beijing | Asia | 83
E002 | Paris | Europe | 89
U001 | New York | N. America | 91
U002 | Las Vegas | N. America | 90
T001 | Sydney | Australia | 98
Expected Output:
Asia:
-----------------------------------------
97 - Hong Kong
94 - Macau
...
N. America
-----------------------------------------
91 - New York
90 - Las Vegas
Now I have to separate the SQL command to output this.
I need a faster solution than
SELECT * FROM Score WHERE Continent='Asia'
SELECT * FROM Score WHERE Continent='N. America'
A:
That's not GROUPED data from database. That's simply a sorted list and then you use your programming language (PHP) to show the grouping.
SELECT * FROM Score ORDER BY Continent
Now when you get that result you have to use PHP to show each new continent in a new line and then show its entries. Since you need all the rows, doing that grouping with database only will be an overkill. And you have to create your continent headers in PHP anyway.
A:
If you select everything in one query:
SELECT * FROM Score WHERE Continent IN ('Asia', 'N. America');
Then, in PHP, you would do as notulyssess suggested and with the result set do:
$data[$row['continent']][] = $row;
Finnally, you would loop through your $data array as such:
for($data as $continent => $entries){
echo '<b>' . $continent . '</b><br />-----------------------------------------<br />';
for($entries as $e){
echo $e['score'] . ' - ' . $e['region_name'] . '<br>';
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Ulimit settings in Oracle 11g on Linux 5
Is there an issue with "Ulimit -Hn" being set too low (at 1024) when (Oracle recommend 65536)? This is for Oracle 64-bit 11g on Linux 5.
It is one of the settings that appears to be woefully short of its recommendation. But I am also aware that the database server in question is an Oracle Data Guard Local Standby and should only really have a connection or two from its Primary database server (to ship the redo logs across).
The Local Standby database server has 'hung' about 3 times in as many months and then requires a reboot. I do not have access to this server, so rely on others to look at logs etc. The sanity check on kernel params uncovered the low value for "ulimit -Hn".
Has anyone ever seen that 'low' value cause a hang or crash?
A:
Linux 5 does not exists. You are using linux 2 or linux 3. Or maybe are you talking about rhel5?
Back to problem : Never seen any kernel crash due to ulimit -Hn output being too low. Merely some softwares won't work correctly or even won't start. IMHO you should raise it but it's not likely to be the root cause of your problem.
Most relational database engines (at least oracle mysql and postgresql) open a lot of files.
| {
"pile_set_name": "StackExchange"
} |
Q:
Creating an Authentication Header in ExpressJS . Translation of Java to Javascript
for the authentication of my Node Server (Express JS) with another API a separate header must be sent within the POST request.
Quote from the documentation:
You need to send a X-Authorization-Ahoi header with this request. The
header value is an encoded JSON string that consists of the
<INSTALLATION_ID>, a random 16-character string as nonce and the
current date in ISO 8601 format.
Example from the documentation:
{
"installationId":"<INSTALLATION_ID>",
"nonce":"0wYWLarLDBrWU7B2I1Go4A==",
"timestamp":"2018-11-01T11:32:44.413Z"
}
In the documentation of the API the following Java example is given which I try to reproduce in Javascript.
String installationId = <INSTALLATION_ID>;
// create nonce
byte[] nonce = new byte[16];
SecureRandom.getInstanceStrong().nextBytes(nonce);
String nonceBase64Enc = Base64.getEncoder().encodeToString(nonce);
// create timestamp
String timeStr = Instant.now().toString();
// create json string
String xAuthAhoiJson = String.format("{\"installationId\":\"%s\",\"nonce\":\"%s\",\"timestamp\":\"%s\"}",
installationId, nonceBase64Enc, timeStr);
// encode encrypted header value
String XAUTH_AHOI_BASE64_URL_ENC = Base64.getUrlEncoder().withoutPadding()
.encodeToString(xAuthAhoiJson.getBytes( StandardCharsets.UTF_8 ));
Here's what I've been trying to do:
const installationId = '<EXAMPLE_INSTALLATIONID>';
const nonce_tmp = crypto.randomBytes(16);
const nonce = nonce_tmp.toString('base64');
const date = new Date();
const timestamp = date.toISOString();
const xAuthAhoiJson = JSON.stringify({installationId, nonce, timestamp});
const XAUTH_AHOI_BASE64_URL_ENC = base64url.encode(xAuthAhoiJson);
const url = 'https://banking-sandbox.starfinanz.de/auth/v1/oauth/token?grant_type=client_credentials';
const options = { headers:
{ 'Authorization': 'Basic ' + Buffer.from(credentials).toString('base64'),
'X-Authorization-Ahoi': XAUTH_AHOI_BASE64_URL_ENC }
};
request.post(url, options, function (e, r, b) { console.log(b); });
For the POST request I use the request-package.
For the encoding in Base64 URL Safe I use the base64url-package.
When executing the POST request I get the following message:
{
"timestamp": 1543229480764,
"status": 400,
"error": "Bad Request",
"message": "Nonce is invalid.",
"path": "/auth/v1/oauth/token"
}
Now my question is: What is wrong with creating my Nonce and how do I fix it?
Or is it the API I'm sending the POST request to?
A:
You just forgot to convert the nonceBase64Enc to string. You have done that in java but not in javascript.
Just add the .toString('hex'); at the end of nonceBase64Enc
Example : const nonceBase64Enc = Buffer.from(nonce, 'base64').toString('hex');
You are done now!
| {
"pile_set_name": "StackExchange"
} |
Q:
Capture Filter with Wildcard in IP Address
I am trying to customize Wireshark capture such that is captures all IP addresses (both source and destination) with the IP address format xxx.xxx.xxx.100.
I used the following Capture Filter
ip matches /.*/.*/.*/.100
but the text box remains red'
These are not IP addresses in a particular range, just the fourth octet is 100
A:
Your regex is a little off, as you need to use a backslash to escape the periods. Try this:
ip.host matches "\.100$"
That should match .100 at the end of the string.
Source: http://ask.wireshark.org/questions/22230/filter-for-partial-ip-address
Edit: Try using the Display Filter (Analyze->Display Filters..), not the Capture Filter
| {
"pile_set_name": "StackExchange"
} |
Q:
Async AjaxCall in a for loop Javascript
How can I make each iteration a new Ajaxcall that needs to be async.
without using
async: false,
If I do this with the async I get a warning message, and my UI Freezes, how can I fix this? This is not a normal for loop
EDIT1
var username = "username1";
var password = "test";
var code = "";
for(var i = 0; i < results.lenght;i++){
$.ajax({
data: {username:username, password: password},
url: './php/'+results[i].NAME+'.php',
method: 'POST',
datatype: 'json',
success: function(msg) {
//all the msg info needs to be filled in in the html. via the var "code"
}
});
}
return code;
A:
You can do something along these lines (haven't tested the code):
function doIteration(done, i){
if(i <= 0){ done(); return; }
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200){
// Process response...
console.log(xmlHttp.responseText);
// Do next iteration.
doIteration(done, --i);
} else {
doIteration(done, 0);
}
}
};
xmlHttp.open("method", "script.php");
xmlHttp.send(null);
}
doIteration(function(){
alert("Done loop!");
}, 10);
EDIT: Didn't realize you were using jQuery, just replace the xmlHttp requests with $.ajax and leave async enabled.
| {
"pile_set_name": "StackExchange"
} |
Q:
Caratheodory equations
Ok, I am reading Fillipov book on discontinuous right hand side differential equations (the red book).
He states the next lemma:
"
Let the function $f(t,x)$ satisfy the Caratheodory conditions and let the function $x(t)$ for $a\leq t \leq b$ be measurable.
Then the composite function $f(x(t),t)$ is summable."
Where Caratheordory codntions are:
In the domain $D$ of the $(t,x)-space$, let:
the function $f(x,t)$ be defined and continuous in $x$ for all most all t;
$f(x,t)$ be measurable in $t$ for each $x$;
$|f(x,t)|\leq m(t) $, the function $m(t)$ being summable (on each finite interval if $t$ is not bounded in $D$).
Now the book provides the next reference which seems to be not in English.
Sansone , G., Equazioni Differenziali nel campo Reale. Parte 2.
Even though I can guess what the title says (differential equations... real ... part 2 ) :-)
Anyone has an English reference of the very exact theorem?
Thanks in advance.
A:
You can find that in §10, XVIII of Walter,W.: Ordinary Differential Equations, volume 182 of Graduate Texts in Mathematics. Springer,
New York, 1998. Translated from the sixth German (1996) edition by Russell Thompson, Readings in Mathematics.
| {
"pile_set_name": "StackExchange"
} |
Q:
Are there distribution properties which are "maximally" hard to test?
A distribution testing algorithm for a distribution property P (which is just some subset of all distributions over [n]) is allowed access to samples according to some distribution D, and is required to decide (w.h.p) if $D\in P$ or $d(D,P)>\epsilon$ ($d$ here is usually the $\ell_1$ distance). The most common measure of complexity is the number of samples used by the algorithm.
Now, in standard property testing, where you have query access to some object, a linear lower bound on query complexity is obviously the strongest lower bound possible, since $n$ queries would reveal the entire object. Is this the case for distribution testing as well?
As far as I understand, the "trivial" upper bound for testing properties of distributions is $O(n^2\log n)$ --- by Chernoff bounds, this is enough to "write down" a distribution D' which is close to D in $\ell_1$ distance, and then we can just check if there are any distributions close to D' which are in P (this might take infinite time, but this is irrelevant to sample complexity).
Is there a better "trivial" test for all distribution properties?
Are there any distribution properties for which we know sample lower bounds stronger than linear?
A:
Sorry for unearthing this post -- it is quite old, but I figured having it answered may not be that bad an idea.
First, it looks like you performed your Chernoff bound with some slightly odd setting of parameters. Note that to perform your suggested "testing by learning" approach, it is sufficient to learn the distribution in total variation distance (or $\ell_1$, if you prefer, which is the same up to a factor 2) to distance $\frac{\varepsilon}{2}$. (before checking "offline" if there is any distribution $p'$ having the property $\mathcal{P}_n$ which itself is at distance at most $\frac{\varepsilon}{2}$ from your learnt hypothesis $\hat{p}$). This would naively lead to an $O\big(\frac{n\log n}{\varepsilon^2}\big)$ sample complexity upper bound for this approach; however, it is known (and "folklore") that learning an arbitrary distribution over a domain of size $n$ up to distance $\varepsilon$ (in total variation distance) can be done with only $O(\frac{n}{\varepsilon^2})$ samples (and this is tight).
So the baseline should actually be $O(\frac{n}{\varepsilon^2})$, which is already linear in $n$. Now, one can ask the next question -- are there "natural" properties for which testing (say, for constant $\varepsilon$) requires a linear dependence in the domain size $n$?
The answer is (as far as I know) "not quite, but close." Namely, following a significant line of work on estimating properties of distributions (or equivalently, tolerant property testing), the results of Valiant and Valiant imply (STOCS'11, FOCS'11, and some others) that the rather contrived property "being $1/10$-close to uniform" has sample complexity $\Theta_\varepsilon(\frac{n}{\log n})$.
(Note that it's a bit "cheating," in the sense that the property is simply a way to take a tolerant testing question and relabel it as testing of an ad hoc property).
If that is not entirely sufficient to quench your thirst, one can also show that for the (natural?) property of "being a $k$-histogram" (is the distribution piecewise constant on a set of $k$ unknown intervals?), setting $k=n/10$ for instance also results in an $\Omega(\frac{n}{\log n})$ lower bound (it's in a paper of mine from 2016; the lower bound follows from a rather simple reduction to the Valiants' result). Now, whether you consider "being an $\frac{n}{100}$-histogram" to be a natural property is up to you.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why can't we override function pointers in C++?
I want to create a member callback variable than can take multiple arguments:
class Polygon : public Shape {
protected:
void (*onClick)( Polygon * );
void (*onClick)( Point * );
void (*onClick)();
...
}
Of course this code throws an error. Is there any particular reason why I can't or shouldn't do this? And are there alternatives? I don't want three different names for the same behavior.
A:
Tl;dr: Because the standard doesn't allow you to do it.
Different behaviour using "the same name" is only possible with function overloads (or with templates to some extent) as function pointers do not overload.
You'd have to resort to overloading in order to maintain the same name for onClick:
#include <functional>
class Polygon : public Shape {
private:
std::function<void(Polygon*)> _poly_f;
std::function<void(Point*)> _point_f;
std::function<void()> _empty_f;
protected:
void onClick(Polygon* p) { _poly_f(p); }
void onClick(Point* p) { _point_f(p); }
void onClick() { _empty_f(); }
...
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Get Data from WebSocket using VB.Net ClientWebSocket
I wish to see a minimal example in VB.NET and without using any external libraries of a websocket client connection.
Like sending Hello to wss //echo.websocket.org and printing the result.
note: the suggested possible duplicate has wrong answers.
1) it uses a library (first answer).
2) The second answer instead confused sockets with websockets.
A:
Was it so difficult?
Dim ws = New System.Net.WebSockets.ClientWebSocket
' optional: ignore certificate errors
ServicePointManager.ServerCertificateValidationCallback = Function(s, c, h, d) True
Try
Await ws.ConnectAsync(New Uri("wss://demos.kaazing.com/echo"), Nothing)
If (ws.State = WebSockets.WebSocketState.Open) Then
Debug.Print("Opened.")
Await ws.SendAsync(New ArraySegment(Of Byte)(System.Text.Encoding.UTF8.GetBytes("{ ""message"":""hello""}")), WebSockets.WebSocketMessageType.Text, True, Nothing)
Dim bytes(4096) As Byte
Dim answ = New ArraySegment(Of Byte)(bytes)
Await ws.ReceiveAsync(answ, Nothing)
Debug.Print("answer:" + System.Text.Encoding.UTF8.GetString(answ.Array))
Else
Debug.Print("Not opened?!")
End If
Catch
Debug.Print("Error.")
End Try
| {
"pile_set_name": "StackExchange"
} |
Q:
Jquery slidedown menu issues
I am trying to animate my wordpress sub-menu with Jquery.
Here's what I am trying to mimic: http://money.co.uk
Here's what I have so far:
$("#main-nav li").hover(function () {
$(this).children('.sub-menu').slideToggle("fast");
});
http://jsfiddle.net/bNeDh/
It seems to be the reverse of what I want, I'd like the children to slide down when user mouseover the parent.
My jquery isn't great at all, can anyone provide the answer?
A:
I have modified your CSS a bit... If you find this (or any) answer useful Accept it by clicking checkmark.
You probably want something like this:
Fiddle Here
$("#main-nav li").hover(function () {
$(this).children('.sub-menu').slideDown("fast");
},function(){
$(this).children('.sub-menu').slideUp('fast');
});
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find a Control without knowing the parent control, narrowed by instance (.Net 1.1)
I'm tasked with making a change to an old .Net 1.1 app that cannot be upgraded at this time. The app is horribly designed, with calls all over the place, repeated functions, unused code that isn't even commented out, and multiple iterations of the same usercontrol without notation as to which one is actually being used. The usercontrols which are used are mixed with controls that aren't user controls at all, but just as complex, when implemented in a central Form.
The central Form called MainForm has a TabControl which itself holds a WorkFormin each page. These are generated dynamically from user input. The WorkForm is a user control and contains the hodgepodge of user controls and contained/uncontained controls, panels, etc. mentioned before. Parentage can be dynamic between a form and a control based entirely on data being loaded, which adds to the complexity of the problem.
An instance of a user control which is a part of the WorkForm user control on its 4th tab has a datagrid, and what I need to do is modify the code that adds a new row in that datagrid to check a control outside of the user control, but in the same WorkForm, and get its SelectedValue. I essentially need to "Where's Waldo" the control I need, but with enough "Carmen Sandiego" to adapt to the fact that the control hierarchy is not guaranteed. Also, the law of Demeter on this one is more like "Law of Demeter? I don't even know her Dename!" so really kludgy calls to static variables that shouldn't be is pretty much how the app runs.
Something like:
Dim row as DataRow = aDataTable.NewRow()
row[12] = Me.Parent.Cousin.TwiceRemoved.OnFathersSide.NotThatOne _
.TheOtherOne.SelectedValue
What would be the best way to go about hunting down this control, since the relation isn't guaranteed? P.S. I didn't write the app. I'm just stuck with instructions to add a change to this nightmare.
A:
This entirely depends on what you know about the control.
If it has a name (or and other kind of unique criteria) you could do a recursive search over all containers like this:
public static Control WhereInTheFormIsWaldoSandiego(Container c, String name)
{
foreach (Control ctrl in c.Controls)
{
if (ctrl.Name.Equals(name)) return ctrl;
if (ctrl is Container)
{
Control inner = WhereInTheFormIsWaldoSandiego(ctrl as Container, name);
if (inner != null) return ctrl;
}
return null;
}
}
Otherwise your best bet would probably to find the logic that places the control and modify it to store a reference to it somewhere.
The later is probably preferable since it gives you better knowledge about the application but might also take much longer.
| {
"pile_set_name": "StackExchange"
} |
Q:
Property inheritance in Javascript
I have the following functions which define an inheritance chain.
function Person(name,age) {
this.name = name;
this.age = age;
}
Person.prototype.dance = function () {
console.log("Person is dancing");
};
var Programmer = function (name, age, skills)
{
Programmer.prototype = new Person(name, age);;
this.skills = skills;
};
Programmer.prototype.talkShit = function () {
console.log("The programmer " + this.name+ " is talking shit....");
};
and I try to call dance() method on a programmer object
var programmerX = new Programmer("Pro A", 30, "Talking crap");
programmerX.dance();
However, an error happened saying that dance() is undefined. I'm just wondering why? What's wrong?
A:
You can extend your Object prototype with
Programmer.prototype = new Person();
Programmer.prototype.constructor = Programmer;
But obviously, an empty constructor will be called, so you will have to call this manually afterwards from within your Programmer object
Person.call(this, name, age);
Giving you
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.dance = function () {
console.log("Person is dancing");
};
function Programmer(name, age, skills)
{
Person.call(this, name, age);
this.skills = skills;
};
Programmer.prototype = new Person();
Programmer.prototype.constructor = Programmer;
Testing this with
var programmerX = new Programmer("Alice", 30, "Something");
var programmerY = new Programmer("Bob", 25, "Something else");
console.log(programmerX);
console.log(programmerY);
programmerX.dance();
We'll get
{ name: 'Alice', age: 30, skills: 'Something' }
{ name: 'Bob', age: 25, skills: 'Something else' }
Person is dancing
| {
"pile_set_name": "StackExchange"
} |
Q:
Throwing exception from constructor?
I have this NamePath class that accepts a string from some system path and tries to split it into two properties, Name and LastName.
Is the code example below fine? I've read that throwing exceptions in constructor is okay, but is there a better way for this case?
public class NamePath{
public string Name {get; private set; }
public string LastName { get; private set; }
public NamePath(string path){
Parse(path);
}
private void Parse(string path){
if ( ParsingOkay() ) {
// set the properties
} else {
throw new Exception
}
}
}
I've thought of another approach where NamePath is just data class, and I would have a static method on another class that would try to create NamePath object or else it would return null.
public class NamePath {
public string Name {get; private set; }
public string LastName { get; private set; }
public NamePath (string name, string lastName){
Name = name;
LastName = lastName;
}
}
public class PathHelper {
public static NamePath ParseNamePath (string path){
if ( ParsingOkay() ){
return new NamePath
} else {
return null
}
}
}
code example is semi-pseudo
A:
Let us assume the caller doesn't need more information than if the parsing failed or not (for whatever reason). Then functionally both of your examples are mostly equivalent. The question you need to ask here then is: how would you prefer to use the feature for constructing NamePath? Would you prefer to write
try
{
var namePath = new NamePath(path);
// some code using namePath
// ...
}
catch(SomeException ex)
{
// do some error handling here
}
Or would you prefer to write
var namePath = PathHelper.ParseNamePath(path);
if(namePath==null)
{
// some error handling here
}
// some code using namePath
If the error handling in the second case is always to throw an exception, then it should be clear that the first variant would make more sense and become more consise.
Note in both cases, if one forgets the error handling, in the first case the outer scope may get a more specific exception, in the second case the outer scope may get a "null reference exception".
Nevertheless, both variants can be used to write correctly working code, and they don't have a huge difference in maintainability and readability. Hence, it stays to be a judgement call.
A:
Throwing exceptions in constructors in C# is fine, but a constructor should always create a valid object. I prefer to keep construction devoid of parsing. Parsing is inherently tricky, because you cannot trust the source of the data. Exceptions should be expected when parsing anything. The .NET stack already has a pattern to deal with this: Parse and TryParse.
While a monad is more idiomatic across languages, the [Try]Parse pattern is a long standing idiom for C#.
The constructor always takes data in the necessary pieces, and throws ArgumentXExceptions in the case invalid arguments are passed. The parse methods can be static methods to handle the parsing either by creating a valid object or throwing a FormatException.
var path = new NamePath(name, lastName); // throws Argument*Exception
try
{
var path = NamePath.Parse("...");
// Use properly constructed path
}
catch (FormatException)
{
// Parse errors
}
if (NamePath.TryParse("...", out NamePath path))
{
// User properly constructed NamePath as path variable
}
else
{
// Parse errors
}
This gives code authors some options with how to construct, parse and recover from errors. You'll see this pattern reflected in the native .NET types DateTime, int, decimal, etc. Your custom NamePath type will feel more natural to deal with along side the built-in types:
if (int.TryParse("...", out int age))
{
// valid int
}
else
{
// invalid int
}
if (NamePath.TryParse("...", out NamePath path))
{
// valid NamePath
}
else
{
// invalid NamePath
}
A:
Words like "OK" or "better" are meaningless unless you can define what those terms mean for your specific software application. The way you do that is you ask: "why?"
OK. So why would you throw from a constructor?
In these situations, it can be useful to determine what your possible options are, and then evaluate each one.
You can throw, or
You can allow the constructor to return an incomplete object.
That's about it, if you want to use a constructor. If you can use something other than a constructor, like a factory method, you can return a more sophisticated object like a Maybe Monad. Maybe that's your "better" way.
But let's say you're not there yet. You just want to know whether or not to throw in a constructor.
The way you choose between those two options is to determine if there's more than one way for the constructor call to fail. Because if there's more than one way for it to fail, you're not going to know which way it failed if you don't throw. because that approach doesn't transmit any specific information about the failure, and you're left with an invalid object without knowing why it is invalid.
And this is why it's desirable to throw in a constructor. When you throw, you can communicate information about why the constructor call failed, and you prevent incomplete objects from being created.
Using a factory method to return null on construction failure does prevent incomplete objects from being created, but communicates no information about why the failure occurred.
I should probably mention that, if your constructor throws exceptions, you're going to have significant performance problems if you do something like parse a file in a tight loop using objects created via constructor calls. Exceptions are expensive, and your parsing operation will grind to a halt if the file you are parsing is not well-formed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a code snippet editor for Intellij Idea 13?
Visual Studio has Snippet Designer extension available for creating and managing custom code snippets. Is there something like this extension for Intellij Idea 13, or a way to simply add custom code snippets?
A:
There's no extension that I'm aware of (and I'm not familiar with Snippet Designer), but that functionality exists in IntelliJ Idea.
Hit Preferences and start typing to find "Live Templates". Expand one of the existing ones to see some of the available functionality. You can set tab stops, cursor position, references to local variables. It's very handy.
| {
"pile_set_name": "StackExchange"
} |
Q:
MongoDB driver for Erlang
I got mongodb version 2.4.3 installed on Ubuntu 13.04
and I installed mongodb-erlang to /usr/lib/erlang/lib/mongodb-master (by make)
but if I try to start it I got this error:
Erlang R16B (erts-5.10.1) [source-05f1189] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]
Eshell V5.10.1 (abort with ^G)
1> application:start(mongodb).
{error,{not_started,bson}}
A:
As indicated by the error message, the bson application is not started; the mongodb application requires it. Just run application:start(bson) first, and you should be good to go.
| {
"pile_set_name": "StackExchange"
} |
Q:
python: convert string to regular expression
I am using python to do some text comparison. The text format is like 44=100. Let's say, I have 2 text, 44=100 and 44=3001. I call the string on the left of = is tag, right is value. Now I need to compare the tag and value for them. The tag must be the same, 44 equals 44, but the values don't have to, as long as its format is the same. ie. 100 and 3001 are in the same format(normal digits). But 1.0E+7 in 44=1.0E+7 is different. tThe point is on value comparison. ie. I write a script comp.py, when I run comp.py 2000 30010, I will get output true; while I run comp.py 100000 1.0E+8, output is false. How can I do it? I am thinking about converting the value into an regular expression and comparing it with other.
pseudo code:
rex1 = '100000'.getRegrex(), rex2 = '1.0E+8'.getRegrex(), rex1.compare(rex2)
Is it a feasible way? any advice?
A:
rex1 = '100000'.getRegrex(), rex2 = '1.0E+8'.getRegrex(), rex1.compare(rex2)
Your approach is wrong. It is not only difficult but also illogical to "deduce" a regexp from a given string. What you would do is:
Define your types. With each type you would have a corresponding regexp.
Compare your input text against all your defined types and check which type it is of.
Compare the two types.
| {
"pile_set_name": "StackExchange"
} |
Q:
Counting the occurence of an object in a Binary Tree
I am trying to develop a recursive algorithm which counts the occurrence of an object in a binary tree. Actually, I could manage to write down one but I'm not sure if it works well or is preferable if it's not, please help me fix it.
Algorithm count(Node, desiredObject)
counter = 0
if(Node is empty)
return counter
else
if(Node's data is equal to the desiredObject's data)
counter := counter + 1
leftCounter = count(Node's left child, desiredObject)
rightCounter = count(Node's right child, desiredObject)
return counter + leftCounter + rightCounter
A:
Your algorithm looks fine. Just some quick thought, it can be smaller in terms of LOC and you can exclude all the counter variables.
Algorithm count(Node, desiredObject)
if(Node is empty)
return 0
return (Node's data == desiredObject's data) +
count(Node's left child, desiredObject) +
count(Node's right child, desiredObject)
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I disable the "Add to My Links" option on a list Actions Menu?
I have a SharePoint 2007 farm where MySites and MyLinks are disabled and there is only one SSP. The 'My Links' menu option that is normally next to the Welcome Control is properly trimmed away. Unfortunately, for every list in the site collection, it still shows the "Add to My Links" menu option in the Actions menu for the list.
Some sites I've looked at have recommended updating the core.js to remove this, which I did as a test but to no avail (I know, I know, core MS file, do not touch). Upon deeper investigation, I discovered that this troublesome link is part of the initial page rendering, not added dynamically via Javascript. This means that the default SharePoint controls are where this is being adding to the page.
How do I disable just this menu option?
A:
See if this helps:
Open your Site collection with a Web browser and go to:
Site Settings => Site Collection Administration => Portal Site Connection
Then choose "Do not connect to portal site"
Worked for me.
| {
"pile_set_name": "StackExchange"
} |
Q:
Filling frame with color
I'm trying to fill the frame with the buttons so it extends the background-color to the end of the window both sides, this worked when doing .pack() but not .grid().
My code:
from tkinter import *
class App:
def __init__(self):
self.root = Tk()
self.width = 800
self.height = 400
self.root.geometry("{}x{}".format(self.width, self.height))
self.root.resizable(False, False)
self.menu_bar()
self.tool_bar()
self.name = Label(self.root, text="Tester", bg="black", fg="white")
self.root.mainloop()
def menu_bar(self):
self.menu = Menu(self.root)
self.root.config(menu=self.menu)
self.subMenu = Menu(self.menu)
self.menu.add_cascade(label="File", menu=self.subMenu)
self.subMenu.add_command(label="New Project...")
self.subMenu.add_command(label="Properties")
self.subMenu.add_separator()
self.subMenu.add_command(label="Do nothing")
def tool_bar(self):
self.toolbar = Frame(self.root, bg="#555555")
self.insert_button = Button(self.toolbar, text="Insert", bg="#555555", fg="white", activeforeground="white",
activebackground="#008CBA", borderwidth=0)
self.insert_button.grid(row=0, column=0)
self.print_buttom = Button(self.toolbar, text="Print", bg="#555555", fg="white", activeforeground="white",
activebackground="#008CBA", borderwidth=0,
command=self.root.quit)
self.print_buttom.grid(row=0, column=1)
self.toolbar.grid(row=0, column=0, sticky=EW)
if __name__ == '__main__':
App()
Thanks for answers in advance.
A:
You can set a weight to your column.
class App:
def __init__(self):
self.root = Tk()
...
self.root.columnconfigure(0,weight=1)
...
| {
"pile_set_name": "StackExchange"
} |
Q:
Manejar evento click en toda el área de un control de usuario en C#
He creado un control de usuario que hereda de un Panel al que le he añadido una imagen y una etiqueta.
Incluyo varios de estos controles en un formulario. En este formulario creo el evento ClickOpciones. Quiero que este evento se maneje desde cualquiera de los botones y se lo incluyo en el manejador de envento Click de los controles.
La cuestión es cuando pulso sobre el área del control que no contiene la imagen ni la etiqueta el evento me salta pero no así si pulso sobre la imagen y la etiqueta. Que debo hacer para que funcione en cualquier parte?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ClickOpciones(object sender, EventArgs e)
{
MessageBox.Show("Hola mundo, esto marcha...");
}
}
/// <summary>
/// Panel extendido con una imagen y una etiqueta.
/// </summary>
[ToolboxBitmap(typeof(PanelOpciones), "PanelOpciones")]
[Description("Panel extendido con una imagen y una etiqueta")]
[Serializable]
public class PanelOpciones : Panel
{
#region DESIGNER
/// <summary>
/// Variable del diseñador requerida.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Limpiar los recursos que se estén utilizando.
/// </summary>
/// <param name="disposing">true si los recursos administrados se deben eliminar; false en caso contrario, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Código generado por el Diseñador de componentes
/// <summary>
/// Método necesario para admitir el Diseñador. No se puede modificar
/// el contenido del método con el editor de código.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PanelOpciones));
this.btnImagenPanel = new System.Windows.Forms.Button();
this.lblTitulo = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// btnImagenPanel
//
this.btnImagenPanel.Cursor = System.Windows.Forms.Cursors.Default;
this.btnImagenPanel.Dock = System.Windows.Forms.DockStyle.Left;
this.btnImagenPanel.FlatAppearance.BorderSize = 0;
this.btnImagenPanel.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnImagenPanel.Location = new System.Drawing.Point(0, 0);
this.btnImagenPanel.Name = "btnImagenPanel";
this.btnImagenPanel.Size = new System.Drawing.Size(16, 26);
this.btnImagenPanel.TabIndex = 0;
this.btnImagenPanel.TabStop = false;
this.btnImagenPanel.UseVisualStyleBackColor = true;
//
// lblTitulo
//
this.lblTitulo.AutoSize = true;
this.lblTitulo.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblTitulo.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.lblTitulo.Location = new System.Drawing.Point(18, 5);
this.lblTitulo.Name = "lblTitulo";
this.lblTitulo.Size = new System.Drawing.Size(0, 14);
this.lblTitulo.TabIndex = 1;
//
// PanelOpciones
//
this.Controls.Add(this.btnImagenPanel);
this.Controls.Add(this.lblTitulo);
this.Dock = System.Windows.Forms.DockStyle.Top;
this.Size = new System.Drawing.Size(26, 26);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public System.Windows.Forms.Button btnImagenPanel;
public System.Windows.Forms.Label lblTitulo;
#endregion
#region Atributos
Color backColor = Color.White;
#endregion
#region Propiedades
/// <summary>
/// Devuelve o establece la descripción de la opción.
/// </summary>
[Category("_Ravisoft")]
[Description("Devuelve o establece la descripción de la opción.")]
public string _Opcion
{
get
{
return lblTitulo.Text;
}
set
{
lblTitulo.Text = value;
}
}
/// <summary>
/// Devuelve o establece la imagen de la opción.
/// </summary>
[Category("_Ravisoft")]
[Description("Devuelve o establece la imagen de la opción.")]
public Image _OpcionImagen
{
get
{
return btnImagenPanel.Image;
}
set
{
btnImagenPanel.Image = value;
}
}
/// <summary>
/// Devuelve o establece el Panel que mostrará.
/// </summary>
[Category("_Ravisoft")]
[Description("Devuelve o establece el Panel que mostrará.")]
public string _PanelForm { get; set; }
#endregion
#region Constructor
/// <summary>
/// Muestra un panel extendido con apariencia de formulario.
/// </summary>
public PanelOpciones()
{
InitializeComponent();
_Opcion = "Opción...";
}
/// <summary>
/// Liberar recursos.
/// </summary>
public void Dispose()
{
GC.SuppressFinalize(this);
}
/// <summary>
/// Destructor de la clase.
/// </summary>
~PanelOpciones()
{
this.Dispose();
}
/// <summary>
/// Liberar recursos.
/// Existe también el método Dispose(), tiene el mismo efecto.
/// </summary>
public void Close()
{
Dispose();
}
#endregion
}
A:
Incluyo la solución que me dieron en MSDN para que conste la pregunta como resuelta:
https://social.msdn.microsoft.com/Forums/es-ES/e9dba49e-30df-4141-92b7-ce5da693ec4c/lanzar-el-evento-click-de-un-usercontrol-pulsando-cualquier-control-del-mismo?forum=vcses
| {
"pile_set_name": "StackExchange"
} |
Q:
PTAS definition vs. FPTAS
From what I read in the preliminary version of a chapter of the book “Lectures on Scheduling”
edited by R.H. M¨ohring, C.N. Potts, A.S. Schulz, G.J. Woeginger, L.A. Wolsey, to appear around 2011 A.D.
This is the PTAS Definition:
A polynomial time approximation scheme (PTAS) for problem $X$ is an
approximation scheme whose time complexity is polynomial in the input
size.
and FPTAS definition
A fully polynomial time approximation scheme (FPTAS) for problem $X$
is an approximation scheme whose time complexity is polynomial in the
input size and also polynomial in 1/$\epsilon$.
Then the writer says:
Hence, for a PTAS it would be acceptable to have a time complexity proportional to $|I|^{1/\epsilon}$ where $|I|$ is the input size;although this time complexity is exponential in $1/\epsilon$. An FPTAS cannot have a time complexity that grows exponentially in $1/\epsilon$ but a time complexity proportional to $|I|^8/\epsilon^3$ would be fine. With respect to
worst case approximation, an FPTAS is the strongest possible result that we can derive for an NP-hard problem.
Then he suggested the following figure to illustrates the relationships between the classes of problems:
Here is my questions:
From the PTAS and the FPTAS definition, how does the writer conclude that the FPTAS cannot have a time complexity that grows exponentially in $1/\epsilon$? and what difference does it make if it can have such time complexity?
A time complexity like $(n+1/\epsilon)^3$ is acceptable for FPTAS but it is not for PTAS, then why FPTAS is considered to be a subset of PTAS?
What does he mean by: an FPTAS is the strongest possible result that we can derive for an NP-hard problem.
In the aggregate I would like to know what exactly these to concepts mean and, what are their distinct properties.
Thanks in advance.
A:
Let me answer your questions in order:
By definition, a problem has an FPTAS if there is an algorithm which on instances of length $n$ gives an $1+\epsilon$-approximation and runs in time polynomial in $n$ and $1/\epsilon$, that is $O((n/\epsilon)^C)$ for some constant $C \geq 0$. A running time of $2^{1/\epsilon}$ doesn't belong to $O((n/\epsilon)^C)$ for any $C$. An algorithm whose running time is $O((n/\epsilon)^C)$ is better than an algorithm whose running time is only guaranteed to be $O(n^C e^{D/\epsilon})$, since the dependency on $\epsilon$ is better for the first algorithm. Furthermore, for any $E$, we can find an $1+1/n^E$-approximation in polynomial time using the first algorithm but not using the second (at least not with the given guarantee).
A problem in which an $1+\epsilon$-approximation can be found in time $(n+1/\epsilon)^3$ is definitely in PTAS, since for every $\epsilon$ this is $O(n^3)$ (exercise) and so polynomial in $n$.
What the authors meant here is that since an NP-hard optimization problem can't be solved exactly in polynomial time, the best we can hope for is for it to be $\epsilon$-approximable in polynomial time, and furthermore with a good dependence on $\epsilon$. Among the common complexity classes, FPTAS gives the strongest guarantee on the dependence on $\epsilon$. But in practice we sometimes get an even better guarantee: the running time is polynomial in $n$ and in $\log(1/\epsilon)$. So it's not strictly true that FPTAS is the strongest possible result; it's only the strongest possible result among the options PTAS,FPTAS,P. If we made up a new class LPTAS (corresponding to time polynomial in $n$ and in $\log(1/\epsilon)$), then that would be a stronger guarantee.
Given an NP-hard optimization problem, it can't be solved exactly in polynomial time; the best one can hope for is to approximate it efficiently. Some problems are NP-hard to approximate to some constant $C>1$. For others, it is possible to approximate the problem arbitrarily well in polynomial time, and these problems have a PTAS and so belong to the class PTAS. It might be that a $1+\epsilon$-approximation takes time proportional to $e^{1/\epsilon}$, and so we can only apply this efficiently for constant $\epsilon$. If the problem has an FPTAS (and so belongs to the class FPTAS), then we know that the dependency on $\epsilon$ is only polynomial, and so we can approximate efficiently to within $1+1/n^C$ for any $C$.
| {
"pile_set_name": "StackExchange"
} |
Q:
X-UA-Compatible ignored when page launched by ShowModalDialog
I am wondering if someone can help me with the "X-UA-Compatible" tag with regards to launching a modal dialog.
I have the following page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<title></title>
</head>
<body onload="load()">
<form id="form1" runat="server">
<iframe name="fr1" frameborder="0" id="fr1" width="675px" height="550px"></iframe>
.
.
.
var src = http://someurl.web;
document.all.fr1.src = src;
If I browse directly to this page (not to the http://someurl.web, but the page with the IFrame on it that points at http://someurl.web), the "X-UA-Compatible" stuff will work correctly, however, if I launch my page like below:
window.showModalDialog(urlToPage, "", "dialogHeight: 550px; dialogWidth: 800px; center: Yes;")
The "X-UA-Compatible" stuff is ignored. Why is this? What do I need to do in order to get that tag to be recognized when the page it is on launched via showModalDialog? This is happening when using IE9 on an Intranet site with "Display Intranet site in Compatibility View" Management will not allows to uncheck this, hence the use of the "X-UA-Compatible" tag.
A:
As I understand it, in IE9 (and newer), if a page is launched in an iframe, the document mode will match that of the parent document, regardless of any X-UA-Compatible meta element or server header, unless the parent is using standards mode and the iframe specifies quirks mode. I'm not aware of a workaround.
See http://blogs.msdn.com/b/ie/archive/2010/06/16/ie-s-compatibility-features-for-site-developers.aspx for more information.
| {
"pile_set_name": "StackExchange"
} |
Q:
Where should I place interface actions in Angular?
I have problem with bootstraping my angular application. I'm wondering, where should I place interface actions? Should I create special controller or maybe a service with these actions? For example: I want to create object responsible for showing alerts and call MyUiModule.showAlert(message) from any place within app.
Which approach is better - controller, service, something else?
A:
As you want to use the showAlert functionality from any place within the app, the best place to put it is in service.
Now in any controller, where you want to avail this service, just inject it as dependency and call the method.
app.factory("MyUiModule", function() {
var UiModule = {};
UiModule.showAlert = function(message) {
// construct the interface to show the alert
// It could be angular-ui modal window
};
return UiModule;
});
In your controller where you want to use it:
app.controller("MyController", function($scope, MyUiModule) {
$scope.login = function() {
MyUiModule.showAlert("Please enter the username");
}
});
| {
"pile_set_name": "StackExchange"
} |
Q:
Html form in email
I have created an html form with text boxes and radio buttons ect.
I can email the form to an email address.
now the problem, when i fill in the form and click reply, i only get my blank html form back no values were left inside the textbox's.
Please help
A:
We did some fairly extensive research about HTML forms in emails for a client of ours. The bottom line is that it barely works, so it’s best to link to a form in a browser. Here’s the article (and chart) with our results:
http://www.flitehaus.com/blog/2011-06-20-can-i-include-form-email
A:
What Quentin said holds water, many email clients (cough, outlook) are very specific in regards to their support for HTML emails. In fact most don't even support div's or embedded <style> blocks. Let alone an HTML form.
Your best bet is to use a URL that they click on, which in-turn opens up a form for them to fill out. If you need to capture some of their information automatically (such as email). you can generate query strings and in your mailer have it add the information in dynamicallly..
i.e; <a href="http://awesomeform.com/form.php?email=$client_email">
In email it would look like: http://awesomeform.com/[email protected]
Either way
If you are insistent on attempting this, use the email boilerplate to get you started. It has a ton of "best practices" and tips/tricks built right into it.
http://htmlemailboilerplate.com/
A:
Complex HTML doesn't mix with many email clients. Forms are especially poorly supported.
Link to an HTML document available over HTTP instead. People can click a link and open it in a regular web browser.
| {
"pile_set_name": "StackExchange"
} |
Q:
Operating systems which have non-x86 instruction set architecture
What are the most famous operating systems for non-x86 computers? I mean, most famous OS which have different instruction set architecture.
Background (to better understand my task):
I ask this question because currently I working on a paper which describes the difference between hypervisors and emulators. It have a passage which looks like:
You could install Windows 95 on Windows 7 with hypervisor, but you cannot install <...> on Windows 7, because these operating systems are developed to use different instructions sets. You will need emulator for it.
"<...>" is the name of OS which I ask for.
A:
(Too long for a comment, sorry)
This question is way too broad to give any serious answer (beside collecting meetoos with whatever favorite OS).
I suggest you go for Wikis OS list (which is non exhaustive anyway) and pick some random.
And then there is maybe a tiny misconception in your assumption. Installing an OS is not only an issue of an instruction set, but a machine structure as well (if not more).
An OS made for some non-IBM-PC x86 computer will as well not boot under a Hypervisor providing a PC-type virtual environment
As an OS for a exact PC style hardware using a non x86 CPU won't either.
And even more, an OS requiring a 'newer' version of a x86 will as well not work.
A further misconception could be that a Hypervisor does not do emulation. But isn't that the whole point? It emulates certain devices for each guest and then merges the results into a real one (think Disk or Network). Similar, many provide emulation layers to present a certain hardware as some other, maybe more simple type. Think a NE2000 hardware level emulation when the actual network interface is a total different one.
P.S.: Somewhat unrelated, but maybe helpful: If you have to write a paper, you should only use analogies that you can defend on your own. 'the internet said' doesn't always work well.
A:
The most famous operating system which you can’t install on a non-binary-translating hypervisor in Windows is probably ... Windows, in one of its non-x86 incarnations (Windows CE, Windows RT, non-x86 Windows NT, or ARM64 Windows 10).
There are many other possibilities:
one of the Unix versions or Unix-like systems on non-x86, going back to the original PDP-7 Unix;
pre-x86 releases of OS X and MacOS, on PowerPC and Motorola 68k;
VMS, on VAX systems;
any of the mainframe or mini or (non-x86) super-computer operating systems;
many micro operating systems, such as Atari TOS, AmigaOS...
These are just a few examples, there are hundreds of others. Determining which one of these is the most famous is probably a matter of context and opinion.
A:
Here are some examples:
AmigaOS
Classic Mac OS
RISC OS
| {
"pile_set_name": "StackExchange"
} |
Q:
Greedy search algorithm
Currently I am a new to the Artificial Intelligent. I have a problem on greedy search algorithm. One of the question I saw on tutorial but cant understand how to answer them. Please help me. Any help much appreciated.
Consider the given figure 1. The values in each node represent the heuristic cost from that node
to goal node (G) and the values within the arcs represent the path cost between two nodes.
[![1.If B is the starting node and G is the goal node,
(i) Find the traversal using Greedy Search Algorithm.
(ii) Find the traversal using A* Search Algorithm
2. Using the result of part(1) show that greedy search is not optimal.
A:
I assume that the greedy search algorithm that you refer to is having the greedy selection strategy as follows: Select the next node which is adjacent to the current node and has the least cost/distance from the current node. Note that the greedy solution don't use heuristic costs at all.
Consider the following figure well crafted such that it proves that greedy solution is not optimal.
The path highlighted with red shows the path taken by Greedy Algorithm and the path highlighted with green shows the path taken by Heuristic A* algorithm.
Explanation:
Greedy algorithm
Starting from Node B, the greedy algorithm sees the path costs (for A it's 6, for C it's 6 and for E it's 5)
We greedily move to node E because it is having least path value.
From E we have only one option to move to F
From F we again have only one option to move to H and from H we move to G (Goal state/node)
Cost for the path by Greedy Algorithm (highlighted in red): B -> E -> F -> H -> G = 5+6+6+3 = 20
A* algorithm (before going forward have a look at the wiki page for A* algorithm and understand what g(n) and h(n) are if you haven't already understood this concept):
Starting from node B, we have three options A, C and E. For each node we calculate f(n) = g(n) + h(n). Here g(n) is the immediate cost on the arc and h(n) is the heuristic value on the node
For node A, f(n) = 6 + 12 = 18
For node B, f(n) = 6 + 10 = 16
For node C, f(n) = 5 + 14 = 19
We choose to proceed with the node that has least f(n). So we move to node B.
We proceed in the similar fashion and find the path highlighted in green.
The path by A* algorithm is B -> C -> D -> H -> G and it's cost is 6+6+4+3 = 19
By the above example we can see that the cost of heuristic path is less than greedy algorithm. Hence greedy algorithm is not always optimal.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cordova/Phonegap not launches the application in the emulator
After running cordova run android and build the application, open the emulator but never load the application. In the terminal returns
LAUNCH SUCCESS
but it's not true. What's the problem?
Ubuntu 14.04 LTS 64 bit
Cordova 5.0.0
Phonegap 5.0.0-0.27.1
Apache Ant(TM) version 1.9.3
A:
I assume you have the same problem as me (Cordova "hello world" app won't display). I found a way to pass through it (but I don't really understand the underlying causes).
On Cordova 5.0.0, adb commands to install the apk can be found at line 101 of file platforms\android\cordova\lib\device.js (and at line 311 of platforms\android\cordova\lib\emulator.js for cordova emulate android):
adb -s ' + resolvedTarget.target + ' install -r -d "' + apk_path + '"
Current command returns to me: "Error: unknown option -d"! If you simply delete the "-d" option, applications run normally with cordova run android.
| {
"pile_set_name": "StackExchange"
} |
Q:
Get percentile for known value
I have a table of ~5000 rows, each with several columns, and a selection of known values that may or may not be contained within the table's columns.
What I'm trying to do is to order the table by the different columns in turn, and find a rough percentile for the known value that maps to that column. I only need brackets of around 10 percentiles (e.g if the 10th percentile cutoff is 6 and the 20th percentile cutoff is 14, and my known value is 7, I'll get back 0.2).
I can't rely on the known value being contained within the column I'm calculating percentiles on.
I'm calculating the percentile 'buckets' like this:
SELECT MAX(colName) as upperVal, (CAST(Percentile as float) / 10.0) as Percentile FROM (
SELECT colName, NTILE(10) OVER(ORDER BY colNameASC) AS Percentile FROM tableName AS a
) as b GROUP BY Percentile
Which gives me a table of values:
upperVal | Percentile
======== | ==========
27 | 0.1
58 | 0.2
89 | 0.3
120 | 0.4
158 | 0.5
200 | 0.6
254 | 0.7
336 | 0.8
495 | 0.9
2450 | 1
The part that's stumping me is how best to loop through these and get the percentile 'bucket' for the known value (without introducing too much overhead).
Can anyone help shed some light on this?
A:
I think of the solution using a correlated subquery. Find all the upper values larger than your value, and then choose the smaller one:
with percentiles as (
SELECT MAX(colName) as upperVal, (CAST(Percentile as float) / 10.0) as Percentile
FROM (SELECT colName, NTILE(10) OVER(ORDER BY colNameASC) AS Percentile
FROM tableName AS a
) as b
GROUP BY Percentile
)
select kv.value,
(select top 1 Percentile
from percentiles p
where p.upperVal >= kv.value
order by upperVal
)
from KnownValues kv;
You can also express this using apply.
| {
"pile_set_name": "StackExchange"
} |
Q:
Every time I write to excel, it overwrites the entire file with a blank file - PUZZLED
What I am trying to do is onTestFailure (TestNG) I am trying to write a pass/fail to a specified column. In the below code, I just wanted to do a little test to write Fail to a specified cell. But what's happening is, instead of writing a pass/fail to the specified cell, it literally overwrites the entire file and erases all of my data and I am puzzled as to why that's happening. I have looked on here and googled but cannot find the answer. Below is the following code:
@Override
public synchronized void onTestFailure(ITestResult tr){
try {
Workbook workbook = Workbook.getWorkbook(new File(testData), workbookSettings);
WritableWorkbook wb = Workbook.createWorkbook(new File(testData), workbook);
WritableSheet ws = wb.getSheet("OrderEditQA3");
Label label = new Label(5,2, "Fail");
ws.addCell(label);
wb.write();
} catch (IOException e) {
e.printStackTrace();
} catch (BiffException b){
System.out.print("Error!");
} catch (WriteException we){
System.out.print("");
}
}
Any help would be greatly appreciated.
UPDATED...
Below is another class that I use to get test data returned to a Dataprovider and I also load all of my elements from a specified sheet. Below is the code
// Code to get all test data
protected static Object[][] loadTestData(String sheetName)throws BiffException, IOException{
Sheet sheet = null;
try{
sheet = getWorkBook().getSheet(sheetName);
rowCount = sheet.getRows();
colCount = sheet.getColumns();
data = new String[rowCount -1][colCount-1];
int ci;
int cj;
ci=0;
for(int i=1; i< rowCount; i++, ci++){
cj=0;
for(int j=1; j< colCount; j++, cj++){
Cell cell = sheet.getCell(j,i);
if(cell.getContents().isEmpty()){ continue;}
System.out.print(cell.getContents() + "\n");
data[ci][cj] = cell.getContents();
}
}
}catch (IOException io){
System.out.print(String.format("File: %s not found!", testData));
}
getWorkBook().close();
return data;
}
//Code to retrieve all element attributes:
@BeforeClass
protected static List<String> loadElements()throws BiffException, IOException {
Sheet sheet = null;
sheet = getWorkBook().getSheet("Elements");
rowCount = sheet.getRows();
colCount = sheet.getColumns();
List<String> list = new ArrayList<>(rowCount);
for (int i = 1; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
Cell cell = sheet.getCell(j,i);
if(cell.getContents().isEmpty()) {continue;}
String cellContents = cell.getContents();
list.add(cellContents);
System.out.print(cell.getContents() + "\n");
}
}
elements = list;
getWorkBook().close();
return list;
}
A:
Just forgot that pesky close() method
@Override
public synchronized void onTestFailure(ITestResult tr){
try {
Workbook workbook = Workbook.getWorkbook(new File(testData), workbookSettings);
WritableWorkbook wb = Workbook.createWorkbook(new File(testData), workbook);
WritableSheet ws = wb.getSheet("OrderEditQA3");
Label label = new Label(5,2, "Fail");
ws.addCell(label);
wb.write();
wb.close();
} catch (IOException e) {
e.printStackTrace();
} catch (BiffException b){
System.out.print("Error!");
} catch (WriteException we){
System.out.print("");
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to move property setting in Struct initialization into another method
So I have a struct, call DemoType, where I want the caller to initialize it with two properties-- however I also want to expose the ability to set the second property,
the problem is that before setting prop2, there is quite a lot of logic that needs to run first. This means that there is a lot of repeat lines of code, which I'm trying to reduce by keeping that logic in one place. I would like to keep it all in setProp2
struct DemoType {
var prop1: String
var prop2: String
init?(p1:String, p2:String) {
self.prop1 = p1
let potentialFailure = true
guard potentialFailure else { return nil }
// Like 20 lines of logic here manipulating p2
self.prop2 = p2
}
mutating func setProp2(_ p2:String) {
let potentialFailure = true
guard potentialFailure else { return }
// Like 20 lines of logic here manipulating p2
self.prop2 = p2
}
}
So from a logical standpoint, I could just call setProp, and everything would be cool
struct DemoType {
var prop1: String
var prop2: String
init?(p1:String, p2:String) {
self.prop1 = p1
self.setProp2(p2)
}
mutating func setProp2(_ p2:String) {
let potentialFailure = true
guard potentialFailure else { return }
// Like 20 lines of logic here manipulating p2
self.prop2 = p2
}
}
Unfortunately, the compiler will complain that I have not initialized all of my properties in the init,
and also i want the init to be fallable, so it can return nil if certain checks fail, so I'm not sure how I would do that with this implementation, as I can make setProp2 just return, but then how do I make the caller (init) return nil?
I imagine what I'm trying to do must be possible, but I just don't know the syntax the compiler is looking for. Alternatively I could pull those 20 lines of logic out into it's own method and have both call it, that would be cleaner as well, but because both call self.prop2 at the end, I was hoping there would be a way to just have one place where self.prop2 is assigned
A:
The problem seems to be because your mutating set function can return early before setting the property. I suggest creating a function that configures prop2 and returns either the successfully configured prop, or a nil for an unsuccessful configuration:
func setProp2(_ prop2: String) -> Prop2? {
// set up
return prop2
}
Now you can call setProp2 both from the initializer and from the mutating set function. This alleviates the duplicated code problem.
| {
"pile_set_name": "StackExchange"
} |
Q:
get number of working days in specific month
I want to get the number of working days in a specific month
in my case the weekend days are FRIDAY and SATURDAY
I use this code :
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class TestWeekDay {
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String dateInString = "01-07-2016";
Date startDate = sdf.parse(dateInString);
String dateInString2 = "31-07-2016";
Date endDate = sdf.parse(dateInString2);
calculateDuration(startDate,endDate);
}
public static int calculateDuration(Date startDate, Date endDate)
{
Calendar startCal = Calendar.getInstance();
startCal.setTime(startDate);
Calendar endCal = Calendar.getInstance();
endCal.setTime(endDate);
int workDays = 0;
if (startCal.getTimeInMillis() > endCal.getTimeInMillis())
{
startCal.setTime(endDate);
endCal.setTime(startDate);
}
do
{
startCal.add(Calendar.DAY_OF_MONTH, 1);
if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.FRIDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY)
{
workDays++;
}
}
while (startCal.getTimeInMillis() <= endCal.getTimeInMillis());
return workDays;
}
}
when I test for example for July month I have 22 and the correct response should be 21
A:
If you add the following line after the if statement, you will see your problem.
System.out.printf("%s %d%n", new SimpleDateFormat("yyyy-MM-dd EEE").format(startCal.getTime()), workDays);
BTW: This is called debugging.
Output
2016-07-02 Sat 0
2016-07-03 Sun 1
2016-07-04 Mon 2
2016-07-05 Tue 3
2016-07-06 Wed 4
2016-07-07 Thu 5
2016-07-08 Fri 5
2016-07-09 Sat 5
2016-07-10 Sun 6
2016-07-11 Mon 7
2016-07-12 Tue 8
2016-07-13 Wed 9
2016-07-14 Thu 10
2016-07-15 Fri 10
2016-07-16 Sat 10
2016-07-17 Sun 11
2016-07-18 Mon 12
2016-07-19 Tue 13
2016-07-20 Wed 14
2016-07-21 Thu 15
2016-07-22 Fri 15
2016-07-23 Sat 15
2016-07-24 Sun 16
2016-07-25 Mon 17
2016-07-26 Tue 18
2016-07-27 Wed 19
2016-07-28 Thu 20
2016-07-29 Fri 20
2016-07-30 Sat 20
2016-07-31 Sun 21
2016-08-01 Mon 22
22
As you can see, you have two problems:
The first day of the month (2016-07-01) is not checked
The first day of next month (2016-08-01) is checked
I'll leave it to you to figure out a solution. Good luck.
A:
I think your problem may be caused by a boundary condition which is resulting in one extra day being added to each month before the evaluation. Try doing the day of week check first before you increment the actual day.
while (startCal.getTimeInMillis() <= endCal.getTimeInMillis()) {
if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.FRIDAY &&
startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY) {
workDays++;
}
startCal.add(Calendar.DAY_OF_MONTH, 1);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Pause / Resume For loop?
I have a for loop running through 500.000ish list. For each of these it is queueing up a SmartThreadPool job.
lines.Length below contains 500.000ish items.
My problem is that i get memory issues when queueing them all at once.. So i though id write a logic to prevent this:
int activeThreads = _smartThreadPool2.ActiveThreads;
if (activeThreads < maxThreads)
{
int iia = 0;
for (int i = 0; i < lines.Length; i++)
{
if (doNotUseAdditive.Checked == true)
{
foreach (string engine in _checkedEngines) // Grab selected engines
{
query = lines[i];
_smartThreadPool2.QueueWorkItem(
new Amib.Threading.Func<string, string, int, int, int>(scrape),
query, engine, iia, useProxies);
iia++;
}
}
}
}
else
{
// Wait
wait.WaitOne();
}
The problem is that i cannot run that if statement inside my for loop, because when i come back to it, it will not remember where it was inside the loop.
I'm using a:
ManualResetEvent wait = new ManualResetEvent(false); //global variable
To "Pause/Resume"
I need to somehow pause the loop after X threads are used and then when threads are available return and continue the loop.
Any ideas?
A:
I don't think that process every item in list in separate thread is a good idea. Even using custom thread pool can be really error-prone (and you examples proves my opinion).
First of all you should determine number of working threads correctly. It seems that you're dealing with computation intensive operations (so called CPU Bound operations) and you should use number of working threads equals to number of logical processors.
Than you can use Parallel LINQ to split all your working set for appropriate amount of chunks and process those chunks in parallel.
Joe Albahari has a great series of posts about this topic: Threading in C#. Part 5. Parallel Programming.
Here is a pseudocode of using PLINQ:
lines
.AsParallel()
.WithDegreeOfParallelism(YourNumberOfProcessors)
.Select(e => ProcessYourData(e));
| {
"pile_set_name": "StackExchange"
} |
Q:
Read and write tbz file in PHP
Hi I want to download a file that is in tbz format. So I first need to download tbz file so I am first reading it and writing to local directory on my server using the following code:
ini_set("memory_limit","15M");
set_time_limit(1600);
if($result){
$write_handle=fopen("temp/$filename", 'a');
while (!feof($handle)) {
$contents = fread($handle, 8192);
echo "<pre>";
echo strlen($contents);
echo time()-$time_start;
echo "</pre>";
fwrite($write_handle, $contents);
}
echo $contents;
fclose($write_handle);
}
And the files is there but when I try to tar -xjf command of linux on it, it says :
Unexpected EOF in archive. So what can be problem?
I actually need to use the file inside that tbz file so is there a way to do so. File size is almost more than 1GB.
A:
Hmz, you only give a part of your code, but reading your issue and considering you said:
File size is almost more than 1GB.
I have to ask..
Are you using set_time_limit() so the scripts lasts long enough and memory_limit in php.ini so the script has enough memory?
| {
"pile_set_name": "StackExchange"
} |
Q:
Python MD5 Cracker "TypeError: object supporting the buffer API required"
My code looks as follows:
md = input("MD5 Hash: ")
if len(md) != 32:
print("Don't MD5 Hash.")
else:
liste = input("Wordlist: ")
ac = open(liste).readlines()
for new in ac:
new = new.split()
hs = hashlib.md5(new).hexdigest()
if hs == md:
print("MD5 HASH CRACKED : ",new)
else:
print("Sorry :( Don't Cracked.")
But, I get this error when I run it:
hs = hashlib.md5(new).hexdigest()
TypeError: object supporting the buffer API required
How do I solve this? "b" bytes?
A:
Whatever the case, by calling split() on new you create a list object and not an str; lists do not support the Buffer API. Maybe you were looking for strip() in order to remove any trailing/leading white space?
Either way, the resulting str from new.strip() (or split() if you select an element of the resulting list) should be encoded since unicode objects must be encoded before feeding it to a hashing algorithms' initializer.
new = new.strip() # or new.split()[index]
hs = hashlib.md5(new.encode()).hexdigest()
| {
"pile_set_name": "StackExchange"
} |
Q:
Find height of rendered/visible text
I know how to get this height of a font:
By placing the text in a div and getting offset height of the div.
But I would like to get this actual height (Which will depend on font family):
Is that in any way possible using web based programming?
A:
Is there a simple solution? I think the answer is no.
If you're ok with a more involved (and processor-intensive) solution, you could try this:
Render the text to a canvas, then use canvasCtx.getImageData(..) to retrieve pixel information. Next you would do something similar to what this pseudo code describes:
first_y : null
last_y : null
for each y:
for each x:
if imageData[x][y] is black:
if first_y is null:
first_y = y
last_y = y
height = last_y - first_y
This basically looks for the top (lowest y-index) of the lettering (black pixels) and the bottom (highest y-index) then subtracts to retrieve the height.
A:
I was writing the code while Jason answered, but I decided to post it anyway:
http://jsfiddle.net/adtn8/2/
If you follow the comments you should get the idea what's going on and why. It works pretty fast and it's not so complicated as it may sound. Checked with GIMP and it is accurate.
(code to be sure it wont be lost):
// setup variables
var c = document.createElement('canvas'),
div = document.getElementsByTagName('div')[0],
out = document.getElementsByTagName('output')[0];
// set canvas's size to be equal with div
c.width = div.offsetWidth;
c.height = div.offsetHeight;
var ctx = c.getContext('2d');
// get div's font from computed style and apply it to context
ctx.font = window.getComputedStyle(div).font;
// use color other than black because all pixels are 0 when black and transparent
ctx.fillStyle = '#bbb';
// draw the text near the bottom of the canvas
ctx.fillText(div.innerText, 0, div.offsetHeight);
// loop trough the canvas' data to find first colored pixel
var data = ctx.getImageData(0, 0, c.width, c.height).data,
minY = 0, len = data.length;
for (var i = 0; i < len; i += 4) {
// when you found it
if (data[i] != 0) {
// get pixel's y position
minY = Math.floor(i / 4 / c.width);
break;
}
}
// and print out the results
out.innerText = c.height - minY + 'px';
EDIT:
I even made jQuery plugin for this: https://github.com/maciek134/jquery-textHeight
Enjoy.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does WiFi support UDP and TCP (Android device)
I've been looking around and I have found that there is evidence that Android can use UDP with it's WiFi, but can TCP be used? I know it probably can, but I can't seem to find any evidence, looking at http://developer.android.com/guide/topics/connectivity/wifip2p.html it doesn't say anything about the protocol it can use,
Does anyone have a website that states what protocols can be used, and also, I'm createing an application for android where multiple users can connect to one WiFI hotspot device and they can all play together and be real time networking, I feel UDP would be best, do you agree?
Canvas
A:
UDP, TCP and much more network stuff is placed under java.net location
and can be found here
java.net in android api
| {
"pile_set_name": "StackExchange"
} |
Q:
NSIS How do I unhide a section when something returns a specific value?
I have an installer created using the HM NIS Edit. And I want to be able to unhide the section called VDF if my check finds out its not installed. And hide it when it's installed and also don't execute that embed installer.
I hope I made myself clear.
This is the function:
Function .onInit #Check's wether the installer is in your installation folder. onInit means that it checks for that even before the installer is initialized.
${If} ${FileExists} "$EXEDIR\VDF2012-17.0.22.8.Client.exe"
MessageBox MB_OK "VDF found"
${Else}
MessageBox MB_OK "The Visual DataFlex setup was not found in the installation folder. However the installation of $(^Name) will still continue."
${EndIf}
A:
To hide a section you must change its name to a empty string.
To check/uncheck a section you should use the helper macros in sections.nsh.
!include sections.nsh
Section "VDF" SID_VDF
#Install VDF
SectionEnd
Function .onInit
${IfNot} ${FileExists} "$EXEDIR\VDF2012-17.0.22.8.Client.exe"
!insertmacro UnselectSection ${SID_VDF}
SectionSetText ${SID_VDF} ""
${EndIf}
FunctionEnd
To unhide you would give it a non-empty name but it is usually less work to show it by default and hide when required...
| {
"pile_set_name": "StackExchange"
} |
Q:
Using element IDs/class names over other CSS selectors
To what extend should I be attempting to use other CSS selectors instead of element IDs/class names or vice versa.
For instance: body > header nav ul+ul { ... } when I could just do #socialnav { ... } to achieve the same thing.
Example HTML code being (obviously there are headers with child navs elsewhere in the code):
<header>
<nav>
<ul>...</ul>
<ul....</ul>
</nav>
</header>
What is the consensus on this? I mean, I find it manageable doing it using CSS selectors, but is there a disadvantage?
A:
Your first guiding principal should be to keep the markup semantic. Your markup above is a great example of this - you're using header, nav, and ul tags in semantically meaningful ways.
Your second guiding principal should be to maintain separation of concerns (e.g., content and presentation). If adding a class names or id's to your markup does nothing for you semantically and you're able to craft CSS selectors w/out them, then you should avoid adding extra noise to the markup.
Sometimes, however, class names and id's are very useful (not just in CSS but also in JavaScript), so they have their place. Just don't resort to them if they're unneeded and are therefore adding unnecessary clutter to your markup.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to underline an EditText
I am having some problems to underline an EditText in AndroidStudio.
This is what I am looking for (this is just a photo, not my real text):
But I do not really know any property to do that.
My code right now is really simple. Just the "normal" one:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_margin="16dp"
android:id="@+id/tx_titulo"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:text="@string/pt_titulo"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:allowUndo="true"
/>
I do not want to underline just the text (in this case "Título"), but the whole PlainText
Does anybody know it?
Greets.
A:
It is default, but try to check your styles. Maybe there is a style that will override the style in the whole application. If there is, just remove it
A:
To do this programatically, you could find an answer in this post.
To set the underline color:
editText.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN);
To remove the underline color:
editText.getBackground().clearColorFilter();
To do it from the XML, you could add background property to do the same thing in your layout.xml with any drawable resource as a background by adding:
android:background="@drawable/mydrawable"
If you have a couple of EditText with the same style configuration, to avoid setting the attribute to each EditText, you could override EditText's default attributes, defining a custom style like it is done here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Decoding SNMP OIDs using tshark (wireshark)
I am debugging an SNMP trap problem using tshark (TShark 1.6.6) on a Linux platform. (The target platform does not support the wireshark GUI.) OIDs in PDUs are shown in numerical format even though I have MIBs installed in /usr/share/snmp/mibs with a link to that in /usr/local/share/mibs. I tried -V. There doesn't appear to be a tshark verbose or debugging option except for some memory debugging options. I have checked the man page and find nothing on SNMP or MIBs. I tried strace and I found a file /usr/share/wireshark/oid file but when I put the MIB directory there, I get a flex error, and a google search for what this mysterious file means turns up nothing. I can copy and paste the OIDs into an snmptranslate command and it correctly translates them. I tried creating a ~/.wireshark directory with smi_modules and smi_paths ("/usr/share/snmp/mibs"). I did a tshark -G currentprefs to see if there was a relevant preference but there isn't. I have googled this issue but I get way too much chaff to make any progress. I checked unix.stackexchange.com, superuser.com, and this site. I verified that people ask wireshark questions on this site (10,000 of them) to make sure it was on topic.
Example invocation:
tshark -R "snmp && ip.dst==<nms_ip>" -i eth0
Running as user "root" and group "root". This could be dangerous.
Capturing on eth0
4.675952 <agent_ip> -> <nms_ip> SNMP 115 sNMPv2-Trap 1.3.6.1.2.1.1.3.0 1.3.6.1.6.3.1.1.4.1.0
Contents of ~/.wireshark/preferences:
name_resolve: mtC
name_resolve_load_smi_modules: TRUE
snmp.display_oid: TRUE
snmp.desegment: TRUE
snmp.var_in_tree: TRUE
How do I get the OIDs to be displayed in symbolic format, e.g. sysUpTimeInstance and snmpTrapOID.0?
A:
I found the information Resolving SNMP OID in snmpbulkwalk and tshark useful.
Adding my MIBs to ~/.wireshark/smi_modules (via wireshark name resolution preferences), and ensuring the MIBs were located in the correct location
(on a mac I used dtrace to trace which files 'tshark' was accessing and located the path as /usr/share/snmp/mibs)
| {
"pile_set_name": "StackExchange"
} |
Q:
Cutting bagels into linked halves
I recently came across this video: Mathematically correct breakfast, which shows how a bagel can be neatly sliced into two identical linked halves.
I'd like to try this with Mathematica. Here's a torus bagel and a Möbius strip cut overlaid. How can I slice the bagel along this cut to create the two halves and pry it open?
With[{opts = {Mesh -> False, Boxed -> False, Axes -> False}},
bagel = ParametricPlot3D[{Cos[t] (3 + Cos[u]), Sin[t] (3 + Cos[u]), Sin[u]},
{t, 0, 2 Pi}, {u, 0, 2 Pi}, opts,
PlotStyle -> Directive[Opacity[0.3], FaceForm[Orange], Lighting -> "Neutral"]];
cut = ParametricPlot3D[{Cos[t] (3 + r Cos[t/2]), Sin[t] (3 + r Cos[t/2]), r Sin[t/2]},
{r, -1, 1}, {t, 0, 2 Pi}, opts,
PlotStyle -> Directive[Opacity[0.9], FaceForm[Gray], Lighting -> "Neutral"]];
]
bagel ~Show~ cut
Although I've used a Möbius strip for the cut, I have a feeling it is a 2-twist strip because of the two sides — I haven't been able to fit this correctly inside a torus...
A:
Here's one way to slice the donut. To draw one half of the sliced donut I'm using a parameterisation of a torus similar to the one on wikipedia, but with v replaced with u + v and v running from 0 to Pi instead of 2 Pi. This means that the cut is actually a double twist loop.
pl = ParametricPlot3D[{{Sin[u] (2 + Cos[u + v]), Cos[u] (2 + Cos[u + v]), Sin[u + v]},
{Sin[u] (2 + (2 v/Pi - 1) Cos[u]), Cos[u] (2 + (2 v/Pi - 1) Cos[u]),
(2 v/Pi - 1) Sin[u]}},
{u, 0, 2 Pi}, {v, 0, Pi}, Mesh -> False, Boxed -> False, Axes -> False]
We could plot the other half in a similar way but to show that the two halves are identical, you can take pl and rotate it over 180 degrees around the z-axis:
Graphics3D[{pl[[1]], Rotate[pl[[1]], Pi, {0, 0, 1}]}, Boxed -> False]
To pry the two halves open, we need to simultaneously rotate and translate one of the halves, for example
Manipulate[Graphics3D[{pl[[1]],
Translate[Rotate[Rotate[pl[[1]], 180 Degree, {0, 0, 1}], -a Degree, {1, 0, 0}],
{1.8 a/90, 0, 0}]}, Boxed -> False],
{{a, 0}, 0, 90}]
Here's an animation of the process:
A:
(This was supposed to be a comment, but it got a bit too long.)
Heike depicted the "sliced bagel" as a composite of two surfaces. Here's how to plot it as a single surface:
With[{c = 2, b = 1},
ParametricPlot3D[Evaluate[
RotationMatrix[-u, {0, 0, 1}].({0, c, 0} +
RotationMatrix[u, {1, 0, 0}].{0, b Cos[v], b UnitStep[Pi - v] Sin[v]})],
{u, 0, 2 Pi}, {v, 0, 2 Pi}, Axes -> False, Boxed -> False, Mesh -> False]]
Now if only there was a way to realistically color the "bagel"...
(If you think that last one is sufficiently "realistic", I'll add the Perlin noise routines needed for this coloring.)
| {
"pile_set_name": "StackExchange"
} |
Q:
Does the tire tread reduce the likelyhood of getting a puncture?
I've been using the last year thickslicks to driver mainly inside my city and I usually tried to don't go through anything else but asphalt to prevent punctures.
I've been wondering if going through a rocky path (or something similar with lot of little rocks) with thickslicks (700x28) and pressure around 100psi is more likely to get a puncture than the traditional wider and with tread tires that most MTB bikes have.
Example with no tread:
And with:
A:
It depends. Tread pattern affects puncture probability in two opposite ways:
Slick tires often, but not always, have thinner rubber, which offers less protection.
Knobs are generally too thick to be punctured through and put some distance between ground and the flat parts of the tire, but on the other hand the part between knobs may be very thin.
Tires with grooved tread may be punctured because small pieces of gravel or glass get stuck in grooves and eventually dig through the rubber. This happens very rarely with slick or knobby tires.
In your case, you should be worried about pinch flats, which happen when the tire is pinched between a rock and rim. 28mm may be just enough for smooth cobblestone roads but is very narrow for rocky or soft terrain.
| {
"pile_set_name": "StackExchange"
} |
Q:
Selecting only the first few characters in a string C++
I want to select the first 8 characters of a string using C++. Right now I create a temporary string which is 8 characters long, and fill it with the first 8 characters of another string.
However, if the other string is not 8 characters long, I am left with unwanted whitespace.
string message = " ";
const char * word = holder.c_str();
for(int i = 0; i<message.length(); i++)
message[i] = word[i];
If word is "123456789abc", this code works correctly and message contains "12345678".
However, if word is shorter, something like "1234", message ends up being "1234 "
How can I select either the first eight characters of a string, or the entire string if it is shorter than 8 characters?
A:
Just use std::string::substr:
std::string str = "123456789abc";
std::string first_eight = str.substr(0, 8);
A:
Just call resize on the string.
A:
If I have understood correctly you then just write
std::string message = holder.substr( 0, 8 );
Jf you need to grab characters from a character array then you can write for example
const char *s = "Some string";
std::string message( s, std::min<size_t>( 8, std::strlen( s ) );
| {
"pile_set_name": "StackExchange"
} |
Q:
Let's get critical: Feb 2015 Site Self-Evaluation
We all love Politics Stack Exchange, but there is a whole world of people out there who need answers to their questions and don't even know that this site exists. When they arrive from Google, what will their first impression be? Let's try to look at this site through the eyes of someone who's never seen it before, and see how we stack up against the rest of the 'Net.
The Site Self-Evaluation review queue is open and populated with 10 questions that were asked and answered in the last quarter.
Run a few Google searches to see how easy they are to find and compare the answers we have with the information available on other sites.
Rating the questions is only a part of the puzzle, though. Do you see a pattern of questions that should have been closed but are not? Questions or answers that could use an edit? Anything that's going really well? Post an answer below to share your thoughts and discuss these questions and the site's health with your fellow users!
A:
Final Results
How could a US Senator be prevented from reading classified information into the record?
Net Score: 5 (Excellent: 7, Satisfactory: 4, Needs Improvement: 2)
What does it mean to send a resolution "over, under the rule"?
Net Score: 3 (Excellent: 4, Satisfactory: 5, Needs Improvement: 1)
Can the POTUS neuter "advice and consent" by refusing to delegate?
Net Score: 3 (Excellent: 4, Satisfactory: 4, Needs Improvement: 1)
Are the OECD, IMF and the WTO really relevant organizations and what is the price for a country to ignore them?
Net Score: 3 (Excellent: 4, Satisfactory: 4, Needs Improvement: 1)
Has Japan's "Special Secrecy Law" been condemned by the United Nations?
Net Score: 2 (Excellent: 4, Satisfactory: 3, Needs Improvement: 2)
When and why did the President of the French Republic inherit the titles of the King of France?
Net Score: 1 (Excellent: 3, Satisfactory: 6, Needs Improvement: 2)
Why do Iran and Saudi Arabia share the same "age of majority"?
Net Score: -3 (Excellent: 2, Satisfactory: 5, Needs Improvement: 5)
Is there separation of religion and state in Canada?
Net Score: -3 (Excellent: 1, Satisfactory: 6, Needs Improvement: 4)
Nationally-mandated term limits for mayors?
Net Score: -3 (Excellent: 0, Satisfactory: 8, Needs Improvement: 3)
Population size and the viability of democracy
Net Score: -5 (Excellent: 1, Satisfactory: 4, Needs Improvement: 6)
| {
"pile_set_name": "StackExchange"
} |
Q:
Geometry problem with rectangular parallelepiped
Given right angled parallelepiped $ABCDA1B1C1D1$, with bases $ABCD$ and $A1B1C1D1$, which are squares with side $1$. if $\angle (B1C;D1A) = 60^\circ$
find the length of the surrounding edge (I'm not sure if this is the right term in English, those edges are $AA1,BB1,CC1,DD1$). Here is drawing:
I'm totally lost on this one.
A:
You can draw $DA1$,which is parallel to $B1C$. This does not define which angle is $60^\circ$. If $E$ is the intersection of the new line and $AD1$, it could be $AEA1$ or $AED$ Either way you have the end face composed of two equilateral triangles and two $120^\circ-30^\circ-30^\circ$ triangles.
| {
"pile_set_name": "StackExchange"
} |
Q:
Sortable List w/ Incrementing Values
Here is my fiddle:
http://jsfiddle.net/WV8du/24/
I would like for the numbers to increase/decrease based on the value/amount of items in the list. Thanks for the help/tips.
$(function () {
$("#sortable-primary").sortable({
placeholder: "ui-state-highlight",
connectWith: ".connected-sortable"
});
$("#sortable-secondary").sortable({
placeholder: "ui-state-highlight",
connectWith: ".connected-sortable"
});
$("#sortable-primary, #sortable-secondary").disableSelection();
});
A:
I think you will need to put the items in one UL, this will certainly make it less complex. I didn't entirely clean up the CSS, but I think this will get you started. It is at least one solution.
function numberLi(){
var i = 1;
$('#sortable-primary > .ca-nav-move > .num').each(function(){
$(this).text(i);
i++;
});
$('#sortable-secondary > .ca-nav-move > .num').each(function(){
$(this).text("");
});
}
Here is the fiddle
Here is an updated fiddle, that will remove the numbers from the bottom list when dragged there.
I didnt like the way that looked with the numbers being dragged along with the item, I decided I could do better. Here is a 3rd fiddle that performs exactly the way you wanted it to. Please mark this as the accepted answer.
| {
"pile_set_name": "StackExchange"
} |
Q:
Multiple Reverse SSH Tunnels using Single Port
I am able to accept reverse SSH connections from multiple remote systems on a single server using a port for each connection:
Remote A: ssh -fN -R5000:localhost:22 user@server-ip -p22
Remote B: ssh -fN -R5001:localhost:22 user@server-ip -p22
Remote C: ssh -fN -R5002:localhost:22 user@server-ip -p22
I can access these systems from my local client as needed:
Access Remote A: ssh root@server-ip -p5000
Access Remote B: ssh root@server-ip -p5001
This requires forwarding one port per remote system on the server. When 100+ remotes connect, do I have any options other than opening 100+ ports in the server firewall and statically assigning each remote to a port as above? My goal is to enable multiple remotes to create tunnels on demand, where I can query who is connected.
I found that sslh is a multiplexer that can differentiate between traffic on a single port based on protocol but this only applies to different protocols eg. ssl/ssh. Is there a solution that allows multiple tunnels on a single port?
Example:
Remote A: ssh -fN -R5000:localhost:22 user@server-ip -p22 -identifier abc123
Remote B: ssh -fN -R5000:localhost:22 user@server-ip -p22 -identifier def456
access Remote A: ssh root@server-ip -p5000 -identifier abc123
access Remote B: ssh root@server-ip -p5000 -identifier def456
A:
I have the same issue you do and, by the time, have only arrived at one possible answer. My scenario is a bit different than yours as I only need one active ssh tunnel, but all clients must be ready to connect if needed.
I guess one could create a client/server simple protocol to handle all the clients and create a list of some sort. The user then could chose one of the clients to create the reverse tunnel. Doing that would require another open port rather than the ssh server, but using a threaded server one could listen() to various clients under the same port for this secondary protocol.
I'm still working on a solution (I'll probably implement what I just wrote), but mind you in your case you should decide the max number of clients connected at a single time and configure that amount of ports. As mine is just a small linux "support" for embedded devices, I can only work on one device at a time anyway, so I only need 1 device.
A cleverer idea would be to inform the client over the aux protocol at which server port to attach the reverse tunnel.
| {
"pile_set_name": "StackExchange"
} |
Q:
JQuery Slider Initialize in Ajax
I am using the JQuery slider, and it loads fine in my header. I suppose it is being initialed with the following code:
$(function() {
$( "#slider" ).slider({
orientation: "horizontal",
range: "min",
min: 0,
max: 100,
value: 60,
slide: function( event, ui ) {
$( "#amount" ).val( ui.value );
}
});
$( "#amount" ).val( $( "#slider" ).slider( "value" ) );
});
$( ".selector" ).on( "slidecreate", function( event, ui ) {
} );
I am calling an Ajax function that responds with another JQuery slider using the tag
<div id="slider"></div>
Here is the Ajax function:
<!-- Ajax Function for removing an users favorites-->
function ShowFavoritesAjax(url,cfunc,userID)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("user_id=" + userID);
}
function ShowFavorites(userID)
{
ShowFavoritesAjax("ajaxPHP/users/ajaxShowFavorites.php",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("userFav").innerHTML=xmlhttp.responseText;
} else {
document.getElementById("userFav").innerHTML='<img src="images/ajax-loader.gif">';
}
},userID,bandID);
}
So I am guessing that I need to "initialize the Slider" in one of my Ajax functions. So I tried this by modifying the return as so: (I just pasted the initialize function in it's entirety right before the response text is displayed)
function ShowFavorites(userID)
{
ShowFavoritesAjax("ajaxPHP/users/ajaxShowFavorites.php",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
$(function() {
$( "#slider" ).slider({
orientation: "horizontal",
range: "min",
min: 0,
max: 100,
value: 60,
slide: function( event, ui ) {
$( "#amount" ).val( ui.value );
}
});
$( "#amount" ).val( $( "#slider" ).slider( "value" ) );
});
$( ".selector" ).on( "slidecreate", function( event, ui ) {
} );
document.getElementById("userFav").innerHTML=xmlhttp.responseText;
} else {
document.getElementById("userFav").innerHTML='<img src="images/ajax-loader.gif">';
}
},userID);
}
If anyone can spot my problem and has a fix I would really be grateful.
Thanks.
A:
Try this:
function ShowFavorites(userID)
{
ShowFavoritesAjax("ajaxPHP/users/ajaxShowFavorites.php",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("userFav").innerHTML=xmlhttp.responseText;
$( "#slider" ).slider({
orientation: "horizontal",
range: "min",
min: 0,
max: 100,
value: 60,
slide: function( event, ui ) {
$( "#amount" ).val( ui.value );
});
$( "#amount" ).val( $( "#slider" ).slider( "value" ) );
$( ".selector" ).on( "slidecreate", function( event, ui ) {
});
} else {
document.getElementById("userFav").innerHTML='<img src="images/ajax-loader.gif">';
}
},userID);
}
What I have changed in this code:
move the line document.getElementById("userFav").innerHTML=xmlhttp.responseText; to be executed first.
Remove the $(function() {
Reasons:
$(function() { fires when document is ready (not in this case).
When you execute your code like $.slider, the html is not inserted into the document yet => so you have to reverse the order.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I define a self closing XML element in an XML Schema
Element I want to define:
<feature_ref id="0"/>
Code I've put in my XSD file:
<xs:attribute name="id" type="xs:integer"/>
<xs:element name="feature_ref" type="xs:string">
<xs:complexType>
<xs:attribute ref="id"/>
</xs:complexType>
</xs:element>
Is there a way I can specify in my XSD that this element should be self-closing?
A:
Self-closing elements are syntaxic sugar for the same value. For the same reason you cannot control the sequence of attributes, or the whitespace between attributes, self-closing cannot be defined with XSD.
In other words:
<feature_ref id="0"/>
is exactly the same as
<feature_ref id="0"></feature_ref>
See the W3 specifications: http://www.w3.org/TR/REC-xml/#sec-starttags
| {
"pile_set_name": "StackExchange"
} |
Q:
Proving a language is not regular
If two languages L1 and L2 are regular than so is their intersection.
If follows that, for two languages L1 and L2, if L1 intersection L2 is not regular and L1 IS regular than L2 is not regular.
I am having a hard time proving this. Since I am dealing with regular languages, I decided to build DFA's for them to help my proof. However, this does not help with my proof if I am supposed to prove the irregularity of a language. How do you prove a language is not regular if you cannot construct a DFA/NFA for them? Is pumping lemma the only way?
A:
The second statement logically follows from the first without any knowledge of how languages or sets work:
$$Regular(L_1) \wedge Regular(L_2) \to Regular (L_1 \cap L_2)$$
$$\lnot Regular (L_1 \cap L_2) \wedge Regular(L_1) \to \lnot Regular(L_2)$$
To prove that the first statement is true, show how you could construct a DFA for the intersection of two languages for which you already have DFAs.
Edit: Here is a slightly more detailed outline. Let $A = Regular(L_1)$, $B = Regular(L_2)$, $C = Regular(L_1 \cap L_2)$. The first 3 lines are given, and you want to show the last line ($\lnot B$).
Given:
$$(A \wedge B) \to C$$
$$\lnot C$$
$$A$$
From line 1:
$$\lnot C \to \lnot (A \wedge B)$$
From lines 2 and 4:
$$\lnot (A \wedge B)$$
From line 5:
$$\lnot A \lor \lnot B$$
From lines 3 and 6:
$$\lnot B$$
This isn't a formal proof--I haven't established a set of inference rules, and listed the rule used at each step. But it should give you a starting place. You'll have to look up which inference rules you're allowed to use in your course.
| {
"pile_set_name": "StackExchange"
} |
Q:
SwiftUI: how to use NavigationView in macOS?
I have two separate Xcode projects that I'm using to learn SwiftUI:
A true macOS project (not Catalyst) on Mac.
An iOS project (iPhone).
The following code creates a simple NavigationView with master-detail views:
import SwiftUI
struct ListView : View {
var body: some View {
NavigationView {
List() {
NavigationButton(destination: Text("detail 1")) {
Text("row 1")
}
NavigationButton(destination: Text("detail 2")) {
Text("row 2")
}
}
}
}
}
#if DEBUG
struct ListView_Previews : PreviewProvider {
static var previews: some View {
ListView()
}
}
#endif
It works as expected on iOS
But on the macOS project the same code as above doesn't work the same way
When I launch the app on Mac, I get this window
And when I click on any row, the detail view just collapses/disappears, never showing me detail view.
Any ideas how to fix this? Maybe I'm missing something? Or perhaps this is just a bug?
A:
I don't have the answer but I'm trying to do the same thing and have a few observations to add, maybe they will help:
Add a destination View:
NavigationButton(destination: DetailView()) {
Text("Show Detail")
}
Setting a width on the NavigationView stops the right-hand view from disappearing.
Also, adding
.onAppear { print("DetailView called") }
to the detail view shows that, even though it isn't being displayed, the view is in fact called when the button is clicked.
Edit: it's there! The view was hidden by the divider, drag it left to see the detail view.
Edit 2: Xcode beta 2 gives a "'NavigationView' is unavailable in macOS" message.
| {
"pile_set_name": "StackExchange"
} |
Q:
swift: modifying arrays inside dictionaries
How can I easily add elements to an array inside a dictionary?
It's always complaining with could not find member 'append' or could not find an overload for '+='
var dict = Dictionary<String, Array<Int>>()
dict["key"] = [1, 2, 3]
// all of these fail
dict["key"] += 4
dict["key"].append(4) // xcode suggests dict["key"].?.append(4) which also fails
dict["key"]!.append(4)
dict["key"]?.append(4)
// however, I can do this:
var arr = dict["key"]!
arr.append(4) // this alone doesn't affect dict because it's a value type (and was copied)
dict["key"] = arr
if I just assign the array to a var, modify it and then reassign it to the dict, won't I be copying everything? that wouldn't be efficient nor elegant.
A:
Swift beta 5 has added this functionality, and you've nailed the new method in a couple of your attempts. The unwrapping operators ! and ? now pass through the value to either operators or method calls. That is to say, you can add to that array in any of these ways:
dict["key"]! += [4]
dict["key"]!.append(4)
dict["key"]?.append(4)
As always, be careful about which operator you use -- force unwrapping a value that isn't in your dictionary will give you a runtime error:
dict["no-key"]! += [5] // CRASH!
Whereas using optional chaining will fail silently:
dict["no-key"]?.append(5) // Did it work? Swift won't tell you...
Ideally you'd be able to use the new null coalescing operator ?? to address this second case, but right now that's not working.
Answer from pre-Swift beta 5:
It's a quirk of Swift that it's not possible to do what you're trying to do. The issue is that the value of any Optional variable is in fact a constant -- even when forcibly unwrapping. If we just define an Optional array, here's what we can and can't do:
var arr: Array<Int>? = [1, 2, 3]
arr[0] = 5
// doesn't work: you can't subscript an optional variable
arr![0] = 5
// doesn't work: constant arrays don't allow changing contents
arr += 4
// doesn't work: you can't append to an optional variable
arr! += 4
arr!.append(4)
// these don't work: constant arrays can't have their length changed
The reason you're having trouble with the dictionary is that subscripting a dictionary returns an Optional value, since there's no guarantee that the dictionary will have that key. Therefore, an array in a dictionary has the same behavior as the Optional array, above:
var dict = Dictionary<String, Array<Int>>()
dict["key"] = [1, 2, 3]
dict["key"][0] = 5 // doesn't work
dict["key"]![0] = 5 // doesn't work
dict["key"] += 4 // uh uh
dict["key"]! += 4 // still no
dict["key"]!.append(4) // nope
If you need to change something in an array in the dictionary you'll need to get a copy of the array, change it, and reassign, like this:
if var arr = dict["key"] {
arr.append(4)
dict["key"] = arr
}
ETA: Same technique works in Swift beta 3, though constant arrays no longer allow changes to contents.
A:
As a simple workaround you can use a NSMutableArray:
import Foundation
var dict = Dictionary<String, NSMutableArray>()
dict["key"] = [1, 2, 3] as NSMutableArray
dict["key"]!.addObject(4)
I am using effectively such simple solution in my project:
https://github.com/gui-dos/Guigna/blob/5c02f7e70c8ee3b2265f6916c6cbbe5cd3963fb5/Guigna-Swift/Guigna/GuignaAppDelegate.swift#L1150-L1157
A:
The accepted answer bypasses the following much simpler possibility, which also works for older Swift versions:
var dict = Dictionary<String, Array<Int>>()
dict["key"] = [1, 2, 3]
print(dict)
dict["key", default: [Int]()].append(4)
print(dict)
This will print:
["key": [1, 2, 3]]
["key": [1, 2, 3, 4]]
And this:
var dict = Dictionary<String, Array<Int>>()
dict["key", default: [Int]()].append(4)
print(dict)
will print:
["key": [4]]
| {
"pile_set_name": "StackExchange"
} |
Q:
Add Google Adsense to an email
Is this answer in google's support enouh to say that is ok to put ads in email's I send to my customers?
A:
That answer refers specifically to Google Affiliate Network ads. It has nothing to do with AdSense. The only supported method for putting AdSense into emails that is not against the AdSense TOS was through AdSense for Feeds and Feedburner, but this was shut down in November, 2012. Currently, as of December, 2012, normal AdSense publishers cannot put AdSense units in emails.
A:
I'd say it means you can place Google Affiliate Network ads in emails if you comply with the email marketing program policies.
You can do this using Feedburner and AdSense for feeds. Then use a mail program like MailChimp to pick up and send the feeds.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can anyone help me out on a form spamming issue?
I have a form for enquiries on my website.
Spammers are using it to keep sending me SEO and dating links.
I want to stop this.
They aways enter "google" in the company name field before submitting the form.
Is there an easy way to send these spammers on to my "thankyou" page on submit, so they think they have successfully spammed me but in effect nothing has happened?
Basically - if submitted companyname field = google then on submit do not send form results by email but just present thankyou.html page.
My page is here here is my contact form
A:
Followup from the comments section.
Inside your formCheck() function, replace this piece of code
if (alertMsg.length == l_Msg){
return true;
}else{
alert(alertMsg);
return false;
}
with
if (alertMsg.length == l_Msg){ // No alerts
let companyName = formobj.elements['Company'].value || "";
if(companyName.trim().toLowerCase()==='google'){ // Potential spam, redirect to "Thank you" page.
window.location.href='confirm.htm'
return false;
}
// Otherwise, proceed as valid entry.
return true;
}else{
alert(alertMsg);
return false;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Simple Python 3 TicTacToe Game
Relatively new here so please let me know if I'm doing something wrong.
I'm mostly wondering if there's any additional way I can make this code more efficient. Specifically the moveset and win condition part of the code feels unnecessarily long or overcomplicated. Still a beginner in python, so any feedback regarding syntax is also appreciated! Thank you!
#Contains all basic variables for ease of coding
class Player():
symbols = ['O','X']
def __init__(self, number):
self.wins = 0
self.number = number
self.symbol = self.symbols[number]
#2D list to represent the 3x3 board
def createBoard():
a = ['', '', '']
b = ['', '', '']
c = ['', '', '']
return [a, b, c]
board = createBoard()
#Makes the board look nicer for user; numbers as placeholder for empty spaces
def printBoard():
i = 0
for row in board:
print("---------------")
for place in row:
i += 1
if place == '':
print("|",i,"|", end='')
else:
print("|",place,"|", end='')
print("")
print("---------------")
#Receives numbers to return x and y position of the 2d list
def getMove():
#Any other more efficient way for this?
moveset = {
'1': (0,0),
'2': (1,0),
'3': (2,0),
'4': (0,1),
'5': (1,1),
'6': (2,1),
'7': (0,2),
'8': (1,2),
'9': (2,2)
}
print("Please enter the number of the spot to place your move",end='')
xpos, ypos = moveset[input("> ")]
return xpos, ypos
#changes the board with received x and y
def placeMove(xpos, ypos, player):
global board
board[ypos][xpos] = player.symbol
#Checkes if the spot has been filled
def validateMove(xpos, ypos):
if board[ypos][xpos] != '':
print("Cannot place there!")
return False
return True
#Checks win conditions; any more efficient way for this as well?
def checkWin():
for row in board:
if row[0]==row[1]==row[2]:
return row[0]
for i in range(0,3):
if board[0][i]==board[1][i]==board[2][i]:
return board[0][i]
if board[0][0]==board[1][1]==board[2][2]:
return board[1][1]
elif board[0][2]==board[1][1]==board[2][0]:
return board[1][1]
for row in board:
for spot in row:
if spot == '':
return False
return 2
def switchPlayer(currentPlayer):
if currentPlayer.number == 0:
return 1
else:
return 0
#game loop
def game():
global board
playerList = [Player(0), Player(1)]
game = True
currentPlayer = playerList[0]
printBoard()
while game:
print("Current Player:",currentPlayer.number+1,)
xpos, ypos = getMove()
#repeats until valid input
while not validateMove(xpos, ypos):
xpos, ypos = getMove()
placeMove(xpos, ypos, currentPlayer)
printBoard()
if checkWin() == currentPlayer.symbol:
print("Player",currentPlayer.number+1, "wins!")
game = False
elif checkWin() == 2:
print("The game is a draw!")
game = False
else:
currentPlayer = playerList[switchPlayer(currentPlayer)]
#Should I just make the game() the main() function?
def main():
game()
if __name__ == "__main__":
main()
A:
In addition to Reinderien's comments:
checkWin() first checks board[0][0]==board[0][1]==board[0][2] and returns the "winning" symbol (a string), if the match was found.
This means that, with the following board:
| |
---+---+---
X | X |
---+---+---
O | O | O
checkWin() returns '', and checkWin() == currentPlayer.symbol is false, so "O" doesn't win. And "X" can fill their row on their move, and will be declared the winner in two more moves!
The only player who can win, is the one that just made a move, so pass that player's symbol to the checkWin() call, and explicitly check for that player winning:
def checkWin(symbol):
for row in board:
if row[0] == row[1] == row[2] == symbol:
return symbol
checkWin() returns 3 different types of values!
str if a winner is detected
bool if there are still moves which can be made
int if the game is tied.
This is just plain wrong. Pick one return type. For instance, you could use int, and return 0 for game not over, 1 for a win by the current player, and -1 for a draw game.
Or you could use str, and return "X" or "O" for a win by that player, "Cat's game" for a draw, and "" for the game not over. Then, created named constants for the values, and use those names in your code, instead of the actual values. Eg)
GAME_HAS_WINNER = 1
GAME_IS_A_DRAW = -1
GAME_IS_NOT_OVER = 0
# ...
def game():
# ...
while True:
# ...
state = checkWin(currentPlayer.symbol)
if state == GAME_HAS_WINNER:
# ... declare winner
break
elif state == GAME_IS_A_DRAW:
# ... declare a draw
break
else:
# ...
Better would be to create an Enum for the return code, if you've learnt that.
You can simplify your createBoard() & printBoard() functions, and at the same time fix the bug in checkWin() by initializing the board with the number characters, instead of empty strings.
def createBoard():
return [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
def printBoard():
for row in board:
print("---------------")
for place in row:
print("|", place, "|", end='')
print("")
print("---------------")
You'll need a different way to check for a draw game. The simplest would be to remove that test from checkWin() and change your while loop into a for loop that runs for at most 9 turns. If you finish the loop without break-ing out of the loop, the else: clause gets executed.
def game():
# ...
for _ in range(9):
# ...
if checkWin(currentPlayer.symbol) == GAME_HAS_WINNER:
# ... announce winner
break
# ...
else:
# ... announce draw game
You can use list comprehension to simplify checkWin(). For instance, checking only for a win by a given symbol, and returning True for a win, and False otherwise:
def checkWin(symbol):
if any( all(board[i][j] == symbol for i in range(3)) for j in range(3)):
return True
if any( all(board[i][j] == symbol for j in range(3)) for i in range(3)):
return True
if all(board[i][i] == symbol for i in range(3)):
return True
return all(board[i][2-i] == symbol for i in range(3)):
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I make Flex file upload work on firefox and safari?
I have a flex app that uploads files to a server. The server requires authentication to be able to upload. In IE the upload works fine. However in FF and Safari, it does not upload. I have seen people all over with this same problem but no answers. Don't fail me now stackoverflowers.
A:
The problem at least in Firefox is that the session cookies are not sent in the request when you invoke FileReference.upload(). What you need to do is add the authentication token either as a form variable or in the query string. Here is an example in Java where the session cookie is called "jsessionid"
var request : URLRequset = new URLRequest( uploadUrl + ";jsessionid=" + jsessionid);
You can parse the jsessionid out of cookies using Javascript and ExternalInterface to invoke the Javascript function. Or after you authenticate you can have Flex call a backend method that returns the current sessionID.
The related Flex bug is here:
http://bugs.adobe.com/jira/browse/FP-201
A:
I found this question while trying to find the answer myself. The solution was rather simple.
Based on the flash player bug that others have linked, and the comments on that page, I decided to append session identifiers to my upload URL and give it a shot. It really was that easy!
To make it work, I started by adding a flashVar parameter called sessionParams. This allowed me to pass any string I want in to the flash player as my session identifier, and it will later get appended to the URL used to upload.
//sessionParams - resolves firefox upload bug
public var sessionParams:String = "";
//...
public function initApp():void{
sessionParams = Application.application.parameters.sessionParams;
}
In my case, I'm on ColdFusion with java sessions enabled, so my sessionParams are setup like the following before being passed into the flash player:
<cfset flashVars = "sessionParams=#urlEncodedFormat('jsessionid=' & session.sessionid)#" />
Don't forget to escape special characters like =,&, etc (which I've done with urlEncodedFormat), so that they are treated as part of the value of the "sessionParams" parameter, and not breakpoints to indicate other parameters. You're embedding future-URL information in the current URL.
Then, use the sessionParams value in your upload code. Here's a snippet of how I set mine up:
// Set Up URLRequest
_uploadURL = new URLRequest;
_uploadURL.url = _url + "?" + _sessionParams;
_uploadURL.method = "GET";
_uploadURL.data = _variables;
_uploadURL.contentType = "multipart/form-data";
The variable names are different (but similar) because this is part of a reusable class.
Hopefully that helps you. If not, let me know and I'll try to provide more code or explanation to help you out.
| {
"pile_set_name": "StackExchange"
} |
Q:
@RunWith(PowerMockRunner.class) says @RunWith not applicable to method
I have a gradle file
testCompile('junit:junit')
testCompile('org.powermock:powermock-core:1.6.5')
testCompile('org.powermock:powermock-api-mockito:1.6.5')
testCompile('org.powermock:powermock-module-junit4:1.6.5')
And my test file
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest(ExperimentService.class)
There seems to be an error with the @RunWith and I have can't seem to find the problem, it just says that '@RunWith' not applicable to method.
What am I doing wrong?
Thanks.
A:
If you see the RunWith.class, target for this annotation is ElementType.Type which means it can only be applied to Class, enum or interface declaration.
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Inherited
public @interface RunWith {
Class<? extends Runner> value();
}
You cannot apply this annotation over a method.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it necessary to apply some window method, to obtain the FFT? Java
I read that the window is needed to apply filter (Low Pass, High Pass, Band Pass or band Stop), but not for the FFT.
1.
What advantage does apply a window or disadvantage does not apply?
2.
What is the criteria to choose the size (My LengthW:Length of Han Window)?
3. Where I can find literature that specifically?
My code:
Suppose an array of samples stored in
integer SIZE = 16384; //SomeValue
short[] sSamples = new short[SIZE];
sSamples = obtainSamples(); //Some method to fill my array
Now I need to obtain my FFT.
I arbitrarily chose 4096 for my FFT, then are 8 times (or 8 fft's)
FFTLength = 4096;
SIZE = 16384;
double Overlap = 0.5;
SIZE/(FFTLength*Overlap) = 8;
DIRECT METHOD:
complex cSamples = new complex[SIZE];
cSamples = short2Complex(sSamples);
Now I need to obtain part of array of sample 8 arrays of length:SIZE/4
//getPartArray(from, until) maybe like System.ArrayCopy
complex[] cSamples00 = getPartArray(0,4095);
complex[] cSamples01 = getPartArray(4096,8191);
//similarly for all, from 00 until 07
complex[] cSamples01 = getPartArray(12287,16383);
Finally, Obatin the FFT
//fft(complex[], length)
complex[] cFFT00 = fft(cSamples00,4096);
//similarly for all, from 00 until 07
complex[] cFFT07 = fft(cSamples00,4096);
WINDOWED METHOD:
//int LengthW = ?? // (besides positive and odd)
double[] Wn = new double[LengthW];
//Suppose Han Window,can be Hamming, Kaiser, Blackman, etc
Wn = obtainHanWindow(LengthW);
double[] sWindowedSamples = applyingWindow(Wn,sSamples);
complex cSamples = new complex[SIZE];
cSamples = short2Complex(sWindowedSamples);
Now I need to obtain part of array of sample 8 arrays of length:SIZE/4
//getPartArray(from, until) maybe like System.ArrayCopy
complex[] cSamples00 = getPartArray(0,4095);
complex[] cSamples01 = getPartArray(4096,8191);
//similarly for all, from 00 until 07
complex[] cSamples01 = getPartArray(12287,16383);
Finally, Obatin the FFT
//fft(complex[], length)
complex[] cFFT00 = fft(cSamples00,4096);
//similarly for all, from 00 until 07
complex[] cFFT07 = fft(cSamples00,4096);
The only difference is calculate a window and apply it to the input.
Definition's class and methods
The complex class is defined like:
class complex {
public double real = 0.0;
public double imag = 0.0;
}
short2Complex:
short2Complex(short[] intSSample) {
complex intCSample = new complex[intSSample.length];
for (int i = 0; i < intSSample.length; i++) {
complex tcomplex = new complex();
tcomplex.real = intSSample[i];
intCSample[i] = tcomplex;
}
return intCSample;
}
obtainHanWindow:
double[] obtainHanWindow(int Size) {
//Size must be Odd and Positive integer
double[] dHan = new double[Size];
int HalfSize = (int)Math.floor((double)Size/2);
for (int i = 0; i < HalfSize; i++) {
int j = 2*HalfSize - i;
double Pi2DivSize = 2.0*Math.PI/Size;
dHan[i] = 0.5+0.5*Math.cos(Pi2DivSize*(double)(i - HalfSize));
dHan[j] = 0.5+0.5*Math.cos(Pi2DivSize*(double)(HalfSize - i));
}
dHan[HalfSize] = 1.0;
return dHan;
}
applyingWindow
applyingWindow(double[] dWn, double[] dSamples) {
double dOutput = new double[dSamples.length]
for (int i=0; i < dWn.length; i++) {
dOutput[i] = 0;
for (int j=0; j < dSamples.length; j++) {
if(i-j>=0) {
dOutput[i] += dSamples[j]*dWn[i-j];
}
}
}
return dOutput;
}
A:
As you can see; When a sinusoidal signal of arbitrary frequency is input to the ‘N’ point DFT, the spectral response of the signal will not be a Delta function (impulse) because when we take into account of the missing end point to be the same as the beginning of the next period of the periodic extension of the sequence, the periodic extension of the signal is no more a sinusoid. One way to solve this problem is to ensure Coherent Sampling as shown in figure 1
But coherent sampling can be done only if the DFT engine receives pure monotone signals. So in a real world application, Coherent sampling is not feasible.
SO, just diminish the magnitude of the discontinuities by multiplying the whole signal with some function.
So, when you multiply by window function, it eliminates the jump discontinuities and removes the false frequency that is introduced when coherent sampling is not done (see Figure 3.
The length of the window should be the length of your signal.
Selection of your window could be depending on how much side-lobe height do you tolerate.
Image Source: http://electronicdesign.com/analog/choose-right-fft-window-function-when-evaluating-precision-adcs
| {
"pile_set_name": "StackExchange"
} |
Q:
How can this be proven (Matrices)
I need to prove why the image on the bottom is true, btw this is on a matrices unit so you know that the order of multiplication does matter
the math problem http://www.imagesup.net/di-2142481773316.png
A:
Since $A = Y^{-1}XY$, $A^2 = (Y^{-1}XY)(Y^{-1}XY) = Y^{-1}X^2 Y$. So
$$\alpha A^2 + \beta A + \gamma I = Y^{-1}(\alpha X^2 + \beta X + \gamma I)Y = Y^{-1}0Y = 0.$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Angularjs tabs only for unique array elements using ng-repeat
I am new to Angularjs, so please bear with me. I have a response object where there are info some exam centers. In the response object the centers are from multiple cities. I want to create a bootstrap tab structure using Angularjs where all common city names will show as the tab header and all the centers under each city will come as tab content.
I am unable to figure out how should I go about it in Angularjs to display just the common city names as the tab header instead of showing all by using simple ng-repeat with some filter.
Sample response:
[{
"_id": "xx67576575ggg",
"name": "Center Name",
"city": "Delhi",
"location": "xyz, Delhi",
"logo": ""
},
{
"_id": "xx67888875ggg",
"name": "Center Name",
"city": "Mumbai",
"location": "xyz, Mumbai",
"logo": ""
},
{
"_id": "xx6733335ggg",
"name": "Center Name",
"city": "Kolkata",
"location": "xyz, Kolkata",
"logo": ""
},
{
"_id": "xx67576575ggg",
"name": "Center Name",
"city": "Delhi",
"location": "xyz, Delhi",
"logo": ""
},
{
"_id": "xx67576575ggg",
"name": "Center Name",
"city": "Mumbai",
"location": "xyz, Mumbai",
"logo": ""
}]
So here the tabs will show only tabs for Delhi, Mumbai, Kolkata once instead of two tabs for mumbai and Delhi.
A:
Modify the value into nested level(first city and then state).
Now you can just do ng-repeat over them.
I wrote a sample html how to use it.
<div>
<div ng-repeat="(key,val) in res" ng-click="show=!show">
<div>{{key}}</div>
<div ng-show="show" ng-repeat="center in res[val]">{{center.name}}</div>
</div>
</div>
var arr = [{
"_id": "xx67576575ggg",
"name": "Center Name",
"city": "Delhi",
"location": "xyz, Delhi",
"logo": ""
},
{
"_id": "xx67888875ggg",
"name": "Center Name",
"city": "Mumbai",
"location": "xyz, Mumbai",
"logo": ""
},
{
"_id": "xx6733335ggg",
"name": "Center Name",
"city": "Kolkata",
"location": "xyz, Kolkata",
"logo": ""
},
{
"_id": "xx67576575ggg",
"name": "Center Name",
"city": "Delhi",
"location": "xyz, Delhi",
"logo": ""
},
{
"_id": "xx67576575ggg",
"name": "Center Name",
"city": "Mumbai",
"location": "xyz, Mumbai",
"logo": ""
}]
var res= {}
arr.forEach((a) => {
if(typeof res[a.city] === 'undefined') {
res[a.city] = [a]
} else {
res[a.city].push(a)
}
})
console.log(res)
| {
"pile_set_name": "StackExchange"
} |
Q:
No Sound (Dummy Output) error Ubuntu 19.10
I am using Ubuntu 19.10 for few months. Suddenly voice output is not working. In-spite of trying reinstalling sound drives and tried all options despite that it is not working. Any inputs to it?
A:
For > 5.3.0-40 kernels, try adding:
"options snd-hda-intel dmic_detect=0" in the /etc/modprobe.d/alsa-base.conf.
and finally reboot the system.
This worked for me!
A:
Adding to Andrea Pavan's answer:
You can first add the variable to a new boot session and check if it works
Reboot your system. AT GRUB, choose Ubuntu and press E. You will be taken to command line options.
Locate the line beginning with Linux. Add the following parameter at the end of the line snd_hda_intel.dmic_detect=0
Press F10 to reboot.
After verifying this has indeed solved your sound issue, you can make this change permanently by performing the below steps
Run sudo gedit /etc/default/grub from terminal.
Locate the line beginning with GRUB_CMDLINE_LINUX_DEFAULT and append the above parameter to it. GRUB_CMDLINE_LINUX_DEFAULT="quiet splash snd_hda_intel.dmic_detect=0"
Save and Close gedit.
Run sudo grub-mkconfig -o /boot/grub/grub.cfg
Reboot.
When I was stuck with the same issue, the below link helped me resolve it.
https://superuser.com/questions/1509312/sound-stopped-working-after-upgrading-to-linux-5-4-intel-hd-audio?newreg=2fc5756bbf694e12b60ef3601f2e2411
| {
"pile_set_name": "StackExchange"
} |
Q:
PrintDocument not printing correct font size in Printing Paper
I am using PrintDocuemnt class to printing records.At run time I am providing fontsize but I getting small size of letter on printing paper.
Function 1:Which calling CreateCheckFormatForCheckWriter method with Details object objTCWLDetailLayout and Current selected object
List<Image> StringToPrint=new List<Image>;
Image objInput = objCWLayout.CreateCheckFormatForCheckWriter(objTCWLDetailLayout, objCWPrintCheck);
StringToPrint.Add(objInput);
Function 2:Which call method CreateCheckFormatForCheckWriter()
Image objCheckImage1 = null;
Graphics g = this.CreateGraphics(); // edited by jeet - assigned this.CreateGraphics()
g.SmoothingMode = SmoothingMode.AntiAlias;
g.TextRenderingHint = TextRenderingHint.AntiAlias;
Brush P = new SolidBrush(Color.Black);
Pen pen = new Pen(Color.Black);
Draw_Check8_StringCompName(objGlobalRulerbitmapData, g, P, i, objCWPrintCheck.ChkCompanyName);
Function 3:Call Draw_Check8_StringCompName() method
private void Draw_Check8_StringCompName(List<TCWLDetail> objGlobalRulerbitmapData, Graphics g, Brush P, int i, string strVal)
{
try
{
string fontFace = ("Vedana");
int fontSize = 6;
Font drawFont = new Font(fontFace, fontSize);
float XCB = horizontalRuler.ScaleValueToPixel(objGlobalRulerbitmapData[i].FX);
float YCB = verticalRuler.ScaleValueToPixel(objGlobalRulerbitmapData[i].FY);
// float YCB = verticalRuler.ScaleValueToPixel((objGlobalRulerbitmapData[i].FY <=(float) 0.1 ?(float) 0.325 : objGlobalRulerbitmapData[i].FY));
string sTemp = strVal;
g.DrawString(sTemp, drawFont, P, XCB, YCB);
}
catch (Exception ex)
{
CusException cex = new CusException(ex);
cex.Show(MessageBoxIcon.Error);
}
}
And Finally We set image on PrintDocument.StringToPrint is List type collection.
private void PrintDocument_PrintPage(Object sender, PrintPageEventArgs e)
{
try
{ //Set image from StringToPrint collection
e.Graphics.DrawImage(StringToPrint[PageCounter], 6, 12, 816, 1256);
//PageCounter++;
//e.HasMorePages = (PageCounter != StringToPrint.Count);
}
catch (Exception ex)
{
CusException cex = new CusException(ex);
cex.Show(MessageBoxIcon.Error);
}
}
A:
You're setting the PaperSize, not the actual font size itself. Either you didn't provide the code which draws the text on your PrintDocument, or the font (type/size/etc) is never set. If you use Graphics.DrawString to draw text, you can set the font (and its size).
| {
"pile_set_name": "StackExchange"
} |
Q:
ValidateServerCertificate - ServerCertificateValidationCallback
I am using the below code for certificate validation.
System.Net.ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf ValidateServerCertificate)
Public Shared Function ValidateServerCertificate(ByVal sender As Object, ByVal certificate As X509Certificate, ByVal chain As X509Chain, ByVal sslPolicyErrors As Net.Security.SslPolicyErrors) As Boolean
If sslPolicyErrors = Net.Security.SslPolicyErrors.None Then
Return True
End If
Return False
End Function
I am getting RemoteCertificateChainErrors. How to resolve it.
A:
Your callback isn't doing anything different to the system default validation. The value of sslPolicyErrors will give an indication as to what the failure is, and you can query the properties of the certificate, chain and sender to decide whether you want to override the failure by returning true.
| {
"pile_set_name": "StackExchange"
} |
Q:
Update Envoy Dockerfile base image to python 3.6+
I try to update the python version in the envoy base image to python-3.6. But it doesn’t work.
Here is the base image I have to use (Envoy Proxy) which have python-3.5.2 by default
https://github.com/envoyproxy/envoy/blob/master/ci/Dockerfile-envoy-image
FROM ubuntu:16.04
RUN apt-get update \
&& apt-get upgrade -y \
&& apt-get install -y ca-certificates \
&& apt-get autoremove -y \
&& apt-get clean \
&& rm -rf /tmp/* /var/tmp/* \
&& rm -rf /var/lib/apt/lists/*
...
Here is my version with the deadsnake/ppa apt-get update
FROM envoyproxy/envoy:latest
RUN apt-get update && apt-get -q install -y \
curl \
software-properties-common \
python-software-properties
RUN add-apt-repository ppa:deadsnakes/ppa
RUN apt-get update && apt-get -q install -y \
python3.6 \
python3-pip
RUN python3 --version && pip3 --version
RUN pip3 install gunicorn
ENV LANG C.UTF-8
ENV LC_ALL C.UTF-8
COPY requirements.txt .
RUN pip3 install --no-cache-dir -r ./requirements.txt
RUN mkdir /code
WORKDIR /code
COPY . /code
ADD ./boot.sh /usr/local/bin/boot.sh
RUN chmod u+x /usr/local/bin/boot.sh
ENTRYPOINT /usr/local/bin/boot.sh
Thank you very much your help or some hints to find the solution by myself.
A:
So I updated the Dockerfile with @pbacterio suggestion and it works now! Thank you very much
FROM envoyproxy/envoy:latest
RUN apt-get update && apt-get -q install -y \
curl \
software-properties-common \
python-software-properties
RUN add-apt-repository ppa:deadsnakes/ppa
RUN apt-get update && apt-get -q install -y \
python3.6 \
python3-pip
RUN curl https://bootstrap.pypa.io/get-pip.py | python3.6
RUN python3.6 --version && pip3.6 --version
COPY requirements.txt .
RUN pip3.6 install --no-cache-dir -r ./requirements.txt
RUN pip3.6 install gunicorn
ENV LANG C.UTF-8
ENV LC_ALL C.UTF-8
RUN mkdir /code
WORKDIR /code
COPY . /code
ADD ./boot.sh /usr/local/bin/boot.sh
RUN chmod u+x /usr/local/bin/boot.sh
ENTRYPOINT /usr/local/bin/boot.sh
| {
"pile_set_name": "StackExchange"
} |
Q:
Why was my account suspended 2 times?
I have my account in Stack Overflow. https://stackoverflow.com/users/2909797/monika
But one moderator Andrew Barber suspending my accounts 2 times. I like this site so much. But I am not getting the real reason for this. I analyzed that this moderator Andrew Barber also puts most of users' questions and answers on hold. Please look into my request other moderators. I want to know real reason behind my account suspension.
A:
Why my account suspened 2 times?
Seriously?
Because of blatant, continued plagiarism. As the "suspended" message says in your profile. Plagiarism is wildly copy & pasting stuff you didn't write and pasting it into answers. That's not acceptable on Stack Overflow, nor anywhere else really.
Just checking your first 8 highest-voted answers:
This answer stolen 100% from this MSDN answer (10k+ rep only)
This answer stolen 100% from here (10k+ rep only)
Oh wow, an original contribution!
This answer from this MSDN Article (10k+ rep only)
This answer from this answer (10k+ rep only)
OK, actually attributed a source here (but it's still not really an answer)
... and apparently, many many more that moderators have already deleted.
A:
You've been contacted by moderators a dizzying five times about your posts, and (as you note) suspended twice. Prior to going on a rant about the moderator, had you considered reading the messages that were sent to you describing the problem?
If you can't find those messages (you get copied via email as well), contact us and we'll make sure you get a copy. If you're having difficulty understanding what the moderators have been trying to tell you, contact us, we'll do our best to explain it.
Barring that, I'm considering this matter closed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Looping a raster stack with a step, R
I have a large raster stack of about 500 rasterlayers.
What I want to do is to extract specific layers and store them in a different strack.
The layers for which I am interested in, have a step of 8 (e.g. I want layers 1,9,17,25,...).
I have tried to do this with the following loop but I get Error in compareRaster(x, value) : different extent.
What is wrong with my code?
new<-stack()
for (i in seq(1,500,8)){
new[[i]]<-old[[i]]
}
I managed to solve this by setting new as list() instead of stack().
Can someone explain to me the error?
A:
You can extract multiple layers by subsetting. Test:
Make a stack of six rasters:
> r = raster(matrix(1:12,3,4))
> s = stack(r,r,r,r,r,r)
> s
class : RasterStack
dimensions : 3, 4, 12, 6 (nrow, ncol, ncell, nlayers)
resolution : 0.25, 0.3333333 (x, y)
extent : 0, 1, 0, 1 (xmin, xmax, ymin, ymax)
coord. ref. : NA
names : layer.1, layer.2, layer.3, layer.4, layer.5, layer.6
min values : 1, 1, 1, 1, 1, 1
max values : 12, 12, 12, 12, 12, 12
Get the odd-numbered ones:
> s[[c(1,3,5)]]
class : RasterStack
dimensions : 3, 4, 12, 3 (nrow, ncol, ncell, nlayers)
resolution : 0.25, 0.3333333 (x, y)
extent : 0, 1, 0, 1 (xmin, xmax, ymin, ymax)
coord. ref. : NA
names : layer.1, layer.3, layer.5
min values : 1, 1, 1
max values : 12, 12, 12
returning a stack with three layers.
In your case you have to create the vector from 1 to 500 in steps of 8, for which you can use seq(1,500,by=8) and its done.
Your error occurs because your empty initial stack has no structure and R doesn't like it:
> new=stack()
> new[[1]]=r
Error in compareRaster(x, value) : different number or columns
>
If you initialise the stack with a raster of the right size you can then add more rasters to it, but you can't start with an empty stack:
> new=stack(r)
> new[[2]]=r
> new[[3]]=r
> new[[4]]=r
> new
class : RasterStack
dimensions : 3, 4, 12, 4 (nrow, ncol, ncell, nlayers)
| {
"pile_set_name": "StackExchange"
} |
Q:
Can't extract information of a file
I am trying to do a script in Python that reads a file (A.out) and when it detects a keyword starts copying the file A.out into B.out.
The file A.out is something like:
CYCLE: 194 TIME: 0.025 TIME LEFT: 2.00D GRAD.: 1.872 HEAT: -420.1845
CYCLE: 195 TIME: 0.025 TIME LEFT: 2.00D GRAD.: 2.232 HEAT: -420.1653
CYCLE: 196 TIME: 0.025 TIME LEFT: 2.00D GRAD.: 1.981 HEAT: -420.1703
EXCESS NUMBER OF OPTIMIZATION CYCLES
CURRENT VALUE OF GRADIENT NORM = 1.890706
CURRENT VALUE OF GEOMETRY
C -2.05768505 +1 4.28867630 +1 0.07135650 +1
O -0.75590874 +1 4.69719052 +1 -0.38910531 +1
H -0.78776710 +1 4.91862889 +1 -1.39007889 +1
C -2.73026659 +1 3.32072929 +1 -0.89832955 +1
# it ends here
The script i made is supposed to find the "CURRENT VALUE OF GEOMETRY" and 4 lines later start copying info from "A" to "B". But it is not working.
The code is:
import os
from os.path import exists, splitext
def out_to_mop_let (fileA, fileB, keywords=""):
fileA="A.out"
fileB="B.out"
filein=open(fileA, "r")
fileout=open(fileB, "w")
lines = filein.readlines()
filein.close()
lstart = None
lfinish = None
for lindex in range(0,len(lines)):
if lindex-4>lstart and lines[lindex]=='\n' and lfinish==None and lstart!=None:
lfinish=lindex+1
if " CURRENT VALUE OF GEOMETRY" in lines[lindex]:
lstart=lindex
print lstart
print lfinish
fileout.write(keywords + "\n\n\n")
for lindex in range(lstart+4,lfinish):
fileout.write(lines[lindex])
fileout.close()
filein.close()
But when I execute it, the terminal returns:
for lindex in range(lstart+4,lfinish):
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
I don't know how to fix it. Any help?
A:
This is a bit shorter and more pythonic:
with open('A.out') as fin, open('B.out', 'w') as fout:
for line in fin:
if line.strip() == 'CURRENT VALUE OF GEOMETRY':
break
for line in fin:
if line.strip():
fout.write(line)
Explanation
It is recommend to use the with statement when for opening files.
This create a so called context. As soon as you dedent, i.e. leave the context, the file will be automatically close.
Here, I open both files, the source and the destination, with one with statement.
Both will closed upon leaving the context.
A file object is an iterator and allows direct iteration with a for loop.
Use line.strip() to get rid of any leading and trailing white spaces.
As soon as you see CURRENT VALUE OF GEOMETRY on a cleaned line, change into a different mode and start copying all non-empty lines from A.out to B.out.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does electric potential decreases along the direction of electric field?
I've been reading about Equipotential Surfaces and I came across this statement which I'm not able to understand conceptually. Does it's mathematical proof has something related to $\mathrm d V = -E.\mathrm d r$?
Any help would be appreciated.
A:
A unit positive charge will have a force on it due to the electric field in the direction of the electric field.
In moving in that direction from position $A$ to position $B$ the electric field does work on the positive charge $\displaystyle \int ^B_A E(x)\, dx$ and this is a positive quantity.
By definition the difference in potential in going from position $A$ to position $B$ is given by $V_{\rm B}-V_{\rm A} = -\displaystyle \int ^B_A E(x)\, dx$.
As the integral is positive it means that $V_{\rm B}-V_{\rm A}$ is negative ie $V_{\rm A}>V_{\rm B}$
In effect the unit positive charge is going down a potential slope.
Another relationship which can be used is $E \,\hat x = - \dfrac{dV}{dx} \hat x$.
If $E$ is positive it means that the potential gradient, $\dfrac{dV}{dx}$, the rate of change of potential with position, is negative ie the potential is decreasing with increasing $x$.
| {
"pile_set_name": "StackExchange"
} |
Q:
Radio input not working with localStorage
Radio input not working with localStorage
I used localStorage for many examples and work with me good except starRating.
Here is example example
I tried many codes , but does not work
Please give me example. Sorry I'm newbie.
<table>
<thead>
<tr>
<th STYLE="width:200px">link</th>
<th STYLE="width:200px">rating</th>
<th STYLE="width:200px">Options</th>
</tr>
</thead>
<tr>
<td>
<A CLASS="flink" HREF="https://www.google.com" TARGET="_blank">site a</A>
</td>
<td>
<span class="starRating">
<input CLASS="inputrating" CHECKED id="rating_9_5" type="radio" name="rating_9" value="5">
<label for="rating_9_5">5</label>
<input CLASS="inputrating" id="rating_9_4" type="radio" name="rating_9" value="4">
<label for="rating_9_4">4</label>
<input CLASS="inputrating" id="rating_9_3" type="radio" name="rating_9" value="3">
<label for="rating_9_3">3</label>
<input CLASS="inputrating" id="rating_9_2" type="radio" name="rating_9" value="2">
<label for="rating_9_2">2</label>
<input CLASS="inputrating" id="rating_9_1" type="radio" name="rating_9" value="1">
<label for="rating_9_1">1</label></span>
</td>
<td>
add
</td>
</tr>
<tr>
<td>
<A CLASS="flink" HREF="https://www.google.com" TARGET="_blank">site b</A>
</td>
<td>
<span class="starRating">
5
4
3
2
1
add
$(".starRating").on("click", function(){
selected_rating = $('input', this).data("inputrating");
selected_id = $('input', this).data("rating-id");
console.log(selected_rating)
});
A:
You need to change your event binding to the Radio Buttons, not the spans that contain them.
Next, you need to access the values of the radio buttons, rather than using the jQuery .data() method, which I'm not sure what you are doing with.
this.value
In the event handler is all you need for that.
Next, you need to actually store the values, which you didn't have any code for:
if(window.localStorage){
localStorage.setItem("Site A Rating", this.value);
} else {
console.log("localStorage not supported.");
}
Here is a working Fiddle: https://jsfiddle.net/6jfey3cj/4/
And a screen shot showing the different site's ratings in localStorage.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mongodb aggregate on filter like subdocument
First of all, sorry for my poor English.
If we have below documents in MongoDB,
Test data
{id:1, filter:{f1:'v1-1', f2:'v2-1', f3:['v3-1', 'v3-3']}}
{id:2, filter:{f1:'v1-1', f2:'v2-2', f3:['v3-2', 'v3-3']}}
{id:3, filter:{f1:'v1-1', f2:'v2-2', f3:['v3-1', 'v3-3']}}
Prepare the collection
db.test.drop()
db.test.insert({id:1, filter:{f1:'v1-1', f2:'v2-1', f3:['v3-1', 'v3-3']}})
db.test.insert({id:2, filter:{f1:'v1-1', f2:'v2-2', f3:['v3-2', 'v3-3']}})
db.test.insert({id:3, filter:{f1:'v1-1', f2:'v2-2', f3:['v3-1', 'v3-3']}})
You can consider the filter field as filter function that used on many shopping sites, for example, they will tell you how many LED TVs and how many LCD TVs on the site.
I want to use MongoDB to calculate how many documents with each filter option (include every item in the array field), the expected result is as below.
Expected result
[
{
_id : { key: 'f1', value: 'v1-1' }, count: 3
},
{
_id : { key: 'f2', value: 'v2-1' }, count: 1
},
{
_id : { key: 'f2', value: 'v2-2' }, count: 2
},
{
_id : { key: 'f3', value: 'v3-1' }, count: 2
},
{
_id : { key: 'f3', value: 'v3-2' }, count: 1
},
{
_id : { key: 'f3', value: 'v3-3' }, count: 3
}
]
It's easy to get the result by using map/reduce,
Map/Reduce solution
map = function () {
for (k in this.filter) {
if (this.filter[k] instanceof Array) {
for (j in this.filter[k]) {
emit( { key: k, value: this.filter[k][j]}, 1 );
}
} else {
emit( { key: k, value: this.filter[k]}, 1 );
}
}
}
reduce = function (k, values) {
result = 0;
values.forEach( function(v) { result += v; } );
return result;
}
db.test.mapReduce(map, reduce, {out:{inline:1}})
But as the performance problem with map/reduce, it can't be used for real time query. and the result set may be changed if I add some query conditions, so I can't save the map/reduce result into another collection for real time query.
And I can use aggregate framework to calculate the count for one filter,
Aggregate solution for only one filter
db.test.aggregate(
{$project: {"filter.f2":1, "_id":0}},
{$group: {"_id": {"key": {$ifNull: [null, "f2"]}, "value":"$filter.f2"}, "count" : {$sum: 1}}}
)
[
{
"_id" : { "key" : "f2", "value" : "v2-2" }, "count" : 2
},
{
"_id" : { "key" : "f2", "value" : "v2-1" }, "count" : 1
}
]
But I don't know how to do it for all filter options. Any idea?
A:
If you change your data structure to something like this, note that all the values are arrays, even the ones with single values:
{
_id: 1,
filters: [{
key: 'f1',
values: ['v1-1']
},{
key: 'f2',
values: ['v2-1']
},{
key: 'f3',
values: ['v3-1', 'v3-3']
}]
}
{
_id: 2,
filters: [{
key: 'f1',
values: ['v1-1']
},{
key: 'f2',
values: ['v2-2']
},{
key: 'f3',
values: ['v3-2', 'v3-3']
}]
}
{
_id: 3,
filters: [{
key: 'f1',
values: ['v1-1']
},{
key: 'f2',
values: ['v2-2']
},{
key: 'f3',
values: ['v3-1', 'v3-3']
}]
}
You could do an aggregate function something like this:
db.test.aggregate({
$unwind: "$filters"
},{
$project: {
_id: 1,
key: "$filters.key",
values: "$filters.values"
}
},{
$unwind: "$values"
},{
$group: {
_id: {
$concat: ["$key","|","$values"]
},
count: { $sum: 1 }
}
})
You could probably skip the project step if you want, I just put it in there as a nicety. You'll need two unwinds no matter what though.
| {
"pile_set_name": "StackExchange"
} |
Q:
Double integrals for reconstructing probablistic model
I am trying to reconstruct this probabilistic model,
\begin{equation}
\begin{split}
\frac{1}{\mu}\int^{\infty}_{0}P(N \geq n\, |\, L=l, T=t)\,e^{-\frac{l}{\mu}} dl &= \frac{1}{(n-1)!\mu}\int^{\infty}_{0} \left\{ \int^{tl}_{0}e^{-y}y^{n-1}dy \right\}e^{-\frac{l}{\mu}}dl \\
&= \frac{1}{(n-1)!}\int^{\infty}_{0} e^{-\{1+1/(t\mu)\}y}y^{n-1}dy \\
&= \frac{1}{(1+1/(t\mu))^{n}} = \left(\frac{t\mu}{1+t\mu}\right)^{n}
\end{split}
\end{equation}
We know that $N$ follows a Poisson distribution. Such that,
\begin{equation}
P(N \geq n) = \frac{1}{(n-1)!}\int^{\lambda}_{0}e^{-x}x^{n-1}dx.
\end{equation}
and also that $L$ is gamma distribution parameter.
I know how to get (using integration by parts),
\begin{equation}
\frac{1}{(n-1)!}\int^{\infty}_{0} e^{-\{1+1/(t\mu)\}y}y^{n-1}dy = \frac{1}{(1+1/(t\mu))^{n}} = \left(\frac{t\mu}{1+t\mu}\right)^{n}
\end{equation}
But I have no idea how to get:
\begin{equation}
\frac{1}{(n-1)!\mu}\int^{\infty}_{0} \left\{ \int^{tl}_{0}e^{-y}y^{n-1}dy \right\}e^{-\frac{l}{\mu}}dl = \frac{1}{(n-1)!}\int^{\infty}_{0} e^{-\{1+1/(t\mu)\}y}y^{n-1}dy
\end{equation}
I have tried different methods of approach, by parts, substitution, but to no avail. Any help with this would be greatly appreciated!
A:
The left hand side of your expression is the Laplace transform of an integral from 0 to $tl$.
$\begin{align}
& \int_{0}^{\infty }{\left\{ \int_{0}^{tl}{{{e}^{-y}}}{{y}^{n-1}}dy \right\}}{{e}^{-\frac{l}{\mu }}}dl= \int_{0}^{\infty }{{{e}^{-\frac{l}{\mu }}}}\left\{ \int_{0}^{l}{{{e}^{-tp}}}{{(tp)}^{n-1}}tdp \right\}dl =\mu \mathfrak{L}(f)\left( \frac{1}{\mu } \right)
\end{align}$
where $\mathfrak{L}(f)$ is the Laplace transform of $f(y)={{e}^{-ty}}{{(ty)}^{n-1}}t$ and we have used the result that $\mathfrak{L}\left( \int_{0}^{l}{f(y)dy} \right)(s)=\frac{\mathfrak{L}\left( f \right)(s)}{s}$ for s = $\frac{1}{\mu}$.
Then
$\mathfrak{L}\left( f \right)\left( \frac{1}{\mu } \right)=\int_{0}^{\infty }{{{e}^{-\tfrac{y}{\mu }}}{{e}^{-ty}}{{(ty)}^{n-1}}tdy=}\int_{0}^{\infty }{{{e}^{-\tfrac{p}{t\mu }}}{{e}^{-p}}{{(p)}^{n-1}}dp=}\int_{0}^{\infty }{{{e}^{-\left( 1+\tfrac{1}{t\mu } \right)p}}{{p}^{n-1}}dp}$
and replace p with y to recover the right hand side of your integral equality.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the best way to figure out if an UPDATE, DELETE or INSERT occur for a trigger
I want to create a single trigger in MS SQL for INSERT, UPDATE and DELETE but I want to be able to simple extract the data without 3 IF statements
I want to do something like this:
DECLARE @PK int
SELECT @PK = COALESCE(i.PK, d.PK)
FROM inserted i, deleted d
This did not work but would like to know if I can do it in one query.
What are some alternatives?
A:
I ended up using a FULL OUTER JOIN
DECLARE @DataIWanted as varchar(255)
SELECT @DataIWanted = COALESCE(i.TheData,d.TheData)
FROM inserted i
FULL OUTER JOIN deleted d on d.PK=i.PK
The query above will be from the deleted table or the inserted/updated table. With the assumption that TheData is defined as NON NULL in the DB.
| {
"pile_set_name": "StackExchange"
} |
Q:
VirtualBox - How to dynamic RAM allocation for Guest OS
VirtualBox Graphic User Interface Version 4.1.2_Ubuntu r38459 (installed with Ubuntu Software Center)
Host OS: Ubuntu 11.10
Guest OS: Windows XP sp 3 (with guest additions installed)
I have search on Google about this topic but not find any help yet. I read some topic that say VirtualBox v 4 now support dynamic RAM allocation but I do not know how to enable this feature.
Can you show me how to enable it?
A:
The feature you are searching for is called Memory Ballooning: http://www.virtualbox.org/manual/ch04.html#guestadd-balloon
| {
"pile_set_name": "StackExchange"
} |
Q:
How to get the results of a HTML select on to a php script
Hello: I'm new to PHP and HTML What I want to do is simple: I create a combo box (select) using a php script. The options are created from a list of files in the server machine and it works just fine. However I would like to trigger a second script when the user actually selects something. Here is the code I wrote (minus all the headers and stuff):
<form method="post">
<select name="index" onchange="submit">
<optgroup>
<option value="nothing"> Elegir un Índice </option>
<?php
//Reading all files in a directory and creating a combo box
$profiles_path = '../perfiles/';
$profile_list = scandir($profiles_path);
for ($i = 1; $i <= count($profile_list); $i++){
$name = strtok($profile_list[$i], ".");
if ($name !== false){
$ext = strtok(".");
if ($ext === "perf"){
echo "<option value=\"$name _1\"> $name </option>";
}
}
}
?>
</optgroup>
</select>
</form>
<?php
$chosen = $_REQUEST['index'];
echo "The selected item is $chosen";
?>
Now the question is why is not working. I know is a newbie question but all the results I've found use JavaScript and I want to avoid doing that.
Thank you for any answer.
A:
Just change your select tag like following
<select name="index" onchange="this.form.submit()">
| {
"pile_set_name": "StackExchange"
} |
Q:
Rebasing my commits onto master without changing history
I have a feature branch and a master branch. My feature branch was checked out of the master branch but prior to some of the commits that are currently on the master branch.
I'd like to rebase my commits on top of the master branch, but I do not want the master's history changed, I'd like the rebase to apply all the commits in one fell swoop and maintain the integrity of the repo's history on any remote branches.
Is this possible with git rebase?
Doing this on master
git rebase feature-branch-name
replayed the masters history on my feature branch, which isn't what I intended.
A:
Yes this is possible, and you were very close on your attempt. You just need to reverse it.
From the feature branch, run this:
git rebase master
Note that you may be prompted to resolve merge issues during this process. Once that is done, you'll see that the most recent commits from master will appear in your feature branch, prior to any of the commits you had performed in your feature branch. Then, from the master branch, you can run this:
git merge feature-branch-name
That will result in the master branch having all of the commits from your feature branch. There are various options when merging. Please reference the git documentation if you don't like what you get from the defaults.
| {
"pile_set_name": "StackExchange"
} |
Q:
Java memory usage stays well within max heap size, but my system memory is slowly being eaten
I'm relatively new to Java programming so please bear with me trying to understand what's going on here.
The application I've developed uses a max heap size of 256MB. With the GC being done, I never run into any problems with this. The used heap builds up when a big image is loaded and gets freed nicely when it is unloaded. Out of memory errors are something that I've yet to see.
However... Running the application for about an hour. I notice that the process uses more and more system memory that never gets freed. So the application starts with around 160MB used, builds up as the heap size grows, but when the heap size shrinks the system memory used just keeps getting more. Up until the process uses 2.5GB and my system starts to become slow.
Now I'm trying to understand the surviving generations bit. It seems the heap size and surviving generations aren't really connected to each other? My application builds up a lot of surviving generations, but I never run out of memory according to the used memory by the application itself. But the JVM keeps eating memory, never giving it back to the system.
I've searching around the web, sometimes finding information that is somewhat useful. But what I don't get is that the application stays well within the heap size boundaries and still my system memory is being eaten up.
What is going on here?
I'm using NetBeans IDE on OSX Lion with the latest 1.6 JDK available.
A:
The best way to start would be jvisualvm from the JDK on the same machine. Attach to your running program and enable profiling.
Another option is to try running the application in debug mode and stop it once in a while to inspect your data structures. This sounds like a broken/weird practice but usually if you have a memory leak it becomes very obvious where it is.
Good luck!
| {
"pile_set_name": "StackExchange"
} |
Q:
Why don't mined blocks show up in my inventory on my Spigot server?
I have a simple Spigot server installed on a Rasperry Pi. So far so good. I log in and it works, until I realize that when I mine a block it never reaches my inventory. No dropped block. Nothing is left behind, except a void which used to be occupied. I have seen others with this problem, is it just a quick permissions/settings file fix, or is it intended. It is not on adventure, it says survival on the console window when starting up. It's really weird. I have tried mining on other Spigot servers powered by Pis, and it didn't work, yet the server admin put up a bunch of signs.
What do I have to do to configure the server to work correctly? Am I accidentally using a "unstable/uncompleted" build? (It says 1.6.4) Is this not a feature yet? Is there a mod that will fix this? Did the original admin of other servers use creative?
A:
When starting a new server, there is a property in server.properties called spawn-protection. On a standard server, the only users that can modify blocks within this region are ops.
You can make yourself an op by running this command on the server op playername. Alternatively, you can edit the ops.txt file directly and add your username to the list.
For more information about server properties, see here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Array only storing last variable when pushing from a JSON in React
I have the following JSON file called 'testing_numbers.json':
[{ "number":1,
"number":2,
"number":3,
"number":4,
"number":4,
"number":5,
"number":6,
"number":7,
"number":9,
"number":10,
"number":11}]
All I want to do is push each value to a list through a for loop, then append the list. My React code is like so:
import React, { Component } from 'react';
let values = require('./test_numbers.json');
class App extends Component {
state = { }
render() {
const numbers = []
for (var x in values) {
numbers.push(values[x].number)
}
return ( numbers );
}
}
export default App;
All I get as an output is the last variable in the JSON (which is 11), and not anything before that. It seems like I have something fundamentally wrong.
I am aware that I could just map the JSON first and then render it, but for my application, it would be better if I extracted data one at a time.
If anyone could help that would be great
A:
The problem isn't the loop, it's the JSON. Your JSON is an array with just one entry, which is a single object with eleven property definitions all using the same name. The result of parsing that JSON is an array with an object with a single property, whose value is the value from the last property definition using the name. You can't reuse the name number like that within the object, you need different names for the properties.
Perhaps you wanted the JSON to have an array with multiple objects in it:
[
{"number":1},
{"number":2},
{"number":3},
{"number":4},
{"number":4},
{"number":5},
{"number":6},
{"number":7},
{"number":9},
{"number":10},
{"number":11}
]
Separately: for-in isn't the correct tool for looping through arrays. See my answer here for your various options for what to use instead. For instance, if I'm right that you meant to have an array of eleven objects, then:
const numbers = values.map(entry => entry.number);
const values = [
{"number":1},
{"number":2},
{"number":3},
{"number":4},
{"number":4},
{"number":5},
{"number":6},
{"number":7},
{"number":9},
{"number":10},
{"number":11}
];
class App extends React.Component {
state = { }
render() {
const numbers = values.map(entry => entry.number);
return numbers; // No need for () around it
}
}
ReactDOM.render(
<App />,
document.getElementById("root")
);
.as-console-wrapper {
max-height: 100% !important;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.2/umd/react-dom.production.min.js"></script>
A:
There is no meaning of having same keys with different values in single object, an object should contain unique key names to simplify your case
Change the json to something like below
[1,2,3,4,5,6,7,8,9,10,11]
And
render() {
const numbers = []
for (var x in values) {
numbers.push(<span key={x}>{x}</span>);
}
return ( {numbers} );
}
Or simply
render() {
return (
{values.map(val => <span key={val}>{val}</span>)}
);
}
Or make it individual object for each number. But I don’t see any meaning of having same key with different number in each object instead keep them as array of numbers instead of objects
| {
"pile_set_name": "StackExchange"
} |
Q:
How to prove the minimal resolution of double rational points can be achieved by iterated blow-ups
In the Slodowy's survey on Kleinian singularities, there is a statement that the minimal resolution of Kleinian singularities can be obtained by iterated blow-ups, I want to know the detail of the proof of this claim.
And I also wonder that the how to blow up the variety we obtain after the first blow-up, since it is a subvariety of $\mathbb{A}^{n}\times\mathbb{P}^{n-1}$, should we treat it as a subvariety of $\mathbb{A}^{2n}$?
This is the link of the survey mentioned above :
http://perso.ens-lyon.fr/sandra.rozensztajn/enseignement/Slodowy.pdf
A:
First let's answer the second question : it doesn't make sense to embedd $\Bbb P^{n-1}$ in $\Bbb A^n$ (any morphism from a projective variety to an affine variety is constant). Over complex numbers, we can take a local chart and compute the blow-up in the local chart, it means that we can always suppose that the blow-up is in the affine space.
There is an elementary proof if your definition of Kleinian singularities is quotient $X = \Bbb C^2/ \Gamma$ where $\Gamma \subset \rm{SL}_2(\Bbb C)$ is a finite subgroup. Then, you just need to compute the equations of $X$ and compute explicitely the blow-up. Computing the blow-up is not hard, and computing the equations might be tedious especially for type $E$, but it's very easy for type $A$ and not too hard in type $D$.
If you use alternating definitions, the paper "Fifteen characterization of rational double points" by Durfee explains many characterizations of the Kleinian singularities, and prove their equivalence, in particular they are the only surfaces with a double point which can be resolved only using blow-up. But I am not sure he proves everything.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to perform unsigned to signed conversion in Java?
Say I read these bytes: "6F D4 06 40" from an input device. The number is a longitude reading in MilliArcSeconds format. The top bit (0x80000000) is basically always zero and is ignored for this question.
I can easily convert the bytes to an unsigned integer: 1876166208
But how do I convert that unsigned value into its final form of 31-bit signed-integer?
So far all I've come up with is:
if value & 0x40000000 then it's actually negative, need to convert it
If it's negative, strip the top bit and do something with the remaining bits...
So I can tell if it's a negative number, but in order to know what value the negative number is, I have to do something with the remaining bits - a one's compliment? How do I do that in Java?
Another way to put the question is, how do I convert an unsigned integer into a 31-bit signed integer in Java?
Thank you!
A:
The answer depends on what the lower 31 bits of your input are meant to represent.
int input = 0x6FD40640 & 0x7FFFFFFF; //strip top bit; only here for clarity
Unsigned input: 0x6FD40640 == 1876166208
Two's complement (desired output: -271317440)
A two's complement integer is one where -1 has all bits set, and lower negatives number count down from there. The first bit still acts as a sign bit.
1000 -> -8
1001 -> -7
...
1110 -> -2
1111 -> -1
0000 -> 0
0001 -> 1
If the lower 31 bits represent a two's complement integer, then I think you should just be able to do this:
input = (input << 1) >> 1;
That's because Java stores integers in two's complement internally: all we do is shift left and then shift back right (signed) so that the sign bit is picked up and the integer goes from 31 bits to 32 bits.
One's complement (desired output: -802424384)
A one's complement number representation is one where the first bit is a dedicated sign bit, and the remaining bits represent the magnitude. The lower bits of -100 will be the same as the lower bits of 100:
1111 -> -7
1110 -> -6
...
1001 -> -1
1000 -> -0 (anomoly)
0000 -> 0
0001 -> 1
If the lower 31 bits represent a one's complement integer (that is, a sign bit followed by 30 bits representing an unsigned magnitude), then you need to convert it into two's complement so that Java extracts the value properly. To do this you just need to extract the lower 30 bits and multiply by -1:
if ( input & 0x40000000 ) {
input = (input & 0x3FFFFFFF) * -1;
}
You said in the question's comments that after converting to degrees (dividing by 3600000) you get around -75.36. When I divide -271317440 by 3600000 I get -75.36595555555556, so I'm guessing your input format is two's complement, so my first and original answer was correct.
| {
"pile_set_name": "StackExchange"
} |
Q:
Unable to get PHP script name using REGEX
I am having quite the challenge. I have my function where() which tracks where users are visiting on the site, and takes the script filename and provides a description and inserts into database.
The script was working great, until recently, and unaware of the failure of this function after a recent minor update from MySQL 5.6.40 to 5.6.47
I am not sure if that had anything to do with it, but I discovered days later that it was not working anymore.
Our function:
function where($scriptname = "index", $userid, $update=1){
if (!is_valid_id($userid))
die;
if (preg_match("/details.php/i", $scriptname))
$where = "Browsing File Details (ID $_GET[id])";
elseif (preg_match("/files.php/i", $scriptname))
$where = "Browsing Files";
elseif (preg_match("/account-info.php/i", $scriptname))
$where = "Browsing Account Info (ID $_GET[id])";
elseif (preg_match("/upload.php/i", $scriptname))
$where = "Uploading File";
elseif (preg_match("/account.php/i", $scriptname))
$where = "Browsing User Control Panel";
elseif (preg_match("/search.php/i", $scriptname))
$where = "Searching For Files";
elseif (preg_match("/forums.php/i", $scriptname))
$where = "Viewing Forums";
elseif (preg_match("/index.php/i", $scriptname))
$where = "Browsing Homepage";
elseif (preg_match("/mailbox.php/i", $scriptname))
$where = "Viewing Messages";
elseif (preg_match("/comments.php/i", $scriptname))
$where = "Viewing Comments";
elseif (preg_match("/recover.php/i", $scriptname))
$where = "Recovering Account";
elseif (preg_match("/bookmarks.php/i", $scriptname))
$where = "Viewing Bookmarks";
elseif (preg_match("/getfile.php/i", $scriptname))
$where = "Downloaded File (ID $_GET[id])";
elseif (preg_match("/faq.php/i", $scriptname))
$where = "Reading FAQ Page";
elseif (preg_match("/friends.php/i", $scriptname))
$where = "Viewing Friends";
elseif (preg_match("/admin.php/i", $scriptname))
$where = "Managing Admin Panel";
else
$where = "Unknown Location";
if ($update) {
// Worked until a few days ago. No site changes were made prior for quite some time.
//$query = sprintf("UPDATE users SET page=".sqlesc($where)." WHERE id ='%s'", mysql_real_escape_string($userid));
// Now using line below, which does insert into row if I use my own variable.
$query = "UPDATE users SET last_access='" . get_date_time() . "', page=" . sqlesc($where) . " WHERE id=" . $userid;
$result = SQL_Query_exec($query);
}
return $where;
}
Now, I have tried the following code to narrow it down to what is causing it. Currently, the function above only inserts
Unknown Location
to the Database, no matter what page is viewed.
I got it down to this:
$stringtest = "This inserts into database!";
$query = "UPDATE users SET last_access='" . get_date_time() . "', page=" . sqlesc($stringtest) . " WHERE id=" . $userid;
This works great, however it is not passing any of the $where conditions.
I've tried varies regular expressions for filename matching to no avail.
Any idea what I'm doing wrong?
Thanks in advance!
A:
For the SQL part use prepared statements, as noted above.
Assuming, the $scriptname holds filename, without extension, and not the absolute path, and based on the code provided I don't see great need for preg_match() there. Just simple switch ... case would do.
Even better, if you want to have a sort of manageable list of locations with descriptions (you reuse them every time anyway), you could had associative array (could be returned by a separate function) like below and do as follows:
$locations = array(
'index' => 'Browsing Homepage',
'forums' => 'Browsing Homepage,
// and so on for all of your files
);
// And to get the description - assuming case matters, otherwise use strtolower()
$desc = isset($locations[$scriptname]) ? $locations[$scriptname] : 'Unknown Location';
| {
"pile_set_name": "StackExchange"
} |
Q:
Padding and removing white in css
New to the world of html and css, and currently making my own one page website.
I'm having a couple of issues with padding and removing white in css.
Firstly, i can't remove the block of white between the first page and second... Before i entered any text on the second page, it was fine? But now that some has been implemented onto the page, it has appeared?
Secondly, how does one push text right? I have a title in my nav bar, but it's not included in the unordered list? Have i set out my html correctly? Can css fix this? I've tried changing a few things on the html, but it just makes the situation even worse.
[
HTML
<!DOCTYPE html>
<html>
<head>
<link href="./Style.css" type="text/css" rel="stylesheet">
<title> George Gilliland </title>
</head>
<body>
<div class = "Title-Page">
<div class = "Nav">
<ul>
<li><a href="#About-Me">About Me</a></li>
<li><a href="#Projects">Projects</a></li>
<li><a href="#Contact">Contact</a></li>
</ul>
</div>
<h1 id = "Title"> George Gilliland </h1>
</div>
</div>
<div id = "About-Me">
<p>
Lorem ipsum dolor sit amet, ea nec oportere torquatos, has sumo <br>
hinc vide et. In has aliquip eruditi, quis dicam sit ut.Tota
gubergren
</p>
</div>
<div id = "Projects">
</div>
<div id = "Contact">
</div>
</body>
</html>
CSS
@import url('https://fonts.googleapis.com/css?family=Poiret+One');
a:link {
text-decoration: none;
}
a:visited {
color: white;
}
.Nav {
border:1px solid #ccc;
border-width:1px 0;
font-family: Poiret One;
position: fixed;
top: 0;
width: 100%;
padding-right: 50cm;
}
.Nav ul {
text-align: right;
}
.Nav li{
display:inline;
}
.Nav a {
display:inline-block;
padding:10px;
}
body, html {
height: 100%;
}
body {
margin: 0;
padding: 0;
width: 100%;
}
.Title-Page {
background-image: url("Images/Campeche.jpg");
background-position: center;
background-repeat: no-repeat;
background-size: cover;
height: 100%;
}
#Title {
font-family: Poiret One;
color: white;
font-size: 60px;
position: fixed;
margin-top: 0;
}
#About-Me {
background-color: #00818f;
height: 100%;
}
h2.Font {
font-family: Nixie One;
}
#About-Me p {
padding:90px;
font-size:25px;
color:white;
height:120px;
}
A:
You can set a margin top of 0px on your about me P. See the codepen and code below.
#About-Me p {
padding:90px;
font-size:25px;
color:white;
height:120px;
margin-top: 0px;
}
https://codepen.io/BobDempsey/pen/QaBGvz
| {
"pile_set_name": "StackExchange"
} |
Q:
How to send elements of array as separate lines in email message in asp.net with C#
I have an application where I will need to send an email in html format to
individuals who place an order.
The order items are placed in a database, and are to be retrieved
and then sent to the client who placed the order in this format:
The format of the email should be in this format:
The items you ordered are:
Dishwasher
Laptop
Ironing Board
Xbox 360
I am stuck on how to get this format. Seeing my array already exists, i believe it should be
something like
for (int i=0;i<array.length;i++)
{
messagebody+="<br/>"+array[i]
}
client.Send(msg);
Am i on the right track?
A:
You could avoid the whole for/foreach loop using the string.Join method:
string[] arr = { "one", "two", "three" };
string messageBody = string.Join("<br/>", arr);
| {
"pile_set_name": "StackExchange"
} |
Q:
Sqlite replace and foreign keys in Android
I have the following table structure:
Table Days: [_id,date,name]
^
|
Table Events: [_id, day_id ,description]
The foreign key day_id is set to ON DELETE CASCADE
I want to "insert or update" the day 2. So I make:
ContentValues values= new ContentValues();
values.put("_id",2);
values.put("date,"...");
values.put("name","welcome");
mDb.replace("days",null,values);
The problem is that if the day_id=2 already exists (in my case is the most probably option) the DBengine deletes the table and inserts a new row so all the events associated to that day are also deleted.
This solution works but its very sub-optimal right?
try {
mDb.insertOrThrow("days", null, values);
} catch (Exception e) {
mDb.update("days", values, "_id=2", null);
}
Whats the correct sollution for that problem
A:
You should add your reference as below in order to allow SQLite to delete or update the referenced column automatically.
FOREIGN KEY [_id] REFERENCES [days] ON DELETE CASCADE ON UPDATE
CASCADE
| {
"pile_set_name": "StackExchange"
} |
Q:
css - vertical space being added on elements with display:inline-block
I've got a series of thumbnail container elements with the css property display:inline-block but when they line up next to each other, the second element has more space at the top than the first (see attached image). Any idea why this happens? Is there a better way to line these elements up next to each other? I know that floating them solves this issue, but it seems like floating isn't the best way to go about this.
Here's my code:
HTML:
<article class="thumb_container">
<div class="thumb_content">
<img src="images/perlin.jpg" alt="Perlin Lines" class="thumb_img"/>
<header class="thumb_header">Perlin Lines</header>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eget lectus ac libero iaculis interdum nec id tortor. quis, ullamcorper id nisi. Etiam ut.
<a href="#">More...</a>
</p>
</div>
</article>
<article class="thumb_container">
<div class="thumb_content">
<img src="images/branching.gif" alt="Branching" class="thumb_img"/>
<header class="thumb_header">Branching</header>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent eget lectus ac libero iaculis interdum nec id tortor. quis, ullamcorper id nisi.
<a href="#">More...</a>
</p>
</div>
</article>
CSS:
.thumb_container { display: inline-block; margin-left: 20px; width:220px; background: #fff; -moz-box-shadow: 1px 1px 1px rgba(10, 72, 90, 0.2); -webkit-box-shadow: 1px 1px 1px rgba(10, 72, 90, 0.2); box-shadow: 1px 1px 1px rgba(10, 72, 90, 0.2); }
.thumb_container:first-child { margin-left: 0px; }
A:
Just add vertical-align: top where you have display: inline-block.
More info here: Why aren't these elements with display:inline-block properly aligned?
| {
"pile_set_name": "StackExchange"
} |
Q:
How to load value to textarea with php echo
Im trying to load a value to an textarea.
I have the variable with the value on the php foreach on the top of the page, and I want to load it into a textarea.
Code from the foreach:
<?php
foreach($tasks as $cl)
{
$cl_nome=$cl['nome'];
$cl_data_nascimento=$cl['data_nascimento'];
$cl_peso=$cl['peso'];
$cl_altura=$cl['altura'];
$cl_tipo_sangue=$cl['tipo_sangue'];
$cl_alergias=$cl['alergias'];
$cl_doencas=$cl['doencas'];
$cl_telefone=$cl['telefone'];
$cl_morada=$cl['morada'];
$cl_notas=$cl['notas'];
$cl_seguro=$cl['seguro'];
$cl_identificador=$cl['identificador'];
}
?>
Code to the textarea:
<div class="form-group">
<label for="textarea">Doenças:</label>
<textarea class="form-control" rows="2" id="doencas" name="doencas" value="<?php echo $cl_doencas?>"></textarea>
</div>
Can someone help me?
Thanks.
A:
The textarea does not have a value attribute, you load the data between the tags like this
<div class="form-group">
<label for="textarea">Doenças:</label>
<textarea class="form-control" rows="2" id="doencas" name="doencas">
<?php echo $cl_doencas; ?>
</textarea>
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
gulp src ignore files from all folder but one
This is my folder structure
views
|
- core
| |
| -core.module.js
| core.controller.js
| some.js
|
- home
|
-home.module.js
home.controller.js
somemore.js
...
...
and in my gulp file I want to include all js files from views folder recursively and exclude *.controller.js from all folders but the core
i.e select all js files from core folder and select all but *.controller.js from all other folders
I tried like below, but its excluding *.controller.js files from core folder too.
gulp.src([
//include all from all folders
'views/**/*.js',
//exclude *.controller.js from all folders but core (not working)
'!views/{**, !core}/*.controller.js'
])
A:
Use the !() glob pattern. From the glob documentation:
!(pattern|pattern|pattern) Matches anything that does not match any of the patterns provided.
So in your case you can do the following:
gulp.src([
'views/**/*.js',
'!views/!(core)/**/*.controller.js'
])
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.