text:
Q: destructor when stopping idhttp.get ( indy, delphi) My application can download one picture from every url in memo1.
It uses idhttp.get and has a skipbutton. After skip it downloads the next picture.
Q1: Do you have code to put into the destructor and what is the  code for " terminate" and "waitfor"?
I found this on another website:
destructor thread.destroy;
begin
try
Terminate;
If HTTP.Connected then HTTP.Disconnect;
finally
WaitFor;
FreeAndNil(HTTP);
end;
inherited;
end;

Q2: How do I call the destructor and make it work?
Q3: Do you have hints (especially security concerns) and additional lines of  code?
the code of my application:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, IdBaseComponent, IdComponent, IdTCPConnection,
  IdTCPClient, IdHTTP;

type
       thread = class
  public
      Constructor Create; overload;
      Destructor  Destroy; override;
  end;

  TForm1 = class(TForm)
    IdHTTP1: TIdHTTP;
    Memo1: TMemo;
    Memo2: TMemo;
    Memo3: TMemo;
    startbutton: TButton;
    skipbutton: TButton;

    procedure startbuttonClick(Sender: TObject);
    procedure skipbuttonClick(Sender: TObject);
    procedure IdHTTP1Work(Sender: TObject; AWorkMode: TWorkMode;
      const AWorkCount: Integer);

         end;
var
  Form1: TForm1;
     http: tidhttp;
     s: boolean;
implementation

{$R *.dfm}

            constructor thread.Create;
begin
      HTTP := TIdHTTP.Create(nil);
      inherited ;
end;

           destructor thread.destroy;
begin
try

If HTTP.Connected then HTTP.Disconnect;
finally
FreeAndNil(HTTP);
end;
inherited;
end;

procedure TForm1.startbuttonClick(Sender: TObject);
var
i: integer;
  fs : TFileStream ;
begin
for i:= 0 to memo1.lines.count-1 do begin
s:= false;
   fs := TFileStream.Create(inttostr(i)+'abc.jpg', fmCreate);
   http:= idhttp1;
   try
   try
HTTP.Get(memo1.lines[i],fs);
memo2.Lines.add(memo1.Lines[i]);
except
on E: Exception do
begin
memo3.lines.add(' ha ha ha not working   '+syserrormessage(getlasterror));
end;
end;
finally
fs.free;
end;
end;

  end;

procedure TForm1.skipbuttonClick(Sender: TObject);
    begin
s:=true;
end;

procedure TForm1.IdHTTP1Work(Sender: TObject; AWorkMode: TWorkMode;
  const AWorkCount: Integer);
begin
application.ProcessMessages;

     if s = true then
http.Disconnect;

end;

end.

A: Since your are using IdHttp from the GUI (= main thread) and Indy is blocking, you have two options: a) use IdAntifreeze in combination with messages (just drop the component on the form), b) use threads.
Do NOT use Application.Processmessages as it will lead to strange side effects.
now to answer your questions:
Q1: the code you found on the internet implemented solution b) so this is not applicable for your current code
Q2: same as Q1
Q3 : here is a version that correctly implements solution a)
This code is still not 100% perfect as it does not implement logic for disabling/enabling the starttransfer and skiptransfer buttons (I leave that as an exercise for you :) ).
unit Unit16;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, IdAntiFreezeBase, IdAntiFreeze, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdHTTP;

const
  WM_TRANSFER = WM_USER + 1;

type
  TForm1 = class(TForm)
    IdHTTP1: TIdHTTP;
    IdAntiFreeze1: TIdAntiFreeze;
    Memo1: TMemo;
    Btn_start: TButton;
    Btn_skip: TButton;
    Memo2: TMemo;
    procedure IdHTTP1Work(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
    procedure Btn_startClick(Sender: TObject);
    procedure Btn_skipClick(Sender: TObject);
  private
    { Private declarations }
    Transferring : Boolean;
    UrlIndex : Integer;
    procedure NextTransfer(var msg : TMessage); message WM_TRANSFER;
    procedure StartTransfer;
    procedure DoTransfer;
    procedure SkipTransfer;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}
procedure TForm1.NextTransfer(var msg: TMessage);
begin
 DoTransfer;
end;

procedure TForm1.SkipTransfer;
begin
 Transferring := false;
end;

procedure TForm1.StartTransfer;
begin
 UrlIndex := 0;
 DoTransfer;
end;

procedure TForm1.DoTransfer;

var
  Url : String;
  Stream : TStringStream;

begin
 if UrlIndex < Memo1.Lines.Count then
  begin
   Url := Memo1.Lines[UrlIndex];
   Memo2.Lines.Add(Format('getting data from URL: %s', [Url]));
   Inc(UrlIndex);
   Transferring := True;
   try
    Stream := TStringStream.Create;
    try
     IdHttp1.Get(Url, Stream);
     Memo2.Lines.Add(Format('Data: "%s"',[Stream.DataString]));
    finally
     Stream.Free;
    end;
   except
    on E: Exception do
     begin
      Memo2.Lines.Add(Format('error during transfer: %s', [E.Message]));
     end;
   end;
   Transferring := False;
   PostMessage(Handle, WM_TRANSFER, 0, 0);
  end;
end;

procedure TForm1.Btn_startClick(Sender: TObject);
begin
 Memo2.Lines.Add('starting transfer');
 StartTransfer;
end;

procedure TForm1.Btn_skipClick(Sender: TObject);
begin
 Memo2.Lines.Add('skipping current transfer');
 SkipTransfer;
end;

procedure TForm1.IdHTTP1Work(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
begin
  Memo2.Lines.Add('work event');
 if not Transferring and (AWorkMode = wmRead) then
 try
  Memo2.Lines.Add('disconnecting peer');
  IdHttp1.Disconnect;
 except
 end;
end;

end.

DFM file:
object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 290
  ClientWidth = 707
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  PixelsPerInch = 96
  TextHeight = 13
  object Memo1: TMemo
    Left = 92
    Top = 12
    Width = 213
    Height = 257
    Lines.Strings = (
      'http://stackoverflow.com'
      'http://www.google.com'
      'http://www.hardocp.com'
      '')
    TabOrder = 0
    WordWrap = False
  end
  object Btn_start: TButton
    Left = 8
    Top = 128
    Width = 75
    Height = 25
    Caption = 'Btn_start'
    TabOrder = 1
    OnClick = Btn_startClick
  end
  object Btn_skip: TButton
    Left = 8
    Top = 159
    Width = 75
    Height = 25
    Caption = 'Btn_skip'
    TabOrder = 2
    OnClick = Btn_skipClick
  end
  object Memo2: TMemo
    Left = 320
    Top = 12
    Width = 373
    Height = 257
    TabOrder = 3
    WordWrap = False
  end
  object IdHTTP1: TIdHTTP
    OnWork = IdHTTP1Work
    AllowCookies = True
    ProxyParams.BasicAuthentication = False
    ProxyParams.ProxyPort = 0
    Request.ContentLength = -1
    Request.ContentRangeEnd = -1
    Request.ContentRangeStart = -1
    Request.ContentRangeInstanceLength = -1
    Request.Accept = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
    Request.BasicAuthentication = False
    Request.UserAgent = 'Mozilla/3.0 (compatible; Indy Library)'
    Request.Ranges.Units = 'bytes'
    Request.Ranges = <>
    HTTPOptions = [hoForceEncodeParams]
    Left = 24
    Top = 16
  end
  object IdAntiFreeze1: TIdAntiFreeze
    Left = 16
    Top = 72
  end
end


text:
Q: Keyboard lagging in some applications but not all My problem is that keyboard input is very slow in some applications. At the same time other applications work just fine.
I recently installed Joplin note taking app and typing is next to impossible because it takes several seconds for each character to appear when I type. Every other app works just fine. This same problem happens sometimes using Hyper terminal and it used to happen with 1Password but not anymore for some time.
I have looked for an answer but with no help. I have checked the settings - Universal Access - Typing Assist settings but with no help. I have also changed my USB mouse dongle to another port, no help. Tried to work with the laptop keyboard without USB keyboard.
The problem appears with and without Bluetooth keyboard and/or mouse.
My setting is:

*

*Lenovo X1 gen8 laptop with External Lenovo monitor

*Ubuntu 20.04.3 LTS

*System language is English but keyboard layout is Finnish (winkeys)

*GNOME version 3.36.8

redpajama_set_name: RedPajamaStackExchange


text:
Q: Node.js: File Upload API and JSON return I'm totally new to node.js, so I'm trying to find a way to create an image-file upload API, which returns a json after the process is finished.
I'm using the Watson Developer Cloud (Visual Recognition), which returns a JSON after finishing the processing task.
I hope you have tips & ideas on how to get this project done. I thought about using the express library?
This is my code, which processes a local image right now and logs the JSON result to the console. I want to be able to upload an image via api and return the JSON, after the process is done.
Thanks a lot!
Code to process Image:
var watson = require('watson-developer-cloud')
var fs = require('fs')

//initialisng the service
var visual_recognition = watson.visual_recognition({
    api_key : '<Enter API Key here>',
    version: 'v3',
    version_date: '2016-05-20'
});

var params = {
    images_file: fs.createReadStream('./resources/image.jpg')
};

visual_recognition.classify(params, function(err, res){
    if(err)
        console.log(err);
    else
        console.log(JSON.stringify(res, null, 2));
});

First Try for the upload Server (Thanks to @Eduard for the tip):
var express = require('express')
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

var app = express()

app.post('/upload', upload.single('avatar'), function (req, res, next) {
    if(err){
        console.log("Error uploading file");
    }
    console.log(req.file);
    console.log(req.body);

    res.status(204).end();
    console.log("Upload success");
})

app.listen(3000, function () {
  console.log('Upload Server listening on port 3000');
});

Unfortunately this returns a 'ReferenceError: err is not defined[..]', while uploading an image with this simple Python Script:
import requests
url='http://localhost:3000/upload'
imageURL = 'ImageURL'

with open(imageURL, 'rb') as image:
    filename = image.name
    files = {'avatar': (image)}
    r = requests.request(method="POST", url=url, files=files)
    print(r.text);
    print(r.status_code)

Sidenote:
Why do I want to use a Node.js Server?
Unfortunately the Watson-Developer-Cloud Python SDK is not supported on my hardware (a robot) and using the API endpoint with a direct upload from python causes trouble due to the old python Version on the hardware (SNI Problems)

A: At first, you will need ExpressJS to easily catch the POST, and secondly, you should be using Multer, as it is the easiest to work with when it comes to file uploading in my opinion.
var express = require('express')
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

var app = express()

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})

Example taken from Multer repo
You have more info about checking the file itself here: https://github.com/expressjs/multer


text:
Q: Image captions/annotations in lightbox Is there any JS script that adds a possibility to add a facebook-like captions into an image opened using some kind of lightbox script?
Example:
I have a little image thumbnail with a photo of my family. I click on that photo. Lightbox pop up appears with original size of my photo and when I mouseover someone of my family facebook-like caption shows up with his/her name.
Thanks a lot!

A: I found a solution: http://code.google.com/p/jquery-image-annotate/


text:
Q: Model HABTM Model Referencing Original Model I have a Team model that is HABTM Match and when I pull the data for a specific Team, I ask for the related Teams for those Matches, but Cake only returns the data for the original Team.
How can I get all the Teams (the opponent) for that Match without looping through the results and pulling them that way?
I am having the same issue with the Team HABTM Player association as well.  When I pull a Player, Cake will not return any of the associated Players (teammates) for the linked Team.
My schema:
CREATE TABLE IF NOT EXISTS `matches` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `tournament_id` int(10) unsigned NOT NULL,
  `name` varchar(255) NOT NULL DEFAULT '',
  `created` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `tournament_id` (`tournament_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ;

CREATE TABLE IF NOT EXISTS `matches_teams` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `match_id` int(10) unsigned NOT NULL,
  `team_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `match_id` (`match_id`,`team_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ;

CREATE TABLE IF NOT EXISTS `players` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ;

CREATE TABLE IF NOT EXISTS `players_teams` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `player_id` int(10) unsigned NOT NULL,
  `team_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `player_id` (`player_id`,`team_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ;

CREATE TABLE IF NOT EXISTS `teams` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `tournament_id` int(10) unsigned NOT NULL,
  `name` varchar(255) NOT NULL,
  `seed` smallint(2) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `tournament_id` (`tournament_id`),
  KEY `seed` (`seed`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ;

My query:
$this->Team->recursive = 3;
$team = $this->Team->read(null, $id);
$this->set('team', $team);

I have also tried:
$this->Team->contain(array(
    'Match' => array(
        'Team',
    ),
));
$team = $this->Team->read(null, $id);
$this->set('team', $team);

The results ($team):
array (size=4)
  'Team' =>
    array (size=5)
      ... team data ...

  'Match' =>
    array (size=2)
      0 =>
        array (size=9)
          ... match data ...

          'MatchesTeam' =>
            array (size=3)
              'id' => string '1' (length=1)
              'match_id' => string '1' (length=1)
              'team_id' => string '1' (length=1)

        // there should be an array for 'Team' here
        // that contains the opponent team

      1 =>
        ... more match data with same missing 'Team' array ...

    ... other related models ...


text:
Q: Pushing to array which is in an array of objects {
    "_id": {
        "$oid": "5bd8fa85bfbf4e27d86c73eb"
    },
    "status": {
        "iat": 1540947201356,
        "exp": 1540950801358
    },
    "code": "1cmTwKC7",
    "mongoDate": {
        "$date": "2018-10-31T00:41:56.016Z"
    },
    "form": [
        {
            "type": "tf",
            "text": "The first form ever. Welcome...",
            "opts": [],
            "responses": []
        }
    ],
    "updateDate": "October 30th, 2018, 8:47 PM",
    "date": "2019",
    "notes": "notes for this lecture.",
    "name": "TEST",
    "user": {
        "$oid": "5bcfd8a8da59d54024172d5c"
    },
    "course": {
        "$oid": "5bd8fa6cbfbf4e27d86c73ea"
    },
    "__v": 1
}

I have a document which is of the form above. I wanted to push a value into the responses array of a document which is in the form array. Im not sure how to do this using mongoose for MongoDB, and havent been able to find a direct answer. Thanks in advance.


text:
Q: Solving a system of equations I'm trying to prove the existence of a solution to the system of equations
$$c_i = \gamma x_i + (1-\gamma) \frac{x_i^2}{\sum_{j=1}^\infty x_j}$$
for $i\in\{1,2,....\}$ where $\sum c_i=1$.
I am also trying to prove that the implicit function $\Phi(\{c_i\})$ that solves for the $x_i$ is continuous.
Edit: I forgot to mention that $\gamma \in (0,1)$.


text:
Q: Assigning categories based on cell containing a string I would like to fill in the category cell of this example
Date        Description    Debit    Category

15/07/2011  Farmer Smith    10

based on an other worksheet containing mapping values like this :
Farmer  | Groceries

I think I have to use a VLOOKUP but it doens't seem to "search" for the term ( farmer ) inside the Description cell, how do I tell my VLOOKUP to search the cell if it CONTAINS the first value and the mapping table and return the second column ( groceries ) .
Thank you

A: Regarding OpenOffice Calc: AFAIK you can't modify the behaviour of VLOOKUP so it uses a CONTAINS check to determine the matching row. But if the relevant word is the the first one in the Description column in every case, you could "prepare" the lookupvalue (the first argument of the VLOOKUP function) so it just uses the first word to look for. A solution may look like this:
=VLOOKUP(LEFT(B2, FIND(" ", B2)-1), $Sheet2.$A$2:$B$4, 2, 0)

(assuming `Sheet2.A2:B4 contains the lookup array). Split on multiple lines:
=VLOOKUP(
    LEFT(
        B2,
        FIND(
            " ",
            B2
        ) -1),
    $Sheet2.$A$2:$B$4,
    2,
    0
)

The first word of the Description column is determined using LEFT and FIND.
So, with the following category table:

you would get the following result:


text:
Q: get email header and only selected text in outlook I am using Office 2007 and Windows 7. With macro below, I extract text from email and open document in Chrome. But, what I want is not to extract whole text, but just selected text and the email header (To, CC, Subject). Is this possible ?
Sub OpenInBrowser()

    Dim BrowserLocation As String
    Dim AlwaysConvert As Boolean
    Dim EvaluateHTML As Boolean

    '=============Set your variables in the section below==========================
    'The default settings are optimized for viewing newsletters and receiving
    'messages with HTML forms or animated gif-files embedded in the message.

    'Set the location of the executable of the browser you want to use.
    BrowserLocation = "C:\Program Files\Google\Chrome\Application\chrome.exe"

    'When set to True, we will let Outlook convert the message to HTML.
    'The message will be opened in the configured browser just as it
    'appears in Outlook.
    'Standard value: False
    AlwaysConvert = False

    'When set to True, we will look for embedded resources in the HTML message and
    'determine whether Outlook should convert the message or whether we can strip
    'the HTML directly. When set to False, we will always strip the HTML and ignore
    'embedded resources.
    'For this setting to take effect, AlwaysConvert must be set to False.
    'Standard value: True
    EvaluateHTML = True

    '=======Don't modify the code below unless you know what you are doing=========

    'Get the user's TempFolder to store the item in
    Dim FSO As Object, TmpFolder As Object
    Set FSO = CreateObject("scripting.filesystemobject")
    Set TempFolder = FSO.GetSpecialFolder(2)

    'Get all selected items
    Dim MyOlNamespace As Outlook.NameSpace
    Set MyOlNamespace = Application.GetNamespace("MAPI")
    Set MyOlSelection = Application.ActiveExplorer.Selection

    'Make sure at least one item is selected
    If MyOlSelection.Count = 0 Then
       Response = MsgBox("Please select an item first", vbExclamation, MyApplName)
       Exit Sub
    End If

    'Make sure only one item is selected
    If MyOlSelection.Count > 1 Then
       Response = MsgBox("Please select only one item", vbExclamation, MyApplName)
       Exit Sub
    End If

    'Retrieve the selected item
    Set MyselectedItem = MyOlSelection.Item(1)

    'construct the filename
    Dim FileName As String
    strname = "www_howto-outlook_com"
    FileName = TempFolder & "\" & strname & ".htm"

    'If the message is in HTML format we directly capture the HTML from the message
    'to construct our htm-file. This will allow us to capture as many HTML elements
    'as possible. If it is a different format, or if the HTML mail includes embedded
    'resources we let Outlook convert it to HTML.
    Dim OutlookConvert As Boolean
    OutlookConvert = True

    If MyselectedItem.BodyFormat = olFormatHTML And AlwaysConvert = False Then
        Dim rawHTML As String
        rawHTML = MyselectedItem.HTMLBody

        If EvaluateHTML = False Then
            OutlookConvert = False
        Else
            'Check if there are embedded resources in the message.
            'If it does, we let Outlook convert the message.
            If InStr(UCase(rawHTML), UCase("src=""cid:")) = 0 Then
                OutlookConvert = False
            End If
        End If
    End If

    'Write the temp-file
    If OutlookConvert = False Then
            'create the htm-file in the temp folder and write the HTML code to it
            Set objFile = FSO.CreateTextFile(FileName, True)
            objFile.Write "" & rawHTML
            objFile.Close
            Set objFile = Nothing
    Else
            'let Outlook convert the message and save the selected item
            'as htm to the temp folder
            MyselectedItem.SaveAs FileName, olHTML
    End If

    'open the saved item in the browser
    Shell BrowserLocation & " " & FileName, vbNormalFocus

    'Cleanup
    Set FSO = Nothing

    Set MyOlNamespace = Nothing
    Set MyOlSelection = Nothing
    Set MyselectedItem = Nothing

End Sub

Edit:
Here's my macro which extracts email header (From, To, Subject ...) and selected text in email - but selected text is raw text, without HTML.
Sub OpenInBrowser()

Dim BrowserLocation As String
Dim AlwaysConvert As Boolean
Dim EvaluateHTML As Boolean

'=============Set your variables in the section below==========================
'The default settings are optimized for viewing newsletters and receiving
'messages with HTML forms or animated gif-files embedded in the message.

'Set the location of the executable of the browser you want to use.
'Standard value: "C:\Program Files\Internet Explorer\iexplore.exe"
BrowserLocation = "C:\Program Files\Google\Chrome\Application\chrome.exe"

'When set to True, we will let Outlook convert the message to HTML.
'The message will be opened in the configured browser just as it
'appears in Outlook.
'Standard value: False
AlwaysConvert = False

'When set to True, we will look for embedded resources in the HTML message and
'determine whether Outlook should convert the message or whether we can strip
'the HTML directly. When set to False, we will always strip the HTML and ignore
'embedded resources.
'For this setting to take effect, AlwaysConvert must be set to False.
'Standard value: True
EvaluateHTML = True

'=======Don't modify the code below unless you know what you are doing=========

'Get the user's TempFolder to store the item in
Dim FSO As Object, TmpFolder As Object
Set FSO = CreateObject("scripting.filesystemobject")
Set TempFolder = FSO.GetSpecialFolder(2)

'Get all selected items
Dim MyOlNamespace As Outlook.NameSpace
Set MyOlNamespace = Application.GetNamespace("MAPI")
Set MyOlSelection = Application.ActiveExplorer.Selection

'Make sure at least one item is selected
If MyOlSelection.Count = 0 Then
   Response = MsgBox("Please select an item first", vbExclamation, MyApplName)
   Exit Sub
End If

'Make sure only one item is selected
If MyOlSelection.Count > 1 Then
   Response = MsgBox("Please select only one item", vbExclamation, MyApplName)
   Exit Sub
End If

'Retrieve the selected item
Set MyselectedItem = MyOlSelection.Item(1)

'construct the filename
Dim FileName As String
strname = "header_printing"
FileName = TempFolder & "\" & strname & ".htm"

'If the message is in HTML format we directly capture the HTML from the message
'to construct our htm-file. This will allow us to capture as many HTML elements
'as possible. If it is a different format, or if the HTML mail includes embedded
'resources we let Outlook convert it to HTML.
Dim OutlookConvert As Boolean
OutlookConvert = True

 Dim msg As Outlook.MailItem
 Dim insp As Outlook.Inspector
 Dim rng As String

 Set insp = Application.ActiveInspector

 If insp.CurrentItem.Class = olMail Then
 Set msg = insp.CurrentItem

 If insp.EditorType = olEditorWord Then ' outlook 2013
     Set hed = msg.GetInspector.WordEditor
     Set word = hed.Application
     rng = word.Selection.Text
 End If
 End If

If MyselectedItem.BodyFormat = olFormatHTML And AlwaysConvert = False Then
    Dim rawHTML As String

    Dim textBody
    If rng = "" Or Len(rng) < 3 Then 'sometimes one letter is selected by it self
        textBody = MyselectedItem.HTMLBody
    Else
        textBody = rng
    End If

    'Email header - to, cc, bcc, subject and selected text from body
    rawHTML = "" & MyselectedItem.Subject & "
" & _
    MyselectedItem.SenderName & " [" & MyselectedItem.SenderEmailAddress & "]" & "
" & _
    "Sent: " & MyselectedItem.SentOn & "
" & _
    "From: " & MyselectedItem.SenderName & " [" & MyselectedItem.SenderEmailAddress & "]
" & _
    "To: " & MyselectedItem.To & "
" & _
    "Subject: " & MyselectedItem.Subject & "
" & _
    "
" & _
    textBody

    If EvaluateHTML = False Then
        OutlookConvert = False
    Else
        'Check if there are embedded resources in the message.
        'If it does, we let Outlook convert the message.
        If InStr(UCase(rawHTML), UCase("src=""cid:")) = 0 Then
            OutlookConvert = False
        End If
    End If
End If

'Write the temp-file
If OutlookConvert = False Then
        'create the htm-file in the temp folder and write the HTML code to it
        Set objFile = FSO.CreateTextFile(FileName, True)

        objFile.Write "" & rawHTML
        objFile.Close
        Set objFile = Nothing
Else
        'let Outlook convert the message and save the selected item
        'as htm to the temp folder
        MyselectedItem.SaveAs FileName, olHTML
End If

'open the saved item in the browser
Shell BrowserLocation & " " & FileName, vbNormalFocus

'Cleanup
Set FSO = Nothing

Set MyOlNamespace = Nothing
Set MyOlSelection = Nothing
Set MyselectedItem = Nothing

End Sub

A: Open Outlook and the Visual Basic Editor.  Click F2 to display the Object Browser.  Scroll down the left hand list (Classes) to find and select MailItem.  The right hand list will display all the properties and methods of a MailItem.  Many, such as BCC, Body and CC, will be obvious others you will have to look up.
Click on CC. Underneath the two lists you will see: "Property CC As String".
You have not asked for Recipients but scroll down and select Recipients.  Now you will see "Property Recipients as Recipients" with the second "Recipients" underlined and coloured green.  You can click the second Recipients but I doubt you will find it helpful until you are more familiar with these properties.  Look up "Recipients" in Help and you will get an example of how to add a recipient.  To access the existing recipients you treat Recipients as an array (its actually a collection).
CC, To and Subject are all strings so are easy to access.
HtmlBody is a string so is easy to access (as you have) but it is an Html string with tags, attributes, element values and so on.  Extracting the particular text you seek may be a little challenging.  If you explain what you are after, I may be able to offer further help.


text:
Q: Induction to prove that for all integers n ≥ 1.
It says we add $(n + 1)^2$ on both sides of this relation and get ......
Then on the left side, it only says (n+1) over the Σ and not (n+1)^2 . Do you folks know why?

A: $$(n+1)^2+\sum_{k=1}^n k^2=\sum_{k=1}^{n+1} k^2$$


text:
Q: Manipulating data in SQL Lite db I am new to SQL Lite db manipulation.
I wrote a DB handling class from this tutorial SQL Lite tutorial
public class DatabaseHandler extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "PersonalAssistant";

// TASKS table name
private static final String TABLE_TASKS = "TASKS";

// Tasks Table Columns names
private static final String KEY_ID = "id";
private static final String UUID = "uuid";
private static final String ACTION = "action";
private static final String TIME = "time";
private static final String DAY = "day";
private static final String RECEPIENTS = "receipients";
private static final String BODY = "body";
private static final String SUBJECT = "subject";
private static final String STATUS = "status";

public DatabaseHandler(Context context)
{
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_TASKS + "("
            + KEY_ID + " INTEGER PRIMARY KEY autoincrement," +UUID + " TEXT,"+ ACTION + " TEXT,"
            + TIME + " TEXT," + DAY + " TEXT," + RECEPIENTS+  " TEXT," +BODY + " TEXT," + " TEXT," +SUBJECT + " TEXT,"  +SUBJECT + " TEXT," +")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_TASKS);

    // Create tables again
    onCreate(db);
}
// add task to table
public void addTask(Task task)
{
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(ACTION, task.getAction());

    values.put(UUID, task.getUuid());

    values.put(TIME, task.getTime());
    values.put(DAY, task.getDay());
    values.put(RECEPIENTS, task.getReceipients());
    values.put(BODY, task.getBody());
    values.put(SUBJECT, task.getSubject());
    values.put(STATUS, task.getStatus());

    // Inserting Row
    db.insert(TABLE_TASKS, null, values);
    db.close(); // Closing database connection
}        .............

My question is how do i call this class for db manipulation from my application activities?
How do i instatiate my class from other activities which are not extending SQLiteOpenHelper?
I can define the class and methods as static but is it a good practice?

A: You can do so just by instantiating object from your DatabaseHandler class like this:
DabataseHandler dbHandler;
dbHandler = new DatabaseHandler(getApplicationContext());

And then you can use methods in your Databasehandler class using dbHandler.
For example:
Task myTask = new Task();
dbHandler.addTask(myTask);

A: I frequently use a Singleton pattern to access the Sqlite DB from all the different activities.
My own accepted answer to the question below describe the approach providing code as well:
How can I access my SQLite Database in a static way?


text:
Q: Subclassing NSDictionary not working I have a dictionary that I read from a plist. I want to create a subclass of NSDictionary to implement something like the following, so that I can avoid using @"key name" everywhere in my source code:
@interface MyDict{
}
-(NSString*) textString;
@end

@implementation MyDict
-(NSString*) textString {
    return [self objectForKey:@"textString"];
}
@end

In my other method:
MyDict *d = ... // something i read from plist
NSString *str = [d textString];

When I call the method, the app crashes because of "unrecognized selector textString". What is wrong here?

A: Just assigning an NSDictionary to a MyDict pointer doesn't make it a MyDict instance.
One way you can do this would be to create a category to add your method to NSDictionary. See http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocCategories.html#//apple_ref/doc/uid/TP30001163-CH20-SW1 for info.

A: Your class has no superclass. Also, the conventional wisdom is that it's very difficult to subclass NSDictionary because it is an class cluster. You don't actually get an NSDictionary back when you:
NSDictionary * myDict = [NSDictionary dictionary];

You get a private subclass (NSCFDictionary in this case).
You might want to try defining your own dictionary keys, the way Apple does:
NSString * const MyWonderfulUnicornKey = @"MyWonderfulUnicornKey";


text:
Q: ASP.NET dotnet -ef database update Im following a tutorial on adding individual authentication in ASP.NET via the following link https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-3.0&tabs=netcore-cli
In part of the tutorial it says to run database migrations using the following CLI:
dotnet ef database update

Im trying to run this code in terminal but I can't seem to make it work as the command cannot find the database. The dotnet documentation for this command isn't very helpful so I'm wondering if someone could explain how this command works/how to run it on my Visual Studio WebApp project with a database called "app.db".

A: You can try specifying the context in the command like so?
dotnet ef database update -c MyDbContextName -e Development

I quite frequently run EF database migrations using the Package Manager Console rather than the CLI - so I'm not 100% familiar with it.
Each time I've had an error it's either because I was running the command without selecting the correct project first (where the project had only one context defined), or because there were multiple contexts available and it should be specified in the command which context I'm running the command against.


text:
Q: how to search and find multiple string from a predifined list to another list in python I'm quite new to python. I'm looking for a solution for search a list and finding the data.
I googled but couldnt find anything specific to my code. i tried find, in ,set it doesnt seem to work.
I'm trying to search and match mutiple string  in a predifined list in another list (it's actually a resoponse from a serial port )
This is my code
responsetocheck = "replyid, ID,ID,transmitid"

datafromport= "replyid, ID, timestamp,sometherinfo,someotherinfo1,ID,transmitid"

I have to compare and find the entire responsetocheck and return true if all the strings are matching with the responsetocheck.
I tried these below given options
if (responsetocheck  in datafromport)  # it's not finding the data

if (set(responsetocheck) <= set(datafromport) )  # returns True even if 2- 3 values
                                                 # are matching - the reverse way of
                                                 # checking just returns true though
                                                 # if just one matches.

responsetocheck[0] in datafromport [0] # and the respective index's : getting
                                       # out of range error

 if all(word in data for word in response) # doesnt seem to work as well

The options might have some syntax error. I've listed down just for letting you know of the options that I had used.

A: If I understand you correctly you have the varibles responsetocheck and datafrom ports that both contains a string representing a comma separated list of words that you want to check. In that case you need to make your strings into python lists before doing the comparison. Like this:
responsetocheck = responsetocheck.replace(' ','').split(',')
datafromport = datafromport.replace(' ', '').split(',')

You now have two lists that look like this:
['replyid', 'ID', 'ID', 'transmitid'] #responsetocheck
['replyid', 'ID', 'timestamp', 'sometherinfo', 'someotherinfo1', 'ID', 'transmitid'] # datafromport

Then you have to iterate through each word in the responsetocheck list and check if it is found in the datafromport list. The following code should give you the results you want (If I've understood you correctly):
all(s in datafromport for s in responsetocheck)


text:
Q: is a page redirect to most current article bad from an seo perspective? I have navigation at the top of my site that links to news/
The news is always paginated, one article per page, with the ability to navigate to the next or previous article.
I would like the default article to be the second-to-last most current article.  So if there are 10 articles, when the user clicks on news/, they are redirected to news/9 with 302 redirect code.
From an SEO perspective, is it bad to be constantly redirecting like this?  Would it be better to change the link in the top navigation to instead link directly to news/9, and keep changing that everytime there is a new article instead?

A: Search engines expect a given piece of content to have a canonical URL. It's OK to have any number of URLs to a single page but use a canonical URL.
Sop no matter what redirect you have, add a canonical URL and search engine will take care of any mess.
302 redirects are for this. Use it.


text:
Q: Is it possible to insert a batch of messages in Artemis JMS I am working on a Java application which receives a list of messages and then inserts them in a queue. Is it possible to directly insert a list of messages in my Artemis JMS server (a kind of batch insert)? Or must I insert them one by one?

A: Using the JMS API you can create a "transacted" session, send a batch of messages, and then call commit() on the session. From the point of view of the application it seems like messages are being sent one-by-one since send() is called for every message. However, the most time consuming work only happens when commit() is called which only happens once per batch. This is often done as a performance optimization especially for persistent messages to avoid the repeated blocking that happens on individual, non-transacted sends. Using transactions for batching purposes is discussed in the "Tuning JMS" section of the ActiveMQ Artemis performance tuning documentation.


text:
Q: Not able to run nodejs project on google app engine I have just started google app engine with nodejs. I have created a local project that works fine on my machine. And If I hit
http://localhost:7000/services/user/getuser
it returns a json object.
I have deployed the same project on google app engine using
gcloud app deploy

Now when I hit
http://help-coin.appspot.com/services/user/getuser
it is showing
Error: Server Error

The server encountered a temporary error and could not complete your request.
Please try again in 30 seconds.

I have checked the logs on server
Load controllers from path '/app/app/services' non recursive.

--------make-runnable-output--------

undefined

------------------------------------

Up and running on port 7000

Loading controller 'UserService.js'.

No error on the server side. What is this issue? Am I missing something?
Here is the project that I have deployed https://github.com/ermarkar/nodejs-typescript-sample

A: Your app must listen to 8080, not 7000 or any else port.
See this.

Listening to port 8080
The App Engine front end will route incoming requests to the appropriate module on port 8080. You must be sure that your application code is listening on 8080.


text:
Q: Applying css isolation for body tag in blazor I want to update the body tag of the page by updating it through a razor component's CSS file(isolation).
I have a razor component. now I want to update the body tag of this page. so the first thing I tried was updating the body tag through CSS file of the razor component like below.
body {
    background-color: red !important;
}

The above did not work, next thing I kept the body tag in style tag of the razor component like below.
<style>
    body{
        background-color: #FFFFFF;
    }
</style>

which did work. Just want to understand why CSS isolation did not work for this.
Note: <link href="{ProjectName}.styles.css" rel="stylesheet" /> is already present in the head tag of _host.cshtml file.

A: Try adding "::deep" before the CSS class in the style sheet. so it will be:
 ::deep body {
    background-color: red;
}


text:
Q: Fetch data only once per React component I have a simple component that fetches data and only then displays it:
class MyComponent extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            loaded: false
            stuff: null
        };
    }

    componentDidMount() {
        // load stuff
        fetch( { path: '/load/stuff' } ).then( stuff => {
            this.setState({
                loaded: true,
                stuff: stuff
            });
        } );
    }

    render() {
        if ( !this.state.loaded ) {
            // not loaded yet
            return false;
        }

        // display component based on loaded stuff
        return (
            <SomeControl>
                { this.state.stuff.map( ( item, index ) =>

items with stuff

                ) }
            </SomeControl>
        );
    }
}

Each instance of MyComponent loads the same data from the same URL and I need to somehow store it to avoid duplicate requests to the server.
For example, if I have 10 MyComponent on page - there should be just one request (1 fetch).
My question is what's the correct way to store such data? Should I use static variable? Or I need to use two different components?
Thanks for advice!

A: For people trying to figure it out using functional component.
If you only want to fetch the data on mount then you can add an empty array as attribute to useEffect
So it would be :
useEffect( () => { yourFetch and set }, []) //Empty array for deps.

A: You should rather consider using state management library like redux, where you can store all the application state and the components who need data can subscribe to. You can call fetch just one time maybe in the root component of the app and all 10 instances of your component can subscribe to state.

A: If you want to simulate the single fetch call with using react only. Then You can use Provider Consumer API from react context API. There you can make only one api call in provider and can use the data in your components.
const YourContext = React.createContext({});//instead of blacnk object you can have array also depending on your data type of response
const { Provider, Consumer } = YourContext
class ProviderComponent extends React.Component {
   componentDidMount() {
     //make your api call here and and set the value in state
      fetch("your/url").then((res) => {
         this.setState({
           value: res,
         })
       })

   }
   render()  {
     <Provider value={this.state.value}>
       {this.props.children}
     </Provider>
   }
}

export {
 Provider,
 Consumer,
}

At some top level you can wrap your Page component inside Provider. Like this
<Provider>
   <YourParentComponent />
</Provider>

In your components where you want to use your data. You can something like this kind of setup

import { Consumer } from "path to the file having definition of provider and consumer"

<Consumer>
{stuff => <SomeControl>
                { stuff.map( ( item, index ) =>

items with stuff

                ) }
            </SomeControl>
}
</Consumer>

The more convenient way is to use some kind of state manager like redux or mobx. You can explore those options also. You can read about Contexts here
link to context react website

Note: This is psuedo code. for exact implementation , refer the link
  mentioned above

A: If you want to avoid using redux or some kind of state management library, you can import a file which does the fetching for you.  Something along these lines.  Essentially the cache is stored within the fetcher.js file.  When you import the file, it's not actually imported as separate code every time, so the cache variable is consistent between imports.  On the first request, the cache is set to the Promise; on followup requests the Promise is just returned.

// fetcher.js
let cache = null;

export default function makeRequest() {
  if (!cache) {
    cache = fetch({
      path: '/load/stuff'
    });
  }

  return cache;
}

// index.js
import fetcher from './fetcher.js';

class MyComponent extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            loaded: false
            stuff: null
        };
    }

    componentDidMount() {
        // load stuff
        fetcher().then( stuff => {
            this.setState({
                loaded: true,
                stuff: stuff
            });
        } );
    }

    render() {
        if ( !this.state.loaded ) {
            // not loaded yet
            return false;
        }

        // display component based on loaded stuff
        return (
            <SomeControl>
                { this.state.stuff.map( ( item, index ) =>

items with stuff

                ) }
            </SomeControl>
        );
    }
}

A: You can use something like the following code to join active requests into one promise:
const f = (cache) => (o) => {
    const cached = cache.get(o.path);
    if (cached) {
        return cached;
    }
    const p = fetch(o.path).then((result) => {
        cache.delete(o.path);
        return result;
    });
    cache.set(o.path, p);
    return p;
};
export default f(new Map());//use Map as caching

A: If your use case suggests that you may have 10 of these components on the page, then I think your second option is the answer - two components. One component for fetching data and rendering children based on the data, and the second component to receive data and render it.
This is the basis for "smart" and "dumb" components. Smart components know how to fetch data and perform operations with those data, while dumb components simply render data given to them. It seems to me that the component you've specified above is too smart for its own good.


text:
Q: myModel.save() => rejected promise with status 201 When I call myModel.save(), in one of my controllers, to insert a new record into the store I get back a promise with isRejected: true.
The reason object has the following attributes:
readyState: 4,
status: 201,
statusText: "created"
The object is created properly in my backend REST service. In fact, if I put the transitionToRoute in the catch(), instead of the then(), everything would appear to be just fine.
What's going on here?

A: You need to return the object back with your request.  This is particularly important because the server should provide an id for that newly created record.  Without an id there is no definitive way of updating and being sure you're updating the correct record.  The format should follow the same format if you were to find the model.
IE:
{
  type: {
    id:12312,
    property:'value',
    otherProperty:'value'
  }
}


text:
Q: Pandas groupby to expanding to list (numpy array) I have a DataFrame that can be produced using this Python code:
import pandas as pd

df = pd.DataFrame({'visit': [1] * 6 + [2] * 6,
                   'time': [t for t in range(6)] * 2,
                   'observations': [o for o in range(12)]})

The following code enables me to reformat the data as desired:
dflist = []
for v_ in df.visit.unique():
    for t_ in df.time[df.visit == v_]:
        dflist.append([df[(df.visit == v_) & (df.time <= t_)].groupby('visit')['observations'].apply(list)])

pd.DataFrame(pd.concat([df[0] for df in dflist], axis=0))

However this is extremely slow.
I have tried using .expanding(), however, this will only return scalars whereas I would like list (or numpy array).
I would appreciate any help in vectorizing or otherwise optimizing this procedure.
Thanks

A: Fortunately, in pandas 1.1.0 and newer, expanding produces an iterable which can be used to use take advantage of the faster grouping, but produce non-scaler data like lists:
new_df = pd.DataFrame({
    'observations':
        [list(x) for x in df.groupby('visit')['observations'].expanding()]
}, index=df['visit'])

new_df:
               observations
visit
1                       [0]
1                    [0, 1]
1                 [0, 1, 2]
1              [0, 1, 2, 3]
1           [0, 1, 2, 3, 4]
1        [0, 1, 2, 3, 4, 5]
2                       [6]
2                    [6, 7]
2                 [6, 7, 8]
2              [6, 7, 8, 9]
2          [6, 7, 8, 9, 10]
2      [6, 7, 8, 9, 10, 11]

Timing via %timeit:
Setup:
import pandas as pd
df = pd.DataFrame({'visit': [1] * 6 + [2] * 6,
                   'time': [t for t in range(6)] * 2,
                   'observations': [o for o in range(12)]})

Original:
def fn():
    dflist = []
    for v_ in df.visit.unique():
        for t_ in df.time[df.visit == v_]:
            dflist.append([
                df[(df.visit == v_) & (df.time <= t_)]
                    .groupby('visit')['observations'].apply(list)
            ])

    return pd.DataFrame(pd.concat([df[0] for df in dflist], axis=0))

%timeit fn()
13 ms ± 692 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

List comprehension with expanding  (~13x faster on this sample):
def fn2():
    return pd.DataFrame({
        'observations':
            [list(x) for x in df.groupby('visit')['observations'].expanding()]
    }, index=df['visit'])

%timeit fn2()
967 µs ± 57.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Sanity Check:
fn().eq(fn2()).all(axis=None)  # True

The double apply approach by @Quixotic22 (~3.4x faster than the original ~3.9x slower than comprehension + expanding):
def fn3():
    return (df.
            set_index('visit')['observations'].
            apply(lambda x: [x]).
            reset_index().groupby('visit')['observations'].
            apply(lambda x: x.cumsum()))

%timeit fn3()
3.78 ms ± 1.07 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

*Note this approach only produces a series of observations, does not include the visit as the index.
fn().eq(fn3()).all(axis=None)  # False

A: Looks like a good solution has been provided but dropping this here as a viable alternative.
(df.
 set_index('visit')['observations'].
 apply(lambda x: [x]).
 reset_index().groupby('visit')['observations'].
 apply(lambda x: x.cumsum())
 )


text:
Q: Unexpected '=' in R when adding header for API connection I'm trying to access an API using the R code supplied by the API developer.
response <- VERB("GET", url, add_headers(x_rapidapi-key =
'9f70422103msh84418664e8696a3p1e3243jsndda4f4f72b69', x_rapidapi-host = 'call-of-duty-modern-
warfare.p.rapidapi.com', '), content_type("application/octet-stream"))

But i get an error regarding an unexpected '=' on add_headers, i'm running the code in RStudio. Any help is appreciated.

A: there are some mistakes in the R snippets provided by RapidAPI. Perhaps you already figure it out but I will add here the corrected snippet:
library(httr)
library(jsonlite)

url <- "YOUR_URL_WITH_ENDPOINT"

response <- VERB("GET", url,
                 add_headers("X-RapidAPI-Key" = 'YOUR_API_KEY'),
                 content_type("application/octet-stream"),
                 encode = 'json')

Robject <- jsonlite::fromJSON(content(response, "text"))
head(Robject$response)

Three things to notice:

*

*in the add_header function there is an extra ' that should be removed.

*the correct header field should be X-RapidAPI-Key not x_rapidapi-key

*as spotted by @MrFlick, you need to put the headers field in quotations.


text:
Q: Linux - transfer all files modified after a specific date to a new harddrive I recently had my second hard-drive of the past semester begin to fail on me and become unable to ghost to a new drive. I still had the first hd that failed so we ghosted that drive but now I need to get all the files and things that have changed since the date of the first ghosting (first failed hd -> second failed hd) onto the new drive (all files on second failed hd since a date -> third working hd). Is there an easy way to script this in the linux terminal or use another program?
I've looked into using the following commands but they haven't been successful and fail after the first few folders have been archived:
find . -type f -mtime -58 |xargs tar --no-recursion -czvf allmodified.tgz

tar czvf allmodified.tgz `find . -type f -mtime -58`

The find code works and locates all the files on the drive I need but I still can't find a way to get them to archive with file structure so that I can unpack the files on the new drive (third working hd) and they will be preserved where they were in the past 2 months.
I'm not the best at describing my problems so if you have confusion please ask questions and I'll do my best to answer them.
Any hints help, thank you so much!

A: They probably fail because you haven't safeguarded against whitespace in filenames in your second example. The invocation is a bit different:
find . -type f -mtime -58 -print0 | tar -czvf allmodified.tar.gz --null -T -

Here, find outputs file paths terminated by NUL characters. They are piped to tar, which reads input from stdin (-T -) delimited by null (--null). The --no-recursion isn't necessary since you will not include directories themselves in your tarball.
See also: GNU tar 1.27: 6.3 Reading Names from a File
You could then extract the archive from the same directory you took it, and it'd place the files in the directories they belong to. Note that tar will overwrite existing files upon extraction. To prevent that, use the --skip-old-files option.

As for your second example, it will fail if a file or path contains whitespace, because tar sees the two files foo bar and baz (which find outputs) as three, i.e. tar foo bar baz. The proper way to deal with this is to pipe the output of find with -print0 to the next command, if that command has a switch to read from NUL-delimited input (which most GNU utilities do).


text:
Q: Formatting my basic tex report with specific spacing and font settings Ok so I am configuring the settings of my tex file before starting my (mathematical) report and am going through my basic template and removing all packages I don't need and believe I have the very crux of it below (if I don't need some of them please let me know!).
Anyway, I have strict settings for my report, these are:
"Use the following margins: 33mm top margin,
38mm bottom margin, 26mm left margin, 20mm right margin. The text should be justified and
typed in BLACK using TIMES ROMAN font (or similar font if not possible) with 12 point
font on 2-point space (single space is acceptable if 2-point space is not possible). Each
paragraph should be indented 5 spaces. Do not leave extra space between paragraphs."
I have set the margins using the geometry package, but I do not know how to change the font or make it justified (I believe it is already justified by default, but am unsure of the font settings). Also, how do I use 2-point spacing and 5 space paragraph indenting?
Thank you for your help!
\documentclass[a4paper,oneside,12pt]{report}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% PACKAGES & SETTINGS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\usepackage[english]{babel} % formatting rules for the English language
\usepackage[T1]{fontenc} % proper formatting for accented characters and non-standard characters such as pipelines
\usepackage{lmodern} % font formatting
\usepackage{float} % allow floating environments such as figures
\usepackage{amsmath} % math eqn formatting
\usepackage{amssymb} % math fonts
\usepackage[top=33mm, bottom=38mm, left=26mm, right=20mm]{geometry} % page layout

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% DOCUMENT
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{document}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% TITLE PAGE
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\title{title here}
\author{author details}
\date{\today}

\maketitle

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% START OF REPORT
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\end{document}

A: I would try something like this:
\documentclass[a4paper,oneside,12pt]{report}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% PACKAGES & SETTINGS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\usepackage[english]{babel} % formatting rules for the English language
\usepackage[T1]{fontenc} % proper formatting for accented characters and non-standard characters such as pipelines
\usepackage{mathptmx}% fot a font which looks like Times New Roman (serif/roman)
%\usepackage{tgtermes}% an altternative
\usepackage[scaled=.90]{helvet}% for a font which looks like Helvetica, scaled to match TNR (sans)
%\usepackage{tgheros}% an altternative
\usepackage{courier}% for a font which looks like Courier (typewriter/monospaced)
%\usepackage{tgcursor}% an altternative
\usepackage{float} % allow floating environments such as figures
\usepackage{amsmath} % math eqn formatting
\usepackage{amssymb} % math fonts
\usepackage[top=33mm, bottom=38mm, left=26mm, right=20mm]{geometry} % page layout
\setlength{\parindent}{5ex}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% DOCUMENT
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\begin{document}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% TITLE PAGE
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\title{title here}
\author{author details}
\date{\today}

\maketitle

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% START OF REPORT
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\end{document}

This will not use Times New Roman itself as that is not included in TeX Live, being a commercial font, but standard substitutions will be used. The commented lines are alternative substitute fonts from the TeX Gyre family. See which you prefer or which look most like TNR to you.
If you have TNR itself, you can use it if you wish. However, you must either use XeLaTeX/LuaLaTeX rather than (pdf)LaTeX, or you must find or generate suitable support files for it. Moreover, the latter is only really an option if you have the font in type1 format or, for pdfLaTeX, truetype format or the licence permits conversion. It you want to know how to generate support files, let me know. I'm assuming there's no reason to in this case since the rules explicitly permit substitution.
The paragraph indentation is trickier. What, you wonder, do they mean by 'space'? This is not obvious in TeX. If they mean the space between words, that is not fixed but varies to get good line breaks etc. Setting it to 5ex seems not entirely unreasonable. This is equivalent to 5 times the nominal width of the letter 'x'. This 'looks about right' to me but see what you think.
Note that it is recommended to specify american or british or whatever for babel rather than english because different versions default to different options. You might also pass this to the class so that any package which can use the option will get it.


text:
Q: Does JRuby not have MemoryImageSource in awt.Image? Using: jruby 1.7.4 (1.9.3p392) 2013-05-16 2390d3b on Java HotSpot(TM) Server VM 1.7.0_76-b13 +indy [linux-i386]
When I try to use memory image source, which is in java.awt.Image, I get an "uninitialized constant" error. If I explicitly do
import java.awt.Image.MemoryImageSource

Then I get "undefined method `MemoryImageSource' for Java::JavaAwt::Image:Class
".  Does JRuby just not support this class for some reason?  Or, is MemoryImageSource somehow not in 1.7?
Edit: I wrote a quick Java test:
import java.awt.image.MemoryImageSource;
class HelloWorldApp {
    public static void main(String[] args) {
        MemoryImageSource ms;
        System.out.println("Hello World! I can find MemoryImageSource"); // Display the string.
    }
}

And I get no problems finding MemoryImageSource, so it seems like the problem is JRuby.
java -version
java version "1.7.0_76"
Java(TM) SE Runtime Environment (build 1.7.0_76-b13)
Java HotSpot(TM) Server VM (build 24.76-b04, mixed mode)

Edit:
Realized it's not clear that other Java aspects work fine in JRuby (I can create a JFrame and draw little squares on it with a JPanel, for example).
Edit:
Maybe the problem is with how I'm trying to import MemoryImageSource? When I write a Java class that uses MemoryImageSource, I can access it from JRuby just fine (just not MemoryImageSource directly).  For now, it's a decent workaround because my java returns the Image I created from MemoryImageSource without Ruby complaining.
I am still curious how I went wrong, though.

A: you just did something completely different (watch for proper casing) :
java_import java.awt.Image.MemoryImageSource first resolves
java.awt.Image which in your case (unfortunately) exists and than tries to call the MemoryImageSource method on the Java class
what you're after is java_import java.awt.image.MemoryImageSource thus JRuby assumes java.awt.image is a package and looks for a class under it


text:
Q: Multiply two host variables in embedded SQL for PostgreSQL I have problem multiplying two host variables in embedded SQL for PostgreSQL.
The SQL-query is big but I have cut out the part that doesn't work.
Declaration:
EXEC SQL BEGIN DECLARE SECTION;
int var1;
int var2;
EXEC SQL END DECLARE SECTION;

Code:
CASE WHEN product_id = :var1 THEN :var1 * :var2
                             ELSE 0 END

The compilation works but I get the following error message at execution:

Errcode: -400
Errmsg:  operator is not unique: unknown * unknown on line 1394

If I change the code to
CASE WHEN product_id = :var1 THEN 1 * :var2
                             ELSE 0 END

or
CASE WHEN product_id = :var1 THEN product_id * :var2
                             ELSE 0 END

or
CASE WHEN product_id = :var1 THEN :var1 * (1 * :var2)
                             ELSE 0 END

it works.
Is it possible to multiply two host variables? If not, is there any workaround? The last code example above works but I would like a solution that is not as ugly.

A: Try casting to integer:
CASE WHEN product_id = :var1 THEN :var1::integer * :var2::integer
                         ELSE 0 END

The error

operator is not unique...

can mostly be fixed by casting to the expected type


text:
Q: How to cancel NSBlockOperation I have a long running loop I want to run in the background with an NSOperation. I'd like to use a block:
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
   while(/* not canceled*/){
      //do something...
   }
}];

The question is, how to I check to see if it's canceled. The block doesn't take any arguments, and operation is nil at the time it's captured by the block. Is there no way to cancel block operations?

A: Doh. Dear future googlers: of course operation is nil when copied by the block, but it doesn't have to be copied. It can be qualified with __block like so:
//THIS MIGHT LEAK! See the update below.
__block NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
   while( ! [operation isCancelled]){
      //do something...
   }
}];

UPDATE:
Upon further meditation, it occurs to me that this will create a retain cycle under ARC. In ARC, I believe __block storage is retained. If so, we're in trouble, because NSBlockOperation also keeps a strong references to the passed in block, which now has a strong reference to the operation, which has a strong reference to the passed in block, which…
It's a little less elegant, but using an explicit weak reference should break the cycle:
NSBlockOperation *operation = [[NSBlockOperation alloc] init];
__weak NSBlockOperation *weakOperation = operation;
[operation addExecutionBlock:^{
   while( ! [weakOperation isCancelled]){
      //do something...
   }
}];

Anyone that has ideas for a more elegant solution, please comment!

A: To reinforce jemmons answer.  WWDC 2012 session 211 - Building Concurent User Interfaces (33 mins in)
NSOperationQueue* myQueue = [[NSOperationQueue alloc] init];
NSBlockOperation* myOp = [[NSBlockOperation alloc] init];

// Make a weak reference to avoid a retain cycle
__weak NSBlockOperation* myWeakOp = myOp;

[myOp addExecutionBlock:^{
    for (int i = 0; i < 10000; i++) {
        if ([myWeakOp isCancelled]) break;
        precessData(i);
    }
}];
[myQueue addOperation:myOp];

A: With Swift 5, you can create a cancellable BlockOperation with addExecutionBlock(_:). addExecutionBlock(_:) has the following declaration:
func addExecutionBlock(_ block: @escaping () -> Void)

Adds the specified block to the receiver's list of blocks to perform.

The example below shows how to implement addExecutionBlock(_:):
let blockOperation = BlockOperation()

blockOperation.addExecutionBlock({ [unowned blockOperation] in
    for i in 0 ..< 10000 {
        if blockOperation.isCancelled {
            print("Cancelled")
            return // or break
        }
        print(i)
    }
})

Note that, in order to prevent a retain cycle between the BlockOperation instance and its execution block, you have to use a capture list with a weak or unowned reference to blockOperation inside the execution block.

The following Playground code shows how to cancel a BlockOperation subclass instance and check that there is no retain cycle between it and its execution block:
import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

class TestBlockOperation: BlockOperation {
    deinit {
        print("No retain cycle")
    }
}

do {
    let queue = OperationQueue()

    let blockOperation = TestBlockOperation()
    blockOperation.addExecutionBlock({ [unowned blockOperation] in
        for i in 0 ..< 10000 {
            if blockOperation.isCancelled {
                print("Cancelled")
                return // or break
            }
            print(i)
        }
    })

    queue.addOperation(blockOperation)

    Thread.sleep(forTimeInterval: 0.5)
    blockOperation.cancel()
}

This prints:
0
1
2
3
...
Cancelled
No retain cycle

A: I wanted to have cancellable blocks that my UICollectionViewController could easily cancel once cells were scrolled off the screen. The blocks are not doing network ops, they are doing image operations (resizing, cropping etc). The blocks themselves need to have a reference to check if their op has been cancelled, and none of the other answers (at the time I wrote this) provided that.
Here's what worked for me (Swift 3) - making blocks that take a weak ref to the BlockOperation, then wrapping them in the BlockOperation block itself:
    public extension OperationQueue {
        func addCancellableBlock(_ block: @escaping (BlockOperation?)->Void) -> BlockOperation {
            let op = BlockOperation.init()
            weak var opWeak = op
            op.addExecutionBlock {
                block(opWeak)
            }
            self.addOperation(op)
            return op
        }
    }

Using it in my UICollectionViewController:
var ops = [IndexPath:Weak<BlockOperation>]()

    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        ...
        ops[indexPath] = Weak(value: DispatchQueues.concurrentQueue.addCancellableBlock({ (op) in
            cell.setup(obj: photoObj, cellsize: cellsize)
        }))
    }

    func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        if let weakOp = ops[indexPath], let op: BlockOperation = weakOp.value {
            NSLog("GCV: CANCELLING OP FOR INDEXPATH \(indexPath)")
            op.cancel()
        }
    }

Completing the picture:
    class Weak<T: AnyObject> {
        weak var value : T?
        init (value: T) {
            self.value = value
        }
    }


text:
Q: Selected state for custom UITableViewCell using drawrect (with animation) I'm trying to determine the best way to use drawRect for something like the cell in the image below and still animate between selected and non-selected states:

I've seen a few suggestions, with the most advanced seeming being this one:
But it still seems pretty hacky, so I'm not quite sold on it. Feels like there has to be a cleaner way.
I suppose another option could be having two different UIViews, one that drew the un-selected state, and one that drew the selected state (the latter probably being a subclass of the former with a slightly different draw rect.) Then you could add both of those to contentView, and hide/fade between them? That wouldn't support edit mode or accessories very well, but maybe that's ok?
Or perhaps you follow that same method, but stick them into backgroundView and selectedBackgroundView respectively?
Or if one respects this cell structure, perhaps you truly only draw the background (the tan I guess in the image above) into the backgroundView, a darker tan into the selectedBackgroundView, and draw everything else in a subclass uiview added to contentView? But then you are drawing in a couple different places (creating your own contexts I would imagine), and still would have issues with the text/decorative images not animating, assuming those changed color.
So what is the answer here?


text:
Q: 'Folder' already locked by 'Folder' I have this very VERY annoying issue where I'm attempting to merge our trunk into my branch for some updates. I have been doing this on a daily basis but almost every single day I get the following error:
Error - 'D:\Code\Website' is already locked via 'D:\Code\Website'.

Only very randomly does this error not happen and I am able to successfully merge trunk back into the branch. However, all day I've been trying to get the latest from the trunk without success. I have looked high and low for answers to this issue.. SO, Google, random forums on the internet... etc. I'm hoping someone can shed some light on why this might be happening.
This is what I've already tried:

*

*Run "Clean up" on every single folder within the directory.

*Checked for "lock" file in .svn directory - doesn't exist.

*Opened wc.db file and checked WC_LOCK table - nothing in there.

*Disabled anti-virus.

*Disabled IIS.

*Checked out a fresh copy of the branch.

*Updated TortoiseSVN

*Completed uninstalled and re-installed TortoiseSVN with latest MSI from TortoiseSVN.net (1.7.10.23359, SVN 1.7.7).

I am able to Update the branch and Commit it.. there has never been an issue with that. It's just Merging trunk back in that is causing me issues. No one else on the team seems to have this problem (with this branch, or any others). They can freely check the branch out.. merge trunk in and commit it without issues.
I am using TortoiseSVN. Any help you guys/gals have would be fantastic!
EDIT: Also, a Test Merge works.. but an actual Merge doesn't.
UPDATE
It turns out TSVNCache.exe CONSTANTLY holds locks on the wc.db file. I have no idea why. Even if I kill the process; once I go through the TSVN Merge GUI it fires up the cache again and locks it. I have managed to successfully merge via the command line.. is there any way to fix the cache locking issue to avoid having to rely on the command line?

A: Try turning off the icon overlay status cache (What the TSVNcache.exe process is responsible for)

*

*Open an Explorer Window

*Right click anywhere, TortoiseSVN -> Settings

*Go to the "Icon Overlays" section

*Select the "None" radio button under Status Cache

*Click Apply

Presumably if the status cache is disabled and TSVNcache.exe isn't running, then it can't lock any files. You can at least rule out whether this is the problem (it sure sounds like it is). This is the process that's responsible for updating the folder/file icons in Explorer with that green checkmark, red modified mark, and so forth. I've disabled this for performance reasons for years. I just view modified files or open a commit dialog to see what files have changed.
After that, the next most likely suspect is the Indexing service (Windows Search) from past experience.

A: I had the same problem. Here is what I did:

*

*Kill explorer.exe in Task Manager

*Start it again from Task Manager

*Now the merge works...

I guess somehow Windows Explorer can lock something.

A: Another option that works for me instead of giving up the Icon Overlays, is to change directory in Windows Explorer to a non-svn folder and this way TortoiseSVN does not conflict with itself. It is so annoying but if you need a quick solution - this is it.

A: I have the same problem for some time now. Especially since my repositories are growing hard.
The pointer that TSVNCache locks the working copy got me thinking. Why would it do that? Conclusion: only when it is busy updating the working copy status (including icon overlays).
One way to overcome this problem is exactly what Joshua McKinnon says: disabling icon overlays. If that is not the solution you want (because you want to keep the icons) you can also go for a different approach: wait till the TSVNCache has finished doing its job. When you open the merge window you can see TSVNCache being busy (in a process explorer). When that busyness is over it is safe to do the merge. No more locking problems since then!


text:
Q: Disabling the Microsoft LLDP Protocol Driver using Group Policy I need to campus-wide disable the Microsoft LLDP Protocol Driver using Group Policy / SCCM / or any other means of centralized management, because I've written my own LLDP broadcast service I plan on using instead of the crippled MS implementation.
I tried googling but wasn't able to come up with a working solution.

EDIT:
I took two registry snapshots and compared them, the three keys that change when the checkbox is toggled are located under
HKLM\SYSTEM\CurrentControlSet\Services\MsLldp\Linkage

The keys are Bind / Route / Export
The problem is when these keys are deleted / emptied, the checkbox turns itself back on.

A: Alright.
I just deleted the entire
HKLM\SYSTEM\CurrentControlSet\Services\MsLldp\

key and while that turned the check box on again, Windows actually stops sending LLDP PDUs (confirmed that using Wireshark)


text:
Q: How do I merge two objects into one? How can we create dynamically (procedurally.... at run-time) one new object from two old objects so that operations performed on the new object are performed on both of the two old objects?
As just one example, we might have two streams:

*

*a string stream ... str_strm = io.StringIO()

*a file stream ... fl_strm = open("test_file.txt", "w")

In the example, we might want it to be that anytime we try to write a string to the new steam, copies of that string are written to the two older streams.
class MergedStream:

    def __init__(strm1, strm2):
        self._strm1 = strm1
        self._strm2 = strm2

    def write(self, msg:str):
        self._strm1.write()
        self._strm2.write()
        return None

str_strm = io.StringIO()
fl_strm = open("test_file.txt", "w")
ms = MergedStream(str_strm, fl_strm)

I can NOT guarantee that the two old objects both have a method named write.
Our solution should be general and dynamically generate the new merged object no matter what the two old objects are.
How might we create a new object in such a way that anytime we try to act upon the new object, we perform that same action upon the two older objects?
Something like the following is a step in the right direction, but not a complete solution:
class MergedObject:

    @classmethod
    def merge(cls, left, right):
        if left == right:
            return left
        else:
            return cls(left, right)

    def __call__(self, *args, **kwargs):
        try:
            r1 = self._lefty(*args, **kwargs)
            r2 = self._righty(*args, **kwargs)
            return type(self).merge(r1, r2)
        except AttributeError:
            raise AttributeError()

    def __init__(lefty, righty):
        self._lefty  = lefty
        self._righty = righty

        reserved = dir(self) # reserved attribute names
        attributes = dict()
        attribute_names = set(dir(lefty), dir(righty)).difference(reserved)

        for attribute_name in attribute_names:
            latter = getattr(lefty)  # `latter` is the `left-attribute`
            ratter = getattr(righty) # `ratter` is the `right-attribute`
            setattr(attribute_name, type(self).merge(latter, ratter))

SOME WRINKLES TO IRON OUT

*

*I need to be able to merge two objects which have no overloaded == operator. That is, even if there is no code inside of the class definition which says def __eq__():, I need to test if two things are equal. Suppose I merge two objects which both have a method named insert() which return -1. I do not want to carry around duplicate values. I do not want a merged object of two copies of the number 10, and then x + 5 computes 10 + 5 twice.

*There are some issues with overriding python's "magic" methods (dunder methods) such as __len__ or __mul__ If the two old objects both have a __len__ method, the new merged object might fail to have a a method named __len__.


text:
Q: Ayuda con esta consulta Estoy trayendo información de varias tablas para un reporte general de información en base a la fecha pero el problema es que me duplica información
    SELECT insumos.fecha,insumos.producto,insumos.cantidad,
 mano_obra.nombre,mano_obra.pago,mano_obra.fecha,
 mantenimiento.descripcion,mantenimiento.gasto,mantenimiento.fecha,
 combustible.vehiculo,combustible.gasolina,combustible.fecha FROM
 insumos,mano_obra,mantenimiento,combustible WHERE insumos.fecha
between '2018-01-01' AND '2018-01-01' and mano_obra.fecha
between '2018-01-01' AND '2018-01-01' and mantenimiento.fecha
between '2018-01-01' AND '2018-01-01' and combustible.fecha
between '2018-01-01' AND '2018-01-01'

resultado:

Ejemplo de como debería ser:

Alguien que pueda ayudarme en esto, se lo agradecería mucho.

A: Tu problema esta la forma en que estas agrupando las tablas.
... FROM tableA, tableB ...
lo que esta pasando es SQL realiza una combinación, entonces por cada registro de la tablaB relaciona todos los registros de la tablaA. Es por esto que se te duplican.
Si las tablas tienes la mista estructura (que no creo), podrías usar la clausula UNION, por ejemplo:
CREATE TABLE PERSONAS (
  ID VARHCAR(10),
  NAME VARCHAR(50)
);

CREATE TABLE VEHICULOS(
 ID VARCHAR(10),
 NAME VARHCAR(50)
);

Con la estructura de las dos tablas anteriores podrías hacer los siguiente:
 SELECT * FROM PERSONAS
 UNION
 SELECT * FROM VEHICULOS;

La otra solución es si tus tablas tienen relación, si la tienen puedes unas INNER JOIN.


text:
Q: How to dynamically generate a webpage with PHP MySQL according to link clicked I previously asked this question but need more help. Read this, then I will provide exact details at the end.
I have successfully transformed the static website I built for my podcast (www.noformatpodcast.com) into a dynamic website in Dreamweaver (on a testing server for now). I have done this without having to learn PHP or MySQL really at all by using the "Database", "Bindings" and "Server Behaviors" tabs in Dreamweaver. THE ONLY THING I AM NOT ABLE TO FIGURE OUT is how to get a page to generate dynamically when some one clicks a link using information about that link to create the page. For example, I have a grid of dynamically generated episodes on the index.php page. When someone clicks the link for, say, episode 55, I want it to load the episode page (which I have already created) and fill in the information from episode 55 such as date, title, blurb etc. If someone clicks the link for episode 43, I want THE SAME page to load and dynamically populate the the page with the info from episode 43. Is this possible to do with Dreamweaver's GUI, or do I need to grow up and learn to actually code?
The answers I got both told me I need to learn how to use $_GET. I've reviewed the basics of it at w3schools.com but still need a lot of help. Here is my dynamic repeating block of code that makes the grid of episodes on my index.php page

    <?php do { ?>

                    <?php echo $row_Episodes['post_id']; ?> | <?php echo $row_Episodes['ep_title']; ?>

                <img src="ep_artwork/ep_<?php echo $row_Episodes['post_id']; ?>.jpg"  width="260" height="260" />

    <?php } while ($row_Episodes = mysql_fetch_assoc($Episodes)); ?>

So basically I have a bunch of big square images that are links to the episode.php page. I have coded the episode.php page to display data dynamically as well:

        <img src="ep_<?php echo $row_Episodes['post_id']; ?>.jpg" width="260" height="260" />

Ep. <?php echo $row_Episodes['post_id']; ?> | <?php echo $row_Episodes['ep_title']; ?>

<?php echo $row_Episodes['ep_date']; ?>

<?php echo $row_Episodes['ep_blurb']; ?>

<audio src="ep_media/ep_<?php echo $row_Episodes['post_id']; ?>.m4a" controls="controls">
</audio>

What I lack is the code to glue these two things together. I mean, as it stands now, if you click on any episode, it just takes you to the episode.php page and displays the info of the first episode (cause it's the first in the database). I need to make it show the info OF THE EPISODE CLICKED. And I guess that involves using $_GET. Could someone show me EXACTLY what code I need to include, and where to include it? Is what I've posted here enough? Or do you need to know more info about my MySQL database as well?

A: To do this use apache rewrite module
This module will help you to rewrite urls which will then forward your requests to a specified script.
See below how to use .htaccess file to rewrite urls.
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]

Now all you have to do is to parse the $_SERVER['REQUEST_URI'] and then interact with the Database to fetch the required content.

A: There are many solutions, but the simplest I think would be if in your first page (the grid page or index.php), you make your links as follows:

    <?php do { ?>

            <a href="episode.php?episodeID=<?php echo $row_Episodes['post_id'] ?>" onmouseout="this.style.opacity=1;" onmouseover="this.style.opacity=0.7;">

                    <?php echo $row_Episodes['post_id']; ?> | <?php echo $row_Episodes['ep_title']; ?>

                <img src="ep_artwork/ep_<?php echo $row_Episodes['post_id']; ?>.jpg"  width="260" height="260" />

    <?php } while ($row_Episodes = mysql_fetch_assoc($Episodes)); ?>

Then in your episode.php page, you should read the get variables using
$_GET['episodeID'];

A suggested code would be:
$postID = $_GET['episodeID'];

// WRITE CODE TO GET CORRESPONDING TITLE, DATE, BLURP, AND OTHER INFO FROM THE DATABASE FOR THE SUBMITTED POST ID
// ASSUME THIS TITLE IS SAVED TO $postTitle, $postDate, $postBlurp, ...etc.

        <img src="ep_<?php echo $postID; ?>.jpg" width="260" height="260" />

Ep. <?php echo $$postID; ?> | <?php echo $postTitle; ?>

<?php echo $postTitle; ?>

<?php echo $postBlurp; ?>

<audio src="ep_media/ep_<?php echo $postID; ?>.m4a" controls="controls">
</audio>

You have to make your code secure as well. But this is the idea behind it.
My advise is to learn php and mysql to make life easier.
Cheers.


text:
Q: How to search rows in order to check if the row contains a value and only extract that specific column I am trying to iterate through rows of a dataframe to search whether a value is TRUE. The dataframe looks like:
Mass    900.5    901.5    902.5    1000.5    1001.5
Height  100      200      300      400       500
mass
901.4  FALSE     TRUE     FALSE    FALSE     FALSE
903.5  FALSE     FALSE    FALSE    FALSE     FALSE
1001.4 FALSE     FALSE    FALSE    FALSE     TRUE

As you can see, a row may have 'TRUE' or may only have 'FALSE'. I want to iterate over rows for the 1st column after mass, and search if a row does not have 'TRUE'. If a row doesn't have 'TRUE', then I want to assign the value for that specific row as empty space (equivalent to None in python I believe). My current code pulls the 'TRUE' values and collects the corresponding Height values.
For example, the above dataframe after using my code will yield:
current results:
Mass    Height
901.4   200
1001.4  500

code 1:
matches = pd.DataFrame(index=pickuplist['mass'],
                        columns=df.set_index(list(df.columns)).index,
                        dtype=bool)

Just FYI, code 1 is where matches df is initially defined.
code 2:
for index, exp_mass, intensity in df.itertuples():
    matches[exp_mass] = abs(matches.index - exp_mass)/matches.index < ppm/1e6

The above line is what creates the example dataframe after picking up values based on ppm tolerance.
code 3:
list = matches.any().reset_index(name='a')[matches.any().values]

The above line is what I believe extracts mass and Height values (current results table).
I tried using if/iloc and others to see if I could assign None to the specific row, but did not work. The expected results should be:
list:
Mass    Height
901.4   200
903.5
1001.4  500

(Edit1)
I tried using the first answer's suggestions, and it gave me like:
    Height
0   TRUE
1   TRUE
2   TRUE

Maybe the dataframes' formats are different. No False or NaN values as well. Please note that there is an empty line between Height row and 901.4 row.
(Edit2)
Tried using the suggestions from the second answer, and it gave me:
    Mass    Height
0   901.4   (901.4, 200)
1   903.5   (903.5, 518)
2   1001.4  (1001.4, 500)

The index 1 row's height value is supposed to be empty but got a random value for some reason. By looking at the imported data that goes into the matches dataframe, the 518 value seems to be the first Height value of the data.
The original data that get feed into matches dataframe looks like:
Mass    Height
899.1   518
900.5   100
901.5   200
902.5   300
950.5   400
1000.5  400
1001.5  500

and so forth.

A: You can do something like the following, it's not a really clean way but it will works for you.
I create a df like your result:
    import pandas as pd
    df = pd.DataFrame(index = [901.4, 903.5, 1001.4],
                      columns=[100, 200, 300, 400, 500],
                      data=[[False, True, False, False, False],
                            [False, False, False, False, False],
                            [False, False, False, False, True]])
   df.index.name = 'mass'
   df.columns.name = 'Height'

Here I will pass for all the rows and create a new df with your correct format:
    import numpy as np

    new_df = pd.DataFrame(columns = ['Height'])
    for index, row in df.iterrows():
        if not row.any():
            new_df.loc[index, 'Height'] = np.nan
        else:
            new_df.loc[index, 'Height'] = row.any()

Hope it helps you!

A: If want first True value if exist, else NaN first remove first level of MultiIndex by DataFrame.droplevel, then add new column with name NaN for match rows with False only and last use DataFrame.idxmax for column of first True per rows:
df1 = df.droplevel(0, axis=1)
df1[np.nan] = True
df2 = df1.idxmax(axis=1).rename_axis('Mass').reset_index(name='Height')
print (df2)
     Mass Height
0   901.4    200
1   903.5    NaN
2  1001.4    500


text:
Q: setting class property through constructor in jquery I am trying to set class property through constructor in separate js file in jquery .  value passes properly , but problem is it is not saving for future use
I have tried following code
A.js
function ShowClassB()
{

$.getScript('../ClassB.js', function()
{

var objB = new ClassB("a");

});
}

B.js
var ClassA = function(options){

var x;

this.construct = function("a"){

this.x="a";

};
this.construct("a");

}

$(document).ready(function(){

var objA =new ClassA();
console.log(objA.x);

})

But everytime I created new object . the property values resets . I am only want to set in class property , not outside . I also tried to create simple class and by prototyping . but it is not working .
please suggest

A: The problem is because you've wrapped the argument name in the construct() definition in quotes. This is a syntax error. Remove those quotes.

var ClassA = function(options) {
  var x;
  this.construct = function(value) { // change here
    this.x = value; // and here
  };
  this.construct("a");
}

$(document).ready(function() {
  var objA = new ClassA();
  console.log(objA.x);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You should note that this pattern is largely redundant though, just use an actual constructor:

function ClassA(options) {
  this.x = options.value;
}

$(document).ready(function() {
  var objA = new ClassA({
    value: 'foo'
  });
  console.log(objA.x);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


text:
Q: Long Running Process in Openshift - like sunspot I know there are quite a few openshift fan out there and the list of feature that openshift give you I dont blame them too
so this question is for those guys I have solr full text search engine running on the openshift
Now the I using sunspot_rails to connect to solr to create indexes
all work well for sometime and all the indexes get create appropriately but we experience that after a while the connection to solr keeping getting lost
So I'm assuming that openshift doesnot allow long running process like solr to run and would kill after some period of time
am I correct in my believe

A: You can use nohup to launch your script with post_start_ and post_stop_ scripts in .openshift\actionhooks
Redhat openshift - Cron Runtime - Is there a default time for how long cron executes shows how to do it with cron.


text:
Q: Call activerecord destroy without transaction I'd like to destroy an object and everything that is associated with it.
The problem is, the tree of dependant: :destroy runs very deep and the operation of destroying the toplevel object takes minutes.
What makes this worse (in this case), is Rails puts all of these destroys in a transaction, which can cause lock wait timeouts for other threads.
This is a special case where I'd like to have the cascading destroys, WITHOUT any transactional wrapper.
Can this be easily done?


text:
Q: XML parsing returns null when using Android Fragments for honeycomb I am trying to parse an XML file and fetch its contents and display in a ListFragment. It is working fine for 1.6 to 2.2 SDK(Without fragments). When I try to use fragments such that on clicking one fragment listitem, it must display another ListFragment beside it by parsing an XML, I get response as null. Has anyone worked on XML parsing using Fragments in Android? If there are tutorials related to this, kindly post the link for the same

A: If this XML is a static xml, create a StringArray in the resource file and use that, parsing XML is not very efficient.
If the XML is a static file and you still want to use it to parse it. Please post the code used for parsing


text:
Q: Adding imageview on UITextField with auto layout I am creating a custom searchbar with UITextfield. Searchbar should look like this:

But, In my case it is appearing like this:

What is the mistake I am doing in setting constraints for imageview on textfield
Code:
    UITextField *searchBarTF=[[UITextField alloc]init];

    [searchBarTF setBackgroundColor:[UIColor whiteColor]];
    searchBarTF.layer.borderColor=[[UIColor darkGrayColor]CGColor];
    searchBarTF.layer.borderWidth=7;
    searchBarTF.layer.cornerRadius=5;
    searchBarTF.returnKeyType=UIReturnKeySearch;

    searchBarTF.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Search by locations" attributes:@{NSForegroundColorAttributeName: [UIColor grayColor],NSFontAttributeName:[UIFont fontWithName:@"Helvetica" size:16]}];
    searchBarTF.textAlignment=NSTextAlignmentCenter;
    UIImageView *srchBariconImageView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"srchBarIcon"]];
    [srchBariconImageView setTranslatesAutoresizingMaskIntoConstraints:NO];
    [searchBarTF  addSubview:srchBariconImageView];
    [searchBarTF addConstraint:[NSLayoutConstraint constraintWithItem:srchBariconImageView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:searchBarTF attribute:NSLayoutAttributeLeading multiplier:1.0f constant:40]];
    [searchBarTF addConstraint:[NSLayoutConstraint constraintWithItem:srchBariconImageView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:searchBarTF attribute:NSLayoutAttributeTrailing multiplier:1.0f constant:-(views.frame.size.width-80)]];

    [searchBarTF addConstraint:[NSLayoutConstraint constraintWithItem:srchBariconImageView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:40]];
//
// [searchBarTF addConstraint:[NSLayoutConstraint constraintWithItem:srchBariconImageView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:40]];

     [searchBarTF setTranslatesAutoresizingMaskIntoConstraints:NO];

     // replace views with self.view.
     [views addSubview:searchBarTF];
     [views addConstraint:[NSLayoutConstraint constraintWithItem:searchBarTF attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:views attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0]];

    [views addConstraint:[NSLayoutConstraint constraintWithItem:searchBarTF attribute:NSLayoutAttributeHeight    relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:60]];

  //  [views addConstraint:[NSLayoutConstraint constraintWithItem:searchBarTF attribute:NSLayoutAttributeTop    relatedBy:NSLayoutRelationEqual toItem:views attribute:NSLayoutAttributeTop multiplier:1.0 constant:-64]];

    [views addConstraint:[NSLayoutConstraint constraintWithItem:searchBarTF attribute:NSLayoutAttributeTrailing   relatedBy:NSLayoutRelationEqual toItem:views attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0]];

      [views addConstraint:[NSLayoutConstraint constraintWithItem:searchBarTF attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:views attribute:NSLayoutAttributeTop multiplier:1.0 constant:130]];

A: Subclass UITextField and overwrite these methods
- (void)awakeFromNib{
    CGRect frame =    self.leftView.frame;
    frame.size.width = 30;
    frame.size.height = 30;
    self.leftView.frame = frame;
    self.leftView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"underfloor_cross_blue.png"]];
}

- (CGRect)leftViewRectForBounds:(CGRect)bounds{
    CGRect rect=CGRectMake(8, 8,50.0, 45);
    [super leftViewRectForBounds:rect];
    return rect ;
}

Note: change image and frame according to your need.


text:
Q: Nginx-passenger RVM cookbook chef Unable to setup nginx-passenger module using chef-solo.. Phusion passenger compile issue.
cookbook 'rvm', '~> 0.9.2'
cookbook 'nginx', '~> 2.7.4'
i have gone through solutions in other similar threads,, but no success yet... any help is highly appreciated..
My Configuration
{
   "name": "nginx-server",
   "description": "Nginx server",
   "default_attributes": {
      "rvm": {
          "default_ruby":"ruby-2.1.2",
          "gems": {
            "2.1.2": [
              {"name": "bundler"},
              {"name": "passenger"},
              {"name": "rake"}
            ]
          }
        },
      "nginx": {
          "version": "1.4.1",
          "dir" : "/etc/nginx",
          "log_dir" : "/var/log/nginx",
          "binary": "/opt/nginx-1.4.1/sbin",
          "user" : "www-data",
          "init_style" : "init",
          "source" :{
              "modules" : [
                  "nginx::http_stub_status_module",
                  "nginx::http_gzip_static_module",
                  "nginx::passenger"
                  ]
              },
              "passenger" : {
                  "version": "3.0.21",
                  "ruby" : "/usr/local/rvm/rubies/ruby-2.1.2/bin/ruby",
                  "root" : "/usr/local/rvm/gems/ruby-2.1.2/gems/passenger-3.0.21"

              }
        }
   },
   "json_class": "Chef::Role",
   "run_list": [
      "rvm::system",
      "rvm::gem_package",
      "nginx::source",
      "monit_configs-tlq::nginx"
   ],
   "chef_type": "role",
   "override_attributes": {
   }
}

Error message: Phusion Passenger support files are not yet compiled. Compiling them for you
adding module in /usr/local/rvm/gems/ruby-2.1.2/gems/passenger-3.0.21/ext/nginx
*** The Phusion Passenger support files are not yet compiled. Compiling them for you... ***
*** Running 'rake nginx RELEASE=yes' in /usr/local/rvm/gems/ruby-2.1.2/gems/passenger-3.0.21/ext/nginx... ***
STDERR: /opt/chef/embedded/bin/rake:9:in `require': no such file to load -- rubygems (LoadError)
    from /opt/chef/embedded/bin/rake:9
---- End output of "bash"  "/tmp/chef-script20141016-27177-1eqrpme" ----
Ran "bash"  "/tmp/chef-script20141016-27177-1eqrpme" returned 1
[2014-10-16T20:45:43+00:00] FATAL: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)
ERROR: RuntimeError: chef-solo failed. See output above.

Any idea to solve this,, will be of great help... :)
Many Thanks
Dave

A: The problem is that you are trying to use the ruby binary from RVM but your path is still setup to use other scripts from the Chef omnibus install. The trace shows rake running the the omnibus folder but ruby from RVM. Fix the PATH environment variable used for the bash recipe or source the RVM shell config in the bash code before running rake. This will likely require forking the above cookbooks unless they have explicit support for each other.