text:
Q: Delphi warning - W1002 Symbol 'FileSetDate' is specific to a platform When I compile my application under Delphi 2006 I get the following warning
[Pascal Warning]- W1002 Symbol 'FileSetDate' is specific to a platform
What must I do to suppress this warning?
The code
MyLastError:= FileSetDate( Files[ i ].Handle, DateTimeToFileDate( arcDate ) );

A: You can turn off the platform unit and platform symbol compiler warnings. They are obsolete (and disabled in Delphi 2009 by default). They were introduced when there was a Delphi for Linux (Kylix). They do not have a meaning anymore. Especially with the replacement of Delphi.NET with Delphi Prism.
You can turn them off for the whole project in the Project Options dialog (Compiler Messages).

A: 1) In the project options you can choose the compiler messages you want to see.
If you don't care about platform independency you can just switch off the platform warning there.
2) Another way is disabling the warning for a certain part of the code:
{$WARN SYMBOL_PLATFORM OFF}
// Your code
{$WARN SYMBOL_PLATFORM ON}

For a complete list of options look at the Delphi help file at the topic '$WARN'
3) A last way would be adding
{$WARNINGS OFF}
// Your code
{$WARNINGS ON}

but that is dangerous, because all warnings will be suppressed.
4) Additionally, as the other answers have already suggested, you could just switch to the platform independant variant of FileSetDate which works on file names (i.e. Strings), but as far as I understand that was not your question.

A: Although the answer of DR solves the warning, it is not the correct solution.
You should use the platform independent version of FileSetDate:
function FileSetDate(const FileName: string; Age: Integer): Integer; overload;

Also in SysUtils.


text:
Q: A Wilson line property Consider a path, say $P$, and three points on it like $x,y,z$. If there were infinitesmally closed, then the following relation would be true.
$$W_{P}(x,y) W_{P}(y,z)=W_{P}(x,z)$$
If the Lie algebra of the theory was Abelian, it was also held for any three points on the path no matter how far they are. Is it also true in non-Abelian cases? The Wilson line of the path $P$ contains path-ordering so I am not sure whether this is the case in non-Abelian Lie algebras.

A: Yes, non-Abelian Wilson lines $W_P[\gamma]$ form a groupoid via concatenation of oriented curves and has OP's mentioned property by definition of path-ordering of ordered exponentials.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wireless device does not work on Dell Inspiron 3521 after installing Ubuntu 12.04 Wifi does not work at all on Inspiron 3521 after installing Ubuntu 12.04..
When I type in  lspci -nn  the wireless device is even not on the list.
Please help in this topic!

A: Some wireless cards are actually listed as USB.
lsusb

will show these.
Check your keyboard. I've had several laptops which have a Fn blue colored key with a wireless icon above the function key that turns on/off the wireless. This is due to the massive power drain wifis require, so they design a soft power switch for this component.
These people were able to get it working with a little trick to force the power profile to reset the wifi.


text:
Q: How do I get a variable folder (e.g. Program files or user) in TeamDeveloper 6.3? I need to get certain special windows folders in Windows 10 from a TD 6.3 program - for instance, Program Files, user, or Appdata. Is there a certain function for this? I've looked through the help but can't seem to find it.
I also need to check if the program currently has read/write access to a folder I specify. I suspect the latter can be achieved by trying a SalFileOpen or SalFileWrite respectively and checking the result.
The point is that I need to get some temporary files from a network location to the local machine to be able to use them, as I only have read access to the network drive.
As of now I've simply created a temp folder in C:\, this works perfectly in debug, but when I build the program and then try running it, for some reason it doesn't get the files and the temp folder stays empty. Thinking this was a permission issue, I tried running as admin to no avail.
I'm kind of at a loss as to why it won't work, so any input is appreciated.
I simply copy the needed files from the network drive to the temp folder using SalFileCopy with the overwrite flag set to true.

A: You can use windows API-functions for that.
To get the temp-path you can use the following:
Define an external function:
Kernel32.dll
Function: GetTempPathW
Return
    DWORD
Parameters:
    Number: DWORD    ! nBufferLength [in] The size of the string buffer identified by lpBuffer, in TCHARs.
    Receive String: LPWSTR    ! lpBuffer [out] A pointer to a string buffer that receives the null-terminated string

Use it like that:
Function: GetTempPath           ! __exported
    Description: WinAPI: This function retrieves the path of the directory designated for temporary files.
    Returns
        String:
    Parameters
    Local variables
        String: sStrBuffer
        Number: nBuffLen
        Number: nNumChars
    Actions
        Set nBuffLen = 0
        Call SalSetBufferLength( sStrBuffer, nBuffLen )
        Set nBuffLen = GetTempPathW( nBuffLen, sStrBuffer )
        Call SalSetBufferLength( sStrBuffer, nBuffLen * 2 )
        Call GetTempPathW( nBuffLen, sStrBuffer )
        If SalStrRightX( sStrBuffer, 1 ) != '\\'
            Set sStrBuffer = sStrBuffer || '\\'
        Return sStrBuffer

To check if you have write access just create a file in that folder and delete it afterwards.
Here some more info about the windows API-function:
https://msdn.microsoft.com/de-de/library/windows/desktop/aa364992(v=vs.85).aspx

A: In case you need any path of the environment variables (e.g. appdata) you can use
VisDosGetEnvString( 'appdata' )
The method is part of the Visual Tool Chest (vt.apl lib within the installation dir)


text:
Q: How are "it's" and "its" different? How is "it's" different from "its"? They look pretty much the same. How do they work? For example, in sentences such as:

It's collar was shaking.

Its collar was shaking.

A: "It's" means "It is". This is a verb "contraction" used quite often in English.
"Its" (no apostrophe) means the subject or object is replaced by the indefinite noun "It"... and "Its'" is a possessive noun. Note: the word "is" in my last phrase denotes action. It is a verb describing the action of (ITS'), which is the subject.
Just remember that It can apply to some undefined object (the planet).
Eg: Freedom is fragile and if it is to survive, its foundation must be strong. Here, its refers to the noun Freedom, i.e. the foundation of Freedom must be strong.
A subject is the person, place, or thing that performs the action (verb). A noun or pronoun can be used as the object in a sentence. An object is the person, place, or thing that receives the action.
E.g. "Its going to be rainy tonight" i.e. "The weather or conditions will be rainy tonight. "Its" implies the weather. Here, it is an object, the conditions refer to the weather, making "Its'" a possessive pronoun. The weather is a subject. (THE subject) !


text:
Q: Montar uma pesquisa dinâmica Como fazer uma pesquisa com filtro no banco de dados usando esse exemplo a seguir:
As variáveis do banco são:
Nome Professor T | Matricula T |Nome Professor S | Matricula S | Nome Professor A | Matricula A | Turma | Ano | Unidade | Modalidade | Tipo do Professor .

Obs: a variável Tipo mostraria na tabela de pesquisa qual o tipo do professor " A S ou T".
Os professores podem variar de tipo dependendo das 4 ultimas variáveis do banco.
Como assim?
O professor pode ser T em uma determinada Unidade e em outra ele poder ser S.
Então no campo da pesquisa ao digitar o nome do professor ou matricula, a pesquisa mostraria a seguinte tabela com os dados :
Professor | Matricula | Unidade |  Modalidade | Ano | Turma | Tipo do Prof.

Alguma ideia de como monta essa pesquisa ? "Qualquer duvida e só
pergunta"
As partes em ja cheguei:
A Html :

<!DOCTYPE html>

  <title>WEB VIDEO AULAS</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

          <input type="text" class="form-control" size="35" id="palavra" placeholder="Digite seu nome ou sua matrícula.." required />

                            <button class="btn btn-blue" id="buscar" type="button">Buscar</button>

  <link rel="stylesheet" href="/SLP/css/css/CDTpag2.css">

  <link rel="stylesheet" href="/SLP/css/css/voltar.css">
  Limpar

  <link rel="stylesheet" href="/SLP/css/css/voltar.css">
  Voltar

E a PHP :

<?php header('Content-Type: text/html; charset=iso-8859-1');?>
<?php
 $host = "localhost";
   $user = "root";
   $pass = "";
   $banco = "slp";
   $conexao = mysqli_connect($host, $user, $pass) or die(mysqli_error());
   mysqli_select_db($conexao, $banco) or die(mysqli_error($conexao));

$palavra = $_POST['palavra'];

$sql = mysqli_query($conexao,"SELECT * from cadastros WHERE nomeProfEfetivo LIKE '%".$palavra."%' OR matricula LIKE '%".$palavra."%'");
$row = mysqli_num_rows($sql);
?>

    <?php
    if($row>0){
    ?>

             Professor
             Matricula
             Unidade
             Modalidade
             Ano
             Turma
             Turno
             Tipo do Prof.

          <?php
            while($linha = mysqli_fetch_assoc($sql)){
            ?>

              <?=$linha['nomeProfEfetivo'];?>

              <?=$linha['matricula'];?>

              <?=$linha['unidade'];?>

              <?=$linha['modalidade'];?>

              <?=$linha['ano'];?>

              <?=$linha['turma'];?>

              <?=$linha['turno'];?>

              <?=$linha['tipo']; ?>

          <?php }?>

      <?php

 }else{?>

Nao foram encontrados registros com esta palavra.

      <?php }?>


text:
Q: Imageview jump to start position i have an imageview
and i move it in timer with:
  ImageView kembali = (ImageView) findViewById(idmusuh);
  kembali.setVisibility(View.VISIBLE);
  RelativeLayout.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
  params.setMargins(5, 0, 0, 0);
  kembali.setLayoutParams(params);

so the imagview is move down 5px every timer tick
now if i click the button i want to put the imageview back to start position ..what is the code?

A: Try this:
kembali.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            RelativeLayout.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
            params.setMargins(0, 0, 0, 0);
            kembali.setLayoutParams(params);
        }
    });

Given that you have moved the ImageView by increasing the margin...


text:
Q: I am having a problem with my APEX InvocableMethod returning an error when run through process builder I have created an invocable method to run through Process builder. Although the class works when triggered with some changes, I get an error when running it through the process builder. From what I have determined, it is happening because the call out isn't run asynchronously.
That being said, I have tried to separate the classes and make one a future call out but I cannot figure out how to pass the three strings I have from the invocable class to my call out class.
Any help would be great!
public class SendText {

        public class DataWrapper {

        @InvocableVariable(label='Correspondence Name' required=true)
        public String CorrespondenceName;
        @InvocableVariable(label='Phone Number' required=true)
        public String PhoneNumber;
        @InvocableVariable(label='Text Message' required=true)
        public String textMessage;

    }

    @InvocableMethod(label='Send Text Message')
    public static void callSendTextMessage (List<DataWrapper> passedData) {

        for (DataWrapper dw: passedData) {

        //Basic Info needed to send request
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://api.podium.com/api/v2/conversations');
        request.setMethod('POST');
        request.setHeader('Content-Type', 'application/json');
        request.setHeader('Accept', 'application/json');
        request.setHeader('Authorization', 'API Key');

        //Create the 4 required fields for Podium
        Map<String, String> message = new Map<String, String>{
            'customerPhoneNumber' => dw.PhoneNumber,
            'message' => dw.textMessage,
            'locationId' => '49257',
            'customerName' => dw.CorrespondenceName
        };

        String messageJson = JSON.serialize(message);
        System.debug(messageJson);

        request.setBody(messageJson);
        HttpResponse response = http.send(request);

        // Parse the JSON response
        if (response.getStatusCode() != 201) {
            System.debug('The status code returned was not expected: ' +
               response.getStatusCode() + ' ' + response.getStatus());
        } else {
            System.debug(response.getBody());
        }
        }
    }

}

A: Not sure if you tried Queueable Apex but this is how I do it, give this a shot:
public class SendText {

    public class DataWrapper {

        @InvocableVariable(label='Correspondence Name' required=true)
        public String CorrespondenceName;

        @InvocableVariable(label='Phone Number' required=true)
        public String PhoneNumber;

        @InvocableVariable(label='Text Message' required=true)
        public String textMessage;

    }

    @InvocableMethod(label='Send Text Message')
    public static void callSendTextMessage (List<DataWrapper> passedData) {

        Id jobId = System.enqueueJob(new TextMessaeQueueable(passedData));
        System.debug('Text messages job Id => ' + jobId);
    }

    private class TextMessaeQueueable implements Queueable, Database.AllowsCallouts {

        private List<DataWrapper> wrappedData;

        public TextMessaeQueueable(List<DataWrapper> passedData) {
            this.wrappedData = passedData
        }

        public void execute(QueueableContext context) {

            for (DataWrapper dw: this.wrappedData) {

                //Basic Info needed to send request
                Http http = new Http();
                HttpRequest request = new HttpRequest();
                request.setEndpoint('https://api.podium.com/api/v2/conversations');
                request.setMethod('POST');
                request.setHeader('Content-Type', 'application/json');
                request.setHeader('Accept', 'application/json');
                request.setHeader('Authorization', 'API Key');

                //Create the 4 required fields for Podium
                Map<String, String> message = new Map<String, String>{
                    'customerPhoneNumber' => dw.PhoneNumber,
                    'message' => dw.textMessage,
                    'locationId' => '49257',
                    'customerName' => dw.CorrespondenceName
                };

                String messageJson = JSON.serialize(message);
                System.debug(messageJson);

                request.setBody(messageJson);
                HttpResponse response = http.send(request);

                // Parse the JSON response
                if (response.getStatusCode() != 201) {
                    System.debug('The status code returned was not expected: ' +
                        response.getStatusCode() + ' ' + response.getStatus());
                } else {
                    System.debug(response.getBody());
                }
            }
        }
    }
}


text:
Q: K8s Pod Lifecycle Hooks I'd like to receive a notification whenever there are any changes to the kubernetes cluster. Pods are created/deleted, etc. This can be a in a form of a webhook, or a message in a pub/sub, etc anything that can be used in autonomous manner.
Running the kubernetes cluster in gcp.

A: You can get such events with creating hooks in linux compatible languages (such as go,python etc.) to relevant k8s object's watch endpoint. i.e./apis/apps/v1/watch/namespaces/{namespace}/deployments/{name} is the watch endpoint of Deployment object. You may find the watch endpoint of the object you desire from the API reference of k8s-api-server. https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.13/


text:
Q: ADC in low power run mode measure same numbers I have stm32L053R8 nucleo64 board. I'm trying to get adc measure in low power run mode. It's not working correctly in Lprun mode but when I try in run mode it's working. In Lprun mode I only get 2 values. Half of the resolution and full of the resolution(12bit -> 2047 & 4095). Can you guys help me to figure out where am I doing wrong?
I tried to figure out why this happens and configured LFMEN, VREFEN, ULP bits but didn't worked.
ADC_HandleTypeDef hadc;

void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_ADC_Init(void);

uint16_t adcVal = 0;

int main(void) {

HAL_Init();

MX_GPIO_Init();
MX_ADC_Init();

/*
//  Bit 25 LFMEN: Low Frequency Mode enabled
ADC->CCR |= (1UL << 25);

//  Bit 22 VREFEN: VREFINT enable
ADC->CCR |= (1UL << 22);

//  Bit 9 ULP: Vrefint is ON in low power mode
PWR->CR &= ~(1UL << 9U);

*/

HAL_PWREx_EnableLowPowerRunMode();

 while (1) {

  HAL_Delay(500);
  HAL_ADC_Start(&hadc);
  HAL_ADC_PollForConversion(&hadc, 100);
  adcVal = HAL_ADC_GetValue(&hadc);
  HAL_ADC_Stop(&hadc);

 }
}

/* @brief System Clock Configuration
 * @retval None
 */
void SystemClock_Config(void) {

RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

/* Configure the main internal regulator output voltage */

__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

/* Initializes the RCC Oscillators according to the specified
 *parameters
 * in the RCC_OscInitTypeDef structure.
 */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI;
RCC_OscInitStruct.MSIState = RCC_MSI_ON;
RCC_OscInitStruct.MSICalibrationValue = 0;
RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_2;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
    Error_Handler();
  }

/* Initializes the CPU, AHB and APB buses clocks */
RCC_ClkInitStruct.ClockType =RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                          |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_MSI;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK) {
    Error_Handler();
  }
}

/*
* @brief ADC Initialization Function
* @param None
* @retval None
*/
static void MX_ADC_Init(void) {

/* USER CODE BEGIN ADC_Init 0 */

/* USER CODE END ADC_Init 0 */

ADC_ChannelConfTypeDef sConfig = {0};

/* USER CODE BEGIN ADC_Init 1 */

/* USER CODE END ADC_Init 1 */

/* Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion) */
hadc.Instance = ADC1;
hadc.Init.OversamplingMode = DISABLE;
hadc.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV1;
hadc.Init.Resolution = ADC_RESOLUTION_12B;
hadc.Init.SamplingTime = ADC_SAMPLETIME_1CYCLE_5;
hadc.Init.ScanConvMode = ADC_SCAN_DIRECTION_FORWARD;
hadc.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc.Init.ContinuousConvMode = DISABLE;
hadc.Init.DiscontinuousConvMode = DISABLE;
hadc.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
hadc.Init.ExternalTrigConv = ADC_SOFTWARE_START;
hadc.Init.DMAContinuousRequests = DISABLE;
hadc.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
hadc.Init.Overrun = ADC_OVR_DATA_PRESERVED;
hadc.Init.LowPowerAutoWait = DISABLE;
hadc.Init.LowPowerFrequencyMode = ENABLE;
hadc.Init.LowPowerAutoPowerOff = DISABLE;
 if (HAL_ADC_Init(&hadc) != HAL_OK) {
   Error_Handler();
  }

/* Configure for the selected ADC regular channel to be converted. */
sConfig.Channel = ADC_CHANNEL_1;
sConfig.Rank = ADC_RANK_CHANNEL_NUMBER;
 if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK) {
   Error_Handler();
  }
}


text:
Q: NPM command (on Windows 10) returns no result As you saw in the title the command npm does not return anything (as in returning to input again) but is a registered command on Powershell. I have tried removing all nodejs and npm folders and retrying installing it with utilities like nvm, but none of them seem to work. As far as I have checked there is no log output.

A: Never mind. I found out what was wrong, my CMD was being blocked by a registry key, deleted that and it worked. Thank you!


text:
Q: Fill in the blanks model I've been trying to figure out the correct model for this new app of mine. Here's the thing. I need to create an exam type app. The app will have a "Grammar" section which requires a paragraph with fill in the blanks approach. So it will look like this.
    "Lorem ipsum dolor sit amet, _________________ , sed do eiusmod tempor
     _______ ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
     exercitation ullamco _________________ ex ea commodo consequat. Duis aute
     irure dolor in reprehenderit in voluptate velit esse _______ dolore eu fugiat nulla
     pariatur. ____________ sint occaecat cupidatat non proident, sunt in culpa qui
     officia deserunt mollit anim id est laborum."

Now, the paragraph is coming from the server. We mark the blanks as {#} so when I display it on the app I will replace it with "____" w/c is equivalent to a uitextfield. The problem is I've no idea how to go about this. Can I put everything in a uitextview? how should I deal with the blanks? And I dont think I can do this with uiwebview coz I need the update the contents of the blanks once I tap on them. Please help.

A: My requirement was also same, but I solved it in native code, with UILabel & UIView, all of it done through pragmatically within a loop. Consider the below text.
Once upon a time there _____  a man called Damocles. A friend of his eventually _____  the ruler of a small city. Damocles thought, 'How lucky my friend ____. He ____  now a ruler. He must ____  a great time.
In which each work is treated as UILabel empty spaces treated as UIView. The correct options are in ordered list as show below.
(lldb) po self.card.questionDataModel.fillAnswers
<__NSArrayI 0x6000008798c0>(
lived,
became,
is,
is,
must be having
)

Check out code.
This methods renders entire UI for empty spaces and its options
    - (void)prepareUIForFillInBlankQuestionType {

    self.totalOptionCount = self.card.questionDataModel.fillAnswers.count;

    CGFloat leading = 8;
    CGFloat trailing = 8;

    if ([NSRUtilities isNilOREmptyString:self.card.questionDataModel.question] == NO) {

        NSAttributedString* titleAttributedString = [[ConstantTools sharedData] convertHTMLToString:self.card.questionDataModel.question];
        NSString* titleString = titleAttributedString.string;

        // Holds all blank UIView (empty spaces)
        NSMutableArray* blankViewContainerList = [NSMutableArray new];

        // Full string will be separate by spaces so that each work can for single instance of UILabel
        NSArray* blankSpaceSeperatedList = [titleString componentsSeparatedByString:@" "];

        CGFloat fillViewWidth = CGRectGetWidth(self.fillBlankContainerView.frame);

        CGFloat labelX = 8;
        CGFloat labelY = 8;
        CGFloat labelHeight = 25;

        NSInteger underscoreIndex = 0;
        for (NSString* text in blankSpaceSeperatedList) {

            CGFloat fillContainerWidth = (fillViewWidth - (trailing + leading));

            // inputs NSString instance, will return back its UILabel for all words in a sentence
            UILabel* textLabel = [self labelFromText:text];

            if ((labelX + textLabel.frame.size.width) < fillContainerWidth) {

                if ([text containsString:@"__"]) {

                    CGFloat answerWidth = CGRectGetWidth(self.fillBlankContainerView.frame) *  FILL_FRAME_RATIO; // 0.4

                    UIView* blankView = [[UIView alloc] initWithFrame:CGRectMake(labelX,
                                                                                labelY,
                                                                                answerWidth,
                                                                                labelHeight)];

                    CALayer* bottomLayer = [CALayer layer];
                    [bottomLayer setFrame:CGRectMake(0, labelHeight - 1, CGRectGetWidth(blankView.frame), 1)];
                    [bottomLayer setBackgroundColor:[UIColor whiteColor].CGColor];
                    [blankView.layer addSublayer:bottomLayer];

                    [blankView setTag:(600 + underscoreIndex)];
                    underscoreIndex++;

                    if (labelX + CGRectGetWidth(blankView.frame) >= fillContainerWidth) {
                        labelX = leading;
                        labelY += labelHeight;
                        [blankView setFrame:CGRectMake(labelX, labelY, answerWidth, labelHeight)];
                    }
                    [self.fillBlankContainerView addSubview:blankView];

                    [blankViewContainerList addObject:blankView];

                    labelX += answerWidth;
                }
                else {
                    CGRect labelFrame = textLabel.frame;
                    labelFrame.origin.x = labelX;
                    labelFrame.origin.y = labelY;
                    [textLabel setFrame:labelFrame];
                    [self.fillBlankContainerView addSubview:textLabel];

                    labelX += textLabel.frame.size.width;
                }

            }
            else{
                labelX = leading;
                labelY += labelHeight;

                if ([text containsString:@"__"]) {

                    CGFloat answerWidth = CGRectGetWidth(self.fillBlankContainerView.frame) *  FILL_FRAME_RATIO;

                    UIView* blankView = [[UIView alloc] initWithFrame:CGRectMake(labelX,
                                                                                labelY,
                                                                                answerWidth,
                                                                                labelHeight)];

                    CALayer* bottomLayer = [CALayer layer];
                    [bottomLayer setFrame:CGRectMake(0, labelHeight - 1, CGRectGetWidth(blankView.frame), 1)];
                    [bottomLayer setBackgroundColor:[UIColor whiteColor].CGColor];
                    [blankView.layer addSublayer:bottomLayer];

                    [blankView setTag:(600 + underscoreIndex)];
                    underscoreIndex++;

                    if (labelX + CGRectGetWidth(blankView.frame) >= fillContainerWidth) {
                        labelX = leading;
                        labelY += labelHeight;
                        [blankView setFrame:CGRectMake(labelX, labelY, answerWidth, labelHeight)];
                    }

                    [self.fillBlankContainerView addSubview:blankView];
                    [blankViewContainerList addObject:blankView];
                    labelX += answerWidth;

                }
                else {

                    CGRect labelFrame = textLabel.frame;
                    labelFrame.origin.x = labelX;
                    labelFrame.origin.y = labelY;
                    [textLabel setFrame:labelFrame];
                    [self.fillBlankContainerView addSubview:textLabel];

                    labelX += textLabel.frame.size.width;
                }
            }
        }

        self.blankViewContaninerList = blankViewContainerList;

        // It has all the options which will dragged on empty spaces
        NSMutableArray* optionList = [NSMutableArray new];

        if ([NSRUtilities isNilOREmptyString:self.card.questionDataModel.A] == NO) {
            NSAttributedString* attributedStringA = [[ConstantTools sharedData] convertHTMLToString:self.card.questionDataModel.A];
            NSString* optionA = [NSRUtilities trimNewlineCharacterFromString:attributedStringA.string];
            [optionList addObject:optionA];
        }

        if ([NSRUtilities isNilOREmptyString:self.card.questionDataModel.B] == NO) {
            NSAttributedString* attributedStringB = [[ConstantTools sharedData] convertHTMLToString:self.card.questionDataModel.B];
            NSString* optionB = [NSRUtilities trimNewlineCharacterFromString:attributedStringB.string];
            [optionList addObject:optionB];
        }

        if ([NSRUtilities isNilOREmptyString:self.card.questionDataModel.C] == NO) {
            NSAttributedString* attributedStringC = [[ConstantTools sharedData] convertHTMLToString:self.card.questionDataModel.C];
            NSString* optionC = [NSRUtilities trimNewlineCharacterFromString:attributedStringC.string];
            [optionList addObject:optionC];
        }

        if ([NSRUtilities isNilOREmptyString:self.card.questionDataModel.D] == NO) {
            NSAttributedString* attributedStringD = [[ConstantTools sharedData] convertHTMLToString:self.card.questionDataModel.D];
            NSString* optionD = [NSRUtilities trimNewlineCharacterFromString:attributedStringD.string];
            [optionList addObject:optionD];
        }

        if ([NSRUtilities isNilOREmptyString:self.card.questionDataModel.E] == NO) {
            NSAttributedString* attributedStringE = [[ConstantTools sharedData] convertHTMLToString:self.card.questionDataModel.E];
            NSString* optionE = [NSRUtilities trimNewlineCharacterFromString:attributedStringE.string];
            [optionList addObject:optionE];
        }

        CGFloat optionsYPoint = labelY + 50;

        for (NSInteger optionIndex = 0 ; optionIndex < optionList.count ; optionIndex++) {

            NSString* option = optionList[optionIndex];
            UILabel* optionLabel = [self optionLabelFromText:option index:optionIndex];

            if (optionIndex % 2 == 0) {
                // Fall out on left side

                CGFloat centerPoint = (CGRectGetWidth(self.fillBlankContainerView.frame) / 4);
                CGFloat optionsCenterPoint = (CGRectGetWidth(optionLabel.frame) / 2);

                CGFloat x = centerPoint - optionsCenterPoint;
                CGFloat y = optionsYPoint;
                CGFloat width = CGRectGetWidth(optionLabel.frame);
                CGFloat height = 25;

                [optionLabel setFrame:CGRectMake(x, y, width, height)];
                [self.fillBlankContainerView addSubview:optionLabel];

                // struct optionRect
                optionLabel.tag                     = optionIndex;
                optionRect[optionIndex].origin      = optionLabel.frame.origin;
                optionRect[optionIndex].size        = optionLabel.frame.size;
                optionRect[optionIndex].center      = optionLabel.center;

            }
            else {
                // Fall out on right side

                CGFloat centerPoint = CGRectGetWidth(self.fillBlankContainerView.frame) -(CGRectGetWidth(self.fillBlankContainerView.frame) / 4);
                CGFloat optionsCenterPoint = (CGRectGetWidth(optionLabel.frame) / 2);

                CGFloat x = centerPoint - optionsCenterPoint;
                CGFloat y = optionsYPoint;
                CGFloat width = CGRectGetWidth(optionLabel.frame);
                CGFloat height = 25;

                [optionLabel setFrame:CGRectMake(x, y, width, height)];
                [self.fillBlankContainerView addSubview:optionLabel];

                // struct optionRect
                optionLabel.tag                     = optionIndex;
                optionRect[optionIndex].origin      = optionLabel.frame.origin;
                optionRect[optionIndex].size        = optionLabel.frame.size;
                optionRect[optionIndex].center      = optionLabel.center;

                optionsYPoint += 40;
            }
        }
    }
}

These methods will prepare UILabel out NSString
- (UILabel*)labelFromText:(NSString*)text {

    UIFont* boldFont = [UIFont boldSystemFontOfSize:15];
    NSAttributedString* labelString = [[NSAttributedString alloc ] initWithString:text
                                                                       attributes:@{NSFontAttributeName:boldFont}];

    CGRect cellRect = [labelString boundingRectWithSize:CGSizeMake(MAXFLOAT, 30)
                                                options:NSStringDrawingUsesLineFragmentOrigin context:nil];

    CGFloat width = cellRect.size.width + 10;

    UILabel* textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 25)];
    [textLabel setText:text];
    [textLabel setTextColor:[UIColor whiteColor]];
    return textLabel;
}

- (UILabel*)optionLabelFromText:(NSString*)text index:(NSInteger)index{

    UIFont* regularFont = [UIFont systemFontOfSize:14];
    CGFloat width = CGRectGetWidth(self.view.frame) * FILL_FRAME_RATIO; // 0.4;

    UILabel* optionLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width, 25)];
    [optionLabel setText:text];
    [optionLabel setFont:regularFont];
    [optionLabel setTextColor:[UIColor whiteColor]];
    [optionLabel setTextAlignment:NSTextAlignmentCenter];
    [optionLabel setBackgroundColor:[UIColor lightTextColor]];

    [optionLabel.layer setBorderColor:[UIColor whiteColor].CGColor];
    [optionLabel.layer setBorderWidth:1.0];
    [optionLabel.layer setCornerRadius:2.0];
    [optionLabel.layer setMasksToBounds:YES];
    [optionLabel setUserInteractionEnabled:YES];

    UIPanGestureRecognizer* panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGestureForFillInBlank:)];
    [optionLabel addGestureRecognizer:panGesture];

    return optionLabel;
}

This Method will help in drag & drop functionality
    - (void)handlePanGestureForFillInBlank:(UIPanGestureRecognizer*)sender{

        __block BOOL isDragOnBlank = NO;

        NSInteger tag = sender.view.tag;
        OptionsFrame senderRect = optionRect[tag];

        if (sender.state == UIGestureRecognizerStateBegan) {

        }
        else if (sender.state == UIGestureRecognizerStateChanged) {
            CGPoint translation = [sender translationInView:sender.view];
            sender.view.center = CGPointMake(sender.view.center.x + translation.x, sender.view.center.y + translation.y);
            [sender setTranslation:CGPointZero inView:sender.view];
        }
        else if (sender.state == UIGestureRecognizerStateEnded || sender.state == UIGestureRecognizerStateCancelled) {

            for (UIView* blankView in self.blankViewContaninerList) {
                if (CGRectIntersectsRect(sender.view.frame, blankView.frame) && blankView.tag != -999) {
                    __weak typeof(self) weakSelf = self;
                    UILabel* selectedLabel = (UILabel*)sender.view;

                    [self computeAnswerFromSelectedLabel:selectedLabel blankView:blankView onCompletion:^(BOOL isCorrectAnswer, NSString *selectedAnswer) {
                        if (isCorrectAnswer) {

                            [selectedLabel setUserInteractionEnabled:NO];

                            blankView.tag = -999;   // Indicates that blank view already contains one label (blank space is already filled)

                            [UIView animateWithDuration:0.25 animations:^{
                                [sender.view setCenter:blankView.center];
                            } completion:^(BOOL finished) {
                                if (weakSelf.correctAnswerCount == weakSelf.totalOptionCount) {
// Your custom logic goes here, after all option dragged on their respective places.
                                }
                            }];
                        }
                        else{
                            [UIView animateWithDuration:0.25 animations:^{
                                [sender.view setFrame:CGRectMake(senderRect.origin.x, senderRect.origin.y, senderRect.size.width, senderRect.size.height)];
                            }];
                        }
                        isDragOnBlank = YES;
                    }];
                }
            }
            if(!isDragOnBlank) {
                [UIView animateWithDuration:0.25 animations:^{
                    [sender.view setFrame:CGRectMake(senderRect.origin.x, senderRect.origin.y, senderRect.size.width, senderRect.size.height)];
                }];
            }
        }
    }

This Method will tell you dragged option empty space is correct or wrong
- (void)computeAnswerFromSelectedLabel:(UILabel*)selectedLabel
                             blankView:(UIView*)blankView
                          onCompletion:(void(^)(BOOL isCorrectAnswer, NSString* selectedAnswer))onCompletion {

    NSInteger tagIndex = (blankView.tag - 600);

    NSString* correctAnswer  = self.card.questionDataModel.fillAnswers[tagIndex];
    NSString* selectedAnswer = selectedLabel.text;

    if ([correctAnswer isEqualToString:selectedAnswer]) {

        self.correctAnswerCount++;

        if (onCompletion) {
            onCompletion(YES, selectedAnswer);
        }
    }
    else {
        self.wrongAnswerCount++;

        // Shake the container view if dragging is wrong.
        [self shakeView:self.fillBlankContainerView withOffest:8];
        if(onCompletion){
            onCompletion(NO, selectedAnswer);
        }
    }
}

Please feel free to use code & improvements are happily welcome :)
Keep coding!

A: You can use UIWebView. And for updating the contents of the blanks you can write javascript inside the HTML pages and bind it with onselect event of the blanks.
You can have a look at my answer iOS UIWebView Javascript - insert data -receive callbacks?
to know more about communicating with a webview. (i.e. executing javascript from Objective C and vice versa)

Update for the comment
Yes, you can pass a string to the webview from outside ,
[webViewInstance stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"displayTheStringInBlank(%@)", stringValue]];

and write a JS function is your HTML file to get and display the string in the blank,
function displayTheStringInBlank(stringValue)
{
//Write code to use the string in the blank
document.getElementById("yourInputIdElement").value = stringValue;

}

A: I sometimes use special tags in NSMutableStrings as placeholders for replacement strings, then replace them as needed with code like...
if ([cStr rangeOfString:@"MYTAG"].location != NSNotFound)
    [cStr replaceCharactersInRange:[cStr rangeOfString:@"MYTAG"] withString:myNewString];

If you need any kind of nice formatting, using UIWebView would be the way to go.


text:
Q: PHP cURL: curl_exec to a webform that redirects I'm new to cURL and I am having a bit of an issue getting it to work. I need to send some parameters, as well as upload a file to a webform. The webform in question will take the file and the input parameters and convert the file to another format. When using this webform directly, submit redirects to a new page that displays a progress bar showing the progress of the file conversion. On completion a download link appears.
What I need to do is submit a file (with parameters), wait for the conversion to complete, download the file and proceed with my PHP code that processes the downloaded file. However, I'm having a hard time with cURL and I'm not sure if it has something to do with the redirect to the page with the progress bar that occurs. Example code is below:
$full_file_path = realpath($inputfile);
$data = array('param1' => '1', 'param2' => '2', 'file' => '@'.$full_file_path);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/Converter/index.pl');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);

#get converted file

$file_head=substr($inputfile, 0, strpos($inputfile, '.raw'));
$output_file=$file_head.".mzXML";
$url="http://example.com/Converter/temp/".$output_file;
$fp = fopen ($output_file, 'w+');

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
curl_close($ch);

The initial instance of $response returns the empty webform. I get no errors with curl_error and from curl_getinfo I can see that I am correctly connecting to the server, however the file conversion process should take ~5minutes while the curl process completes in <1 sec. I'm not sure what's going wrong or how to get more info to tell me what's happening. My best guess is it has something to do with the redirect but I don't know for sure.
Any help is much appreciated.
EDIT
Here is the output from CURLOPT_VERBOSE

*

*Adding handle: conn: 0x7fa754818000

*Adding handle: send: 0

*Adding handle: recv: 0

*Curl_addHandleToPipeline: length: 1

*Conn 16 (0x7fa754818000) send_pipe: 1, recv_pipe: 0

*About to connect() to example.com port 80 (#16)

*Trying XX.XXX.XXX.XXX...

*Connected to example.com (XX.XXX.XXX.XXX) port 80 (#16)

*POST /Converter/index.pl HTTP/1.1

*Host: example.com

*Accept: /

*Content-Length: 249010577

*Expect: 100-continue

*Content-Type: multipart/form-data; boundary=----------------------------52f3c644b6de

*HTTP/1.1 100 Continue

*HTTP/1.1 200 OK

*Date: Fri, 01 May 2015 14:01:17 GMT

*Server Apache/2.2.22 (Win32) is not blacklisted

*Server: Apache/2.2.22 (Win32)

*Transfer-Encoding: chunked

*Content-Type: text/html; charset=ISO-8859-1

*Connection #16 to host example.com left intact

A: I guess you can use header() to redirect the user to the converted file, also, remove the last curl, and use  CURLOPT_FOLLOWLOCATION, true on the first curl i.e.:
$full_file_path = realpath($inputfile);
$data = array('param1' => '1', 'param2' => '2', 'file' => '@'.$full_file_path);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/Converter/index.pl');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);

#get converted file

$file_head=substr($inputfile, 0, strpos($inputfile, '.raw'));
$output_file=$file_head.".mzXML";
$url="http://example.com/Converter/temp/".$output_file;
$fp = fopen ($output_file, 'w+');

header("Location: $url");


text:
Q: .NET Core WebApi Secure Hangfire Dashboard with Azure AD Login I am currrently trying to secure the access to Hangfire Dashboard.
As I am using a .NET Core WebApi I do not really know how to secure the dashboard with Azure AD.
I tried to use a Policy, but without success:
services.AddAuthorization(options =>
            {
                // Policy to be applied to hangfire endpoint
                options.AddPolicy(AppConstants.HangfirePoilicyName, builder =>
                {
                    builder
                        .AddAuthenticationSchemes(AzureADDefaults.AuthenticationScheme)
                        .RequireAuthenticatedUser();
                });
            });

And here the Configure method:
app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller}/{action=Index}/{id?}")
                    .RequireAuthorization();

                endpoints.MapHangfireDashboard("/hangfire", new DashboardOptions()
                    {
                        Authorization = new List<IDashboardAuthorizationFilter> { }
                    })
                    .RequireAuthorization(AppConstants.HangfirePoilicyName);
            });

What I expect is when I go to the Hangfire Dashboard that I see the Microsoft Login through Azure AD and then login to my tenant and gain access to the dashboard.
Maybe worth to mention: Default authentication is JWTBearerDefaults, but for the Hangfire Dashboard I need AzureAdDefaults

A: Some preamble information:

*

*The solution I have is for implementations that follow the MSAL 2 flows, using .NET Core 6.

*For the statement:

Default authentication is JWTBearerDefaults, but for the Hangfire
Dashboard I need AzureAdDefaults

AzureAdDefaults is now obsolete, so you would need to use something else, like the JWTBearerDefaults, but read on to see how I got my implementation working.

*

*Another confusing thing for me was having a WebApi which also acted as a WebApp, since you're enabling application-like authentication on certain endpoints, but on others, not. Turns out this is possible.

Solution:
I came across this nugget after quite a lot of browsing through code samples:
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
          .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
              .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
                  .AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
                  .AddInMemoryTokenCaches();

services.AddAuthentication()
        .AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAd"),
                                    JwtBearerDefaults.AuthenticationScheme)
        .EnableTokenAcquisitionToCallDownstreamApi();

Essentially, this is saying you can have 2 separate calls to .AddAuthentication(...), with 1 chaining the AddMicrosoftIdentityWebApp call, and another the AddMicrosoftIdentityWebApi call, specifying which authentication to use in both cases.
For me, I setup my Api to authenticate with JwtBearerDefaults.AuthenticationScheme, and the WebApp portion uses OpenIdConnectDefaults.AuthenticationScheme, making it look like this:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAd"),
                                  JwtBearerDefaults.AuthenticationScheme);

services.AddAuthentication()
            .AddMicrosoftIdentityWebApp(Configuration, "AzureAd", OpenIdConnectDefaults.AuthenticationScheme);

Next, setup a policy for Hangfire to use, which matches the scheme previously setup for the WebApp portion.
services.AddAuthorization(options =>
        {
            options.AddPolicy("azureAdPolicy", builder =>
            {
                builder
                    .AddAuthenticationSchemes(OpenIdConnectDefaults.AuthenticationScheme)
                    .RequireAuthenticatedUser();
            });
        });

I then created some extension methods for setting up the Hangfire services and routes.
public static IServiceCollection AddHangfireService(
        this IServiceCollection services,
        IConfiguration configuration)
    {
        services.AddHangfireServer();
        services.AddHangfire(cfg =>
        {
            // Additional setup code
        });
        return services;
    }

Called like so:
 services.AddHangfireService(Configuration);

For the routing:
public static IEndpointRouteBuilder AddHangfireRoute(this IEndpointRouteBuilder endpoints,
        HangfireDBOptions hangfireDbOptions)
    {
        endpoints.MapHangfireDashboard("/hangfire", new DashboardOptions
        {
            DashboardTitle = "Your App Title",
            AppPath = hangfireDbOptions.BackToSiteUrl,
            Authorization = new[]
            {
                new HangfireDashboardAuthFilter() // if you need a filter
            }
        })
        .RequireAuthorization("azureAdPolicy"); // Matches your policy name
        return endpoints;
    }

Which is called like so:
app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers(); // Call this first

            endpoints.AddHangfireRoute(hangfireOptions);
        });

The only thing left to do is properly configure the routes for your Hangfire routes in your Azure AD environment.
On your App Registration, add a Web application type, and add the following routes:

*

*(your base application URL)/signin-oidc

*(your base application URL)

*(your base application URL)/hangfire

And make sure to have the ID Token checkbox selected

That should be it :) Hope this helps, your application might be using other auth flows or older library versions etc - this is what I got working which is currently used in production. I would recommend you upgrade your packages anyway as there are a lot of 'better' auth flows to use, and as I mentioned, some features are now obsolete.
Humble apologies again for the delayed answer, was quite a lot of information to compile

A: I think you are missing an AddAuthentication call for the AzureAdDefaults:
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
        .AddAzureAD(options => Configuration.Bind("AzureAd", options));

With this call the rest of code should work. As you mentioned your policy must be against AzureAdDefaults so you need to add authentication for the scheme.
Where AzureAd is the following configuration:
"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "[Enter the domain of your tenant, e.g. contoso.onmicrosoft.com]",
    "TenantId": "[Enter 'common', or 'organizations' or the Tenant Id (Obtained from the Azure portal. Select 'Endpoints' from the 'App registrations' blade and use the GUID in any of the URLs), e.g. da41245a5-11b3-996c-00a8-4d99re19f292]",
    "ClientId": "[Enter the Client Id (Application ID obtained from the Azure portal), e.g. ba74781c2-53c2-442a-97c2-3d60re42f403]"
}


text:
Q: Can we apply custom shaders to three.js objects dynamically I have a MeshBasicMaterial with VideoTexture. Can I apply custom shaders to the material dynamically. I was able to apply shader to the complete scene using THREE.EffectComposer but what if I want to apply custom filters to a specific element inside the scene. I want to test simple filters like sepia, hue-saturation. Also I must be able to switch between the two without reloading the project.
I did not go with js libraries like seriously.js or glfx.js because it may cause problem at later stages when I will work with three.js objects not having canvas/img/video as map.
videoTexture = new THREE.VideoTexture(video);
videoTexture.minFilter = THREE.LinearFilter;
videoTexture.magFilter = THREE.LinearFilter;
material = new THREE.MeshBasicMaterial({
    map: videoTexture,
    side: THREE.DoubleSide,
    transparent: true,
    depthTest: false,
    depthWrite: false
});

composer = new THREE.EffectComposer( renderer );
composer.addPass( new THREE.RenderPass( scene, camera ) );
var effect = new THREE.ShaderPass( THREE.SepiaShader );
effect.renderToScreen = true;
composer.addPass( effect );
composer.render();

Edit 1: filter css( https://developer.mozilla.org/en-US/docs/Web/CSS/filter) won't work either as it only changes visual media and hence though it can manipulate final canvas it can not manipulate internal object textures.

A: THREE.EffectComposer has a .reset function that you could use to wipe it, and then add the new filters you want. So just load the different filters you want to cycle through into an array, then reset and add passes from that array.
EDIT I thought you were talking about changing shaders in the composer. To change shaders on an object, you can create multiple shadermaterials with different shaders but referencing the same texture, and swap the materials out on the object. So you can write a shader that reinterprets the texture colorspace to sepia, one that reinterprets the texture colorspace to bnw, or swizzles hue and saturation with r,g, or b.
Then you swap multiple materials out on the fly. These effects are basic glsl, but if you have trouble writing the shaders, just post another thread with specific problems. If you're a glsl novice, I highly recommend  the book of shaders. It's a great, fast, interactive crash course on glsl.
But the solution to your problem is to create multiple shadermaterials, or create one shader material that does everything and then use uniforms to enable/lerp between the different effects.


text:
Q: Движение двух объектов (actor) одновременно при касании экрана public void create() {

//код

stage = new Stage();

stage.addActor(tank); // оба танка наследуются от 1 класса
stage.addActor(tank2);

Gdx.input.setInputProcessor(stage);
}

рендер
public void render() {
//код
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
//код
}

оба actor отображаются, но реагирует на нажатие лишь tank2.
Как сделать так, чтоб при нажатии 1 пальцем оба actor'а реагировали одновременно?
Пробовал InputMultiplexer, но так они реагируют на нажатия 2 пальцами (причем каждый actor на 1 палец по очереди).

в описании к классу Stage:
If an actor handles an event by returning true from the input method, then the stage's input method will also return true, causing subsequent InputProcessors to not receive the event.
Если actor обработал событие, возвращая истину от input method, то  input method класса Stage также возвратит истину, в результате последующий InputProcessors не получит событие.

A: Вам нужно просто добавить один и тот же InputListener и тому, и другому объекту.
Если я правильно понял, то вам нужно что-то такое:
InputListener myListener = new InputListener() {
    @Override
    public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
        // Двигаем объекты
        tank.move();
        tank2.move();

        return true; // Говорим, что нажатие было обработано
    }
};
tank.addListener(myListener);
tank2.addListener(myListener);


text:
Q: Read & write in csv using python I'm trying to fetch data from a FTP server every 5 minutes .with that data i need to do some process like fetching high,low values.For this i'm converting the .sec.gz to a csv(csv is comfortable for me identify the valuse).have to process around 4000 lines in a single file.likewise have to do for every 5 mins in a day.Firstly i'm retreiving a csv and then i'm replacing the header in that csv.In this process some of the files got stucked with incomplete data in the second csv.
My code is:
ip="ip address"
password='password'
file_connect=[]
file_sec=[]
interval=1
starttime=time.time()

for interval in range(1000):
    ftp=FTP('ip address')
    ftp.login('username',password)
    #print "File List:"
    files=ftp.dir()
    date_filename='c:/DATA_INTV_NEW/'
    filematch='C:/DATA_INTV_NEW/*'
    filer=ftp.nlst(date_filename)
    for files in filer:
        if files!='C:/DATA_INTV_NEW/June062014':
            data1=files
            #print data1
    date_a=data1.split('/')
    date_b=date_a[2]
    #print date_b
    day_all=date_b[-6:-4]
    year_all=date_b[-4:]
    month_all=date_b[0:-6]
    monthDict = {'January':'1', 'February':'2', 'March':'3', 'April':'4', 'May':'5', 'June':'6',
                                'July':'7', 'August':'8', 'September':'9', 'October':'10', 'November':'11', 'December':'12'}
    month_all = monthDict[month_all]
    Date=day_all+"/"+month_all+"/"+year_all
    #print Date
    filenames=ftp.nlst(filematch)
    #print filenames
    mypath1='C:\\test\\'+date_b
    #os.makedirs(mypath1)
    #if (interval==1):
      #  mypath1='C:\\test\\'+date_b
        #os.makedirs(mypath1)

    for file_ in natsorted(filenames):
        if ((file_ not in file_connect) & (file_ in filenames)):
            if file_.endswith('.sec.gz'):
                file_c=file_.split('/')
                file_d=file_c[3]
                print file_d
                Files=date_b+'\\'+file_d
                print Files
                ftp.retrbinary('RETR C:/DATA_INTV_NEW/'+Files, open(mypath1+'\\'+file_d, 'wb').write)
        file_connect.append(file_)
    ftp.quit()
    #time.sleep(60)

    #Setting the path
    path = mypath1+'//*.sec.gz'
    file_s=glob.glob(path)

    #Creating a historical data csv where all the data to be fed
    fl=open(mypath1+"//final2.csv","ab")
    writer = csv.DictWriter(fl, fieldnames = ["S No", "Instrument Name", "High", "Low", "Open", "Close", "V" ,"Time" , "Date"])
    writer.writeheader()

    header = ["Instrument Name", "High", "Low", "Open", "Close", "V", "Time", "Date"]

    #Setting the start time as 9:15 am
    start_time=timedelta(hours=9,minutes=15,seconds=0)

    #Real process
    #if (files==file_s):
    for file_group in natsorted(file_s):
        if ((file_group not in file_sec) & (file_group in file_s)):
            f = gzip.open(file_group, 'rb')
            a=f.read()
            def stripped(x):
                return "".join([i for i in x if 31 < ord(i) < 127])
            b = stripped(a)

            if 'OPT' in b:
                c=string.split(b, 'OPT')

            #Stripped Opt symbol is added again
                for line in c:
                    if line[0:2]!='FUT':
                        line='OPT'+line
                        d=line

                    #Split lines into lines wrt Futures
                    if 'FUT' in d:
                        e=string.split(d,'FUT')

                        #Stripped fut symbol is added again
                        for line in e:
                            if line[0:2]!='OPT':
                                line='FUT'+line

                        #Separating the fields using Comma
                    i=0

                    #Conversion to list

                    g=list(line)
                    for g[i] in g:
                        if (i==5 or i==16 or i==28 or i==39 or i==42 or i==44 or i==55 or i==68 or i==79 or i==92 or i==103 or i==116 or i==127 or i==139 or i==150 or i==161 or i==172 or i==183 or i==194 or i==205 or i==216 or i==228):
                            g.insert(i+1,",")

                        i+=1
                        #Conversion back to string

                    h="".join(g)

                    #Writing into .txt or .csv file

                    num, ext = os.path.basename(file_group).split(".", 1)

                    output_filename = os.path.join(os.path.dirname(file_group), "%s.csv" % (num,))

                    fn=open(output_filename,"ab")
                    fn.write(h + '\n')
                    fn.close

                #Removing Blank & none types
                with open(output_filename,"rb") as inf:
                    next(inf)  # skip header row
                        #Adding header
                    num1, ext1 = os.path.basename(file_group).split(".", 1)
                    output_filename1 = os.path.join(os.path.dirname(file_group), "%sa.csv" % (num1,))
                    f1=open(output_filename1,"ab")
                    writer = csv.DictWriter(f1, fieldnames = ["Instrument Name", "Symbol", "Expiry Date", "Strike Price", "Option Type","Market Type", "Buy Price", "Buy Quantity", "Sell Price", "Sell Quantity", "Last Traded Price", "Total Traded Quantity", "Average Traded Price", "Open Price", "High Price", "Low Price", "Close Price", "High", "Low", "Open", "Close", "V", "Quant", "Time", "Date"])
                    writer.writeheader()
                    #Removing emptylines
                    for line in inf:
                        if not line:
                            empty_lines += 1
                            continue
                            #print line
                        count_c=1
                        g1=list(line[count_c] for count_c in range(23))
                        h1="".join(g1)
                        f1.write(h1)
                    f1.close  #stucking in this part

            start_time=start_time+timedelta(seconds=300)
        file_sec.append(file_group)
    time.sleep(300.0 - ((time.time() - starttime) % 300.0))

Please help me to solve the issue.I'll show the output what i'm getting.For example my readable file has contents:
OPT{T
OPTSTK  AMBUJACEM   24/12/2014  240 CE  N   3.1 2000    3.3 4000    3.25    24000   3.21    4   4   2.9 3.5
OPTSTK  BPCL        24/12/2014  820 CE  N   6.85    1500    7.35    1500    7   21000   7.42    8.15    8.75    6.95    7.7
OPTSTK  DIVISLAB    24/12/2014  1750    CE  N   36.4    1500    48.2    375 46.05   0   0   0   0   0   46.05

in destination file:
Instrument Name Symbol  Expiry Date Strike Price    Option Type Market Type Buy Price   Buy Quantity    Sell Price  Sell Quantity   Last Traded Price   Total Traded Quantity   Average Traded Price    Open Price  High Price  Low Price   Close Price
OPTSTK  AMBUJACEM   24/12/2014  240 CE  N   3.1 2000    3.3 4000    3.25    24000   3.21    4   4   2.9 3.5
OPTSTK  BPCL        24/12/2014  820 CE  N   6.85    1500    7.35    1500    7   21000   7.42    8.15    8.75    6.95    7.7
OPTSTK  DIVISLAB    #here columns are missing


text:
Q: Scala to Java migration method definition not clear In order to reduce the number of technologies used in one of the projects I'm working on I'm trying to migrate few Scala classes to Java. Totally inexperienced in Scala I'm trying to convert this method:
private val subscriptionStore = new ConcurrentHashMap[String, Promise[PushMessage]]()

def subscribe[T](msgType: PushMessageType, callerId: String, ctx: Context)(parser: PushMessage => T): Future[T] = {
    val notificationPromise = Promise[PushMessage]
    subscriptionStore.put(toKey(callerId, msgType.notificationString), notificationPromise)
    notificationPromise.future.map(parser(_))(VertxExecutionContext.apply(ctx))
}

My current Java version
private ConcurrentHashMap<String, CompletableFuture<PushMessage>> subscriptionStore = new ConcurrentHashMap<>();

public CompletableFuture<PushMessage> subscribe(PushMessageType msgType, String callerId, Context ctx) {
    CompletableFuture<PushMessage> future = new CompletableFuture<>();
    return subscriptionStore.put(toKey(correlationId, msgType.notificationString), future);
}

toKey returns a String value
My main issue is the method declaration
def subscribe[T](msgType: PushMessageType, callerId: String, ctx: Context)(parser: PushMessage => T): Future[T]

Any suggestion?
Many thanks

A: The simplest form (not the purest functional form) is without multiple parameter lists, i.e. convert
def subscribe[T](msgType: PushMessageType, callerId: String, ctx: Context)(parser: PushMessage => T): Future[T]

to
def subscribe[T](msgType: PushMessageType, callerId: String, ctx: Context, parser: PushMessage => T): Future[T]

to pass the parser function in Java 8, you can do something like this:
import java.util.function.*;

class FunctionTest {

    public static Integer subscribe(String msgType, Function<String,Integer> parser) {
        return parser.apply(msgType);
    }

    public static void main(String[] args) {
        Function<String,Integer> parserImpl = (a) -> a.length();
        System.out.println(subscribe(args[0], parserImpl));
    }
}

A: First of all I'd say that subscribe method that uses Future in Scala (i.e. something that can be fired only once) sounds suspicious to me. It would be really much easier to help you, if you provided more context on how this method is used and who/when/how fires (resolves) the Promises.
For now let's assume that you want to translate Scala code as closely as possible to Java. To do this let's first understand what Scala code does.
def subscribe[T](msgType: PushMessageType, callerId: String, ctx: Context)(parser: PushMessage => T): Future[T] = {
    val notificationPromise = Promise[PushMessage]
    subscriptionStore.put(toKey(callerId, msgType.notificationString), notificationPromise)
    notificationPromise.future.map(parser(_))(VertxExecutionContext.apply(ctx))
}

First signature
def subscribe[T](msgType: PushMessageType, callerId: String, ctx: Context)(parser: PushMessage => T): Future[T] = {

It means that this is a "partially applied" method i.e. this is effectively a method with 4 arguments: msgType, callerId, ctx, and parser but you call it using to set of brackets such as subscribe(msgType, callerId, ctx)(parser). The important part here is that in Scala you can do something like this:
val partialApplication = subscribe(msgType, callerId, ctx)

// much later or in a different place

val future = partialApplication(parser)

Note that if this feature is not used in Scala for subscribe you can safely merge arguments into one set and get much simpler Java code as @motilio suggests. I'll assume that you really need this partial application usage. IMHO, the simplest way so simulate the same behavior in Java is to have a method that returns a java.util.Function.
Now the body of the subscribe:
    val notificationPromise = Promise[PushMessage]
    subscriptionStore.put(toKey(callerId, msgType.notificationString), notificationPromise)
    notificationPromise.future.map(parser(_))(VertxExecutionContext.apply(ctx))

We create a notificationPromise which is similar to ComputableFuture and put it into subscriptionStore. And then we return a different Future that is calculated as result of the future inside notificationPromise modified by applying parser lambda to it, and execute that on an Executor specified by call to VertxExecutionContext.apply(ctx).
So reasonably similar code in Java would be something like this:
private final ConcurrentHashMap<String, CompletableFuture<PushMessage>> subscriptionStore = new ConcurrentHashMap<>();

public <T> Function<Function<PushMessage, T>, CompletableFuture<T>> subscribeLikeScala(PushMessageType msgType, String callerId, Context ctx) {
    CompletableFuture<PushMessage> future = new CompletableFuture<>();
    subscriptionStore.put(toKey(callerId, msgType.notificationString), future);
    return fn -> future.thenApplyAsync(fn, new Executor() {
        @Override
        public void execute(Runnable command) {
            ctx.runOnContext(ignore -> command.run());
        }
    });
}

Custom Executor implementation here is based on VertxExecutionContext Scala source.
And usage example might be something like (obviously just returning hashCode is a stupid parser but this is an example):
Function<Function<PushMessage, Integer>, CompletableFuture<Integer>> partialApplication = subscribeLikeScala(msgType, callerId, ctx);

// much later or in a different place

CompletableFuture<Integer> future = partialApplication.apply(msg -> msg.hashCode());

The fact that you need to specify type of the parser at the moment you call subscribe rather than apply might be either a plus or a minus depending on what you need. Given how easy it is actually to apply transformation to ComputableFuture in Java using thenApplyAsync, it might be OK to just use your signature and left application of the parser to the caller. The only thing that you loose here is a control over which executor will be used to apply parser which might or might not be important for you. But beware that your logic with
return subscriptionStore.put(toKey(correlationId, msgType.notificationString), future);

seems like almost 100% bug because ConcurrentHashMap.put returns the previous value stored under the same key which is almost definitely not what you want and surely not what Scala code did.
Lastly and getting back to what I started with, subscription that can be fired only once is really strange and is possibly a bad hack. Your usage scenario might be covered much better by RxJava Observable. I strongly encourage you considering it in your context.


text:
Q: What does "a satisfactory conclusion the UN Security Councilˈs consideration of this matter" mean?
There would be additional steps in between the initial measures and the final step, including, among other things, addressing the UN Security Council resolutions, with a view toward bringing to a satisfactory conclusion the UN Security Councilˈs consideration of this matter.

For context: here
1)Is there any redundancy in "including, among other things"?
2)This part seems a bit odd: with a view toward bringing to a satisfactory conclusion the UN Security Councilˈs consideration of this matter.
What is the apostrophe s contradiction for?

A: The confusion seems to be a result of a heavy NP shift (heavy noun phrase shift).
Consider:

with a view toward bringing it to a conclusion.
with a view toward bringing to a conclusion it.*
* denotes incorrect usage

We wouldn't move it to the end of the sentence because it is too light. However, in our sentence we instead have the UN Security Council's consideration of this matter, which is a heavy NP (noun phrase), so it can be shifted to the end.

with a view toward bringing to [a satisfactory conclusion] [the UN Security Council's consideration of this matter].

It might be easier to understand the phrase by moving the heavy NP back:

with a view toward bringing [the UN Security Council's consideration of this matter] to [a satisfactory conclusion].

With that, it should be easy to see that this heavy NP is simply the "Council's consideration", where "Council" means the UN Security Council, and the "consideration" means the consideration of this matter, and it's the Council's consideration.
The part "addressing the UN Security Council resolutions, with a view toward bringing to a satisfactory conclusion the UN Security Councilˈs consideration of this matter" would refer to such addressing and it means that the addressing would be done with a view toward bringing the Council's consideration to a satisfactory conclusion.

As for whether including, among other things is redundant or not, I would say that it can be considered redundant; however, in my opinion, if we removed the among other things part, the addressing would appear to be less important than it currently is, as it appears in the original sentence.

A: Among other things is more in the nature of semantic fluff, although it is redundant. The existence of "other things" is implied by the use of the word including. Otherwise, it might have been phrased like this:

There would be additional steps in between the initial measures and the final step, consisting of addressing the UN Security Council...

So yes, it is redundant. In the context, among other things appears to me to be adding useless length to the sentence. It's a misguided attempt at sounding impressive. ("I'll just throw more words at them. They'll never know the difference! Bumblebee. Gorgonzola. Chlorophyll. Soliloquy.")
As to the apostrophe, it is used to indicate a possessive form of "The UN Security Council". The sentence could be correctly re-written like this:

...with a view toward bringing to a satisfactory conclusion the Councilˈs consideration of this matter.

Which could then be more plainly be re-written like this:

...with the intention of helping the Council to finish their deliberations on the issue.

When the modifiers are stripped, the possessive form of the noun becomes clear. The apostrophe is "correctly" used, in the sense that it is syntactically correct. However, the full extract would be easier to read if it were written like this:

Additionally, before the final step, there would be an address to the UN Security Council. It would be intended to help the Council conclude their deliberations in a manner that would be satisfactory to all parties.


text:
Q: Calling R from Python, passing parameters, R reports: "object of type 'closure' not subsettable" I am trying to use the R package igraph to map mesh networks at various different locations.
The data to do this is in a MySQL database. I can query the database, write the data to a csv file, and generate the graphs I want by having R read in the csv files with no problem.
My problem is that I now need to script this process up so that it can be done at will for all 50 locations we have. Previously I was manually changing values to produce graphs peace-meal.
I am trying to use Python as my scripting language to tie everything together.
Here is the relevant bit of my Python script:
import mysql.connector
import csv
import subprocess
localConnection = mysql.connector.connect(xxxx)

....CODE BLOCK DEFINING SQL QUERIES OMITTED....

facilityCursor = localConnection.cursor()
wLinksCursor = localConnection.cursor()
wNodesCursor = localConnection.cursor()
gatewayCursor = localConnection.cursor()

facilityCursor.execute(facilityQuery)
facility = facilityCursor.fetchone()
while facility is not None:
    print facility[0]
    wLinksCursor.execute(weightedLinksQuery % facility[0])
    wLinks = wLinksCursor.fetchall()
    linkWriter = csv.writer(open('/tmp/weightedLinks.csv', 'w'))
    for row in wLinks:
        linkWriter.writerow(row)
    wNodesCursor.execute(weightedNodesQuery % facility[0])
    wNodes = wNodesCursor.fetchall()
    nodeWriter = csv.writer(open('/tmp/weightedNodes.csv', 'w'))
    for row in wNodes:
        nodeWriter.writerow(row)
    gatewayCursor.execute(determineGatewayQuery % facility[0])
    gateways = gatewayCursor.fetchall()
    gateWriter = csv.writer(open('/tmp/gatewayWriter.csv', 'w'))
    for row in gateways:
        gateWriter.writerow(row)

    command = 'Rscript'
    path2script = '/pathToScript/networkMapper2.R'
    args = ['/tmp/weightedLinks.csv', '/tmp/weightedNodes.csv', '/tmp/gatewayWriter.csv', facility[0]]
    cmd = [command, path2script] + args
    subprocess.Popen(cmd)
    facility = facilityCursor.fetchone()

And now the R script that is being called:
library(igraph)

wlinks <- read.csv(toString(args[1]), header=T)
wnodes <- read.csv(toString(args[2]), header=T)
gateways <- read.csv(toString(args[3]), header=T)
fac <-  toString(args[4])

gateways <- as.vector(gateways[2:14,])
nodeList <- wnodes$address
func <- function(x) {x %in% gateways}
truthTable <- lapply(wnodes, func)
wnodes <- as.data.frame(cbind(wnodes,truthTable$address))

getColors <- function(x){if (x == TRUE) {x = 2} else {x = 1}}
wow <- as.matrix(lapply(wnodes$truthTable, getColors))
wnodes <- cbind(wnodes,wow)

net <- graph.data.frame(wlinks, wnodes, directed=T)
net <- simplify(net, remove.multiple = F, remove.loops = T)

E(net)$width <- E(net)$frequency/4
V(net)$size <- V(net)$frequency*0.04 + 1
V(net)$color <- gsub(TRUE, "blue", wnodes$wow)

g <- layout.fruchterman.reingold
l <- layout.kamada.kawai(net)
graphTitle <- paste("Network Visualization For ", fac, "On ", Sys.Date())
graphFileName <- paste("/tmp/", fac, "_Network_Visualization_", Sys.Date())
png(file=graphFileName, width=1500, height=1500)
plot(net, edge.color="azure4", vertex.frame.color="gray80", edge.arrow.size = 2,
     layout=g, vertex.label=wnodes$address, vertex.label.degree=0, vertex.label.dist=0.25,
     vertex.label.font = 2, vertex.label.cex = 1.2, vertex.label.color = "black", frame=TRUE,
     main=graphTitle)
dev.off()

And finally the error I'm getting when I try to run the Python script:
Loading required package: methods

Attaching package: 'igraph'

The following objects are masked from 'package:stats':

    decompose, spectrum

The following object is masked from 'package:base':

    union

Error in args[1] : object of type 'closure' is not subsettable
Calls: read.csv -> read.table -> toString
Execution halted


text:
Q: Accessing protected members in base class objects Consider:
class A {
protected:
    int _i;
};

class B : public A {
    B(const B & object) {
        _i = object._i;
    };

    B(const A & object) {
        _i = object._i;
    };
};

First copy constructor is correct, because permissions are based on classes, not on objects. So I can reach protected members from my own class objects.
Why second constructor (or any similar method) raises compile time error?
In short: Why permission checking in C++ does not regard class inheritance rules in this case?
Also this was encountered in Apple LLVM-4.2 but not in Apple LLVM-4.1.

A:
In short: Why permission checking in C++ does not regard class inheritance rules in this case?

You're asking for rationale behind the rule which prohibits the second constructor.
To understand the rationale, consider this code:
A a;
a._i = 100; //error, _i is protected

That is correct, and expected. So far, so good.
But if the second constructor is allowed (in your code), then anyone can write a class modify as:
struct modify : public A {
    void i(A & object, int newValue) {
        object._i = newValue; //MODIFY THE PROTECTED MEMBER of the argument!
    };
};

And then you can do this instead:
A a;
modify().i(a, 100); //okay, indirectly modify a._i !!!
std::cout << a._i << std::endl; //prints 100

If the second constructor can access the protected member of the argument, then modify::i() can also do the same! That way you actually modify the protected members!


text:
Q: How do I compile a .cpp file on Linux? I'm fairly comfortable with Linux and compiling things - I normally just follow the instructions and can manage to get myself out of trouble. This time, I was given a .cpp file by a random Internet citizen and I would really like to know how to compile it. Everything I seem to try (g++, c++, gcc) doesn't seem to work.
Anyhow, here's the file: http://pastebin.ca/2073013
Edit: Updated with verbose output from g++ file.cpp -o whatever: http://pastebin.ca/2073052

A: You'll need to compile it using:
g++ inputfile.cpp -o outputbinary

The file you are referring has a missing #include <cstdlib> directive, if you also include that in your file, everything shall compile fine.

A: The compiler is telling you that there are problems starting at line 122 in the middle of that strange FBI-CIA warning message.  That message is not valid C++ code and is NOT commented out so of course it will cause compiler errors.  Try removing that entire message.
Also, I agree with In silico: you should always tell us what you tried and exactly what error messages you got.

A: Just type the code and save it in .cpp format. then try "gcc filename.cpp" . This will create the object file. then try "./a.out" (This is the default object file name). If you want to know about gcc you can always try "man gcc"


text:
Q: How do i access and store two dimension list value in scala? In Scala Programming Language, how does one store the value of the two dimensional list?
var lists = List[List[Double]]

How do i assign the value to it in a way like
lists(0)(1) = 0.4

When i try this way, it says
value update is not a member of List[Double]

What went wrong here, and how to make it right?
Thank you

A: Like said in my comment, you cannot access to n-th element of list like you tried but it will works with an Array :
scala> val a = Array[Array[Double]](Array(1.2))
a: Array[Array[Double]] = Array(Array(1.2))

scala> a(0)(0) = 1.1

scala> a
res16: Array[Array[Double]] = Array(Array(1.1))

If you want to use a mutable List, use ListBuffer like below :
scala> val l = ListBuffer[ListBuffer[Double]](ListBuffer(1.1))
l: scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[Double]] = ListBuffer(ListBuffer(1.1))

scala> l(0)(0) = 10.2

scala> l
res21: scala.collection.mutable.ListBuffer[scala.collection.mutable.ListBuffer[Double]] = ListBuffer(ListBuffer(10.2))

A: If you want to update a List, use the updated method which returns a new List with a single element updated.
val updatedLists = lists.updated(0, lists(0).updated(1, 0.4))

This looks pretty ugly, it's also a bad idea. You should reconsider your choice of datastructure. List is not a good choice if this is what you want to do. If you find yourself needing to do this or using List for anything other than head, tail, or :: you probably don't want a List (Vector is usually a better default collection than List but that's not what this question is about).  Index based reads and especially updates are very slow for Lists and updates potentially require lots of object copying.  It just isn't the purpose of list to do this, they aren't designed for it.
Based on what you are trying to do, you almost certainly want an Array or ArrayBuffer like alifirat says.  Arrays are mutable are very efficient for random reads and updates.    If you are making updates, you want a mutable structure.  If you absolutely must have an immutable structure you can use Vector which allows for efficient random reads.  Random updates can be better then List but it's still not something you want to do that often.


text:
Q: Aggregate over categories that contain NAs with ddply and lapply? I would like to aggregate a data.frame over 3 categories, with one of them varying. Unfortunately this one varying category contains NAs (actually it's the reason why it needs to vary). Thus I created a list of data.frames. Every data.frame within this list contains only complete cases with respect to three variables (with only one of them changing).
Let's reproduce this:
library(plyr)

mydata <- warpbreaks
names(mydata) <- c("someValue","group","size")
mydata$category <- c(1,2,3)
mydata$categoryA <- c("A","A","X","X","Z","Z")
# add some NA
mydata$category[c(8,10,19)] <- NA
mydata$categoryA[c(14,1,20)] <- NA

# create a list of dfs that contains TRUE FALSE
noNAList <- function(vec){
res <- !is.na(vec)
return(res)
}

testTF <- lapply(mydata[,c("category","categoryA")],noNAList)

# create a list of data.frames
selectDF <- function(TFvec){
res <- mydata[TFvec,]
return(res)
}

# check x and see that it may contain NAs as long
# as it's not in one of the 3 categories I want to aggregate over
x <-lapply(testTF,selectDF)

## let's ddply get to work
doddply <- function(df){
ddply(df,.(group,size),summarize,sumTest = sum(someValue))
}

y <- lapply(x, doddply);y

y comes very close to what I want to get
$category
group size sumTest
1     A    L     375
2     A    M     198
3     A    H     185
4     B    L     254
5     B    M     259
6     B    H     169

$categoryA
group size sumTest
1     A    L     375
2     A    M     204
3     A    H     200
4     B    L     254
5     B    M     259
6     B    H     169

But I need to implement aggregation over a third varying variable, which is in this case category and categoryA. Just like:
group size category sumTest sumTestTotal
1      A    H        1      46          221
2      A    H        2      46          221
3      A    H        3      93          221

and so forth. How can I add names(x) to lapply, or do I need a loop or environment here?
EDIT:
Note that I want EITHER category OR categoryA added to the mix. In reality I have about 15 mutually exclusive categorical vars.

A: I think you might be making this really hard on yourself, if I understand your question correctly.
If you want to aggregate the data.frame 'myData' by three (or four) variables, you would simply do this:
aggregate(someValue ~ group + size + category + categoryA, sum, data=mydata)

   group size category categoryA someValue
1      A    L        1         A        51
2      B    L        1         A        19
3      A    M        1         A        17
4      B    M        1         A        63

aggregate will automatically remove rows that include NA in any of the categories. If someValue is sometimes NA, then you can add the parameter na.rm=T.
I also noted that you put a lot of unnecessary code into functions. For example:
# create a list of data.frames
selectDF <- function(TFvec){
    res <- mydata[TFvec,]
    return(res)
}

Can be written like:
selectDF <- function(TFvec) mydata[TFvec,]

Also, using lapply to create a list of two data frames without the NA is overkill. Try this code:
x = list(mydata[!is.na(mydata$category),],mydata[!is.na(mydata$categoryA),])

A: I know the question explicitly requests a ddply()/lapply() solution.
But ... if you are willing to come on over to the dark side, here is a data.table()-based function that should do the trick:
# Convert mydata to a data.table
library(data.table)
dt <- data.table(mydata, key = c("group", "size"))

# Define workhorse function
myfunction <- function(dt, VAR) {
    E <- as.name(substitute(VAR))
    dt[i = !is.na(eval(E)),
       j = {n <- sum(.SD[,someValue])
            .SD[, list(sumTest = sum(someValue),
                       sumTestTotal = n,
                       share = sum(someValue)/n),
                by = VAR]
           },
       by = key(dt)]
}

# Test it out
s1 <- myfunction(dt, "category")
s2 <- myfunction(dt, "categoryA")

ADDED ON EDIT
Here's how you could run this for a vector of different categorical variables:
catVars <- c("category", "categoryA")

ll <- lapply(catVars,
             FUN = function(X) {
                       do.call(myfunction, list(dt, X))
                   })
names(ll) <- catVars

lapply(ll, head, 3)
# $category
#      group size category sumTest sumTestTotal     share
# [1,]     A    H        2      46          185 0.2486486
# [2,]     A    H        3      93          185 0.5027027
# [3,]     A    H        1      46          185 0.2486486
#
# $categoryA
#      group size categoryA sumTest sumTestTotal share
# [1,]     A    H         A      79          200 0.395
# [2,]     A    H         X      68          200 0.340
# [3,]     A    H         Z      53          200 0.265

A: Finally, I found a solution that might not be as slick as Josh' but it works without no dark forces (data.table). You may laugh – here's my reproducible example using the same sample data as in the question.
qual <- c("category","categoryA")

# get T / F vectors
noNAList <- function(vec){
res <- !is.na(vec)
return(res)
}

selectDF <- function(TFvec) mydata[TFvec,]

NAcheck <- lapply(mydata[,qual],noNAList)

# create a list of data.frames
listOfDf <- lapply(NAcheck,selectDF)

workhorse <- function(charVec,listOfDf){
dfs <- list2env(listOfDf)
# create expression list
exlist <- list()
for(i in 1:length(qual)){
exlist[[qual[i]]] <- parse(text=paste("ddply(",qual[i],
                                  ",.(group,size,",qual[i],"),summarize,sumTest =    sum(someValue))",
                                  sep=""))
}

res <- lapply(exlist,eval,envir=dfs)
return(res)

}

A: Is this more like what you mean? I find your example extremely difficult to understand. In the below code, the method can take any column, and then aggregate by it. It can return multiple aggregation functions of someValue. I then find all the column names you would like to aggregate by, and then apply the function to that vector.
# Build a method to aggregate by column.
agg.by.col = function (column) {
    by.list=list(mydata$group,mydata$size,mydata[,column])
    names(by.list) = c('group','size',column)
    aggregate(mydata$someValue, by=by.list, function(x) c(sum=sum(x),mean=mean(x)))
}

# Find all the column names you want to aggregate by
cols = names(mydata)[!(names(mydata) %in% c('someValue','group','size'))]

# Apply the method to each column name.
lapply (cols, agg.by.col)


text:
Q: Haskell - check whether a 2D list has the same number of rows as columns I have a 2D list [[Int]] in Haskell and I want to check two things:

*

*whether the list has the sam number of rows as columns

*whether the rows have the sam number of elements

For instance:
[[1,2,3], [1,55,9]] has the same number of rows as columns - here 2 - and each row has the same number of elements namely 3.
But
[[1,2], [1,55], [4,7]] has the same number of elements in each row though it has unequal number of rows and columns namely 3r 2c.
yet another example:
[[1,2], [1,55], [4,7,8]] has neither the same number of rows as columns nor each row has the same number of elements.
Actually step 1 includes step 2, am I right??
My attempt:
So what I attempted so far, is this:
listIsEqual :: [[Int]] -> Bool
listIsEqual myList = (all (\x -> length x == (length myList)) )

Right now I get the following error mesage:
Couldn't match expected type `Bool' with actual type `[a0] -> Bool'
In the return type of a call of `all'
Probable cause: `all' is applied to too few arguments
In the expression: (all (\ x -> length x == (length myList)))
In an equation for `listIsEqual':
            listIsEqual myList = (all (\ x -> length x == (length myList)))

Could anyone tell me where the problem is?
Is there also any other ways to solve this problem?

A: GHC's error messages aren't always the most helpful, but in this case it got it right.

Probable cause: `all' is applied to too few arguments

And indeed, you forgot the second argument to all:
listIsEqual myList = all (\x -> length x == length myList) myList
                                                           ^^^^^^

A: For the second task, you can map the length of every row (the number of columns in that row) defining a function
let columnLengths rows = map length rows
Prelude> columnLengths [[1,2], [1,55], [4,7,8]]
[2,2,3]

Now that we have a list containing the lengths of the columns, we have to check whether they are all equal. The function nub in Data.List removes duplicates from a list.
let columnsLengthEqual = (==) 1 . length . nub . columnLengths

Or all together
let columnsLengthEqual = (==) 1 . length . nub . map length

A: Matrix respecting your criteria, are  squared matrix then checking if the square of first 's row's length is equal to the number of element should be ok.
isSquaredMatrix xs@(h:_)  = ((^2) . length $ h) == (length . concat $ xs)
isSquaredMatrix _         =  True

But as it has been pointed out by hammar, this is incorrect since we can have positive outcome using wrong input.
# isSquaredMatrix [[1,2,3],[4,5],[6,7,8,9]]
True -- But this is false

@John,
we use @ into pattern matching when we want to refer to the whole type at the same time we have break it down. An example should give you more insight,
Usually we can define an exhaustive function working on list using pattern matching as follow.
actOnList []     = -- do something when we encounter an empty list
actOnList (x:xs) = -- do something with h, and do another stuff with xs

For example,
actOnList [] = []
actOnList (x:xs) =
    if (pred x)
    then x:xs
    else actOnList xs

Here my function consumme the list until a predicate is satisfied.
We can imagine skipUntilMeetAChar
skipUntilMeetAChar :: [Char] -> Char -> [Char]
skipUntilMeetAChar []  c    = []
skipUntilMeetAChar (x:xs) c =
    if (x==c)
    then x:xs
    else actOnList xs c

As you see when the char is met we'd like to return the list as it, not only the tail, then to do so we need to reconstruct our list using the head x and the tail xs. This can be overcome using @.
skipUntilMeetAChar :: String -> Char -> String
skipUntilMeetAChar []  c    = []
skipUntilMeetAChar l@(x:xs) c =
    if (x==c)
    then l
    else actOnList xs c

Now, regarding ($) operator, this is again some syntactic sugar.
As function application are left associative, this lead us to extensively use bracket to reorder the application of our function, as in the example below.
# f3 (f2 (f1 (f0 x)))

Then to avoid the pain of managing closing parentheses, dollars operator $ have been introduce and then our previous expression become.
# f3 $ f2 $ f1 $ f0 x

Which is definitely more readable and easiest to write.
Note that this operator is defined as follow.
($) :: (a -> b) -> a -> b
f $ x = f x

And I advise you to learn more about it consulting the following introduction material.


text:
Q: Are PERC 5/i RAID controller drivers available and easily installed on Ubuntu 9.04? We are looking to migrate a Dell PowerEdge 1950 with PERC 5/i RAID controller from an aging Windows 2000 Server installation to a modern Linux distro, probably Ubuntu 9.04.
I have come across some discussions regarding drivers for these RAID controllers indicating that some users have experienced frustration on older versions of Ubuntu (6.06).
My question is, has anyone installed a more recent version of Ubuntu on a PowerEdge with this RAID controller?  Has the driver support/installation experience improved?
I don't mind having to follow these workarounds, but I don't really have a server that I can test on, so I'm trying to get a feel for what issues I might hit during my install so I can be as prepared as possible to resolve them quickly.
Thanks

A: I'm fairly certain that 9.04 will have the PERC 5/i compatible megaraid_sas driver.  It's not a particularly new chipset by now.


text:
Q: Take snapshots of iterations of the Fruchterman-Reingold layout I want to take some snapshot of the evolving Fruchterman-Reingold layout, to get a feeling of how the layout is evolving. First I thought I could do some steps, draw the layout, and put the already calculated positions back to the layout.fruchterman.reingold via the start argument.
It doesn't work because the initial heat can not be adjusted. Maybe the documentation lacks some information. I am using igraph version 0.7.1.
Thanks in advance!

A: Unfortunately this is not supported by the implementation of the Fruchterman-Reingold layout in igraph. If you feel adventurous, you can tweak the source code of the C core of igraph (in particular, src/layout.c) to log the coordinates after each iteration in the layout, but that requires recompiling the library from scratch.


text:
Q: Difference between ways of using malloc What's the difference between 1 and 2?

*

*
int *p;
p = malloc(2 * sizeof(int));

*
int *p = malloc(2 * sizeof(int));

The way I first learned it is number 1, but I've seen someone do it number 2.
Is number 1 and 2 the same thing? I'm assuming it is, but
I'm confused because I don't understand why number 2 is
int *p = malloc(2 * sizeof(int));

not
int p = malloc(2 * sizeof(int));

The way he used it was for array. Later in the code, he used p to save some desired values.
Like this.
p[0] = i;
p[1] = j;

A: (1) and (2) are the same which are used to initialize pointer with memory allocation.
I think you're confused with the way to initialize pointer, not how to use malloc(). Take a look on some articles about "Initialize pointer" like this one.
int number = 88;     // An int variable with a value
int * pNumber;       // Declare a pointer variable called pNumber pointing to an int (or int pointer)
pNumber = &number;   // Assign the address of the variable number to pointer pNumber

int * pAnother = &number; // Declare another int pointer and init to address of the variable number

int p = malloc(2 * sizeof(int));

This way is not correct to declare a pointer, in this case, p is just an integer variable, not a pointer that points to an integer variable.

A:
What's the difference between 1 and 2?

1 and 2 do the same thing. The compiler should produce exactly the same code. They both declare a variable p of type int * and then initialize p with the pointer returned from malloc.
It's int *p = ... because int * is the type. The variable is p. It is declaring the variable p as the type int * and then assigning to p.
The difference is that 2 does it in a single statement. This is preferable because it ensures the variable is initialized, and it makes it easier to see that the variable is initialized. Uninitialized variables contain garbage and are a common source of errors. It's usually a good idea to initialize every variable immediately, even if it's to 0 or NULL.
You will often see code which declares and initializes variables separately; sometimes all the variables are declared at the top of each function. This is an old style from way back when C required you to declare all your variables at the start of a function. This is no longer an issue. You can declare variables as needed now.


text:
Q: ¿Cómo remover el nombre de un elemento div padre una clase con C# Razor? En jQuery se puede obtener el elemento padre de un elemento div y remover la clase, una cosa similar a esto:
var padre = $("#id_div").parents('li');
var id_padreDIV = padre.attr('id');
$("#" +id_padreDIV).removeClass("estilo_div")

En la vista tengo estos elementos:

                            Solicitud

En C#, necesito obtener el id=li_padre
Pero al trabajar en MVC y Razor, ¿cómo sería o se traduciría el ejemplo de jQuery en un View usando Razor?


text:
Q: Oracle connection works on one server but not another I have an ASP.NET (4.0) application developed in Visual Studio 2012 (C#) with an Oracle (4.121.1.0) connection.  A connection string is used so we are not looking at TNS.
The application runs without issue in debug on my development server (Windows 2008 R2 SP1), where I have the Oracle DataAccess components.
I can publish the project to my Production server (Windows 2008 R2), running IIS, but had to place the following dlls into the bin folder of the application.

*

*oci.dll

*Oracle.DataAccess.dll  (published with application)

*orannzsbb12.dll

*oraocci12.dll

*oraociei12.dll

*oraons.dll

*OraOps12.dll

I created an application pool for this app using 4.0 integrated and set "Enable 32-Bit Applications" to true.
The oracle connection runs successfully on this environment.
But now, when I publish the exact same code to my Test server (Windows 2008 R2 SP1), and copy the same dlls to the bin folder and set up my application pool the same as my production environment, I get:
 The provider is not compatible with the version of Oracle client
This is the line of code that errors out on the TEST server:
oracleConnection = new OracleConnection();

I've verified that everything is the same between both PROD and TEST servers, but the TEST server gives me this error WITHOUT EXCEPTION and the PROD server runs PERFECTLY.
Neither PROD nor TEST servers have the Oracle DataAccess components installed.
Any suggestions on what to check?
Thanks.

A: Based on Mason's suggestion, I converted to the Oracle Managed Data Access driver which resolved the problem.  So much simpler and resolved the issue.


text:
Q: Add checkmark next to menu item How can I add a check symbol next to a menu item, like so?

Also, how do I modify the value associated with it? As of now, I have the following code:
//Create the menu

theMenu = [[NSMenu alloc] initWithTitle:@""];
[theMenu setAutoenablesItems:NO];

[theMenu addItemWithTitle:@"Enabled" action:@selector(logIt) keyEquivalent:@""];
[theMenu addItem:[NSMenuItem separatorItem]];

[theMenu addItemWithTitle:@"About" action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
[theMenu addItemWithTitle:@"Check For Updates" action:nil keyEquivalent:@""];

[theMenu addItem:[NSMenuItem separatorItem]];

[theMenu addItemWithTitle:@"Quit" action:@selector(terminate:) keyEquivalent:@""];

NSStatusBar *statusBar = [NSStatusBar systemStatusBar];
statusItem = [statusBar statusItemWithLength:NSVariableStatusItemLength];
[statusItem setImage:[NSImage imageNamed:@"Icon2.png"]];
[statusItem setToolTip:_appName];
[statusItem setHighlightMode:YES];
[statusItem setMenu:theMenu];

A: The check is linked to the state of the menuItem.
[statusItem setState:NSONState];

The check should appear when the item is in ON State