id
stringlengths 3
6
| prompt
stringlengths 100
55.1k
| response_j
stringlengths 30
18.4k
|
---|---|---|
111206 | I'm creating a JSON webservice in CakePHP 1.3.
I want to be able to send AJAX requests from a different server to this webservice.
I know this is a cinch in Cake 2+, but I cannot for the life of me figure it out for v1.3. [Based on what I have found in the docs](http://book.cakephp.org/1.3/en/The-Manual/Core-Components/Request-Handling.html), I have attempted the following in my controller:
```
public $components = array('RequestHandler');
function beforeFilter() {
Configure::write('debug', 0);
$this->header('Access-Control-Allow-Origin','*');
$this->header('Access-Control-Allow-Methods','*');
$this->header('Access-Control-Allow-Headers','X-Requested-With');
$this->header('Access-Control-Allow-Headers','Content-Type, x-xsrf-token');
$this->header('Access-Control-Max-Age','172800');
}
```
This unfortunately results in `500 ERR_INVALID_RESPONSE`.
I have attempted to do `$this->response->header` instead of `$this->header`, and same problem. I've also attempted `header` instead of `$this->header`, and again I'm getting a server response of `500`. I have *also* attempted moving the `header` block into my action in the controller, into the top-level app\_controller.php file, into the bootstrap.php file, and into the view file itself (with every variation of `header`, `$this->header`, and `$this->response->header` attempted). Removing `Configure::write('debug', 0);` does not solve the issue.
Heck, I even have this in my `.htaccess` file:
```
<IfModule mod_headers.c>
<FilesMatch "\.(json)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
```
Although that doesn't seem to do anything. I have `mod_headers.load` in my mods-available folder in Apache as well.
Anyone know how to set the Access-Control-Allow-Origin header in CakePHP 1.3? | ```
header("Access-Control-Allow-Origin: *");
```
I know this is an old post but I jut want to answer this to help others. |
111279 | Some years ago, I picked up a Cannondale R3000 and moved all the components to my current bike as an exercise in bike building, never repeated (in fairness, the Cannondale fit me a little better but my beautiful 1998 Klein has such a sweet, sweet paint job...). I've been putting the frame on Craigslist off and on for a few years, but no one seems to want to pay what I'm asking. Regardless, my current MTB is an all-mountain beast that I bought before I knew my riding style, and I'm thinking of picking up a more cross-country steed.
Times being tight and all, is there anything preventing me from building out the Cannondale road frame as a mountain bike? Obvious [potential] answers (e.g., tire clearance) are good, more involved ones (e.g., frame robustness) are too. I'm trying to get a picture of what might lie ahead in this venture. | If you want to use it for "proper mountain biking" (however you define that) the answer is almost certainly no. You won't be able to fit wide enough tyres to give you decent grip, and punctures are likely to be a problem. Additionally, the geometry will be all wrong (if you put straight bars on it you'll probably feel quite cramped without a long stem, which will make the handling wierd). That's without getting into the strength issue - Cannondales have always seemed quite fragile to me (but that's an opinion only, never owned one).
However, if you want something for blasting along relatively smooth forest trails that aren't muddy, fit the widest grippiest tyres you can and give it a whirl. Despite what I said about strength in relation to proper mountain biking, road bikes are surprisingly strong provided the forces are applied to them in the way the bike is designed. A few small bumps are unlikely to break it assuming you're not a large rider, you don't try jumping and you don't crash. It'll be a very different experience from a proper mountain bike, but on the right trails could still be a lot of fun.
Ultimately though for proper cross country mountain biking you do need a mountain bike (or a cyclo cross bike). I'd suggest trying ebay with a reserve price to find out what people are prepared to pay for it. Second hand aluminium road bike frames aren't that desireable any more, even if they did have dura ace on them when purchased, simply because carbon frames are so much cheaper. However, second hand mountain bike frames are also pretty cheap, and a couple of hundred dollars towards one from selling the R3000 frame is infinitely more than nothing if it's just gathering dust.
Hope this helps. |
111770 | I am using Webdriver in Ruby and I want to locate an element by its xpath, below is an example html:
```
<li id="ID1">
<label for="accountNumber"> </label>
123456
<span id="accountNumber"></span>
</li>
```
How do I get 123456 by xpath or ID?
I have tried below and it does not work:
```
element = driver.find_element :xpath => "//li[@id='ID1']/"
puts element.text
```
Thanks. | Your database files are probably in /var/lib/mysql. If you have THOSE files backed up, with EXACTLY the same version of mysql, same libraries, etc., then you could just restore them to another machine, and check the configuration for hostnames (MySQL only uses these IN the database though, for login security, iirc, so it won't apply until you're up and running again). Then, just boot it up. Do keep a copy of the backed up /var/lib/mysql though, in case it fails to come up correctly. MySQL will probably repair some files on startup, which may not work properly.
Once you can do pgrep -l mysql (as root), and you see mysql running, then you can worry about installing a webserver, php, phpmyadmin, etc.
Next time, have proper, regular backups (mysqldump plus a filesystem backup using something like rdiff-backup, dirvish, or faubackup), use a redundant RAID filesystem, and maybe a data-checksummed filesystem on top, like ZFS. |
111798 | I am trying to repair a simple form which should be sending a simple email
I receive no javascript errors, but the ajax request is not fired. I seached a lot of answers here and in google, but none was helping my case.
Here the form html code
```
<form method="post" id="signupform">
<input type="text" name="name" id="name" placeholder="Nimi"><br>
<input type="email" name="email" id="email" placeholder="sähköposti@osoite.com"><br>
<p><a href="#" id="send"><b>Ilmoittaudu</b></a></p>
</form>
<div id="response"></div>
```
And this is the jquery validation and sending code:
```
<script>
/* <![CDATA[ */
$(document).ready(function(){
$("#countdown").countdown({
date: "13 october 2013 12:00:00", <!--set website launch date and time here-->
format: "on"
},
function() {
// callback function
});
var left = $('.newsletter').offset().left;
$("#subscribe").click(function(event){
$(".newsletter").show().animate({ left : left }, { duration: 1000 });
event.preventDefault();
return false;
});
$(".close1").click(function(event){
$(".newsletter").animate({ left : "110%" }, { duration: 1000 });
event.preventDefault();
return false;
});
$("#send").click(function(event){
event.preventDefault();
var cname = $("#signupform").find("#name").val();
var cemail = $("#signupform").find("#email").val();
var errcount=0;
if(cname.length < 1) {
$(this).parent().find("#name").addClass("error");
errcount = 1;
} else
$(this).parent().find("#name").removeClass("error");
var emailRegex = new RegExp(/^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$/i);
var valid = emailRegex.test(cemail);
if (!valid) {
$(this).parent().find("#email").addClass("error");
errcount = 1;
} else
$(this).parent().find("#email").removeClass("error");
if (errcount === 0 ) {
alert('noerror');
//form submitted succesfully
$.ajax ({
type: "POST",
url: 'send.php',
data: {
name: cname,
email: cemail
},
processData: false,
async: false,
success: function(response) {
alert('success');
if (response == 'Kaavake ei ole täytetty oikein') {
$('#response').html(response);
} else {
$('#response').html(response);
$('#response').fadeIn('slow');
}
},
error: function(xhr, text, error) {
alert(text);
alert(error);
}
});
} else {
return false;
}
});
$("a[data-rel^='prettyPhoto']").prettyPhoto({deeplinking:false});
$(window).resize(function(){
var height=$('.activeslide').height();
var sidebarheight=$('.sidebar').height();
$('.sidebar').css('min-height',height);
});
$(window).resize();
});
/* ]]> */
</script>
```
The alert with noerrors is shown, but not the alert with success, and I cannot see the ajax activity in the network of chrome dev-tools.
Here the code from send.php
```
<?php
$subject = "Uusi ilmoittautuminen";
$error = 0;
$sendto = 'email@yahoo.com';
print_r($_POST);
if (!empty($_POST)) {
//validate and strip user data
if (!empty($_POST['name'])) {
$name = htmlspecialchars(strip_tags($_POST['name']));
} else {
$error = 1;
}
if (!empty($_POST['email'])) {
$email = htmlspecialchars(strip_tags($_POST['email']));
} else {
$error = 1;
}
if ($error == 0) {
//SENDING SECTION
//prepare body
$namesender = 'Yhteydenotto';
$header = "MIME-Version: 1.0" . "\r\n".
"Content-type: text/plain; charset=utf-8" . "\r\n".
"From:Yhteydenotto < noreply@mail.com >\r\n" .
"Reply-To:".$name." <".$email.">\r\n".
"X-Mailer: PHP/" . phpversion();
$body = "Uusi ilmoittautuminen\n\nNimi: ".$name."\n\nSähköposti: ".$email."";
//prepare subject
$newsubject='=?UTF-8?B?'.base64_encode($subject).'?=';
//send email
$mailresult = mail($sendto, $newsubject, $body, $header);
die("<p>Kiitos ilmoittautumisestasi!</p>");
} else {
echo 'Kaavake ei ole täytetty oikein';
die;
}
} else { echo 'no direct access allowed'; }
``` | what does the `return false;` do after the success method? better remove that. furthermore you have semicolon after the `url: 'send.php';`it should be a normal comma.
Except that everything looks right.
For finding this kind of errors just check the console (i think) every browser enables you to use. There warnings and errors are logged.
<http://jsfiddle.net/EvXgZ/2/> there you have working version with just the addition that i had dto change the destination url to work on jsfiddle.
your ajax call should look like
```
$.ajax ({
type: "POST",
url: 'send.php',
data: {
'name': cname,
'email': cemail
},
async: false,
success: function(response) {
alert('success');
if (response == 'Kaavake ei ole täytetty oikein') {
$('#response').html(response);
} else {
$('#response').html(response);
$('#response').fadeIn('slow');
}
},
error: function(xhr, text, error) {
alert(text);
alert(error);
}
});
```
As a matter of fact this version works and all the confusion resulted of a `//` in front of the pasted code, which was additionally pasted in one line and therefore was never excuted. One more important thing to note is that if you develop and change your js-files, you always have to make sure that they are cleared from the cache so you really load the latest version on the website if you visit and test it |
111806 | I am writing a code that creates a PowerPoint from Excel VBA, using data from the Excel document. In this document, i have a Sheet called IMG where there is a series of images named "Picture X", X being the number of the current picture. The code I have for copying these pictures and pasting them on their respective PowerPoint Slide uses the .Select method, which, according to what I have read around here, makes the code run slower, and can/must be avoidable. I want to know if it is possible to avoid using the ".Select" method and still be able to paste the images from the excel sheet.
The code I am using is:
```
Dim pptSlide As PowerPoint.Slide
Sheets("IMG").Select
ActiveSheet.Shapes.Range(Array("Picture 1")).Select
Selection.Copy
pptSlide.Shapes.PasteSpecial(ppPasteMetafilePicture).Select
pptSlide.Shapes(4).Width = 121
pptSlide.Shapes(4).Height = 51
pptSlide.Shapes(4).Left = 580
pptSlide.Shapes(4).Top = 3
```
Thanks
Rest of my code:
```
Dim pptApp As PowerPoint.Application
Dim pptPres As PowerPoint.Presentation
Dim pptSlide As PowerPoint.Slide
Dim pptShape As PowerPoint.Shape
Dim excelTable As Excel.Range
Dim SlideTitle As String
Dim SlideText As String
Dim SlideObject As Object
Dim pptTextbox As PowerPoint.Shape
Dim SlideNumber As String
Dim myPic As Object
On Error Resume Next
Set pptApp = New PowerPoint.Application
Set pptPres = pptApp.Presentations.Add
pptPres.PageSetup.SlideSize = ppSlideSizeOnScreen
pptPres.ApplyTemplate "c:\Program Files\Microsoft Office\Templates\1033\Blank.potx"
pptPres.PageSetup.FirstSlideNumber = 0
''Consolidados
Set excelTable1 = Worksheets("TDCSD").Range("N280:U287")
Set excelTable2 = Worksheets("TDEXITO").Range("N48:U55")
Set excelTable3 = Worksheets("TDGPA").Range("N81:U88")
Set excelTable4 = Worksheets("TDSACI").Range("N234:U241")
Set excelTable5 = Worksheets("TDSMU").Range("N47:U54")
Set excelTable6 = Worksheets("TDRPLY").Range("N76:U83")
Set excelTable7 = Worksheets("TDInR").Range("N44:U51")
Set excelTable8 = Worksheets("TDPA").Range("N59:U66")
Set excelTable9 = Worksheets("TDIRSA").Range("N31:U38")
Set excelTable10 = Worksheets("TCOM").Range("Q8:AC17")
Set excelTable11 = Worksheets("TCOM").Range("Q24:AC33")
'SLIDES
'Slide 0
Set pptSlide = pptPres.Slides.Add(1, ppLayoutTitle)
SlideTitle = ThisWorkbook.Sheets("PPT").Range("F7").Value
pptSlide.Shapes(1).TextFrame.TextRange.Text = SlideTitle
pptSlide.Shapes.Title.TextFrame.TextRange.Characters(Start:=36, Length:=65).Font.Size = 20
pptSlide.Shapes.Title.Width = 610
pptSlide.Shapes(2).TextFrame.TextRange.Text = ThisWorkbook.Sheets("PPT").Range("B7").Value
'Agregar el número de diapositiva en la esquina derecha:
Set pptTextbox = pptSlide.Shapes.AddTextbox( _
msoTextOrientationHorizontal, 686, 510, 34, 29)
With pptTextbox.TextFrame
.TextRange.InsertSlideNumber
.TextRange.Font.Size = 8
.TextRange.Font.Name = "Tahoma"
.TextRange.Font.Color = RGB(137, 137, 137)
.VerticalAnchor = msoAnchorMiddle
End With
'Slide 1:
Set pptSlide = pptPres.Slides.Add(2, ppLayoutCustom)
SlideTitle = "Introducción"
pptSlide.Shapes.Title.TextFrame.TextRange.Text = SlideTitle
pptSlide.Shapes.Title.TextFrame.TextRange.Font.Size = 22
Set pptTextbox = pptSlide.Shapes(1)
pptTextbox.TextFrame.TextRange.Text = ThisWorkbook.Sheets("PPT").Range("B11").Value
pptTextbox.Top = 88
pptTextbox.TextFrame.TextRange.Paragraphs.ParagraphFormat.Alignment = ppAlignJustify
'Agregar el número de diapositiva:
Set pptTextbox = pptSlide.Shapes.AddTextbox( _
msoTextOrientationHorizontal, 686, 510, 34, 29)
With pptTextbox.TextFrame
.TextRange.InsertSlideNumber
.TextRange.Font.Size = 8
.TextRange.Font.Name = "Tahoma"
.TextRange.Font.Color = RGB(137, 137, 137)
.VerticalAnchor = msoAnchorMiddle
End With
'Slide 2:
Set pptSlide = pptPres.Slides.Add(3, ppLayoutTitleOnly)
SlideTitle = "Agenda"
pptSlide.Shapes.Title.TextFrame.TextRange.Text = SlideTitle
pptSlide.Shapes.Title.TextFrame.TextRange.Font.Size = 22
Set pptTextbox = pptSlide.Shapes.AddTextbox( _
msoTextOrientationHorizontal, 686, 510, 34, 29)
With pptTextbox.TextFrame
.TextRange.InsertSlideNumber
.TextRange.Font.Size = 8
.TextRange.Font.Name = "Tahoma"
.TextRange.Font.Color = RGB(137, 137, 137)
.VerticalAnchor = msoAnchorMiddle
End With
'Slide 3:
''Crear Slide y añadir título
Set pptSlide = pptPres.Slides.Add(4, ppLayoutCustom)
SlideTitle = "Noticias Relevantes"
pptSlide.Shapes.Title.TextFrame.TextRange.Text = SlideTitle
pptSlide.Shapes.Title.TextFrame.TextRange.Font.Size = 22
''Insertar el texto desde Excel
Set pptTextbox = pptSlide.Shapes(1)
pptTextbox.TextFrame.TextRange.Text = ThisWorkbook.Sheets("PPT").Range("B24").Value
pptTextbox.Top = 68.8
pptTextbox.TextFrame.TextRange.Paragraphs.ParagraphFormat.Alignment = ppAlignJustify
''Añadir número de Slide
Set pptTextbox = pptSlide.Shapes.AddTextbox( _
msoTextOrientationHorizontal, 686, 510, 34, 29)
With pptTextbox.TextFrame
.TextRange.InsertSlideNumber
.TextRange.Font.Size = 8
.TextRange.Font.Name = "Tahoma"
.TextRange.Font.Color = RGB(137, 137, 137)
.VerticalAnchor = msoAnchorMiddle
End With
'Añadir imagenes
'Falabella
Sheets("IMG").Shapes("Picture 1").Copy
pptSlide.Shapes.PasteSpecial(ppPasteMetafilePicture).Select
pptSlide.Shapes(4).Width = 121
pptSlide.Shapes(4).Height = 51
pptSlide.Shapes(4).Left = 579.4
pptSlide.Shapes(4).Top = 3.4
'Slide 4:
''Crear Slide y añadir el título
Set pptSlide = pptPres.Slides.Add(5, ppLayoutCustom)
SlideTitle = "Noticias Relevantes"
pptSlide.Shapes.Title.TextFrame.TextRange.Text = SlideTitle
pptSlide.Shapes.Title.TextFrame.TextRange.Font.Size = 22
''Añadir texto
Set pptTextbox = pptSlide.Shapes(1)
pptTextbox.TextFrame.TextRange.Text = ThisWorkbook.Sheets("PPT").Range("B49").Value
pptTextbox.Top = 77
pptTextbox.TextFrame.TextRange.Paragraphs.ParagraphFormat.Alignment = ppAlignJustify
''Añadir número de Slide
Set pptTextbox = pptSlide.Shapes.AddTextbox( _
msoTextOrientationHorizontal, 686, 510, 34, 29)
With pptTextbox.TextFrame
.TextRange.InsertSlideNumber
.TextRange.Font.Size = 8
.TextRange.Font.Name = "Tahoma"
.TextRange.Font.Color = RGB(137, 137, 137)
.VerticalAnchor = msoAnchorMiddle
End With
''Añadir imagenes
'Grupo Éxito
Sheets("IMG").Shapes("Picture 2").Copy
pptSlide.Shapes.PasteSpecial (ppPasteMetafilePicture)
pptSlide.Shapes(4).Width = 108
pptSlide.Shapes(4).Height = 65
pptSlide.Shapes(4).Left = 592
pptSlide.Shapes(4).Top = 1.42
``` | I would go for the **jsonlite** package in combination with the usage of **mapply**, a **transformation function** and data.table's **rbindlist**.
```
# data
raw_df <- data.frame(id = 1:2, json = c('{"user": "xyz2", "weightmap": {"P1":100,"P2":0}, "domains": ["a2","b2"]}', '{"user": "xyz1", "weightmap": {"P1":0,"P2":100}, "domains": ["a1","b1"]}'), stringsAsFactors = FALSE)
# libraries
library(jsonlite)
library(data.table)
# 1) First, make a transformation function that works for a single entry
f <- function(json, id){
# transform json to list
tmp <- jsonlite::fromJSON(json)
# transform list to data.frame
tmp <- as.data.frame(tmp)
# add id
tmp$id <- id
# return
return(tmp)
}
# 2) apply it via mapply
json_dfs <-
mapply(f, raw_df$json, raw_df$id, SIMPLIFY = FALSE)
# 3) combine the fragments via rbindlist
clean_df <-
data.table::rbindlist(json_dfs)
# 4) et-voila
clean_df
## user weightmap.P1 weightmap.P2 domains id
## 1: xyz2 100 0 a2 1
## 2: xyz2 100 0 b2 1
## 3: xyz1 0 100 a1 2
## 4: xyz1 0 100 b1 2
``` |
111831 | I'm building an interface where **I need to process touch events**. In particular I would to be able to enable them only to a confined area in a fragment.
To better understand the problem, to respect the standards and for the goal of my application, **I planned the navigation drawer, which assumes the presence of many fragment** (instead of activities). An activity with touch events is implemented quite easily, on the other hand I have read on the internet that **with the fragments can become a problem**.
My application, at the architectural level, is as follows:
- MainActivity.java
- NavigationDrawer.java
- TestFragment.java (for a single fragment now, waiting to solve the problem)
I've not found a solution or a tutorial that explains how to do well (or how to workaround the problem). Then I ask you, simplifying the problem to just "**enable a touch event in a fragment (getPressure() in this case)**". Below are some pieces of code that may help to solve the problem:
**TestFragment**
```
public class TestFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static TestFragment newInstance(int sectionNumber) {
TestFragment fragment = new TestFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public TestFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_test, container, false);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// Here I want to return the press value (0 to 1)
}
}
```
How to associate the listener to the whole fragment? And in the case of a particular area? Finally, how can I return the value of the pressure on the screen?
Thank you so much in advice! :) | I'm not sure if I understood your problem, but I will try to answer this. So to get touch events on fragment I would do this:
-in your fragment onCreateView:
```
View view = inflater.inflate(R.layout.fragment_test, container, false);
view.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_MOVE){
//do something
}
return true;
}
});
//here the rest of your code
return view;
```
and you can check for different MotionEvents in onTouch, for example:
```
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_UP,...
``` |
111855 | Make a discord.js bot send ephemeral messages when a user uses a slash command, i have tried using `interation.editReply({content: "etc-etc", ephemeral:true});` ,
and anything that seemed reasonable but it seemed unsuccessful, please send an example how i would implement ephemeral message!
Edit:
My Slash command Help file:
```
const { Message, Client } = require("discord.js");
module.exports = {
name: "help",
description: "Sends web page url for all commands",
run: async (client, interaction) => {
await interaction.deferReply({ephemeral: true});
interaction.editReply({
embeds: [
{
title: `${client.user.username}'s Help Page`,
description: `https://help.tcb.jayeshrocks.xyz`,
color: "RANDOM"
}
]
})
}
};
```
Now I am recieving interaction already replied errors
Edit 2: It was an error with my interactionCreate.js and now that i fixed it, it's working with .deferReply() , thanks! | According to the [docs](https://discord.js.org/#/docs/) you need to add the [`ephemeral` option](https://discord.js.org/#/docs/discord.js/stable/typedef/InteractionReplyOptions) in your [`InteractionReplyOptions`](https://discord.js.org/#/docs/discord.js/stable/typedef/InteractionReplyOptions). You can also check out Discord.js's [guide about ephemeral responses](https://discordjs.guide/interactions/slash-commands.html#ephemeral-responses).
>
> You may not always want everyone who has access to the channel to see a slash command's response. Thankfully, Discord implemented a way to hide messages from everyone but the executor of the slash command. This type of message is called `ephemeral` and can be set by using `ephemeral: true` in the `InteractionReplyOptions`
>
>
> - [discordjs.guide](https://discordjs.guide/interactions/slash-commands.html#ephemeral-responses)
>
>
>
**Here's an example:**
```js
//use the `interaction.reply()` function normally
await interaction.reply({
embeds: [{
title: `${client.user.username}'s Help Page`,
description: `https://help.tcb.jayeshrocks.xyz`,
color: "RANDOM"
}],
//this is the important part
ephemeral: true
});
```
**Learn More**
--------------
* [discordjs.guide](https://discordjs.guide/interactions/slash-commands.html#ephemeral-responses)
* [discord.js.org](https://discord.js.org/#/docs/discord.js/stable/typedef/InteractionReplyOptions)
* [Discord's Official Docs](https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-response-object-messages) |
111921 | What is meant by "Enabling command line editing and vi and emacs editing modes"?
I know `vi` is an editor and have used it as well, but what and how is it related to command line editing bamboozles me. I am using bash shell and a Red Hat system essentially in command line mode to learn. | This refers to which keys to use to move move the cursor (and go to beginning of line, etc).
In `vi` mode use `h` (left), `j` (down), `k` (up), `l` (right)
In 'emacs mode use `Ctrl`+`F` (left), `Ctrl`+`N` (down), `Ctrl`+`P` (up), `Ctrl`+`B` (right) |
112055 | I have discover that the pushFrontViewController function in SWReveal.
I have added the UIViewController in the storyboard's Contact.![enter image description here](https://i.stack.imgur.com/U6B5R.png)
And I am trying covert to swift, but it do not work.
Here is the code:
```
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//CODE TO BE RUN ON CELL TOUCH
var newFrontController: UIViewController
let selectedItemMenu = arrayOfSlider[indexPath.row]
var revealController = SWRevealViewController()
var contact_nav = ContactViewController()
newFrontController = UINavigationController(rootViewController:contact_nav)
revealController.pushFrontViewController(newFrontController , animated:true)
}
```
Is there anything that I am wrong? | SWRevealViewControllor is not that much hard. you should follow [this example](http://www.appcoda.com/sidebar-menu-swift/). I think its a perfect example you can try. It may help you ! |
112112 | Suppose I have a function that is continuous in every point of its domain, but its domain is only a subset of the real numbers (for example $\mathbb{R}-\{1\}$). Can I say that the function is continuous in $\mathbb{R}$? If not, what's the best way to express it? | Manos, I know the frustration, so let me make another attempt in a different direction. I will do a simple case, where $n=3,s=2$. So, we have $V(F\_1,F\_2)=X\subset\mathbb{P}^3$, a smooth, irreducible complete intersection curve. Let $I\subset\mathcal{O}\_{\mathbb{P}^3}$ be its ideal sheaf. Then, we have the Koszul resolution, $0\to \mathcal{O}\_{\mathbb{P}^3}(-\deg F\_1-\deg F\_2)\to \mathcal{O}\_{\mathbb{P}^3}(-\deg F\_1)\oplus \mathcal{O}\_{\mathbb{P}^3}(-deg F\_2)\to I\to 0$, which by using the the fact that $H^i(\mathcal{O}\_{\mathbb{P}^3}(l))=0$ for $i=1,2$ and all $l$ gives $H^1(I(l))=0$ for all $l$ and the map $H^0(\mathcal{O}\_{\mathbb{P}^3}(-\deg F\_1+l)\oplus \mathcal{O}\_{\mathbb{P}^3}(-\deg F\_2+l))\to I(l)$ is onto for all $l$. Thus, we see that $\oplus I(l)\subset\oplus\mathcal{O}\_{\mathbb{P}^3}(l)=k[x\_0,x\_1,x\_2,x\_3]$ is just the ideal $(F\_1,F\_2)$. From the long exact sequence coming from $0\to I\to\mathcal{O}\_{\mathbb{P}^3}\to\mathcal{O}\_X\to 0$, using the vanishing of $H^1$, we get an exact sequence, $0\to (F\_1,F\_2)\to k[x\_0,x\_1,x\_2,x\_3]\to \oplus H^0(\mathcal{O}\_X(l))\to 0$. Using the fact that $X$ is integral, easy to check that so is $\oplus H^0(\mathcal{O}\_X(l))$, but this is precisely $k[x\_0,x\_1,x\_2,x\_3]/(F\_1,F\_2)$. |
112185 | I have two Windows 2008 R2 64-bit servers that are identical in pretty much every way. Each of them has an app that basically does a lot of calculations. The hard drive is not really accessed at all. The app is very much CPU bound.
Inexplicably, though, one of the servers is processing 1/3 less data than the other one.
I checked and rechecked but everything seems to be the same. I've gone tab by tab of CPUZ to make sure that absolutely every last piece of memory and timing is the same - all to no avail. I've checked the affinity of each app to make sure it's utilizing all the CPUs.
Each box has 2 physical CPUs (each of which sports 4 cores).
How can I troubleshoot why the one box is slower than the other? | Much like many IT problems you're going to have to divide the problem, measure and then divide again...
If you can I'd move the hard disk/s of the 'slow' server to the hardware of the 'fast' server, does the problem follow the disks? If yes then you've probably got an OS/filesystem/config issue, if not then maybe you've got some broken/semi-broken hardware.
If the problem did move with the disks then I'd suggest you boot from a CD/ISO-based OS and carry out some form of test suite of CPU, memory and disk then repeat the tests but on the regular disk-based OS, this should hel identify if you have an OS or filesystem problem.
Then basically keep dividing up the problem into areas, kind of 50/50 each time (or as close as you can get anyway). |
112282 | I'm new to PHP. I tried creating a contact form using HTML and PHP. This contact form when submitted will send a mail to receiver.
**Below is the code the code for the contact form in HTML :**
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9" />
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
<link rel="stylesheet" type="text/css" href="css/coder.css"/>
<style type="text/css">
.bg-color{
background-color:#F9F1E4;
border-radius:5px;
margin:5px;
}
.row_color{
border:2px solid #A40F17;
margin:0px;
}
.footer_class{
background-color:#A40F17;
height:40px;
}
.font_color{
color:#fff;
margin-top:5px;
}
.navbar-inverse .navbar-nav > .active > a, .navbar-inverse .navbar-nav > .active > a:hover, .navbar-inverse .navbar-nav > .active > a:focus {
background-color: #A40F17;
color: #FFFFFF;
}
.h_color{
background-color:#FFFFFF;
}
.danger{
color:#A40F17;
}
.h_top{
margin-top:30px;
}
.h_height{
height:173px;
}
</style>
</head>
<body>
<header>
<div class="row h_color h_height">
<div class="container">
<div class="col-lg-12">
<div class="col-lg-6">
<a href="" class="navbar-brand"><img class="image-responsive" src="images/logo_rugs.jpg"/></a>
</div>
</div>
</div>
<nav class="navbar navbar-inverse">
<div class="container">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navHeader">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<div class="collapse navbar-collapse navHeader">
<ul class="nav navbar-nav navbar-right">
<li><a href="index.html">Home</a></li>
<li><a href="aboutus.html">About Us</a></li>
<li><a href="products.html">Products</a></li>
<li><a href="gallery.html">Gallery</a></li>
<li class="active"><a href="contactus.html">Contact Us</a></li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container" style="background-color:#fff;">
<div class="row">
<div class="col-lg-12">
<h3>Contact Us</h3>
<div class="col-lg-7 well">
<form enctype="multipart/form-data" method="post" name="contactform" id="former" action="contact.php">
<h4 style="padding-top:8px;">Your email address will not be published. Required fields are marked *</h4>
<label>Name*</label><br>
<input class="form-control" style="height:35px;width:230px;border-radius:4px;"type="text" name="text"/><br>
<label>Phone*</label><br>
<span>
<input id="element_4_1" name="element_4_1" class="element text" size="3" maxlength="3" value="" type="text"> -
</span>
<span>
<input id="element_4_2" name="element_4_2" class="element text" size="4" maxlength="4" value="" type="text"> -
</span>
<span>
<input id="element_4_3" name="element_4_3" class="element text" size="10" maxlength="10" value="" type="text">
</span>
<br><br>
<label>Email*</label><br>
<input class="form-control" style="height:35px;width:230px;border-radius:4px;"type="email" name="text"/><br>
<label for="input4">Message</label>
<textarea name="contact_message" class="form-control" rows="4" id="input4"></textarea>
<p> </p>
<button type="submit" style="margin-left:65px;"class="btn btn-large btn-info">Submit</button>
</form>
</div>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="js/bootstrap.js"></script>
</body>
</html>
```
**Below is the code for contact.php which is called when the contactus form is submitted.**
```
<?php
extract($_POST, EXTR_OVERWRITE);
$name=chop($name);
$phone=chop($element_4_1);
$phone.=chop($element_4_2);
$phone.=chop($element_4_3);
$email=chop($text);
$message1=chop($contact_message);
if ($name && $phone && $email) {
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "From: auto-reply\n";
$recipient= "test@gmail.com";
$subject="Online Enquiry";
$message.="\nName : $name\n";
$message.="\nPhone : $phone\n";
$message.="\nEmail ID : $email\n";
$message.="\nMessage : $message1\n";
//send auto-reply
$subject_reply="Thank you";
$message_reply="Thank you for contacting us.";
mail($email, $subject_reply, $message_reply, $headers);
//Send Mail
//===========
if(mail($recipient, $subject, $message, $headers)) {
echo "<meta http-equiv='REFRESH' content='0;url=contactus.html'>";
}
}
else {
exit("You have not filled out all the required fields. Please hit your back button and fill out all the required fields.");
}
?>
```
The above code works fine. Now, when I submit the form without filling the required fields I get the error after submitting the form in another page
I want to validate the required fields in such a way that if they are unfilled the error must be shown below the required text field. Suppose Name is not filled, then an error Name is manadatory should be displayed after the text field. How can I do this. | I have feel quiet difficult to see your full code.. Because you have added with css everything.. Please follow the following URL to create a form with validation
<http://www.freecontactform.com/email_form.php>
Please follow the steps and improve your code. |
112456 | I am attempting to center an image vertically inside of a parent fluid container.
[Here is a fiddle that outlines the problem.](https://jsfiddle.net/DTcHh/10247/)
```
<div class="container-fluid">
<div class="row">
<div class="col-md-2 col-sm-4 col-xs-4 col-xxs-4">
<div class="">
<a href="#"><img id="logo" class="img-responsive" src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRnfIk3IX1dY-okcqPH5BX_L0XF2z31qwP-MD0nijTdAGc2alNc4Q" style="vertical-align: middle;" alt="logo here"/></a>
</div>
</div>
<div class="col-md-10 col-sm-8 col-xs-8 col-xxs-8">
<div class="row">
<div class="col-md-12">
<div class="">
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#example-navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="example-navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li><a href="#" style="color: #1B75BB;">Search</a>
</li>
<li><a href="#" style="color: #1B75BB;">Archives</a>
</li>
<li><a href="#" style="color: #1B75BB;">About</a>
</li>
</ul>
</div>
</nav>
</div>
</div>
</div>
</div>
</div>
</div>
```
As you can see, the image is centered horizontally, but not vertically. Doing things like setting the margin, even of the parent container, does not seem to work. This feels like it should be fairly simple to solve, but I am struggling with it. | There are two ways of centring elements vertically within other elements, both of them are dependent upon styles of the parent container. One is to set the line height the same as the container height, and the other is to use table cells:
```css
img {
height: 25px;
width: 25px:
}
.container {
height: 50px;
width: 50px;
text-align: center;
border:1px solid;
}
.one {
line-height: 50px; /* Same as container height */
}
.container.two {
display:table-cell;
vertical-align:middle;
}
```
```html
<div class="container one">
<a href="#">
<img class="img-responsive" src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRnfIk3IX1dY-okcqPH5BX_L0XF2z31qwP-MD0nijTdAGc2alNc4Q" style="vertical-align: middle;" alt="logo here" />
</a>
</div>
<br />
<div class="container two">
<a href="#">
<img class="img-responsive" src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRnfIk3IX1dY-okcqPH5BX_L0XF2z31qwP-MD0nijTdAGc2alNc4Q" style="vertical-align: middle;" alt="logo here" />
</a>
</div>
``` |
112529 | I use the following code to build a desired path for an XML file:
```
System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
```
When executed from a Windows Forms application, it returns:
```
C:\Users\MyUsername\AppData\Roaming\...\Database.xml
```
When executed from within a Windows Service, it returns:
```
C:\Windows\system32\config\systemprofile\AppData\Roaming\...\Database.xml
```
I am now resorting to having a custom installer action persist the path in a registry key since the custom action will have a desktop context. If there is a better approach, please let me know.
What I am really interested in finding out is why the behavior is different in the first place. The Windows Service in question is set up to use the `LocalSystem` account in case that matters. | Only you know what the specific requirements are for this folder, but if it's to share data between multiple users, `ApplicationData` is the wrong choice:
>
> The directory that serves as a common repository for application-specific data for the current roaming user.
>
>
> A roaming user works on more than one computer on a network. A roaming user's profile is kept on a server on the network and is loaded onto a system when the user logs on
>
>
>
See the [`SpecialFolder`](http://msdn.microsoft.com/en-us/library/system.environment.specialfolder%28v=vs.110%29.aspx) enumeration and pick an appropriate value that fits your requirements - one that doesn't depend on a specific user. Most of these start with `Common`. |
112557 | In C# its possibly to use [AsDynamic](http://blogs.msdn.com/b/davidebb/archive/2010/01/18/use-c-4-0-dynamic-to-drastically-simplify-your-private-reflection-code.aspx) to invoke a overloaded method on a subclass (example [here](https://github.com/gregoryyoung/m-r/blob/master/SimpleCQRS/Domain.cs)) thus allowing an abstract class to invoke methods it does not itself define. Is something similar possible with Scala 2.9 **applyDynamic** ?. I tried the following
```
abstract class AggregateRoot extends Dynamic {
def applyChange(event: Event) {
this.applyDynamic("handleEvent")(event)
}
// this does not work
def applyDynamic(name : String)(args: Any*) = this
}
```
used like this
```
class InventoryItem extends AggregateRoot {
def handleEvent(event: InventoryItemCreated) {
println("received InventoryItemCreated")
}
def handleEvent(event: InventoryItemDeactivated) {
println("received InventoryItemDeactivated")
}
}
```
where **InventoryItemCreated** and **InventoryItemDeactivated** both are events
```
class Event;
class InventoryItemDeactivated extends Event;
class InventoryItemCreated extends Event;
```
I then expect to be able to do something like this
```
var aggregate : AggregateRoot = new InventoryItem
var event = new InventoryItemDeactivated
aggregate.applyChange(event) // should print "received InventoryItemDeactivated"
```
but I cannot figure out how to define **applyDynamic** (in **AggregateRoot**) so that it can invoke overloaded methods in subclasses at runtime without itself defining them. Other solutions that achieve the same result are welcome (perhaps structural typing can come in handy ?). | You could try something like:
```
list<string> iterator it = whichList.begin();
std::advance(it, i);
if(*it == "") { /* ... */ }
```
But I think you need to clearly define what you mean by "empty" here - you can't compare strings to 0.
The key point is that `list` doesn't support random access - because of its implementation (a doubly-linked list), supporting random access would be an `O(n)` operation, i.e. linear in the length of the list in the worst case. That's inefficient, so it's deliberately not supported in the interface.
As others have pointed out, if you want random access then you're better off using something like a `vector` or `deque`. Generally speaking, you would use a `vector` if you only need fast insertion/removal at the end of the container, a `deque` if you also need fast insertion/removal at the front of the container, and a `list` only if you need fast insertion/removal in the middle of the container. In order to support the latter type of operation, `list` ends up sacrificing random access to elements.
See here for the definition of `advance`, incidentally:
<http://www.sgi.com/tech/stl/advance.html>
EDIT: As Alf pointed out, you can to some extent get fast insertion/removal in the middle of a vector using the gap buffer technique (see <http://en.wikipedia.org/wiki/Gap_buffer>), although an individual operation can be costly if you fill the gap (the idea is to amortise the cost over lots of operations, making an operation sequence comparatively cheap). |
112894 | I have a data frame with duplicated rows having one continuous variable column and 2-factor columns (0,1). The goal is to find the duplicated rows and identify them as replicates in a new column.
Here is the structure of the data frame
```
cont.var fact1 fact2
1 1.0 1 0
2 1.0 0 1
3 1.5 1 0
4 1.5 1 0
5 1.5 0 1
6 1.5 0 1
```
Now let's say
* If `cont.var` has value **1.0** in two rows but has different values for `fact1` and `fact2`, so it will be assigned two different replicates.
* If `cont.var` has value **1.5** and `fact1`/`fact2` is also the same for successive rows, they will be given the same replicate identifier.
**Expected Output**
```
cont.var fact1 fact2 rep
1 1.0 1 0 1
2 1.0 0 1 2
3 1.5 1 0 3
4 1.5 1 0 3
5 1.5 0 1 4
6 1.5 0 1 4
```
**What I have tried**
```
library(dplyr)
sample.df <- data.frame(
cont.var = c(1,1,1.5,1.5,1.5,1.5,2,2,2,3),
fact1 = c(1,0,1,1,0,0,1,1,0,1),
fact2 = c(0,1,0,0,1,1,0,0,1,0)
)
sample.df %>%
group_by(cont.var, fact1, fact2) %>%
mutate(replicate = make.unique(as.character(cont.var), "_"))
```
**Incorrect Output**
* I would expect that `row-1` and `row-2` will have different replicate counts.
* I would expect that Replicate count for `row-3` == `row-4` and `row-5` == `row-6`, but `row-5` != `row-3`
```
cont.var fact1 fact2 replicate
1 1.0 1 0 1
2 1.0 0 1 1
3 1.5 1 0 1.5
4 1.5 1 0 1.5_1
5 1.5 0 1 1.5
6 1.5 0 1 1.5_1
```
I couldn't find a straightforward solution to this; I would really appreciate any help.
Thanks in advance. | You can use `data.table::rleid`:
```r
library(dplyr)
df %>%
mutate(rleid = data.table::rleid(cont.var, fact1, fact2))
cont.var fact1 fact2 rleid
1 1.0 1 0 1
2 1.0 0 1 2
3 1.5 1 0 3
4 1.5 1 0 3
5 1.5 0 1 4
6 1.5 0 1 4
```
---
If you have dplyr's dev. version, you can also use `consecutive_id`, the `dplyr` version of `data.table::rleid`:
```r
#devtools::install_github("tidyverse/dplyr")
library(dplyr)
df %>%
mutate(rleid2 = consecutive_id(cont.var, fact1, fact2))
```
---
Finally, a `base R` option would be to `match` the rows by unique values:
```r
df$rleid <- match(do.call(paste, df), do.call(paste, unique(df)))
``` |
113268 | I'm trying to do three jQuery posts, set their results equals to a variable outside their scope and then after all three have returned, if they are succcessful, execute another function. Right now I'm doing nested callbacks and would like to move away from that if possible.
I looked at the documentation for jQuery promise and deferreds, but haven't figured out how to use it with a $.post function
My current code:
```
var workout, diet, feedback
var postobj = { id: workoutId };
$.post("./RowingWorkouts/GetWorkoutUsingId", postobj, function(result) {
workout = result;
$.post("./Diet/GetDietUsingId", postobj, function(result) {
diet = result;
$.post("./RowingWorkouts/GetWorkoutFeedback", postobj, function(result) {
feedback = result;
renderCharts(workout, diet, feedback);
});
});
});
```
What I would like to do (pseudo code-ish):
```
var workout, diet, feedback
var postobj = { id: workoutId };
var getWorkout = $.post("./RowingWorkouts/GetWorkoutUsingId", postobj, function(result) {
workout = result;
});
var getDiet = $.post("./Diet/GetDietUsingId", postobj, function(result) {
diet = result;
});
var getFeedback = $.post("./RowingWorkouts/GetWorkoutFeedback", postobj, function(result) {
feedback = result;
});
// When all three are successful - I haven't gotten the when syntax to actually work yet
$.when(All3AreSuccessful).doThisOrSomething(renderCharts(workout, diet, feedback));
```
If there is a more elegant way to do it I'm happy to switch up my code too. I want to get into using promises and deferred now, because even though this code is simple and easy to understand with nested callbacks, I would rather learn a new tool and make the switch sooner rather than later. | using [$.when](http://api.jquery.com/jQuery.when/)
```
var postobj = {
id: workoutId
};
var getWorkout = $.post("./RowingWorkouts/GetWorkoutUsingId", postobj);
var getDiet = $.post("./Diet/GetDietUsingId", postobj);
var getFeedback = $.post("./RowingWorkouts/GetWorkoutFeedback", postobj);
// When all three are successful - I haven't gotten the when syntax to actually work yet
$.when(getWorkout, getDiet, getFeedback).done(function (workout, diet, feedback) {
//each of the parameter is an array
renderCharts(workout[0], diet[0], feedback[0])
});
``` |
113335 | I've got a search working for my application however it only works for the first page when I click next page I get the following error:
[![enter image description here](https://i.stack.imgur.com/R9mV1.png)](https://i.stack.imgur.com/R9mV1.png)
I've the following code in my vehicles controller:
```
def search
vehicles = Vehicle.fuzzy_search(params[:search_string])
@vehicles = Kaminari.paginate_array(vehicles.order:make).page(params[:page]).per(3)
if @vehicles.empty?
flash.now[:alert] = "No records found - displaying all records ..."
@vehicles = Vehicle.order(:make).page(params[:page]).per(3)
end
render :action => "index"
end
```
I've got the following code in my vehicle.rb
```
def self.fuzzy_search(search_string)
search_string = "%" + search_string + "%"
self.where("make LIKE ?", search_string)
end
```
and my routes.rb has the following:
```
get 'vehicles/search', to: 'vehicles#search'
post 'vehicles/search', to: 'vehicles#search'
```
For some reason its trying to show a record which is called "search" rather then displaying the second page. I've spend hours trying to figure out why its doing this can someone please help!
Edit --
Full Trace
[![enter image description here](https://i.stack.imgur.com/bIz01.png)](https://i.stack.imgur.com/bIz01.png)
[![enter image description here](https://i.stack.imgur.com/KNXyp.png)](https://i.stack.imgur.com/KNXyp.png) | **Exact Problem:**
If you see your error, it is pointing to **`VehicleController#show`**
It is happening because `get 'vehicles/search'` is going to show action but not `search`
Show will be something like,
`get '/vehicles/:id', to: 'vehicles#show'`, so the search it is thiniking as Id and giving you error.
**Solution:**
Move
`get 'vehicles/search', to: 'vehicles#search'`
above `resources: vehicles`
**Your search route should be on the top of vehicles show route**
So, your routes should be something like,
**routes.rb excerpt:**
```
get 'vehicles/search', to: 'vehicles#search'
post 'vehicles/search', to: 'vehicles#search'
resources: vehicles
``` |
113415 | A similar question was asked [here](http://social.msdn.microsoft.com/Forums/en/msbuild/thread/9d2e32c2-09bc-445d-9c0c-e5b75b808b34) without any answers. I have a cs project with a reference to MySql.Data.Dll with CopyLocal=true. When I run the msbuild from command line on one computer (Windows 7 64 bit), it works perfectly.
When I run the same MsBuild on another computer (Windows Server 2008 RC2), the DLL is not copied to the output directory. Other copy-local DLLs are copied without a problem, and no error is printed. I do have permissions to access the DLL, and copying it manually works.
Does anyone know why this happens / how to circumvent? | MySql.Data.Dll may be in the GAC on the Win 2008 RC2 computer and not on the Win7 one, which could explains the different behaviours. |
113930 | I've checked a few other threads around the topic and search around, I am wondering if someone can give me a clear direction as to ***why*** should I consider NoSQL and ***which*** one (since there are quite a few of them each with different purposes)
* [Why NoSQL over SQL?](https://softwareengineering.stackexchange.com/questions/109192/why-nosql-over-sql)
* [Is MongoDB the right choice in my case?](https://softwareengineering.stackexchange.com/questions/139108/is-mongodb-the-right-choice-in-my-case)
* <https://softwareengineering.stackexchange.com/questions/5354/are-nosql-databases-going-to-take-the-place-of-relational-databases-is-sql-goin>
Like many others - I started with relational databases and been working on them ever since, thus when presented with a problem, the first instinct is to always think of *"I can create these tables, with these columns, with this foreign keys"*, etc
My overall goal is **How to get into "NoSQL" mindset**? ie getting away from the inclination of always thinking about tables/columns/FKs (I understand that there are cases where RDBMS is still the better way to go)
I am thinking of 2 scenarios for example just to get more concrete direction
**Scenario 1**
Imagine a database to model building a furniture instructions (think of IKEA instructions) where you would have the object "furniture" which would have a list of "materials" and have a list of "instructions"
* Furniture - would simply have a name that have a list of Materials and Instructions
* Materials - would be a name + quantity, may be we can even have "Material Category" table as well
* Instructions - would simply be an ordered list of texts
My first instinct would go the RDBMS way:
* Create a table called "Furniture", "Material" and "Instruction" and the approppriate columns
* Create the appropriate JOIN tables as necessary and FKs
The use of this system can include *searching* based on materials or may be combination of materials. And may be think of extending the data stored to include information on how many people are required to build it? Difficulty level? how much time it would take?
Would something like this be a good candidate for a NoSQL database?
**Scenario 2**
Imagine a database to model a User database with basic information (eg. name, email, phone number, etc), but you also want to have the flexibility of being able to add any custom fields as you wish.
Think of different systems consuming this user database, each system will want to have their own custom attribute to be attached to the user
My inclination would go the RDBMS way:
* Create a table for "USER" with columns: ID, name, email, phone
* Create a table for "USER\_ATTRIBUTE" with columns: ID, USER\_ID, attr\_name, attr\_type, attr\_value
The USER\_ATTRIBUTE will allow that customization and flexibility without having to shut down the system, alter the database and restart it.
Would something like this be a good candidate for a NoSQL database? | NoSQL isn't a very well defined term and all the solutions that run under this name have very different features, so a lot may be possible or not depending on what exactly you are planning to do with it.
Basically you could use some of the more general solutions like maybe MongoDB or Cassandra to simply replace your current relational database. In some cases this makes more sense in others less, but it will work once your team got used to it. Certain things will be easier then, others will be more difficult and you must weight those options against each other and decide (which often enough will mean that there are no advantages big enough and the simple fact that everybody in the team feels most comfortable with relationals and SQL will make the decision easy)
Other NoSQL solutions that are more specialised are not really good candidates to replace your relational DB, like graph databases or simple key value stores. So lets from here talk mainly about those databases that are at least to some degree similar to relational databases.
**Scenario 1**
Where I work we have exactly this scenario, though quite more complex with a lot of different attributes per article. Some of those attributes in hierarchies like Apple -> iPad -> Air.
The data is still stored in a relational database. But: searching this in real time became a pain. With SQL it was slow and code would have been terribly complex. Selects over many tables, with the additional option to exclude certain attributes like "not blue".
In this case Apache Solr or Elastic Search are a solution. Though of course data is duplicated from the relational database.
But from here our experience with this kind of document store showed that it can handle certain problems very well and we will consider to replace part of the existing relational structure with some other kind of storage. So not the whole database where we also store all the transactional data like orders etc, but for example take out all the attribute information which can be handled much better in the aggregate like data structures of NoSQL.
**Scenario 2**
Difficult to say, since what you describe is most likely only a very small part of your user handling. Having schemaless storage is an advantage with many NoSQL databases. But some relational databases allow to store such data too (as long as you don't need to query it via SQL in most cases).
Cassandra for example would allow you to define column families in such a case, where your first set of attributes would be one such family and the variable attributes another one.
As somebody said: NoSQL is less about storage and more about querying. So the question is what will be the typical use case for those queries.
A typical problem would be the transactional data here. If you want to store orders, one way would be a schema where users and their orders form an aggregate (kind of user document that contains the orders as subdocuments). This would make getting a user together with his orders very simple and fast, but would make it very difficult to retrieve all orders from last month for sales statistics.
Also strengths of NoSQL solutions are that it can be easier to run them on multiple clusters if you have to work with very large datasets.
**Conclusion:** Both your scenarios could be modelled with certain NoSQL solutions, but I don't think that (assuming they have to run in a larger environment) they really justify a large extra effort in learning, training and implementation and maybe some other additional disadvantages because both are not specific enough to really leverage the strengths of NoSQL. At least not in that simple form you describe it. Things may become very different once some aspects you describe would be very, very prominent in your usage scenario, like in scenario one the attribute data becomes very complex or in scenario two the variable fields become the largest part of data you store with every user. |
114030 | I have integrated the `Wepay payment gateway`. But I have facing a problem to pass `json object to wepay`. It always shows a incorrect json format. Please look at the below code.
```
$forca_a = array(
'debit_opt_in'=>true
);
$forca = json_encode($forca_a,JSON_FORCE_OBJECT);
$wepay_create_array = array(
'name' =>"xxxx",
'description' => "xxxxxxxxx xxxx",
'callback_uri' => "xxxxxxx",
'country' => "CA",
'currencies' => array('CAD'),
'country_options' => $forca,
'rbits'=> array(
array(
'receive_time'=>strtotime("now"),
'type' =>'website_uri',
'source' => 'partner_database',
'properties'=> array('uri'=>xxxxx)
)
)
);
```
If I won't pass the `country_options`, its seems to working but If I pass this parameter, it always give me an error says "Incorrect JSON format".
I sent an email to wepay help center. They told me that, you are passing the string `"country_options":"{"debit_opt_in":true}" <--- this is a string` Instead of `"country_options":{"debit_opt_in":true} <--- this is a JSON object`. So I'm confused. I have no idea how do I pass the JSON object. There is only way and is `json_encode($object)`. | The problem is that you are using the [Object.ToString()](https://msdn.microsoft.com/en-us/library/system.object.tostring(v=vs.110).aspx) method. This method, does not have arguments. If you want to convert it into a date, you might try this:
```
DateTime dt = DateTime.Parse(rdr.GetValue(4).ToString())
lblDate.Text = dt.ToString("MMMM d,yyyy");
```
### Edit:
Please note, that if the date column in your database contains null-values, the parse methode will throw an exception. So testing for null is mandatory.
```
String s = Convert.ToString(rdr.GetValue(4));
if(!String.IsNullOrEmpty(s))
{
DateTime dt = DateTime.Parse(s);
lblDate.Text = dt.ToString("MMMM d,yyyy");
}
``` |
114234 | I'm trying to add values to a table using jQuery - unfortunately, I don't know how to get jQuery to add table cells to an existing row. For example:
```
$("<td><a href='#'>" + key + "</a></td>").click(function(e) {
e.preventDefault();
testset(key);
}).appendTo('#table1');
```
This adds cells to the end of the table with id `table1`. What would be the best way to go about adding cells to an existing table row (`<tr>`) using jQuery? Quick google hasn't revealed anything.
Regards,
SystemError | ```
.appendTo('#table1 #rowId');
```
Or you could do:
```
.appendTo('#table1 tr:nth-child(5)');
```
<http://api.jquery.com/nth-child-selector/> |
114570 | I have a table like this:
```
col | status
----+-------
1 | 0
1 | 1
2 | 1
2 | 2
3 | 1
3 | 0
```
I want to select only the row with having max status value. But also want to ignore if there is any 0 in status. So expected rows would be as follows (I am ignoring 1 and 3 for having status = 0).
```
col | status
----+-------
2 | 2
```
I only can pick the rows based on max(). But when I add another clause to filter the zero, it doesn't work.
```
SELECT col, max(status)
FROM my_table
WHERE
(select count(*)
from my_table t1
where t1.col = col
and status = 0) = 0
GROUP BY col;
```
Any guide will do for me. | Use `HAVING` clause:
```
SELECT col, MAX(STATUS)
FROM tab
GROUP BY col
HAVING SUM(CASE WHEN STATUS = 0 THEN 1 ELSE 0 END) = 0;
```
**[DBFiddle](http://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=f2b476c01046d253cacbd383a2852ae7)**
---
If your minimal value for `STATUS` is `0` then you could use:
```
SELECT col, MAX(STATUS)
FROM tab
GROUP BY col
HAVING MIN(STATUS) > 0;
``` |
114586 | I've created a multilingual TYPO3 6.2 website with fluid and Gridelements.
I have a big Problem with the language translations (btw: same problems occur in TYPO3 7.6)
If I create an alternative page language with **no** content inside, I want to show the **default language**, in my case German.
Otherwise, if there **is** some content on the translated (english) site, the german default should be hidden and the **complete alternativ language content** should be visible.
In my case it is **only** possible to translate exakt these parts from the german default language and it is not possible to create some new content which is not shown in the default language. In the TYPO3-backend I can create the new content, but it will not be shown.
If I set `config.sys_language_overlay = 0` at Typoscript, the new content is visible, but the complete default content isn't shown.
Which Settings are necessary to show the complete content at the alternative language and the default content for empty pages?
This is what I have tried so far:
```
styles.content.get.select.includeRecordsWithoutDefaultTranslation = 1
styles.content.getLeft.select.includeRecordsWithoutDefaultTranslation = 1
styles.content.getRight.select.includeRecordsWithoutDefaultTranslation = 1
```
And here my Typoscript
```
### language Menü ###
lib.langselect = COA
lib.langselect {
wrap = <ul class="langNav">|</li></ul></ul>
30 = HMENU
30 {
special = language
special.value = 0,1,7
special.normalWhenNoLanguage = 0
1 = TMENU
1 {
noBlur = 1
# Standard Sprachen
NO = 1
NO {
linkWrap = <li>|</li>
stdWrap.override = Deutsch /|| English /
doNotLinkIt = 1
stdWrap.typolink.parameter.data = page:uid
stdWrap.typolink.additionalParams = &L=0 || &L=1
stdWrap.typolink.addQueryString = 1
stdWrap.typolink.addQueryString.exclude = L,id,cHash,no_cache
stdWrap.typolink.addQueryString.method = GET
stdWrap.typolink.useCacheHash = 1
stdWrap.typolink.no_cache = 0
}
ACT < .NO
ACT.linkWrap = <li class="active">|</li>
USERDEF1 < .NO
USERDEF2 < .ACT
}
}
}
config.linkVars = L
config.locale_all = de_DE
config.sys_language_uid = 0
config.sys_language_mode = content_fallback
[globalVar = GP:L = 1]
config.sys_language_uid = 1
config.sys_language_overlay = 1
config.metaCharset = iso-8859-1
config.locale_all = en_GB.ISO88591
config.language = en
[GLOBAL]
[globalVar = GP:L = 7]
config.sys_language_uid = 7
config.metaCharset = iso-8859-1
config.locale_all = fr_FR.ISO88591
config.language = fr
[GLOBAL]
```
And here’s the script where I load the content to my lib-field:
```
lib.contentmid = HMENU
lib.contentmid {
1 = TMENU
1 {
expAll = 1
NO = 1
NO {
ATagParams = class="notUsableLink"
wrapItemAndSub.insertData = 1
wrapItemAndSub = <section id="{field:subtitle}">|</section>
allWrap = <div class="mainContent"><div class="contentHolder">|</div></div>
before = <div class="hideLink" data-link="{field:subtitle}">{field:title}</div>
before.insertData = 1
after.cObject = CONTENT
after.cObject {
table = tt_content
select {
orderBy = sorting
pidInList.field = uid
languageField=sys_language_uid
where = colPos = 2
}
}
}
}
2 < .5
2 {
wrapItemAndSub.insertData = 1
NO.wrapItemAndSub = <div id="{field:subtitle}" class="subContent"><div class="contentHolder">|</div></div>
NO.allWrap >
}
}
```
Any idea? Many thanks. | Add 'includeRecordsWithoutDefaultTranslation = 1' to 'after.cObject.select.' The styles.content.get is some kind of shortcut for colPos 0 ... 3, but does not affect your TypoScript at this point. |
114696 | Example:
test.py
```
class test_class(object):
def display(self):
print "Hello"
```
lock1.py
```
from test import test_class
from time import sleep
obj = test_class()
while True:
obj.display()
sleep(1)
```
lock2.py
```
from test import test_class
obj = test_class()
# Raise error if instance of test_class has been implemented before
try:
obj.display()
except Exception as e:
print e
```
What I need to do is lock (or anything) the class (or entire test.py) for file lock2.py if the object has already been initialized for that class
before raising Error(or Expeption). I've simplied the example though the example might not look relevant.
I tried locking the file i.e. test.py using
```
http://packages.python.org/lockfile/lockfile.html
http://pypi.python.org/pypi/zc.lockfile
```
but it doesn't seem to help.
---
HERE IS A ACTUAL CODE SNIPPET
-----------------------------
comm\_port.py
```
import serial
class CommPort(object):
def __init__(self):
self.ser = serial.Serial("/dev/ttyUSB0")
# update in db (I've removed actual db update process
# db.flag = 1
```
accessing\_file1.py
```
from comm_port import CommPort
# if db.flag != 1:
port = Commport()
port.ser.flushInput()
port.ser.flushOutput()
## will flush the buffer.. what if it flused the data that was supposed for go for accessing_file2
port.ser.write("1")
# do stuff using serial-port object "port"
# lets say script gets busy for 30 secs for doing some stuffs
# db.flag = 0
```
accessing\_file2.py
```
from comm_port import CommPort
# if db.flag != 1:
port = Commport()
port.ser.flushInput()
port.ser.flushOutput()
port.ser.write("2")
# do stuff using serial-port object "port"
# lets say script gets busy for 40 secs for doing some stuffs
# db.flag = 0
```
Still the example might not look relevant but this is my case.
Both of file can be activated at once too but I need only one to operate at a time.
what i did was created a db flag if comm\_port.py is used and rest files check this flag.
if comm\_port is busy other accessing files will not work.
But I dont think its best practice.
So I need to check if there is a way to check if CommPort class is being instiated by any object or
by locking the comm\_port.py or any other existing ideas are most welcome. | You can't apply a lock to this situation, since importing doesn't work this way. An imported module is only executed **once**, the first time it is imported. Subsequent imports only copy the existing reference from `sys.modules`. You will need to figure out what your actual problem is and ask about that instead. |
114871 | **This is my task**
```
journey = """Just a small tone girl
Leaving in a lonely whirl
She took the midnight tray going anywhere
Just a seedy boy
Bored and raised in South Detroit or something
He took the midnight tray going anywhere"""
```
Gross. Okay, so for this exercise, your job is to use Python's string replace method to fix this string up and print the new version out to the console.
**This is what I did**
```
journey = """ just a small tone girl
Leaving in a lonely whirl
she took a midnight tray going anywhere
Just a seedy boy
bored and raised in south detroit or something
He took the midnight tray going anywhere"""
journeyEdit = journey.replace("tone" ,
"town").replace("tray","train").replace("seedy","city").replace("Leaving",
"living").replace("bored","born").replace("whirl","world").replace("or
something", " ")
print (journeyEdit)
``` | Here is a sample way to replace words from text. you can use **python re** package.
please find the below code for your guidance.
```
import re
journey = """ just a small tone girl Leaving in a lonely whirl she took a
midnight tray going anywhere Just a seedy boy bored and raised in south
detroit or something He took the midnight tray going anywhere"""
# define desired replacements here
journeydict = {"tone" : "town",
"tray":"train",
"seedy":"city",
"Leaving": "living",
"bored":"born",
"whirl":"world"
}
# use these given three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in journeydict.items())
#Python 3 renamed dict.iteritems to dict.items so use rep.items() for latest
versions
pattern = re.compile("|".join(journeydict.keys()))
text = pattern.sub(lambda m: journeydict[re.escape(m.group(0))], journey)
print(journey)
print(text)
``` |
115278 | We have an Sharepoint Online 2013. Yammer Embed is added to our site. In Firefox and Chrome it works swell, in IE it does not work.
On IE:
When logging in the first time Yammer pops up an windows stating that it is trying to authenticate. Then a message appears stating that a webpage is trying to close the window. Whatever I do, I do end up at the same blue login button.
At some point (not sure when, why or how) it got beyond that and then told me that content could not be shown in an iframe but after clicking on the message it logs me straight in on Yammer. After resetting IE I was back on the blue login button.
Colleagues who have not resetted their IE settings get the i-frame thing.
This behaviour occurs on all machines, even on vanilla VM's (windows 7-8.1-10) and using new O365 credentials (1 admin and 1 user) specifically created for this. Resetting my IE did not help (even though I think that to be superfluous on newly installed machines)
Any suggestions? | We had a similar situation with office 365 and yammer embed in IE 11. Enabling Protected Mode for the Trusted Sites Zone (Internet Options > Security > Trusted Sites > Enable Protected Mode) solved it. Apparently Protected Mode used to be on by default in IE but no longer is. |
115455 | I am installing Pimcore 5 using Nginx 1.12.1, MYSQL 5.6, Redis 3.2.4, PHP 7.0, PHP 7.0 FPM with user set nginx and started at 127.0.0.1:9000 on Amazon Linux AMI
My virtual host setting is as
```
#
# A virtual host using mix of IP-, name-, and port-based configuration
#
upstream php-pimcore5 {
server 127.0.0.1:9000;
}
server {
listen 80;
root /var/www/html/web;
server_name pimcoretest.local
index index.php index.html;
#try_files $uri $uri/ /app.php?$args;
access_log /var/log/access.log;
error_log /var/log/error.log error;
rewrite ^/cache-buster-(?:\d+)/(.*) /$1 last;
location ~* /var/assets/*\.php(/|$) {
return 404;
}
location ~* (?:\.(?:bak|conf(ig)?|dist|fla|in[ci]|log|psd|sh|sql|sw[op])|~)$ {
deny all;
}
location ~* .*/(image|video)-thumb__\d+__.* {
try_files /var/tmp/$1-thumbnails$request_uri /app.php;
# expires 2w;
access_log off;
add_header Cache-Control "public";
}
location ~* (.+?)\.((?:css|js)(?:\.map)?|jpe?g|gif|png|svgz?|eps|exe|gz|zip|mp\d|ogg|ogv|webm|pdf|docx?|xlsx?|pptx?)$ {
try_files /var/assets$uri $uri =404;
# expires 2w;
access_log off;
log_not_found off;
add_header Cache-Control "public";
}
if (-f $document_root/install.php) {
rewrite ^/install(/?.*) /install.php$1 last;
}
location / {
error_page 404 /meta/404;
add_header "X-UA-Compatible" "IE=edge";
try_files $uri /app.php$is_args$args;
fastcgi_pass php-pimcore5;
}
location ~ ^/app\.php(/|$) {
send_timeout 1800;
fastcgi_read_timeout 1800;
# regex to split $uri to $fastcgi_script_name and $fastcgi_path
fastcgi_split_path_info ^(.+\.php)(/.+)$;
# Check that the PHP script exists before passing it
try_files $fastcgi_script_name =404;
include fastcgi.conf;
# Bypass the fact that try_files resets $fastcgi_path_info
# see: http://trac.nginx.org/nginx/ticket/321
set $path_info $fastcgi_path_info;
fastcgi_param PATH_INFO $path_info;
# Activate these, if using Symlinks and opcache
# fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
# fastcgi_param DOCUMENT_ROOT $realpath_root;
# fastcgi_pass php-pimcore5;
# Prevents URIs that include the front controller. This will 404:
# http://domain.tld/app.php/some-path
# Remove the internal directive to allow URIs like this
internal;
}
# PHP-FPM Status and Ping
location /fpm- {
access_log off;
include fastcgi_params;
location /fpm-status {
allow 127.0.0.1;
# add additional IP's or Ranges
deny all;
# fastcgi_pass php-pimcore5;
}
location /fpm-ping {
# fastcgi_pass php-pimcore5;
}
}
location /nginx-status {
allow 127.0.0.1;
deny all;
access_log off;
stub_status;
}
}
```
.htaccess in project is as
```
# Use the front controller as index file. It serves as a fallback solution when
# every other rewrite/redirect fails (e.g. in an aliased environment without
# mod_rewrite). Additionally, this reduces the matching process for the
# start page (path "/") because otherwise Apache will apply the rewriting rules
# to each configured DirectoryIndex file (e.g. index.php, index.html, index.pl).
DirectoryIndex app.php
# By default, Apache does not evaluate symbolic links if you did not enable this
# feature in your server configuration. Uncomment the following line if you
# install assets as symlinks or if you experience problems related to symlinks
# when compiling LESS/Sass/CoffeScript assets.
# Options FollowSymlinks
# Disabling MultiViews prevents unwanted negotiation, e.g. "/app" should not resolve
# to the front controller "/app.php" but be rewritten to "/app.php/app".
<IfModule mod_negotiation.c>
Options +MultiViews
</IfModule>
# mime types
AddType video/mp4 .mp4
AddType video/webm .webm
AddType image/jpeg .pjpeg
Options +SymLinksIfOwnerMatch
# Use UTF-8 encoding for anything served text/plain or text/html
AddDefaultCharset utf-8
RewriteEngine On
<IfModule mod_headers.c>
<FilesMatch "\.(jpe?g|png)$">
Header always unset X-Content-Type-Options
</FilesMatch>
</IfModule>
# Determine the RewriteBase automatically and set it as environment variable.
# If you are using Apache aliases to do mass virtual hosting or installed the
# project in a subdirectory, the base path will be prepended to allow proper
# resolution of the app.php file and to redirect to the correct URI. It will
# work in environments without path prefix as well, providing a safe, one-size
# fits all solution. But as you do not need it in this case, you can comment
# the following 2 lines to eliminate the overhead.
RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
RewriteRule ^(.*) - [E=BASE:%1]
# Sets the HTTP_AUTHORIZATION header removed by Apache
RewriteCond %{HTTP:Authorization} .
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect to URI without front controller to prevent duplicate content
# (with and without `/app.php`). Only do this redirect on the initial
# rewrite by Apache and not on subsequent cycles. Otherwise we would get an
# endless redirect loop (request -> rewrite to front controller ->
# redirect -> request -> ...).
# So in case you get a "too many redirects" error or you always get redirected
# to the start page because your Apache does not expose the REDIRECT_STATUS
# environment variable, you have 2 choices:
# - disable this feature by commenting the following 2 lines or
# - use Apache >= 2.3.9 and replace all L flags by END flags and remove the
# following RewriteCond (best solution)
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^app\.php(?:/(.*)|$) %{ENV:BASE}/$1 [R=301,L]
<IfModule mod_status.c>
RewriteCond %{REQUEST_URI} ^/(fpm|server)-(info|status|ping)
RewriteRule . - [L]
</IfModule>
# restrict access to dotfiles
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule /\.|^\.(?!well-known/) - [F,L]
# ASSETS: check if request method is GET (because of WebDAV) and if the requested file (asset) exists on the filesystem, if both match, deliver the asset directly
RewriteCond %{REQUEST_METHOD} ^(GET|HEAD)
RewriteCond %{DOCUMENT_ROOT}/var/assets%{REQUEST_URI} -f
RewriteRule ^(.*)$ /var/assets%{REQUEST_URI} [PT,L]
# Thumbnails
RewriteCond %{REQUEST_URI} .*/(image|video)-thumb__[\d]+__.*
RewriteCond %{DOCUMENT_ROOT}/var/tmp/%1-thumbnails%{REQUEST_URI} -f
RewriteRule ^(.*)$ /var/tmp/%1-thumbnails%{REQUEST_URI} [PT,L]
# cache-buster rule for scripts & stylesheets embedded using view helpers
RewriteRule ^cache-buster\-[\d]+/(.*) $1 [PT,L]
# rewrite /install to install.php if file exists
RewriteCond %{DOCUMENT_ROOT}/install.php -f
RewriteCond %{REQUEST_URI} !^/install\.php
RewriteRule ^install /install.php [L]
# If the requested filename exists, simply serve it.
# We only want to let Apache serve files and not directories.
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]
# Rewrite all other queries to the front controller.
RewriteRule ^ %{ENV:BASE}/app.php [L]
##########################################
### OPTIONAL PERFORMANCE OPTIMIZATIONS ###
##########################################
<IfModule mod_deflate.c>
# Force compression for mangled headers.
# http://developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping
<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
</IfModule>
</IfModule>
# Compress all output labeled with one of the following MIME-types
# (for Apache versions below 2.3.7, you don't need to enable `mod_filter`
# and can remove the `<IfModule mod_filter.c>` and `</IfModule>` lines
# as `AddOutputFilterByType` is still in the core directives).
<IfModule mod_filter.c>
AddOutputFilterByType DEFLATE application/atom+xml application/javascript application/json \
application/vnd.ms-fontobject application/x-font-ttf application/rss+xml \
application/x-web-app-manifest+json application/xhtml+xml \
application/xml font/opentype image/svg+xml image/x-icon \
text/css text/html text/plain text/x-component text/xml text/javascript
</IfModule>
</IfModule>
<IfModule mod_expires.c>
ExpiresActive on
ExpiresDefault "access plus 1 week"
# specific overrides
#ExpiresByType text/css "access plus 1 year"
</IfModule>
<IfModule pagespeed_module>
# pimcore mod_pagespeed integration
# pimcore automatically disables mod_pagespeed in the following situations: debug-mode on, /admin, preview, editmode, ...
# if you want to disable pagespeed for specific actions in pimcore you can use $this->disableBrowserCache() in your action
RewriteCond %{REQUEST_URI} ^/(mod_)?pagespeed_(statistics|message|console|beacon|admin|global_admin)
RewriteRule . - [L]
ModPagespeed Off
AddOutputFilterByType MOD_PAGESPEED_OUTPUT_FILTER text/html
ModPagespeedModifyCachingHeaders off
ModPagespeedRewriteLevel PassThrough
# low risk filters
ModPagespeedEnableFilters remove_comments,recompress_images
# low and moderate filters, recommended filters, but can cause problems
ModPagespeedEnableFilters lazyload_images,extend_cache_images,inline_preview_images,sprite_images
ModPagespeedEnableFilters combine_css,rewrite_css,move_css_to_head,flatten_css_imports,extend_cache_css,prioritize_critical_css
ModPagespeedEnableFilters extend_cache_scripts,combine_javascript,canonicalize_javascript_libraries,rewrite_javascript
# high risk
#ModPagespeedEnableFilters defer_javascript,local_storage_cache
</IfModule>
```
Document Root is `/var/www/html/web`
I have added following command in app.php as
```
error_reporting(E_ALL);
ini_set('display_errors', 1);
```
to enable all errors in PHP. Also add these commands in install.php.
Ensured that project has 0775 permission to user nginx.
There is folder prod present in /var/www/html/var/cache
Now as I am hitting <http://pimcoretest.local> it get redirected to <http://pimcoretest.local/install> with no errors in error log and **completely blank**.
As I inspect in browser it shows 301 redirection and 200 for /install
I have no clue what is problem and how should I troubleshoot it. Please help. | `Contains` actually looks for substring in it, you need here is full match so you can try using `==` operator here like:
```
var project = db.Projects.FirstOrDefault(x => projectIds.Any(id=> id ==x.ProjectId))
```
This will now make sure to match the complete string value in it. |
115595 | i'm not searching to do something complicated , i just want to retrieve certain titles from a website , the first button was just for a test ... The thing is , even the "lala" text isn't showing up which means it doesn't enter in the loop in the first place ...
```
Public Class Form1
Function ElementsByClass(document As HtmlDocument, classname As String)
Dim coll As New Collection
For Each elem As HtmlElement In document.All
If elem.GetAttribute("appcenter").ToLower.Split(" ").Contains(classname.ToLower) Then
coll.Add(elem)
End If
Next
Return coll
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim wb As New System.Net.WebClient
wb.Headers.Add("user-agent", "Only a test!")
Dim sourceString As String = wb.DownloadString("http://www.ign.com/games/upcoming")
RichTextBox1.Text = sourceString
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim elementss As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("div")
For Each pElem As HtmlElement In elementss
If pElem.GetAttribute("class") = "item-title" Then
RichTextBox1.Text = "lala"
RichTextBox1.Text = pElem.InnerHtml
End If
Next
End Sub
End Class
``` | You are giving to onTouchTap void, because that's what this.doSomething(id) returns .
```
this.doSomething(id)
```
is executed the firs time MyOwnComponent is rendered.
Instead you should do this :
```
class MyOwnComponent extends Component {
doSomething = () => {
const {id} = this.props.object;
alert('doSomething: id = ' + id )
}
render() {
return (
<RaisedButton secondary={true} label={'My label'} onTouchTap={this.doSomething}/>
)
}
}
``` |
115733 | I am using CodeIgniter and have a login system. I am still fairly new with php and I am wondering once the user is logged in, how I can access his/her data to use throughout the site? Right now I am trying to make it say welcome "username" but I dont know where the variables come from and how I should use them. Right now in my home\_view.php I have:
```
<div class="main">
<h2>Welcome <?php echo $username; ?>!</h2>
</div>
```
It throws this error:
```
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: username
Filename: views/home_view.php
Line Number: 22
```
Can someone tell me how to do this? | >
> Question: How do you access a logged-in user's data for use throughout the site?
>
>
>
The logged-in user specific data is usually stored in a session. For codeigniter, you can access session data using `$this->session->userdata('item');`, or for example `$this->session->userdata('username');`.
However, if you are using a specific login system **it depends on the login system that you are using**.
---
**Custom Login System**
After receiving the login information from a login form, pass the data to the session using the following:
```
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe@some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
```
Then refer to the username with the following:
```
$this->session->userdata('username');
```
See [Adding Custom Session Data](https://ellislab.com/codeigniter/user-guide/libraries/sessions.html) in the Codeigniter Documentation.
---
**Login System Example**
A popular codeigntier authentication library is [Tank-Auth](https://github.com/TankAuth/Tank-Auth).
When using Tank-Auth, after a user is logged in, you can call `$this->tank_auth->get_username()` (which calls `$this->ci->session->userdata('username')`, as mentioned above). This can then be stored and passed to a view.
In Tank-Auth you will see:
application/controller/welcome.php
```
$data['user_id'] = $this->tank_auth->get_user_id();
$data['username'] = $this->tank_auth->get_username();
$this->load->view('welcome', $data);
```
application/views/welcome.php
```
Hi, <strong><?php echo $username; ?></strong>! You are logged in now.
``` |
115773 | **Bug introduced after 10.0, in 10.3 or earlier and persisting in 13.2.1**
---
I'm fairly sure the following is a bug, and I would normally just report it to WRI. However, this is related to my answer to
[When using NDsolve, how to determine the positions of steady states?](https://mathematica.stackexchange.com/questions/86276/when-using-ndsolve-how-to-determine-the-positions-of-steady-states)
So I thought I would post it as a question, for two reasons. One is to let the community verify that it is in fact a bug. The other is to give a reference to the issue for the other question.
Here is a simplified example. With the `WhenEvent` rule `x[t] -> 1.`, `NDSolve` fails to integrate the ODE and gives no message.
```
{sol} = NDSolve[
{x'[t] == -0.08 x[t], x[0] == 1.,
WhenEvent[Norm[{x'[t]}] < 0.0001, {x[t] -> 1.}]},
{x}, {t, 0, 200}]
```
![Mathematica graphics](https://i.stack.imgur.com/6ehB3.png)
One the other hand, using an empty action, the system is integrated:
```
{sol} = NDSolve[
{x'[t] == -0.08 x[t], x[0] == 1.,
WhenEvent[Norm[{x'[t]}] < 0.0001, {}]},
{x}, {t, 0, 200}]
```
![Mathematica graphics](https://i.stack.imgur.com/xfaDp.png)
Problem also seems connected to the use of the derivative `x'[t]` in the event condition. It works fine with `x[t]`.
![Mathematica graphics](https://i.stack.imgur.com/rfncN.png)
Am I doing something wrong, or is it a bug?
*[Mathematica 10.4.1, OSX 10.11.4.]* | Here is a workaround suggested by the response I received from WRI:
```
{sol} = NDSolve[{x'[t] == -0.08 x[t], x[0] == 1.,
WhenEvent[Norm[{x'[t]}] < 0.0001, {x[t] -> 1.}]},
{x}, {t, 0, 200},
Method -> {"EquationSimplification" -> "Residual"}
]
Plot[x[t] /. sol, {t, 0, 200}]
```
![Mathematica graphics](https://i.stack.imgur.com/HwCZu.png)
Warning: This option works by converting the system to a DAE, for which only machine-real code is available. That is probably sufficient for most cases, but it does limit one's options. For example, you cannot change `WorkingPrecision`, and it will not solve a BVP.
The response from WRI suggested using `NDSolve[.., SolveDelayed -> True]`, which indeed works. Its use with `NDSolve` is pretty much undocumented, and it shows up in red in the front end. One can find references to it in the documentation for the messages
[`NDSolve::ntdv`](http://reference.wolfram.com/language/ref/message/NDSolve/ntdv.html)
and
[`NDSolve::ndnum`](http://reference.wolfram.com/language/ref/message/NDSolve/ndnum.html).
While the text for `NDSolve::ntdv` in the documentation advises trying `SolveDelayed -> True`, the text in my current system (V10.4.1) reads like this:
```
NDSolve::ntdv
(*
"Cannot solve to find an explicit formula for the derivatives. \
Consider using the option \
Method->{\"EquationSimplification\"->\"Residual\"}."
*)
```
It's hard to know which option should be considered the preferred solution. After a little testing, they seem to produce **identical** solutions, so I feel they might be invoking the same internal code. I opted for `"EquationSimplification"` because it is documented for DAEs.
Also, the response from WRI did not indicate that they thought this was a bug (or "issue"); it did not indicate otherwise either. |
116660 | I'm trying to create a comment tree but I don't have any idea how to do that. The package I found on `pub.dev` is not like what I want. I mesh with codes. No tutorial found related to me.
This is what I want :
[![Image](https://i.stack.imgur.com/RajQh.jpg)](https://i.stack.imgur.com/RajQh.jpg)
I want a tutorial or idea to create design like showing in the image. | Welcome to stackoverflow and C++!
I tool the liberty of fixing some smaller issues with the code:
`<cmath>` is the proper C++ header, use that instead of `<math.h>` (the C header. C and C++ are different).
Do not build an early habit of `using namespace std`. Yes, it seems convenient, but [read here why you should not do it.](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice)
Using `std::endl` will likely drop your performance. [Read here about the differences](https://stackoverflow.com/questions/213907/stdendl-vs-n). using `\n` works just as good, is cross-platform-compatible and even less to type.
Does this achieve what you want?
```
#include <cmath>
#include <iostream>
#include <string>
class People{
public:
std::string name;
int age;
bool educated;
People(){
std::cout << typeid(*this).name() << "class people is initialised\n";
}
~People(){
std::cout << typeid(*this).name() << "class people is destroyed\n";
}
private:
double worth;
};
int main(){
People Joe;
}
```
Responding to the comment:
```
People(std::string const& str)
: name(str)
{
std::cout << name << " class people is initialised\n";
}
////
int main(){
Person Joe("Joe");
}
```
Note this important difference:
`People(std::string str)` will create a copy of the string (which is usually expensive).
`People(std::string const& str)` will create a constant reference. Constant means it can not be changed and since it is a reference, it will not be copied here (it will be copied into the class member though). |
116707 | We had to write a program that would perform rotation of elements in an array. The array size was entered by user, so it had to be in a sense, dynamic.
**Rotation or Circular Shifting**
Initial Array: `1 3 7 4 8 6 5 2 9`
Shift by: `4`
Final Array: `6 5 2 9 1 3 7 4 8`
Notice, in rotation, each elements position increased by shift amount. Also, elements in the end came to the front.
**My Try**
I used an approach in which I had to create a new array of **size = shift amount**. This array stored the **shift no. of** elements in the end of array. Now I shifted all the elements in the beginning of array by shift amount. In the end, I copied the elements of shift sized array to beginning of original array.
I tried to use minimum memory possible so only used **shift sized array**. I and keep it a bit fast (**shift%=n** statement to reduce inefficiency if **shift >= n**).
```
// Rotation
#include <iostream>
int main() {
int n;
std::cout << "Array size: ";
std::cin >> n;
int* list = new int[n];
std::cout << "Enter elements:\n";
for( int i = 0; i < n; ++i) {
std::cin >> list[i];
}
int shift;
std::cout << "Shift amount: ";
std::cin >> shift;
shift %= n; // to reduce work if shift > n
int* temp = new int[shift];
for( int i = n-shift; i < n ; ++i) {
temp[i-n+shift] = list[i];
}
for( int i = n-1; i >= shift; --i) {
list[i] = list[i-shift];
}
for( int i = 0; i < shift; ++i) {
list[i] = temp[i];
}
delete [] temp;
// Printing
for( int i = 0; i < n; ++i) {
std::cout << list[i] << " ";
}
delete [] list;
}
```
**Question**
My question is that all the optimization that i was able to make were a bit obvious and natural. I wanted to know if there was a **significant algorithmic, or memory optimization** possible for this problem.
**PS**
I know there's a function `std::rotate` available from `algorithm`, but we had to solve this problem on our own. | I see some things that may help you improve your program.
Separate I/O from calculations
------------------------------
The program has three basic phases. First, it gets input, then it manipulates that input, and then it produces output. I would recommend putting the rotation code into a separate function.
Consider signed vs. unsigned
----------------------------
Does it make sense to have a negative array size? Does it make sense to have a negative shift value? I'd answer "no" to the first and "yes" to the second question. For that reason, I'd recommend making `n` a `size_t` or `unsigned` type and also adding code to handle negative rotations.
Rethink your algorithm
----------------------
The code currently creates a temporary array, but all that's really needed is a single temporary `int`. Here's one way to do it:
```
unsigned gcd(unsigned a, unsigned b) {
return b == 0 ? a : gcd(b, a % b);
}
void rotate(unsigned n, int shift, int *list)
{
if (shift < 0) {
shift = n -(-shift % n);
} else {
shift %= n;
}
if (shift == 0) {
return;
}
for (unsigned cycles = gcd(n, shift); cycles; --cycles) {
unsigned i = 0;
unsigned nexti = n-shift;
for (int temp=list[nexti+cycles-1]; nexti; i = nexti) {
nexti = i+shift;
if (nexti >= n) {
nexti -= n;
}
std::swap(temp, list[i+cycles-1]);
}
}
}
```
Worked example
--------------
This is probably easier to understand with an example. Let's start with a simple array or length 7 = `{ 0, 1, 2, 3, 4, 5, 6}` and a requested shift amount of 4. When the `for` loop starts we have this:
[![step 0](https://i.stack.imgur.com/u2LZR.gif)](https://i.stack.imgur.com/u2LZR.gif)
[![step 1](https://i.stack.imgur.com/McVUi.gif)](https://i.stack.imgur.com/McVUi.gif)
[![step 2](https://i.stack.imgur.com/E4J3H.gif)](https://i.stack.imgur.com/E4J3H.gif)
[![step 3](https://i.stack.imgur.com/T3qVF.gif)](https://i.stack.imgur.com/T3qVF.gif)
[![step 4](https://i.stack.imgur.com/wTl3R.gif)](https://i.stack.imgur.com/wTl3R.gif)
[![step 5](https://i.stack.imgur.com/Oac8j.gif)](https://i.stack.imgur.com/Oac8j.gif)
[![step 6](https://i.stack.imgur.com/PwTWD.gif)](https://i.stack.imgur.com/PwTWD.gif) |
116756 | As far as I am aware,
1. HDMI 2.1 does support 12-bit 4K 60fps, Also it doesn't use TMDS, rather FRL. Sends upto 48Gbps
2. GPUs can do calculation in fp32 and from some reference, I think that it can send 16bpc (48-bit per pixel deep color) (Assuming that it is a high end Quadro GPU) (fp16 had the capability to send 12bpc 36-bit deep color, right?)
But there are monitors that don't support more than 10bpc 30-bit depth deep color
Why is that? Why do displays have limited bit-depth?
Can you give me some idea about the science behind this? Why does it cost more to produce higher bit-depth monitors?
Isn't it like, RGB pixels on the displays are emitting photons? Then how do different displays differ in terms of emitting photons? | The short answer is, cost. Higher bit-depths require more bandwidth at every point in the digital signal chain, from rendering unit, DRAM, link, all the way to the DACs that drive the panel.
Technology being what it is, as pipeline costs have come down, deeper color standards have been introduced, so panels have evolved along with the rest of the display ecosystem to offer both higher resolution and increased color depth. To enable this, HDMI 2.1 supports 8K and 48 bits per pixel now.
Looking further up the pipeline, cameras commonly support 12 bits, with 14 coming available (RAW modes). Editing systems already use 16 bits per component internally and quantize back down at the end when the work is finalized.
I should also mention the various HDR coding schemes that seek to improve display dynamic range in a more bit-efficient way than just adding more color bits. |
116762 | From the OPTPARSE library reference:
```
option_list = [
make_option("-f", "--filename",
action="store", type="string", dest="filename"),
make_option("-q", "--quiet",
action="store_false", dest="verbose"),
]
parser = OptionParser(option_list=option_list)
```
---
Like the above example, I want to make a option list using make\_option and pass it to a decorator which instantiates the parser and adds the arguments.
How can this be achieved in argparse? Is there a way to populate the parser other than parse\_args()? | You can give `argparse.ArgumentParser` a list of [parent parsers](http://docs.python.org/2.7/library/argparse.html#parents):
```
parent = argparse.ArgumentParser(add_help=False)
parent.add_argument('-f','--filename')
parent.add_argument('-q','--quiet',action='store_false',dest='verbose')
parser = argparse.ArgumentParser(parents=[parent])
...
namespace = parser.parse_args()
``` |
117149 | I have two tables in my db, one that records exceptions, and another that records log messages.
I am leveraging the `SqlDependency` object to be notified when those tables change so that I can update my web dashboard. I got this working:
```
public IEnumerable<ElmahException> GetExceptions()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["elmah-sqlserver"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(@"SELECT [ErrorId],[Application],[Host],[Type],[Source],[Message],[User],[StatusCode],[TimeUtc],[Sequence],[AllXml]
FROM [dbo].[ELMAH_Error] ORDER BY [TimeUtc] desc", connection))
{
// Make sure the command object does not already have
// a notification object associated with it.
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(ELMAHdependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new ElmahException()
{
ErrorId = x.GetGuid(0),
Application = x.GetString(1),
Host = x.GetString(2),
Type = x.GetString(3),
Source = x.GetString(4),
Error = x.GetString(5),
User = x.GetString(6),
Code = x.GetInt32(7),
TimeStamp = x.GetDateTime(8).ToString().Replace("T", " ")
}).ToList();
}
}
}
private void ELMAHdependency_OnChange(object sender, SqlNotificationEventArgs e)
{
Console.Write("Exception table changed!");
}
```
This is working well, so with the wind in my sails, I then took a crack at doing something similar for the log messages:
```
public IEnumerable<LogMessage> GetLogMessages()
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["elmah-sqlserver"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(@"SELECT [application],[time_stamp],[logLevel],[logger],[message]
FROM [dbo].[LogTable] ORDER BY [time_stamp] desc", connection))
{
// Make sure the command object does not already have
// a notification object associated with it.
command.Notification = null;
SqlDependency dependency = new SqlDependency(command);
dependency.OnChange += new OnChangeEventHandler(NLOGdependency_OnChange);
if (connection.State == ConnectionState.Closed)
connection.Open();
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new LogMessage()
{
Application = x.GetString(0),
TimeStamp = x.GetDateTime(1).ToString().Replace("T", " "),
LogLevel = x.GetString(2),
Logger = x.GetString(3),
Message = x.GetString(4)
}).ToList();
}
}
}
private void NLOGdependency_OnChange(object sender, SqlNotificationEventArgs e)
{
Console.Write("Log table has changed!");
}
```
At this point, I am alerted only to when the log table has changed. With this additional `SqlDependency` in the mix, `ELMAHdependency_OnChange` never gets called. If I comment out my `GetLogMessages()` method, then `ELMAHdependency_OnChange` is called once more.
It looks like multiple `SqlDependency` objects are mutually exclusive. Any ideas on how I can monitor two tables at the same time? | It is possible to concatenate another SqlStatement using a semicolon.
Here's a snippet from your code, with my changes.
```
[...]
connection.Open();
var queries = new [] {@"SELECT [application],[time_stamp],[logLevel],[logger],[message] FROM [dbo].[LogTable] ORDER BY [time_stamp] desc",
@"SELECT [ErrorId],[Application],[Host],[Type],[Source],[Message],[User],[StatusCode],[TimeUtc],[Sequence],[AllXml] FROM [dbo].[ELMAH_Error] ORDER BY [TimeUtc] desc"};
using (SqlCommand command = new SqlCommand(string.Join("; ", queries), connection))
{
[...]
```
It's also important to re-register the `SqlDependency` once it has called the event. Or else the event is only triggered once..
```
private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
{
SqlDependency dependency = sender as SqlDependency;
if (dependency != null) dependency.OnChange -= dependency_OnChange;
if (e.Type == SqlNotificationType.Change)
{
// Do things
}
SetupDatabaseDependency();
}
```
`SetupDatabaseDependency()` would contain the code to set up the `SqlDependency`. |
117837 | Let me begin with the disclaimer: I am a mathematician and not an electrical engineer. That being said, surely I am missing something simple. For classroom demonstrations in dynamical systems, I have been constructing analogue computers from op-amp circuits. Some of the circuits are of my own design, and some are copied from other scientists. All of them have been successful except for this one, by Cuomo & Oppenheim, 1993, Physics Review Journal:
![Cuomo & Oppenheim - MIT 1993](https://i.stack.imgur.com/YDNsV.png)
This circuit is designed to mimic the Lorenz Equations (rather, a re-scaled version thereof). The [x] are analog multipliers (AD633JN), and I am using NTE858M op amps. I have checked my work and I am convinced that I have built correctly. I have also verified the accuracy of the schematic, and I cannot find any discrepancy between the circuit and the corresponding dynamical system. The only output is a millivolts noise.
Why does this implementation fail?
Here is a link to the author's paper for more detailed information:
<http://www.rle.mit.edu/dspg/documents/CircuitImplementation_000.pdf> | Here's is my thoughts I think that implementation might fail is because in the paper you reference, the author's use the device AD632AD multiplier while you are using the AD633JN multiplier. A quick glance through the datasheet and we can see that the AD632AD multiplier performance total error has maximum of +/-1 while the AD633JN has a multiplier performance total error has maximum of +/-2. Also the AD632 multiplier under the multiplier perfomance has a maximum Output Offset Voltage of +/-30mV while the AD633 has a maximum Output Offset Voltage of +/-50mV. It think that those differences between might be worth looking into because given the nature of chaotic system it might just be enough to modified the circuit behavior. |
117881 | I can't seem to get my head around the off-line minimum algo. Can someone explain it to me more?
Possibly with pseudo-code in a "near-code" fashion.
Say, for example, that I have the following sequence:
```
"5","4","6","E","1","7","E","E","3","2"
```
**What are the steps to return the smallest integer in the whole set.** I understand the problem but I don't seem to find a way to code it.
Regards | If you want people to give you the code they wont.
In terms of this particular problem with the list you have given you can either
1) sort it then start from the begining to find the smallest integer
2) just run through every number
You can keep a temporary variable to keep the current lowest. Then step through and compare it to this variable. If it is lower then set that value to the lowest value.
Once you have finished stepping through them all you just return the value of that temporary variable. |
118016 | I've looked at a number of questions but can't find a **good** solution for a View-Based NSOutlineView
[Coloring NSTableView Text per row](https://stackoverflow.com/questions/2786362/coloring-nstableview-text-per-row)
[Change color of NSTableViewCell](https://stackoverflow.com/questions/2879154/change-color-of-nstableviewcell)
[Custom background colors for NSTableCellView](https://stackoverflow.com/questions/16369061/custom-background-colors-for-nstablecellview)
I'm trying to set each row to whatever color I want. I've read somewhere that I need to subclass `NSTableRowView` which I've now done.
According to the [AppleDocs](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSTableRowView_Class/Reference/Reference.html), I see the following methods:
```
– drawBackgroundInRect:
– drawDraggingDestinationFeedbackInRect:
– drawSelectionInRect:
– drawSeparatorInRect:
```
How would I go about setting the background color for the individual rows? Am I going the wrong route above?
**Edit: below (also edited title)**
Since i'm using an NSOutlineView and not a NSTableView, when i change the background color of the cells the image looks like the following. The disclosure arrows to the left is not colored. Is there any way to change the color of the whole row for the NSOutlineView?
![this](https://i.stack.imgur.com/p9rRj.png) | You could subclass NSTableViewCell, and add a method to it which sets its color.
NSTableViewCell is already a subclass of NSView, so in your subclass, you would add the following method:
```
- (void)setBackgroundColor {
self.layer.backgroundColor = CGColorCreateGenericRGB(0, 0, 0, 1.0f); // or whatever color
}
```
Or something like that. You'll probably want to have the color be a param to the method. Then, in your table view delegate, you can set the color depending on the row index passed to the delegate method. For example:
```
- (UITableViewCell *)tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:@"Cell"];
if (cell == nil)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
if (indexPath.row % 2) {
[cell setBackgroundColor:[UIColor redColor]]; // or something like that
}
}
``` |
118042 | How can i check if user is logged in to umbraco from the view(.cshtml)?
I would also know how to check the users role.
`User.Identity.IsAuthenticated` always returns false.
```
if( User has role = "someRole" )
{
do stuff
}
```
Im using Umbraco version: 7.8.1 | If `User.Identity.IsAuthenticated` is false you are probably not calling `FormsAuthentication.SetAuthCookie(username, true);` after the user is successfully validated.
To check the authentication and roles use:
```
var userIsAuthenticated = Request.IsAuthenticated;
var userIsAdmin = User.IsInRole(role: "admin");
``` |
118690 | **Problem:** Consider the subfield $$E = \mathbb{Q} \big(\left\{\sqrt[n]{2} \mid n \in \mathbb{N} \setminus \left\{0\right\} \right\} \big)$$ of $\mathbb{R}$. Prove that $[E: \mathbb{Q}]$ is not finite.
**Attempt:** I proved that $E$ is algebraic over $\mathbb{Q}$. Because let $u \in E$. Then there is a $n \in \mathbb{N} \setminus \left\{0\right\}$ such that $u = \sqrt[n]{2}$. Then $f(x) = x^n - 2 \in \mathbb{Q}[x]$ is the minimal polynomial of $u$ over $\mathbb{Q}$ such that $f(u) = 0$. Hence $E$ is algebraic over $\mathbb{Q}$.
I now want to prove the degree of extension is not finite. I assume it is finite. Suppose then $[E: \mathbb{Q}] = k \in \mathbb{N}$. I don't know how to derive a contradiction from this.
I know that if $u$ is algebraic over $\mathbb{Q}$ and $f$ is the minimal polynomial of $u$ over $\mathbb{Q}$, then $[\mathbb{Q}(u) : \mathbb{Q}] = \deg(f)$.
Help/suggestions are appreciated. | The good news is that looks like you have all the pieces of information required; you just need to arrange them into the correct order to make the argument.
As you noted, if $f$ is an irreducible polynomial of degree $n$ over some field $F$, then $F(\alpha)$ is a degree $n$ field extension of $F$, for any root $\alpha$ of $f$. This fact, together with the fact that $f(x) = x^n - 2$ is irreducible over $\mathbb{Q}$ per Eisenstein gives you what you want.
In particular, suppose the extension in question is finite, say of degree $m$, and consider $\sqrt[n]{2}$ for some $n>m$. Since $\sqrt[n]{2} \in E$ by assumption, we must have a tower of inclusions $\mathbb{Q} \subset \mathbb{Q}( \sqrt[n]{2}) \subset E$: a contradiction per the [multiplicativity formula](https://en.wikipedia.org/wiki/Degree_of_a_field_extension#The_multiplicativity_formula_for_degrees).
---
P.S.: Be careful with this statement:
>
> let $u \in E$. Then there is a $n \in \mathbb{N} \setminus \left\{0\right\}$ such that $u = \sqrt[n]{2}$.
>
>
>
This is not *quite* true. The statement you're looking for is that $u$ can be written as some combination of powers of elements from a finite subset of the generating set. To be specific, the notation $F(S)$ for some set $S$ denotes $\Big\{f(u\_1, u\_2, ..., u\_k) \ \Big| \ u\_i's \in S, \ f \in F[x\_1, x\_2, ..., x\_k], \ k \in \mathbb{N} \Big\}$. For a concrete example, notice that $\displaystyle 1 + 5\sqrt[3]{2} - \frac{4}{7}(\sqrt[3]{2})^2 \in \mathbb{Q}(\sqrt[3]{2})$. The conclusion is salvageable, however, since it can be shown that the set of algebraic numbers is a field (hence addition/multiplication of algebraic numbers yields an algebraic number). In this case, $S = \{ \sqrt[k]{2} \ | \ k \in \mathbb{N} \}$ is comprised entirely of algebraic elements, so $E$ is algebraic. |
118827 | >
> **Possible Duplicate:**
>
> [Rails 3 deprecated methods and APIs](https://stackoverflow.com/questions/3648063/rails-3-deprecated-methods-and-apis)
>
>
>
What resources are out there (free or paid) that help walk you through the process of migrating a Ruby on Rails 2 application to Rails 3? I've seen some blog posts (some of which seem out of date) and an eBook for sale somewhere on the RoR website, but what can you recommend as an accurate and complete explanation of what changed from version 2 to version 3 and what needs to be updated when porting to a Rails 3 environment? | Watch this <http://railscasts.com/episodes/225-upgrading-to-rails-3-part-1> |
118865 | I have been trying to code a script to upload files only if all selected files match predefined type (pdf,doc or docx). For example if user select 3 files all of them need to match the criteria or none of the selected ones will be uploaded.
here is what I have so far:
```
<?php
for($i=0; $i<count($_FILES['file']['name']); $i++) {
$file_type = $_FILES['file']['type'][$i];
$allowedExts = array("application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
if(in_array($file_type, $allowedExts))
{
if ($_FILES["file"]["error"][$i] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"][$i] . "<br>";
}
else
{
if (file_exists("uuuuu/" . $_FILES["file"]["name"][$i]))
{
$file_name = $HTTP_POST_FILES['file']['name'][$i];
$random_digit=rand(0000,9999);
$new_file_name=$random_digit.$file_name;
$file_final = str_replace(' ', '_', $new_file_name);
$path= "uuuuu/".$file_final;
copy($HTTP_POST_FILES['file']['tmp_name'][$i], $path);
$message = "success....";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"][$i],
"uuuuu/" . $_FILES["file"]["name"][$i]);
$message = "success....";
}
}
}
else
{
$message1 ="at least one of your files has the wrong extension! you can only select doc,docx or pdf";
}
}
?>
<form id="form2" name="form2" method="post" action="" enctype="multipart/form-data">
<input name="file[]" type="file" id="file" class="for-text-fields" multiple="multiple"/>
<label for="textarea2"></label>
<textarea name="textarea2" id="textarea2" rows="10" class="for-text-f"></textarea>
<br /><br />
<input name="submit" type="submit" id="submit" value="submit" />
</form>
```
I know this should not be hard to do but I can not sort it out :( I would really appriciate your help on this one.
EDIT: I forgot to mention that there will be 4 text fields where users will type some title for each selected file, be it 1, 2,3 or four and thats why I want all of the selected ones to match the type, namely to easily write the update script... hope this makes any sense | You don't have an `.accordion` element ?
```
$('.accordion-group').on('show hide', function (n) {
$(n.target).siblings('.accordion-heading').find('.accordion-toggle i').toggleClass('icon-chevron-up icon-chevron-down');
});
```
[**FIDDLE**](http://jsfiddle.net/HwNYB/19/) |
119895 | Problem Background
------------------
I am currently working on a camel based ETL application that processes groups of files as they appear in a dated directory. The files need to be processed together as a group determined by the beginning of the file name. The files can only be processed once the done file (".flag") has been written to the directory. I know the camel file component has a done file option, but that only allows you to retrieve files with the same name as the done file. The application needs to run continuously and start polling the next day's directory when the date rolls.
**Example Directory Structure:**
```
/process-directory
/03-09-2011
/03-10-2011
/GROUPNAME_ID1_staticfilename.xml
/GROUPNAME_staticfilename2.xml
/GROUPNAME.flag
/GROUPNAME2_ID1_staticfilename.xml
/GROUPNAME2_staticfilename2.xml
/GROUPNAME2_staticfilename3.xml
/GROUPNAME2.flag
```
Attempts Thus Far
-----------------
I have the following route (names obfuscated) that kicks off the processing:
```
@Override
public void configure() throws Exception
{
getContext().addEndpoint("processShare", createProcessShareEndpoint());
from("processShare")
.process(new InputFileRouter())
.choice()
.when()
.simple("${header.processorName} == '" + InputFileType.TYPE1 + "'")
.to("seda://type1?size=1")
.when()
.simple("${header.processorName} == '" + InputFileType.TYPE2 + "'")
.to("seda://type2?size=1")
.when()
.simple("${header.processorName} == '" + InputFileType.TYPE3 + "'")
.to("seda://type3?size=1")
.when()
.simple("${header.processorName} == '" + InputFileType.TYPE4 + "'")
.to("seda://type4?size=1")
.when()
.simple("${header.processorName} == '" + InputFileType.TYPE5 + "'")
.to("seda://type5?size=1")
.when()
.simple("${header.processorName} == '" + InputFileType.TYPE6 + "'")
.to("seda://type6?size=1")
.when()
.simple("${header.processorName} == '" + InputFileType.TYPE7 + "'")
.to("seda://type7?size=1")
.otherwise()
.log(LoggingLevel.FATAL, "Unknown file type encountered during processing! --> ${body}");
}
```
My problems are around how to configure the file endpoint. I'm currently trying to programatically configure the endpoint without a lot of luck. My experience in camel thus far has been predominently using the Spring DSL and not the Java DSL.
I went down the route of trying to instantiate a FileEndpoint object, but whenever the route builds I get an error saying that the file property is null. I believe this is because I should be creating a FileComponent and not an endpoint. I'm not creating the endpoint without using a uri because I am not able to specify the dynamic date in the directory name using the uri.
```
private FileEndpoint createProcessShareEndpoint() throws ConfigurationException
{
FileEndpoint endpoint = new FileEndpoint();
//Custom directory "ready to process" implementation.
endpoint.setProcessStrategy(getContext().getRegistry().lookup(
"inputFileProcessStrategy", MyFileInputProcessStrategy.class));
try
{
//Controls the number of files returned per directory poll.
endpoint.setMaxMessagesPerPoll(Integer.parseInt(
PropertiesUtil.getProperty(
AdapterConstants.OUTDIR_MAXFILES, "1")));
}
catch (NumberFormatException e)
{
throw new ConfigurationException(String.format(
"Property %s is required to be an integer.",
AdapterConstants.OUTDIR_MAXFILES), e);
}
Map<String, Object> consumerPropertiesMap = new HashMap<String, Object>();
//Controls the delay between directory polls.
consumerPropertiesMap.put("delay", PropertiesUtil.getProperty(
AdapterConstants.OUTDIR_POLLING_MILLIS));
//Controls which files are included in directory polls.
//Regex that matches file extensions (eg. {SOME_FILE}.flag)
consumerPropertiesMap.put("include", "^.*(." + PropertiesUtil.getProperty(
AdapterConstants.OUTDIR_FLAGFILE_EXTENSION, "flag") + ")");
endpoint.setConsumerProperties(consumerPropertiesMap);
GenericFileConfiguration configuration = new GenericFileConfiguration();
//Controls the directory to be polled by the endpoint.
if(CommandLineOptions.getInstance().getInputDirectory() != null)
{
configuration.setDirectory(CommandLineOptions.getInstance().getInputDirectory());
}
else
{
SimpleDateFormat dateFormat = new SimpleDateFormat(PropertiesUtil.getProperty(AdapterConstants.OUTDIR_DATE_FORMAT, "MM-dd-yyyy"));
configuration.setDirectory(
PropertiesUtil.getProperty(AdapterConstants.OUTDIR_ROOT) + "\\" +
dateFormat.format(new Date()));
}
endpoint.setConfiguration(configuration);
return endpoint;
```
Questions
---------
1. Is implementing a GenericFileProcessingStrategy the correct thing to do in this situation? If so, is there an example of this somewhere? I have looked through the camel file unit tests and didn't see anything that jumped out at me.
2. What am I doing wrong with configuring the endpoint? I feel like the answer to cleaning up this mess is tied in with question 3.
3. Can you configure the file endpoint to roll dated folders when polling and the date changes?
As always thanks for the help. | You can refer to a custom ProcessStrategy from the endpoint uri using the processStrategy option, eg file:xxxx?processStrategy=#myProcess. Notice how we prefix the value with # to indicate it should lookup it from the registry. So in Spring XML you just add a
<bean id="myProcess" ...> tag
In Java its probably easier to grab the endpoint from the CamelContext API:
```
FileEndpoint file = context.getEndpoint("file:xxx?aaa=123&bbb=456", FileEndpoint.class);
```
This allows you to pre configure the endpoint. And of course afterwards you can use the API on FileEndpoint to set other configurations. |
120230 | So I've designed a program that runs on a computer, looks for particular aspects of files that have been plaguing us, and deletes the files if a flag is passed. Unfortunately the program seems to be almost-randomly shutting down/crashing. I say almost-randomly, because the program always exits after it deletes a file, though it will commonly stay up after a success.
I've run a parallel Python program that counts upwards in the same intervals, but does nothing else. This program does not crash/exit, and stays open.
Is there perhaps a R/W access issue? I am running the program as administrator, so I'm not sure why that would be the case.
Here's the code:
```
import glob
import os
import time
import stat
#logging
import logging
logging.basicConfig(filename='disabledBots.log')
import datetime
runTimes = 0
currentPhp = 0
output = 0
output2 = 0
while runTimes >= 0:
#Cycles through .php files
openedProg = glob.glob('*.php')
openedProg = openedProg[currentPhp:currentPhp+1]
progInput = ''.join(openedProg)
if progInput != '':
theBot = open(progInput,'r')
#Singles out "$output" on this particular line and closes the process
readLines = theBot.readlines()
wholeLine = (readLines[-4])
output = wholeLine[4:11]
#Singles out "set_time_limit(0)"
wholeLine2 = (readLines[0])
output2 = wholeLine2[6:23]
theBot.close()
if progInput == '':
currentPhp = -1
#Kills the program if it matches the code
currentTime = datetime.datetime.now()
if output == '$output':
os.chmod(progInput, stat.S_IWRITE)
os.remove(progInput)
logging.warning(str(currentTime) +' ' + progInput + ' has been deleted. Please search for a faux httpd.exe process and kill it.')
currentPhp = 0
if output2 == 'set_time_limit(0)':
os.chmod(progInput, stat.S_IWRITE)
os.remove(progInput)
logging.warning(str(currentTime) +' ' + progInput + ' has been deleted. Please search for a faux httpd.exe process and kill it.')
currentPhp = 0
else:
currentPhp = currentPhp + 1
time.sleep(30)
#Prints the number of cycles
runTimes = runTimes + 1
logging.warning((str(currentTime) + ' botKiller2.0 has scanned '+ str(runTimes) + ' times.'))
print('botKiller3.0 has scanned ' + str(runTimes) + ' times.')
``` | Firstly, it'll be hell of a lot easier to work out what's going on if you base your code around something like this...
```
for fname in glob.glob('*.php'):
with open(fname) as fin:
lines = fin.readlines()
if '$output' in lines[-4] or 'set_time_limit(0)' in lines[0]:
try:
os.remove(fname)
except IOError as e:
print "Couldn't remove:", fname
```
And err, that's not actually a secondly at the moment, your existing code is just too tricky to follow fullstop, let alone all the bits that could cause a strange error that we don't know yet! |
120276 | ```
numberrange returns [String value]
: numberrangesub
{
String numberRange = ($numberrangesub.text);
String [] v = numberRange.split(",");
if ( Integer.parseInt(v[0].trim()) < Integer.parseInt(v[1].trim())) $value =numberRange;
else throw new RecognitionException();
}
;
```
Please observe the above ANTLR code. In this I want to throw a user friendly error message like `"from value should be less than to value in BETWEEN clause"`.
I am expecting like this `RecognitionException("from value should be less than to value in BETWEEN clause");` But antlr did not accept like as above.
In java class where I am calling the generated java class by Antlr. I am handling like as follows.
```
try
{
parser.numberRangeCheck();
}
catch (RecognitionException e)
{
throw createException("Invalid Business logic syntax at " + parser.getErrorHeader(e) + ", " + parser.getErrorMessage(e, null), Level.INFO, logger);
}
```
Any help will be appriciated. | try reordering your chaining like:
```
Product.currency(0.69).all
```
I have not tested that, but you may have issue with other arbitrary conditions since your `:select` contains `*` |
120495 | I have a 1-0 matrix data from excel csv file for market basket analysis to apply association rule. However, program cannot find any rule. Probably, it reads the 0 and 1s as string. When I convert to them numeric, the program gives error and cannot generate any rules again.
How can I convert it to binary variables in order to use in association rule finding?
```
> y <- read.transactions("C:/Users/toshıba pc/Desktop/2009.csv")
Warning message:
In asMethod(object) : removing duplicated items in transactions
> rules <- apriori(y, parameter=list(supp=0.1, conf=0.8))
Apriori
Parameter specification:
confidence minval smax arem aval originalSupport maxtime support minlen maxlen target ext
0.8 0.1 1 none FALSE TRUE 5 0.1 1 10 rules FALSE
Algorithmic control:
filter tree heap memopt load sort verbose
0.1 TRUE TRUE FALSE TRUE 2 TRUE
Absolute minimum support count: 52
set item appearances ...[0 item(s)] done [0.00s].
set transactions ...[553 item(s), 521 transaction(s)] done [0.00s].
sorting and recoding items ... [0 item(s)] done [0.00s].
creating transaction tree ... done [0.00s].
checking subsets of size 1 done [0.00s].
writing ... [0 rule(s)] done [0.00s].
creating S4 object ... done [0.00s].
> rules <- apriori(y, parameter=list(supp=0.01, conf=0.8))
Apriori
Parameter specification:
confidence minval smax arem aval originalSupport maxtime support minlen maxlen target ext
0.8 0.1 1 none FALSE TRUE 5 0.01 1 10 rules FALSE
Algorithmic control:
filter tree heap memopt load sort verbose
0.1 TRUE TRUE FALSE TRUE 2 TRUE
Absolute minimum support count: 5
set item appearances ...[0 item(s)] done [0.00s].
set transactions ...[553 item(s), 521 transaction(s)] done [0.00s].
sorting and recoding items ... [0 item(s)] done [0.00s].
creating transaction tree ... done [0.00s].
checking subsets of size 1 done [0.00s].
writing ... [0 rule(s)] done [0.00s].
creating S4 object ... done [0.00s].
> enter image description here
``` | I had to add the type="javax.sql.DataSource" in the context of my application
```
<ResourceLink
name="jdbc/toto"
global="shared/jdbc/toto"
type="javax.sql.DataSource"
/>
```
You need to write the type in the ressource definition and in the context of your server.xml |
120730 | I have a class which has a property of generic type as given below. Type T can be any number (short, int, float ...)
```
public class EqualFilter <T> : Filter {
private T _value;
public override T Value {
get {
return _value;
}
set {
if (!EqualityComparer<T>.Default.Equals(_value, value)) {
_value = value;
RaiseFilteringChanged();
}
}
}
.....
}
```
Now I have a client class which has a "String" that needs to be passed to the above setter. Now at the time of setting the value in the above setter, the type T is already determined at runtime and I can get hold of that type as Type T in my client. Is it possible to convert the string to the appropriate type ,as identified by the EqualFilter, in client program? Something like this that is not working
```
Type T = filter.getFilterType();
filter.Value = (T) myTextBox.Text;
```
The below code works but it will involve if-else for all the types that can be numeric.
```
Type T = filter.getFilterType();
if (T == typeof(int)) {
filter.Value = Int32.Parse(myTextBox.Text);
} else if() {
....
}
```
In short I am not sure how to approach the issue in a better way. | You could try the following:
```
filter.Value = Convert.ChangeType(myTextBox.Text, filter.getFilterType());
```
This won't work if the conversion isn't defined though.
**Edit:**
I didn't notice your `Value` property was generic.
To make this work you could extend your filter object by something like this:
```
public object UnsafeValue
{
set
{
Value = (T)value;
}
}
```
and assign the result of `Convert.ChangeType` to that property.
Every approach without modifying the filter class would involve either more generics in the call hierarchy or reflection. |
120933 | I am creating a game in objective C, and I am stopped by a matter : I have a warning for passing multiple variables on @selector.
What I want to do, is call a method in my UIViewController but after a delay. So I try to make a first method, that call the other after delay like this :
```
-(void)AnimationCoinInitWith_x:(int)x y:(int)y w:(int)w h:(int)h afterDelay:(NSTimeInterval)t
{
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:
[self methodSignatureForSelector:@selector(AnimationCoinCopyInitWith_x:y:w:h:)]];
[invocation setTarget:self];
[invocation setSelector:@selector(AnimationCoinCopyInitWith_x:y:w:h:)];
[invocation setArgument:x atIndex:1];
[invocation setArgument:y atIndex:2];
[invocation setArgument:w atIndex:3];
[invocation setArgument:h atIndex:4];
[NSTimer scheduledTimerWithTimeInterval:t invocation:invocation repeats:NO];
}
-(void)AnimationCoinCopyInitWith_x:(int)x y:(int)y w:(int)w h:(int)h
{
UIImageView* imageViewCoin = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, w, h)];
[imageViewCoin setAnimationImages:images];
[imageViewCoin setAnimationRepeatCount:1000];
[imageViewCoin setAnimationDuration:(1/24)];
[imageViewCoin startAnimating];
[self addSubview:imageViewCoin];
[imageViewCoin release];
}
```
But it's not working, I don't know why.
Thanks for your help ! | Here, your problem is that `NSInvocation` doesn't automagically set the offsets of arguments you need, and as all objective-c methods have two invisible arguments (`self` and `_cmd`), you must offset your argument indices by 2, not 1.
Another issue here is that you are failing to pass the arguments by reference, so you must use the address operator (`&`):
```
[invocation setArgument:&x atIndex:2];
[invocation setArgument:&y atIndex:3];
[invocation setArgument:&w atIndex:4];
[invocation setArgument:&h atIndex:5];
```
Once you do that, your code above should work fine. |
121088 | I am making a program that continually prompts the user to input numbers which are then stored in an array until the user provides a given response (E.g "continue"), where the program then displays the array in terminal.
I have been debugging my program and it is setting all values within the array to the last value from console input.
How can I stop the counter from going all the way to the max for that array and instead step through the array 1 by 1 and input a new value from console each time
```
for (int i = 0; i < inputArray.GetLength(0); i++)
inputArray[i] = Convert.ToDouble(input);
goto STARTOVER;
```
Here is my main code:
```
using System;
namespace Task3
{
class MainClass
{
public static void Main(string[] args)
{
double[] inputArray = new double[40];
Console.WriteLine("Begin");
while (true)
{
STARTOVER:
var input = Console.ReadLine();
if (input.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
break;
}
if (input.Equals("continue",StringComparison.OrdinalIgnoreCase))
{
goto DISPLAY;
}
else
{
for (int i = 0; i < inputArray.GetLength(0); i++)
inputArray[i] = Convert.ToDouble(input);
goto STARTOVER;
}
}
DISPLAY:
for (int i = 0; i < inputArray.GetLength(0); i++)
{
Console.Write("{0} ", inputArray[i]);
Console.WriteLine();
}
}
}
}
```
From my understanding, I shouldn't use goto where possible but I cannot find an alternative to get the program to go back to where "STARTOVER:" is. | Aside from `goto`, which is pretty bad, the problem is the code loops through the entire array on every entry. It needs an integer variable that starts at 0 and increments with each new input, so it can set just that position each time.
```
public static void Main(string[] args)
{
Console.WriteLine("Begin");
double[] inputArray = new double[40];
int inputCount = 0;
var input = Console.ReadLine();
while (!input.Equals("exit", StringComparison.OrdinalIgnoreCase)
&& !input.Equals("continue", StringComparison.OrdinalIgnoreCase)
&& inputCount < inputArray.Length)
{
inputArray[inputCount++] = Convert.ToDouble(input);
input = Console.ReadLine();
}
for (int i = 0; i < inputCount; i++)
{
Console.Write("{0} ", inputArray[i]);
Console.WriteLine();
}
}
```
Even better to use a List:
```
public static void Main(string[] args)
{
Console.WriteLine("Begin");
var data = new List<double>;
var input = Console.ReadLine();
while (!input.Equals("exit", StringComparison.OrdinalIgnoreCase)
&& !input.Equals("continue", StringComparison.OrdinalIgnoreCase))
{
data.Add(double.Parse((input));
input = Console.ReadLine();
}
for (double d in data)
{
Console.WriteLine(d);
}
}
``` |
122151 | I want to get only `hh:mm` from date.
How I can get this?
I have tried this :
```
CONVERT(VARCHAR(8), getdate(), 108)
``` | Just use the first 5 characters...?
```
SELECT CONVERT(VARCHAR(5),getdate(),108)
``` |
122371 | There are [many](http://www.alistapart.com/articles/howtosizetextincss) [articles](http://www.w3.org/TR/CSS2/fonts.html#font-size-props) and [questions](https://stackoverflow.com/questions/132685/font-size-in-css-or-em) about [percentage-sized vs other-sized](http://kyleschaeffer.com/best-practices/css-font-size-em-vs-px-vs-pt-vs/) fonts. However, I can not find out WHAT the reference of the percent-value is supposed to be. I understand this is 'the same size in all browsers'. I also read this, for instance:
>
> Percent (%): The percent unit is much like the “em” unit, save for a few fundamental differences. First and foremost, the current font-size is equal to 100% (i.e. 12pt = 100%). While using the percent unit, your text remains fully scalable for mobile devices and for accessibility.
>
>
>
Source: <http://kyleschaeffer.com/best-practices/css-font-size-em-vs-px-vs-pt-vs/>
But if you say "ie 12 pt = 100%", then it means you first have to define `font-size: 12pt`. Is that how it works? You first define a size in an absolute measure, and then refer to this as '100%'? Does not make a lot of sense, as many samples say it is useful to put:
```
body {
font-size: 100%;
}
```
So by doing this, *WHAT* is the font size relative to? I notice that the size I see on my screen differs for every font. Arial looks way bigger than Times New Roman, for instance. Also, if I would just do this, body size = 100%, would *that* mean that it will be the same on all browsers? Or only if I first define an absolute value?
**UPDATE, SAT JUL 23**
I am getting there, but please bear with me.
So, the % value relates to the default browser font size, if I understand correctly. Well, that is nice but gives me again several other questions:
1. Is this standard size always the same for every browser version, or do they vary between versions?
2. I ! found (see image below) the settings for Google Chrome (never looked at this before!), and I see standard "serif", "sans-serif" and "monospace" settings. But how do I interpret this for other fonts? Say I define `font: 100% Georgia;`, what size will the browser take? Will it look up the standard size for serif, or has the "Georgia" font a standard size for the browser
3. On several websites I [read](http://www.alistapart.com/articles/howtosizetextincss) things like `Sizing text and line-height in ems, with a percentage specified on the body [..], was shown to provide **accurate, resizable text across all browsers** in common use today`. But from what I am learning now I believe that you should actually choose between either resizable text (using % or em, like what they recommend in this quote), or having 'accurate, consistent font-sizes across browsers' (by using px or pt as a base). Is this correct?
Google Settings:
![Google Chrome Settinsg](https://i.stack.imgur.com/9dR1N.png)
This is how I *think* things *could* look like if you do not define the size in absolute values.
![enter image description here](https://i.stack.imgur.com/GomGD.gif) | My understanding is that when the font is set as follows
```
body {
font-size: 100%;
}
```
the browser will render the font as per the user settings for that browser.
The spec says that % is rendered
>
> relative to parent element's font size
>
>
>
<http://www.w3.org/TR/CSS1/#font-size>
In this case, I take that to mean what the browser is set to. |
122443 | How can I get specific data from **JSON**?
**JSON:**
```
[
{ "TotalPageCount": 66 },
{ "TotalTitleCount": 199 },
{ "Title": "cola" },
{ "Title": "elvis tom" },
{ "Title": "dvd" }
]
```
**Javascript Code:**
```
<script>
function updateTitlesArea() {
$.getJSON(
"/lates/json/",
null,
function(data) {
$("#titlesDiv").html("");
$("#pagesDiv").html("");
var x;
if (data.length > 0) {
for (x in data) {
$("#titlesDiv").html($("#titlesDiv").html() +
"<li><a href=\"/" + data[x].Title.replace(/ /g, '-') + "\">" + data[x].Title + "</a>" +
"</li>"
);
}
} else {
$("#titlesDiv").html("<li>no entry</li>");
}
});
}
</script>
```
I'm trying to get `{"TotalPageCount":66}` AND `{"TotalTitleCount":199}`
from Javascript. Please provide me a method to get them?
Thanks a lot.
Update
======
Something going wrong, I tried all solutions but not worked fine.
**I have control on json format:**
**Current Json Builder:**
>
>
> ```
> if (title.Any())
> {
> foreach (var x in title)
> {
> result.AddLast(new { Title = x.Title });
> }
> }
> result.AddLast(new { TotalPageCount = totalPageCount });
> result.AddLast(new { TotalTitleCount = totalTitleCount });
>
> return Json(result.ToList(), JsonRequestBehavior.AllowGet);
>
> ```
>
>
I made a small change in json format, took totalpage and title count to end of json.
**Current:**
>
> [{"Title":"kola"},{"Title":"yilmaz
> ozdil"},{"Title":"dvd"},{"Title":"truly madly
> deeply"},{"Title":"deportivo de la coruna"},{"Title":"sizi seven
> kisiyle sevdiginiz kisinin farkli olmasi"},{"Title":"kadinlarin bavul
> gibi canta tasimalari"},{"Title":"hosbuldum"},{"Title":"sark
> cibani"},{"Title":"mevsimler gecerken"},{"Title":"bir kerede kolon
> gibi sicmak"},{"Title":"gelismek"},{"Title":"faz ve alasim
> bilimi"},{"Title":"memetq"},{"Title":"ogrencilerin sinav kagidina
> dustugu ilginc notlar"},{"Title":"cami duvarina
> isemek"},{"Title":"kufurden sonra tovbe etmek"},{"Title":"gida tarim
> ve hayvancilik bakanligi"},{"Title":"cevre orman ve sehircilik
> bakanligi"},{"Title":"google da nikah masasi
> calmak"},{"TotalPageCount":9},{"TotalTitleCount":199}]
>
>
>
With my code and given examples I still couldn't get the TotalPageCount and TotalTitleCount.
For the record: Maybe next time I can add more attributes next to **Title**.
So I would like to keep that json format.
Thanks for advance | When you do `x in data` you get every key of objects. So you have to do a simple check if it's `TotalPageCount` or `TotalTitleCount`. Like this;
```
<script>
function updateTitlesArea() {
$.getJSON(
"/lates/json/",
null,
function(data) {
var x, totalPageCount, totalTitleCount;
$("#titlesDiv").html("");
$("#pagesDiv").html("");
if (data.length > 0) {
for (x in data) {
if('TotalPageCount' == x) {
totalPageCount = data[x];
continue;
}
if('TotalTitleCount' == x) {
totalTitleCount = data[x];
continue;
}
$("#titlesDiv").html($("#titlesDiv").html() +
"<li><a href=\"/" + data[x].Title.replace(/ /g, '-') + "\">" + data[x].Title + "</a>" +
"</li>"
);
}
// You can do here whatever you want with 'totalPageCount' and 'totalTitleCount'
} else {
$("#titlesDiv").html("<li>no entry</li>");
}
});
}
</script>
``` |
122497 | I am very new in .net programming. I have a database of product suppliers and there are some details about the suppliers. On the phonetextbox i want the phone number to be at least 8 digits. I coded this but doesn't work. Could you please help me?
```
'Dim numbers As Decimal = Convert.ToDecimal(PhoneTextBox.Text)
Dim regex As Regex = New Regex("^\d{8}")
Dim match As Match = regex.Match(numbers)
If Not match.Success() Then
MessageBox.Show("Attention!!!The phone number must be at least 8 digits")
e.Cancel = True
End If
End Sub`
``` | *(Note: This is probably the kind of information that should be added to the Wiki, as it is not so much a language question but the kind of thing that is subject to change over time. But, answerable, so...)*
If you're using the GNU make method to build (where `make -f makefile.boot` generates a makefile for you) then you should find some lines in there like:
```
TO_OS_BASE?= TO_OSX
TO_OS_NAME?= TO_OSX_X64
OS_ID?= 0.2.40
BIN_SUFFIX=
RAPI_FLAGS= -D__LP64__ -DENDIAN_LITTLE -DHAS_LL_CONSTS -O1 ...
HOST_FLAGS= -DREB_EXE -D__LP64__ -DENDIAN_LITTLE ...
```
Modify the RAPI\_FLAGS and HOST\_FLAGS lines at the beginning to add `-DHAVE_LIBFFI_AVAILABLE`. That (-D)efines a preprocessor directive to tell the code it's okay to generate calls to FFI, because you have it available for linking later.
Now to tell it where to find include files. There's a line for includes that should look like:
```
INCL ?= .
I= -I$(INCL) -I$S/include/ -I$S/codecs/ ...
```
To the tail of that you need to add something that will look like `-I/usr/local/opt/libffi/lib/libffi-3.0.13/include`, or similar. The actual directory will depend on where you have libffi on your system. On the OSX system I'm looking at, that has two files in it, `ffi.h` and `ffitarget.h`.
*(Note: I'm afraid I don't know how these files got on this computer. They didn't ship with the OS, so they came from...somewhere. I don't generally develop on OSX--nor for that matter do I use this FFI. You'll have to consult your local FFI-on-OSX website, or perhaps for support contact [Atronix Engineering](http://www.atronixengineering.com/downloads)) who added the FFI features to Rebol.)*
Then it's necessary to tell it where you have libffi on your system. You'll find a CLIB line that is likely just `CLIB= -lm`. You'd change this for example to:
```
CLIB= -L/usr/local/opt/libffi/lib -lm -lffi
```
`-lffi` Tells it to look for the ffi (-l)ibrary, and -lxxx means it assumes the name of the library will be `libxxx[something]`. `-L/usr/local/opt/libffi/lib` tells it where to look for it. You'll have to figure out where (if anywhere) you have libffi, and if not get it. If you had it, the directory would have contents something like:
```
libffi-3.0.13
libffi.6.dylib
libffi.a
libffi.dylib
pkgconfig
```
>
> I mainly use OS X for development, though would also like to be able to build it for use with Linux.
>
>
>
On Linux it's similar but generally much easier to get the library, as easy as `sudo apt-get install libffi-dev`. Same step for the RFLAGS and CFLAGS, and it should take care of the location automatically... so you can add just `-lffi` to CLIB. |
123523 | WARNING:I'm not asking for a better code, I'm asking for a shorter code for HackerRank just to learn what can be done to shorten it.
I'm newbie to Java and was trying out this FizzBuzz problem:
>
> Write a program that prints the numbers from 1 to 100. But for multiples of three print >“Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which >are multiples of both three and five print “FizzBuzz”.
>
>
>
I wrote my solution as short as possible.
```
class Solution{
public static void main(String[]b){
for(int i=1;i<101;i++){
String a=(i%3==0)?(i%5==0)?"FizzBuzz":"Fizz":(i%5==0)?"Buzz":i+"";
System.out.println(a);}}}
```
and I got a 3.6 score. But obviously there's room to improve because some people wrote it with 27 characters less. How is that possible ? Any suggestions? I don't really care about the ranks, I just wanna know what I'm missing.
EDIT: So with your help, I made it like this:
```
class Solution{public static void main(String[]b){for(int i=1;i<101;i++){System.out.println((i%3==0)?(i%5==0)?"FizzBuzz":"Fizz":(i%5==0)?"Buzz":i);}}}
```
and it seems I got rid of 14 characters. God knows what the other people did to lose 13 more characters. Anyway, thanks. | What about something like:
```
for(int i=0;i++<100;System.out.println((i%3>0?"":"Fizz")+(i%5>0?i%3>0?i:"":"Buzz")))
```
**Warning:** this code is just an exercise of trying to *make the code shorter*. It is neither good or readable as normal code should try to be! |
123730 | Swift 4 / Xcode 9.3 / OS X 10.13.4 / iOS 11.3 & 11.2.6
I'm trying to build my app and I'm getting the above error message. I've checked the code over and over and over and I can't figure out why I'm getting this error. I'm not certain which part of the code you need to see, but here is the page I'm getting the error on. The error code is flagging the very last line of code.
```
import UIKit
import os.log
class Bonus: NSObject, NSCoding {
//MARK: Archiving Paths
static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static let ArchiveURL = DocumentsDirectory.appendingPathComponent("bonuses")
//MARK: Properties
var bonusCode: String
var category: String
var name: String
var value: Int
var city: String
var state: String
var photo: UIImage?
//MARK: Initialization
init?(bonusCode: String, category: String, name: String, value: Int, city: String, state: String, photo: UIImage?) {
// The name must not be empty.
guard !name.isEmpty else {
return nil
}
// The value must not be negative.
guard (value >= 0) else {
return nil
}
// Initialize stored properties.
self.bonusCode = bonusCode
self.category = category
self.name = name
self.value = value
self.city = city
self.state = state
self.photo = photo
}
//MARK: Types
struct PropertyKey {
static let bonusCode = "bonusCode"
static let category = "category"
static let name = "name"
static let value = "value"
static let city = "city"
static let state = "state"
static let photo = "photo"
}
//MARK: NSCoding
func encode(with aCoder: NSCoder) {
aCoder.encode(bonusCode, forKey: PropertyKey.bonusCode)
aCoder.encode(category, forKey: PropertyKey.category)
aCoder.encode(name, forKey: PropertyKey.name)
aCoder.encode(value, forKey: PropertyKey.value)
aCoder.encode(city, forKey: PropertyKey.city)
aCoder.encode(state, forKey: PropertyKey.state)
aCoder.encode(photo, forKey: PropertyKey.photo)
}
required convenience init?(coder aDecoder: NSCoder) {
// The name is required. If we cannot decode a name string, the initializer should fail.
guard let bonusCode = aDecoder.decodeObject(forKey: PropertyKey.bonusCode) as? String else {
os_log("Unable to decode the Code for a Bonus object.", log: OSLog.default, type: .debug)
return nil
}
// Because photo is an optional property of Meal, just use conditional cast
let photo = aDecoder.decodeObject(forKey: PropertyKey.photo) as? UIImage
let category = aDecoder.decodeObject(forKey: PropertyKey.category)
let value = aDecoder.decodeInteger(forKey: PropertyKey.value)
let city = aDecoder.decodeObject(forKey: PropertyKey.city)
let state = aDecoder.decodeObject(forKey: PropertyKey.state)
// Must call designated initializer.
self.init(bonusCode: String, category: String, name: String, value: Int, city: String, state: String, photo: UIImage?)
}
}
```
The error is flagging on the bonusCode: String, specifically on the S in String.
I'm pretty new to programming, but I only found one other search result for this specific question, and the other similar ones seemed to be very specific to the code being used. | First of all your container has to have `max-width` or `width` fixed. Second of all your `overflow` has to be `hidden` instead of `none`:
```css
.outer {
background-color: #FFAAAA;
display: flex;
flex-direction: row;
}
.inner {
background-color: #AAAAFF;
display: flex;
flex-direction: column;
margin: 5px;
}
.header {
margin: 5px;
background-color: #AAFFAA;
white-space: nowrap;
max-width:200px;
overflow: hidden;
text-overflow: ellipsis;
}
.line {
margin: 5px;
background-color: #FFAAFF;
}
```
```html
<div class="outer">
<div class="inner">
<div class="header">
superlongtextthatshouldbeellipsed
</div>
<div class="line">
short text
</div>
<div class="line">
even shorter text
</div>
</div>
</div>
``` |
123735 | OK, I must be overlooking something silly because I am unable to get my tabhost to display in my Activity class. I am getting the dreaded force close when I try to run the app. It will work if i extend TabActivity, **but I can't do that** [see edit below] because once I move the code from my prototype project its going to be in a custom class that inherits from Activity.
Here is the XML layout:
```
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
</TabHost>
```
And here is the class that is trying to create and display the TabHost:
```
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TabHost;
public class my_proto extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
Log.i(this.toString(), "OnCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(this.toString(), "get tab host");
TabHost host = (TabHost)findViewById(R.id.tabhost);
host.setup();
Log.i(this.toString(), "add tabs");
host.addTab(host.newTabSpec("one")
.setIndicator("First Results")
.setContent(new Intent(this, FirstResultsListViewActivity.class)));
host.addTab(host.newTabSpec("two")
.setIndicator("Second Results")
.setContent(new Intent(this, SecondResultsListViewActivity.class)));
Log.i(this.toString(), "adjust tab size");
host.getTabWidget().getChildAt(0).getLayoutParams().height = 35;
host.getTabWidget().getChildAt(1).getLayoutParams().height = 35;
}// end onCreate
}// end class my_proto
```
This is the error I get in the log.
```
11-17 16:49:51.271: INFO/com.my_proto.my_proto@43b80b50(1302): OnCreate
11-17 16:49:51.472: INFO/com.my_proto.my_proto@43b80b50(1302): get tab host
11-17 16:49:51.480: INFO/com.my_proto.my_proto@43b80b50(1302): add tabs
11-17 16:49:51.521: DEBUG/AndroidRuntime(1302): Shutting down VM
11-17 16:49:51.521: WARN/dalvikvm(1302): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
11-17 16:49:51.530: ERROR/AndroidRuntime(1302): Uncaught handler: thread main exiting due to uncaught exception
11-17 16:49:51.552: ERROR/AndroidRuntime(1302): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.my_proto/com.my_proto.my_proto}: java.lang.IllegalStateException: Did you forget to call 'public void setup(LocalActivityManager activityGroup)'?
11-17 16:49:51.552: ERROR/AndroidRuntime(1302): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
11-17 16:49:51.552: ERROR/AndroidRuntime(1302): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
11-17 16:49:51.552: ERROR/AndroidRuntime(1302): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
11-17 16:49:51.552: ERROR/AndroidRuntime(1302): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
11-17 16:49:51.552: ERROR/AndroidRuntime(1302): at android.os.Handler.dispatchMessage(Handler.java:99)
11-17 16:49:51.552: ERROR/AndroidRuntime(1302): at android.os.Looper.loop(Looper.java:123)
11-17 16:49:51.552: ERROR/AndroidRuntime(1302): at android.app.ActivityThread.main(ActivityThread.java:4363)
11-17 16:49:51.552: ERROR/AndroidRuntime(1302): at java.lang.reflect.Method.invokeNative(Native Method)
11-17 16:49:51.552: ERROR/AndroidRuntime(1302): at java.lang.reflect.Method.invoke(Method.java:521)
11-17 16:49:51.552: ERROR/AndroidRuntime(1302): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
11-17 16:49:51.552: ERROR/AndroidRuntime(1302): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
11-17 16:49:51.552: ERROR/AndroidRuntime(1302): at dalvik.system.NativeStart.main(Native Method)
11-17 16:49:51.552: ERROR/AndroidRuntime(1302): Caused by: java.lang.IllegalStateException: Did you forget to call 'public void setup(LocalActivityManager activityGroup)'?
11-17 16:49:51.552: ERROR/AndroidRuntime(1302): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:646)
11-17 16:49:51.552: ERROR/AndroidRuntime(1302): at android.widget.TabHost.setCurrentTab(TabHost.java:320)
11-17 16:49:51.552: ERROR/AndroidRuntime(1302): at android.widget.TabHost.addTab(TabHost.java:213)
11-17 16:49:51.552: ERROR/AndroidRuntime(1302): at com.mc_proto.mc_proto.onCreate(my_proto.java:29)
11-17 16:49:51.552: ERROR/AndroidRuntime(1302): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-17 16:49:51.552: ERROR/AndroidRuntime(1302): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
11-17 16:49:51.552: ERROR/AndroidRuntime(1302): ... 11 more
```
Its complaining about not calling setup, but I am calling it. There is another version of setup that needs some kind of LocalActivityMananger. I have tried replacing the call to setup the call below but no luck.
```
LocalActivityManager mLocalActivityManager = new LocalActivityManager(this, false);
host.setup(mLocalActivityManager);
```
[edit] The call above didn't work so I took it back out. Although I was getting a new error logged.
```
11-17 20:24:58.382: ERROR/AndroidRuntime(1432): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.my_proto/com.my_proto.my_proto}: java.lang.IllegalStateException: Activities can't be added until the containing group has been created.
```
[edit] Based on some of the comments below I realized I need to be clearer about why I can't inherit from TabActivity. Once I have the prototype working I need to port this into an existing app's screen that inherits from Activity. I will need to load the TabHost into a Layout within that Activity. It will basically be a LinearLayout with a row of status icons, followed my a LinearLayout with the Tabhost in it. I know that if I can get this working I can move onto the next phase. Thanks!
```
---------------------------
| status icons |
---------------------------
| Tab, Tab, Tab |
| |
| |
| |
---------------------------
| status icons |
---------------------------
``` | I changed the class to
```
public class my_proto extends ActivityGroup
```
and change the following:
```
this.mHost = (TabHost) findViewById(R.id.tabhost);
this.mHost.setup(getLocalActivityManager());
```
It seems ok for me |
123971 | I'm using MVC3 and I have a model like this:
```
public class Foo
{
[Required]
[Range(0.01, 99.99)]
public double? f1{ get; set; }
}
```
And I want to ugnore javascript range validation, but keep the required javascript validation.
How can I do that? | I found solution, just removed some attributes from textbox:
```
$('#fieldId').removeAttr("data-val-range");
$('#fieldId').removeAttr("data-val-range-min");
$('#fieldId').removeAttr("data-val-range-max");
``` |
123984 | Do Perl, Python or Ruby run flawless on a 64bit Win7 system, or do you have to keep in mind pitfalls with integers and restriction on functions like I have read of on PHP? | Updated: Please have a look at <http://jsfiddle.net/p96denv4/2/>
Here's what you would do.
HTML
```
<div id="ifMobile1"></div>
```
CSS
```
#ifMobile1 {
background-image: url(/images/arts/IMG_1447m.png)
width: set your width ;
height: set your height ;
}
@media all and (max-width: 499px) {
#ifMobile1 {
background-image: url(/images/arts/IMG_1447.png)
width: set your width ;
height: set your height ;
}
}
``` |
124006 | I have a very annoying problem, and it is bugging me for some time now, and I've tried everything to fix it, but I simply fail at doing so.
The problem is: I have a navigation which consists of many `<div>` elements inside `<div>`, which is inside another `<div>` and so on.
**Here is the code for my navigation:**
```
<div class="nav-laptop"><a href="proizvodi.php?upit=SELECT Slika, Naziv, Opis, Cijena FROM Proizvodi WHERE Kategorija='Laptop' ORDER BY Proizvodac Asc;">Laptop</a><br />
<div class="nav-bot"><a href="proizvodi.php?upit=SELECT Slika, Naziv, Opis, Cijena FROM Proizvodi WHERE Kategorija='Laptop' AND Proizvodac='Acer' ORDER BY Proizvodac ASC;">Acer</a></div>
<br />
<div class="nav-bot"><a href="proizvodi.php?upit=SELECT Slika, Naziv, Opis, Cijena FROM Proizvodi WHERE Kategorija='Laptop' AND Proizvodac='Apple' ORDER BY Proizvodac ASC;">Apple</a></div>
<br />
<div class="nav-bot"><a href="proizvodi.php?upit=SELECT Slika, Naziv, Opis, Cijena FROM Proizvodi WHERE Kategorija='Laptop' AND Proizvodac='Asus' ORDER BY Proizvodac ASC;">Asus</a></div>
<br />
<div class="nav-bot"><a href="proizvodi.php?upit=SELECT Slika, Naziv, Opis, Cijena FROM Proizvodi WHERE Kategorija='Laptop' AND Proizvodac='Dell' ORDER BY Proizvodac ASC;">Dell</a></div>
<br />
<div class="nav-bot"><a href="proizvodi.php?upit=SELECT Slika, Naziv, Opis, Cijena FROM Proizvodi WHERE Kategorija='Laptop' AND Proizvodac='HP' ORDER BY Proizvodac ASC;">HP</a></div>
<br />
<div class="nav-bot"><a href="proizvodi.php?upit=SELECT Slika, Naziv, Opis, Cijena FROM Proizvodi WHERE Kategorija='Laptop' AND Proizvodac='Lenovo' ORDER BY Proizvodac ASC;">Lenovo</a></div>
<br />
<div class="nav-bot"><a href="proizvodi.php?upit=SELECT Slika, Naziv, Opis, Cijena FROM Proizvodi WHERE Kategorija='Laptop' AND Proizvodac='Toshiba' ORDER BY Proizvodac ASC;">Toshiba</a></div>
</div>
```
**I will attach a picture to give you a better view on what I have:**
[![Here the first dropdown nav you see is the code above, and all others are completely the same, only contain more data. The dropdown is animated with CSS3.](https://i.stack.imgur.com/JkWiO.jpg)](https://i.stack.imgur.com/JkWiO.jpg)
**Now here is my CSS for those navigation `<div>`s:**
```
.nav-laptop, .nav-pc, .nav-tablet, .nav-periferije, .nav-dijelovi, .nav-audio, .nav-mobitel, .nav-monitor, .nav-televizor, .nav-usluge {
transition: height 0.5s;
-moz-transition: height 0.5s;
-ms-transition: height 0.5s;
-o-transition: height 0.5s;
-webkit-transition: height 0.5s;
height: 20px;
width: 72px;
border-radius: 8px 8px 0px 0px;
-moz-border-radius: 8px 8px 0px 0px;
-ms-border-radius: 8px 8px 0px 0px;
-o-border-radius: 8px 8px 0px 0px;
-webkit-border-radius: 8px 8px 0px 0px;
float: left;
text-align: center;
vertical-align: middle;
border-top-width: 2px;
border-top-style: solid;
border-top-color: #F00;
font-size: 1.05em;
margin-top: 6px;
overflow: hidden;
}
```
**And here is :hover version for laptop nav only:**
```
.nav-laptop:hover {
height: 186px;
width: 72px;
border-radius: 8px 8px 0px 0px;
-moz-border-radius: 8px 8px 0px 0px;
-ms-border-radius: 8px 8px 0px 0px;
-o-border-radius: 8px 8px 0px 0px;
-webkit-border-radius: 8px 8px 0px 0px;
float: left;
text-align: center;
vertical-align: middle;
font-size: 1.05em;
margin-top: 6px;
}
```
Now this all navigation works awesome and beautiful and everything, but the problem is, whenever I hover with my mouse over any category, when the division drops down, it distorts all the content below, and makes a huge mess, and once I move my mouse, it all gets back to normal.
How should I go about it? This may be very inefficient way to do it, and I'm open to all suggestions, and looking forward to learning more from you people.
**Here's a normal content:**
[![enter image description here](https://i.stack.imgur.com/Jl6UT.jpg)](https://i.stack.imgur.com/Jl6UT.jpg)
**And here's distorted content due to hovering onto navigation:**
[![enter image description here](https://i.stack.imgur.com/ZZZzG.jpg)](https://i.stack.imgur.com/ZZZzG.jpg) | You are floating the "dropdown" parts of the menu. And if all the rest of the content are also floating, all the things are in the same flow. Thus they get all "weird", even though this is not at all weird but rather exactly the expected behavior.
Instead, you should be using absolute positioning for the parts that you want to overlay on the other content. Absolute positioning removes the element from the document flow, and thus is does not affect the layout of anything else other than itself.
So, make the "dropdown" parts `position: absolute` and the main menu items `position: relative`, for example. This way the "dropdown" parts will get positioned relative to the main menu items.
Take a look at e.g. <http://www.w3schools.com/css/css_positioning.asp> or <http://learnlayout.com> for basic CSS layout tutorials.
**Simple example of a hover menu:**
```css
ul, li {
list-style: none;
padding: 0;
margin: 0;
}
li {
display: inline-block;
width: 100px;
background: #ddd;
}
ul li {
position: relative;
}
li ul {
position: absolute;
display: none;
}
li:hover ul {
display: block;
}
li ul li {
background: #eee
}
```
```html
<ul>
<li>
<span>First</span>
<ul>
<li>First</li>
<li>Second</li>
</ul>
</li>
<li>
<span>Second</span>
<ul>
<li>First</li>
<li>Second</li>
</ul>
</li>
</ul>
<div class="content">
<p>Content content content content content content content<br>content content content content content content...</p>
<p>Content content content content content content content<br>content content content content content content...</p>
</div>
``` |
124024 | In AfterScenario method, I want to get the rows from table "Examples" in Scenario Outline, to get the values in it, and search that specific values in the database
I know that this can be achieved by using `Context.Scenario.Current`...
```
Context.Scenario.Current[key]=value;
```
...but for some reason I'd like to be able to get it in a simpler way
like this:
```
ScenarioContext.Current.Examples();
```
----------- SCENARIO --------------------------------
```
Scenario Outline: Create a Matter
Given I create matter "< matterName >"
Examples:
| matterName |
| TAXABLE |
```
----------AFTER SCENARIO -----------------------------------
```
[AfterScenario()]
public void After()
{
string table = ScenarioContext.Current.Examples();
}
``` | You can use [`touchstart`](https://developer.mozilla.org/en-US/docs/Web/Events/touchstart) event which fires on mobile browsers.
```
$('nav li.bg').on('click touchstart', function(){
return true;
});
```
[**More touch based events**](http://www.w3.org/TR/touch-events/) |
124134 | I have a table that is similar below.
```
| user_id | point_1 | point_2 | point_3
453123 1234 32 433
321543 1 213 321
```
My query is something like this:
```
$query = "SELECT * FROM my_table WHERE user_id = 12345 OR user_id = 987654321"
```
Obviously, this will return nothing since `user_id` 12345 OR `user_id` 987654321 do not exist on the table.
But I still want to return something like the one below :
```
| user_id | point_1 | point_2 | point_3
12345 0 0 0
987654321 0 0 0
``` | You could use an inline view as a rowsource for your query. To return a zero in place of a NULL (which would be returned by the outer join when no matching row is found in my\_table, you can use the `IFNULL` function.
e.g.
```
SELECT s.user_id
, IFNULL(t.point_1,0) AS point_1
, IFNULL(t.point_2,0) AS point_2
, IFNULL(t.point_3,0) AS point_3
FROM ( SELECT 12345 AS user_id
UNION ALL SELECT 987654321
) s
LEFT
JOIN my_table t
ON t.user_id = s.user_id
```
NOTE: If datatype of `user_id` column my\_table is character, then I'd enclose the literals in the inline view in single quotes. e.g. **`SELECT '12345' AS user_id`**. If the characterset of the column doesn't match your client characterset, e.g. database column is latin1, and client characterset is UTF8, you'd want to force the character strings to be a compatible (coercible) characterset... **`SELECT _latin1'12345' AS user_id`** |
125209 | I have a HTML table with few rows. [Demo](http://jsfiddle.net/R3Jy7/2/). I want to expand all collapsed rows on hitting "Ctrl + F" on keyboard.
Currently I using following piece of code for expand/collapse the required rows.
```
$('#resultDetails').on('click', '.toggle', function () {
var findChildren = function (tr) {
var depth = tr.data('depth');
return tr.nextUntil($('tr').filter(function () {
return $(this).data('depth')
<= depth;
}));};
```
[Edit] : If I am searching for a string using Ctrl + F and if any row is hidden/collapsed (and row contains the required string), then browser will not be able to find the required string as its hidden. So my idea is to capture the Ctrl+F event and expand all the rows. With above piece of code I am able to expand only those rows on which user has clicked. But I want to expand all rows once user enters Ctrl + F.
How can I do this or any other ideas to handle this scenario.
Thoughts. | Use `window.onkeyup` event:
```
window.onkeyup = function(event) {
if (e.ctrlKey && e.keyCode == 70) { // Your Code Here }; }
```
This [**fiddle**](http://jsfiddle.net/Karim_AG/PcR7v/) might help you |
125602 | >
> Given a list of points, find the shortest path that visits all points and returns to the starting point.
>
>
>
The [Travelling Salesman Problem](http://en.wikipedia.org/wiki/Travelling_salesman_problem) is well-known in the computer science field, as are many ways to calculate/approximate it. It's been solved for very large groups of points, but some of the largest take many CPU-years to finish.
>
> Don't get burned by the potato.
>
>
>
[Hot Potato](http://en.wikipedia.org/wiki/Hot_potato_%28game%29) is a game where 2+ players pass a "potato" around in a circle while music plays. The object is to pass it to the next player quickly. If you are holding the potato when the music stops, you're out.
---
The object of **Hot Potato Salesman** is:
>
> Given a set of **100 unique points**, return those points in a better order (*shorter total distance as defined further down*). This will "pass" the problem to the next player. They have to improve it and pass it to the next, etc. If a player cannot improve it, they are out and play continues until one player is left.
>
>
>
To keep this from being a "brute-force-me-a-path" competition, there are these stipulations:
* You cannot take more than **one minute** to pass the potato. If you haven't found and passed a shorter solution by the time one minute is up, you're out.
* You cannot change the position of more than **25** points. To be exact, `>= 75` points must be in the same position as you received them. It does not matter *which* ones you decide to change, just the *amount* you change.
When only one player is left, he is the winner of that game, and receives one point. A tourney consists of `5*n` games, where `n` is the number of players. Each game, the starting player will be *rotated*, and the remaining player order will be *shuffled*. The player with the most points at the end is the winner of the tourney. If the tourney ends with a tie for first place, a new tourney will be played with only those contestants. This will continue until there is no tie.
The starting player for each game will receive a set of pseudorandomly selected points in no particular order.
Points are defined as a pair of integer `x,y` coordinates on a cartesian grid. Distance is measured using [Manhattan distance](http://en.wikipedia.org/wiki/Taxicab_geometry), `|x1-x2| + |y1-y2|`. All coordinates will lie in the `[0..199]` range.
Input
-----
Input is given with a single string argument. It will consist of 201 comma-separated integers representing the number of current players(`m`) and 100 points:
```
m,x0,y0,x1,y1,x2,y2,...,x99,y99
```
The order of these points is the current path. The total distance is obtained by adding the distance from each point to the next (`dist(0,1) + dist(1,2) + ... + dist(99,0)`). *Don't forget to return to start when calculating total distance!*
Note that `m` is *not* the number of players that started the game, it is the number that are still in.
Output
------
Output is given in the same way as input, minus `m`; a single string containing comma-separated integers representing the points in their new order.
```
x0,y0,x1,y1,x2,y2,...,x99,y99
```
The control program will wait for output for one minute only. When output is received, it will verify that:
* the output is well-formed
* the output consists of *only* and *all* the 100 points present in the input
* `>=75` points are in their original positions
* the path length is less than the previous path
If any of these checks fail (or there is no output), you are out and the game will proceed to the next player.
Control Program
---------------
You can find the control program [at this link](https://bitbucket.org/Geobits/hotpotatosalesman/src). The control program itself is deterministic, and is posted with a dummy seed of `1`. The seed used during scoring will be different, so don't bother trying to analyze the turn order/point lists it spits out.
The main class is `Tourney`. Running this will do a full tournament with contestants given as arguments. It spits out the winner of each game and a tally at the end. A sample tourney with two SwapBots looks like:
```
Starting tournament with seed 1
(0) SwapBot wins a game! Current score: 1
(1) SwapBot wins a game! Current score: 1
(1) SwapBot wins a game! Current score: 2
(1) SwapBot wins a game! Current score: 3
(0) SwapBot wins a game! Current score: 2
(1) SwapBot wins a game! Current score: 4
(1) SwapBot wins a game! Current score: 5
(1) SwapBot wins a game! Current score: 6
(1) SwapBot wins a game! Current score: 7
(1) SwapBot wins a game! Current score: 8
Final Results:
Wins Contestant
2 (0) SwapBot
8 (1) SwapBot
```
If you want to test just one game at a time, you can run the `Game` class instead. This will run one game with players in the order given as arguments. By default, it will also print a play-by-play showing the current player and path length.
Also included are a few test players: `SwapBot`, `BlockPermuter`, and `TwoSwapBot`. The first two will not be included in scoring runs, so feel free to use and abuse them during testing. `TwoSwapBot` **will** be included in judging, and he's no slouch, so bring your A-game.
Miscellany
----------
* You cannot save state information, and each turn is a separate run of your program. The only information you will receive each turn is the set of points.
* You cannot use external resources. This includes network calls and file access.
* You cannot use library functions designed to solve/assist with the TSP problem or its variants.
* You cannot manipulate or interfere with other players in any way.
* You cannot manipulate or interfere with the control program or any included classes or files in any way.
* Multi-threading is allowed.
* One submission per user. If you submit more than one entry, I will only enter the first one submitted. If you want to change your submission, edit/delete the original.
* The tournament will be running on Ubuntu 13.04, on a computer with an [i7-3770K CPU](http://ark.intel.com/products/65523/Intel-Core-i7-3770K-Processor-8M-Cache-up-to-3_90-GHz) and 16GB RAM. It will not be run in a VM. Anything I perceive as malicious will immediately disqualify the current **and** any future entry you submit.
* All entries must be runnable from the command line with free ([*as in beer*](http://en.wikipedia.org/wiki/Gratis_versus_libre#.22Free_beer.22_vs_.22free_speech.22_distinction)) software. If I have problems compiling/running your entry, I will request aid in the comments. If you do not respond or I cannot ultimately get it running, it will be disqualified.
Results (22 May 2014)
---------------------
New results are in! UntangleBot has beaten the competition quite soundly. TwoSwapBot managed seven wins, and SANNbot snuck a victory in as well. Here's a scoreboard, and a [link to the raw output](http://pastebin.com/wFePpbiU):
```
Wins Contestant
22 (2) ./UntangleBot
7 (0) TwoSwapBot
1 (5) SANNbot.R
0 (1) BozoBot
0 (3) Threader
0 (4) DivideAndConquer
```
As it stands *now*, **UntangleBot** has won the checkmark. Don't let that discourage you from entering, though, since I'll run the tournament as more contestants appear and change the accepted answer accordingly. | UntangleBot (formerly NiceBot)
==============================
A C++11 bot that uses two strategies.
At first it will try to "untangle" the path if possible, by detecting intersections between paths that are closer than 25 points (since untangling implies modifying all points in-between).
If the first strategy fails, it randomly swaps points to find better distances until a better path has been found.
This bot consistently beats TwoSwapBot with an approximate ratio of five victories for one loss in my test tourneys.
```cxx
// g++ -std=c++11 -O3 -o UntangleBot UntangleBot.cpp
#include <algorithm>
#include <chrono>
#include <cmath>
#include <iostream>
#include <iterator>
#include <random>
#include <set>
#include <sstream>
const int NPOINTS = 100;
struct Point {
int x, y;
Point():x(0),y(0) {}
Point(int x, int y):x(x),y(y) {}
int distance_to(const Point & pt) const {
return std::abs(x - pt.x) + std::abs(y - pt.y);
}
};
std::ostream & operator<<(std::ostream & out, const Point & point) {
return out << point.x << ',' << point.y;
}
int total_distance(const Point points[NPOINTS]) {
int distance = 0;
for (int i = 0; i < NPOINTS; ++i) {
distance += points[i].distance_to(points[(i+1)%NPOINTS]);
}
return distance;
}
bool intersects(const Point & p1, const Point & p2, const Point & p3, const Point & p4) {
double s1_x, s1_y, s2_x, s2_y;
s1_x = p2.x - p1.x;
s1_y = p2.y - p1.y;
s2_x = p4.x - p3.x;
s2_y = p4.y - p3.y;
double s, t;
s = (-s1_y * (p1.x - p3.x) + s1_x * (p1.y - p3.y)) / (-s2_x * s1_y + s1_x * s2_y);
t = ( s2_x * (p1.y - p3.y) - s2_y * (p1.x - p3.x)) / (-s2_x * s1_y + s1_x * s2_y);
return s >= 0 && s <= 1 && t >= 0 && t <= 1;
}
int main(int argc, char ** argv) {
Point points[NPOINTS];
using Clock = std::chrono::system_clock;
const Clock::time_point start_time = Clock::now();
// initialize points
if (argc < 2) {
std::cerr << "Point list is missing" << std::endl;
return 1;
}
std::stringstream in(argv[1]);
int players;
char v;
in >> players >> v;
for (int i = 0; i < NPOINTS; ++i) {
in >> points[i].x >> v >> points[i].y >> v;
}
int original_distance = total_distance(points);
// detect intersection between any 4 points
for (int i = 0; i < NPOINTS; ++i) {
for (int j = i+1; j < NPOINTS; ++j) {
Point & p1 = points[i];
Point & p2 = points[(i+1)%NPOINTS];
Point & p3 = points[j];
Point & p4 = points[(j+1)%NPOINTS];
// points must all be distinct
if (p1.distance_to(p3) == 0 || p1.distance_to(p4) == 0 || p2.distance_to(p3) == 0 || p2.distance_to(p4) == 0) {
continue;
}
// do they intersect ?
if (!intersects(p1, p2, p3, p4)) {
continue;
}
// can modify less than 25 points ?
if (std::abs(j-i) > 25) {
continue;
}
// swap points
for (int m = 0; m < std::abs(j-i)/2; ++m) {
if (i+1+m != j-m) {
std::swap(points[i+1+m], points[j-m]);
//std::cerr << "untangle " << i+1+m << " <=> " << j-m << '\n';
}
}
int new_distance = total_distance(points);
if (new_distance < original_distance) {
std::copy(std::begin(points), std::end(points)-1, std::ostream_iterator<Point>(std::cout, ","));
std::cout << points[NPOINTS-1];
return 0;
}
else {
// swap points back
for (int m = 0; m < std::abs(j-i)/2; m++) {
if (i+1+m != j-m) {
std::swap(points[i+1+m], points[j-m]);
}
}
}
}
}
// more traditional approach if the first fails
std::mt19937 rng(std::chrono::duration_cast<std::chrono::seconds>(start_time.time_since_epoch()).count());
std::uniform_int_distribution<> distr(0, NPOINTS-1);
while (true) {
// try all possible swaps from a random permutation
int p1 = distr(rng);
int p2 = distr(rng);
std::swap(points[p1], points[p2]);
for (int i = 0; i < NPOINTS; ++i) {
for (int j = i+1; j < NPOINTS; ++j) {
std::swap(points[i], points[j]);
if (total_distance(points) < original_distance) {
std::copy(std::begin(points), std::end(points)-1, std::ostream_iterator<Point>(std::cout, ","));
std::cout << points[NPOINTS-1];
return 0;
}
else {
std::swap(points[i], points[j]);
}
}
}
// they didn't yield a shorter path, swap the points back and try again
std::swap(points[p1], points[p2]);
}
return 0;
}
``` |
125685 | I dont get it - I cannot align the `RelativeLayout` in the `ListView` - that is I want to center the `RelativeLayout` that holds and image and some textviews.
The `RelativeLayout` is still on the lefthand-side of the screen, though the listview-width should match the parent. What could be wrong?
Here's the xml, for the list item layout in the adapter.
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout_os_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<ImageView
android:id="@+id/os_listview_imageview1_id"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_margin="10dp"
android:layout_centerVertical="true"
android:src="@drawable/ic_launcher_background"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/os_listview_imageview1_id"
android:orientation="vertical"
android:layout_centerVertical="true">
<TextView
android:id="@+id/os_listview_name_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nougat"
android:layout_centerVertical="true"/>
<TextView
android:id="@+id/os_listview_version_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:text="7.0"
android:layout_centerVertical="true"/>
<TextView
android:id="@+id/os_listview_api_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="24"
android:layout_centerVertical="true"/>
<TextView
android:id="@+id/os_listview_release_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="2016"
android:layout_centerVertical="true"/>
</LinearLayout>
</RelativeLayout>
```
[![enter image description here](https://i.stack.imgur.com/xDqRGm.png)](https://i.stack.imgur.com/xDqRGm.png)
And the `ListView` is here in the following layout.
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
tools:context="se.listview.stude.listviewtest180303.MainActivity">
<ListView
android:id="@+id/os_listView_id"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
```
Edit: this is how it looks the list item in the design-mode in android-studio.
[![enter image description here](https://i.stack.imgur.com/8b3cg.jpg)](https://i.stack.imgur.com/8b3cg.jpg) | Use this as rootLayout of your item :-
```
<RelativeLayout
xmlns:android
="http://schemas.android.com/apk/res/android"
android:id="@+id/relativeLayout_os_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
>
```
You would get the same output..
Also in your activity put **listView** width as `match_parent` |
126029 | I am planning to drive over the [Curonian Spit](http://en.wikipedia.org/wiki/Curonian_Spit) from the Lithuanian side in 2013. I would love to travel on into the Russian side and visit Kaliningrad. Is there a border crossing on the Spit? If not, will I have to travel back up the Lithuanian side and find an alternative crossing into Russian/Kaliningrad? | As you say you're going to pass the border at Curonian Spit, you'll be in Klaipeda before this. @Marcel C. already said about the Nida station, but I want to add some information which can be useful for you and others who will view this question.
So, you have two different ways to get from Klaipeda to Curonian Spit and Kaliningrad with your car:
1. As @Marcel C. said, border station Nida - Morskoe is the best variant for you, if you want to get on Spit. Note that the quality of the road very differs between Lithuanian and Russian sides. Border station works all the time, note that you can't pass it by walk, but you can do that on bicycle.
Note that you must use [ship](http://www.keltas.lt/eng/Price-list) to get from Klaipeda to the Spit and to some activities in Klaipeda, say Seamuseum and Dophinarium.
2. By ship [Lisco Patria](http://baltfinn.ru/), as I know, they still operating and you can sail with your car.
3. If you are traveling across the Lithuania, you can use two other border stations for foreigners:
* [Chernyshevskoye](http://en.wikipedia.org/wiki/Chernyshevskoye) - [Kybartai](http://en.wikipedia.org/wiki/Kybartai). Border station works all the time, and there are no restrictions about way you travel. In 2009 border station was opened after the reconstruction.
* [Sovetsk](http://en.wikipedia.org/wiki/Sovetsk,_Kaliningrad_Oblast) - [Panemunė](http://en.wikipedia.org/wiki/Panemun%C4%97) via the Queen Luise bridge. Border station works all the time, and there are no restrictions about way you travel.
![enter image description here](https://i.stack.imgur.com/zTEDQ.jpg)
I should note that where are other way to get to the Kaliningrad from Klaipeda, if you don't want to use your car - international buses are operating between two cities on daily basis.
You can find information [here](http://vokzal39.ru/bus-klaypeda.html) (site about the Kaliningrad bus station) and [here](http://www.kenigauto.com/schedule/kaliningrad-klaipeda/) (site about the international bus line from Kaliningrad). Note that various buses have various stops - some of them will move you across the Klaipeda's bay, some of them will not. |
126285 | Let `T={t|t=1,2,3..T}` be the time (sequence order number) For each group, at each `t` when/if a sequence occurs, we need to make sure the sequence (it is a number,let's assume it is `X`) is within the set of {`K-1,K,K+1`}, where `K` is the previous sequence number at `t-1`. For example, if the previous sequence number K=4, for the next sequence X, if X fall within [3,4,5]. Then this X meet the requirement. If every X in the sequence meets the requirement, this group meets the require and labeled it TRUE.
I know the for loop can do the trick but I have large observations, it is very slow to do it in a loop. I known the `cummax` can help find the non-deceasing sequence quickly. I was wondering is there any quick solution like `cummax`.
```
seq <- c(1,2,1,2,3,1,2,3,1,2,1,2,2,3,4)
group <- rep(letters[1:3],each=5)
dt <- data.frame(group,seq)
> dt
group seq
1 a 1
2 a 2
3 a 1
4 a 2
5 a 3
6 b 1
7 b 2
8 b 3
9 b 1
10 b 2
11 c 1
12 c 2
13 c 2
14 c 3
15 c 4
```
The desired output:
```
y label
a:true
b:false
c:true
``` | You can use the `diff` function to check if the adjacent sequence satisfies the condition:
```
library(dplyr)
dt %>% group_by(group) %>% summarize(label = all(abs(diff(seq)) <= 1))
# A tibble: 3 x 2
# group label
# <fctr> <lgl>
#1 a TRUE
#2 b FALSE
#3 c TRUE
```
Here is the corresponding `data.table` version:
```
library(data.table)
setDT(dt)[, .(label = all(abs(diff(seq)) <= 1)), .(group)]
``` |
126398 | I am on Day 4 of trying to get an `autocomplete` field to fire in an RSpec test. Works super in the browser, it is just incredibly resistant to running in my request specs.
---
UPDATE: It looks like my RSpec/Capy scripts are running against the dev db instead of the test db. I'm using Pow, so I don't know what to set `default_url_options[:host]` or `Capybara.app_host` and `Capybara.server_port` to. I have a feeling if I fix this, it may work.
---
The stack is:
* Rails 3.2.16
* Capybara
* RSpec
* Poltergeist/PhantomJS
* Pow
* Zeus
* Factory Girl
Click links, click buttons, fill\_in fields all work great. But when it comes time to get this autocomplete to work, it absolutely refuses to work.
I am using this method:
```
def fill_autocomplete(field, options = {})
fill_in field, with: options[:with]
page.execute_script %Q{ $("##{field}").trigger('focus') }
page.execute_script %Q{ $("##{field}").trigger('keydown') }
selector = %Q{ul.ui-autocomplete li.ui-menu-item a:contains("#{options[:select]}")}
Capybara::Screenshot.screenshot_and_open_image
page.should have_selector('ul.ui-autocomplete li.ui-menu-item a')
page.execute_script %Q{ $("#{selector}").trigger('mouseenter').click() }
end
```
which I found [here](http://ruby-journal.com/how-to-do-jqueryui-autocomplete-with-capybara-2/). The `screenshot` line is my own. But the line above:
```
page.should have_selector('ul.ui-autocomplete li.ui-menu-item a')
```
returns `false`. It works like a charm in the browser. I just can't for the life of me figure out why it won't work. I have tried everything I know how. How can I debug this?
The screenshot just shows the page I am expecting, with the field filled in appropriately. I even tested this with a "hello" alert that I inserted into the `autocomplete` call. Works flawlessly in the browser, but no result at all in the test.
In short, it looks like the following two lines are having no effect:
```
page.execute_script %Q{ $("##{field}").trigger('focus') }
page.execute_script %Q{ $("##{field}").trigger('keydown') }
``` | I had a similar problem and even though Capybara's documentation says that `have_selector` will wait for the AJAX call to complete, it did not work for me.
The following worked in my case:
```
def fill_in_autocomplete(field_label, field_class, options = {})
field_id = "##{page.evaluate_script("$('#{field_class}').attr('id')")}"
selector = "ul.ui-autocomplete li.ui-menu-item a"
fill_in(field_label, with: options[:with])
page.execute_script("$('#{field_id}').trigger('focus')")
page.execute_script("$('#{field_id}').trigger('keydown')")
sleep(2) # Hack! not sure why the line below isn't working...
#expect(page).to have_selector(selector, text: options[:with])
page.execute_script("$('#{selector}').click()")
end
```
You can call the method above like this:
```
fill_in_autocomplete('Some label', '.js-some-field', with: 'Some value'
```
I didn't want to pass the field ID and opted for a class instead, which is why the first line in the helper gets the ID based on the element's class. |
126534 | I'm new to Julia and learning use of Map, reduce, filter.
It is becoming very hard for me to comprehend how it can replace for and while loops.
For ex for below code, I would like to replace for loop
```
function addMultiplesOf3And5(N::Int)
sumOfMultiples = 0
if(N == 3)
return sumOfMultiples + N
end
for i = 3:N-1
if(i % 3 == 0 && i % 5 == 0)
continue
elseif(i % 3 == 0)
sumOfMultiples += i
elseif(i % 5 == 0)
sumOfMultiples += i
end
end
return sumOfMultiples
end
```
I would really appreciate the help.
Update :
This is what I did after going through tutorials
```
function addMultiplesOf3And5(N::Int)
array = range(1,N-1)
return reduce(+, map(x -> multiples_of_3_Or_5(x), array))
end
function multiples_of_3_Or_5(n)
if(n % 3 == 0 && n % 5 == 0)
return 0
elseif(n % 3 == 0)
return n
elseif(n % 5 == 0)
return n
else
return 0
end
end
```
Final:
```
function addMultiplesOf3And5(N::Int)
array = range(1,N-1)
return reduce(+, filter(x -> ((x%3==0)$(x%5==0)), array))
end
``` | To understand how you can replace your 'for loop + if block' code with 'map / reduce / filter' you need to know exactly how they work and why they might be chosen instead.
---
1. The `map` function
=====================
`map` is a function that takes a *function* variable and a list as arguments, and returns a *new* list, where each element is the result of applying the function to each element of the old list. So for example if your variable `f` refers to a function `f(x) = x + 5` you defined earlier, and you have a list `L=[1,2,3,4,5]`, then `map(f, L)` will return `[f(L[1]), f(L[2]), f(L[3]), f(L[4]), f(L[5])]`
So if you have code like:
```
f(x) = x + 5;
L = [1,2,3,4,5];
A = zeros(5);
for i in L
A[i] = f(i);
end
```
You could rewrite this as a mapping operation like so:
```
A = map(x -> x + 5, [1,2,3,4,5]);
```
2. The `reduce` function
========================
`reduce` takes a *binary* function variable (i.e. a function that takes two arguments) and a list as arguments. What it does is probably best explained by an example. Calling reduce with the `+` operator, and list `[1,2,3,4,5]` will do the following:
```
Step 1: [1, 2, 3, 4, 5] % : 5 elements
Step 2: [1+2, 3, 4, 5] % [3,3,4,5] : 4 elements
Step 3: [3+3, 4, 5] % [6, 4, 5] : 3 elements
Step 4: [6+4, 5] % [10, 5] : 2 elements
Step 5: [10+5] % [15] : 1 elements
result: 15
```
i.e. we have reduced the list to a single result by successively applying the binary function to the first pair of elements, consuming the list little by little.
So if you have code like:
```
f(x,y) = x + y
L = [1,2,3,4,5];
A = L[1];
for i in 2:length(L)
A = f(A, L[i])
end
```
you could rewrite this as a reduce operation like so:
```
A = reduce(x,y -> x+y, [1,2,3,4,5])
```
3. The `filter` function
========================
`filter` takes a *predicate* function (e.g. `iseven`, `isnull`, `==`, or anything that takes an argument and performs a test on it, resulting in true or false) and a list, tests each element of the list with the function and returns a new list that only contains the elements that pass that test. e.g.
```
filter(iseven, [1,2,3,4,5]) # returns [2,4]
```
The answer to your problem
==========================
If I understand correctly, `addMultiplesOf3And5` takes a number N (e.g. 20), and does the following:
* *filter* out all the elements that can be divided by either 3 or 5 from the list [1,2,3,...,20]
* successively add all elements of the resulting list together using a *reduce* function.
You should be able to use the above to figure out the exact code :) |
127471 | ```
my_dict = {"fruits": ["apple", "orange", "grape", "maracuya", "pineapple"],
"countries": [["India", "China", "Brazil", "Lesotho", "Nepal"],
["Spain", "Italy", "Japan", "Indonesia", "Russia"],
["Germany", "Austria", "Paraguay", "New Zealand", "Peru"],
["Australia", "Colombia", "Belice", "Swaziland"]],
"colors": [["blue", "black", "green", "yellow", "red"],
["purple", "pink", "white", "lila"]]}
```
Is there a way to know how many lists I have under each key? for example: under the key "fruits" I just have one, under "countries" I have 4
what I've tried it was mostly:
```
for key, values in my_dict.items():
print(len(values))
```
which didn't work
```
for key in my_dict.values():
print(len(key))
```
also failed | One approach, although it doesn't feel very pythonic, is to just loop through the values and, if a value is a list, test each item in the list to see whether *it* is a list, keeping count of the ones that are:
```
for key, value in my_dict.items():
count = 0
if isinstance(value, list):
for val in value:
if isinstance(val, list):
count += 1
print(f'{key} has {count} lists')
```
Prints:
```none
fruits has 0 list
countries has 4 lists
colors has 2 lists
``` |
127505 | Hopefully a simple question but My google foo is failing me - I've got a maven project where we're using SLF4J with Log4J 1.2 bindings.
We now want to move to Log4j 2 particularly for the performance improvement - however, I can't for the life of me find the maven dependency for the log4j 2.0 binding. I've found some notes at <http://logging.apache.org/log4j/2.x/log4j-slf4j-impl/> but no mention of any dependency info.
I'm also slightly confused by the fact there's apparently two ways to put slf4j on top of log4j2 (binding or adaptor)
What's the correct way to bind slf4j with log4j2 and how do I define the maven dependencies?
Editing to add some code following the 1st answer below, I'm getting exception:
>
> Exception in thread "main" java.lang.NoSuchMethodError:
> org/apache/logging/log4j/spi/AbstractLoggerWrapper.(Lorg/apache/logging/log4j/spi/AbstractLogger;Ljava/lang/String;)V
> at org.slf4j.impl.SLF4JLogger.(SLF4JLogger.java:48)
>
>
>
POM:
```
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>logging.test</groupId>
<artifactId>logtest2</artifactId>
<version>0.0.1</version>
<name>logtest2</name>
<description>logtest2</description>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j.adapters</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.0-beta3</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.0-beta9</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.0-beta9</version>
</dependency>
</dependencies>
```
My log4j.xml:
```
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="A1" class="org.apache.log4j.FileAppender">
<param name="File" value="c:/logtest2.0/log.txt" />
<param name="Append" value="false" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %p %X{sessionId} %c MSG: %m%n" />
</layout>
</appender>
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %p %X{sessionId} %c MSG: %m%n" />
</layout>
</appender>
<category name="org.apache.log4j.xml">
<priority value="debug" />
<appender-ref ref="A1" />
</category>
<root>
<priority value="debug" />
<appender-ref ref="STDOUT" />
</Root> </log4j:configuration>
```
and my test java class:
```
package loggertest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LoggerTest {
public static final Logger LOGGER = LoggerFactory.getLogger(LoggerTest.class);
public static void main(final String[] p_args) throws InterruptedException {
LOGGER.debug("Logger test");
}
}
``` | ```
"org.apache.logging.log4j:log4j-slf4j-impl:2.0-beta9" -
LOG4J implementation of SLF4J API
"org.apache.logging.log4j:log4j-core:2.0-beta9" - Core LOG4J implementation
```
This, plus a valid log4j2.xml on the classpath should get you started. |
127565 | I am using C# serial port controlling gsm modem. Now in Mikroelectronia USART Terminal
after sending:
>
> AT+CUSD=1,"\*778#",15
>
>
>
It receives:
>
> AT+CUSD=1,"\*778#",15
>
>
> OK
>
>
> +CUSD: 0,"Balance: 0.00 TK. Validity: 29-Jul-13. Bonus: 0.00TK. Free Min: 0. Dial \*121\*2092# for 3 hit songs of Ashiqui-2 as ur Caller
> Tunetk.10",64
>
>
>
But in C# after sending data
>
> AT+CUSD=1,"\*778#",15
>
>
>
it returns:
>
> AT+CUSD=1,"\*778#",15
>
>
> OK
>
>
> +CUSD: 0,"Balance: 0.00 TK. Validity: 29-Jul-13. Bonus: 0.00TK. Free Min: 0. Dial \*121\*2092# for 3 hit songs of Ashiqui-2 as ur Caller Tune
>
>
>
That means in C# it does not receive any data after "Caller Tune". Why is that happening? Part of C# code I have used is
```
private void Form1_Load(object sender, EventArgs e)
{
sp1.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
}
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
var valueOfPort = sp1.ReadExisting();
textBox1.AppendText(valueOfPort);
}
private void button1_Click(object sender, EventArgs e)
{
TextBox.CheckForIllegalCrossThreadCalls = false;
try
{
if (!sp1.IsOpen)
{
sp1.Open();
}
sp1.Write(textBox2.Text+"\r");
}
catch(Exception ex)
{
MessageBox.Show(string.Format("Exception : {0}", ex.Message), "Port Error");
}
}
``` | the `TextBox.CheckForIllegalCrossThreadCalls = false;` makes me very suspicious, I think that is what is breaking your program, simply just invoke to update the text box properly and I think it will work. Just change the event code to the following:
```
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if(textbox1.InvokeRequired)
{
textbox1.Invoke(new SerialDataReceivedEventHandler(sp_DataReceived), sender, e);
}
else
{
var valueOfPort = sp1.ReadExisting();
textBox1.AppendText(valueOfPort);
}
}
```
What this will do is check if you are running on the correct thread, if not it restarts the function again on the UI thread with the same arguments. Also be sure to remove the `TextBox.CheckForIllegalCrossThreadCalls = false;`
---
**UPDATE:** After re-reading the MSDN I found [this remark](http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readexisting.aspx)
>
> This method returns the contents of the stream and internal buffer of the SerialPort object as a string. This method does not use a time-out. Note that this method can leave trailing lead bytes in the internal buffer, which makes the BytesToRead value greater than zero.
>
>
>
Try checking to see if there is more data to read after calling `ReadExisting`.
```
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if(textbox1.InvokeRequired)
{
textbox1.Invoke(new SerialDataReceivedEventHandler(sp_DataReceived), sender, e);
}
else
{
while(sp1.BytesToRead > 0)
{
var valueOfPort = sp1.ReadExisting();
textBox1.AppendText(valueOfPort);
}
}
}
``` |
127583 | I am retrieving some data from an external API using javascript, I'm then displaying this data on a HTML page.
Within this returned data is a URL, it's in the following format;
```
var url = https://img.evbuc.com/moreStuff
```
I need to rewrite this URL so that it's prefixed with `www`, like this;
```
var url = https://www.img.evbuc.com/moreStuff
```
I want to achieve this using either javascript or jquery.
How can I achieve this? An explanation of the correct code would be great too. | You can use a regular expression to search and replace.
Following example also works with:
* `http://img.evbuc.com/moreStuff`
* `//img.evbuc.com/moreStuff`
* `https://img.evbuc.com/moreStuff//someMoreStuff`
```js
function prependUrl(url) {
return url.replace(/^([^\/]*)(\/\/)(.*)/, '$1//www.$3');
}
const urls = [
'https://img.evbuc.com/moreStuff',
'http://img.evbuc.com/moreStuff',
'//img.evbuc.com/moreStuff',
'https://img.evbuc.com/moreStuff//someMoreStuff'
];
urls.forEach((url) => console.log(`${ url } -> ${ prependUrl(url) }`));
```
* The regular expression contains 3 capturing groups:
1. Select everything up to the first `/` (excluding)
2. Select the `//` (for protocol root)
3. Select the rest
* The replacement value takes everything up to the first `/` (which may be an empty string as well)
* Replace the `//` with `//www.`
* Append the rest |
127925 | I have a number of strings similar to `Current Level: 13.4 db.` and I would like to extract just the floating point number. I say floating and not decimal as it's sometimes whole. Can RegEx do this or is there a better way? | If your float is always expressed in decimal notation something like
```
>>> import re
>>> re.findall("\d+\.\d+", "Current Level: 13.4db.")
['13.4']
```
may suffice.
A more robust version would be:
```
>>> re.findall(r"[-+]?(?:\d*\.\d+|\d+)", "Current Level: -13.2db or 14.2 or 3")
['-13.2', '14.2', '3']
```
If you want to validate user input, you could alternatively also check for a float by stepping to it directly:
```
user_input = "Current Level: 1e100 db"
for token in user_input.split():
try:
# if this succeeds, you have your (first) float
print float(token), "is a float"
except ValueError:
print token, "is something else"
# => Would print ...
#
# Current is something else
# Level: is something else
# 1e+100 is a float
# db is something else
``` |
127943 | after i spend 2 days of searching the bug i have to ask for help here. i do have MapViewController and place some pins on the map. i´ve copied most of the code from MapCallouts and WeatherMap of the apple code samples.
anyhow it seems that i´ve deleted or missed essential parts. it seems there is no connection between the MapViewController and the following code
```
- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation
{
NSLog(@"MKAnnotationView");
return nil;
}
```
setting an annotation looks like this and it works well:
```
- (void)createPoi:(CLLocationCoordinate2D)theCoordinate
{
NSLog(@"createPoi");
RandomAnnotation *randomAnnotation = [[RandomAnnotation alloc] init];
[randomAnnotation setTheCoordinate:theCoordinate];
[randomAnnotation setTheTitle:@"bla"];
[randomAnnotation setTheSubTitle:@"bla"];
[self.mapAnnotations insertObject:randomAnnotation atIndex:kRandomAnnotationIndex];
[randomAnnotation release];
[self.mapView addAnnotation:[self.mapAnnotations objectAtIndex:kRandomAnnotationIndex]];
}
```
i can´t figure out what's wrong. could anybody give me a hint what´s missing? i have to admit that i don´t have any experience with the delegate pattern. | Make sure the map view's `delegate` property is set.
If the map is created in IB, right-click on it and hook up its delegate outlet to File's Owner.
If the map is created in code, set the delegate after creating the map view:
```
mapView.delegate = self;
``` |
128083 | I have one-to-many relation between tables user and tag:
```
Users:
id username
--------------
1 Bob
2 Alice
3 Eve
Tags:
id user_id name
--------------------
1 1 java // Bobs tags...
2 1 java script
3 1 C#
4 2 java // Alices tags...
5 3 java // Eves tags...
6 3 java script
```
My goal is to extract all users with tags java or java script only, but not users which have java, java script and C# together.
As output of the query I expect to receive following result:
```
Result:
id username
--------------
2 Alice
3 Eve
```
I've tried to use query from [SQL one-to-many relationship - How to SELECT rows depending on multiple to-many properties?](https://stackoverflow.com/questions/51153040/sql-one-to-many-relationship-how-to-select-rows-depending-on-multiple-to-many), but as I noticed it is a bit different idea behind of it | Try this one:
```
const to = moment("2020-06-30T00:00:00");
const toNextDay = moment(to.add(1, 'days').toDate());
```
As moment is modifying the original moment object, either use toString() or toDate() to get the modified date.
```js
const to = moment("2020-06-30T00:00:00");
const toNextDay = moment(to.add(1, 'days').toDate());
console.log('In local time => ', toNextDay.toString());
const toUTC = moment.utc("2020-06-30T00:00:00");
const toNextDayUTC = moment.utc(toUTC.add(1, 'days').toDate());
console.log('In UTC => ', toNextDayUTC.toString());
```
```html
<script src="https://momentjs.com/downloads/moment.min.js"></script>
``` |
128592 | I am new to regex, so any help is really appreciated.
I have an expression to identify a URL :
`(http[^'\"]+)`
Unfortunately on some URLs, I get additional square brackets at the end
For instance "http://example.com]]"
As the result want to receive "http://example.com"
How do I get rid of those brackets with the help of the regex I wrote above? | What you actually have is called a negated character class, so just add characters that should not be matched. In addition, there's not really a need for a capturing group. That said, you could use
```
http[^'"\]\[]+
# ^^^^
```
Note that this will exclude square brackets *anywhere* in your possible url not just at the end. See [**a demo on regex101.com**](https://regex101.com/r/geOUbI/1). |
128671 | I am using Android Jetpack Navigation to navigate between fragments in my App and using a single Main Activity. I have a nav host fragment in main activity and a bottom navigation to naviagte between fragments.
```
navController = Navigation.findNavController(this,R.id.nav_host_fragment_container);
BottomNavigationView bottomNavigationView = findViewById(R.id.bot_nav_bar);
NavigationUI.setupWithNavController(bottomNavigationView,navController);
```
But I have a major issue - whenever I navigate to another fragment, the current fragment is destroyed and when I navigate back, it is recreated, along with the view model. Then the view model again fetches the data from the repository.
How can I fix this issue. I want to navigate between the tabs and load other fragments without destroying the current one. | You have to create your custom NavHostFragment(). There is a simple example here
<https://medium.com/@programmerr47/navigate-back-with-navigation-component-6cec37ba6964> |
128763 | Is it possible to create a user in PostgreSQL without providing the plain text password (ideally, I would like to be able to create a user providing only its password crypted with sha-256) ?
What I would like to do is to create a user with something like that :
```
CREATE USER "martin" WITH PASSWORD '$6$kH3l2bj8iT$KKrTAKDF4OoE7w.oy(...)BPwcTBN/V42hqE.';
```
Is there some way to do that ?
Thank you for your help. | You may provide the password already hashed with `md5`, as said in the doc ([CREATE ROLE](http://www.postgresql.org/docs/9.2/static/sql-createrole.html)):
>
> ENCRYPTED UNENCRYPTED These key words control whether the password is
> stored encrypted in the system catalogs. (If neither is specified, the
> default behavior is determined by the configuration parameter
> password\_encryption.) **If the presented password string is already in
> MD5-encrypted format, then it is stored encrypted as-is**, regardless of
> whether ENCRYPTED or UNENCRYPTED is specified (since the system cannot
> decrypt the specified encrypted password string). This allows
> reloading of encrypted passwords during dump/restore.
>
>
>
The information that's missing here is that the MD5-encrypted string should be the password concatened with the username, plus `md5` at the beginning.
So for example to create `u0` with the password `foobar`, knowing that `md5('foobaru0')` is `ac4bbe016b808c3c0b816981f240dcae`:
```
CREATE USER u0 PASSWORD 'md5ac4bbe016b808c3c0b816981f240dcae';
```
and then u0 will be able to log in by typing `foobar` as the password.
I don't think that there's currently a way to use `SHA-256` instead of `md5` for PostgreSQL passwords. |
128830 | This query works:
```
item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = 13")[0]
```
although if there are no results returned, it blows up in my face. (How can I get around this? A `for` loop seems dubious when I want at max one iteration.)
This query does not work:
```
item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = :1", CSIN)[0]
```
`CSIN` is a string representing a number. I get this error:
```
Traceback (most recent call last):
File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 507, in __call__
handler.get(*groups)
File "path\to\src\Main.py", line 42, in get
item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = :1", CSIN)[0]
File "C:\Program Files\Google\google_appengine\google\appengine\ext\db\__init__.py", line 1717, in __getitem__
raise IndexError('The query returned fewer than %d results' % (arg+1))
IndexError: The query returned fewer than 1 results
```
What am I doing wrong here? | You're trying to get an item from a list (or a list-like object) that is empty. What you're doing is sort of comparable to the following:
```
>>> results = [] # an empty list
>>> item = results[0] # Raises an IndexError, because there is nothing in the list
```
What you need to do instead is:
```
item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = :1", CSIN).get()
```
Then, `item` will be either `None` or the first result from the query. |
128834 | I've ran into some problems while using cordova plugin File Transfer. Thats my code:
```
window.requestFileSystem(
LocalFileSystem.PERSISTENT,
0,
function onFileSystemSuccess(fileSystem) {
fileSystem.root.getFile(
"dummy.html", {create: true, exclusive: false},
function gotFileEntry(fileEntry) {
var sPath = fileEntry.fullPath.replace("dummy.html", "");
var fileTransfer = new FileTransfer();
fileEntry.remove();
fileTransfer.download( 'http://cordova.apache.org/images/cordova_bot.png', sPath + photo.original_name,
function (theFile) {
alert('success: ' + JSON.stringify(theFile));
console.log("download complete: " + theFile.toURI());
// showLink(theFile.toURI());
},
function (error) {
alert('error: ' + JSON.stringify(error));
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code: " + error.code);
},
true
);
})
},
function (error) {
alert('error request: ' + JSON.stringify(error));
}
);
```
The fileTransfer.download's error callback is being returned with error code 3, http 401.
I already updated the File and FileTransfer plugins, my cordova version is 4.3.0.
Also checked my config.xml for
```
<access origin="*" />
```
but it's there.
I tried adding the header Connection: close, but no result.
Tried setting the download's 4th param to its default (false) too - no luck.
Testing on Android tablet.
Anyone anything? Thanks! | Just found a "solution" to my problem.
What I did was to downgrade the file-transfer plugin version from 0.5.0 to 0.4.8.
If someone ever face similar problem, do as below:
1. Delete the existing file-transfer plugin by running 'cordova plugins list' and then 'cordova plugin remove *name\_from\_list*'
2. Go to <https://github.com/apache/cordova-plugin-file-transfer/releases> and download the zip file of 0.4.8 release.
3. Unzip the file in root of your cordova application
4. Run 'cordova plugin add *path\_to\_unzipped\_folder*'
That's it. Seems to be working well, at least the success callback is returned, didn't really test more of it. |
128973 | I am currently concatenating a first and a last name like this (using PostgreSQL):
```
concat(customers.firstname, ' ', customers.lastname)
```
The problem I am having here is that I have customers that were entered with just a first name (ie. "Ronaldo"). The query above will return "Ronaldo " and that will not match.
I can use my server-side language to check for trailing spaces, but if there is a customer somewhere in my database that was accidentally typed in with a trailing space (ie. "Harry Potter "), then I won't match that one either.
I am looking for SQL that will return "Ronaldo", "John Smith", and "Harry Potter ". So basically I want to include a space between first and last name if last name is not equal to "" (empty string). If lastname is "" (empty string) then I want no space following the firstname. Is this possible with just SQL? Or will I have to figure out how to parse this appropriately with a server-side language? | You could use a [`TRIM()` function](http://www.postgresqltutorial.com/postgresql-trim-function/) call to strip off any leading or trailing spaces :
```
TRIM(CONCAT(customers.firstname, ' ', customers.lastname))
```
`TRIM()` also allows you to specific the characters you which to remove along with the location within the string (i.e. beginning, end, both, etc.) using the following syntax :
```
TRIM([LEADING | TRAILING | BOTH] [characters] FROM YourColumnOrString)
``` |
129410 | I have a working hibernate setup using annotations
```
@Entity
@Table(name="Users")
public class User implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="USER_ID")
private int id = 0;
@Column(name="EMAIL")
private String email = "";
@Temporal(TemporalType.TIMESTAMP)
@Column(name="CREATED")
private Date created = null;
public User(){
Calendar cal = Calendar.getInstance();
this.created = cal.getTime();
}
public User(int id, String email, Date created) {
this.id = id;
this.email = email;
this.created = created;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
@Override
public String toString() {
return "centaurus.hib.User{" +
"id=" + id +
", email='" + email + '\'' +
", created=" + created +
'}';
}
}
```
to make this work i have to have a entry(amongst others) in my hibernate.cfg.xml file
```
<mapping class="centaurus.hib.User"/>
```
Otherwise hibernate throws error saying it has no mapping file.
alternatively when i create my persistent sessionfactory I can specify what classes are to be mapped.
The issue is, on other projects i have worked on I only needed to add a class and annotate it correctly for hibernate to use it. this is what i would like to do but don't know how. I don't want to have a list of classes in my hibernate config in addition to the annotated classes. | You could `.join()` the new distributions to your existing `df` and then `.plot()` using wide format:
```
lower, upper = df.total_bill.quantile([.25, .75]).values.tolist()
df = df.join(df.loc[df.total_bill < lower, 'total_bill'], rsuffix='_lower')
df = df.join(df.loc[df.total_bill > upper, 'total_bill'], rsuffix='_upper')
sns.pointplot(data=df.loc[:, [c for c in df.columns if c.startswith('total')]])
```
to get:
[![enter image description here](https://i.stack.imgur.com/Ywl0c.png)](https://i.stack.imgur.com/Ywl0c.png)
If you wanted to add groups, you could simply use `.unstack()` to get to `long` format:
```
df = df.loc[:, ['total_bill', 'total_bill_upper', 'total_bill_lower']].unstack().reset_index().drop('level_1', axis=1).dropna()
df.columns = ['grp', 'val']
```
to get:
```
sns.pointplot(x='grp', y='val', hue='grp', data=df)
```
[![enter image description here](https://i.stack.imgur.com/FtMfO.png)](https://i.stack.imgur.com/FtMfO.png) |
129441 | We have an outdated build of SQL Server 2008 R2(SP1) and therefore we are in need of patching(SP3).
Does this have any impact on SharePoint?
What measures should I take, besides backing everything up and testing before doing in production? | SharePoint 2010 is supported on SQL 20018 R2 SP3, so no, there shouldn't be any issue installing the service pack onto your SQL Server.
I'd test (if at all possible) on a test system first, simply to ensure that any other solution installed within the SharePoint farm also continues to function as expected once the service pack is installed.
Obviously you should also take a set of backups of all of the databases on the SQL Server before you proceed (and test the backups!) in case you have any issues and need to be able to roll back. A SQL alias (as mentioned by Benny) is your friend here as you can run up a new server quickly, change the SQL alias(es) to point to the new server and you're good to go.
During the installation of the service pack there will be downtime to the farm as the database services will be unavailable for a period of time during the patching process. If at all possible, shut down the SharePoint server before starting the work. |
129503 | Say you are a program, and you are given some source code but you don't know in what language, it can be C++/Java/Python/Lisp/... all you know is that it is highly structured and LR(1) parse-able, and you want to make **some guesses on the corresponding syntactic tree**.
How would you try to achieve this, and would you have any hope to make it working on some toy problems ?
To be clear, the goal isn't to make a parser for 4 or 5 different (but similar) programming languages, but really to detect -from some examples- the regularity in how the data is structured, and build from it a syntactic tree, with the hope to generate a grammar, a syntactic parser and -let's dream- a semantic parser and an interpreter.
My thoughts : a major problem is that in general the grammar needed for parsing a given source code isn't LR(1), but only locally LR(1), and globally recursive. For example HTML contains some Javascript, itself containing some HTML+Javascript **hidden in a string** :
```
<html><body><script>
document.onLoad = (function(){
document.write("<div> <input type='button' value='click' \
onClick='javascript:fn();'></input> </div> \
<script> \
function fn() { alert('wow a language nested into another'); } \
</script> ");
</scritp></body></html>
```
For parsing this, you need to generate a grammar for HTML and another one for Javascript, and generate a recursive grammar saying that sometimes in the syntactic tree (from one node to its child) it can jump from one language to the other.
**Do you have any reference/idea on this problem?** | You might be interested in learning about [grammar induction](https://en.wikipedia.org/wiki/Grammar_induction): given a set of examples of strings from a context-free language, there are algorithms to learn a context-free grammar that generates those strings.
To learn more about it, read the Wikipedia article I linked to, and [Inducing a context free grammar](https://cs.stackexchange.com/q/44583/755), [Is there a known method for constructing a grammar given a finite set of finite strings?](https://cs.stackexchange.com/q/53279/755), and the the [Sequitur](https://en.wikipedia.org/wiki/Sequitur_algorithm), [Lempel-Ziv-Welch](https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch), and [byte pair encoding](https://en.wikipedia.org/wiki/Byte_pair_encoding) algorithms.
There's no hope for automatically building an interpreter for the language, because that depends on the semantics (meaning) of the programs, and you can't determine that solely from the program source code; the most you can hope to learn is to characterize the syntax of the language, not the semantics. |
129677 | JavaScript happy times fun land
```js
// make a method
var happy = function(a, b, c) {
console.log(a, b, c);
};
// store method to variable
var b = happy;
// bind a context and some arguments
b.bind(happy, 1, 2, 3);
// call the method without additional arguments
b();
```
Output. Yay!
```
1 2 3
```
---
In Ruby
```rb
# make a method
def sad a, b, c
puts a, b, c
end
# store method to variable
b = method(:sad)
# i need some way to bind args now
# (this line is an example of what i need)
b.bind(1, 2, 3)
# call the method without passing additional args
b.call
```
Desired output
```
1, 2, 3
```
---
For what it's worth, I know JavaScript can change the context of the binding with the first argument passed to `.bind`. In Ruby, I'd be 99% happy even if I couldn't change the context. I primarily need to simply bind parameters to the method.
**Question**
Is there a way to bind parameters to an instance of a Ruby `Method` such that when I call `method.call` without additional parameters, the bound parameters are still passed to the method?
**Goal**
This is a common JavaScript idiom and I think it would be useful in any language. The goal is to pass a method `M` to a receiver `R` where R does not need (or have) intrinsic knowledge of which (or how many) parameters to send to M when R executes the method.
A JavaScript demonstration of how this might be useful
```js
/* this is our receiver "R" */
var idiot = function(fn) {
console.log("yes, master;", fn());
};
/* here's a couple method "M" examples */
var calculateSomethingDifficult = function(a, b) {
return "the sum is " + (a + b);
};
var applyJam = function() {
return "adding jam to " + this.name;
};
var Item = function Item(name) {
this.name = name;
};
/* here's how we might use it */
idiot(calculateSomethingDifficult.bind(null, 1, 1));
// => yes master; the sum is 2
idiot(applyJam.bind(new Item("toast")));
// => yes master; adding jam to toast
``` | Normally, rebinding methods isn't something you do in Ruby. Instead, you use blocks:
```
# This is our receiver "R"
def idiot(&block)
puts("yes, master; #{block.call}")
end
# Here's a couple method "M" examples
def calculateSomethingDifficult(a, b)
return "the sum is #{a + b}"
end
def applyJam(object)
return "adding jam to " + object.name
end
class Item
attr_reader :name
def initialize(name)
@name = name
end
end
# Here's how we might use it
idiot do
calculateSomethingDifficult(1, 1)
end
#=> yes master; the sum is 2
# You *can* change calling context too (see instance_exec), but I'd
# discourage it. It's probably better to just pass the object as a
# parameter.
idiot do
applyJam(Item.new("toast"))
end
#=> yes master; adding jam to toast
```
---
If you really want to "bind" methods like you do in JavaScript it's definitely possible though:
```
class Method
def bind *args
Proc.new do |*more|
self.call *(args + more)
end
end
end
```
That should make your example work *almost* as you originally described:
```
# make a method
def sad a, b, c
puts a, b, c
end
# store method to variable
b = method(:sad)
# Get a "bound" version of the method
b = b.bind(1, 2, 3)
# call the method without passing additional args
b.call
```
If you need it exact, you can probably define `Object#bindable_method` to return some `BindableMethod` class that does what you want. For most cases though I think the above should work for you. |
129715 | ```
public override Task<IdentityResult> ValidateAsync(AppUser item)
{
if(item.Email != "a@a.com")
{
IEnumerable<string> errors = new List<string>() { "error1" };
}
}
```
The IdentityResultjust needs a simple array or ienumerable of strings in its constructor.
Whats the correct syntax? | If you absolutely need to have ValidateAsync() instead of just Validate(), use a TaskCompletionSource to simulate.
```
public override Task<IdentityResult> ValidateAsync(AppUser item)
{
var result = new IdentityResult();
var tcs = new TaskCompletionSource<IdentityResult>();
if(item.Email != "a@a.com")
{
IEnumerable<string> errors = new List<string>() { "error1" };
result.Add(errors)
}
tcs.SetResult(result);
return tcs.Task;
}
```
[Using Task.Run creates unnecessary overhead](http://blogs.msdn.com/b/pfxteam/archive/2012/03/24/10287244.aspx).
EDIT: I'm not exactly sure if TaskCompletionSource is any better than Task.Run. I'd love to hear the answer. |
130082 | This code interprets an abstract syntax tree generated by a recursive descent parser for a dynamic scripting language called Hassium. The syntax of this language looks like this
```
# Recursion functions
func fibonacci(n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
func main () {
for (i = 0; i < 33; i++) {
println(fibonacci(i));
}
}
```
Anyways, people on an IRC network I am a member of have been complaining with this specific class. Obliviously, this a very big file so I wouldn't ask you all to review every line. It works, but what stylistic things should be refactored; such as readability, design, coding style, ect? Also does this reek of anti-patterns or bad code smell?
// Credit to contributer Zdimension, who has done countless amounts of work on this project
```
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Hassium.Functions;
using Hassium.HassiumObjects;
using Hassium.HassiumObjects.Collections;
using Hassium.HassiumObjects.Conversion;
using Hassium.HassiumObjects.Debug;
using Hassium.HassiumObjects.Drawing;
using Hassium.HassiumObjects.IO;
using Hassium.HassiumObjects.Math;
using Hassium.HassiumObjects.Networking;
using Hassium.HassiumObjects.Networking.HTTP;
using Hassium.HassiumObjects.Text;
using Hassium.HassiumObjects.Types;
using Hassium.Lexer;
using Hassium.Parser;
using Hassium.Parser.Ast;
using Hassium.Semantics;
namespace Hassium.Interpreter
{
public delegate void ExitEventHandler(int code);
/// <summary>
/// Interpreter.
/// </summary>
public class Interpreter : IVisitor
{
public Stack<StackFrame> CallStack = new Stack<StackFrame>();
public Dictionary<string, HassiumObject> Globals = new Dictionary<string, HassiumObject>();
public AstNode Code { get; set; }
public SymbolTable SymbolTable { get; set; }
public int isInFunction;
private bool enforceMainEntryPoint;
private bool isRepl;
private bool firstExecute = true;
private int isInLoop;
private bool continueLoop;
private bool breakLoop;
public bool returnFunc;
public HassiumObject GetVariable(string name, AstNode node)
{
if (Constants.ContainsKey(name))
return Constants[name];
if (CallStack.Count > 0 && CallStack.Any(x => x.Locals.ContainsKey(name)))
return CallStack.First(x => x.Locals.ContainsKey(name)).Locals[name];
if (CallStack.Count > 0 && CallStack.Any(x => x.Locals.Any(y => y.Key.StartsWith(name))))
return
CallStack.First(x => x.Locals.Any(y => y.Key.StartsWith(name)))
.Locals.First(x => x.Key.StartsWith(name))
.Value;
if (Globals.ContainsKey(name))
return Globals[name];
if (Globals.Any(x => x.Key.StartsWith(name)))
return Globals.First(x => x.Key.StartsWith(name)).Value;
else throw new ParseException("The variable '" + name + "' doesn't exist.", node);
}
public bool HasVariable(string name, bool onlyglobal = false)
{
return onlyglobal
? Globals.ContainsKey(name) || Constants.ContainsKey(name)
: Globals.ContainsKey(name) || Constants.ContainsKey(name) ||
(CallStack.Count > 0 &&
(CallStack.Peek().Scope.Symbols.Contains(name) || CallStack.Any(x => x.Locals.ContainsKey(name))));
}
public void SetVariable(string name, HassiumObject value, AstNode node, bool forceglobal = false,
bool onlyexist = false)
{
if (Constants.ContainsKey(name))
throw new ParseException("Can't change the value of the internal constant '" + name + "'.", node);
if (!forceglobal && CallStack.Count > 0 &&
(!onlyexist ||
(CallStack.Peek().Scope.Symbols.Contains(name) || CallStack.Any(x => x.Locals.ContainsKey(name)))) &&
!Globals.ContainsKey(name))
{
if (CallStack.Any(x => x.Locals.ContainsKey(name)))
CallStack.First(x => x.Locals.ContainsKey(name)).Locals[name] = value;
else CallStack.Peek().Locals[name] = value;
}
else
Globals[name] = value;
}
public void FreeVariable(string name, AstNode node, bool forceglobal = false)
{
if (Constants.ContainsKey(name))
throw new ParseException("Can't delete internal constant '" + name + "'.", node);
if (forceglobal)
{
if (!Globals.ContainsKey(name))
throw new ParseException("The global variable '" + name + "' doesn't exist.", node);
Globals.Remove(name);
}
else
{
if (!HasVariable(name)) throw new ParseException("The variable '" + name + "' doesn't exist.", node);
if (CallStack.Count > 0 &&
(CallStack.Peek().Scope.Symbols.Contains(name) || CallStack.Any(x => x.Locals.ContainsKey(name))))
CallStack.First(x => x.Locals.ContainsKey(name) || x.Scope.Symbols.Contains(name))
.Locals.Remove(name);
else
Globals.Remove(name);
}
}
public bool HasFunction(string name, int parm, AstNode node)
{
return HasVariable(name + "`" + parm) || HasVariable(name + "`i") || HasVariable(name);
}
public IFunction GetFunction(string name, int parm, AstNode node)
{
if (HasVariable(name + "`" + parm))
{
return GetVariable(name + "`" + parm, node);
}
if (HasVariable(name + "`i"))
{
return GetVariable(name + "`i", node);
}
if (HasVariable(name))
{
return GetVariable(name, node);
}
throw new ParseException("The function " + name + " doesn't exist", node);
}
private bool exit;
public int exitcode = -1;
public Dictionary<string, HassiumObject> Constants = new Dictionary<string, HassiumObject>
{
{"true", new HassiumBool(true)},
{"false", new HassiumBool(false)},
{"Convert", new HassiumConvert()},
{"Console", new HassiumConsole()},
{"null", null},
};
/// <summary>
/// Initializes a new instance of the <see cref="Interpreter"/> class.
/// </summary>
public Interpreter(bool forcemain = true)
{
SymbolTable = new SymbolTable();
enforceMainEntryPoint = forcemain;
LoadInternalFunctions();
}
public Interpreter(SymbolTable symbolTable, AstNode code, bool forcemain = true)
{
Code = code;
SymbolTable = symbolTable;
enforceMainEntryPoint = forcemain;
LoadInternalFunctions();
}
public void Execute(bool repl = false)
{
isRepl = repl;
foreach (var node in Code.Children)
{
if (node is FuncNode && firstExecute)
{
var fnode = ((FuncNode) node);
var scope = SymbolTable.ChildScopes[fnode.Name + "`" + fnode.Parameters.Count];
SetVariable(fnode.Name + "`" + fnode.Parameters.Count, new HassiumMethod(this, fnode, scope, null),
node);
}
else if (node is ClassNode)
{
var cnode = ((ClassNode) node);
if (!Globals.ContainsKey(cnode.Name))
Globals.Add(cnode.Name, new HassiumClass(cnode, this));
}
}
if (!Globals.ContainsKey("main`0") && enforceMainEntryPoint)
{
Console.WriteLine("Could not execute, no main entry point of program!");
Environment.Exit(-1);
}
firstExecute = false;
foreach (var node in Code.Children)
{
if (exit) return;
if (node is FuncNode)
{
var fnode = ((FuncNode) node);
var scope = SymbolTable.ChildScopes[fnode.Name + "`" + fnode.Parameters.Count];
//If there is a main, let it be the main entry point of the program
if (fnode.Name == "main")
{
new HassiumMethod(this, fnode, scope, null).Invoke();
return;
}
}
else
node.Visit(this);
}
}
public void LoadInternalFunctions()
{
foreach (var entry in GetFunctions())
Globals.Add(entry.Key, entry.Value);
}
private HassiumObject interpretBinaryOp(BinOpNode node)
{
var right = (HassiumObject) node.Right.Visit(this);
if (node.BinOp == BinaryOperation.Assignment)
{
if (node.Left is ArrayGetNode)
{
var call = (ArrayGetNode) (node.Left);
if (!call.Target.CanBeIndexed)
throw new ParseException(
"The [] operator only applies to objects of type Array, Dictionary or String.", node);
if (!call.Target.CanBeModified)
throw new ParseException("The specified target cannot be modified.", node);
var evaluated = call.Target.Visit(this);
if (evaluated is HassiumDictionary)
{
var theArray = ((HassiumDictionary) evaluated);
HassiumObject arid = null;
if (call.Arguments.Children.Count > 0)
arid = (HassiumObject) call.Arguments.Children[0].Visit(this);
var theValue = (node.IsOpAssign && arid != null)
? interpretBinaryOp(theArray[arid], right, node.AssignOperation)
: right;
if (arid == null)
theArray.Value.Add(new HassiumKeyValuePair(theArray.Value.Count, theValue));
else
{
if (theArray.Value.Any(cur => cur.Key.ToString() == arid.ToString()))
{
foreach (var cur in theArray.Value.Where(cur => cur.Key.ToString() == arid.ToString()))
{
theArray.Value[cur.Key].Key = theValue;
break;
}
}
else
{
theArray[arid] = theValue;
}
}
SetVariable(call.Target.ToString(), theArray, call);
}
else if (evaluated is HassiumArray || evaluated is HassiumString)
{
HassiumArray theArray = null;
if (evaluated is HassiumString)
{
theArray = new HassiumArray(evaluated.ToString().ToCharArray().Cast<object>());
}
theArray = ((HassiumArray) evaluated);
int arid = -1;
bool append = false;
if (call.Arguments.Children.Count > 0)
arid = (HassiumObject) call.Arguments.Children[0].Visit(this);
else
append = true;
var theValue = node.IsOpAssign
? interpretBinaryOp(theArray[arid], right, node.AssignOperation)
: right;
if (append)
theArray.Add(new[] {theValue});
else
{
if (arid >= theArray.Value.Length)
throw new ParseException("The index is out of the bounds of the array", call);
theArray[arid] = theValue;
}
SetVariable(call.Target.ToString(), theArray, call);
}
else
{
throw new ParseException(
"The [] operator only applies to objects of type Array, Dictionary or String.", node);
}
}
else if (node.Left is MemberAccessNode)
{
var accessor = (MemberAccessNode) node.Left;
var target = (HassiumObject) accessor.Left.Visit(this);
target.SetAttribute(accessor.Member, right);
}
else
{
if (!(node.Left is IdentifierNode))
throw new ParseException("Not a valid identifier", node);
SetVariable(node.Left.ToString(),
node.IsOpAssign
? interpretBinaryOp(new BinOpNode(node.Position, node.AssignOperation, node.Left, node.Right))
: right, node);
}
return right;
}
var left = node.Left.Visit(this);
if (node.BinOp == BinaryOperation.Is)
{
var target = right;
Type ttype = null;
if (target is HassiumClass) ttype = target.GetType();
return left.GetType() == ttype;
}
return interpretBinaryOp(left, right, node.IsOpAssign ? node.AssignOperation : node.BinOp, node.Position);
}
/// <summary>
/// Interprets a binary op
/// </summary>
/// <param name="left">The left-hand parameter</param>
/// <param name="right">The right-hand parameter</param>
/// <param name="_op">The operation type</param>
/// <param name="pos">position</param>
/// <returns>The result of the operation</returns>
private HassiumObject interpretBinaryOp(object left, object right, BinaryOperation _op, int pos = -1)
{
if (left == null && _op != BinaryOperation.NullCoalescing)
throw new ParseException("Left operand can't be null", pos);
if (left is AstNode) left = ((AstNode) left).Visit(this);
if (left is int) left = (double) (int) left;
if (right is AstNode) right = ((AstNode) right).Visit(this);
if (right is int) right = (double) (int) right;
switch (_op)
{
case BinaryOperation.Addition:
if (left is HassiumString || right is HassiumString)
return new HassiumString(left + right.ToString());
if (left is HassiumDate || right is HassiumDate)
return (HassiumDate) left + (HassiumDate) right;
if (left is HassiumKeyValuePair || right is HassiumKeyValuePair)
return new HassiumString(left + right.ToString());
if (left is HassiumInt && right is HassiumInt)
return new HassiumInt(Convert.ToInt32(left) + Convert.ToInt32(right));
if (left is HassiumEvent && right is HassiumMethod)
{
var ev = (HassiumEvent) left;
ev.AddHandler((HassiumMethod) right);
return ev;
}
return new HassiumDouble(Convert.ToDouble(left) + Convert.ToDouble(right));
case BinaryOperation.Subtraction:
if (left is HassiumInt && right is HassiumInt)
return new HassiumInt(Convert.ToInt32(left) - Convert.ToInt32(right));
if (left is HassiumEvent && right is HassiumMethod)
{
var ev = (HassiumEvent) left;
ev.RemoveHandler((HassiumMethod) right);
return ev;
}
return new HassiumDouble(Convert.ToDouble(left) - Convert.ToDouble(right));
case BinaryOperation.Division:
if (Convert.ToDouble(right) == 0.0) throw new ParseException("Cannot divide by zero", pos);
if (left is HassiumInt && right is HassiumInt)
return new HassiumInt(Convert.ToInt32(left) / Convert.ToInt32(right));
return new HassiumDouble(Convert.ToDouble(left) / Convert.ToDouble(right));
case BinaryOperation.Multiplication:
if ((left is HassiumString && right is HassiumInt) ||
right is HassiumString && left is HassiumInt)
{
if (left is HassiumString)
return new HassiumString(string.Concat(Enumerable.Repeat(left, Convert.ToInt32(right))));
else
return new HassiumString(string.Concat(Enumerable.Repeat(right, Convert.ToInt32(left))));
}
if (left is HassiumInt && right is HassiumInt)
return new HassiumInt(Convert.ToInt32(left) * Convert.ToInt32(right));
return new HassiumDouble(Convert.ToDouble(left) * Convert.ToDouble(right));
case BinaryOperation.Equals:
return new HassiumBool(left.ToString() == right.ToString());
case BinaryOperation.LogicalAnd:
return new HassiumBool(Convert.ToBoolean(left) && Convert.ToBoolean(right));
case BinaryOperation.LogicalOr:
return new HassiumBool(Convert.ToBoolean(left) || Convert.ToBoolean(right));
case BinaryOperation.NotEqualTo:
return new HassiumBool(left.GetHashCode() != right.GetHashCode());
case BinaryOperation.LessThan:
return new HassiumBool(Convert.ToDouble(left) < Convert.ToDouble(right));
case BinaryOperation.GreaterThan:
return new HassiumBool(Convert.ToDouble(left) > Convert.ToDouble(right));
case BinaryOperation.GreaterOrEqual:
return new HassiumBool(Convert.ToDouble(left) >= Convert.ToDouble(right));
case BinaryOperation.LesserOrEqual:
return new HassiumBool(Convert.ToDouble(left) <= Convert.ToDouble(right));
case BinaryOperation.CombinedComparison:
if (new HassiumBool(interpretBinaryOp(left, right, BinaryOperation.GreaterThan)))
return new HassiumInt(1);
return new HassiumBool(interpretBinaryOp(left, right, BinaryOperation.LessThan))
? new HassiumInt(-1)
: new HassiumInt(0);
case BinaryOperation.Xor:
return new HassiumInt(Convert.ToInt32(left) ^ Convert.ToInt32(right));
case BinaryOperation.BitwiseAnd:
return new HassiumInt(Convert.ToInt32(left) & Convert.ToInt32(right));
case BinaryOperation.BitwiseOr:
return new HassiumInt(Convert.ToInt32(left) | Convert.ToInt32(right));
case BinaryOperation.BitshiftLeft:
return new HassiumInt(Convert.ToInt32(left) << Convert.ToInt32(right));
case BinaryOperation.BitshiftRight:
return new HassiumInt(Convert.ToInt32(left) >> Convert.ToInt32(right));
case BinaryOperation.Modulus:
return new HassiumInt(Convert.ToInt32(left) % Convert.ToInt32(right));
case BinaryOperation.Pow:
if (left is HassiumInt && right is HassiumInt)
return new HassiumInt((int) Math.Pow(Convert.ToInt32(left), Convert.ToInt32(right)));
return new HassiumDouble(Math.Pow(Convert.ToDouble(left), Convert.ToDouble(right)));
case BinaryOperation.Root:
/*if (left is HassiumInt && right is HassiumInt)
return new HassiumInt((int)Math.Pow(Convert.ToDouble(left), 1.0 / Convert.ToDouble(right)));*/
return new HassiumDouble(Math.Pow(Convert.ToDouble(left), 1.0 / Convert.ToDouble(right)));
case BinaryOperation.NullCoalescing:
return HassiumObject.ToHassiumObject(left) ?? HassiumObject.ToHassiumObject(right);
}
// Raise error
return new HassiumInt(-1);
}
/// <summary>
/// Interprets the unary op.
/// </summary>
/// <returns>The unary op.</returns>
/// <param name="node">Node.</param>
private HassiumObject interpretUnaryOp(UnaryOpNode node)
{
var value = node.Value.Visit(this);
switch (node.UnOp)
{
case UnaryOperation.Not:
return !Convert.ToBoolean(value);
case UnaryOperation.Negate:
if (value is int) return -(int) value;
return -Convert.ToDouble(value);
case UnaryOperation.Complement:
return ~(int) Convert.ToDouble(value);
}
//Raise error
return -1;
}
/// <summary>
/// Gets the functions.
/// </summary>
/// <returns>The functions.</returns>
/// <param name="path">Path.</param>
public static Dictionary<string, InternalFunction> GetFunctions(string path = "")
{
var result = new Dictionary<string, InternalFunction>();
var testAss = path == "" ? Assembly.GetExecutingAssembly() : Assembly.LoadFrom(path);
foreach (var type in testAss.GetTypes())
{
if (type.GetInterface(typeof (ILibrary).FullName) != null)
{
foreach (var myfunc in type.GetMethods(BindingFlags.Public | BindingFlags.Static))
{
var theattr1 = myfunc.GetCustomAttributes(typeof (IntFunc), true);
foreach (var theattr in theattr1.OfType<IntFunc>())
{
foreach (int argNumber in theattr.Arguments)
{
var rfunc = new InternalFunction(
(HassiumFunctionDelegate)
Delegate.CreateDelegate(typeof (HassiumFunctionDelegate), myfunc),
argNumber, false, theattr.Constructor);
result.Add(theattr.Name + "`" + (argNumber == -1 ? "i" : argNumber.ToString()), rfunc);
if (theattr.Alias != "")
result.Add(theattr.Alias + "`" + (argNumber == -1 ? "i" : argNumber.ToString()), rfunc);
}
}
}
}
}
return result;
}
public object Accept(Expression expr)
{
VisitSubnodes(expr);
return null;
}
public object Accept(ArgListNode node)
{
var arguments = new HassiumObject[node.Children.Count];
for (var x = 0; x < node.Children.Count; x++)
{
arguments[x] = (HassiumObject) node.Children[x].Visit(this);
}
return arguments;
}
public object Accept(ArrayGetNode node)
{
var call = node;
if (!call.Target.CanBeIndexed)
throw new ParseException(
"The [] operator only applies to objects of type Array, Dictionary or String.", node);
var evaluated = (HassiumObject) call.Target.Visit(this);
if (evaluated is HassiumDictionary)
{
var theArray = ((HassiumDictionary) evaluated);
HassiumObject arid = null;
if (call.Arguments.Children.Count > 0)
arid = (HassiumObject) call.Arguments.Children[0].Visit(this);
if (arid == null)
return theArray.Value.Last().Value;
else
{
return theArray.Value.Any(cur => cur.Key.ToString() == arid.ToString())
? theArray.Value.First(cur => cur.Key.ToString() == arid.ToString()).Value
: theArray[arid];
}
}
else if (evaluated is HassiumArray || evaluated is HassiumString)
{
HassiumArray theArray = null;
if (evaluated is HassiumString)
{
theArray = new HassiumArray(evaluated.ToString().ToCharArray().Cast<object>());
}
else theArray = ((HassiumArray) evaluated);
int arid = -1;
bool append = false;
if (call.Arguments.Children.Count > 0)
arid = (HassiumObject) call.Arguments.Children[0].Visit(this);
else
append = true;
int count = (HassiumObject) call.Count.Visit(this);
if (append)
return theArray.Value.Last();
else
{
if (arid >= theArray.Value.Length || arid + count > theArray.Value.Length)
throw new ParseException("The index is out of the bounds of the array", call);
var r = theArray.Value.Skip(arid).Take(count).ToArray();
return r.Length == 1 ? r[0] : r.ToArray();
}
}
else
{
throw new ParseException(
"The [] operator only applies to objects of type Array, Dictionary or String.", node);
}
}
public object Accept(ArrayIndexerNode node)
{
return null;
}
public object Accept(ArrayInitializerNode node)
{
var ainode = node;
var content = ainode.Value;
if (ainode.IsDictionary)
return new HassiumDictionary(content.Select(
pair =>
new KeyValuePair<HassiumObject, HassiumObject>(
pair.Key is AstNode
? (HassiumObject) ((AstNode) (pair.Key)).Visit(this)
: HassiumObject.ToHassiumObject(pair.Key),
pair.Value is AstNode
? (HassiumObject) ((AstNode) (pair.Value)).Visit(this)
: HassiumObject.ToHassiumObject(pair.Value)))
.ToDictionary(x => x.Key, x => x.Value));
else
return
new HassiumArray(
content.Values.Select(x => x is AstNode ? (HassiumObject) ((AstNode) x).Visit(this) : x));
}
public object Accept(BinOpNode node)
{
var bnode = node;
var res = interpretBinaryOp(bnode);
if (isRepl) ConsoleFunctions.PrintLn(new[] {res});
return res;
}
public object Accept(BreakNode node)
{
if (isInLoop == 0) throw new ParseException("'break' cannot be used outside a loop", node);
breakLoop = true;
return null;
}
public object Accept(CaseNode node)
{
node.Body.Visit(this);
return null;
}
public object Accept(ClassNode node)
{
return null;
}
public object Accept(CodeBlock node)
{
VisitSubnodes(node);
return null;
}
public object Accept(ConditionalOpNode node)
{
var ifStmt = node;
if ((HassiumBool) (ifStmt.Predicate.Visit(this)))
{
return ifStmt.Body.Visit(this);
}
else
{
return ifStmt.ElseBody.Visit(this);
}
}
public object Accept(ContinueNode node)
{
if (isInLoop == 0) throw new ParseException("'continue' cannot be used outside a loop", node);
continueLoop = true;
return null;
}
public object Accept(ForEachNode node)
{
var forStmt = node;
var needlestmt = forStmt.Needle;
var haystackstmt = forStmt.Haystack.Visit(this);
isInLoop++;
if (haystackstmt is HassiumDictionary)
{
var theArray = ((HassiumDictionary) haystackstmt);
var keyvname = "";
var valvname = "";
if (needlestmt is ArrayInitializerNode)
{
keyvname = ((ArrayInitializerNode) needlestmt).Value[0].ToString();
valvname = ((ArrayInitializerNode) needlestmt).Value[1].ToString();
}
else
{
valvname = needlestmt.ToString();
}
if (keyvname != "") SetVariable(keyvname, null, forStmt);
SetVariable(valvname, null, forStmt);
foreach (var needle in (keyvname != "" ? theArray : (IEnumerable) (theArray.Value.Select(x => x.Value)))
)
{
if (keyvname != "") SetVariable(keyvname, ((HassiumKeyValuePair) needle).Key, forStmt);
SetVariable(valvname,
keyvname != "" ? ((HassiumKeyValuePair) needle).Value : HassiumObject.ToHassiumObject(needle),
forStmt);
forStmt.Body.Visit(this);
if (continueLoop) continueLoop = false;
if (breakLoop)
{
breakLoop = false;
break;
}
}
if (keyvname != "") FreeVariable(keyvname, forStmt);
FreeVariable(valvname, forStmt);
isInLoop--;
}
else if (haystackstmt is HassiumArray || haystackstmt is HassiumString)
{
HassiumArray theArray = null;
if (haystackstmt is HassiumString)
{
theArray = new HassiumArray(haystackstmt.ToString().ToCharArray().Cast<object>());
}
else theArray = ((HassiumArray) haystackstmt);
var valvname = needlestmt.ToString();
SetVariable(valvname, null, forStmt);
foreach (var needle in theArray.Value)
{
SetVariable(valvname, HassiumObject.ToHassiumObject(needle), forStmt);
forStmt.Body.Visit(this);
if (continueLoop) continueLoop = false;
if (breakLoop)
{
breakLoop = false;
break;
}
}
FreeVariable(valvname, forStmt);
isInLoop--;
}
else
{
isInLoop--;
throw new ParseException("Foreach can only be used with objects of type Array, Dictionary or String.",
node);
}
return null;
}
public object Accept(ForNode node)
{
var forStmt = node;
isInLoop++;
forStmt.Left.Visit(this);
while ((HassiumBool) (forStmt.Predicate.Visit(this)))
{
forStmt.Body.Visit(this);
if (continueLoop) continueLoop = false;
if (breakLoop)
{
breakLoop = false;
break;
}
forStmt.Right.Visit(this);
}
isInLoop--;
return null;
}
public object Accept(FuncNode node)
{
var fnode = node;
var stackFrame = new StackFrame(SymbolTable.ChildScopes[fnode.Name + "`" + fnode.Parameters.Count]);
if (CallStack.Count > 0)
{
stackFrame.Scope.Symbols.AddRange(CallStack.Peek().Scope.Symbols);
CallStack.Peek().Locals.All(x =>
{
stackFrame.Locals.Add(x.Key, x.Value);
return true;
});
}
var hfunc = new HassiumMethod(this, fnode, stackFrame, null);
SetVariable(fnode.Name + "`" + fnode.Parameters.Count, hfunc, fnode);
return hfunc;
}
public object Accept(FunctionCallNode node)
{
var call = node;
IFunction target = null;
bool dontEval = false;
switch (call.Target.ToString())
{
case "free":
dontEval = true;
break;
case "exit":
// internal interpreter functions
break;
default:
if ((!(call.Target is MemberAccessNode) &&
!HasFunction(call.Target.ToString(), call.Arguments.Children.Count, node)))
{
throw new ParseException("The function " + call.Target + " doesn't exist", node);
}
if (call.Target is MemberAccessNode)
{
var man = (MemberAccessNode) call.Target;
var targ = (HassiumObject) man.Left.Visit(this);
if (targ.Attributes.ContainsKey(man.Member + "`" + call.Arguments.Children.Count))
{
target = targ.GetAttribute(man.Member + "`" + call.Arguments.Children.Count, node.Position);
}
else if (targ.Attributes.ContainsKey(man.Member))
{
target = targ.GetAttribute(man.Member, node.Position);
}
else
{
throw new ParseException(
"The function " + man.Member + " doesn't exist for the object " + man.Left, node);
}
}
else
target = GetFunction(call.Target.ToString(), call.Arguments.Children.Count, node);
break;
}
if (HassiumInterpreter.options.Secure)
{
var forbidden = new List<string> {"system", "runtimecall", "input"};
if (forbidden.Contains(call.Target.ToString()))
{
throw new ParseException("The " + call.Target + "() function is disabled for security reasons.",
node);
}
}
if (target is InternalFunction && (target as InternalFunction).IsConstructor)
throw new ParseException("Attempt to run a constructor without the 'new' operator", node);
if (target is HassiumMethod)
{
var th = target as HassiumMethod;
if (!th.IsStatic)
{
if (call.Target is MemberAccessNode)
{
var man = (MemberAccessNode) call.Target;
if (!((HassiumObject) man.Left.Visit(this)).IsInstance)
{
throw new ParseException("Non-static method can only be used with instance of class", call);
}
}
}
}
var arguments = new HassiumObject[call.Arguments.Children.Count];
for (var x = 0; x < call.Arguments.Children.Count; x++)
{
arguments[x] = dontEval
? new HassiumString(call.Arguments.Children[x].ToString())
: (HassiumObject) call.Arguments.Children[x].Visit(this);
}
switch (call.Target.ToString())
{
case "free":
FreeVariable(arguments[0].ToString(), node);
return null;
case "exit":
exit = true;
exitcode = arguments.Length == 0 ? 0 : arguments[0].HInt().Value;
return null;
}
HassiumObject ret = target.Invoke(arguments);
if (returnFunc)
returnFunc = false;
//if (ret is HassiumArray) ret = ((Array)ret).Cast<HassiumObject>().Select((s, i) => new { s, i }).ToDictionary(x => HassiumObject.ToHassiumObject(x.i), x => HassiumObject.ToHassiumObject(x.s));
return ret;
}
public object Accept(IdentifierNode node)
{
return GetVariable(node.Identifier, node);
}
public object Accept(IfNode node)
{
var ifStmt = node;
if ((HassiumBool) (ifStmt.Predicate.Visit(this)))
{
ifStmt.Body.Visit(this);
}
else
{
ifStmt.ElseBody.Visit(this);
}
return null;
}
public object Accept(InstanceNode node)
{
var inode = node;
var fcall = (FunctionCallNode) inode.Target;
var arguments = (HassiumObject[]) fcall.Arguments.Visit(this);
HassiumObject theVar = null;
if (fcall.Target is MemberAccessNode)
{
theVar = (HassiumObject) fcall.Target.Visit(this);
}
else theVar = (HassiumObject) GetFunction(fcall.Target.ToString(), fcall.Arguments.Children.Count, node);
if (theVar is InternalFunction)
{
var iFunc = (InternalFunction) theVar;
if (iFunc.IsConstructor)
{
var ret = iFunc.Invoke(arguments);
ret.IsInstance = true;
return ret;
}
}
else if (theVar is HassiumClass)
{
var iCl = (HassiumClass) theVar;
if (iCl.Attributes.ContainsKey("new"))
{
var ctor = iCl.GetAttribute("new", fcall.Position);
ctor.Invoke(arguments);
iCl.IsInstance = true;
return iCl;
}
}
throw new ParseException("No constructor found for " + fcall.Target, node);
}
public object Accept(LambdaFuncNode node)
{
var funcNode = node;
var stackFrame = new StackFrame(SymbolTable.ChildScopes["lambda_" + funcNode.GetHashCode()]);
if (CallStack.Count > 0)
{
stackFrame.Scope.Symbols.AddRange(CallStack.Peek().Scope.Symbols);
CallStack.Peek().Locals.All(x =>
{
stackFrame.Locals.Add(x.Key, x.Value);
return true;
});
}
return new HassiumMethod(this, (FuncNode) funcNode, stackFrame, null);
}
public object Accept(MemberAccessNode node)
{
var accessor = node;
var target = (HassiumObject) accessor.Left.Visit(this);
var attr = target.GetAttribute(accessor.Member, node.Position + 1);
if (attr is InternalFunction && ((InternalFunction) attr).IsProperty)
{
return ((InternalFunction) attr).Invoke();
}
else
{
return attr;
}
}
public object Accept(MentalNode node)
{
var mnode = node;
if (!HasVariable(mnode.Name))
throw new ParseException(
"The operand of an increment or decrement operator must be a variable, property or indexer", mnode);
var oldValue = GetVariable(mnode.Name, mnode);
switch (mnode.OpType)
{
case "++":
SetVariable(mnode.Name, Convert.ToInt32((object) GetVariable(mnode.Name, mnode)) + 1, mnode);
break;
case "--":
SetVariable(mnode.Name, Convert.ToInt32((object) GetVariable(mnode.Name, mnode)) - 1, mnode);
break;
default:
throw new ParseException("Unknown operation " + mnode.OpType, mnode);
}
return mnode.IsBefore ? GetVariable(mnode.Name, mnode) : oldValue;
}
public object Accept(NumberNode node)
{
// ReSharper disable once ConvertIfStatementToReturnStatement
if (node.IsInt)
{
return new HassiumInt(Convert.ToInt32(node.Value));
}
return new HassiumDouble(node.Value);
}
public object Accept(PropertyNode node)
{
var prop = new HassiumProperty(node.Name, x => GetPropVal(node, x[0]), x => SetPropVal(node, x[1], x[0]),
node.SetNode == null);
SetVariable(node.Name, prop, node);
return prop;
}
private HassiumObject GetPropVal(PropertyNode node, HassiumObject self)
{
var funcnode = new HassiumMethod(this,
new FuncNode(node.GetNode.Position, "__getprop__" + node.Name + "`1", new List<string> {"this"},
node.GetNode.Body), SymbolTable.ChildScopes["__getprop__" + node.Name + "`1"], self);
return funcnode.Invoke();
}
private HassiumObject SetPropVal(PropertyNode node, HassiumObject value, HassiumObject self)
{
if (node.SetNode == null)
throw new ParseException("The property is read-only, it cannot be modified.", node);
var funcnode = new HassiumMethod(this,
new FuncNode(node.SetNode.Position, "__setprop__" + node.Name + "`2", new List<string> {"this", "value"},
node.SetNode.Body), SymbolTable.ChildScopes["__setprop__" + node.Name + "`2"], self);
funcnode.Invoke(value);
return null;
}
public object Accept(ReturnNode node)
{
if (isInFunction == 0) throw new ParseException("'return' cannot be used outside a function", node);
var returnStmt = node;
if (returnStmt.Value != null && !returnStmt.Value.ReturnsValue)
throw new ParseException("This node type doesn't return a value.", returnStmt.Value);
var ret = returnStmt.Value.Visit(this);
returnFunc = true;
CallStack.Peek().ReturnValue = (HassiumObject) ret;
return ret;
}
public object Accept(StatementNode node)
{
return node.Visit(this);
}
public object Accept(StringNode node)
{
return new HassiumString(node.Value);
}
public object Accept(SwitchNode node)
{
var pred = node.Predicate.Visit(this);
if (node.Body.Any(x => x.Values.Any(y => y.Visit(this).ToString() == pred.ToString())))
{
var cnode = node.Body.First(x => x.Values.Any(y => y.Visit(this).ToString() == pred.ToString()));
cnode.Visit(this);
}
else
{
if (node.DefaultBody != null)
{
node.DefaultBody.Visit(this);
}
}
return null;
}
public object Accept(ThreadNode node)
{
var threadStmt = node;
Task.Factory.StartNew(() => threadStmt.Node.Visit(this));
return null;
}
public object Accept(UseNode node)
{
if (node.IsModule)
{
string mname = node.Path.ToLower();
if (HassiumInterpreter.options.Secure)
{
var forbidden = new List<string> {"io", "net", "network", "drawing"};
if (forbidden.Contains(mname))
{
throw new ParseException(
"The module " + mname + " is cannot be imported for security reasons.", node);
}
}
switch (mname)
{
case "io":
Constants.Add("File", new HassiumFile());
Constants.Add("Directory", new HassiumDirectory());
Constants.Add("Path", new HassiumPath());
Constants.Add("IO", new HassiumIO());
Constants.Add("StreamWriter",
new InternalFunction(
x =>
new HassiumStreamWriter(x[0] is HassiumStream
? new StreamWriter(((HassiumStream) x[0]).Value)
: new StreamWriter(x[0].ToString())), 1, false, true));
Constants.Add("StreamReader",
new InternalFunction(
x =>
new HassiumStreamReader(x[0] is HassiumStream
? new StreamReader(((HassiumStream) x[0]).Value)
: new StreamReader(x[0].ToString())), 1, false, true));
Constants.Add("FileStream",
new InternalFunction(
x => new HassiumFileStream(new FileStream(x[0].ToString(), FileMode.OpenOrCreate)), 1,
false, true));
Constants.Add("BinaryWriter",
new InternalFunction(
x => new HassiumBinaryWriter(new BinaryWriter(((HassiumStream) x[0]).Value)), 1, false,
true));
Constants.Add("BinaryReader",
new InternalFunction(
x => new HassiumBinaryReader(new BinaryReader(((HassiumStream) x[0]).Value)), 1, false,
true));
break;
case "math":
Constants.Add("Math", new HassiumMath());
break;
case "debug":
Constants.Add("Debug", new HassiumDebug());
break;
case "collections":
Constants.Add("Stack",
new InternalFunction(
x =>
new HassiumStack(x.Length == 0
? new Stack<HassiumObject>()
: new Stack<HassiumObject>(x[0].HInt().Value)), new[] {0, 1}, false, true));
Constants.Add("Dictionary",
new InternalFunction(
x => new HassiumDictionary(new Dictionary<HassiumObject, HassiumObject>()), 0, false,
true));
break;
case "net":
case "network":
Constants.Add("WebClient",
new InternalFunction(x => new HassiumWebClient(new WebClient()), 0, false, true));
Constants.Add("TcpClient",
new InternalFunction(x => new HassiumTcpClient(new TcpClient()), 0, false, true));
Constants.Add("NetworkStream",
new InternalFunction(
x => new HassiumNetworkStream(new NetworkStream(((HassiumSocket) x[0]).Value)), 1, false,
true));
Constants.Add("HttpListener",
new InternalFunction(x => new HassiumHttpListener(new HttpListener()), 0, false, true));
break;
case "text":
Constants.Add("StringBuilder",
new InternalFunction(x => new HassiumStringBuilder(new StringBuilder()), 0, false, true));
Constants.Add("Encoding",
new InternalFunction(x => new HassiumEncoding(x[0].HString()), 1, false, true));
if (!HassiumInterpreter.options.Secure)
{
Constants.Add("TextWriter",
new InternalFunction(x => new HassiumTextWriter(File.CreateText(x[0].ToString())), 1,
false, true));
Constants.Add("TextReader",
new InternalFunction(x => new HassiumTextReader(File.OpenText(x[0].ToString())), 1,
false, true));
}
break;
case "drawing":
Constants.Add("Color",
new InternalFunction(x => new HassiumColor(x), new[] {1, 3, 4, 5}, false, true));
Constants.Add("Bitmap",
new InternalFunction(x => new HassiumBitmap(x), new[] {1, 2}, false, true));
Constants.Add("Image",
new InternalFunction(x => new HassiumImage(x[0].HString()), 1, false, true));
break;
default:
throw new Exception("Unknown Module: " + node.Path);
}
}
else if (node.IsLibrary)
{
foreach (KeyValuePair<string, InternalFunction> entry in GetFunctions(node.Path))
Globals.Add(entry.Key, entry.Value);
}
else
{
Interpreter inter = new Interpreter(false);
Parser.Parser hassiumParser = new Parser.Parser(new Lexer.Lexer(File.ReadAllText(node.Path)).Tokenize());
AstNode ast = hassiumParser.Parse();
inter.SymbolTable = new SemanticAnalyser(ast).Analyse();
inter.Code = ast;
inter.Execute();
if (node.Global)
{
foreach (KeyValuePair<string, HassiumObject> entry in inter.Globals)
{
if (Globals.ContainsKey(entry.Key))
Globals.Remove(entry.Key);
Globals.Add(entry.Key, entry.Value);
}
}
else
{
var modu = new HassiumModule(node.Name);
foreach (KeyValuePair<string, HassiumObject> entry in inter.Globals)
{
modu.SetAttribute(entry.Key, entry.Value);
}
SetVariable(node.Name, modu, node);
}
}
return null;
}
public object Accept(TryNode node)
{
var tryStmt = node;
try
{
tryStmt.Body.Visit(this);
}
catch
{
tryStmt.CatchBody.Visit(this);
}
finally
{
if (tryStmt.FinallyBody != null)
tryStmt.FinallyBody.Visit(this);
}
return null;
}
public object Accept(UnaryOpNode node)
{
return interpretUnaryOp(node);
}
public object Accept(UncheckedNode node)
{
unchecked
{
node.Node.Visit(this);
}
return null;
}
public object Accept(WhileNode node)
{
var whileStmt = node;
isInLoop++;
int counter = 0;
while ((HassiumBool) whileStmt.Predicate.Visit(this))
{
counter++;
whileStmt.Body.Visit(this);
if (continueLoop) continueLoop = false;
if (breakLoop)
{
breakLoop = false;
break;
}
}
if (counter == 0)
{
if (whileStmt.ElseBody != null)
whileStmt.ElseBody.Visit(this);
}
isInLoop--;
return null;
}
public object Accept(DoNode node)
{
var doStmt = node;
isInLoop++;
do
{
doStmt.DoBody.Visit(this);
if (continueLoop)
continueLoop = false;
if (breakLoop)
{
breakLoop = false;
break;
}
} while ((HassiumBool)doStmt.Predicate.Visit(this));
isInLoop--;
return null;
}
private void VisitSubnodes(AstNode node)
{
foreach (var nd in node.Children)
{
nd.Visit(this);
if (continueLoop || breakLoop || returnFunc || exit) break;
}
}
}
}
``` | Well, it's a large chunk of code so here just a few things which came to mind when skimming over it:
1. You don't have any unit tests (at least none that I could find on github). You should start writing them. I suspect it will be a PITA to do so which is good since it will highlight refactoring targets plus it will provide regression tests for when you break things while refactoring. Yes it means you'll have to invest time in it without making actual progress on features but if you'd like the project to grow and more people contributing to it you can easily put yourself into a world of pain if you don't.
2. Check all your `public`/`private` modifiers and make sure that only things which need to be `public` actually are. In large blobs like these I often find public methods or properties which aren't used anywhere outside of the class (or not even there). Anything public is a lot harder to change since it will potentially affect a lot of calling code. Things which are private can be changed around at will (as long as you don't break anything, see unit testing above).
3. There is no documentation on the public interface of the class so you are pretty much resigned to read the code if you want to use it.
4. Related to this: The public interface of this class is very broad and it's absolutely not obvious how it is meant to be used. I assume methods are meant to be called in a certain order and in certain states or otherwise things will go wrong. Also having a public dictionary called `Constants` which is apparently everything but constant seems like an oxymoron to me.
5. I tend to start refactoring these kind of things in baby steps. A good candidate seems to the be `CallStack`. Code like this:
>
>
> ```
> if (CallStack.Count > 0 &&
> (CallStack.Peek().Scope.Symbols.Contains(name) || CallStack.Any(x => x.Locals.ContainsKey(name))))
> CallStack.First(x => x.Locals.ContainsKey(name) || x.Scope.Symbols.Contains(name))
> .Locals.Remove(name);
>
> ```
>
>
makes things very hard to read and is scattered around in various places. Create a `Callstack` class, define the interface to it in terms of how the Interpreter should interact with it on the most basic level. This should clean up some code.
6. I'm not 100% sure what exactly the purpose of the `Accept` methods is and how they are related to the `interpret*` methods and how it is all related to `Execute`. So at the first glance it seems your `Interpreter` has at least two responsibilities: Turn the AST nodes into `Hassium*` nodes and execute the `Hassium*` nodes. This is at least one responsibility too much and turning the AST nodes into `Hassium*` nodes should probably be extracted.
7. Also reading a lot of code like `if (evaluated is HassiumArray || evaluated is HassiumString)` seems like a step backwards in the age of OOP. |
130259 | how to get id or position of a checkbox inside listview?
I need to update database when isChecked = true or false, but I need position...
maybe I could just do same things as in OnItemClick method?
```
@Override
public void onItemClick(AdapterView<?> parent, View itemClicked, int position, long id){
CheckBox cbx = (CheckBox)itemClicked.findViewById(R.id.cbxList);
cbx.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
if(cbx.getVisibility() == View.VISIBLE){
ContentValues cv = new ContentValues();
if(cbx.isChecked()){
cbx.setChecked(false);
int cbxID = 0;
cv.put(DB.CBX, cbxID);
mDB.updateCbx(cv, id);
Log.d(LOG, " updated with id = " + id + " and cbxID is " + cbxID);
}else{
cbx.setChecked(true);
int cbxID = 1;
cv.put(DB.CBX, cbxID);
mDB.updateCbx(cv, id);
Log.d(LOG, " updated with id = " + id + " and cbxID is " + cbxID);
}
}else{
Intent intentContactView = new Intent(this, ContactView.class);
intentContactView.putExtra("id", id);
startActivity(intentContactView);
}
}
```
The method getView() from class with SimpleCursorAdapter... same question, how to get the position or id of chosen checkbox?
```
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mLayoutInflater.inflate(R.layout.item, parent, false);
view = super.getView(position, convertView, parent);
CheckBox cbx = (CheckBox)convertView.findViewById(R.id.cbxList);
}
return view;
}
```
and my Xml file with listview's items. Here said checkboxes are invisible, but they appears, when I call them (just for understanding.
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="@dimen/margin"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="@dimen/margin"
android:layout_weight="0.5"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/margin"
android:orientation="vertical" >
<ImageView
android:id="@+id/ivPhoto"
android:layout_width="@dimen/imageWidth"
android:layout_height="@dimen/imageHeight"
android:layout_gravity="center_vertical"
android:contentDescription="@string/photoDescription"
android:src="@drawable/default_contact" />
</LinearLayout>
<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="@dimen/margin"
android:text=""
android:textSize="@dimen/textSize" />
<TextView
android:id="@+id/tvSurname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="@dimen/margin"
android:text=""
android:textSize="@dimen/textSize" />
</LinearLayout>
<CheckBox
android:id="@+id/cbxList"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="@dimen/margin"
android:layout_weight="0.2"
android:focusable="false"
android:visibility="invisible" />
</LinearLayout>
``` | You can set tag to the checkbox, and when you get the callback for the event, you can extract the tag from view provided in callback. Set the position in the tag (setTag() is the method for setting tag).
So your stuff should look something like following:
```
public View getView(int position, View convertView, ViewGroup parent)
{
//...
CheckBox cbx;
//...
cbx.setTag(position);
cbx.setOnCheckedChangeListener(checkListener);
//...
}
OnCheckedChangeListener checkListener = new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
int position = buttonView.getTag();
}
};
``` |
130448 | After countless attempts and sieving through every SO answer + google result, it baffles me that working with EXIF on iOS is so frustrating.
Below is working code with its results.
```
[[self stillImageOutput] captureStillImageAsynchronouslyFromConnection:videoConnection
completionHandler:^(CMSampleBufferRef imageSampleBuffer, NSError *error)
{
NSData *imageNSData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
CGImageSourceRef imgSource = CGImageSourceCreateWithData((__bridge_retained CFDataRef)imageNSData, NULL);
//get all the metadata in the image
NSDictionary *metadata = (__bridge NSDictionary *)CGImageSourceCopyPropertiesAtIndex(imgSource, 0, NULL);
NSLog(@"original metadata Info: %@",metadata);
//make the metadata dictionary mutable so we can add properties to it
NSMutableDictionary *metadataAsMutable = [metadata mutableCopy];
NSMutableDictionary *EXIFDictionary = [[metadataAsMutable objectForKey:(NSString *)kCGImagePropertyExifDictionary]mutableCopy];
NSMutableDictionary *GPSDictionary = [[metadataAsMutable objectForKey:(NSString *)kCGImagePropertyGPSDictionary]mutableCopy];
NSMutableDictionary *RAWDictionary = [[metadataAsMutable objectForKey:(NSString *)kCGImagePropertyRawDictionary]mutableCopy];
if(!EXIFDictionary)
EXIFDictionary = [[NSMutableDictionary dictionary] init];
if(!GPSDictionary)
GPSDictionary = [[NSMutableDictionary dictionary] init];
if(!RAWDictionary)
RAWDictionary = [[NSMutableDictionary dictionary] init];
[GPSDictionary setObject:@"camera coord Latitude"
forKey:(NSString*)kCGImagePropertyGPSLatitude];
[GPSDictionary setObject:@"camera coord Longitude"
forKey:(NSString*)kCGImagePropertyGPSLongitude];
[GPSDictionary setObject:@"camera GPS Date Stamp"
forKey:(NSString*)kCGImagePropertyGPSDateStamp];
[GPSDictionary setObject:@"camera direction (heading) in degrees"
forKey:(NSString*)kCGImagePropertyGPSImgDirection];
[GPSDictionary setObject:@"subject coord Latitude"
forKey:(NSString*)kCGImagePropertyGPSDestLatitude];
[GPSDictionary setObject:@"subject coord Longitude"
forKey:(NSString*)kCGImagePropertyGPSDestLongitude];
[EXIFDictionary setObject:@"[S.D.] kCGImagePropertyExifUserComment"
forKey:(NSString *)kCGImagePropertyExifUserComment];
[EXIFDictionary setValue:@"69 m" forKey:(NSString *)kCGImagePropertyExifSubjectDistance];
//Add the modified Data back into the image’s metadata
[metadataAsMutable setObject:EXIFDictionary forKey:(NSString *)kCGImagePropertyExifDictionary];
[metadataAsMutable setObject:GPSDictionary forKey:(NSString *)kCGImagePropertyGPSDictionary];
[metadataAsMutable setObject:RAWDictionary forKey:(NSString *)kCGImagePropertyRawDictionary];
NSLog(@"metadataAsMutable Info: %@",metadataAsMutable);
CFStringRef UTI = CGImageSourceGetType(imgSource); //this is the type of image (e.g., public.jpeg)
//this will be the data CGImageDestinationRef will write into
NSMutableData *newImageData = [NSMutableData data];
CGImageDestinationRef destination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)newImageData, UTI, 1, NULL);
if(!destination)
NSLog(@"***Could not create image destination ***");
//add the image contained in the image source to the destination, overidding the old metadata with our modified metadata
CGImageDestinationAddImageFromSource(destination, imgSource, 0, (__bridge CFDictionaryRef) metadataAsMutable);
//tell the destination to write the image data and metadata into our data object.
//It will return false if something goes wrong
BOOL success = NO;
success = CGImageDestinationFinalize(destination);
if(!success)
NSLog(@"***Could not create data from image destination ***");
CIImage *testImage = [CIImage imageWithData:newImageData];
NSDictionary *propDict = [testImage properties];
NSLog(@"Properties %@", propDict);
}];
```
Which outputs this:
```
2012-10-12 23:17:45.415 Waypointer[3120:907] original metadata Info: {
ColorModel = RGB;
DPIHeight = 72;
DPIWidth = 72;
Depth = 8;
Orientation = 1;
PixelHeight = 2448;
PixelWidth = 3264;
"{Exif}" = {
ApertureValue = "2.526069";
BrightnessValue = "-4.410617";
ColorSpace = 1;
ComponentsConfiguration = (
1,
2,
3,
0
);
ExifVersion = (
2,
2,
1
);
ExposureMode = 0;
ExposureProgram = 2;
ExposureTime = "0.06666667";
FNumber = "2.4";
Flash = 16;
FlashPixVersion = (
1,
0
);
FocalLenIn35mmFilm = 35;
FocalLength = "4.28";
ISOSpeedRatings = (
800
);
MeteringMode = 5;
PixelXDimension = 3264;
PixelYDimension = 2448;
SceneCaptureType = 0;
SensingMethod = 2;
ShutterSpeedValue = "3.906905";
SubjectArea = (
1631,
1223,
881,
881
);
WhiteBalance = 0;
};
"{TIFF}" = {
Orientation = 1;
ResolutionUnit = 2;
XResolution = 72;
YResolution = 72;
"_YCbCrPositioning" = 1;
};
}
```
And this:
```
2012-10-12 23:17:45.421 Waypointer[3120:907] metadataAsMutable Info: {
ColorModel = RGB;
DPIHeight = 72;
DPIWidth = 72;
Depth = 8;
Orientation = 1;
PixelHeight = 2448;
PixelWidth = 3264;
"{Exif}" = {
ApertureValue = "2.526069";
BrightnessValue = "-4.410617";
ColorSpace = 1;
ComponentsConfiguration = (
1,
2,
3,
0
);
ExifVersion = (
2,
2,
1
);
ExposureMode = 0;
ExposureProgram = 2;
ExposureTime = "0.06666667";
FNumber = "2.4";
Flash = 16;
FlashPixVersion = (
1,
0
);
FocalLenIn35mmFilm = 35;
FocalLength = "4.28";
ISOSpeedRatings = (
800
);
MeteringMode = 5;
PixelXDimension = 3264;
PixelYDimension = 2448;
SceneCaptureType = 0;
SensingMethod = 2;
ShutterSpeedValue = "3.906905";
SubjectArea = (
1631,
1223,
881,
881
);
SubjectDistance = "69 m";
UserComment = "[S.D.] kCGImagePropertyExifUserComment";
WhiteBalance = 0;
};
"{GPS}" = {
DateStamp = "camera GPS Date Stamp";
DestLatitude = "subject coord Latitude";
DestLongitude = "subject coord Longitude";
ImgDirection = "camera direction (heading) in degrees";
Latitude = "camera coord Latitude";
Longitude = "camera coord Longitude";
};
"{Raw}" = {
};
"{TIFF}" = {
Orientation = 1;
ResolutionUnit = 2;
XResolution = 72;
YResolution = 72;
"_YCbCrPositioning" = 1;
};
}
```
And, after it's all done, this:
```
2012-10-12 23:17:47.131 Waypointer[3120:907] Properties {
ColorModel = RGB;
DPIHeight = 72;
DPIWidth = 72;
Depth = 8;
Orientation = 1;
PixelHeight = 2448;
PixelWidth = 3264;
"{Exif}" = {
ApertureValue = "2.526069";
BrightnessValue = "-4.410617";
ColorSpace = 1;
ComponentsConfiguration = (
0,
0,
0,
1
);
ExifVersion = (
2,
2,
1
);
ExposureMode = 0;
ExposureProgram = 2;
ExposureTime = "0.06666667";
FNumber = "2.4";
Flash = 16;
FlashPixVersion = (
1,
0
);
FocalLenIn35mmFilm = 35;
FocalLength = "4.28";
ISOSpeedRatings = (
800
);
MeteringMode = 5;
PixelXDimension = 3264;
PixelYDimension = 2448;
SceneCaptureType = 0;
SensingMethod = 2;
ShutterSpeedValue = "3.906905";
SubjectArea = (
1631,
1223,
881,
881
);
UserComment = "[S.D.] kCGImagePropertyExifUserComment";
WhiteBalance = 0;
};
"{JFIF}" = {
DensityUnit = 1;
JFIFVersion = (
1,
1
);
XDensity = 72;
YDensity = 72;
};
"{TIFF}" = {
Orientation = 1;
ResolutionUnit = 2;
XResolution = 72;
YResolution = 72;
"_YCbCrPositioning" = 1;
};
}
```
As the example illustrates, you can see the image's original metaData, its modification, and then its final output.
The final output is what bothers me because no matter what I do, I cannot get my modified values to stick!
Is there some very specific format I'm missing?
Why is iOS stripping my modifications?
What do I need to do to add these extra values? They are listed in the .header and figured it should be easily accepted. | Scott, a developer at Apple, returned with my incident report and fixed the issue:
>
> The previous code above is writing **string values** for the GPS
> values - *this won't work*, they **must be NS/CFNumbers** (we extract
> a float value for EXIF).
>
>
>
I'll be filing a bug report to Apple against their documentation.
Although it took a week to get this response, I really do appreciate the support Apple provides to their developers. (thanks Scott!) **;-)**
Below is the improved code and its correct output:
```
[[self stillImageOutput] captureStillImageAsynchronouslyFromConnection:videoConnection
completionHandler:^(CMSampleBufferRef imageSampleBuffer, NSError *error)
{
NSData *imageNSData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
CGImageSourceRef imgSource = CGImageSourceCreateWithData((__bridge_retained CFDataRef)imageNSData, NULL);
//get all the metadata in the image
NSDictionary *metadata = (__bridge NSDictionary *)CGImageSourceCopyPropertiesAtIndex(imgSource, 0, NULL);
//make the metadata dictionary mutable so we can add properties to it
NSMutableDictionary *metadataAsMutable = [metadata mutableCopy];
NSMutableDictionary *EXIFDictionary = [[metadataAsMutable objectForKey:(NSString *)kCGImagePropertyExifDictionary]mutableCopy];
NSMutableDictionary *GPSDictionary = [[metadataAsMutable objectForKey:(NSString *)kCGImagePropertyGPSDictionary]mutableCopy];
NSMutableDictionary *RAWDictionary = [[metadataAsMutable objectForKey:(NSString *)kCGImagePropertyRawDictionary]mutableCopy];
if(!EXIFDictionary)
EXIFDictionary = [[NSMutableDictionary dictionary] init];
if(!GPSDictionary)
GPSDictionary = [[NSMutableDictionary dictionary] init];
if(!RAWDictionary)
RAWDictionary = [[NSMutableDictionary dictionary] init];
[GPSDictionary setObject:[NSNumber numberWithFloat:37.795]
forKey:(NSString*)kCGImagePropertyGPSLatitude];
[GPSDictionary setObject:@"N" forKey:(NSString*)kCGImagePropertyGPSLatitudeRef];
[GPSDictionary setObject:[NSNumber numberWithFloat:122.410]
forKey:(NSString*)kCGImagePropertyGPSLongitude];
[GPSDictionary setObject:@"W" forKey:(NSString*)kCGImagePropertyGPSLongitudeRef];
[GPSDictionary setObject:@"2012:10:18"
forKey:(NSString*)kCGImagePropertyGPSDateStamp];
[GPSDictionary setObject:[NSNumber numberWithFloat:300]
forKey:(NSString*)kCGImagePropertyGPSImgDirection];
[GPSDictionary setObject:[NSNumber numberWithFloat:37.795]
forKey:(NSString*)kCGImagePropertyGPSDestLatitude];
[GPSDictionary setObject:@"N" forKey:(NSString*)kCGImagePropertyGPSDestLatitudeRef];
[GPSDictionary setObject:[NSNumber numberWithFloat:122.410]
forKey:(NSString*)kCGImagePropertyGPSDestLongitude];
[GPSDictionary setObject:@"W" forKey:(NSString*)kCGImagePropertyGPSDestLongitudeRef];
[EXIFDictionary setObject:@"[S.D.] kCGImagePropertyExifUserComment"
forKey:(NSString *)kCGImagePropertyExifUserComment];
[EXIFDictionary setObject:[NSNumber numberWithFloat:69.999]
forKey:(NSString*)kCGImagePropertyExifSubjectDistance];
//Add the modified Data back into the image’s metadata
[metadataAsMutable setObject:EXIFDictionary forKey:(NSString *)kCGImagePropertyExifDictionary];
[metadataAsMutable setObject:GPSDictionary forKey:(NSString *)kCGImagePropertyGPSDictionary];
[metadataAsMutable setObject:RAWDictionary forKey:(NSString *)kCGImagePropertyRawDictionary];
CFStringRef UTI = CGImageSourceGetType(imgSource); //this is the type of image (e.g., public.jpeg)
//this will be the data CGImageDestinationRef will write into
NSMutableData *newImageData = [NSMutableData data];
CGImageDestinationRef destination = CGImageDestinationCreateWithData((__bridge CFMutableDataRef)newImageData, UTI, 1, NULL);
if(!destination)
NSLog(@"***Could not create image destination ***");
//add the image contained in the image source to the destination, overidding the old metadata with our modified metadata
CGImageDestinationAddImageFromSource(destination, imgSource, 0, (__bridge CFDictionaryRef) metadataAsMutable);
//tell the destination to write the image data and metadata into our data object.
//It will return false if something goes wrong
BOOL success = NO;
success = CGImageDestinationFinalize(destination);
if(!success)
NSLog(@"***Could not create data from image destination ***");
CIImage *testImage = [CIImage imageWithData:newImageData];
NSDictionary *propDict = [testImage properties];
NSLog(@"Final properties %@", propDict);
}];
```
Which outputs this:
```
Final properties info {
ColorModel = RGB;
DPIHeight = 72;
DPIWidth = 72;
Depth = 8;
Orientation = 6;
PixelHeight = 2448;
PixelWidth = 3264;
"{Exif}" = {
ApertureValue = "2.526069";
BrightnessValue = "0.547474";
ColorSpace = 1;
ComponentsConfiguration = (
0,
0,
0,
1
);
ExifVersion = (
2,
2,
1
);
ExposureMode = 0;
ExposureProgram = 2;
ExposureTime = "0.05";
FNumber = "2.4";
Flash = 16;
FlashPixVersion = (
1,
0
);
FocalLenIn35mmFilm = 35;
FocalLength = "4.28";
ISOSpeedRatings = (
320
);
MeteringMode = 5;
PixelXDimension = 3264;
PixelYDimension = 2448;
SceneCaptureType = 0;
SensingMethod = 2;
ShutterSpeedValue = "4.321929";
SubjectArea = (
1631,
1223,
881,
881
);
SubjectDistance = "69.999";
UserComment = "[S.D.] kCGImagePropertyExifUserComment";
WhiteBalance = 0;
};
"{GPS}" = {
DateStamp = "2012:10:18";
DestLatitude = "37.795";
DestLatitudeRef = N;
DestLongitude = "122.41";
DestLongitudeRef = W;
ImgDirection = 300;
Latitude = "37.795";
LatitudeRef = N;
Longitude = "122.41";
LongitudeRef = W;
};
"{JFIF}" = {
DensityUnit = 1;
JFIFVersion = (
1,
1
);
XDensity = 72;
YDensity = 72;
};
"{TIFF}" = {
Orientation = 6;
ResolutionUnit = 2;
XResolution = 72;
YResolution = 72;
"_YCbCrPositioning" = 1;
};
}
```
As you can see, all values are now properly embedded into the EXIF header and I've tested that this is correctly written with the JPG to the camera roll.
Enjoy! :) |
130486 | Recently i came across a question during a programming contest on codeforces. Problem tags referred that the problems could be solved by using two pointer method.
What exactly is the Two Pointer Method? | Google reports 2350 hits for "two pointer method" but the first couple pages use the phrase to refer to a variety of algorithms. It's seldom capitalized. Probably they were referring to one of several alternatives that had already been established in other discussion, literature, etc specific to the group hosting the competition. |
130710 | **This is my connection string**
```
{
"Data": {
"PhotoGalleryConnection": {
"ConnectionString": "Server=WINDOWS-B7MJR5T\\SQLEXPRESS;User Id=sa;password=allah;Database=PhotoGallery;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
}
```
**And I am facing this exception**
>
> An exception of type 'System.Data.SqlClient.SqlException' occurred in
> Microsoft.EntityFrameworkCore.dll but was not handled in user code
> Additional information: Cannot open database "PhotoGallery" requested
> by the login. The login failed.
>
>
> | It should work after You delete Trusted\_Connection=True; from connection string.
>
> If you specify either Trusted\_Connection=True; or Integrated
> Security=SSPI; or Integrated Security=true; in your connection string
> THEN (and only then) you have Windows Authentication happening. Any
> user id= setting in the connection string will be ignored. Found in here: [When using Trusted\_Connection=true and SQL Server authentication, will this effect performance?](https://stackoverflow.com/questions/1642483/when-using-trusted-connection-true-and-sql-server-authentication-will-this-effe)
>
>
> |
131026 | I am getting
```
yld: Symbol not found: _OBJC_CLASS_$_UIUserNotificationSettings
```
and here's the function that is causing the error ***when the application is running on an iOS7 device*** and without even calling the function at all in the code.
>
>
> ```
> func reigsterForRemoteUserNotifications(notificationTypes: UIUserNotificationType, categories: NSSet) {
> let userNotificationSettings = UIUserNotificationSettings(forTypes: notificationTypes, categories: categories)
> (UIApplication.sharedApplication()).registerUserNotificationSettings(userNotificationSettings)
> UIApplication.sharedApplication().registerForRemoteNotifications()
> }
>
> ```
>
>
I don't want this method to be accessible at all when running on an iOS7 device. I do not want a select check inside of it because that means the method is available for use to begin with.
What I want is a build config parameter to check the version :
I can't figure out a way to write a swift equivalent preprocessor macro to check for the correct iOS version and neglect the new and undeclared iOS 8 library functions.
```
#if giOS8OrGreater
// declare the functions that are iOS 8 specific
#else
// declare the functions that are iOS 7 specific
#endif
```
In the documentation apple is suggesting functions and generics to substitute for complex macros but in this case I need a build config precompile check to avoid processing undeclared functions. Any suggestions. | **Update:** This is fixed in Xcode 6 beta 6 (build 6A280e)
---
~~Here's a (perhaps not so great) workaround: explicitly link to UIKit weakly (I know that `import` statements are supposed to link to frameworks already, but we do it explicitly anyway).~~
* Click on the project in Xcode
* select the target in the drop down at the top left
* go to General tab
* scroll down to Linked Frameworks and Libraries
* add UIKit.framework
* change Status from Required to Optional
It may cause all of UIKit to be weakly linked, which may affect performance. Not sure.
In Objective-C, even with Required, the compiler automatically weak-linked the symbols whose availability is above the deployment target, and leave the others strongly linked. I don't know why this doesn't work with Swift. |
131276 | I'm trying to use Android Annotations and dynamically add layout components when my **createNewRow** button is clicked. The app runs and displays the default rows defined in **activity\_main.xml** and, after clicking **createNewButton** I see children attached to my **dynamicTable** in the debugger but the new children are not displayed. Here is my main activity XML:
**activity\_main.xml**
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/inflateLayout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="net.richardriley.inflate.app.MainActivity">
<Button
android:id="@+id/createNewRow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/newRowButton"/>
<TableLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/dynamicTable">
<TableRow>
<TextView
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</TableRow>
</TableLayout>
</LinearLayout>
```
So simply a linear layout with a button and then a table container. Clicking **createNewRow** should add a new **InflatedRow**. Here is the XML for the row I want to dynamically add:
**inflatedrow.xml**
```
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >
<TextView
android:id="@+id/inflatedRowTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/inflatedRowLabel"/>
<Button
android:id="@+id/inflatedRowButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/defaultNewRowText"
/>
</merge>
```
Using AA my subclass for a tableRow is
**InflatedRow.java**
```
package net.richardriley.inflate.app;
import android.content.Context;
import android.widget.Button;
import android.widget.TableRow;
import android.widget.TextView;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById;
/**
* inflate : Created by rgr on 20/03/14.
*/
@EViewGroup(R.layout.inflatedrow)
public class InflatedRow extends TableRow {
@ViewById
Button inflatedRowButton;
@ViewById
TextView inflatedRowTextView;
public InflatedRow(Context context) {
super(context);
}
}
```
and finally my main activity java itself:
**MainActivity.java**
```
package net.richardriley.inflate.app;
import android.support.v7.app.ActionBarActivity;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import org.androidannotations.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static ch.qos.logback.classic.android.BasicLogcatConfigurator.configureDefaultContext;
@OptionsMenu(R.menu.main)
@EActivity(R.layout.activity_main)
public class MainActivity extends ActionBarActivity {
static {
configureDefaultContext();
log = LoggerFactory.getLogger(MainActivity.class);
}
@ViewById
LinearLayout inflateLayout;
@ViewById
TableLayout dynamicTable;
public MainActivity() {
}
protected static Logger log;
@Click
void createNewRow() {
log.info("clicked");
InflatedRow_ inflatedRow=new InflatedRow_(this);
dynamicTable.addView(inflatedRow,0);
/*LayoutInflater layoutInflater= (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.inflatedrow,null);
dynamicTable.addView(view);*/
}
@OptionsItem
void openSettingsSelected(){
log.info("Hello");
}
}
```
In **createNewRow** if I use the inflater service directly it works.
What am I missing?
many thanks. | Don't use the annotated class when you're inflating the view and make sure you're calling the build method that inflates it.
```
@Click
void createNewRow() {
log.info("clicked");
InflatedRow inflatedRow = new InflatedRow_.build(this);
dynamicTable.addView(inflatedRow,0);
}
``` |
132041 | I have a class that I would like to map to a single table in two different ways, for privacy reasons. Let's say the class looks like this:
```
class Person
{
public int ID { get; set; }
public string Name { get; set; }
// ... many other properties omitted ...
}
```
And the corresponding database table looks like this:
```
create table Person
(
ID int not null,
RealName nvarchar(512) not null,
FakeName nvarchar(512) not null,
-- many other columns omitted
)
```
The two mappings I need are:
* From **Name** property to **RealName** column
* From **Name** property to **FakeName** column
All other properties should be mapped the same in both cases. I strongly prefer not to have to repeat the mappings for these other properties.
I have tried several different approaches with no luck. Using **<union-subclass>** to isolate the different mappings fails with this error: *DuplicateMappingException: Duplicate table mapping Person*. I could create two distinct database views, and map to them separately in order to avoid the duplicate table mapping error, but that is not preferable.
Using an **"entity-name"** attribute to specify the mappings is tempting, but is poorly documented and seems to have some major drawbacks: a) it requires me to repeat all the other mappings for both entities, and b) it is not compatible with <many-to-one> relationships from other classes that refer to the Person class.
Is there a good way to do this that I am missing? | Thanks for the data sample.
You need to:
* read each paragraph/line
* split the line by whitespace to extract each tagged word, e.g. `Summerdale/np`
* split the word by `/` to see if it is tagged `np`
* if so, add the other half of the split (the actual word) to your noun list
So something like the following (based on *Bogdan*'s answer, thanks!)
```
def noun(word):
nouns = []
for word in sentence.split():
word, tag = word.split('/')
if (tag.lower() == 'np'):
nouns.append(word);
return nouns
if __name__ == '__main__':
nouns = []
with open('tesu.txt', 'r') as file_p:
for sentence in file_p.read().split('\n\n'):
result = noun(sentence)
if result:
nouns.extend(result)
print nouns
```
which for your example data, produces:
```
['Summerdale', 'Bellows', 'Parsons', 'Alan', 'Clements']
```
**Update**: In fact, you can shorten the whole thing down to this:
```
nouns = []
with open('tesu.txt', 'r') as file_p:
for word in file_p.read().split():
word, tag = word.split('/')
if (tag.lower() == 'np'):
nouns.append(word)
print nouns
```
if you don't care which paragraph the nouns come from.
You could also get rid of the `.lower()` if the tags are always lowercase as they are in your example. |
132176 | Is it possible? I mean
```
Select * from tbl limit 100;
```
I want to replace with a query like
```
Select * from tbl WHERE ...some_condition...
``` | You could use `row_number()` for that:
```
select *
from (
select row_number() over () as rn
, *
from YourTable
) as SubQueryAlias
where rn <= 100
```
If you have a specific ordering in mind, you can add an `order by` clause:
```
select row_number() over (order by date_column) as rn
``` |
132329 | I'm trying to use jQuery to detect the orientation of a number of images. Once detected, I want to add a class to indicate this i.e `.landscape`.
The code below seems to only be assessing the first image it comes across, and then applying that to all subsequent images. For example, if the first image is landscape, this will be applied to all images including portrait or square image.
Am I misusing the `.each()` statement?
Thank you.
**HTML**
```
<div class="carousel-cell">
<img src="domain.com" data-width="100" data-height="200" />
</div>
<div class="carousel-cell">
<img src="domain.com" data-width="200" data-height="100" />
</div>
<div class="carousel-cell">
<img src="domain.com" data-width="100" data-height="100" />
</div>
```
**JQUERY**
```
// Detect image orientation
$('.carousel-cell').each(function () {
"use strict";
var img = $('img');
if (img.attr('data-width') > img.attr('data-height')){
// Landscape
img.removeClass().addClass('landscape');
} else if (img.attr('data-width') < img.attr('data-height')){
// Portrait
img.removeClass().addClass('portrait');
} else {
// Equal (Square)
img.removeClass().addClass('square');
}
});
``` | In each loop, you're selecting `$("img")`, which is *every `<img>` on the page*.
You need to limit your search to find the `img` within the current element, using `$(this).find("img")` instead.
```js
// Detect image orientation
$('.carousel-cell').each(function() {
"use strict";
var $img = $(this).find('img');
var w = parseInt($img.attr("data-width"));
var h = parseInt($img.attr("data-height"));
$img.removeClass();
if (w > h) {
$img.addClass('landscape');
} else if (w < h) {
$img.addClass('portrait');
} else {
$img.addClass('square');
}
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span><strong>Right click on image > Inspect Element</strong> to see classes.</span>
<div class="carousel-cell">
<img src="domain.com" data-width="100" data-height="200" />
</div>
<div class="carousel-cell">
<img src="domain.com" data-width="200" data-height="100" />
</div>
<div class="carousel-cell">
<img src="domain.com" data-width="100" data-height="100" />
</div>
```
**EDIT:** Per your comment about the weird behavior, I suspect it's simply because you're not parsing the width and height as integers, and as such, the `>` and `<` comparisons will be done *alphabetically*. For example, `"1000"` would be *less than* `"800"`, because `"1" < "8"`. I've added `parseInt()` to resolve this. |
132504 | I have used the CAM::PDF module to read the text content from PDF file. In a directory I am having list of PDF files, so i have used the code like below to read the text content, which is not giving me the text in $text variable.
```
my $Filepath = "E:/test/";
opendir (DIR, $Filepath);
while (my $filename = readdir(DIR))
{
next if ($filename =~ m/^\./);
$filename = $Filepath.$filename;
my $pdf = CAM::PDF->new($filename);
my $text = $pdf->getPageText(1);
}
```
But if I pass the filename directly into the CAM::PDF, then it is working. Like below code
`my $pdf = CAM::PDF->new("E:/test/test.pdf");
print $pdf->numPages(), " pages\n\n";
my $text = $pdf->getPageText(1);`
But my requirement is toread the PDF files one by one from the directory.
Please help me in this. | To answer my own question, achieved with a trial and error:
```
$scope.$apply(function() {
$location.path('/home');
$window.location.reload();
});
```
This will go to /home (default) and reload everything, thus creating new service, module, controllers etc. If there is a better way of doing it (if I change default path to /blah in my module, this won't pick it up and thus I will have to edit this code too), let me know :) |
132604 | I have a problem with very simple `UIView` animation:
```
- (void)showView:(CGFloat)delay
{
[UIView animateWithDuration:1.0 delay:delay options:0 animations:^{
// self.alpha = 0.5; // Works OK with delay
self.frame = CGRectMake(100, 100, 100, 30); // delay is ignored
} completion:nil];
}
```
`delay` could be set to `1000` and still view is animated immediately. But somehow it works fine with `alpha` (without setting `frame`). | The frame is probably being set for you, perhaps by layout being performed by the superview, or this view itself. You haven't said how you're adding this view or what it does so its difficult to give specific advice, but in general terms:
* Don't let a view be in control of its own frame - this is the superview's or view controllers responsibility. A view can have a preferred size, but the rest is outside.
* it's usually better to animate bounds and / or centre instead of frame, particularly if you're ignoring the first point.
* For presentation type animations, it may be better to animate the transform instead - either translation or scale, depending what your animation is. |
133134 | The code below serves to change connection string in App.config at runtime, I found it [here](http://www.c-sharpcorner.com/uploadfile/1a81c5/configuring-connection-string-in-app-config-file-during-runt/?login=true&user=66f1ec) but this code did not work for me on Visual Studio 2010 and SQL Server 2008, I could not open the connection to the Northwind database.
```
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace MyNameSpace
{
public partial class FrmConnectionTest : Form
{
public FrmConnectionTest()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//Constructing connection string from the inputs
StringBuilder Con = new StringBuilder("Data Source=");
Con.Append(TxtServer.Text);
Con.Append(";Initial Catalog=");
Con.Append(TxtDatabase.Text);
Con.Append(";Integrated Security=SSPI;");
string strCon = Con.ToString();
updateConfigFile(strCon);
//Create new sql connection
SqlConnection Db = new SqlConnection();
//to refresh connection string each time else it will use previous connection string
ConfigurationManager.RefreshSection("connectionStrings");
Db.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ToString();
//To check new connection string is working or not
SqlDataAdapter da = new SqlDataAdapter("select * from employee");
DataTable dt = new DataTable();
da.Fill(dt);
CmbTestValue.DataSource = dt;
CmbTestValue.DisplayMember = "EmployeeID";
}
catch (Exception E)
{
MessageBox.Show(ConfigurationManager.ConnectionStrings["con"].ToString() + ".This is invalid connection", "Incorrect server/Database");
}
}
public void updateConfigFile(string con)
{
//updating config file
XmlDocument XmlDoc = new XmlDocument();
//Loading the Config file
XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
foreach (XmlElement xElement in XmlDoc.DocumentElement)
{
if (xElement.Name == "connectionStrings")
{
//setting the coonection string
xElement.FirstChild.Attributes[2].Value = con;
}
}
//writing the connection string in config file
XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
}
}
```
Using Visual Studio 2010 and SQL Server2008, I got 2 errors for the next line:
```
SqlDataAdapter da = new SqlDataAdapter("select * from employee");
```
* Error 1 The best overloaded method match for 'System.Data.SqlClient.SqlDataAdapter.SqlDataAdapter(System.Data.SqlClient.SqlCommand)' has some invalid arguments
* Error 2 Argument 1: cannot convert from 'string' to 'System.Data.SqlClient.SqlCommand'
Is there any solution to this issue? Thank you. | The error is telling you that you are passing incorrect parameters to your [SqlDataAdapter](http://msdn.microsoft.com/en-us/library/kx703tc9.aspx). I think the proper call would be:
```
SqlDataAdapter da = new SqlDataAdapter("select * from employee", Db);
```
**Edit**
It looks like you're creating your connection string from within your program, saving it to your config file, then reading it out of our config file right before you create your SqlDataAdapter. So, when you debug this line:
```
Db.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ToString();
```
Double check that `Db.ConnectionString` actually contains a connection string.
The other thing to do is open up your SQL Server Management Studio and confirm you can connect to the Northwind database from there. Including/alternatively, in Visual Studio, open your "Server Explorer" window and confirm you can create a Data Connection to Northwind by clicking Add Connection and then setting the connection property window to your server and dropping down the combobox to see if it populates with your databases:
![enter image description here](https://i.stack.imgur.com/5sMdK.jpg) |