text:
Q: Convert SMTP Client Mail message to HTML I have an issue with an mvc4 application in witch i would like to send a generated html page created with HTML + C#. The problem is that when i recieved the email i see my c# code like the exemple bellow:
Recieved Email
But in the mail preview i can see the correct values like this:
Mail Preview
So this is my EmailTemplate method:
<pre>
 public static async Task<string> EMailTemplate (string template)
        {
            var templateFilePath =HostingEnvironment.MapPath("~/Views/Home/") + template + ".cshtml";
            StreamReader objstreamreaderfile = new StreamReader(templateFilePath);
            var body = await objstreamreaderfile.ReadToEndAsync();
            objstreamreaderfile.Close();
            return body;

        }
</pre>

Please if you have any idea how to convert my template to Html without inclouding my C# code.
Thanks,

A: Use Pure Html template (Not a cshtml view) with Inline CSS and Absolute image URIs for email body and fill it text templates. See the below image.

In the above image, field with ##...## are text templates.
Now read this HTML template as a string and replace ##...## fields by some dynamic information using the C# code (Actually any language code). You can use string.Replace() method to replace these fields by actual values. I have already used this method and it is working fine. I hope this will help you too.


text:
Q: randomly splice values into array I have an array "A" of scrambled, randomly generated ASCII characters... and a message "M". I want to insert the characters of message M into array A such that the order of M's characters are intact... but randomly distributed throughout array A.
Original array: zH$@%@$#@$@^^#@(%*$@^&@!$^%&
Sample output: zH$@%@^t$#@$@^^h#@(%*$@^&@i!$^%&s, etc...
                    var randomChars = [];
                    for(var i=33;i<127;++i) {
                        var letter = document.createElement('span');
                        letter.innerHTML = String.fromCharCode(i);
                        randomChars.push(letter);
                    }

                    var message = "this is a message";
                    var rand = 0;
                    for (var i = 0; i < message.split("").length; i++) {
                        rand = Math.floor((Math.random() * randomChars.length) + rand);
                        var letters = document.createElement('span');
                        letters.innerHTML = message.split("")[i];
                        letters.setAttribute("hidden","");
                        randomChars.splice(rand, 0, letters);
                    }

Fiddle: https://jsfiddle.net/0ftm2srz/1/

A: Use the previous random index as the minimum (non inclusive) of your next randomly generated index. Start at zero.
You could end up with some barely scrambled stuff, though. (!@#!$!@$#!@#this) But it's random.
EDIT A better way would be to generate a message.length amount of unique random indices, sort them in ascending, and then insert characters from message at those spots in the scrambled array.
http://jsbin.com/kuzepujabo/1/edit?js,console

A:

var o = {
   array: "zH$@%@$#@$@^^#@(%*$@^&@!$^%&".split(''),
   msg: "this is a message",
   randomMsgIndex: function () { return Math.floor(Math.random() * this.msg.length); },
   randomMsgChar: function () { return this.msg[this.randomMsgIndex()]; },
   //resultingArray: [],
   randomArrayIndex: function () { return Math.floor(Math.random() * this.array.length); }
}

for(var i = 0; i < o.msg.length; i++) {
  o.array.splice(o.randomArrayIndex(), 0, o.randomMsgChar());
}

console.log(o.array);

I have come up with this - but I assume it is still not what you want - you probably want something that keeps track of which message chars were already added - so not to add them twice - and make sure the entire message (all its characters) were added to the array.
Version 2 with the feature described above:

var o = {
   array: "zH$@%@$#@$@^^#@(%*$@^&@!$^%&".split(''),
   msg: "this is a message",
   msgArray: function () { this.msg.split(''); },
   randomMsgIndex: function () { return Math.floor(Math.random() * this.msg.length); },
   randomMsgChar: function (i) { return this.msg[i]; },
   //resultingArray: [],
   randomArrayIndex: function () { return Math.floor(Math.random() * this.array.length); },
   stripStr: function (indexToSkip, originalStr) {
    var result = "";
    for (var i = 0; i < originalStr.length; i++)
     if (indexToSkip != i)
      result += originalStr[i];

    return result;
   }
}

for(var i = 0; i < o.msg.length; i++) {
  var msgRandomIndex = o.randomMsgIndex();
  o.array.splice(o.randomArrayIndex(), 0, o.randomMsgChar(msgRandomIndex));
  o.msg = o.stripStr(msgRandomIndex, o.msg);
}

console.log(o.array);

I think it it is still not a 100%, but moving towards the "optimized" solution :-)

redpajama_set_name: RedPajamaStackExchange


text:
Q: sdef command not found - OSX 10.8 I'm trying to follow the instructions here:
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ScriptingBridgeConcepts/UsingScriptingBridge/UsingScriptingBridge.html#//apple_ref/doc/uid/TP40006104-CH4-SW1
Whenever I try to use the "sdef" command I'm getting a "command not found" error. This worked fine under 10.7. I'm trying to use it under 10.8 and it doesn't work anymore.
Was the sdef command removed in 10.8? What should I use instead?

A: Try xcrun sdef; that'll use the copy of sdef inside the Xcode application bundle.  Most developer tools have been moved into the bundle in recent Xcode versions.  You can also try installing the command-line tools from inside Xcode's preferences.


text:
Q: Script Google Sheets error because cell is empty I tried to take a code and adapt it to my needs but without success because I am a novice in scripting.
This code allows to generate an image of a Google Maps with markers for each address and a line that connects them.
At first this code was for 2 addresses that we had to indicate in the code and the generated image was sent by email.
So I rewrote the code (my first one alone) to plot and mark the points of 6 addresses and then have the generated image pasted into a cell of my sheet.
The problem I have is that I get the error "Exception: Invalid argument: address" when at least one of the cells containing the addresses does not contain a value (so the value is an address). I need to add something after the .getValue() function but I can't.
I know that the answer to this question may seem simple to the advanced script users, but also that this code could be useful to others.
Thank you for your insight and indulgence.
My Sheets:
https://docs.google.com/spreadsheets/d/1eZUlQK3-4WZmhQAIw5BTLsKkbTUheCTsdKEhdG0k87E/edit#gid=1047347094
My Sript:
function onOpen() {
  SpreadsheetApp.getUi().createMenu('⇩ M E N U ⇩')
    .addItem(' Générer les Cartes', 'myFunction')
    .addToUi();
  myFunction()
}

function myFunction() {
  var sheet = SpreadsheetApp.getActive();
  var address1 = sheet.getRange('K121').getValue();
  var address2 = sheet.getRange('K122').getValue();
  var address3 = sheet.getRange('K123').getValue();
  var address4 = sheet.getRange('K124').getValue();
  var address5 = sheet.getRange('K125').getValue();
  var address6 = sheet.getRange('K126').getValue();

  var map = Maps.newStaticMap().setLanguage('fr')
  .setSize(846,479)
  .setMapType(Maps.StaticMap.Type.HYBRID)
  .setMarkerStyle(Maps.StaticMap.MarkerSize.MID, Maps.StaticMap.Color.GREEN,'1')
  .addMarker(address1)
  .setMarkerStyle(Maps.StaticMap.MarkerSize.MID, Maps.StaticMap.Color.BLUE,'2')
  .addMarker(address2)
  .setMarkerStyle(Maps.StaticMap.MarkerSize.MID, Maps.StaticMap.Color.BLUE,'3')
  .addMarker(address3)
  .setMarkerStyle(Maps.StaticMap.MarkerSize.MID, Maps.StaticMap.Color.BLUE,'4')
  .addMarker(address4)
  .setMarkerStyle(Maps.StaticMap.MarkerSize.MID, Maps.StaticMap.Color.BLUE,'5')
  .addMarker(address5)
  .setMarkerStyle(Maps.StaticMap.MarkerSize.MID, Maps.StaticMap.Color.RED,'6')
  .addMarker(address6)
  .beginPath()
  .addAddress(address1)
  .addAddress(address2)
  .addAddress(address3)
  .addAddress(address4)
  .addAddress(address5)
  .addAddress(address6)
  .endPath()
  .getBlob()
  sheet.insertImage(map,5,15)
}

A: This will loop through all your addresses and check whether they are empty or not and add to the map only the ones with a non empty address:
function onOpen() {
  SpreadsheetApp.getUi().createMenu('⇩ M E N U ⇩')
    .addItem(' Générer les Cartes', 'myFunction')
    .addToUi();
  myFunction()
}

function myFunction() {
  var spreadsheet = SpreadsheetApp.getActive();
  var sheet = spreadsheet.getSheetByName('AVRIL 22');
  var addresses = sheet.getRange('K121:K126').getValues().flat();
  var colors = [ Maps.StaticMap.Color.GREEN,Maps.StaticMap.Color.BLUE,
                 Maps.StaticMap.Color.BLUE,Maps.StaticMap.Color.BLUE,
                 Maps.StaticMap.Color.BLUE,Maps.StaticMap.Color.RED];

  var map = Maps.newStaticMap().setLanguage('fr')
  .setSize(846,479)
  .setMapType(Maps.StaticMap.Type.HYBRID);

   addresses.forEach((address,i)=>{

     if(address!=''){
          map.addMarker(address)
             .setMarkerStyle(Maps.StaticMap.MarkerSize.MID,colors[i],(i+1).toString())
             .addMarker(address)
     }
   });

   map = map.endPath().getBlob();
   spreadsheet.insertImage(map,5,15)

}

Another reason it does not work now is that because you have invalid addresses:

put correct values and let me know if the code works.

A: The code of soMarios was working nice but markers colors was not correct. Here is the solution from another comunity. I let the code if it can help someone else.
function onOpen() {
  SpreadsheetApp.getUi().createMenu('⇩ M E N U ⇩')
    .addItem(' Générer les Cartes', 'myFunction')
    .addToUi();
  myFunction()
}

function myFunction() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  //var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Testing")

   // Deletes all images in sheet
    var images = sheet.getImages();
    images.map(function(img){img.remove();});

  var cards = []

  //gets the addresses of each card into an array
  for(i=0; i<16; i++)
  {
    cards.push(sheet.getRange(121, 11 + (15*i), 6, 1).getValues().flat())
  }

  //loop through the array of cards
  for(c=0; c < cards.length; c++){

   //create a new map
   var map = Maps.newStaticMap().setLanguage('fr')
  .setSize(846,479)
  .setMapType(Maps.StaticMap.Type.HYBRID)

  //remove blanks from card addresses
  var card = cards[c].filter(j => j)

  //begin a new path for the map
  map.beginPath()

  //loop through card addresses
  for(n=0; n < card.length; n++){

    //add the nth address to the map
    map.addAddress(card[n])

    //if first address, create new green marker (note n +1 due to array starting from 0 not 1)
    if(n == 0){

      map.setMarkerStyle(Maps.StaticMap.MarkerSize.MID, Maps.StaticMap.Color.GREEN,n+1)
      var marker = map.addMarker(card[n])
    }
    //if last address, create new red marker
    else if(n == card.length - 1){
      map.setMarkerStyle(Maps.StaticMap.MarkerSize.MID, Maps.StaticMap.Color.RED,n+1)
      var marker = map.addMarker(card[n])
    }
    //if any other address create blue marker
    else{
      map.setMarkerStyle(Maps.StaticMap.MarkerSize.MID, Maps.StaticMap.Color.BLUE,n+1)
      var marker = map.addMarker(card[n])
    }
  }

  //end the path and insert the map image to the sheet
  map.endPath()
  map.getBlob()
  sheet.insertImage(map,5+ (15*c),15)
  }
}


text:
Q: How can I utilize JQuery's ".on()" method to work with non-native jquery elements? I have recently posted a question here that told me to use .on() to attach elements to dynamically created objects. I'm just having an issue implementing this into my scripts, because I use an element that is from EasyUI:
$(".item").draggable({ ... });
And I'm not quite sure how to modify this to work with .on().
I have tried the following:
$('body').on('draggable', '.item', function() { ... }); (gives me an error that : is an unexpected token (the line of code is revert:true,)).
And:
$('body').on('draggable', '.item', draggable({ ... })); but that says draggable is not defined.
Sorry if this is really easy, It's just all going a bit over my head :P
Thanks for any help

A: draggable isn't an event, so you can't attach an event handler to it. It's a jQuery plugin method, and you can't call it on an element until the element exists.
If you're creating the element dynamically, you need to put the code that initializes the plugin into the code that creates the element. So it would look something like:
newElement = $("<div>", { "class": "item" }).draggable({...}).appendTo(something);

When using .load, you can attach the widget in the callback function.
$("#shop").load("showcontent/cat1.html", function() {
    $(this).find(".item").draggable({ ... });
});

A: for the first issue, it looks like revert:true needs to be an object {revert:true}.
for the second issue you need to pass a callback function to the event listener, you can declare one inline using the function keyword eg.
$('body').on('draggable', '.item', function draggable({ ... }));

or you can pass an anonymous function
$('body').on('draggable', '.item', function({ ... }));

or declare the function elsewhere and pass it to the event listener by reference eg.
function draggable( event ){ ... }
$('body').on('draggable', '.item', draggable));

A: Looks like you are confusing the name of the element with the name of the event. You would call $(".item").draggable({...}) to generate a new element that can be dragged.
To listen to the event of when the element gets dragged, you want to listed to either the onStartDrag, onDrag or onStopDrag. Like this $('.item').on('onStartDrag', function(event) {...}).
See full documentation here: http://www.jeasyui.com/documentation/index.php


text:
Q: select 2 jquery custom attribute country name with capital name I'm trying to add a custom attribute to select 2 options, Even if I search with "data-name" the option should show up
 <select name="countries" class="vat" id="example">
        <option value="USA" data-name="Newyork" selected="selected">United States</option>
        <option value="UK"  data-name="london">Unied Kingdom</option>
        <option value="DE"  data-name="Berlin">Germany</option>
    </select>

I'm trying to approach in the search, if I type berlin, Germany should show up on the select list
<script type="text/javascript">
        $(document).ready(function() {
            $("#example").select2().find(":selected").data("name");
        });
    </script>

Please try to help me on this
Thanks

A: You can use matcher method of select2 plugin . So ,whenever user typed inside input-box you can filter options inside select-box using ..indexOf(input_value). If the value is true then option will be shown else it will get hidden.
Demo Code :

$(function() {
  $("select").select2({
    "width": "150px",
    matcher: function(term, text, option) {
      //get input box value
      var input_value = $(".select2-input").val().toLowerCase();
      //get the data attribute value..
      var data_name = $(option[0]).data("name").toLowerCase();
      //if match ..show that option
      return data_name.indexOf(input_value) != -1 || option[0].textContent.toLowerCase().indexOf(input_value) != -1;
    }
  })

})
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.min.css" />
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.min.js"></script>

<select name="countries" class="vat" id="example">
  <option value="USA" data-name="Newyork" selected="selected">United States</option>
  <option value="UK" data-name="london">Unied Kingdom</option>
  <option value="DE" data-name="Berlin">Germany</option>
</select>

A: try this, you can search the state and country will show
<input list="brow">
<datalist id="brow">
        <option value="USA" data-name="Newyork" selected="selected">new york, florida</option>
        <option value="UK"  data-name="london">london</option>
        <option value="DE"  data-name="Berlin">berlin, other states</option>

</datalist>


text:
Q: What does this quote from The New Yorker mean? What does this bold part mean:

The man who, as one author put it, "ruled the literary world from a fifteen-square-metre office" led a life more full of pain, wonder, and irony than most literary heroes. Born in Poland in 1920, Reich-Ranicki was sent to Berlin to study as a boy. "With every year that he discovered more joy in, and love for, Thomas Mann and Brecht and Gründgens and Goethe, there also grew hate," wrote Frank Schirrmacher, publisher of the influential F.A.Z., where Reich-Ranicki headed the literature section in the nineteen-seventies and eighties. "The hate of an entire nation and all its bureaucracy for the young Jewish man who just wanted to go to the Deutsche Theatre."
The New Yorker

A: I think the author of this passage confuses you by breaking a very long but continuous quotation into two parts. It works like this:

With every year
      that he discovered more [joy and love for these guys] (this is a relative clause modifying "year")
      there also grew hate—
          —hate of [those other guys] for [him]

Year by year, while Reich-Ranicki was growing in love for his literary idols, the rest of the nation was growing in hatred for people like Reich-Ranicki.


text:
Q: How to fix the psycopg2 syntax error at or near '%'? Basically trying to create ISNERT function, which will compile the insert and execute it.
def Insert(self,tablename, **kwargs):
        qms = []
        for idx, item in enumerate(kwargs):
            qms.append('%%s')
        qmarks = ', '.join(qms)
        res = []
        res.extend(kwargs.keys())
        res.extend(kwargs.values())
        res = tuple(res)
        QUERY = "INSERT INTO "+tablename+" (%s) VALUES (%s)" % (qmarks, qmarks)
        self.dc.execute(QUERY, res)
        self.db.commit()

Returns me:
psycopg2.errors.SyntaxError: syntax error at or near "%"
LINE 1: INSERT INTO users (%s, %s) VALUES (%s, %s)

A: psycopg2's execute() function just injects the values but not the columns, you need to pass the real column names to QUERY:
import psycopg2
import psycopg2.extras

class A():
    def __init__(self):
        self.dc = ...
        self.db = ...

    def Insert(self, tablename, **kwargs):
        columns = []
        valuePlaceholders = []
        values = []
        for column, value in kwargs.items():
            columns.append(column)
            valuePlaceholders.append('%%s')
            values.append(value)

        QUERY = "INSERT INTO " + tablename + " (%s) VALUES (%s)" % (', '.join(columns), ', '.join(valuePlaceholders))
        print(self.db.mogrify(QUERY, values))
        #self.db.execute(QUERY, values)
        #self.db.commit()

a = A().Insert('foo', arg1="bar", arg2="test")

Output:
b'INSERT INTO foo (arg1, arg2) VALUES (%s, %s)'

A: Your qms array is filled with the string values '%s'.
Your qmarks string then equals '%s, %s'.
After that you inject that value in your query string twice so you have 'INSERT INTO users (%s, %s) VALUES (%s, %s)'.
The issue here is that you have filled your array with incorrect values.
You need to inject your table names and values instead of %s


text:
Q: include_once, relative path in php I have 3 files: home, failed_attempt, login.
The file home and failed_attempt all refer to login file.
The annoying thing is that they throw a mistake saying that the login file doesnt exist. home will throw an exception if i do this, but failed_attempt wont.
  include_once("../StoredProcedure/connect.php");

include_once("../untitled/sanitize_string.php");
and if I do this:
   include_once("StoredProcedure/connect.php");
   include_once("untitled/sanitize_string.php");

the opposite happens, failed_attempt throws an exception , but home, wont. How do I fix this..
Do I tell the include to go up a page by putting this ../ , and therefore home.php doesnt need to go one page up therefore it throws that exception..
How can I make it so both files accept those inclueds as valid.. perhaps not relative to where they are placed.. i.e. without that ../
Directory structure:
PoliticalForum
->home.php
->StoredProcedure/connect.php
->untitled/sanitize_string.php
->And other irrelevant files

A: Here are three possible solutions.  The second are really just work-arounds that use absolute paths in a clever way.
1: chdir into the correct directory
<?php

// check if the 'StoredProcedure' folder exists in the current directory
// while it doesn't exist in the current directory, move current
// directory up one level.
//
// This while loop will keep moving up the directory tree until the
// current directory contains the 'StoredProcedure' folder.
//
while (! file_exists('StoredProcedure') )
    chdir('..');

include_once "StoredProcedure/connect.php";
// ...
?>

Note that this will only work if your StoredProcedure folder is in the topmost directory of any files that might need to include the files it contains.
2: Use absolute paths
Now before you say this is not portable, it actually depends on how you implement it.  Here's an example that works with Apache:
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . "/StoredProcedure/connect.php";
// ...
?>

Alternatively, again with apache, put the following in your .htaccess in the root directory:
php_value auto_prepend_file /path/to/example.php

Then in example.php:
<?php

define('MY_DOC_ROOT', '/path/to/docroot');

?>

And finally in your files:
<?php
include_once MY_DOC_ROOT . "/StoredProcedure/connect.php";
// ...
?>

3: Set PHP's include_path
See the manual entry for the include_path directive.  If you don't have access to php.ini, then this can be set in .htaccess, providing you are using Apache and PHP is not installed as CGI, like so:
php_value include_path '/path/to/my/includes/folder:/path/to/another/includes/folder'

A: For the beginners this will help to understand. Use simply the following based on your relative path:
//include file directly from parent directory:
include_once(dirname(__FILE__) . '/../connect.php');

OR
//include file from parent's child directory:
include_once(dirname(__FILE__) . '/../StoredProcedure/connect.php');

OR
//include file from own child directory:
include_once('StoredProcedure/connect.php');

OR
//include sibling files from same directory:
include_once('connect.php');

A: Do something like require(dirname(__FILE__) . '[RELATIVE PATH HERE]');

A: Things like realpath() and __DIR__ are your friends when it comes to creating paths in PHP.
Realpath http://php.net/manual/en/function.realpath.php
Magic constants http://php.net/manual/en/language.constants.predefined.php
Since include and require are language constructs (rather than functions) they don't need brackets. Generally speaking you'd use include to include "templates" (output files) and require to include PHP files such as classes.
So you could use something like:
$sPath = realpath( __DIR__ . '/../relative/path/here');
if($sPath) { require_once $sPath; }

(use dirname(__FILE__) instead of __DIR__ on PHP < 5)
It's worth evaluating the path before attempting to require the file as realpath() returns false if the file doesn't exist and attempting to require false; spaffs out a PHP error.
Alternatively you can just use absolute paths like:
require /home/www/mysite.com/htdocs/inc/somefile.php

A: The other guys have answered your question correctly, however I thought I'd contribute something else: autoloaders.
Autoloaders allow you to define a function that will automatically include certain files, when you attempt to use a class.
The documentation is here and can explain it better than I can: http://php.net/manual/en/language.oop5.autoload.php
Would really recommend using them, will save you time and is better practice.


text:
Q: What is the difference between "See you" and "So long"? I want to say "Let's work this later, "see you/so long" I don't know which one is more formal and I don't know which one take more time to "meet someone again"

A: "See you" and "so long" are roughly equal in formality in American English. Both are what most people would probably call informal - you can use either as a sign-off to coworkers of equal rank, and to immediate supervisors with which you have friendly interaction in any typical office environment. For anything farther off, you'd want something more formal such as "sincerely" or "signed". (It's also common to omit a signoff altogether in email, and just use a signature file.)
"So long"'s origin is unknown, though there are a few candidates. Nowadays, it's identical to "goodbye", "farewell", and several other parting phrases.
It would be odd to inquire how long it would be until next meeting, unless there were another reason to ask (i.e. you need to meet again to follow up on some issue). In all cases, the choice of signoff phrase is independent of time until next meeting unless you explicitly provide a time (e.g. "see you tomorrow"; "so long until next year").


text:
Q: Как вычислить среднее арифметическое элементов, расположенных между минимальным и максимальным? Получилось слишком громоздко, можно ли сделать короче это задание?

В одномерном массиве А(10) вычислить среднее арифметическое элементов, расположенных между минимальным и максимальным.

#include <stdio.h>
int main(){
    int mas[10], result = 0, max, min, i, max_in=0, min_in=0, am, count = 0;
        for (i = 0; i < 10; i++){
            printf("Введите элемент mas[%d] = ",i);
            scanf("%d", &mas[i]);
        }
        max=mas[0];
        min = mas[0];
        for(i = 0; i < 10; i++){
            if(mas[i]>max){
                max=mas[i];
                max_in = i;
            }else if(mas[i]<min){
                min=mas[i];
                min_in = i;
            }
        }
        if(max_in<min_in){
                count = (min_in - max_in) - 1;
                if(count == 0){
                      printf("Кол-во = 0");
                }else{
                for(i = max_in + 1; i<min_in; i++){
                        result += mas[i];
                }}
        }else if(max_in>min_in){
                count = (max_in - min_in) - 1;
                if(count == 0){
                      printf("Кол-во = 0");
                }else{
                for(i = min_in + 1; i<max_in; i++){
                        result += mas[i];
                }}
        }
        am = result/count;
        printf("Результат  =  %d \n", am);
return 0;
}

A: Ну, если действовать исключительно (не включая минимум и максимум) и рассматривая первые же минимум и максимум среди равных, то, например, так:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int m, max, min, imax = 0, imin = 0, d[10];
    for(int i = 0; i < 10; i++)
    {
        printf("Введите элемент mas[%d] = ",i);
        scanf("%d", &m);
        if (i == 0)
            max = min = d[0] = m;
        else
        {
            d[i] = d[i-1] + m;
            if (m > max) max = m, imax = i;
            else if (m < min) min = m, imin = i;
        }
    }
    if (imax < imin) { m = imin; imin = imax; imax = m; }
    if (imax - 1 <= imin) printf("no elements\n");
    else printf("%lf\n",((double)(d[imax-1] - d[imin]))/(imax-imin-1));

}

Надеюсь, числа не такие, чтоб вызвать переполнение при суммировании :)

A: Не знаю, что по мнению преподавателя является "громоздким", поэтому постарался использовать парадигму функционального программирования для облегчения читаемости кода. Ну и в некоторых моментах специально ужал количество строк, вдруг имелся ввиду объём.
Мой вариант
#include <stdio.h>
#include <stdbool.h>
#include <limits.h>

int getMaxOrMin(int* arr, bool isMax) {
    int maxOrMin = isMax ? INT_MIN : INT_MAX;
    for (int i = 0; i < 10; i++) {
        if (arr[i] > maxOrMin && isMax)
            maxOrMin = arr[i];
        else if (arr[i] < maxOrMin && !isMax)
            maxOrMin = arr[i];
    }
    return maxOrMin;
}
int getIndex(int* arr, int num) {
    for (int i = 0; i < 10; i++) {
        if (arr[i] == num)
            return i;
    }
}
double getAvg(int* arr, int max_i, int min_i) {
    int begin = max_i < min_i ? max_i : min_i, end = max_i > min_i ? max_i : min_i,
    count = 0, sum = 0;
    for (int i = begin + 1; i < end; i++, count++)
        sum += arr[i];
    return sum / count;
}
int main() {
    int arr[10], max, min, max_i, min_i;
    for (int i = 0; i < 10; i++) {
        printf("Введите элемент arr[%d] = ", i);
        scanf("%d", &arr[i]);
    }
    max = getMaxOrMin(arr, true);
    min = getMaxOrMin(arr, false);
    printf("Среднее арифметическое = %lf", getAvg(arr, getIndex(arr, max), getIndex(arr, min)));
    return 0;
}


text:
Q: How can I install l3backend-pdfmode.def? When I try to compile a .tex file with no additional \usepackage, I get the following error:

LaTeX Error: File `l3backend-pdfmode.def' not found.

Following this thread I ran tlmgr update --all and tlmgr update --self, but I still got the error. I noticed that there is no l3backend-pdfmode.def in the directory l3backend:

C:\texlive\2020\texmf-dist\tex\latex\l3backend
2020/10/16  18:54              .
2020/10/16  18:54              ..
2020/10/16  16:13            24,777 l3backend-dvipdfmx.def
2020/10/16  16:13            32,860 l3backend-dvips.def
2020/10/16  16:13            17,860 l3backend-dvisvgm.def
2020/10/16  16:13            24,060 l3backend-luatex.def
2020/10/16  16:13            23,704 l3backend-pdftex.def
2020/10/16  16:13            26,739 l3backend-xetex.def

I am guessing that I have to add `l3backend-pdfmode.def' manually, but how can I do that?


text:
Q: How to run .net application on Linux environment? Is it possible to run a .net application on Linux environment? If yes then how? Will all the components of .net framework work properly on Linux ?

A: While there are alternatives (I believe), Mono is probably what you want.
It doesn't support everything that .NET supports, but there's a compatibility tool which will check for you. (I wouldn't blindly trust the results of the compatibility tool to be 100% accurate, as there will always be a few sneaky unknown incompatibilities, but it's a very good start.)

A: A new answer for an old question, as technology improves.
You might also consider running your app as a dotnet core application.
The same code will work nativly with MAc Windows and linX
download dotnet runtime for your OS and on a console type
Dotnet .\yourapp.dll

A: There is also MainSoft that lets you run on J2EE environment on Linux. It basically compiles the .NET source into Java bytecode.

A: Please see Running .Net applications on Linux with Mono:

Imagine the fate of your company rests
  on your completing your new Linux
  project on time. You have a crack team
  of first-class developers, but they're
  all .Net programmers. What are you
  going to do? Admit that Windows is
  better that Linux? Cry? Resign? No,
  you're going to install Mono and save
  the world!

A: An updated answer for 2018 with the current state of the Mono Project in Linux.
mono repos exist for:
Ubuntu
Debian
Raspbian
CentOS
Fedora
Docker

The instructions suggest installing mono-complete - on Centos I also had to install mono-basic for VB.NET to work. The current level of support for VB.NET is:
default runtime: v4.0.30319

which is good enough to run a VB.NET XML client which required a 3.5 runtime:

A: For running simple .net Applications mono is the tool of your choice! I used it for many applications and it worked without major glitches. I would not reccommend starting to develop on Mono though. Some people in my Class tried to do C# on Linux with mono, and failed terribly.
When you do simple stuff it works good, but when you go to the more advanced stuff like using NHibernate or something like that, it may fail you. And you will miss out the best thing about .net - the Development Environment and that everything works together because everything is provided by Microsoft.


text:
Q: Selecting and Identifying element with JQuery to use it in Selenium 2 Java API This is the situation:

*

*I use the Java API of Selenium 2 to open and control a firefox browser instance

*I load the jQuery script to a page via JavaScript execution

*I then use jQuery expressions to select elements and traverse through the DOM tree

Now is my question, can i somehow find a unique identifier for each of the found elements? My goal is to get the same element with Selenium by using an Xpath or CSS selector. So it would be most straighforward if i could generate an unambiguous selector for the elements in jQuery. Other ideas are welcome too.
I need an automatic approach for identifying elements in jQuery, which can be "converted" to Selenium elements / locators.
/edit
To make it clearer:
If i have selected an element in jQuery:
webDriver.executeScript("var element = $('#myDiv input.test')");

Now, I want something like this:
WebElement webElement = webDriver.executeScript("return element");

Is that possible?

A: I found the solution, which is quite easy:
String jQuerySelector = "'#myDiv input.test'";
RenderedWebElement webElement = (RenderedWebElement) ((JavascriptExecutor) webDriver).executeScript("return $(" + jQuerySelector+ ").get(0);");

Working with an element in jQuery which was previosly selected in Selenium works too:
String jQuerySelector = "arguments[0]";
((JavascriptExecutor) webDriver).executeScript("return $(" + jQuerySelector+ ").doSomethingInJquery();", webElement);

A: Using eval makes it even easier. Use an index selector such as [0] with the jQuery code or it will return a collection of elements.
    String elementLocator = "$('#btnID')[0]";
    public RemoteWebElement getElementByJQueryLocator(String jQueryLocator){
        JavascriptExecutor js = (JavascriptExecutor) driver;
        RemoteWebElement element = (RemoteWebElement) js.executeScript("return eval(arguments[0]);", jQueryLocator);
        return element;
    }

        RemoteWebElement webElement = getElementByJQueryLocator(elementLocator);
        webElement.click();

A: Not sure of your exact problem but you can build you locator using html id, name, class etc attributes.


text:
Q: Angular - Modify component property in app.component.html I have a component named "input-text" which just have html textbox in it.
<input type="text" />

Now, I am using this component in my app.component.html but I want to change the type of this textbox to email, password, etc.
<app-input-text>??</app-input-text>

How can I achieve that?

A: If you want to go with component way, you could just add @Input() type: string and in html use it
input-text.component.ts
export class InputTextComponent {
   @Input() type: string
}

input-text.component.html file
<input [attr.type]="type" />

and in element which contains input-text.component
<app-input-text [type]="inputType"></app-input-text>
where `inputType` is string type for input like `email, password, text...`

A: Try this:
input.component.ts
import { Component, Input } from "@angular/core";

@Component({
  selector: "app-input",
  template: `
    <input [type]="type" />
  `
})
export class InputComponent {
  @Input() type: String;
}

app.component.ts
import { Component } from "@angular/core";

@Component({
  selector: "app-root",
  template: `

Stack Overflow

      <app-input type="text"></app-input>
      <app-input type="checkbox"></app-input>
      <app-input type="radio"></app-input>

  `
})
export class AppComponent {}

This is the demo: https://codesandbox.io/s/21p1y9vqqj


text:
Q: How do I keep the keyboard hidden when it's not wanted? The app I'm working on allows the user both to read text and to compose text, using different buttons.  My problem now is that on the screen for reading text, if the user taps inside the UITextView box used on the screen for writing text, the keyboard appears.  The UITextView in this case is self.textView; I've put the keyboard notifications and the keyboardWillShow method inside if(self.textView) statements and then made sure to call [self.textView removeFromSuperView] and set self.textView = nil; at the beginning of the reading text methods, but the keyboard still appears when you tap the space where self.textView is set (programmatically, by the way, not using the IB).
What am I doing wrong?
Edit:  Thanks for the answers, guys and gals, but still that darn keyboard keeps coming back, just like the cat in the song....  Here's my code.  Forgive its length, please, if you can; if I've done something wonky I don't know where it is, and so I don't know what to leave out.
Here's viewDidLoad.
-(void)viewDidLoad {
[super viewDidLoad];
self.textView.editable=NO;
self.textView.userInteractionEnabled = NO;
UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(previousHaiku)];
swipeRight.numberOfTouchesRequired = 1;
swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:swipeRight];
UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(nextHaiku)];
swipeLeft.numberOfTouchesRequired = 1;
swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:swipeLeft];
 NSError *error;
 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectory = [paths objectAtIndex:0];
 NSString *path = [documentsDirectory stringByAppendingPathComponent:@"gayHaiku.plist"];
 NSFileManager *fileManager = [NSFileManager defaultManager];
 if (![fileManager fileExistsAtPath: path])
 {
 NSString *bundle = [[NSBundle mainBundle] pathForResource:@"gayHaiku" ofType:@"plist"];
 [fileManager copyItemAtPath:bundle toPath: path error:&error];
 }
 self.gayHaiku = [[NSMutableArray alloc] initWithContentsOfFile: path];
 [self nextHaiku];
}

Here's nextHaiku, the last method called in viewDidLoad -- this is the reading method.
-(void)nextHaiku
{
[self.view.layer removeAllAnimations];
[self.bar removeFromSuperview];
self.textToSave=@"";
self.haiku_text.text=@"";
[self.view viewWithTag:1].hidden = NO;
[self.view viewWithTag:3].hidden = NO;
int indexOfHaiku;
NSMutableArray *arrayOfHaikuSeen;
NSString *cat;
if (!self.selectedCategory) cat = @"Derfner";
else cat = self.selectedCategory;
NSArray *filteredArray;
if (cat==@"all")
{
    filteredArray = self.gayHaiku;
    indexOfHaiku = self.indxAll;
    arrayOfHaikuSeen = self.theseAreDoneAll;
}
else
{
    indexOfHaiku = (cat==@"user")?self.indxU:self.indxD;
    arrayOfHaikuSeen = (cat==@"user")?self.theseAreDoneU:self.theseAreDoneD;
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"category == %@", cat];
    filteredArray = [self.gayHaiku filteredArrayUsingPredicate:predicate];
}
int array_tot = [filteredArray count];
int sortingHat;
NSString *txt;
if (array_tot > 0)
{
    if (indexOfHaiku == arrayOfHaikuSeen.count)
    {
        while (true)
        {
            sortingHat = (arc4random() % array_tot);
            if (![arrayOfHaikuSeen containsObject:[filteredArray objectAtIndex:sortingHat]]) break;
        }
        txt = [[filteredArray objectAtIndex:sortingHat] valueForKey:@"quote"];
        if (!arrayOfHaikuSeen || arrayOfHaikuSeen.count==array_tot)
        {
            arrayOfHaikuSeen = [[NSMutableArray alloc] init];
        }
        [arrayOfHaikuSeen addObject:[filteredArray objectAtIndex:sortingHat]];
        indexOfHaiku = arrayOfHaikuSeen.count;
        if (arrayOfHaikuSeen.count==filteredArray.count)
        {
            [arrayOfHaikuSeen removeAllObjects];
            indexOfHaiku=0;
        }
    }
    else
    {
        txt = [[arrayOfHaikuSeen objectAtIndex:indexOfHaiku] valueForKey:@"quote"];
        indexOfHaiku += 1;
    }
}
//Need to test to make sure it starts over once all 110 haiku have been seen.

CGSize dimensions = CGSizeMake(320, 400);
CGSize xySize = [txt sizeWithFont:[UIFont fontWithName:@"Helvetica" size:14.0] constrainedToSize:dimensions lineBreakMode:0];
self.haiku_text = [[UITextView alloc] initWithFrame:CGRectMake((320/2)-(xySize.width/2),200,320,200)];
self.haiku_text.font = [UIFont fontWithName:@"Helvetica Neue" size:14];
self.haiku_text.backgroundColor = [UIColor clearColor];
self.haiku_text.text=txt;
CATransition *transition = [CATransition animation];
transition.duration = 0.25;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionPush;
transition.subtype =kCATransitionFromRight;
transition.delegate = self;
[self.view.layer addAnimation:transition forKey:nil];
[self.view addSubview:self.haiku_text];

if (cat==@"user")
{
    self.theseAreDoneU = arrayOfHaikuSeen;
    self.indxU = indexOfHaiku;
}
else if (cat==@"all")
{
    self.theseAreDoneAll = arrayOfHaikuSeen;
    self.indxAll = indexOfHaiku;
}
else
{
    self.theseAreDoneD = arrayOfHaikuSeen;
    self.indxD = indexOfHaiku;
}
}

And here's the writing method.
-(void)userWritesHaiku

//Set up the screen.
[self clearScreen];
self.textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 60, 280, 150)];
self.textView.delegate = self;
self.textView.returnKeyType = UIReturnKeyDefault;
self.textView.keyboardType = UIKeyboardTypeDefault;
self.textView.font = [UIFont fontWithName:@"Helvetica Neue" size:14];
self.textView.scrollEnabled = YES;
self.textView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
self.textView.userInteractionEnabled = YES;
self.textView.editable=YES;
self.textView.backgroundColor = [UIColor colorWithRed:217 green:147 blue:182 alpha:.5];
[self.view addSubview: self.textView];

[self loadNavBar:@"Compose"];
[self addLeftButton:@"Instructions" callingMethod:@"haikuInstructions"];

//If you've added text before calling haikuInstructions, when you return from haikuInstructions the textView window with the different background color AND the keyboard.
[self addRightButton:@"Done" callingMethod:@"userFinishedWritingHaiku"];
self.titulus.hidesBackButton=YES;
[self seeNavBar];

//Create and add the space for user to write.
[self createSpaceToWrite];
if (self.textToSave!=@"")
{
    self.textView.text = self.textToSave;
}
[self.view addSubview:self.textView];
[self.textView becomeFirstResponder];

//Keyboard notifications.

if (self.textView)
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

}

A: try this
[self.textView setEditable:NO];

A: When the user taps on the reading button, I would just call
self.textView.userInteractionEnabled = NO;

and when you want them to edit it call
self.textView.userInteractionEnabled = YES;

A: Well, it turned out that the whole time there was a UITextView I'd created in the xib and forgotten about because it was hiding under the main view--when I decided to create the UITextView programmatically I didn't remember to delete the other one, because I couldn't see it, but it was there working its evil will the entire time.  I finally figured this out after commenting out literally the entire code with the exception of [super viewDidLoad] and removing everything from the xib.


text:
Q: Standard PHP Page - incorporating Bootstrap.min.css AND original stylesheet // bootstrap is overriding main CSS I'm adding a new page to a current site - with php.
I decided that the best solution, for this new page, was to add bootstrap, for column capability.
The issue stems from accessing both the original style sheet AND the bootstrap.min.css // the original style sheet is overridden.
What is the best way to keep the original styles, while integrating the capabilities of bootstrap?
Essentially, I don't want bootstrap to replace the original style sheet - just enhance it.

A: By the sounds of it you are importing the bootstrap css after you have imported your original style sheet.
Browsers pay attention to the order in which stylesheets are loaded. In your document head you probably have something like this
<link rel="stylesheet" href="/style.css">
<link rel="stylesheet" href"/bootstrap.min.css">

Because you are importing the bootstrap css after your style.css. it's over riding anything which you may already have styled.
For example
You may have this in your style.css
p{
color:red;
}

And this in bootstrap.min.css
p{
color:blue;
}

The end result would mean your paragraphs will all be blue, and not red as you defined.
There is other factors which could come into play such as how targeted your css is or the use of !important but I don't think that's your problem.
You'll find a similar question here was answered as well


text:
Q: Socket io doesn't connect after calling disconnect function .i.e Connect -> Disconnect -> Connect won't work iOS swift I am working on Chat engine using Socket io version 15.2.0,
When first time when I call socket.connect() it works properly, then if I call socket.disconnect() and then again try to call socket.connect() then socket fails to connect without any error or log. Then I have to kill the app and need to relaunch the app then socket connects without any issue.
following is my Shared class for Socket connect and disconnect
 class SocketHelper {

    static let shared = SocketHelper()
    var socket: SocketIOClient!

    let manager = SocketManager(socketURL: URL(string: ApiUrls.socketUrl)!, config: [.log(true), .compress, .connectParams(["token": Globals.shared.session.accessToken]), .secure(true), .forceNew(true)])

    private init() {
        socket = self.manager.defaultSocket
    }

    func getSocketWithLazyConnect() -> SocketIOClient {
        if self.socket.status == .connected {
            return self.socket
        }

        self.socket.connect()

        return self.socket
    }

    func disconnect() {
        self.socket.disconnect()
    }

    func isConnected() -> Bool {
        return self.socket.status == .connected
    }
 }

Any help much appreciated...

A: Thank you guys but I figured out what I was doing wrong
I have one shared class named ChatEngine it handle all chat related socket events.
in that method while to disconnect from socket, I wrote a function switchOff
func switchOff() {
    socket?.off(Constants.SocketEvent.connect)
    SocketHelper.shared.disconnect()
}

as shown above I was calling off funtion for connect event and that's why after that when I called socket.connect, I didn't received any call back for that inside
self.socket?.on(clientEvent: .connect, callback: { (data, ack) in

})

I just removed off function call from my switchOff function and now it's working fine. Now my switchOff function is like this
func switchOff() {
    SocketHelper.shared.disconnect()
}


text:
Q: Where clause missing in SQL Query I am sending  a SQL query from a client to a MySQL database.
When I run the query in MySQL the result is correct.
The result from the query is wrong, when sent from client.
The last WHERE clause is missing.
The query original looks like this:
SELECT SUM(Second_In_State) From
(SELECT
    Time_Stamp,
    State,
    TIMESTAMPDIFF(SECOND, LAG(Time_Stamp) OVER(ORDER BY Time_Stamp), Time_Stamp)
AS Second_In_State
FROM db.xyz_1_state
ORDER BY Time_Stamp) AS T
Where State = 1;

Result is number of seconds where State = 1 (The wanted result)
In the MySQL Query log the query looks like this:
SELECT SUM(Second_In_State) From
(SELECT
    Time_Stamp,
    State,
    TIMESTAMPDIFF(SECOND, LAG(Time_Stamp) OVER(ORDER BY Time_Stamp), Time_Stamp)
AS Second_In_State
FROM db.xyz_1_state
ORDER BY Time_Stamp) AS T

The result is the total of seconds in all states. (Wrong result)
Any suggestions why the last line is missing?

A: Thanks for your comments.
I found out that the client is limited in number of lines. So when saving the last line is deleted.
So converting the query to a single line, solved the problem.
Thanks.


text:
Q: Runnable Handler not executing inside fragment. Could not start a runnable I have a runnable inside a fragment. The runnable is meant to update the textviews as well as receive input using buttons. But the program does not enter even once inside the runnable.
Please help. What am I doing wrong.
Thanks.
The code is as follows. I have buttons and textviews inside the runnable.
public class TodayFragment extends Fragment {
//initialisations

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

//UI initialisations

Handler mHandler = new Handler();
Runnable mTicker = new Runnable() {
            @Override
            public void run() {

//user interface interactions and updates on screen

    mHandler.postDelayed(mTicker, 1000);

   mTicker.run();

 }

A: it seems you wanna change your views in every 1 second. if you say so you should execute your handler outside your runnable method aswell. i.e:
    Handler mHandler = new Handler();
    Runnable mTicker = new Runnable() {
        @Override
        public void run() {

            // user interface interactions and updates on screen
            // if you want to run this handler only once then delete below line
            mHandler.postDelayed(mTicker, 1000);

        }
    };

mHandler.postDelayed(mTicker, 1000);

A: It's work for me.
public class TodayFragment extends Fragment {
//initialisations
Runnable mTicker;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    final Handler mHandler = new Handler();
    mTicker = new Runnable() {
        @Override
        public void run() {

            // user interface interactions and updates on screen

            mHandler.postDelayed(mTicker, 1000);

            }
        };

    mHandler.postDelayed(mTicker, 1000);

    return inflater.inflate(R.layout.fragment_today, container, false);;

}

A: try this change
mTicker = new Runnable() {
        public void run() {

         //user interface interactions and updates on screen

           mHandler.postDelayed(mTicker, 1000);

        }
    };
    mTicker.run();


text:
Q: setJavaScriptEnabled doesn't work in webview I have a simple layout that contains a webview.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<WebView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/webView"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:padding="10dp"
    android:layout_alignParentStart="true" />

Inside this webview i loaded some HTML dinamically on the OnCreate Method.
 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    WebView displayVideo = (WebView)findViewById(R.id.webView);
    displayVideo.getSettings().setJavaScriptEnabled(true);
    String html = "<!DOCTYPE html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/> <title></title>
Test
 ";
 displayVideo.loadDataWithBaseURL("file:///android_asset/web/", html, "text/html", "UTF-8", null);

*As you can see in the loaded HTML, I am calling jquery from code.jquery.com
In the document ready i am testing jquery by adding css class to

Test

when i execute the app nothing changes, i am guessing javascript or jquery is not working.
By the way: in the method
 displayVideo.loadDataWithBaseURL("file:///android_asset/web/", html, "text/html", "UTF-8", null);

I have no idea what "file:///android_asset/web/"" is for , maybe the problem is there?


text:
Q: Solve for input with given TransferFunctionModel I obtained the transfer function for an electrical system from experimental data (left plot). Thereby, I can calculate the output voltage response for a given voltage input, using TransferFunctionModel[] and OutputResponse[] in the time domain (right plot):

My question is, how can I use the obtained TransferFunctionModel to find the right voltage input pulse for a desired output voltage?
I know from this publication, that for simple RC networks there is an analytical solution for this task, see for example Fig. 4(b) therein. As I'm not aware of an analytical solution for an arbitrary transfer function I was wondering if I could numerically solve for the required input (blue curve from above) if I want my output response to follow a specific function (green curve from above), e.g., Sin[x]^2.
I'm thinking that I might need to parametrize my possible input function somehow and then use Solve or NSolve to find the right parameters. However, I expect the required input to be of complex shape, i.e., not simply proportional to Sin[x]^2 like the blue curve above, and, thus, not sure how to parametrize it.
I really would appreciate comments or suggestions on how to proceed.

A: my solution. You can compute the inverse transferfuncion
PT2[K_, T1_, T2_] := K/((1 + T1 s) (1 + T2 s))
BodePlot[PT2[1, 1 10^-5, 10 10^-5], ImageSize -> Medium]

Pinv[s_] = TransferFunctionModel[1/PT2[1, 1 10^-5, 10 10^-5], s]

Than you can pass your desired output through the artificial system and calculate the response
desOut[t_] := Sin[t]^2
resInput[t_] = OutputResponse[Pinv[s], desOut[t], t] // FullSimplify

Now you can use this function as an input for the original system
P[s_] = TransferFunctionModel[PT2[1, 1 10^-5, 10 10^-5], s]

   Plot[{Evaluate@OutputResponse[P[s], resInput[t], t], desOut[t]}, {t, 0, 10},
 PlotStyle -> {Thick, Dashed}]


text:
Q: I do not understand this warning: The method or function should not be given explicit type argument(s) I have this code:
type BSCReply =
    {
        status:  int
        message: string
        result:  string
    }

let private decodeResult<'a> (result: IRestResponse) =
    let deserialize content =
        try
            Ok (JsonConvert.DeserializeObject<'b> content)
        with ex ->
            Error (HttpStatusCode.InternalServerError, ex.Humanize())

    match result.IsSuccessful with
    | true  ->  match deserialize<BSCReply> result.Content with
                | Ok r    -> deserialize<'a> r.result
                | Error e -> Error e
    | false ->  Error(result.StatusCode, result.ErrorMessage)

but when compiling, I get this error:

[FS0686] The method or function 'deserialize' should not be given explicit type argument(s) because it does not declare its type parameters explicitly

the warning happens two times, one for each use of 'deserialize'
I don't understand this error, can someone explain?

A: I think the problem here is that deserialize refers to a type 'b that you haven't defined anywhere. To fix this, you should move deserialize out to the top level and declare 'b explicitly. Something like this:
let private deserialize<'b> content =
    try
        Ok (JsonConvert.DeserializeObject<'b> content)
    with ex ->
        Error (HttpStatusCode.InternalServerError, ex.Humanize())

let private decodeResult<'a> (result: IRestResponse) =
    match result.IsSuccessful with
    | true  ->  match deserialize<BSCReply> result.Content with
                | Ok r    -> deserialize<'a> r.result
                | Error e -> Error e
    | false ->  Error(result.StatusCode, result.ErrorMessage)


text:
Q: How the variable values are changing while using conditional operator? Can anyone help me to Explain the output of the the Above code..
it will printing different output in different compilers. Which
one to be considered.
Code
#include<stdio.h>

int main()
{
    int a=0, b=1, c=2;
    *((a+1 == 1) ? &b : &a) = a ? b : c;
    printf("%d, %d, %d\n", a, b, c);
    return 0;
}

Output
0,2,2

This output is from Codeblocks

A: Your code is equivalent to:
int* ptr;

if (a + 1 == 1)   // which is true
{
    ptr = &b;     // So ptr points to b
}
else
{
    ptr = &a;
}

if (a != 0)       // which is false
{
    *ptr = b;
}
else
{
    *ptr = c;      // so *ptr (which is same as b) is set equal to c
}

So what happens is b=c;

A: The line in your code
   *((a+1 == 1) ? &b : &a) = a ? b : c;

uses conditional operator (or, ternary operator) ?:. As per the properties, quoting from C11, chapter §6.5.15,

The first operand is evaluated; there is a sequence point between its evaluation and the
  evaluation of the second or third operand (whichever is evaluated). The second operand
  is evaluated only if the first compares unequal to 0; the third operand is evaluated only if
  the first compares equal to 0; the result is the value of the second or third operand
  (whichever is evaluated), converted to the type described below [...]

So, for LHS,
 *((a+1 == 1) ? &b : &a)

a is 0, so (a+1 == 1) is true (1), so it reduces to *(&b) (second operand).
For the RHS,
     a ? b : c;

a being 0, it reduces to c, (third operand).
So, taken together, it is
 *(&b) = c;

or
  b = c;

A: int a=0, b=1, c=2;
*((a+1 == 1) ? &b : &a) = a ? b : c;
printf("%d, %d, %d\n", a, b, c);

a+1 -> 0+1 -> 1 == 1 True, therefore *(&b)
Now, a = 0 false, therefore c.
Now equating *(&b) = c which is b = c , a and c don't change.
a ? b : c

is same as :
  if(a)
        b;
    else
        c;


text:
Q: How to create collapsible panels as custom controls in Winforms? The closest I can think of using is the GroupBox control which has a custom drawing at the top identifying the panel.
Is it doable? I have done independent custom controls like buttons, sliders, color pickers, but not totally sure if this sort of drawing can be done on a GroupBox?
I would need the grouping of a GroupBox or a TabPanel.
Are there any alternatives on the net that I can use?
Just exploring the alternatives before I start doing it.

A: A technique we used was to create multiple panels docked to the top of a frame and set their height to zero. Then when we wanted to display a panel we set its height correctly. Winforms automatically reflows other panels to accommodate the new one.
You can also create a recurring timer to trigger every few hundred milliseconds that increases the panel's height by a few pixels until it reaches full size. This creates a nice animation of the panel expanding into place.

A: See how others have done this.  Code Project's got a bunch.  Try searching there.
I used this one a while ago and liked it:
Windows XP style Collapsible Panel Bar

A: Why not just create a composite control?  Something to the effect of.. 2 panels or a label and a panel or whatever suits your needs.  Drawing it wouldn't be all that difficult but seems overly complicated for your desired functionality.  Am I completely missing the mark?


text:
Q: How to compress Tesseract-encoded PDFs while maintaining embedded text from OCR? I've been experimenting with using Tesseract to OCR my PDFs, and it has been mostly successful, particularly with German Fraktur texts (the old style gothic print), which tools like Adobe Acrobat can't recognize properly.
The problem is that the output files from Tesseract are rather large, and I want to compress them after OCRing. However, when I use Ghostscript to compress the files, the embedded OCR text he's messed up. Similarly, if I use ImageMagick, the embedded text is removed. Is there a way around this? Theoretically I could compress before OCRing but that would make the OCR accuracy worse.
Generally speaking, my goal is to have high-quality OCR embedded text in my output PDF files, and have the embedded images be highly compressed so that the files don't take up nearly as much space. I have found that the Adobe Acrobat Pro feature "Save as Other > Reduced Size PDF" highly compresses the images but screws up any OCR'd text. This is true whether the files were OCR'd in Acrobat, or using a tool like Tesseract.
Here's my current workflow, using a sample pdf.
Split PDF into TIFF files
pdftk infile.pdf burst output "temp/page_%03d.pdf"
dpi=130 #this is the dpi of the particular file
parallel convert -verbose -density $dpi "{}" -depth 8 -background white -compress zip "{}.tiff" ::: temp/*.pdf

Run Tesseract on each of the TIFF files (see sample file's output)
language=deu_frak
parallel tesseract {} {} -l $language pdf ::: temp/*.tiff

*

*When I combine the output PDF files with Ghostscript, I get a file like this one, which screws up the embedded text

*When I combine them with PDFtk (e.g. pdftk temp/*.pdf cat output outfile.pdf`), I get a file like this one, which maintains the embedded text but somehow makes the file larger

*And then when I try to compress that file using ImageMagic (e.g. convert -density 130x130 -quality 5 -compress jpeg outfile-pdftk.pdf outfile-pdftk-imagemagick.pdf) it removes the embedded OCR text (output)

It seems that Tesseract doesn't compress the images in the output PDF, which is to be expected - its job is to OCR the files, not compress the output.
For instance, on the initial Tesseract OCR'd files, pdfimages -list temp/page_001.pdf.tiff.pdf produces:
page   num  type   width height color comp bpc  enc interp  object ID x-ppi y-ppi size ratio
--------------------------------------------------------------------------------------------
   1     0 image    1067  1508  rgb     3   8  jpeg   no        11  0   129   130  318K 6.7%

... which indicates that the image object in the PDF isn't exactly stored optimally. It is still in RGB, not black & white. Upon compressing with ImageMagick, by contrast, pdfimages -list gives:
  pdfimages -list outfile-pdftk-imagemagick.pdf
page   num  type   width height color comp bpc  enc interp  object ID x-ppi y-ppi size ratio
--------------------------------------------------------------------------------------------
   1     0 image    1075  1520  gray    1   8  jpeg   no         8  0   130   131 54.0K 3.4%
   1     1 smask    1075  1520  gray    1   8  image  no         8  0   130   131 25.1K 1.6%
   2     2 image    1075  1520  gray    1   8  jpeg   no        22  0   130   131 59.9K 3.8%
   2     3 smask    1075  1520  gray    1   8  image  no        22  0   130   131 25.1K 1.6%
   3     4 image    1075  1520  gray    1   8  jpeg   no        36  0   130   131 45.2K 2.8%
   3     5 smask    1075  1520  gray    1   8  image  no        36  0   130   131 25.1K 1.6%
   4     6 image    1075  1520  gray    1   8  jpeg   no        50  0   130   131 62.8K 3.9%
   4     7 smask    1075  1520  gray    1   8  image  no        50  0   130   131 25.1K 1.6%
   5     8 image    1075  1520  gray    1   8  jpeg   no        64  0   130   131 61.1K 3.8%
   5     9 smask    1075  1520  gray    1   8  image  no        64  0   130   131 25.1K 1.6%
   6    10 image    1075  1520  gray    1   8  jpeg   no        78  0   130   131 63.4K 4.0%
   6    11 smask    1075  1520  gray    1   8  image  no        78  0   130   131 25.1K 1.6%
   7    12 image    1075  1520  gray    1   8  jpeg   no        92  0   130   131 65.1K 4.1%
   7    13 smask    1075  1520  gray    1   8  image  no        92  0   130   131 25.1K 1.6%
   8    14 image    1075  1520  gray    1   8  jpeg   no       106  0   130   131 61.0K 3.8%
   8    15 smask    1075  1520  gray    1   8  image  no       106  0   130   131 25.1K 1.6%
   9    16 image    1075  1520  gray    1   8  jpeg   no       120  0   130   131 66.8K 4.2%
   9    17 smask    1075  1520  gray    1   8  image  no       120  0   130   131 25.1K 1.6%
  10    18 image    1075  1520  gray    1   8  jpeg   no       134  0   130   131 65.6K 4.1%
  10    19 smask    1075  1520  gray    1   8  image  no       134  0   130   131 25.1K 1.6%

As we can see the images take up less space, however the OCR-embedded text was removed and, somehow, the file is less. By comparison, if I take the original file (without OCR-embedded text) and compress it using Adobe Acrobat's "Save As Other > Reduced Size PDF", I get:
  pdfimages -list infile-adobe.pdf
page   num  type   width height color comp bpc  enc interp  object ID x-ppi y-ppi size ratio
--------------------------------------------------------------------------------------------
   1     0 image    1000  1499  gray    1   8  jpx    no        38  0   129   129 78.1K 5.3%
   2     1 image    1000  1499  gray    1   8  jpx    no         3  0   129   129 89.1K 6.1%
   3     2 image    1000  1499  gray    1   8  jpx    no         6  0   129   129 65.6K 4.5%
   4     3 image    1000  1499  gray    1   8  jpx    no         9  0   129   129 97.7K 6.7%
   5     4 image    1000  1499  gray    1   8  jpx    no        12  0   129   129 95.4K 6.5%
   6     5 image    1000  1499  gray    1   8  jpx    no        15  0   129   129 98.7K 6.7%
   7     6 image    1000  1499  gray    1   8  jpx    no        18  0   129   129  102K 6.9%
   8     7 image    1000  1499  gray    1   8  jpx    no        21  0   129   129 94.6K 6.5%
   9     8 image    1000  1499  gray    1   8  jpx    no        24  0   129   129  105K 7.2%
  10     9 image    1000  1499  gray    1   8  jpx    no        27  0   129   129  103K 7.1%

... As we can see, Adobe Acrobat seems to compress images using JPEG2000 (JPX) which isn't available to Ghostscript or ImageMagick due to patent issues.
On the whole, any suggestions on how to compress Tesseract-OCR'd PDF files?


text:
Q: code::blocks linking doesn't work for lib files I just had a fresh new version of Code::Blocks(12.11) and tried to make a glut example project, but the generated code has some linking issues.
The minGW settings are is set to the correct values, since I successfully linked ad compiled a glfw project from *.a files. My problem is the linker just can't handle .lib files for some reason. I always get undefined reference errors, despite of the linking of the correct libraries.
I just don't know what to do/link...

How can I link *.lib files in the new Code::blocks?
IF I cannot, are there any glut binaries in the format of *.a files, or should I build it myself?

A: Finally I found this link, used this package, and did a clean build(rebuild) of the project, instead of Build. Works like a charm!


text:
Q: @ViewChild value is not available in parent? Parent component is:
export class DictionaryComponent implements OnInit, AfterViewInit {
  @ViewChild(ViewModeComponent)
  primarySampleComponent: ViewModeComponent;

   ngAfterViewInit() {
      console.log('Values on ngAfterViewInit():');
      console.log(this.primarySampleComponent.viewMode);

    }

}

Children component is ViewModeComponent:
export class ViewModeComponent {

  public viewMode: mode = 'inline';
  public constructor(
  ) {}

  public switchMode(mode: mode) {
    this.viewMode = mode;
  }
}

Why after changing value this.viewMode in children component I don't receive it value in parent ngAfterViewInit() {}?
Console.log says nothing.
Angular version is 8

A: Use Observables
in Service
private viewMode = new BehaviorSubject(false); // create observable variable
checkMode = this.viewMode.asObservable();

changeMode(falg) {
    this.viewMode.next(falg);
}

In Child Component :
this.viewMode // local variable of Component

public switchMode(mode: mode) {
    this.viewMode = mode;
    this.service.changeMode(mode); // setting value to observable variable
}

in Parent Component :
this.viewMode // local variable of Component
this.service.checkMode.subscribe(response => this.viewMode = response); // get the value

A: You can use an EventEmitter to emit values from your child components
parent.html
<ChildComponent (viewModeEvent)="handleViewModeChange($event)"></ChildCompoment>

child.component.ts
Import {..., Output, EventEmitter } from "@angular/core";

export class ViewModeComponent {

  @Output() viewModeEvent = new EventEmitter<mode>();
  public viewMode: mode = 'inline';

  public constructor(
  ) {}

  public switchMode(mode: mode) {
    this.viewModeEvent.emit(mode)
  }
}

parent.component.ts
handleViewModeChange(args: mode) {
  // gets called everytime there is a viewMode change emitted from child
}

A: You can achieve the same using the EventEmitter. Just make an EventEmitter in the child component and pass the event to the parent component..!
child.component.ts
export class ChildComponnent implements OnInit {

  name: EventEmitter<string> = new EventEmitter<string>();

  ngOnInit() {
    setInterval(() => this.name.emit(new Date().toString()), 1000);
  }

}

parent.component.ts
export class AppComponent implements OnInit {

  @ViewChild('appChild', { static: true }) appChild: ChildComponnent;

  ngOnInit() {
    this.appChild.name.subscribe(console.log);
  }

}

parent.component.html
<app-child #appChild></app-child>
{{(appChild.name | async) | json}}

You can see the live example in the stackblitz here..!


text:
Q: Submit button redirecting to different address So the submit button of this form is supposed to send the data to localhost/mvc/contact/test and redirect to localhost/mvc/contact
at the first click of submit button it works well
Right
but when I click the submit button again its taking me to localhost/mvc/test
Not right
here is the html code of the form <form action="test" method="post" accept-charset="utf-8" class="contact">
when I had this as <form action="contact/test" method="post" accept-charset="utf-8" class="contact"> it first redirected me to localhost/mvc/contact but on second attempt redirected to localhost/mvc/contact/contact/test
Btw it's a simple mvc framework you may check it out on github for more clarity on Leggera @ Github
The above mentioned code is present on view/contact/index.php

A: You can try these things:

*

*You must give the full path to the file like <form action="contact/test/index.html" method="post" accept-charset="utf-8" class="contact">

*In the index file of contact/test you can use <?php header("Location: http://www.example.com/");?>  for redirection.

*Maybe you have given wrong paths to files.

You must give more details for more specific answer


text:
Q: Android Webview on ICS (Ice Cream Sandwich) Webview on ICS looks lile buggy. Below code show nothing on 2.x emulators but half page white screen on ICS emulators. Below layout is for test porpuses. If I put some html to render inside webview on ICS it shows nothing for half page then continue like it has rendered the half but I see only white empty area.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello" />
<WebView
    android:id="@+id/webView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >
</WebView>

</LinearLayout>

Has anybody an idea?

A: I guess you should either make webview fill_parent (or match_parent), or give width and height, im not sure, but guess it will not be very smart "wraping to content" as webview content is difficult to measure.
That said, I have thousands of problems with webview on ICS: No refreshing windows, Hardware acceleration causing all kind of artifacts, problems with iframes, screen flickering, browser crashing on CSS3 animations, etc etc. Most of these problems are new on ICS, while others like Hardware Acceleration are not new, but have worsen noticeabily.

A: I'm encountering the same problem, or at least a very similar one.  What I have is a WebView that is centered horizontally when in landscape and fills the vertical space.  The WebView is being positioned correctly, but it seems like the region of the screen that is actually rendered is aligned to the left side of the screen, but with the same width of the WebView.  This causes only part of the WebView to render with the rest showing as the background color.  So there does seem to be a bug of some kind in 4.0, as it works perfectly fine on the 2.3 and 3.2 devices I've tested it on.


text:
Q: PackageCloud unable to install global packages i was previously using package cloud for work;
i ran curl https://MASTER_TOKEN_GOES_HERE:@packagecloud.io/install/repositories/{privateRepoName}/script.node.sh | bash to set up packagecloud
now that i am not using package cloud i am unable to install any global packages as its only looking for packages within that package cloud repo;
when i try, i get something like: npm ERR! 404  '@aws-amplify/cli@https://packagecloud.io/{privateRepoName}/npm/@aws-amplify/cli/-/cli-4.45.2.tgz' is not in the npm registry.
how do i remove packagecloud from my computer locally.


text:
Q: Passing more than one array to more than one view I'm trying to load a controller wich loads two two different views, and passes a different array to each view.
public function index(){
        $this->load->view('Head');

        $data=$this->DAOPromotor->recuperarPromotor();
        $eventos=$this->DAOEvento->recuperarPromotorEventos();
        $this->load->view('MostrarPromotor', $data);
        $this->load->view('MostrarPromotorEventos', $eventos);
        $this->load->view('Footer');
}

This is my Controller. Now, the first view ("MostrarPromotor') loads just fine, but the second one keeps throwing an Undefined Variable warning. I've used the recuperarPromotorEventos() method on differnt controllers, and it works just fine. I treat the array the same way on both scripts, but it only works in one.
I'm wondering if maybe it's not possible to have two views reciving data at the same time.

A: Found a solution after looking around some more: when you pass an array to a view, it breaks down said array on its different components, using the index names of the array as references. So, if I had this array:
$eventos = array(
   'data1' => 'someData',
   'data2' => 'someMoreData'
);

When I pass that array to a view, the view can access the variables $data1 and $data2, but not the $eventos data. As my original array didn't have any index named eventos, there wasn't any variable called that.
As for my particular problem, the only thing I had to do to fix it was to change the code to this:
public function index(){
    $this->load->view('Head');

    $data=$this->DAOPromotor->recuperarPromotor();
    $eventos["eventos"]=$this->DAOEvento->recuperarPromotorEventos();
    $this->load->view('MostrarPromotor', $data);
    $this->load->view('MostrarPromotorEventos', $eventos);
    $this->load->view('Footer');
}


text:
Q: Query Optimization - Performance Degradation with time I've got a process that inserts about 1 million records a day into a table and it's been doing that for a year. I then have a secondary table that joins to the results table and selects a count of the results grouped by an id and status for the part three months. Everything has been going on fine but the query now is performing extremely slow , I can't seem to figure out what's gone wrong. Could someone point me towards where I'd need to start with to get the performance up.

A: We can think of a table as of a large file on disk. To search some information in the file you need to scan it. This is expensive.
To make the process more efficient, RDBMS builds indexes - data structures, that are usually kept in memory, organised to simplify specific queries and for each row contain references where to find the row within the file. The more rows you have, the larger become indexes.
At some point the indexes become too large to fit into memory and parts of it are swapped into disk. Random access to popular indexes start causing a lot of disk IO operations, because the OS is constantly saving/loading parts of the indexes, and this is much slower than working with just memory.
What to do heavily depends on the data, there are several approaches, but the common idea behind them is to make popular indexes fit into memory again:

*

*you can just add some memory

*you can use smaller datatypes

*you can delete or merge indexes and rewrite queries to use the indexes in a certain way

*you can partition your data and distribute an index among several machines

*...

And make sure you do use indexes, because if a table is rapidly growing, table scans of the whole table will slow down your queries very soon.


text:
Q: Bootstrap popover with a link creates problem upon changing the resolution and zooming In my project we use bootstrap and jquery, the popover function is used to display additional information about records.
The problem is the popover width is generated dynamically , so a column with longtext or varchar set to a high number uses the max-width of popover class i.e that's set 800px at the moment.The project here also has a nav bar , so upon having a record with lots of characters in it , the popover width is set to max and it glitches. The glitches are :-

*

*Zooming in a lot , makes the link/popover flicker , i.e my cursor
keeps changing , the popover comes and goes. Please note that code
snippet linked below is without a nav bar so upon trying a bit , the
popover displays correctly but not with in my project. So this makes
impossible for me to click on the link attached. The cursor just
keeps changing.

*Changing screen size to a phone ( pixel 2 ) or tablet ( ipad pro) , sets the popover function to on click from on hover , was fine on my previous bootstrap file ie the popover displayed onclick for a second then the link opened. But Like i said before when the width of a column is alot it creates an issue.Over here the issue is the popover does not get displayed on clicking the element , nor does why link work.

The code snippet link is code pen
The files used:-
https://drive.google.com/open?id=1hFU_jaHwZk3anw2wwRK7DKyaM0VKQ8hz
https://drive.google.com/open?id=17G9a6LE-x3MRcIsP2FuBsoxJ66NJE-Rs
https://drive.google.com/open?id=1L6BcD_-90S2twjJXv7FXI9655DN_aMbx
https://drive.google.com/open?id=1AMdOYQ878b_CEANGUWAjqOoP6bwpT_t5
https://drive.google.com/open?id=10eJw0JvGMrDLLH07D9ABxVu9YMaOCBf3
I need to know how to make the popover displayed onclick for a second then the link opened for phone/tablet and solve the first glitch.


text:
Q: How can draw the line of linear regression on my original image in MATLAB? I want to draw a red line on the edge of this image, I wanted to do that with the Linear Regression and I've already got the points of the edge and drawn the best line through the points on a graph, but I couldn't find out how to use the information to draw the same line on my original image.

Image = imread('55-1_a.jpg');

imshow(Image)

binary_Image = imbinarize(Image);

[PIC_X, PIC_Y] = size(binary_Image);

imshow(binary_Image)

% i creat a matrix with two columns and PIC_X-1 rows
black_pixel_on_edge = zeros(PIC_Y , 2); % in each row i will save the lowest black point to use it later in the linear regression

 for k = 1 : PIC_Y % i go through the columns of the image
     black_pixel_on_edge(k, 1) = k;

     for k2 = 1000 : 2000% i o through the rows
         if( binary_Image(k2, k) == 0)%if the pixel is black i should save it in my array(WIDTH)

             black_pixel_on_edge(k, 2) = k2;
         end

     end

 end

 %draw all the points from my Matrix
 scatter(black_pixel_on_edge(:,1),black_pixel_on_edge(:,2));
  axis equal tight;

 h1 = lsline;% draw a line with linear regression
 h1.Color = 'r';

%save the data of the red line
 p2 = polyfit(get(h1,'xdata'),get(h1,'ydata'),1);

 Slope_Of_Line = p2(1, 1);
 Hight_Of_Line = p2(1, 2);

 % here i just want to draw the same red line on my original 'Image'


text:
Q: PSQL: select all assets that have all of given list of associated objects ids Suppose we have a standard has and belongs to many association between products and categories
product_categories table consists of product_id and category_id pairs.
We have list of category_id's and need to select all products that belongs to all these categories.
The best approach that came to my mind is to have multiple EXISTS() in where clause conjuncted by AND at programming language level:
SELECT * FROM products p WHERE
EXISTS(SELECT * FROM product_categories pc
   WHERE pc.product_id = p.id AND pc.category_id = {first_id}) AND
EXISTS(SELECT * FROM product_categories pc
   WHERE pc.product_id = p.id AND pc.category_id = {second_id}) AND ...

EXISTS is fast in Postgres 8.4 so no performance issue with this approach.
But I wounder is there any more elegant of doing this type of queries?

A: SELECT * FROM products p WHERE
EXISTS(SELECT * FROM product_categories pc
       WHERE pc.product_id = p.id AND pc.category_id = {first_id})
INTERSECT
SELECT * FROM products p WHERE
EXISTS(SELECT * FROM product_categories pc
       WHERE pc.product_id = p.id AND pc.category_id = {second_id})
INTERSECT
....


text:
Q: ASP.NET Master Page Parser Error I have this directory structure:
[website]
  [folder]
    Default.aspx
  Default.aspx
  Web.config

The Page Directive in the file in [folder] was created by Visual Studio 2010 when I added a new Web Form using Master Page:
<%@ Page Title="" Language="C#" MasterPageFile="~/Page.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="website.folder.Default" %>

When I run this application in the debugger (using localhost), it works fine.
When I push it up to the server (Windows Server 2003 R2), that same page produces a Parser Error on the Page Directive line:

Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: The file '/website/folder/Page.Master' does not exist.
Source Error:
Line 1:  <%@ Page Title="" Language="C#" MasterPageFile="~/Page.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="website.folder.Default" %>
  Line 2:
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1008

What needs to be configured on the server to eliminate this error message?

A: On our server, I used IIS Manager to delete all of the files in the [website] folder, then republished it through Visual Studio 2010.
It seems to be working now.
Clearly, I don't know enough about how the whole IIS system works!


text:
Q: Regex to grab string between a comma and a period I have a string like this
Allen, Mr. William Henry

and I want to grab the 'Mr' part.
I've tried this
[,](.*?)[.]

But this grabs the ', Mr.'
How can I grab only the 'Mr' part?

A: You may capture Mr with a regular TRE regex using regmatches and regexec:
> s <- "Allen, Mr. William Henry"
> m <- regmatches(s, regexec(",\\s*([^.]*)", s))
> m[[1]][2]
[1] "Mr"

Pattern details:

*

*, - comma

*\\s* - zero or more whitespaces

*([^.]*) - Group 1 capturing 0+ characters other than .
See the regex demo.

A: If every string in your data is of the form
"NAME, TITLE. FIRSTNAME(S)
Then you can also use
x <- "Allen, Mr. William Henry"
gsub("(.*),\\s(.*)\\.(.*)", "\\2", x)

A: Or this
s <- "Allen, Mr. William Henry"
sub(".*,\\s{0,}(\\w+)\\..*", "\\1", s)

Logic
.*,       any characters until comma
\\s{0,}   spaces 0 to as many
\\w+      words at least one
\\..*     period followed by any character(s)

the "\\1" keep the pattern within the parenthesis

A: We can use str_extract
library(stringr)
str_extract(s, "\\w+(?=\\.)")
#[1] "Mr"


text:
Q: Xamarin.Android device requirements Does Xamarin.Android have any requirements against the device, like a minimum Android version or for example at least an ARMv7 CPU?

A: Xamarin.Android requires you to build for API Level 4 (Android 1.6) or higher. The supported architectures are x86, armeabi and armeabi-v7a (the same as native Android development)


text:
Q: (Delphi bug) Controls won't remember their position on form I have a (Delphi bug?) that is annoying me for months: in one of my apps I have some controls (tedit, tbutton, etc) on a TPanel. Every time I close the project and reopen it I find the controls moved few pixels up. After 20-30 closings the controls are almost out of the panel so I have to drag them back. Anybody encountered such a problem? How to fix it?
I have Delphi XE.

Update:
Actually I have encountered this in two of my projects. Both involve controls on a TPanel.
If I compile the project the controls, in the exe, the controls are at the wrong position also.
I have a TEdit that is aligned to the top (of the TPanel) and its bottom is anchored to the bottom. The bottom will also 'forget' its correct position and move to the top.

Update:
Bug confirmed. It appears when the user changes the Bevel properties of the panel!

A: This issue is reported in Quality Central #106320 for Delphi XE2, in June 2012.
Its status is still 'need feedback', there is no sample project, but it looks as if has to do with descendant forms.
I suggest that once you have determined the exact location that you want the components to be in, you adjust their position in the FormCreate.
Then, in designmode you can just 'approximately' correct the position quickly, knowing that they will come out right at run-time.
Robs suggestions also sound worth a try.
BTW Should you manage to make a sample project, maybe others can then determine if it is fixed in later versions.

A: There is evidently some conflict between anchors and position, possibly involving form inheritance. I expect it has something to do with the order that various positioning constraints are applied in, as well as when the parent control's border size or margin gets updated. Besides, aligning to the top and anchoring the bottom sounds like a recipe for problems. Instead, consider clearing the alignment setting and anchoring the top and sides; it should give the same effect. Alternatively, put a spacing control (e.g., a TShape) aligned to the bottom of the panel, and then align the edit control to the client area, which should give the same effect as anchoring to the bottom.
Nonetheless, this should be easy to work around. In your form's OnCreate event handler, move your components to their correct positions by calling SetBounds on them. To stop further movement during the development cycle, you should probably clear the anchors, and then re-set them at run time.

A: It happened to me also in D7. I found that whenever I have open design time forms and change the resolution of desktop or minimize the IDE the bottom aligned controls are get pushed downwards, sometimes out of the form.
In order to prevent that kind of I use nowadays the same way HTML pages are designed.
Each of my forms have a layout that are divided with tPanels (like  or  tags used in html) tPanels are aligned according to their design.
Might not be the same problem but I think the solution I've found might work for you too.


text:
Q: How do I translate this sentence and keep the translation free of any reference to the person's gender? In Italian, I can use the following sentence without revealing the gender of the person I am talking of.

L'utente preferisce mantenere protetta la propria identità. (The user prefers to keep [possessive adjective] own identity protected.)

While the grammar gender of propria and identità is feminine, they aren't refering to a female person; so, I can say propria identità when referring (for example) to my aunt, my mother, or my uncle.
How do I translate that sentence and still keeping it gender-free? Do I need to replace propria with her/his own or is there a better way not to make explicit the gender of the person I am speaking of, including changing the sentence from active to passive?
Notice that I could use the plural, in Italian, and make the sentence the following one.

Gli utenti preferiscono mantenere protetta la propria identità. (Users prefer to keep their own identity protect.)

The sentence would have a different meaning, though, since it is generically referring to all or most the users, not specifically to a user.

A: Their is the pronoun you're looking for.

The user prefers to keep their identity protected.

They isn't necessary a plural pronoun. It could also be used as singular, meaning he/she.
Singular they - Wikipedia


text:
Q: Inserting images in LaTeX spacing problem \documentclass[12pt,openany]{book}
\usepackage{amsmath,polynom,amssymb,venndiagram,mathtools,graphicx,fancyhdr,wrapfig}
\usepackage[rightcaption]{sidecap}
\graphicspath{ {./spm/} }
\usepackage[margin=3cm]{geometry}
.
.
.
.
\begin{enumerate}

    \setcounter{equation}{0}
    \item [(a)]
    \begin{align}
    y-x&=7 \\
    y-x^2&=1
    \end{align}
    (1)-(2):
    \begin{align*}
    x^2-x-6&=0 \\
    (x-3)(x+2)&=0 \\
    x=3 \  \  \text{or} \ \  x=-2
        \end{align*}

    Substituting    $x=3$ and $x=-2$ into (1) , we get $y=10$ and $y=5$ respectively.
    $\therefore$ The points of intersection between the lines $y-x=7$ and $y-x^2=1$ are \\ \ (3 , 10) and (-2 , 5).
    \item[(b)]

\includegraphics[width=\textwidth]{geogebra-export}
    \item[(c)]
    The height that the crossbar in Figure A must be raised 5 feet higher to achieve the position in Figure B. The coordinates of the ends of the rope are (-3,10) and (3,10).

\end{enumerate}
.
.
..
.
.
.
.
.

The spaces between the lines are abnormally large......it wasnt like this before i inserted the picture    may i know whats the problem?


text:
Q: Why am I getting an access denied error on the second file (a text file) for mysqldump using the tab option? I am trying to backup a mysql db on Ubuntu using the --tab option using the following:
mysqldump -umy_user my_database -p --tab=/path/to/backup/dir

I enter the password and then get the following error:

mysqldump: Got error: 1045: Access denied for user
  'my_user'@'localhost' (using password: YES) when executing
  'SELECT INTO OUTFILE'

The password is okay, and File is in the list from show privileges for the user. Additionally it looks like I can produce .sql files, but it dies on the first .txt file. Also a mysqldump to just a plain .sql file works.
After running the command and seeing the error, if I ls the backup dir I see one sql file that looks correct of structure, but it seems to have died trying to write the first txt file of table contents.
I created an empty dir for the dump ahead of time. I tried chmoding it to 777 and before that I tried chowning it to mysql:mysql.

A: While this works on my end for a problem with the exact same symptoms, this apparently does not solve the OP's problem. I'm leaving this here for reference and for other people who get this error.
Problem:
You will get this error if your MySQL user does not have FILE PRIVILEGE_TYPE, which is separate from file system permissions and not listed by show privileges (see documentation below). You can check all of your user's permissions by running the following query after connecting using the mysql command.
SHOW GRANTS FOR CURRENT_USER();

Or, enter this handy one-liner into your shell.
echo 'SHOW GRANTS FOR CURRENT_USER();' | mysql -u my_user -p

If you have these permissions, you will get a response containing GRANT FILE or GRANT ALL ON *.*, on a line resembling the following.
GRANT FILE ON *.* TO 'user'@'host' IDENTIFIED BY PASSWORD '*hash'

If you do not receive a line like this, you will need to grant the user this permission.
Alternately, you can check that your user has these permissions in the USER_PRIVILEGES table of the information_scheme database.
Solution:
To permission your user, log in as a sufficiently-privileged user, and run the following command.
GRANT FILE ON *.* to 'my_user'@'localhost';

Documentation:
From the mysqldump documentation for --tab=path, -T path:

Note
This option should be used only when mysqldump is run on the same machine as the mysqld server. You must have the FILE privilege, and the server must have permission to write files in the directory that you specify.

A: Looks like apparmor is causing this.
Since the mysql user has the correct permission, and you tried setting the file permissions and owners, the thing that is left is something other than mysql or file permissions. On Ubuntu this would be apparmor.
To verify that mysqld is effected, try:
> sudo aa-status

...
2 processes are in enforce mode.
/usr/sbin/mysqld (1182)
...

Once verified, you have to tell apparmor to allow mysqld to write to your backup dir. The permissions are stored in: /etc/apparmor.d/usr.sbin.mysqld
...
/usr/sbin/mysqld {
    ....
    /run/mysqld/mysqld.sock w,
    /path/to/backup/dir/** w,
}

You can add write permission to the directory you want to backup as in the example above.
And just for reference, here is the directory ownership that was required in addition to the apparmor changes:
chown -R mysql:mysql /path/to/backup/dir

As a final note that sheds a little more light on why the first file was written and then errored out, the ownership of the dumped files was not uniform. For whatever reason the sql files were owned by the shell user running the command and the txt files were owned by mysql:
> ls -al /path/to/backup/dir
...
-rw-r--r-- 1 my_user my_user  1596 Feb  2 01:24 wp_terms.sql
-rw-rw-rw- 1 mysql   mysql    5117 Feb  2 01:24 wp_terms.txt
...

A: mysqldump runs SELECT INTO OUTFILE to dump the data as CSV or tab-separated values
(when --tab is used).
A note near the end of the manual page of SELECT INTO OUTFILE says:

If the secure_file_priv system variable is set to a nonempty directory name, the file to be written must be located in that directory.

"By default, the variable secure_file_priv is empty" -- says the official documentation, but sometimes the bundlers use customized configurations.
Check the value of this variable on your system using:
SELECT @secure_file_priv;

If it is not NULL then you have to either reset it or use the path it contains to dump your files.


text:
Q: Cordova / Phonegap: Disable bounce only for header and footer I'm using this property inside the config.xml to disabe the bouncing of the webview (iOS):
<preference name="DisallowOverscroll" value="true" />

This works as expected. But what if I only want to disable this bouncing for my header and footer? They are fixed at the top and bottom of my app, so I don't want them to bounce. But it would be more like a native feeling (especially for lists) when the inner container still has this bounce effect.

*

*Is there any way to achieve this? My header and my footer should not bounce, but my inner container should bounce.

*And is there also an iOS / Android cross compatible way?

A: Just keep using
<preference name="DisallowOverscroll" value="true" />

and in your CSS use the following code on your scrollable wrapper:
-webkit-overflow-scrolling: touch;

It will give this bouncy effect to the scrollable content.
overflow: hidden on your header and footer to avoid the user to scroll on it and overflow:scroll on your content plus the css webkit scrolling touch.
Here is a JSFiddle LIVE DEMO:
http://jsfiddle.net/mPfeQ/
Note:You should test it on a mobile device (it won't render on a computer)

A: Hi simple add these CSS rules to list or scrolable elemet
  overflow: scroll;
  -webkit-overflow-scrolling: touch;

-webkit-overflow-scrolling: touch; will give bounce effect to scrollling area (native look)


text:
Q: Is there any other proper way to have same control on two different tabs in C# form? Here is what I have tried and is working. But I want to whether this is proper or is there a better option or way to do the same
private void tabs_SelectedIndexChanged(object sender, EventArgs e)
{
    TabControl control = (TabControl)sender;
    if(control.SelectedIndex == 3  || control.SelectedIndex == 0)
    {
        button1.Parent = control.SelectedTab;
        zonalarealabel.Parent = control.SelectedTab;
        pictureBox3.Parent = control.SelectedTab;

    }
}

A: If you don't mind coupling your code to your user interface then your approach is valid. However, I think the better option is to create a user control that raises events handled by the selected tab. The user control would appear on tabs 0 and 3 at all times. The advantage of this is that you don't need to modify your SelectedIndexChanged event handler should you want these buttons to appear on a future tab. There are many ways to approach this problem, but given the very narrow functional requirements you shared, it's a better design to relegate these buttons to a user control rather than re-parent them at runtime.


text:
Q: How to convolution integration(Duhamel Integration) by python? Hi~ I'm studying about structural dynamics.
I want to make a code about Duhamel Integration which is kind of Convoution Integration.
If the initial conditions are y(0)=0 and y'(0)=0,
Duhamel Integration is like this.
enter image description here
Using Ti Nspire
I solved this problem with my Ti Npire softwere. The result is like that.
enter image description here
Its response(y) of t=1 is -0.006238
Using python(sympy)
I tried to solve this problem using by Python(Jupyter Notebook).
But I couldn't solve the problem.
I wrote the code like this.
from sympy import *

t, tau=symbols('t, tau')

m=6938.78
k=379259
wn=sqrt(k/m)
wd=wn*sqrt(1-0.05**2)

eq1=(900*sin(5.3*tau))
eq2=exp(-0.05*wn*(t-tau))
eq3=sin(wd*(t-tau))

y0=1/(m*wd)*integrate(eq1*eq2*eq3,(tau,0,t))
y0

But I couldn't get the result.
enter image description here
Is there other way to solve this problem?
enter image description here

A: Use the unevaluated Integral and then substitute in a value for t and use the doit method:
...
>>> y0=1/(m*wd)*Integral(eq1*eq2*eq3,(tau,0,t))
>>> y0.subs(t,1).doit()
-0.00623772329557205

To see the symbolic result before substituting t=1 you need to help SymPy a little by expanding your integrand; I also evaluate floats to show only 3 digits from sake of simplicity:
>>> integrate((eq1*eq2*eq3).expand(),(tau,0,t)).simplify().replace(
... lambda x:x.is_Float, lambda x: x.n(3))
245.0*sin(5.3*t) - 36.1*cos(5.3*t) - 174.0*exp(-0.37*t)*sin(7.38*t) + 36.1*exp(-0.37*t)*cos(7.38*t)