text:
Q: How to hide title app when display a layout? I have a layout A. When i enter to layout A, i want title app or actionbar will be hide.
i have searched in Google.
<style name="AppTheme.Fullscreen">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>

But it must do in AndroidManifest.xml
 (My app have many screen, and just only layout A, action bar will hide.)
So, i find a way which can set up it into file layout A?
How can i do that ?

A:
use getSupportActionBar().hide(); to hide your action bar programtically

getSupportActionBar().hide();

if you want fullscreen activity than use below code

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
    }

Or you can do it via your AndroidManifest.xml file:

<activity android:name=".YourActivity"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen"/>


text:
Q: client.send_file sending image as 0 bytes discord py Whenever the  await client.send_file(client.get_channel('491846919262437377'), 'jackpotpapi2.png') hits, a file with 0 bytes is sent to the channel instead of the actual image. The file size is around 52kb and fairly small. The image that sends at the end shows up with no problem (await client.send_file(client.get_channel('491846919262437377'), 'jackpotpapi.png'))
elif slot1 == '<:papii:492030512760750090>' and slot2 == '<:papii:492030512760750090>' and slot3 == '<:papii:492030512760750090>':
    await client.edit_message(mtg, "\t{}".format(slotOutput))
    await client.send_file(client.get_channel('491846919262437377'), 'slots2.png')
    await client.send_message(message.channel, " {} hit 3 <:papii:492030512760750090>'s for $800! ".format(message.author.mention))
    await client.send_message(message.channel, "{} moves onto the bonus round for a chance to win the jackpot!".format(message.author.mention))
    add_dollars(message.author, 800)
    remove_dollars(message.author, 10)

    #JACKPOT BONUS ROUND

    await asyncio.sleep(3)
    await client.send_file(client.get_channel('491846919262437377'), 'jackpotpapi2.png')
    jck = await client.send_message(message.channel, "{}".format(jackOutput))
    await client.edit_message(jck, "{}".format(animationjack))
    await client.edit_message(jck, "{}".format(animationjack2))
    await client.edit_message(jck, "{}".format(animationjack3))
    if jack1 == '' and jack2 == '' and jack3 == '' and jack4 == '' and jack5 == '':
        await client.edit_message(jck, "{}".format(jackOutput))
        await client.send_file(client.get_channel('491846919262437377'), 'jackpotpapi.png')
        await client.send_message(message.channel, " CONGRATS {}! You've hit 5 's for an additional $1000! ".format(message.author.mention))
        add_dollars(message.author, 1000)
    elif jack1 == '' and jack2 == '' and jack3 == '' and jack4 == '' and jack5 == '':
        await client.edit_message(jck, "{}".format(jackOutput))
        await client.send_file(client.get_channel('491846919262437377'), 'jackpotpapi.png')
        await client.send_message(message.channel, " CONGRATS {}! You've hit 5 's for an additional $1250! ".format(message.author.mention))
        add_dollars(message.author, 1250)
    elif jack1 == '<:papi:492025149525327902>' and jack2 == '<:papi:492025149525327902>' and jack3 == '<:papi:492025149525327902>' and jack4 == '<:papi:492025149525327902>' and jack5 == '<:papi:492025149525327902>':
        await client.edit_message(jck, "{}".format(jackOutput))
        await client.send_file(client.get_channel('491846919262437377'), 'jackpotpapi.png')
        await client.send_message(message.channel, " CONGRATS {}! YOU'VE WON THE JACKPOT FOR AN ADDITIONAL $2000! ".format(message.author.mention))
        add_dollars(message.author, 2000)
    else:
        await client.edit_message(jck, "{}".format(jackOutput))
        await client.send_file(client.get_channel('491846919262437377'), 'jackpotpapi.png')
        await client.send_message(message.channel, "Better luck next time {}!".format(message.author.mention))

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# WPF - How to Change a 'Preferences' Window's Displayed Grid using a ListView? I am currently in the process of making a 'Preferences' window in my C# WPF program.
The aim of this window is to have a ListView on the left, and a list of tweakable controls on the right.
Each item in the ListView directly corresponds to a Grid that contains all of the controls under the selected item's content.
Once the item in the ListView is changed, the current grid's visibility must be collapsed, and the grid that corresponds to the item selected's visibility must be changed to visible.
I thought that DataBinding might work for this, however I have no idea how to use it. Could someone please inform me how to implement this feature?
I have only one grid at the moment. The whole window looks like this:
<Window x:Class="DarkOrbit_Skill_Price_Calculator.DarkOrbit_Skill_Price_Calculator___Preferences"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:DarkOrbit_Skill_Price_Calculator"
        mc:Ignorable="d"
        Title="DarkOrbit Skill Price Calculator - Preferences" Height="360" Width="640" WindowStartupLocation="CenterScreen" WindowStyle="ToolWindow">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <ListView Name="ListView_PreferenceOption" Width="150" Margin="5" SelectionChanged="SelectionChanged_ListView_PreferenceOption">
            <ListViewItem IsSelected="True">
                <StackPanel Orientation="Horizontal">
                    <Image Source="Images\Installing Updates.png" Height="35"/>
                    <TextBlock Text="Update" FontSize="14" FontFamily="Segoe UI" VerticalAlignment="Center" Margin="5"/>
                </StackPanel>
            </ListViewItem>
        </ListView>
        <Grid Margin="5" Name="Grid_Update" Grid.Column="1">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <StackPanel Orientation="Horizontal">
                <Label Content="Update Version Architecture" VerticalAlignment="Center"/>
                <ComboBox IsReadOnly="True" Width="100" Margin="5">
                    <ComboBoxItem Content="64-Bit"/>
                    <ComboBoxItem Content="32-Bit" IsSelected="True"/>
                </ComboBox>
            </StackPanel>
        </Grid>
    </Grid>
</Window>

I have absolutely no clue as to how to swap the grid depending on the index selected.

A: You can bind the visibility of each grid to the selected state of its corresponding list item by referencing the ListViewItem element. Something like this:
<Grid>
    <Grid.Resources>
        <BooleanToVisibilityConverter x:Key="Converter" />
    </Grid.Resources>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <ListView Width="150" Margin="5">
        <ListViewItem IsSelected="True" x:Name="One">
            <TextBlock Text="Update" FontSize="14" FontFamily="Segoe UI"
                VerticalAlignment="Center" Margin="5"/>
        </ListViewItem>
        <ListViewItem IsSelected="False" x:Name="Two">
            <TextBlock Text="Foo" FontSize="14" FontFamily="Segoe UI"
                VerticalAlignment="Center" Margin="5"/>
        </ListViewItem>
    </ListView>
    <Grid Margin="5" Grid.Column="1"
        Visibility="{Binding IsSelected, ElementName=One, Converter={StaticResource Converter}}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal">
            <Label Content="Update Version Architecture" VerticalAlignment="Center"/>
            <ComboBox IsReadOnly="True" Width="100" Margin="5">
                <ComboBoxItem Content="64-Bit"/>
                <ComboBoxItem Content="32-Bit" IsSelected="True"/>
            </ComboBox>
        </StackPanel>
    </Grid>
    <Grid Margin="5" Grid.Column="1"
        Visibility="{Binding IsSelected, ElementName=Two, Converter={StaticResource Converter}}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal">
            <Label Content="Update Something Else" VerticalAlignment="Center"/>
            <ComboBox IsReadOnly="True" Width="100" Margin="5">
                <ComboBoxItem Content="64-Bit"/>
                <ComboBoxItem Content="32-Bit" IsSelected="True"/>
            </ComboBox>
        </StackPanel>
    </Grid>
</Grid>

A: For those who are having the same predicament and want to use C# code to make this work, I eventually thought of the following code:
StackPanel[] allGrids = { Grid_1, Grid_2, Grid_3, Grid_4, ... }; //Replace StackPanel with the
//type of control you are using, e.g. Grid or WrapPanel.

foreach (StackPanel grid in allGrids)
{
    grid.Visibility = Visibility.Collapsed; //collapse all grids
}

allGrids[(your listview/other control).SelectedIndex].Visibility = Visibility.Visible;
//make the grid you need visible


text:
Q: what is a model matrix / design matrix I stumbeled upon the stats::model.matrix function in R. In the description it sais that it would create a design matrix. It gives me a weired number of rows, which does not correspend to neither the number of observations in my data, nor the number of parameters in my model.
What is a design matrix / model matrix?
Here is how i used it:
M03b <- glmer(APMs ~ PrePost + Gf + eyeFRF + (1|content) + (eyeFRF|ID),    data=mlmData, family=binomial("logit"))
X <- model.matrix(M03b)

it gives me a 2895x4 Matrix. ID has 105 levels and content 28, so the number of rows does not make much sense to me. Maybe missing values are an issue?

A: In a regression model, written in matrix-vector form as
Y = X * B + e,

the matrix X is the design matrix, while Y is the vector of observations on the dependent variable, B is a vector of response coefficients (one for each explanatory variable) and e is a vector containing the values of the model's error term for the various observations. In the design matrix, each column is a vector of observations on one of the explanatory variables.
Thus, the size of X must be such that it is a n X m matrix and B is a m x p matrix, allowing that the product XB is defined only if the number of columns in X is equal to the number of rows in B, in this case m.
Given your 2895x4 dim for X, you should be able to confirm that your B, M03b, has 4 response coefficients.


text:
Q: onError for SVG Image Tag With normal HTML images, there is the onError attribute which fires if the image cannot be displayed or the link is broken, does anyone know if there is an equivalent (or work around which achieves the same) for the Image tag in SVG?
I'm happy to use javascript if there is no native option.
Along the lines of:
<svg>
  <image xlink:href="path/to/image.jpg" onError="path/to/alternate.png" />
</svg>


text:
Q: liquibase agnostic insert with sequence I want to create a new insert changeset in liquibase using a sequence to populate the id field. Is there any way to make it database agnostic for Oracle an Postgres?
This is the oracle way:
    <changeSet author="XX" id="XX">
        <insert tableName="NODO_MENU">
            <column name="ID" defaultValueSequenceNext="SEQ_NODO_MENU" />
            <column name="CODIGO" value="ABC" />
            <column name="ORDEN" value="0" />
        </insert>
        <rollback>
            <delete tableName="NODO_MENU">
                <where>CODIGO = 'ABC'</where>
            </delete>
        </rollback>
    </changeSet>

It doesn´t work in postgres:
[Failed SQL: INSERT INTO public.NODO_MENU (ID, CODIGO, ORDEN) VALUES (SEQ_NODO_MENU.NEXTVAL, 'ABC', '0')]
To make it work in postgres I changed the column tag to:
<column name="ID" valueComputed="nextval('SEQ_NODO_MENU')" />

How can i write this changeset to make it work in Oracle an Postgress?

A: You can write two separate changesets. One for Postgres, one for Oracle.
Just add corresponding dbms preConditions to them.
As such:
<changeSet author="XX" id="XX_oracle">
    <preConditions onFail="MARK_RAN">
        <dbms type="oracle"/>
    </preConditions>
    <!-- your logic for Oracle-->
</changeSet>

<changeSet author="XX" id="XX_postgres">
    <preConditions onFail="MARK_RAN">
        <dbms type="postgresql"/>
    </preConditions>
    <!-- your logic for Postrgres-->
</changeSet>


text:
Q: What is the correct way to have the option tag default value set in IE6? What is the correct way to have the option tag default value set in IE6?
I've tried doing
<option SELECTED>
<option selected='selected'>
<option selected='true'>

none of them work in ie6, any ideas?

A: Proper markup is:
<option selected="selected" value="1">Some Text</option>

Source

A: Depends on the doctype. If HTML, then you need
<option value="value1" selected>label1</option>

If XHTML (i.e. HTML massaged into XML flavor), then you need
<option value="value1" selected="selected">label1</option>

If still in vain, then the problem lies somewhere else. You'll need to post an SSCCE then, for example:
<!doctype html>
<html lang="en">
    <head>
        <title>SO question 2073877</title>
    </head>
    <body>
        <select>
            <option value="value1">label1</option>
            <option value="value2" selected>label2</option>
            <option value="value3">label3</option>
        </select>
    </body>
</html>

This shows "label2" as selected option in all browsers, including IE6.

A: <option value="someValue" selected="selected">Label</option>


text:
Q: saving an immutable variable in a mapping in solidity? I am trying to do something like this code below
any thought's ??
    mapping (uint256 => string immutable) public IdToAddress ;

A: A map is a hash table. You cannot, therefore, set the value type to be immutable. Think of a map as a "key: value" pair where idToAddress[uint256] will return a string from the hash table in your example. It is not an array of data where you can return data by index. Not to mention that your syntax is wrong if this were to be introduced to solidity. Please note that you cannot set the data type after it is named.
Therefore, you cannot accomplish this with mapping.
You can read more in the solidity to find a use case that can suit your need:
https://docs.soliditylang.org/en/v0.8.15/types.html?highlight=mapping#mapping-types


text:
Q: Is Django 3.0 compatible with Jinja2 when rendering forms? I am using Jinja2 (via django-jinja 2.3.1) in my Django 3.0 project.
It renders the templates fine, however when I want to display a {{ form }} such as in a LoginView I get the following error:

expected token 'end of print statement', got ':'

I traced this back to the input widget in django/forms/templates/django/forms/widgets/input.html, which renders as follows:
<input type="{{ widget.type }}" name="{{ widget.name }}"
{% if widget.value != None %} value="{{ widget.value|stringformat:'s' }}"
{% endif %}{% include "django/forms/widgets/attrs.html" %}>

It would appear Jinja doesn't accept |stringformat:'s', is this correct? Does this mean it is not compatible with Django forms? Perhaps I am missing something?


text:
Q: Swift: Pass parameters for a uicontainerview I have a container bearing a view (only once) he has a gallery of images with scrollView, I need this gallery is dynamic.
How can I pass data to this container / view once it is loaded?
Already tried by protocol, and passing by below. unsuccessfully.

A: You can get the container as a ViewController and pass whatever you want. For example:
let container = self.childViewControllers[0] as! MyContainerViewController

    container.myDataArray.append("Data 1")
    container.myDataArray.append("Data 2")
    container.myDataArray.append("Data 3")


text:
Q: Set Class on document ready, depending on field Value I have a page where i need to add a class to a div, depending on a field value. The field value in this example is a Select input, however in the actual scenario, its a returned field on the page I am finding by document.getElementById.
The fiddle is here https://jsfiddle.net/s3w3ocy8/3/
Currently there is no change in the selected option/result change...
I have updated the code below (thanks Praveen and Alexander)
Any advice would be gratefully received!
Thanks
CSS:

HTML:
<select id="select1">
<option>Select</option>
<option>Pill1</option>
<option>Pill2</option>
<option>Pill3</option>
</select>

Pill 1

result 1

Pill 2

result 2

Pill 2

result 3

JS:

A: You are missing $ everywhere. Replace your code with:
$(document).ready(function($) {
  var value = '#select1';
  if ($(value).val() == "Pill1")
    $('#pill1,#pill1Result').addClass('active');
  if ($(value).val() == "Pill2")
    $('#pill2,#pill2Result').addClass('active');
  if ($(value).val() == "Pill3")
    $('#pill3,#pill3Result').addClass('active');
  else
    $('#pill1,#pill2,#pill3,,#pill1Result,#pill2Result,#pill3Result').removeClass('active');
});

And an improved code would look like:
$(document).ready(function($) {
  var value = '#select1';
  switch ($(value).val()) {
    case "Pill1":
      $('#pill1,#pill1Result').addClass('active');
      break;
    case "Pill2":
      $('#pill2,#pill2Result').addClass('active');
      break;
    case "Pill3":
      $('#pill3,#pill3Result').addClass('active');
      break;
    default:
      $('.active').removeClass('active');
  }
});

Updated Working Snippet

$(document).ready(function() {
  var value = '#select1';
  $(value).change(function() {
    $('.active').removeClass('active');
    switch ($(this).val()) {
      case "Pill1":
        $('#pill1,#pill1Result').addClass('active');
        break;
      case "Pill2":
        $('#pill2,#pill2Result').addClass('active');
        break;
      case "Pill3":
        $('#pill3,#pill3Result').addClass('active');
        break;
      default:
        $('.active').removeClass('active');
    }
  });
});
.active {
  color: red;
  background-color: blue;
}

<select id="select1">
  <option>Select</option>
  <option>Pill1</option>
  <option>Pill2</option>
  <option>Pill3</option>
</select>

  Pill 1

  result 1

  Pill 2

  result 2

  Pill 2

  result 3


text:
Q: Ignoring a particular attribute of a specific Node while comparing xml files using XMLUnit <!------------------------File1--------------------------------->
Node id="123">
 <to>Name</to>
 <from>User</from>
<Boolean id>123</Boolean id>
</Node >
 <!------------------------File2--------------------------------->
<Node id="12369">
<to>Name</to>
<from>User</from>
<Boolean id>123</Boolean id>
 </Node >

I have to ignore the attribute:boolean id from  Node up on comparing the files at specific node level.
I am using DiffBuilder
Diff diff =
      DiffBuilder.compare(root).withTest(root2).checkForSimilar()
            .withNodeFilter(
                    node -> !(node.getNodeName().equals("Assoc_CIDB") || node.getNodeName().equals("Synoptics")))
            .withNodeMatcher(new DefaultNodeMatcher(es)).build();

Can someone suggest me a way how i can achieve the issues :
1.Ignore specific attributes on a specific node.
2.If the differences are at from attributes then i just compare and check to attributes details
I can achieve this using XMLUnit 2.x Iam New to XMLUnit so someone please help me accordingly.
Thanks in advance.


text:
Q: ЧПУ постраничной навигации в Yii2 Есть у меня на главной странице в контроллере sitecontroller экшен
public function actionIndex()
{
    $searchModel = new CourseSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

CourseSearch
public function search($params)
{
    $query = Course::find()->active()->with(['category'])->orderBy(['id' => SORT_DESC]);

    // add conditions that should always apply here

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
        'pagination' => [
            'pageSize' => 2,
        ],

]); .............

Который выводит список постов через вьюху
<?= ListView::widget([
        'dataProvider' => $dataProvider,
        'layout' => "{items}\n{pager}",
        'itemView' => '_item',
        'emptyText' => 'Ничего не найдено.',
        'emptyTextOptions' => [
            'tag' => 'div class="alert alert-danger"'
        ],
        'pager' => [
            'firstPageLabel' => '««',
            'lastPageLabel' => '»»',
            'nextPageLabel' => false,
            'prevPageLabel' => false,
            'maxButtonCount' => 5,
        ],
]); ?>

И постраничная навигация когда переходишь например на вторую страницу выдает вот такой вид:
mysite.ru/?page=2&per-page=2

Вот как сделать чтобы страницы выводились mysite.ru/page-2
'urlManager' => [
        'class' => 'yii\web\UrlManager',
        // Disable index.php
        'showScriptName' => false,
        // Disable r= routes
        'enablePrettyUrl' => true,
        'rules' => [
            'page-<page:\d+>-<per-page:\d+>' => 'site/index',
            '' => 'site/index',
            '<action:login|logout|signup|contact|about|request-password-reset>' => 'site/<action>',
            '<slug:[\w_\-]+>' => 'site/category',
            '<category:[\w]+>/<slug:[\w_\-]+>' => 'site/view',

A: Открываем config/web.php и добавляем в components:
'components' => [
    'urlManager' => [
        'class' => 'yii\web\UrlManager',
        // Disable index.php
        'showScriptName' => false,
        // Disable r= routes
        'enablePrettyUrl' => true,
        'rules' => [
             '<controller:\w+>/<action:\w+>/page-<page:\d+>' => '<controller>/<action>',
             '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
     ],
//Далее какой-то код.
],

Код рабочий, если возникнут какие-то проблемы, выложите config/web.php и мы поможем.


text:
Q: Science fiction novel where the scientists discover a cosmic square wave signal Here's what I remember for sure:

*

*A group of scientists discovered some cosmic phenomenon signal, that after some more research was described as a square wave.

*When the cosmic wave was positive, good things happened.
When the cosmic wave was negative, bad things happened.
I think it was equated to the universe's 'luck signal'.

*At some point in the book (or books) they travel to a different world, where some other entities tried to control this wave, to make it positive most of the time,  but it backfired somehow.

*I've read it about 15 years ago I think, so it's not anything new.

*It might be a book series rather than a single book.
Things I'm unsure of:
There's a scene where they encounter robotic sentries, and those sentries kill anything taller than like, 3ft,  because their creators are around 3ft tall.
1 of the humans encountered a sentry, but he was crouching down at the time (to poop? idk) so the sentry didn't register his height correctly and spared him.


text:
Q: Strongly balanced tree - improvement I have the following structure to represent binary tree:
typedef struct node *pnode;
typedef struct node {
   int val;
   pnode left;
   pnode right;
} snode;

Weight of the tree is sum of the val parameter from all nodes of the tree. We say that tree is strongly balanced when it's empty or weight of left equals weight of right subtree and each subtree(left and right) is strongly balanced. I have to write function which tells whether tree is or isn't strongly balanced.
The code I wrote:
int getWeight(pnode tree)
{
   if(! tree)
      return 0;
   return getWeight(tree->left) + getWeight(tree->right)
            + tree->val;
}

bool isStronglyBalanced(pnode tree)
{
   if(! tree)
      return true;

   int wL, wR;
   wL = getWeight(tree->left);
   wR = getWeight(tree->right);

   if(wL != wR)
      return false;
   return (isStronglyBalanced(tree->left) && isStronglyBalanced(tree->right));
}

The function above does its job pretty good, but I've noticed it's visiting nodes of the tree more than once. Can it be improved (maybe by using dynamic programming) to visit each of the tree's node only once?

A: If getweight also told you whether the subtree were strongly-balanced, you could simplify the code to a single scan.
There are a few approaches to returning two pieces of information from a function call. If there were some return value which you knew would never be the weight of a subtree (perhaps a negative number), you could use that as a signal that the subtree was not strongly-balanced. Or you could simply return two values: a bool and an int. (In C, you would use an "out" argument for one of them.) Or you could define a composite object with the two values, which in C would be struct { bool balanced; int weight; }.
However you do it, the logic is the same. In the following pseudo-code, I just assume you can return pairs of values as you can in some languages (C++, for example, but despite any casual similarity, it is still pseudocode):
pair<bool, int> get_weight(tree) {
  if (!tree) return {true, 0};
  balanced, weight_left = get_weight(tree->left);
  if (!balanced) return {false, 0};      /* Returned weight doesn't matter */
  balanced, weight_right = get_weight(tree->right);
  return {balanced && weight_left == weight_right,
          2 * weight_right + tree->val}; /* weight_left == weight_right */
}


text:
Q: System.IO.IOException: The process cannot access the file 'file_name' I have a method in my windows service as follows:
System.IO.File.Copy(path, ConfigurationManager.AppSettings["BulkInsertGiftRegisterCreatorDirectory"] + System.IO.Path.GetFileName(path));

Loyalty.Entity.Base.FileInfo file = new Loyalty.Entity.Base.FileInfo();
file.FileName = path;
request.Object = file;

ResponseBase response = new ResponseBase(request);
RequestConnection connection = new RequestConnection("cn");
FileManager fileManager = new FileManager(request, connection);
response = fileManager.OfflineGiftRegisterBulkInsert();

System.IO.File.Delete(ConfigurationManager.AppSettings["BulkInsertGiftRegisterCreatorDirectory"] + System.IO.Path.GetFileName(path));

// here is the part of stored procedure that uses file
SELECT @SCRIPT= 'BULK INSERT GIFT_CARD.GIFT_TEMP'
                            +' FROM '''
                            + @FILE_PATH
                            +''' WITH ('
                                 +'FIELDTERMINATOR = '','','
                                 + 'KEEPNULLS'
                            +');'

I can delete the file from file system by hand, but this code says me "Ooops! System.IO.IOException: The process cannot access the file 'filename'
because it is being used by another process."
I've searched the similar questions on stackoverflow and else where. But I could not find anything to help me. Copy or Delete methods return void and I have no stream in my code to dispose.
How can I fix it?
Thanks in advance.

A: Here is a method for you to check if a file is in use:
public static System.Boolean FileInUse(System.String file)
{
    try
    {
        if (!System.IO.File.Exists(file)) // The path might also be invalid.
        {
            return false;
        }

        using (System.IO.FileStream stream = new System.IO.FileStream(file, System.IO.FileMode.Open))
        {
            return false;
        }
    }
    catch
    {
        return true;
    }
}

Also, to wait for a file I have made:
public static void WaitForFile(System.String file)
{
    // While the file is in use...
    while (FileInUse(file)) ; // Do nothing.
}

I hope this helps!

A: Before you go looking through the code you might want to use process explorer to Identify what process has the handle. This might rule out some issue you haven't thought of
update
Since you are using a timer you must make sure that your method is reentrant and you don't have any race conditions.. E.g. the timer ticks faster than you can process the event.
See this question
And  this answer

A: Even better solution, is to add this two lines of code before using the function FileInUse that Vercas showed:
GC.Collect();
GC.WaitForPendingFinalizers();


text:
Q: Bootstrap not working with MVC4 I´ve downloaded tweeter bootstrap (not the bootststrap for MVC) to a brand new MVC4 project, but I can´t make it work.
No errors in browser´s F12 window.
Here is my _layout code:
<!DOCTYPE html>

    <title>Bootstrap 101 Template</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link href="@Url.Content("~/Content/bootstrap-theme.min.css")" rel="stylesheet" media="screen">

Hello, world!

      @RenderBody()

When the screen pops up, I get a normal Hello, world! body (no bootstrap fonts). My system has the following files:

What may I be doing wrong?

A: You only included the bootstrap-theme.min.css file and not the base bootstrap.css file. (though you did include the bootstrap.js file)


text:
Q: Programaticly fill and submit form Angular 4 I have following problem: I need to  auto fill form and immediately submitted to some url with post method.
this is Component .ts and html example:

import { Component, OnInit, ViewChild, ElementRef, AfterViewInit, Renderer  } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { PayModel } from './shared/pay.model';
import { PayService } from './shared/pay.service';
@Component({
    selector: 'cp-pay',
    templateUrl: './pay.component.html',
    styleUrls: ['./pay.component.css']
})
export class PayComponent implements OnInit {

    model: PayModel;
    cardProcessingId: number;

    constructor(
        private payService: PayService,
        private route: ActivatedRoute,
        private renderer: Renderer

    ) {
        this.cardProcessingId = route.snapshot.params["processingid"];
    }
    ngOnInit() {
        this.model = new PayModel();
        this.getProcessing();

    }

    getProcessing() {
        this.payService.getProcessing(this.cardProcessingId).subscribe(
            res => {
               this.model.fname = res.fname;
               this.model.lname = res.lname;
               this.model.age = res.age;
               }
                err => {
                console.log('getProcessing Error')
            },
            () => {
                let form: HTMLFormElement = <HTMLFormElement>document.getElementById('payform');

                form.submit();
            }
        );
  }
}
<form ngNoForm id="payform" action="https://localhost:44300/api/pay/test" target="_blank" method="post">
        <input type="text" id="fname" name="merchant" value="{{model.fname}}" />
        <input type="text" name="lname" value="{{model.lame}}" />
        <input type="text" name="age" value="{{model.age}}" />
        <input type="submit">
</form>

I just want raw html form to be posted to url, that's all, but when code hits form.submit() it posts null values only. I tried to simulate submit button click but it does not work either. I wonder is that kind of thing even possible? It seems to me that form gets submitted before the form is filled. Pls help

A: Finally! I have found a workaround. First things first: the problem was that form submit was happening before the html was populated with values and data posted was empty (null). I didn't know that with Angular could force html to be populated with values pretty much whenever u want using ApplicationRef module. All you need to do is to import module, create ApplicationRef  instance and call it's method .tick() whenever you want to html values to be filled. My code should be like this now:

    import { Component, OnInit, ElementRef, AfterViewInit, ApplicationRef} from '@angular/core';
    import { ActivatedRoute } from '@angular/router';

    import { PayModel } from './shared/pay.model';
    import { PayService } from './shared/pay.service';
    @Component({
        selector: 'cp-pay',
        templateUrl: './pay.component.html',
        styleUrls: ['./pay.component.css']
    })
    export class PayComponent implements OnInit {

        model: PayModel;
        cardProcessingId: number;

        constructor(
            private payService: PayService,
            private route: ActivatedRoute,
            private appRef: ApplicationRef

        ) {
            this.cardProcessingId = route.snapshot.params["processingid"];
        }
        ngOnInit() {
            this.model = new PayModel();
            this.getProcessing();

        }

        getProcessing() {
            this.payService.getProcessing(this.cardProcessingId).subscribe(
                res => {
                   this.model.fname = res.fname;
                   this.model.lname = res.lname;
                   this.model.age = res.age;
                   appRef.tick(); // to immediately force html value fill
                   }
                    err => {
                    console.log('getProcessing Error')
                },
                () => {
                    let form: HTMLFormElement = document.getElementById('payform');

                    form.submit();
                }
            );
      }
    }

On Html side ngNoForm not needed in form tag.


text: Q: NPM - Excluding a part of dependency from installing I have a problem, which come from the thing that I replace a bootstrap.min.css with another one. I adjusted .gitignore in way, that on github repo there is only /node_modules/bootstrap/dist/css/bootstrap.min.css from all the dependencies. But after cloning the repo and use "npm i", this file is overrided. So I just want to add this specified file to .npmignore. But I don't have a idea how to do that. Could anybody want to reveal me the secret? :) Thanks in advance!


text:
Q: Custom ListView adapter Force close :( I am a newbe to android and have been following the tutorials posted online to experiment with coding for android. I am trying to display a list which has input from two different arrays, but every time i run the code i keep on getting a force close and can seem to figure out what i am doing wrong. here is my code ( this is from an online tutorial)
Main.XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:orientation="vertical"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent">

  <TextView android:id="@+id/TextView01"
          android:layout_height="wrap_content"
          android:text="List of Country & their denotation"
          android:textStyle="normal|bold"
          android:gravity="center_vertical|center_horizontal"
          android:layout_width="fill_parent">
  </TextView>
  <ListView android:id="@+id/ListView01" android:layout_height="wrap_content"
            android:layout_width="fill_parent">
  </ListView>
</LinearLayout>

listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_height="wrap_content"
              android:gravity="left|center"
              android:layout_width="wrap_content"
              android:paddingBottom="5px"
              android:paddingTop="5px"
              android:paddingLeft="5px">

  <TextView android:id="@+id/TextView01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:background="@drawable/bg"
            android:textColor="#FFFF00"
            android:text="hi"/>

  <TextView android:text="@+id/TextView02"
            android:id="@+id/TextView02"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10px"
            android:textColor="#0099CC"/>

</LinearLayout>

display.java
package com.example.display

import android.app.Activity;
import android.os.Bundle;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class customlistview extends Activity {

  private static class EfficientAdapter extends BaseAdapter {
  private LayoutInflater mInflater;

  public EfficientAdapter(Context context) {
    mInflater = LayoutInflater.from(context);
  }

  public int getCount() {
    return country.length;
  }

  public Object getItem(int position) {
    return position;
  }

  public long getItemId(int position) {
    return position;
  }

  public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
      convertView = mInflater.inflate(R.layout.listview, null);
      holder = new ViewHolder();
      holder.text = (TextView) convertView.findViewById(R.id.TextView01);
      holder.text2 = (TextView) convertView.findViewById(R.id.TextView02);

      convertView.setTag(holder);
      } else {
        holder = (ViewHolder) convertView.getTag();
      }

      holder.text.setText(curr[position]);
      holder.text2.setText(country[position]);

      return convertView;
    }

    static class ViewHolder {
      TextView text;
      TextView text2;
    }
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ListView l1 = (ListView) findViewById(R.id.ListView01);
    l1.setAdapter(new EfficientAdapter(this));
  }

  private static final String[] country = { "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Laos", "Latvia", "Lebanon", "Lesotho ", "Liberia", "Libya", "Lithuania", "Luxembourg" };

  private static final String[] curr = { "ISK", "INR", "IDR", "IRR", "IQD", "EUR", "ILS", "EUR", "LAK", "LVL", "LBP", "LSL ", "LRD", "LYD", "LTL ", "EUR"};

}

This code can also be found at http://www.androidpeople.com/android-custom-listview-tutorial-example/,
I have tried several times, changing different values and even trying to print one array but have been unsuccessful at it and keep on getting a force close. I would appreciate it if someone would be able to point out what is wrong with the code and point me in the right direction.

A: Did you include your activity file inside AndroidManifest.xml file.
Every Activity Needs to be included in this xml file.
Syntax:

Also check your launcher activity is set in xml file


text:
Q: SELECT WHERE id ='123' || other_col = other_call I'm trying to write a select query to retrieve rows where id='123' or where col_x is the same as col_x where id ='123' but the syntax escapes me.
SELECT * FROM table WHERE id='325' || cart_id IN (SELECT cart_id FROM table WHERE ID='325')

What's a better way to do this?

A: Assuming id is the PK so can only match at most one row and that col_x is not nullable.
SELECT *
FROM   table
WHERE  col_x = (SELECT col_x
                FROM   table
                WHERE  id = '325')

If id is a numeric datatype you don't need the single quotes.


text:
Q: Restrict standard users to run a command with a specific argument I know how to restrict standard users to run a command by removing execute permissions for that command. But it's possible restrict standard users to run a command with a specific option/argument?
For example a standard user should be able to run the following command:
ls

but not:
ls -l

I think that this can be possible since there are some commands like chsh or passwd which a standard user can run them, but he get permission denied when he runs chsh root or passwd -a -S.

A: I think the only way would be to write your own wrapper to the command/utility in question and have it decide what is allowed or not allowed based on the (E)UID of the user who started it. The tools you mention that do this such as chsh or passwd have this functionality built into their implementation.
How to write a wrapper for ls
#!/usr/bin/perl

use strict;
use warnings;

my $problematic_uid = 1000; # For example
my $is_problematic = $< == $problematic_uid;
unless(/ -l / ~~ @ARGV or $is_problematic){
    exec qq{/new/path/to/ls }.join '',@ARGV
}else{
    die "Sorry, you are not allowed to use the -l option to ls\n"
}

You need to ensure that the path to the original ls isn't in your user's PATH. Which is why I wrote /new/path/to/ls. The problem is, this wrapper requires that your user be able to execute the original ls so the user may still circumvent it by calling the original ls directly.

A: Commands like chsh and passwd are coded specially. They run with extra privileges (they're setuid) root) and contain their own authorization mechanism. Both check which user is invoking them, and allow non-root users only a subset of their functionality.
chsh and passwd are the exception. Most commands don't care who invokes them.
Forbidding users from running one particular command is pointless: they can do whatever that command does in some other way, such as by supplying their own executable.
You can make a restricted account that is only allowed to run a whitelisted set of commands: with a restricted shell, or for data-transfer-only accounts, rssh or scponly.
If you want to allow a user to run a certain command with elevated privileges (typically via sudo), but only for certain combinations of options, then write a wrapper script that checks the options and allow the user to run that wrapper script.

A: Rahul's answer is relevant to your question, because what you want is a) not a good idea and b) probably only possible by creating a custom shell. Executables like ls are separate, stand-alone programs that handle their arguments by themselves - if you'd want to prevent users from using ls -l, you would have to write and compile your own custom ls. As you can probably imagine, that would not be easy and it would also take a lot of time, because you have to do that for every single command that you want to change.
You could maybe try to replace the whole shell (in your case probably bash) completely with a different shell that filters the commands of your users. For example, it could try to remove the -l from ls command lines before actually calling ls. This isn't as easy as it sounds though, because shells and also the commands that you can run from a shell usually have a very powerful and complex syntax, and trying to filter that will probably leave holes and break stuff.

I think that this can be possible since there are some commands like chsh or passwd which a standard user can run them, but he get permission denied when he runs chsh root or passwd -a -S.

That's something else entirely, because these programs are written that way. If you'd want to change their behaviour just as you want to change the behaviour of ls, you would have to modify their source codes and recompile them.


text:
Q: Track not locking to same net pad in Altium I use interactive routing with Altium to route components using Ctrl+W. This normally works well, but I have some castellated holes that are not in the schematic (I created them in the PCB file directly). They are set to the nets they are intended to, but I cannot interactively route to them. The tracks won't lock to the castellated pads:

I have to do it the other way around, from them to the other components like so:

This is a concern because it starts the tracks from the center of the pad, where as I could lock them from their lower edge if I could connect with the interactive routing as seen in first image.
Is there a setting somewhere that could let me connect to pads like these that are not in the schematics?

A: Here are some things you can try:

*

*Sometimes this behavior (not connecting to same-net objects) is inhibited by a clearance issue. Try momentarily setting Routing Options > Conflict Resolution to "Ignore Obstacles":

This will eliminate clearance rules as the reason it is not allowing the connection. (If this solves the issue, then you need to check your design rules to see if any are affecting the tracks/pads in question.)

*There could be a track fragment hiding in the pad of a different net. Set the selection filter to track only:

And select everything over and around the pads that are giving you the problem. If you see any pieces of track within the pad, delete them as they might be conflicting.
For example, here's a pic showing a track fragment where the visible pieces exiting the pad were removed, but the remaining piece is still superimposed over the pad, and has a different net:

*If your castellated holes are on the PCB edge, it could be a Board Outline Clearance design rule preventing the track from routing to the pad. Even if the pad is not in the schematic, Altium should route to it if it is the same net. Try A) disabling any Board Outline Clearance rules if they exist, or B) move the castellated pad to another location (temporarily) to see if routing to it is allowed.


text:
Q: How to move cursor position using WebDriver I am working on a Liferay 6.2 project. In Liferay, they used Vaadin. When I click on a button it opens with a different iframe. I can code that all functionality. Now I want to move the cursor to the iframe element using WebDriver. Because when I move mouse to the iframe checkbox after that my automate script can run. I want to automate a script to move the mouse pointer to the the element.
I have tried the code below, but it doesn't work.
1) using Action moveToElement:
driver.findElement(By.xpath("element1")).click();
new Actions(driver).moveToElement(driver.findElement(By.xpath("element2"))).click().perform();

2) using mouseMove
WebElement element = driver.findElement(By.xpath("element xpath"));
Locatable hoverItem = (Locatable) element;
Mouse mouse = ((HasInputDevice) driver).getMouse();
mouse.mouseMove(hoverItem.getCoordinates());

error: getting a error in ((HasInputDevice) driver).
  HasInputDevice cannot be resolved to a type

3)
Locatable hoverItem = (Locatable) driver.findElement(By.xpath("element xpath"));
int y = hoverItem.getCoordinates().getLocationOnScreen().getY();
((JavascriptExecutor)driver).executeScript("window.scrollBy(0,"+y+");");

error: getting a error in getLocationOnScreen()
  The method getLocationOnScreen() is undefined for the type Coordinates

4)
Point coordinates = driver.findElement(By.xpath("element xpath")).getLocation();
Robot robot = new Robot();
WebElement markNews = driver.findElement(By.xpath("element xpath"));
markNews.click();
robot.mouseMove(coordinates.x,coordinates.y+80);

This does not work.
I just want to move cursor point to the iframe locator.

A: You can directly select iframe using:
driver.switchTo().frame(driver.findElement(By.id("frameId")));

Now by using selenium web driver you can perform any operation in this iframe.
To move back to main window you just need to :
driver.switchTo().defaultContent();

A: It's:
HasInputDevices

(devices is plural)

A: I thought your first example:
new Actions(driver).moveToElement(driver.findElement(By.xpath("element2"))).click().perform();

Should read:
new Actions(driver).moveToElement(driver.findElement(By.xpath("element2"))).build().perform().click();

That is, you first find the element, then build a series of actions to perform on it (in this case just one) then perform those actions (now the mouse should be over the element) then click

A: You can use a tool called Sikuli which integrates directly into Selenium:
Sikuli Install Info
Example Code:
import org.sikuli.script.Button;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Location;
import org.sikuli.script.Match;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;

Screen screen = new Screen();
// Find where you want to move the mouse and set a location
Location wheelPoint = new Location(1000, 800);
// You can always just get center as well
// Location wheelCenter = screen.getCenter();
try {
    screen.wheel(wheelPoint, Button.WHEEL_DOWN, steps);
} catch (Exception e) {
    Assert.fail("Mouse did not move to desired location");
}


text:
Q: "Make up" Vs "Compensate" I wonder what is the difference between the two verbs "make up" and "compensate"? In order to discover it and make you able to explain it in a simpler way, I have made four examples. Please do me a favor and let me know which option works better in each sentence and which choice doesn't work at all plus the reason behind it.
The first scenario:

Teacher: you have missed 5 sessions so far. Do you know?
Student: yes, Mr. Johnson. I know!
Teacher: How are you going to ................ for the classes you have missed?

a. make up
b. compensate
The second scenario:

The insurance company will ............... people for the damage caused by the flood.

a. make up
b. compensate
The third scenario:

He is suffering from depression and is under treatment now. Unfortunately, he had a very unpleasant childhood and many dark past. I think nothing can............... for his lost childhood.

a. make up
b. compensate
The fourth scenario:

I'm late and I have to drive fast to ................

a. make up
b. compensate
I have read the similar thread on the forum.

A: The only one where the two phrases are not interchangeable is scenario two.
This is because 'to make up for' is the complete idiom. You need to include 'for' immediately after 'make up' in order for it to make sense.
So you can't say:

The insurance company will make up for people for the damage caused by the flood.

Whereas, if you said

The insurance company will make up for people who incurred damage from the flood.

it would be grammatical, but means something completely different from your intention. In this case the insurance company is 'making up for' the actions of the people, not the flood. In other words 'to make up for' is always followed by the thing that is being 'made up for' - the thing that caused the problem. Whereas compensate, acting as a transitive verb, can be followed by the object that is being compensated. The presence or absence of 'for' changes 'to compensate' between transitive and intransitive.
"But!", I hear you say, "The fourth example breaks that rule! I could end the sentence with 'make up'".
Well - sort of. In fact there is an implied 'for' in the final sentence

I'm late and I need to drive fast to make up [for my lateness].


text:
Q: How to repeat a checkout after changing CRLF to LF only I have a repository checked out on a windows machine, but it has CRLF newlines in every file. I would like to check this repository out with Unix format LF only instead. I've changed the setting on tortoise git to disable changing newlines to the Windows format, but how to I get it to actually update the newlines in my checkout to LF?
I'm in this pickle because I have some changes I've made and committed to one repository on my windows machine that I would like to copy to another repository on my Linux machine. The repositories are not easily comparable / have no commits in exact sync with each other, so I'd just like to delete all the files and copy in the updated versions. For ease of viewing the git history, I don't want every file to be marked as changed. The commit should be a reasonably nice diff between the copied in files and the previous commit.


text:
Q: LockedFileException: failed to lock file config.lock for writing I'm trying to run a dotnet build on my Jenkins build server. I keep getting the following error:

C:\Nuget\PackagesCache\gitversiontask\5.1.3\build\GitVersionTask.targets(10,9): error : LockedFileException: failed to lock file 'C:/jenkins/workspace/Shared-Build/.git/config.lock' for writing

And sometimes this message appear:

C:\Nuget\PackagesCache\gitversiontask\5.1.3\build\GitVersionTask.targets(10,9): error : LibGit2SharpException: failed to rename lockfile to 'C:/jenkins/workspace/Shared-Build/.git/config': Access is denied.

What interesting is that another team member can successfully run the build, without these errors appearing.
I tried to look online but no clear solution is available. This exception seems to be related to the gitversiontask Nuget package, but I'm using a fairly updated version of it. Did anyone ever encountered this error before?

A: The solution was re-creating the config and config.lock (while keeping the worktree intact).
del .git\config
del .git\config.lock

And then use this command
git reset --mixed head

A: Just for reference, this is a serious issue with parallel runners in GitVersionTask: https://github.com/GitTools/GitVersion/issues/1381.


text:
Q: Invoke ToList() method using reflection at runtime in C# I have a generic as follows.
public class PaginatedList<T> : List<T>
{...}

I simply want to invoke ToList() method on that object at runtime using reflection.
Can someone please help.
I have come so only far.
MethodInfo toListMethod = typeof(Enumerable).GetMethod("ToList");
var constructedToList = toListMethod.MakeGenericMethod(TypeObjectOfT);
constructedToList.Invoke(paginatedListObject, null);

I get exception at the last line with message, Parameter count mismatch. I feel that the first two steps are ok, as I have checked the toListMethod.ToString() and constructedToList.ToString(). And they have given me the following output, which I feel is correct.
System.Collections.Generic.List`1[TSource] ToList[TSource](System.Collections.Generic.IEnumerable`1[TSource])
System.Collections.Generic.List`1[AvbhHis.BL.Entities.PatientCategory] ToList[PatientCategory](System.Collections.Generic.IEnumerable`1[AvbhHis.BL.Entities.PatientCategory])

Questions:
1. Am I right so far?

*What should be the parameter to MakeGenericMethod() method. In my case it is the Type of intance of the object of Type T at runtime.

*There seems to be some problem with the Invoke method call. Is passing null correct as second parameter? The first parameter should be an object of the type PaginatedList right?
My energy is out, so kindly help.

A:
The first parameter [to Invoke] should be an object of the type PaginatedList right?

ToList is a static method on Enumerable that takes an IEnumerable<T> as it's only parameter:
public static List<TSource> ToList<TSource>(
    this IEnumerable<TSource> source
)

Invoke takes the instance as the first parameter and the method parameters after that.  For a static method you use null for the "instance" parameter.
So the proper syntax would be
object o = constructedToList.Invoke(null, new object[] {paginatedListObject});

o will then be an object of type List<T> (but you don't know kniw what T is at compile time, so you can't cast it).

A: List<T> has a constructor that takes an IEnumerable<T> (Which gets called in ToList) so you can simplyfy this task by writing the following:
    var resul = Activator.CreateInstance(typeof(List<>).MakeGenericType(TypeObjectOfT), paginatedListObject);


text:
Q: VSTS How to deploy the compiled "published" app to IIS Setting up the VSTS CI process. I have a build setup and a release. It "works" in the sense that it puts files on the IIS server correctly. What it doesn't do is copy the published files to IIS. It's just copying the build files.
And to make sure I'm not using the wrong terminology here. In visual studio, when you build, it builds each project individually. When you "publish" (whether to a local directory or to an IIS server), it compiles all those files into a proper IIS ready set of files.
In other words, I expect a single webconfig and bin directory. What I get is a directory for each project in the solution with its own bin.
I'm using the .net Desktop template for the build and IIS website deployment template for the release definition.
I feel like I'm missing a step in there but I was following the tutorial on how to do this. But no bueno :(

A: There are multiple tutorials about how to perform IIS web Deploy through TFS/VSTS in google.
The fist thing should make sure you have used the properly MSBuild Argument in your build task. For example, if you want to package the build result to a single file:
/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactstagingdirectory)\\"

You can set up Copy and Publish Build Artifacts to copy zip package to share. In this task you could determine which files/folder will be published.
Once your package is ready, we're behind two steps to deployed app:

*

*create and run site and app pool – WinRM – IIS Web App Management

*publish our app – WinRM – IIS Web App Deployment

For details step you could refer this tutorial-- IIS web deploy by vsts
Besides  you could also create a publish profile file(xxxx.pubxml) for the  multiple web app projects. Using the publish file to publish your web apps. Make sure the publish file name is same. In your build definition, specify the publish file: "/p:DeployOnBuild=true /p:PublishProfile=xxxx".

A: You can still use web deploy publish method if the IIS server can be accessed from build agent.
/p:DeployOnBuild=true /p:PublishProfile=Staging /p:Password=hdNSWsbuqno7J5uqnwKafwlfNPt1DSco7J5uqnwKafwlfNPt1DSpKHuYgCco7J5 /p:AllowUntrustedCertificate=true

Some articles can help you:
https://learn.microsoft.com/en-us/aspnet/web-forms/overview/deployment/visual-studio-web-deployment/command-line-deployment
https://www.codeproject.com/Articles/1184858/Deploying-a-Web-App-from-a-Command-Line-using-MSBu


text:
Q: Supremum of a subset is less or equal than infimum of another subset Let $X,Y$ be two bounded subsets of $\mathbb{R}$ satisfying the following proposition 1 :
$$\forall x \in X, \forall y \in Y : x \leq y  $$
I wanted to know if there's a direct proof of $$\sup X \leq \inf Y$$
I think I managed to prove it by contradiction ( correct if I'm wrong please ).

Suppose $\sup X > \inf Y$ . It then follows that     $\sup X - \inf Y > 0$ .
Choosing $\varepsilon_1  = \sup X - \inf Y,$    by definition of infimum, we have that
 $$\exists y_0 \in Y [ y_0 < \inf Y + ( \sup X - \inf Y ) = \sup X ] $$
Choosing $\varepsilon_2  = \sup  X - y_0,  $  by definition of supremum, we have that
$$\exists x_0 \in X [ (\sup X - (\sup X - y_0) = y_0 < x_0 ] $$
Last statement contradicts proposition 1.
I always try to avoid proving by contradictions, but regarding this proposition I can't a direct proof.
Thanks a lot.

A: You can argue without $\epsilon$s:
If $B$ is an upper bound for $X$, then you must have $\sup X \le B$.
Since you have $x \le y$ for all $x \in X, y \in Y$, each $y$ is an upper bound for $X$, that is, we have $\sup X \le y$ for all $y \in Y$.
Similarly, if $C$ is a lower bound for $Y$, we must have $C \le \inf Y$, and since $\sup X$ is a lower bound for $Y$, we have $\sup X \le \inf Y$.


text:
Q: FirebaseInstaceId, InstanceIdResult deprecated How do I change this code since FirebaseInstanceId and InstanceIdResult are deprecated? It also states 'cannot resolve method getToken()' from the code.
FirebaseInstanceId.getInstance().getId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
        @Override
        public void onSuccess(InstanceIdResult instanceIdResult) {
            String token = instanceIdResult.getToken();
            if (!token.equals(session.getData(Session.KEY_FCM_ID))) {
                UpdateToken(token, MainActivity.this);
            }
        }
    });

A: That's not how you should get the token. All those methods are deprecated. Nowadays, the solution is:
FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
    @Override
    public void onComplete(@NonNull Task<String> task) {
        if (task.isSuccessful()) {
            String token = task.getResult();
            //Do what you need to do with your token
            Log.d(TAG, token);
        }
    }
});


text:
Q: How to count NAs using terra's global function? I am trying to count the non-NA values in a spatRaster using the global() function from the terra package. All the functions (mean, max, sd, etc.) seem to work except for "isNA" and "notNA". For these two functions it returns this error: Error in fun(values(x[[i]]), ...) : could not find function "fun", which is the same error it returns for a misspelled/non-existent function.
r <- rast(ncols=10, nrows=10)
values(r) <- c(1:(ncell(r)-1),NA) # Add one NA value
global(r, fun="mean", na.rm=TRUE) # works
global(r, fun="notNA") # error
global(r, fun="notAfunction") # error

Interestingly, when looking at the documentation (?global), the NA functions are named in the function description but are not listed specifically listed as argument options for fun.
So can global() count the NAs/non-NAs? Are the NA function names correct?
Edit:
terra version: 1.4.22

A: Your version of terra is likely outdated and does not include the functions isNA or notNA. You can see the functions in the source code of the current version at Terra raster methods (lines 2551 to 2639 for the global function).
I am currently running version 1.5.21, and the functions work fine.
packageVersion("terra")
#[1] '1.5.21'

global(r, fun="isNA")
#      isNA
#lyr.1    1

global(r, fun="notNA")
#      notNA
#lyr.1    99

You can update the package and reload the library with the following:
install.packages("terra")
library(terra)

A: When I run your code, it actually works:
library(terra)
r <- rast(ncols=10, nrows=10)
values(r) <- c(1:(ncell(r)-1),NA)
global(r, fun="mean", na.rm=TRUE)
global(r, fun="isNA")
global(r, fun="notNA")

Output of isNA:
      isNA
lyr.1    1

Output of notNA:
      notNA
lyr.1    99


text:
Q: PT1000 2 wire probe. Can I add third wire? I'v got 2 wire (81 cm) PT1000 probe which I want to utilize in a project.
I would like to use current source and couple of opamps to make the measurement through ADC (uC) just like described here: link1.
The point is I need to reach measurement spot which is 5 meters away. I will  measure added wire resitance by multimeter and substract it in uC.
As I understand from link1 PT1000 3 wire probe has been used there (first image on the top). Can I modify somehow the schematic to use my 2 wire probe or can I attach third wire [link2 in comments] (I understand disadvantages of this setup)?

A: Sure you can add the extra wire. Just bring it out to the element.
It should be noted that this is not a proper 3-wire RTD scheme and the extra wire only halves the error. A proper 3-wire scheme will reduce the error (in theory) to zero, or at least to the mismatch in resistance between wires.
Here is an example of such a scheme:

simulate this circuit – Schematic created using CircuitLab
To see how this works, consider equal resistances RL in each line. The voltage drop from ground to the lower end of R1 is \$(Ix-2\cdot I_X) \cdot R_L\$. The voltage drop from the top of the element to Vsense is \$+I_X \cdot R_L\$. The voltage drop across the element is just \$I_X R1\$.
So the voltage at Vsense relative to ground is:
\$-I_X \cdot R_L +I_X \cdot R_L + I_X R1 = I_X R1 \$
And the line resistances (if matched) don't have any effect on the measurement.

A: What your looking for is called a kelvin connection, it eliminates the resistance of the wire by using a high impedance measuring circuit that is separate from the power cables http://slideplayer.com/slide/3603346/ slide 6
Run (three or four) wires out to the sensor as close as you can get it. Two for power (VCC and ground) and run two back to the Input.


text:
Q: Wiremock - how to read response from json file? I am trying to use wiremock, using this dependency:
<dependency>
    <groupId>com.github.tomakehurst</groupId>
    <artifactId>wiremock-jre8</artifactId>
    <version>2.33.2</version>
    <scope>test</scope>
</dependency>

I intend to read responses from json files. However, nothing I do works. The test passes without reading the file (I've attempted to use random file names and it always works). What could be wrong here?
@SpringBootTest
@TestExecutionListeners
@ContextConfiguration(initializers = [WireMockContextInitializer::class])
@AutoConfigureWebTestClient
class EndpointsTest {

    @Autowired
    private lateinit var wireMockServer: WireMockServer

    @AfterEach
    fun afterEach() {
        wireMockServer.resetAll()
    }

    @Test
    fun anything() {
        wireMockServer = WireMockServer()
        wireMockServer.stubFor(post("/some-endpoint").willReturn(aResponse().withBodyFile("something.json")))
        ...
    }
}

A: WireMock has a specific path requirement.

To read the body content from a file, place the file under the __files directory. By default this is expected to be under src/test/resources when running from the JUnit rule.

Make sure your file is located at src/test/resources/__files/something.json.


text:
Q: Keepalived can't bind to vip and no error report I need your help.My keepalived can't bind to vip,and i couldn't find any error.This is my log in /var/log/message.By the way,I use Centos6.5
[vagrant@director1 ~]$ sudo tail /var/log/messages
May 26 09:35:53 director1 Keepalived_vrrp[14272]: Registering gratuitous ARP shared channel
May 26 09:35:53 director1 Keepalived_vrrp[14272]: Opening file '/etc/keepalived/keepalived.conf'.
May 26 09:35:53 director1 Keepalived_vrrp[14273]: Netlink reflector reports IP 10.0.2.15 added
May 26 09:35:53 director1 Keepalived_vrrp[14273]: Netlink reflector reports IP 192.168.1.104 added
May 26 09:35:53 director1 Keepalived_vrrp[14273]: Netlink reflector reports IP fe80::a00:27ff:fec7:8f23 added
May 26 09:35:53 director1 Keepalived_vrrp[14273]: Netlink reflector reports IP fe80::a00:27ff:fe55:b1cd added
May 26 09:35:53 director1 Keepalived_vrrp[14273]: Registering Kernel netlink reflector
May 26 09:35:53 director1 Keepalived_vrrp[14273]: Registering Kernel netlink command channel
May 26 09:35:53 director1 Keepalived_vrrp[14273]: Registering gratuitous ARP shared channel
May 26 09:35:53 director1 Keepalived_vrrp[14273]: Opening file '/etc/keepalived/keepalived.conf'.
[vagrant@director1 ~]$ sudo tail /var/log/messages
May 26 09:35:57 director1 Keepalived_vrrp[15242]: Opening file '/etc/keepalived/keepalived.conf'.
May 26 09:35:57 director1 Keepalived[24939]: VRRP child process(15242) died: Respawning
May 26 09:35:57 director1 Keepalived[24939]: Starting VRRP child process, pid=15243
May 26 09:35:57 director1 Keepalived_vrrp[15243]: Netlink reflector reports IP 10.0.2.15 added
May 26 09:35:57 director1 Keepalived_vrrp[15243]: Netlink reflector reports IP 192.168.1.104 added
May 26 09:35:57 director1 Keepalived_vrrp[15243]: Netlink reflector reports IP fe80::a00:27ff:fec7:8f23 added
May 26 09:35:57 director1 Keepalived_vrrp[15243]: Netlink reflector reports IP fe80::a00:27ff:fe55:b1cd added
May 26 09:35:57 director1 Keepalived_vrrp[15243]: Registering Kernel netlink reflector
May 26 09:35:57 director1 Keepalived_vrrp[15243]: Registering Kernel netlink command channel
May 26 09:35:57 director1 Keepalived_vrrp[15243]: Registering gratuitous ARP shared channel

The worst thing is it always print that,and I don't know what's the matter going on.
Here is my keepalived.conf,it's at /etc/keepalived/keepalived.conf
! Configuration File for keepalived

global_defs {
    notification_email {
    willcream@126.com

  }
   notification_email_from Keepalived@localhost
   smtp_server 127.0.0.1
   smtp_connect_timeout 30
   router_id LVS_DEVEL
}

vrrp_sync_group G1{
    group{
        VI_1
    }
}

vrrp_instance VI_1 {
    state MASTER
    interface eth1
    virtual_router_id 51
    priority 100
    advert_int 1
    smtp_alert
    authentication {
        auth_type PASS
        auth_pass baidu
    }
    virtual_ipaddress {
        192.168.1.99/24 dev eth1 label eth1:0
    }
}

Thanks a lot.
Here is my "ip a" output.
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 08:00:27:c7:8f:23 brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global eth0
    inet6 fe80::a00:27ff:fec7:8f23/64 scope link
       valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 08:00:27:55:b1:cd brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.104/24 brd 192.168.1.255 scope global eth1
    inet6 fe80::a00:27ff:fe55:b1cd/64 scope link
       valid_lft forever preferred_lft forever

A: I make lab and found that your config starting only when remove this section:
vrrp_sync_group G1{
    group{
        VI_1
    }
}

If you want to start keepalived that's enough, but it required additional investigation why it not starting.


text:
Q: warning: refname 'HEAD' is ambiguous. warning: refname 'HEAD' is ambiguous. warning: refname 'HEAD' is ambiguous I have read the similar Question Git error: refname 'HEAD' is ambiguous and tried all the answers but in my case those do not help, since the reason for the message in the usual case is a local branch or tag named HEAD. I found this message to appear even when no HEAD or head branch is within the workspace.
I'm facing the following issue, after each interaction with git I get the warning:
$git status
warning: refname 'HEAD' is ambiguous.
warning: refname 'HEAD' is ambiguous.
warning: refname 'HEAD' is ambiguous.
Auf Branch main
Ihr Branch ist auf demselben Stand wie 'origin/main'.

nichts zu committen, Arbeitsverzeichnis unverändert

No I checked all my local and remote branch and tag names and also did the prune thing:
git fetch --prune

but still, no luck.
The message has popped up a few weeks after hosting an other git repo within my parent multi repo but with its own forked head, so this might have somehow trigger the issue. I moved the repo out but the error is still there. Any suggestions?
PS
I do not have a branch called head:
git show-ref
84dac8551de99be283025395338935cd9583c707 refs/heads/Resoner-provierder-as-singleton-hook-experiments
4350427f8397f7c12c16c3f38a15a14cddf2061a refs/heads/add-RNTet
f00d5c15743cabf3fe2b41e68b71c0278e9d8e3a refs/heads/bring_OCR_back
a15789e8f93a23f8a6ec5436608a6c1a0001713d refs/heads/local
6818867b2be03fdb3b606a6e910ef5093e5b81c5 refs/heads/locale
20cdee211a6ad0d8346d3bc445ee7073fb0b03fc refs/heads/main
a4cb53d8fccc568b00283d8daa9b55d2b1fce35f refs/heads/refactoring-of-getStatements
ea8d2b94c2b36932dfdc1ccffd9e5d990546e4c5 refs/heads/refactoring-of-getStatements-mergebranch
572750357cfe3f73633f5c7bf4545857ba1c24ea refs/heads/reproducing_the_tesseract_issue_in_the_simulator
84dac8551de99be283025395338935cd9583c707 refs/remotes/origin/Resoner-provierder-as-singleton-hook-experiments
4350427f8397f7c12c16c3f38a15a14cddf2061a refs/remotes/origin/add-RNTet
f00d5c15743cabf3fe2b41e68b71c0278e9d8e3a refs/remotes/origin/bring_OCR_back
6818867b2be03fdb3b606a6e910ef5093e5b81c5 refs/remotes/origin/locale
20cdee211a6ad0d8346d3bc445ee7073fb0b03fc refs/remotes/origin/main
a4cb53d8fccc568b00283d8daa9b55d2b1fce35f refs/remotes/origin/refactoring-of-getStatements
ea8d2b94c2b36932dfdc1ccffd9e5d990546e4c5 refs/remotes/origin/refactoring-of-getStatements-mergebranch
572750357cfe3f73633f5c7bf4545857ba1c24ea refs/remotes/origin/reproducing_the_tesseract_issue_in_the_simulator
22e504f1143c43b38ad058931fae8599f4e09305 refs/stash
61880f86be6a3d6624b32ce2a5dbc75b7a1d4d5c refs/tags/mileston/1

PPS (no HEAD head situation)
the .git folder looks good as well:
➜  .git git:(main) ll
total 80
-rw-r--r--    1 mac  staff    51B 19 Feb 23:59 COMMIT_EDITMSG
-rw-r--r--    1 mac  staff    85B 20 Feb 00:07 FETCH_HEAD
-rw-r--r--    1 mac  staff    21B 19 Feb 18:06 HEAD
-rw-r--r--    1 mac  staff    41B 20 Feb 00:07 ORIG_HEAD
-rw-r--r--    1 mac  staff   1,0K 19 Feb 23:57 config
drwxr-xr-x    3 mac  staff    96B 27 Sep 22:16 hooks
-rw-r--r--    1 mac  staff    19K 19 Feb 23:59 index
drwxr-xr-x    4 mac  staff   128B 27 Sep 23:01 logs
drwxr-xr-x  260 mac  staff   8,1K 20 Feb 00:07 objects
drwxr-xr-x    6 mac  staff   192B 20 Feb 16:02 refs
drwxr-xr-x   16 mac  staff   512B 21 Jan 12:19 rr-cache

PPPS (.gitmodules)
➜  fak10 git:(main) find . -name ".gitmodules"
./node_modules/extsprintf/.gitmodules
./node_modules/verror/node_modules/extsprintf/.gitmodules
./packages/app/node_modules/art/.gitmodules
./packages/app/node_modules/art/lib/slick/.gitmodules
./packages/app/node_modules/extsprintf/.gitmodules
./packages/app/node_modules/verror/node_modules/extsprintf/.gitmodules
./packages/app/node_modules/realm/vendor/realm-core/.gitmodules
./packages/app/node_modules/realm/src/object-store/.gitmodules

PPPS (workaround)
Its actually quite easy to get rid of the problem by deleting local copy and cloning the repo once again, but it would be good to get behind the issue in order to batter understand it.

A: You have to have a ref named HEAD somehow.
Type that to list all refs on your repo:
git show-ref

I assume you will find a ref path ending by HEAD. Maybe refs/HEAD.
Note that it is normal to have a HEAD for remote repos, like refs/remotes/origin/HEAD, leave it.
Copy that path and delete it with:
git update-ref -d refs/HEAD


text:
Q: str_replace - with the replacement of the figures Hello,
Is there a solution to this problem?
$vowels_1 = array("1","12","11");
$vowels_2 = array("One","Twelve","Eleven");
$onlyconsonants = str_replace($vowels_1, $vowels_2, "11");
echo $onlyconsonants;

Result = OneOne

It is supposed to be = Eleven
Is there a solution?

Thanks

A: Simple, Just swap you $vowels
$vowels_1 = array("11","12","1");
$vowels_2 = array("Eleven","Twelve","One")


text:
Q: Program cannot resolve host name if it's started before first successful internet connection This is related to a stackoverflow post I posted.
Basically I have a Python script that I'm running on an embedded system (Buildroot-based). The python script runs on startup, but I cannot guarantee that the internet connection will be up by then (based on pppd), because the unit might not be in an area with mobile phone signal.
What I've found is that if the python code starts before an internet connection has been established on the machine, even after the connection is established, the python code is still unable to resolve names. I get a [Errno -3] Temporary failure in name resolution error when the socket tries to connect. The only way I can get it to work is to establish the internet connection at least once before I start the python code.
What changes are being made to the system after the internet connection is established at least once that the Python code could be looking for? Is there something I can set up on boot up so that this does not happen?

A: You may use the script hooks that pppd provides, to call your script after ip is up. For instance (from pppd manpage)
/etc/ppp/ip-up
A program or script which is executed when the link is available for
sending and receiving IP packets (that is, IPCP has come up). It is
executed with the parameters

interface-name tty-device speed local-IP-address remote-IP-address ipparam

When you start your python script from inside there, you should be ok.

A: Most programs read the system DNS configuration (in /etc/resolv.conf) only once when they start up or when they make their first network access. They don't re-read the configuration if it changes.
It appears that on your system, the DNS configuration changes when the network goes up (probably changes from unconfigured to having DNS servers configured). This is very common, and unavoidable if the system isn't always connected to the same network.
A way to ensure that programs won't be affected is to run a local DNS caching server. This way, the DNS configuration for applications can be static (always nameserver 127.0.0.1 in /etc/resolv.conf), and only the DNS caching server needs to be told about the servers provided by the network connection. Dnsmasq is a common choice, especially on embedded systems (if you have a Linux router, it probably runs dnsmasq). If you're building your own image with Buildroot, include the dnsmasq package. If you have a pre-built image without dnsmasq, installing dnsmasq via Builtroot may still be the best bet but I'm not familiar with Buildroot so I can't explain how to do it.

A: To force a refresh of the resolve table, you can run this (on linux):
import ctypes
libc = ctypes.cdll.LoadLibrary('libc.so.6')
res_init = libc.__res_init
res_init()


text:
Q: Firebase: Error (auth/api-key-not-valid.-please-pass-a-valid-api-key.) Finally, I (un)successfully deployed my new app. I had many errors on production like, I was used tutorial to implement login/rest/register part and there was an error that login.js not correctly import signInWithEmailAndPassword from ./firebase  so I just import it from import {signInWithEmailAndPassword} from "firebase/auth"; as is should. I had another error like Error [FirebaseError]: Firebase: Error (auth/invalid-api-key). on but I just change my variable to be in quotes "NEXT(...) " .
But now I deployment everything and it should work perfect, but when I try to login in I see an alert Firebase: Error (auth/api-key-not-valid.-please-pass-a-valid-api-key.).
and do not know what I suppost to do to fix it.
Not only login form do not work, but also do not work any of other section of application. I can fetch date etc.
btw. i depoleyd  on Vercel.
btw. it all work perfect on local
update.
I updated variable in verbal environmental variable like
NEXT_PUBLIC_MEASUREMENT_ID but there is no difference. In documentation is written that it should be ````NEXT_PUBLIC_VERCEL_MEASUREMENT_ID``` but this approach do not work.
in my env.local:
NEXT_PUBLIC_VERCEL_API_KEY=
in my env
NEXT_PUBLIC_VERCEL_API_KEY=
(it is in gitignore)
in Vercel server all variable are the same
NEXT_PUBLIC_VERCEL_API_KEY=

A: To solve my problem with no access to firebase in production I had to do many things:

*

*correctly set variables

*set up authorised domain

ad1
npm i -g vercel
Vercel env add NAME
then connect to variable and select what kind of variable it is (using space).
variable should look like NEXT_PUBLIC_KEY_API="..." and used as process.env.NEXT_PUBLIC_API_KEY (without "...").
then Vercel --prod
ad 2 Authentication => settings =>.
Authorized domains and add domain.


text:
Q: Is there a way to make this statement using Eloquent? I have been trying in many ways but my knowledge is not good enough XD
DB::select ('SELECT c.`id_client`, UPPER (c.`name`) AS `name`, '
    . 'c.`telephone`, MATCH (c.`name`) AGAINST ( ? ) AS `match` '
    . 'FROM client c '
    . 'WHERE MATCH (c.`name`) AGAINST ( ? ) '
    . 'HAVING `match` > 5.2 ORDER BY `match` DESC LIMIT 10', array ($name, $name));

A: Not sure if it can be done with Eloquent, perhaps Fluent instead?
$results = DB::table('client')
    ->select(array(
        'id_client', 'name', 'telephone',
        DB::raw("MATCH(name) AGAINST (?) AS match")
    ))
    ->whereRaw("MATCH (name) AGAINST(?)")
    ->having('match', '>', 5.2)
    ->orderBy('match','desc')
    ->limit(10);

There will probably be some typos there, but this should point you in the right direction.
Fixed some typos.
Update:
You can try using "match against" as shown in the 2 examples below. Not sure if either works as I haven't tested, but give both a try -- the second looks cleaner:
->where(DB::raw('MATCH(`some_field`)'),'AGAINST',DB::raw('("bar")'))

OR
->whereRaw('MATCH (some_field) AGAINST("bar")')

Just replace the bar with something you wish to match against. Hope that helps.


text:
Q: How to avoid avoid broken pipes using c# and Python? When trying to use stdin and stdout in C# (Unity) to pipe to a Python process, I get about a dozen or so transactions and the process breaks and the error "ObjectDisposedException: The object was used after being disposed."
After trying several of the more obvious things, I'm bringing the problem here perhaps someone know just the right technique.  Thanks in advance.
Here's the C# Startup code:
Process pyProcess;    // <=== fixed
ProcessStartInfo pyStartInfo;
public StreamReader pyStreamReader;
public StreamWriter pyStreamWriter;

public void startPython()
{

    // Create new process start info
    pyStartInfo = new ProcessStartInfo(pyPath)
    {
         UseShellExecute = false,
         RedirectStandardInput = true,
         RedirectStandardOutput = true,
         Arguments = pyApp + " " + pyArgs
    };

pyProcess = new Process { StartInfo = pyStartInfo };
pyProcess.Start();
pyStreamReader = pyProcess.StandardOutput;
pyStreamWriter = pyProcess.StandardInput;
pyStreamWriter.WriteLine("Hello!");
string str = pyStreamReader.ReadLine();
Debug.LogFormat(str + "\n");
}

void Start()
{
    if(testPython == true)
        startPython();

Here is the fragment that generates data sent to python at each update...
if (controller.testPython)
{
    string str, python;
    str = String.Format("data to send");
    pyStreamWriter.DiscardBufferedData();  #<==== fixed
    pyStreamWriter.WriteLine(str);
    python = pyStreamReader.ReadLine();
    Debug.LogFormat("python says: " + python + "\n");
    }

And here is the simplified python process that's echoing the data
while True:
    cmd = input()        # read a command from c#
    print(cmd)  # process the cmd, here we just echo it back to c#

A: After a little experimentation, I discovered that adding
pyStreamReader.DiscardBufferedData();

before
pyStreamWriter.WriteLine(str);

solves the main problem and this simple form of piping seems to work, at least for hundreds of transactions that I observed.
I also had to declare pyProcess outside the scope so the code so that its handle is not released.  That resolved the ObjectDisposed exception.


text:
Q: Issue with kable() output after loading TBDBr package in Quarto document I'm having an issue with table output once I load the TBDBr package (https://github.com/TalkBank/TBDBr) in my Quarto document.
Here's a reproducible example of my .qmd document with the rendered tables.
---
title: "Test document"
format: html
---

Load in the basic packages.

```{r}
#| label: setup
#| message: false
library(tidyverse)
library(knitr)
```

Create a table using `kable()`.

```{r}
#| label: tbl-test-1
#| tbl-cap: 'Good table.'

iris |>
  slice_head(n = 10) |>
  kable()
```

Load the `TBDBr` package and then run the same code as above to generate a table using `kable()`.

```{r}
#| label: tbl-test-2
#| tab-cap: 'Bad table.'

library(TBDBr)

iris |>
  slice_head(n = 10) |>
  kable()
```

I suspect that it may have something to do with kableExtra being loaded as a dependency with the TBDBr package.
Here's my session info if it is of any help.
─ Session info

 version  R version 4.1.2 (2021-11-01)
 os       macOS Monterey 12.6
 system   x86_64, darwin17.0
 ui       RStudio
 language (EN)
 collate  en_US.UTF-8
 ctype    en_US.UTF-8
 tz       America/New_York
 date     2022-10-18
 rstudio  2022.07.1+554 Spotted Wakerobin (desktop)
 pandoc   2.19.2 @ /usr/local/bin/ (via markdown)

─ Packages

 package   * version date (UTC) lib source
 dplyr     * 1.0.10  2022-09-01 [1] CRAN (R 4.1.2)
 forcats   * 0.5.2   2022-08-19 [1] CRAN (R 4.1.2)
 ggplot2   * 3.3.6   2022-05-03 [1] CRAN (R 4.1.2)
 knitr     * 1.40    2022-08-24 [1] CRAN (R 4.1.2)
 purrr     * 0.3.4   2020-04-17 [1] CRAN (R 4.1.0)
 readr     * 2.1.3   2022-10-01 [1] CRAN (R 4.1.2)
 shiny     * 1.7.2   2022-07-19 [1] CRAN (R 4.1.2)
 stringr   * 1.4.1   2022-08-20 [1] CRAN (R 4.1.2)
 TBDBr     * 0.1.0   2022-09-03 [1] Github (Talkbank/TBDBr@f88caca)
 tibble    * 3.1.8   2022-07-22 [1] CRAN (R 4.1.2)
 tidyr     * 1.2.1   2022-09-08 [1] CRAN (R 4.1.2)
 tidyverse * 1.3.2   2022-07-18 [1] CRAN (R 4.1.2)

 [1] /Users/francojc/R/Library
 [2] /Library/Frameworks/R.framework/Versions/4.1/Resources/library

A: Thanks @user2554330, adding the options(kableExtra.auto_format = FALSE) before loading the TBDBr package worked great.
Also a big thanks for the typo catch @shafee. The table outputs are identical now as desired.


text:
Q: Show that $ f(p) \approx \sum_{k=0}^n f (\tfrac{k}{n}) \binom{n}{k} p^k (1-p)^{n-k}$ I have a probability question.  We have a function $f:[0,1] \to \mathbb{R}$ that we would like to estimate.  So we use the Bernstein polynomials and write:
$$  f(p) \approx \sum_{k=0}^n f (\tfrac{k}{n}) \binom{n}{k} p^k (1-p)^{N-k}$$
Mathematicians would say this convergence is uniform on [0,1].  Nonetheless I noticed this is the expected value of a biased random walk after $N$ steps.  Our random variable $X_n = x_1 + \dots x_n$ taking values on the set $\{ 0, 1, 2, \dots, n\}$  with $x_i \in \{ 0,1\}$ at random with probability $p$ or $1-p$.
$$ f(x) \approx \mathbb{E}[\,f(\tfrac{X_n}{n})\,]$$
What does it mean to let $p$ vary from $0$ to $1$ ? --- I have never seen a model that lets the probability vary like this.  This might run under a different name in the statistics literature:

*

*mixture distribution

*student t-distribution

*maximum likelihood
I really don't know.

This is called the Weierstrass approximation theorem.  Here is the paper by Levasseur if interested.
Interestingly the Berenstein polynomials are also the basis of the Bezier curves (and de Casteljau algorithm) as well as NURBS and other splines.  These are use in computer graphics to design the shapes of our alphabets and many other things.


text:
Q: Form not adding parameters in GET submission in production in Rails I have a form like this:
<%= form_tag how_it_works_path, :method=>:get do %>
            <fieldset>
              <select id="location" name="location">
                <option value="">Please select your location</option>
                <optgroup label="Area 1">
                  <option value="city1">City1</option>
                  <option value="city2">City2</option>
                </optgroup>
                <optgroup label="Area 2">
                  <option value="city3">City3</option>
                  <option value="city4">City4</option>
                </optgroup>
              </select>
              <input class="button" name="commit" type="submit" value="How it works?" />
            </fieldset>
          <% end %>

Which is under welcome#index view.  When I do the submission (which goes to pages#how_it_works) in development environment, it correctly adds the location parameter in the URL.  However, when doing it in production, it doesn't.  Why would this be happening?
I am using the exactly same form in pages#how_it_works and the submission is done correctly.


text: Q: Is there any way to force blank Macbook Pro 2011 to use Intel Graphics all the time? Macbook Pro 2011 (15-inch) AMD Graphics is dead and stuck on white screen, HDD is formatted, Windows 10 installed, is there any way to force it to use Intel Graphics all the time through windows or maybe CMD?


text:
Q: Make dynamic name text field in Postman I'm using Postman to make REST API calls to a server. I want to make the name field dynamic so I can run the request with a unique name every time.
{
  "location":
  {
    "name": "Testuser2", // this should be unique, eg. Testuser3, Testuser4, etc
    "branding_domain_id": "52f9f8e2-72b7-0029-2dfa-84729e59dfee",
    "parent_id": "52f9f8e2-731f-b2e1-2dfa-e901218d03d9"
  }

}

A: In Postman you want to use Dynamic Variables.
The JSON you post would look like this:
{
  "location":
  {
    "name": "{{$guid}}",
    "branding_domain_id": "52f9f8e2-72b7-0029-2dfa-84729e59dfee",
    "parent_id": "52f9f8e2-731f-b2e1-2dfa-e901218d03d9"
  }

}

Note that this will give you a GUID (you also have the option to use ints or timestamps) and I'm not currently aware of a way to inject strings (say, from a test file or a data generation utility).

A: In Postman you can pass random integer which ranges from 0 to 1000, in your data you can use it as
{
  "location":
  {
    "name": "Testuser{{$randomInt}}",
    "branding_domain_id": "52f9f8e2-72b7-0029-2dfa-84729e59dfee",
    "parent_id": "52f9f8e2-731f-b2e1-2dfa-e901218d03d9"
  }

}

A: Just my 5 cents to this matter. When using randomInt there is always a chance that the number might eventually be present in the DB which can cause issues.
Solution (for me at least) is to use $timestamp instead.
Example:
{
    "username": "test{{$timestamp}}",
    "password": "test"
}

A: For anyone who's about to downvote me this post was made before the discussion in comments with the OP (see below). I'm leaving it in place so the comment from the OP which eventually described what he needs isn't removed from the question.

From what I understand you're looking for, here's a basic solution. It's assuming that:

*

*you're developing some kind of script where you need test data

*the name field should be unique each time it's run

If your question was more specific then I'd be able to give you a more specific answer, but this is the best I can do from what's there right now.

var counter = location.hash ? parseInt(location.hash.slice(1)) : 1; // get a unique counter from the URL
var unique_name = 'Testuser' + counter; // create a unique name
location.hash = ++counter; // increase the counter by 1

You can forcibly change the counter by looking in the address bar and changing the URL from ending in #1 to #5, etc.
You can then use the variable name when you build your object:
var location = {
    name: unique_name,
    branding_domain_id: 'however-you-currently-get-it',
    parent_id: 'however-you-currently-get-it'
};

A: Add the below text in pre-req:

var myUUID = require('uuid').v4();
  pm.environment.set('myUUID', myUUID);

and use the myUUID wherever you want
like
name: "{{myUUID}}"
It will generate a random unique GUID for every request

A: var uuid = require('uuid');
pm.globals.set('unique_name', 'testuser' + uuid.v4());

add above code to the pre-request tab.
this was you can reuse the unique name for subsequent api calls.
Dynamic variable like randomInt, or guid is dynamic ie : you donot know what was send in the request. there is no way to refer it again, unless it is send back in response. even if you store it in a variable,it will still be dynamic
another way is :
var allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var shuffled_unique_str = allowed.split('').sort(function(){return 0.5-Math.random()}).join('');

courtsey refer this link for more options


text:
Q: Monitor big text file for change and show what was added I try to monitor text log file for changes and want to see lines that was added
I try with watchdog it seems to work with some manually created/edited files for testing, but my log file (in the same directory) isn't detected as "changed", but it was changed. It's probably because this file is already open (maybe in a specific mode). If I close the app that uses this log file and change it manually then watchdog works ok.
How do I check if the file was changed and if the changes were written to
 the console?
#!/usr/bin/python
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class MyHandler(FileSystemEventHandler):
    def on_modified(self, event):
        print(f'event type: {event.event_type}  path : {event.src_path}')

if __name__ == "__main__":
    event_handler = MyHandler()
    observer = Observer()
    observer.schedule(event_handler, path='C:\gory\parcienaszklo\logs', recursive=False)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()


text:
Q: Porting Perl to Python I am wondering if there are any tips or tricks to converting perl into python.  It would be nice if there was a script like python's 2to3.  Or perhaps some compatibility libraries.  It doesn't have to be complete,  anything to help speed up the process would be helpful.

A: There are so many ways of doing the same thing in Perl that writing any sort of crosscompiler would be... painful at best. Reconstruct (don't just translate) the program manually.

A: Another approach is that you might be able to reuse existing Perl code and complement it with new Python code.
One possibility that might work for you is to use the perl Python module, which allows you to execute Perl code inside Python.
Another approach is to have Perl produce its output as simple text/JSON/YAML files which is parsed by Python for further processing.  Thus, I was able to use my legacy Perl code without rewriting it, while switching to Python.  Your mileage may vary, as this "gluing" method might be too slow for your needs.  This "pass files" method is good when you have long calculations that produce intermediate results: you can start the computation in Perl, and continue it in Python.

A: Unfortunately I ran in to the same pickle, there seems to be no direct way to do it. But if you are a vim savvy like I am you could quickly come up with a list like this one.
Just type all this in a file called(or something else) 'substitute' and open the Perl script(back up your original script first) and do :source path/to/the/substitute. Please note this is by no means perfect but might give you a good direction of start (Hopefully!)

    1,$s/\$\(.*\) /\1 /g
    1,$s/\$\(.*\)->/\1\./g
    1,$s/->/\./g
    1,$s/\$//g
    1,$s/ eq / \=\= //g
    1,$s/@//g
    1,$s/=>/:/g
    1,$s/use /import /g
    1,$s/::/\./g
    1,$s/||/or/g
    1,$s/&&/and/g
    1,$s/my //g
    1,$s/sub /def /g
    1,$s/ undef/ None/g
    1,$s/%//g
    1,$s/;$//g
    1,$s/\/os.environ/g
    1,$s/defined //g

A: the best "tool" to convert Perl to Python is still yourself :). Learn the syntax of Python and how it works from Python docs. Then do the conversion manually. for example, Perl makes use of regex a lot, however, in Python, string manipulation is so easy that most of the time, regex is not needed. How would a converter know this beforehand?? There are also many ways to do things in Perl, so how would a converter know what is the best with Python equivalents ? therefore, manual conversion is still the best way to go
If you are interested, you can take a look at this book
Also of interest, Pleac

A: Keep a phrasebook handy as you go through the code you want to port.

A: Converting would require writing a Perl parser, semantic checker, and Python code generator.
Not practical. Perl parsers are hard enough for the Perl teams to get right. You'd be better off translating Perl to Python from the Perl AST (opcodes) using the Perl Opcode or related modules.
http://perldoc.perl.org/Opcode.html
Some notations do not map from Perl to Python without some work. Perl's closures are different, for example. So is its regex support.
In short, either convert it by hand, or use some integration modules to call Python from Perl or vice-versa.


text:
Q: List of Elements that are editable in Salesforce Production Environment Is there an article or a document by Salesforce where I can find a comprehensive list of elements or types that can be modified in Salesforce Production Environment?
Thank you!

A: Presuming you're talking about the various types of metadata, the only five types you can't edit in production are Lightning Web Components, Aura Components, Visualforce Pages, Visualforce Components, and Apex Code. All other types of metadata can be edited under correct circumstances (e.g. you can't edit an Activated Process Builder, but you can clone to create a new one).


text:
Q: Google App Engine page URL goes to 404 page instead of index page I have a Node JS web application deployed with Google App Engine.  When I navigate to the page URL:
https://outdoor-activity-finder.appspot.com
after a delay, the 404 page for the website loads.  If I go to:
https://outdoor-activity-finder.appspot.com/
The index page loads and the website works as expected.  Do I need to specify that the default route for the app is '/'?
This is my app.yaml:
runtime: nodejs8
env_variables:
  databasePassword: ""
  googleAPIKey: ""
  googleMapsAPIKey: ""
  openWeatherAPIKey: ""
  trailAPIKey: ""
  state: "production"


text:
Q: Remove First Character of (Original) String in JavaScript I see this article but it's specific to deleting a character if it's a certain number (0, in that case).
I want to remove the first character from a string no matter what it is.
splice() and shift() won't work because they're specific to arrays:

let string = "stake";
string.splice(0, 1);
console.log(string);

let string = "stake";
string.shift();
console.log(string);

slice() gets the first character but it doesn't remove it from the original string.

let string = "stake";
string.slice(0, 2);
console.log(string);

Is there any other method out there that will remove the first element from a string?

A: Use substring

let str = "stake";
str = str.substring(1);
console.log(str);


text:
Q: Why when Y=-X I get negative p.d.f? Am I doing something wrong here?
Suppose we know the pdf of the random variable X  fx(x) and we wish to find the pdf of the random variable Y fy(y), where Y=-X
Then fy(y)=-fx(-y). But that means the p.d.f of Y is negative since p.d.f of X is positive.
But we can't have a negative p.d.f
What's going on here?
Thanks in advance

A: Let us restrict to the case where the CDF of $X$ is differentiable.
Then its derivative serves as PDF ($F_X'=f_X$) and:
$$F_{Y}\left(y\right)=P\left\{ Y\leq y\right\} =P\left\{ X\geq-y\right\} =1-F_{X}\left(-y\right)$$
so that: $$f_{Y}\left(y\right)=F_{Y}'\left(y\right)=f_{X}\left(-y\right)$$
Equality $f_{Y}\left(y\right)=f_{X}\left(-y\right)$ holds also if $F_X$ is not differentiable.


text:
Q: Blank line at EOF with PHP I have a script that writes a .CSV
,pretty self explaining:
$handle = fopen($name);

foreach ($data as $tkey => $tval) {
    fwrite($handle, $eol);
}
fclose($handle);

This works compleatly fine, everything is, as it should be.
BUT:
At the end of the file, there is always a blank line that causes problems, when i want to process the .CSV with another programm.
EX:
1 Date;Time
2 22.4;03:22;
3 23.4;09:22;
4 24.4;14:22;
5

When I reload the file and echo it to the browser, the line is not within the array, so it seems to be created, when the file is closed.
I have read aboud some sort of of PSR Coding guides, but thought these are more like ,yeah, guidelines.
Is the blank line a fixed thing or is there a a workaround?