I wanna create a function that replaces a specific part of a string sentence "2.x^56+5.x-2.x^3+x^4+2" and I had a problem with the while loop, I used multiple condition in the while loop but it still working even when the condition is match,
fun replacePow() {
while (newString.contains('^')) {
for (i in 0 until newString.lastIndex) {
if (newString[i] == '^') {
m = i
while (newString[m] != '.' || newString[m] != '+' || newString[m]!= '-' ) {
m -= 1
}
if (newString[m] == '.' || newString[m] != '+' || newString[m]!= '-') {
previousLim = m
}
o = i
while (newString[o] != '+' || newString[o]!= '-') {
o += 1
}
if (newString[o] == '+'|| newString[o]== '-') {
nextLim = o
}
newString = newString.replaceRange(m + 1, o, powred[r].toString())
r += 1
}
if (i == newString.lastIndex){
break
}
}
}
println(newString)
}
if there is a better way to write this code just write it in the comment, And thank you anyway
Related
In the Fizz-Buzz problem, we replace a number multiple of 3 with the word fizz and a number divisible by 5 with the word buzz. If a number is divisible by both three and five, we replace it with the word"FizzBuzz." in a counting incremental loop.
But my code is not working properly. Please take a look and let me know what I am doing wrong.
for (i in 1..100){
if ( i%5 == 0 || i%3 == 0) {
println("FizzBuzz")}
else if(i%5 == 0) {
println("Buzz")}
else if(i%3 == 0){
println("Fizz")}
else {
println(i)
}
}
You are using || instead of &&.
Replace:
if (i%5 == 0 || i%3 == 0) {
println("FizzBuzz")
}
With:
if (i%5 == 0 && i%3 == 0) {
println("FizzBuzz")
}
Or with:
if (i%15 == 0) {
println("FizzBuzz")
}
The more elegant solution is:
fun fizzBuzz(currentNumber: Int) = when {
currentNumber % 15 == 0 -> "FizzBuzz"
currentNumber % 3 == 0 -> "Fizz"
currentNumber % 5 == 0 -> "Buzz"
else -> "$currentNumber"
}
for (currentNumber in 1..100) {
print(fizzBuzz(currentNumber))
}
I have this code:
if ((oldTest != null) && (oldTest.snapshotUrl != null)) {
val startPos = oldTest.snapshotUrl!!.lastIndexOf("_") + 1
}
Is there a way in Kotlin to shorten this? I don't believe it's necessary to check to see if oldTest.snapshotUrl is null. Unfortunately this does not work:
if (oldTest != null) {
val startPos = oldTest.snapshotUrl?.lastIndexOf("_") + 1
}
oldTest?.snapshotUrl?.let {
val startPos = it.lastIndexOf("_") + 1
}
See https://kotlinlang.org/docs/reference/idioms.html#execute-if-not-null
Or, if snapshotUrl is not nullable
oldTest?.let {
val startPos = it.snapshotUrl.lastIndexOf("_") + 1
}
I am implementing a virtual console for my game and I am piping Key up events thro an event pipe (Observable Subject) and handling them on the virtual console side with
public void ReceiveInput (Event e)
{
Debug.Log ("ReceiveInput: " + e.ToString ());
if (e.keyCode == KeyCode.Backspace) {
if (ConsoleInputLine.LineText.Length > 2)
ConsoleInputLine.RemoveLastChar ();
return;
}
if (e.keyCode == KeyCode.Return || e.keyCode == KeyCode.KeypadEnter) {
ConsoleInputLine.LineText = "$ ";
return;
}
var chr = e.keyCode.ToString ();
if (e.capsLock || e.shift)
chr = chr.ToUpper ();
else
chr = chr.ToLower ();
ConsoleInputLine.AppendText ("" + chr);
}
While this works for simple A-Z and a-z letters, when you get to the numbers and other characters I will get the raw key name, such as "Alpha1" for the horizontal "1" key above the "Q" key, "Alpha2" for the "2" above "W", etc.
Is there a way to easily get the "rendered" text out of the key events without building a switch of all the possible keycode results?
PS: I forgot to mention that, shift+Alpha1 is "!" in US Querty, shift+Alpha2 is "#", etc, but it will differ in keyboards of different countries and its not feasible to make switch statements for every keyboard in the world.
This is not the correct answer!!!
Leaving it here in the spirit of assisting further research or get someone out of a jam.
For US Querty only keyboards, this works for now, until someone replies with a proper answer :
public static char ToChar (this Event e)
{
var key = e.keyCode;
char c = '\0';
if ((key >= KeyCode.A) && (key <= KeyCode.Z))
return (char)((int)((e.shift || e.capsLock) ? 'A' : 'a') + (int)(key - KeyCode.A));
if ((key >= KeyCode.Alpha0) && (key <= KeyCode.Alpha9)) {
if (e.shift) {
var specials = new char[] {'!', '#', '#', '$', '%', '^', '&', '*', '(', ')'};
return specials [(int)(key - KeyCode.Alpha0)];
}
return (char)((int)'0' + (int)(key - KeyCode.Alpha0));
}
if (key == KeyCode.Space)
return ' ';
if (key == KeyCode.Quote)
return (e.shift) ? '"' : '\'';
if (key == KeyCode.LeftBracket)
return (e.shift) ? '{' : '[';
if (key == KeyCode.RightBracket)
return (e.shift) ? '}' : ']';
if (key == KeyCode.BackQuote)
return (e.shift) ? '~' : '`';
if (key == KeyCode.Backslash)
return (e.shift) ? '|' : '\\';
if (key == KeyCode.Equals)
return (e.shift) ? '+' : '=';
if (key == KeyCode.Minus)
return (e.shift) ? '_' : '-';
if (key == KeyCode.Semicolon)
return (e.shift) ? ':' : ';';
if (key == KeyCode.Comma)
return (e.shift) ? '<' : ',';
if (key == KeyCode.Period)
return (e.shift) ? '>' : '.';
if (key == KeyCode.Slash)
return (e.shift) ? '?' : '/';
// implement more
return c;
}
I have catalog price rules for some categories. In frontend, in category.tpl, I have to notify if there are special prices bound to that specific category or some of its parents.
For now, I'm building a function on the controller that finds it with a query. I was wandering if there was some shortcut for doing this.
I wrote a function (a CategoryController method) to solve my problem and I share:
public function get_category_promo(){
//get the active country, since promo are also country-based
if($this->context->customer->isLogged()){
$current_country = Customer::getCurrentCountry($this->context->customer->id);
} else {
$current_country = $this->context->country->id;
}
$db = Db::getInstance();
$sql = '
SELECT
truncate(`reduction`,0) as reduction,
`reduction_type`,
`from`,
`to`,
`type` as category_type,
`value` as id_category,
`id_parent` as category_parent,
`level_depth` as depth
FROM
`'._DB_PREFIX_.'specific_price_rule_condition` rule_condition
INNER JOIN
`'._DB_PREFIX_.'specific_price_rule_condition_group` rule_group
on rule_condition.`id_specific_price_rule_condition_group` = rule_group.`id_specific_price_rule_condition_group`
INNER JOIN
`'._DB_PREFIX_.'specific_price_rule` price_rule
on price_rule.`id_specific_price_rule` = rule_group.`id_specific_price_rule`
INNER JOIN
`'._DB_PREFIX_.'category` category
on rule_condition.`value` = category.`id_category`
WHERE rule_condition.`type` = "category"';
$parents = $this->category->getParentsCategories();
array_shift($parents);//first is == this->category so I shift it out
$sql_aux = ' and (rule_condition.`value` = ' . $this->category->id_category;
foreach($parents as $parent){
$sql_aux .= ' or rule_condition.`value` = ' . $parent["id_category"];
}
$sql_aux .= ')';
$sql_aux .= ' and price_rule.`id_country` = ' . $current_country;
$sql_aux .= ' order by level_depth desc';
$sql .= $sql_aux;
$promo_data = $db->executeS($sql);
$promo_data = count($promo_data) > 0 ? $promo_data : null;
if(!$promo_data) return false;//stop
function validate_date($promo){
//if there are no dates
if((int)$promo['to'] == 0 && (int)$promo['from'] == 0) return true;
//if there is end promo date
if((int)$promo['to'] != 0){
$to = new DateTime($promo['to']);
//...and is still valid
if($to >= new DateTime('NOW')) return true;
}
}//end validate
//refine query results
$filtered = array_values(array_filter($promo_data,'validate_date'));
$promo_data = $filtered[0];//if there are more than one promo on the same category, the promo on the higher depth is used form the system, so I need only that promo
//promo without dates. Only refine to/from to better use in smarty
if((int)$promo_data['to'] == 0 && (int)$promo_data['from'] == 0){
$promo_data['to'] = 0;
$promo_data['from'] = 0;
$this->context->smarty->assign('promo_data', $promo_data);
return true;
}
if((int)$promo_data['to'] != 0){//promo ha send date
$to = new DateTime($promo_data['to']);
if($to >= new DateTime('NOW')){
$promo_data['to'] = $to->format('d-m-Y');
} else {
return false;//not a valid date
}
}
if((int)$promo_data['from'] != 0){
$from = new DateTime($promo_data['from']);
$promo_data['from'] = $from->format('d-m-Y');
} else {
$promo_data['from'] = 0;
}
$this->context->smarty->assign('promo_data', $promo_data);
}//end get_category_promo
i How to use queryover (Join) for same table...example
if (!string.IsNullOrEmpty(ufResidencia) ||
!string.IsNullOrEmpty(cidadeResidencia))
{
EnderecoProspect endPros = null;
TipoEndereco tipoEnd = null;
query
.JoinQueryOver<EnderecoProspect>(x => x.Enderecos,()=> endPros)
.And(()=> endPros.Uf ==ufResidencia)
.JoinQueryOver<TipoEndereco>(x => x.TipoEndereco,()=> tipoEnd)
.And(()=> tipoEnd.Descricao != "Fazenda");
}
if (!string.IsNullOrEmpty(ufFazenda) ||
!string.IsNullOrEmpty(cidadeFazenda))
{
EnderecoProspect endPros1 = null;
TipoEndereco tipoEnd1 = null;
query
.JoinQueryOver<EnderecoProspect>(x => x.Enderecos,()=> endPros1)
.And(()=> endPros1.Uf ==ufFazenda)
.JoinQueryOver<TipoEndereco>(x => x.TipoEndereco,()=> tipoEnd1)
.And(()=> tipoEnd1.Descricao == "Fazenda");
}
When I try to run I get the message that the path is duplicated. Im using alias correct? what problem? havy ideal? exception is "duplicate association path"
I managed to solve with LINQ to NHibernate ... there is the example for all ...
var q =
from c in Context.Query<Prospect>()
join o in Context.Query<EnderecoProspect>() on c.Identificacao equals o.Prospect.Identificacao
join e in Context.Query<TipoEndereco>() on o.TipoEndereco.Identificacao equals e.Identificacao
join a in Context.Query<EnderecoProspect>() on c.Identificacao equals a.Prospect.Identificacao
join b in Context.Query<TipoEndereco>() on a.TipoEndereco.Identificacao equals b.Identificacao
where (
(
(o.Uf == ufFazenda || ufFazenda == null) &&
(o.Cidade == cidadeFazenda || cidadeFazenda == null)
) && e.Descricao == "Fazenda"
)
&&
(
(
(a.Uf == ufResidencia || ufResidencia == null) &&
(a.Cidade == cidadeResidencia || cidadeResidencia == null)
) && b.Descricao != "Fazenda"
)
Now I can sleep a little more until ...ehehehe...see you