text:
Q: Problem filtering data upon choosing an item from combo box WPF MVVM I have two datagrid's in two different tabitems. The datagrid in first tabitem displays some specific data on app load and should get updated if the data changes, pretty simple. The second tabitem's datagrid should be empty on app load but when an item is selected/typed from the combo box then it should filter the data as per that combo box selected item and show on the filtered data on datagrid of second tabitem (maintaining MVVM pattern).
This is what I've tried:
XAML
<TabControl>
    <TabItem Header="Pending Bills">
        <DataGrid ItemsSource="{Binding FilteredBills}" AutoGenerateColumns="False" CanUserAddRows="False">
            <DataGrid.Columns>
                <DataGridTextColumn
                        Header="Vendor"
                        Binding="{Binding Path=Party, Mode=OneWay}"
                        Width="275"
                        IsReadOnly="True" />
                <DataGridTextColumn
                        Header="Bill No."
                        Binding="{Binding Path=BillNo, Mode=OneWay}"
                        Width="275"
                        IsReadOnly="True" />
                ......
            </DataGrid.Columns>
        </DataGrid>
    </TabItem>
    <TabItem Header="Filtered Bills">
    ........
            <DataGrid Grid.Row="0" ItemsSource="{Binding AllBills}" AutoGenerateColumns="False" CanUserAddRows="False">
                <DataGrid.Columns>
                    <DataGridTextColumn
                        Header="Vendor"
                        Binding="{Binding Path=Party, Mode=OneWay}"
                        Width="275"
                        IsReadOnly="True" />
                    <DataGridTextColumn
                        Header="Bill No."
                        Binding="{Binding Path=BillNo, Mode=OneWay}"
                        Width="275"
                        IsReadOnly="True" />
                    ......
                </DataGrid.Columns>
            </DataGrid>
            <StackPanel Orientation="Horizontal">
                <ComboBox x:Name="cmbBox" ItemsSource="{Binding ComboItems}" SelectedItem="{Binding SelectedCBItem}"/>
            </StackPanel>
        </Grid>
    </TabItem>
</TabControl>

A base viewmodel to enable the PropertyChangedEventHandler
public class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Basic model:
public class Bills : ViewModelBase
{
    private int _id;
    public int Id
    {
        get
        {
            return _id;
        }
        set
        {
            _id = value;
            OnPropertyChanged("Id");
        }
    }

    private string _party;
    public string Party
    {
        get
        {
            return _party;
        }
        set
        {
            _party = value;
            OnPropertyChanged("Party");
        }
    }

    private string _billNo;
    public string BillNo
    {
        get
        {
            return _billNo;
        }
        set
        {
            _billNo = value;
            OnPropertyChanged("BillNo");
        }
    }

    .......

}

The billsviewmodel and a helper data access class called Model:
public class BillsViewModel : ViewModelBase
    {

        public BillsViewModel()
        {
            cvsAll.Source = m.AllBills;
            cvsFiltered.Source = m.FilteredBills;
        }

        Model m = new Model();

        CollectionViewSource cvsAll = new CollectionViewSource();
        public ICollectionView AllBills
        {
            get { return cvsAll.View; }
        }

        public List<string> ComboItems
        {
            get { return m.UniqueValues(); }
        }

        CollectionViewSource cvsFiltered = new CollectionViewSource();
        public ICollectionView FilteredBills
        {
            get { return cvsFiltered.View; }
        }

        private string _selectedCBItem;
        public string SelectedCBItem
        {
            get { return _selectedCBItem; }
            set
            {
                _selectedCBItem = value;
                cvsFiltered.Source = m.GetBills_Pen(value);
                OnPropertyChanged("SelectedCBItem");
            }
        }
    }

    public class Model
    {
        private List<Bills> _allBills;

        public List<Bills> AllBills
        {
            get
            {
                if (_allBills == null) LoadAllBillsFromDatabase();

                return _allBills;
            }
        }

        private List<Bills> _filteredBills;

        public List<Bills> FilteredBills
        {
            get
            {
                if (_filteredBills == null) LoadUnpaidBillsFromDatabase();

                return _filteredBills;
            }
        }

        public void LoadAllBillsFromDatabase()
        {
            SQLiteConnection m_dbConnection = new SQLiteConnection(@"Data Source=Bills.db;");
            SQLiteCommand sqlCom = new SQLiteCommand(@"Select * From billdata", m_dbConnection);
            SQLiteDataAdapter sda = new SQLiteDataAdapter(sqlCom);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            _allBills = new List<Bills>();

            foreach (DataRow row in dt.Rows)
            {
                _allBills.Add(new Bills()
                {
                    Id = Convert.ToInt32(row["Id"]),
                    Party = (string)row["Party"],
                    BillNo = (string)row["BillNo"],
                    .......
                });

            }
            m_dbConnection.Close();
        }

        public void LoadUnpaidBillsFromDatabase()
        {
            SQLiteConnection m_dbConnection = new SQLiteConnection(@"Data Source=Bills.db;");
            SQLiteCommand sqlCom = new SQLiteCommand(@"Select * From billdata where PaidOn != ''", m_dbConnection);
            SQLiteDataAdapter sda = new SQLiteDataAdapter(sqlCom);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            _filteredBills = new List<Bills>();

            foreach (DataRow row in dt.Rows)
            {
                _filteredBills.Add(new Bills()
                {
                    Id = Convert.ToInt32(row["Id"]),
                    Party = (string)row["Party"],
                    BillNo = (string)row["BillNo"],
                    .......
                });

            }
            m_dbConnection.Close();
        }

        public List<string> UniqueValues()
        {
            return _allBills.Select((s) => s.Party).Distinct().OrderBy((s) => s).ToList();
        }

        public List<Bills> GetBills_Pen(string filterValue)
        {
            return _allBills.FindAll(s => s.Party == filterValue).ToList();
        }
    }

There are 2 issues:

*

*The datagrid on 2nd tabitem is displaying all data on app load

*When I select or type a valid item in the combo box the datagrid on 2nd tabitem is not showing the filtered data.

Have I not implemented the ICollectionView the right way or what am I doing wrong here and most importantly how do I fix this ?

A: This should work. I also added a function to ViewModelBase to make the code shorter
public class ViewModelBase
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
    protected virtual void SetValue<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
    {
        field = value;
        OnPropertyChanged(propertyName);
    }
}

public class BillsViewModel : ViewModelBase
{
    private List<BillViewModel> _allBills;

    public BillsViewModel()
    {
        _allBills = m.AllBills;
        AllBills = new ListCollectionView(_allBills);
        ComboItems = _allBills.Select(b => b.Party).Distinct().OrderBy(b => b).ToList();
        FilteredBills = new ListCollectionView(_allBills)
        {
            Filter = o => ((BillViewModel)o).Party == SelectedCBItem
        };
    }

    Model m = new Model();

    public ICollectionView AllBills { get; private set; }
    public ICollectionView FilteredBills { get; private set; }

    public List<string> ComboItems { get; private set; }

    private string _selectedCBItem;
    public string SelectedCBItem
    {
        get { return _selectedCBItem; }
        set
        {
            SetValue(ref _selectedCBItem, value);
            FilteredBills.Refresh();
        }
    }
}

A: Using the approach shown by @Firo I've managed to successfully implement in my app(so I'm marking his answer as accepted) and here is what I ended up with(in case it helps anyone who might have similar issues)
public class Model
{
    private List<Bills> _sBills;

    public List<Bills> SBills
    {
        get
        {
            if (_sBills == null) LoadAllBillsFromDatabase();

            return _sBills;
        }
    }

    public List<Bills> FilteredBills { get; private set; }

    public void LoadAllBillsFromDatabase()
    {
        SQLiteConnection m_dbConnection = new SQLiteConnection(@"Data Source=Bills.db;");
        SQLiteCommand sqlCom = new SQLiteCommand(@"Select * From billdata", m_dbConnection);
        SQLiteDataAdapter sda = new SQLiteDataAdapter(sqlCom);
        DataTable dt = new DataTable();
        sda.Fill(dt);
        _sBills = new List<Bills>();

        foreach (DataRow row in dt.Rows)
        {
            _sBills.Add(new Bills()
                        {
                            Id = Convert.ToInt32(row["Id"]),
                            Party = (string)row["Party"],
                            BillNo = (string)row["BillNo"],
                            BillDt = (string)(row["BillDt"]),
                            Amt = (string)row["Amt"],
                            DueDt = (string)(row["DueDt"]),
                            PaidOn = (string)(row["PaidOn"])
                        });

        }
        m_dbConnection.Close();
    }

}

public class BillsViewModel : ViewModelBase
{

    private List<Bills> _allBills;

    public BillsViewModel()
    {
        _allBills = m.SBills;
        AllBills = new ListCollectionView(_allBills)
        {
            Filter = o => ((Bills)o).PaidOn==""
        };
        ComboItems = _allBills.Select(b => b.Party).Distinct().OrderBy(b => b).ToList();
        FilteredBills = new ListCollectionView(_allBills)
        {
            Filter = o => ((Bills)o).Party == SelectedCBItem && ((Bills)o).PaidOn==""
        };
    }

    Model m = new Model();

    public ICollectionView AllBills { get; private set; }
    public ICollectionView FilteredBills { get; private set; }

    public List<string> ComboItems { get; private set; }

    private string _selectedCBItem;
    public string SelectedCBItem
    {
        get { return _selectedCBItem; }
        set
        {

            SetValue(ref _selectedCBItem, value);
            FilteredBills.Refresh();

        }
    }
}

The itemsource in the datagrid in 1st tabitem is AllBills and itemsource in the datagrid in 2nd tabitem is FilteredBills


text:
Q: Uploading Base64 encoded image to server - 400 Server Error I'm uploading Base64 encoded image to the HelpScout server with JSON payload using Volley. This return in com.android.volley.ServerError and status code 400. I'm encoding the image as below:
var imageEncoded = ""
            try {
                val bitmap = MediaStore.Images.Media.getBitmap(context?.contentResolver, uri)
                //val bitmap = BitmapFactory.decodeFile(path)
                val stream = ByteArrayOutputStream()
                bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream)
                val imageBytes = stream.toByteArray()
                imageEncoded = Base64.encodeToString(imageBytes, Base64.DEFAULT)
            } catch (e: Exception) {
                e.printStackTrace()
            }

I already have checked several questions asked but got no luck. Below is Volley method I'm working with:
public static void volleyRowJsonPostRequest(Context context,String url, JSONObject object,final Map<String, String> headers, final VolleyTaskListener taskListener) {
        final JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.POST, url, object,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            taskListener.onTaskComplete(response.toString());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        NetworkResponse networkResponse = error.networkResponse;
                        if (networkResponse != null)
                            taskListener.onTaskFailed(networkResponse.statusCode);

                    }
                }
        ){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return headers;
            }
        };

        jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(
                60000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        jsObjRequest.setShouldCache(false);
        Volley.newRequestQueue(context).add(jsObjRequest);
    }

and JSONObject is as:
{
  "subject": "some test value",
  "mailboxId": 170715,
  "type": "email",
  "status": "active",
  "customer": {
    "email": "mymailaddress@mail.com"
  },
  "threads": [
    {
      "type": "customer",
      "text": "some test value",
      "customer": {
        "email": "mymailaddress@mail.com"
      },
      "attachments": [
        {
          "fileName": "Screenshot_20181005-160109.png",
          "mimeType": "image\/png",
          "data": "base64 encoded string goes here"
        }
      ]
    }
  ],
  "tags": [
    "Swytch",
    "Help"
  ]

}

A: I have fixed the error just updating the Base64 encoding method as  Base64.encodeToString(imageBytes, Base64.DEFAULT) to Base64.encodeToString(imageBytes, Base64.NO_WRAP). With Base64.DEFAULT the resulting encoded string is default values for encoder flags (incliding line breaks). Base64.NO_WRAP Encoder flag bit to omit all line terminators (i.e., the output will be on one long line). Here is more info.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Implementing my own HashSet class... my add() logic seems faulty when scanning a file for words and using the built-in hashset class from the API, my word count returns 349 (which is what it's supposed to be)
Using my home-made hashset class, I get 235... so something in my add() method must be wrong, but I can't understand what it is.
thanks for any help!
public class HashWordSet implements WordSet {

private int size = 0;
private Node[] buckets = new Node[8];

public Iterator<Word> iterator() {
    return new WordIterator();
}

//Add word if not already added
public void add(Word word) {
    int key = getBucketNumber(word);
    Node node = buckets[key];
    while (node != null) {
        if (node.value.equals(word))
            return;
        else
            node = node.next;
    }
    node = new Node(word);
    buckets[key] = node;
    size++;
    if (size == buckets.length) rehash();
}

private int getBucketNumber(Word word) {
    int hc = word.hashCode();
    if (hc < 0) hc = -hc;
    return hc % buckets.length;
}

A: It seems like you override nodes[key] with the new word [only] instead of appending a new node to the list, so you lose all old data that was already in this node.
It should work fine if there are no elements in there before add() was invoked, but if there are - you will lose some data.
node = new Node(word);
buckets[key] = node;

Though it is hard to be 100% sure about it without the actual implementation of Node.

A: node = new Node(word);
buckets[key] = node;

If there are any nodes already in the bucket you have just thrown them away.  Try something like:
node = new Node(word);
node.next = buckets[key];
buckets[key] = node;


text:
Q: How to set test group to @Test methods dynamically using TestNG? I want to set group to a particular @Test method at runtime depending on some condition
Suppose I have the following classes
public class MyTest1{
  @Test
  public void test1(){
    System.out.println("test1 called");
  }
}

public class MyTest2{
  @Test(groups={"group1"})
  public void test2(){
    System.out.println("test2 called");
  }

  @Test(groups={"group2"})
  public void test3(){
    System.out.println("test3 called");
  }
}

Now while running test I am sending "-groups group1" or "-groups group2" to TestNG in command line. So testng is running either test2() or test3() depending on the group name passed. Now my requirement is to run test1() that is not supposed have any groups attached. Whatever group I provide to testng runner this test1() should be run every time. I tried with implementing alter method of IAlterSuiteListener but I could not get all the test methods including which are not considered to run. So I could not set the group name at runtime.
So is there any other way to set groups to @Test methods (having no groups defined) at runtime?

A: You should perhaps start exploring the beanshell way of method selection that TestNG provides to you for this purpose.
Sometime back I wrote up a blog post which talks about how to work with Beanshell expressions in TestNG. You can read more about it here and refer to the official TestNG documentation here.
Quoting the TestNG documentation,

TestNG defines the following variables for your convenience:

*

*java.lang.reflect.Method method:  the current test method.

*org.testng.ITestNGMethod testngMethod:  the current test method.

*java.util.Map groups:  a map of the groups the current test method belongs to.

So with just your example, I went ahead to create a suite xml file that looks like below
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="1265_Suite" parallel="false" verbose="2">
    <test name="92" parallel="false" preserve-order="true">
        <method-selectors>
            <method-selector>
                <script language="beanshell">
                    <![CDATA[whatGroup = System.getProperty("groupToRun");
                (groups.containsKey(whatGroup) || testngMethod.getGroups().length ==0);
                ]]>
                </script>
            </method-selector>
        </method-selectors>
        <classes>
            <class name="com.rationaleemotions.stackoverflow.MyTest1"/>
            <class name="com.rationaleemotions.stackoverflow.MyTest2"/>
        </classes>
    </test>
</suite>

And I run it via the command prompt using maven as below : (The test classes are basically what you shared in your question )
mvn clean test -DsuiteXmlFile=dynamic_groups.xml -DgroupToRun=group2

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running TestSuite
...
... TestNG 6.11 by Cédric Beust (cedric@beust.com)
...

test1 called
test3 called
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 15.377 sec - in TestSuite

Results :

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

A: There is no direct way of doing this if you are specifying groups.  However, there are two other ways of doing this.

*

*You can mark all your tests with no groups in a group called "nogroups" and include that group while you run
Or

*If you have huge number of tests that you already have, then write up an Annotation Transformer which basically adds cases with no groups in this group --sample example below.  Writing a transformer can help you control edge cases programmatically as well.

public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {
    if (annotation.getGroups().length == 0) {
        annotation.setGroups(new String[]{"noGroups"});
    }
}


text:
Q: How to organize this excel page in proper rows and columns? I want to organize this sheet in proper rows and columns. can anyone suggest to me the steps to do it?

A: You can utilize Text to Column feature. It is in DATA tab under Data Tools section.
Or if you want to go with Excel formula then could use-
=DROP(REDUCE(0,A1:INDEX(A1:A50000,COUNTA(A1:A50000)),LAMBDA(a,b,VSTACK(a,TEXTSPLIT(b,"|")))),1)

Little bit simpler approach.
=DROP(REDUCE(0,TOCOL(A:A,1),LAMBDA(a,b,VSTACK(a,TEXTSPLIT(b,"|")))),1)


text:
Q: Error:RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase I got error after running the following script:
-- coding: utf-8 --
Import the Stuff
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils import data
from torch.utils.data import DataLoader
import torchvision.transforms as transforms

import cv2

import numpy as np

import csv

Step1: Read from the log file
samples = []
with open('data/driving_log.csv') as csvfile:
    reader = csv.reader(csvfile)
    next(reader, None)
    for line in reader:
        samples.append(line)

Step2: Divide the data into training set and validation set
train_len = int(0.8*len(samples))
valid_len = len(samples) - train_len
train_samples, validation_samples = data.random_split(samples, lengths=[train_len, valid_len])

Step3a: Define the augmentation, transformation processes, parameters and dataset for dataloader
def augment(imgName, angle):
  name = 'data/IMG/' + imgName.split('/')[-1]
  current_image = cv2.imread(name)
  current_image = current_image[65:-25, :, :]
  if np.random.rand() < 0.5:
    current_image = cv2.flip(current_image, 1)
    angle = angle * -1.0
  return current_image, angle

class Dataset(data.Dataset):

    def __init__(self, samples, transform=None):

        self.samples = samples
        self.transform = transform

    def __getitem__(self, index):

        batch_samples = self.samples[index]

        steering_angle = float(batch_samples[3])

        center_img, steering_angle_center = augment(batch_samples[0], steering_angle)
        left_img, steering_angle_left = augment(batch_samples[1], steering_angle + 0.4)
        right_img, steering_angle_right = augment(batch_samples[2], steering_angle - 0.4)

        center_img = self.transform(center_img)
        left_img = self.transform(left_img)
        right_img = self.transform(right_img)

        return (center_img, steering_angle_center), (left_img, steering_angle_left), (right_img, steering_angle_right)

    def __len__(self):
        return len(self.samples)

Step3b: Creating generator using the dataloader to parallasize the process
def _my_normalization(x):
    return x/255.0 - 0.5
transformations = transforms.Compose([transforms.Lambda(_my_normalization)])

params = {'batch_size': 32,
          'shuffle': True,
          'num_workers': 4}

training_set = Dataset(train_samples, transformations)
training_generator = data.DataLoader(training_set, **params)

validation_set = Dataset(validation_samples, transformations)
validation_generator = data.DataLoader(validation_set, **params)

Step4: Define the network
class NetworkDense(nn.Module):

    def __init__(self):
        super(NetworkDense, self).__init__()
        self.conv_layers = nn.Sequential(
            nn.Conv2d(3, 24, 5, stride=2),
            nn.ELU(),
            nn.Conv2d(24, 36, 5, stride=2),
            nn.ELU(),
            nn.Conv2d(36, 48, 5, stride=2),
            nn.ELU(),
            nn.Conv2d(48, 64, 3),
            nn.ELU(),
            nn.Conv2d(64, 64, 3),
            nn.Dropout(0.25)
        )
        self.linear_layers = nn.Sequential(
            nn.Linear(in_features=64 * 2 * 33, out_features=100),
            nn.ELU(),
            nn.Linear(in_features=100, out_features=50),
            nn.ELU(),
            nn.Linear(in_features=50, out_features=10),
            nn.Linear(in_features=10, out_features=1)
        )

    def forward(self, input):
        input = input.view(input.size(0), 3, 70, 320)
        output = self.conv_layers(input)
        output = output.view(output.size(0), -1)
        output = self.linear_layers(output)
        return output

class NetworkLight(nn.Module):

    def __init__(self):
        super(NetworkLight, self).__init__()
        self.conv_layers = nn.Sequential(
            nn.Conv2d(3, 24, 3, stride=2),
            nn.ELU(),
            nn.Conv2d(24, 48, 3, stride=2),
            nn.MaxPool2d(4, stride=4),
            nn.Dropout(p=0.25)
        )
        self.linear_layers = nn.Sequential(
            nn.Linear(in_features=48*4*19, out_features=50),
            nn.ELU(),
            nn.Linear(in_features=50, out_features=10),
            nn.Linear(in_features=10, out_features=1)
        )

    def forward(self, input):
        input = input.view(input.size(0), 3, 70, 320)
        output = self.conv_layers(input)
        output = output.view(output.size(0), -1)
        output = self.linear_layers(output)
        return output

Step5: Define optimizer
model = NetworkLight()
optimizer = optim.Adam(model.parameters(), lr=0.0001)

criterion = nn.MSELoss()

Step6: Check the device and define function to move tensors to that device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print('device is: ', device)

def toDevice(datas, device):

  imgs, angles = datas
  return imgs.float().to(device), angles.float().to(device)

Step7: Train and validate network based on maximum epochs defined
max_epochs = 22

for epoch in range(max_epochs):

    model.to(device)

    # Training
    train_loss = 0
    model.train()
    for local_batch, (centers, lefts, rights) in enumerate(training_generator):
        # Transfer to GPU
        centers, lefts, rights = toDevice(centers, device), toDevice(lefts, device), toDevice(rights, device)

        # Model computations
        optimizer.zero_grad()
        datas = [centers, lefts, rights]
        for data in datas:
            imgs, angles = data
#             print("training image: ", imgs.shape)
            outputs = model(imgs)
            loss = criterion(outputs, angles.unsqueeze(1))
            loss.backward()
            optimizer.step()

            train_loss += loss.data[0].item()

        if local_batch % 100 == 0:
            print('Loss: %.3f '
                 % (train_loss/(local_batch+1)))

    # Validation
    model.eval()
    valid_loss = 0
    with torch.set_grad_enabled(False):
        for local_batch, (centers, lefts, rights) in enumerate(validation_generator):
            # Transfer to GPU
            centers, lefts, rights = toDevice(centers, device), toDevice(lefts, device), toDevice(rights, device)

            # Model computations
            optimizer.zero_grad()
            datas = [centers, lefts, rights]
            for data in datas:
                imgs, angles = data
#                 print("Validation image: ", imgs.shape)
                outputs = model(imgs)
                loss = criterion(outputs, angles.unsqueeze(1))

                valid_loss += loss.data[0].item()

            if local_batch % 100 == 0:
                print('Valid Loss: %.3f '
                     % (valid_loss/(local_batch+1)))

Step8: Define state and save the model wrt to state
state = {
        'model': model.module if device == 'cuda' else model,
        }

torch.save(state, 'model.h5')

This the error message:
"D:\VICO\Back up\venv\Scripts\python.exe" "D:/VICO/Back up/venv/Scripts/self_driving_car.py"
device is:  cpu
device is:  cpu
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\isonata\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 105, in spawn_main
exitcode = _main(fd)
File "C:\Users\isonata\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 114, in _main
prepare(preparation_data)
File "C:\Users\isonata\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 225, in prepare
_fixup_main_from_path(data['init_main_from_path'])
File "C:\Users\isonata\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 277, in _fixup_main_from_path
run_name="mp_main")
File "C:\Users\isonata\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 263, in run_path
Traceback (most recent call last):
File "D:/VICO/Back up/venv/Scripts/self_driving_car.py", line 165, in
pkg_name=pkg_name, script_name=fname)
File "C:\Users\isonata\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 96, in _run_module_code
for local_batch, (centers, lefts, rights) in enumerate(training_generator):
File "D:\VICO\Back up\venv\lib\site-packages\torch\utils\data\dataloader.py", line 291, in iter
mod_name, mod_spec, pkg_name, script_name)
File "C:\Users\isonata\AppData\Local\Programs\Python\Python37\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "D:\VICO\Back up\venv\Scripts\self_driving_car.py", line 165, in
return _MultiProcessingDataLoaderIter(self)
File "D:\VICO\Back up\venv\lib\site-packages\torch\utils\data\dataloader.py", line 737, in init
for local_batch, (centers, lefts, rights) in enumerate(training_generator):
File "D:\VICO\Back up\venv\lib\site-packages\torch\utils\data\dataloader.py", line 291, in iter
return _MultiProcessingDataLoaderIter(self)
File "D:\VICO\Back up\venv\lib\site-packages\torch\utils\data\dataloader.py", line 737, in init
w.start()
File "C:\Users\isonata\AppData\Local\Programs\Python\Python37\lib\multiprocessing\process.py", line 112, in start
self._popen = self._Popen(self)
File "C:\Users\isonata\AppData\Local\Programs\Python\Python37\lib\multiprocessing\context.py", line 223, in _Popen
w.start()
File "C:\Users\isonata\AppData\Local\Programs\Python\Python37\lib\multiprocessing\process.py", line 112, in start
return _default_context.get_context().Process._Popen(process_obj)
File "C:\Users\isonata\AppData\Local\Programs\Python\Python37\lib\multiprocessing\context.py", line 322, in _Popen
self._popen = self._Popen(self)
File "C:\Users\isonata\AppData\Local\Programs\Python\Python37\lib\multiprocessing\context.py", line 223, in _Popen
return Popen(process_obj)
File "C:\Users\isonata\AppData\Local\Programs\Python\Python37\lib\multiprocessing\popen_spawn_win32.py", line 89, in init
return _default_context.get_context().Process._Popen(process_obj)
File "C:\Users\isonata\AppData\Local\Programs\Python\Python37\lib\multiprocessing\context.py", line 322, in _Popen
reduction.dump(process_obj, to_child)
File "C:\Users\isonata\AppData\Local\Programs\Python\Python37\lib\multiprocessing\reduction.py", line 60, in dump
return Popen(process_obj)
File "C:\Users\isonata\AppData\Local\Programs\Python\Python37\lib\multiprocessing\popen_spawn_win32.py", line 46, in init
ForkingPickler(file, protocol).dump(obj)
BrokenPipeError: [Errno 32] Broken pipe
prep_data = spawn.get_preparation_data(process_obj._name)
File "C:\Users\isonata\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 143, in get_preparation_data
_check_not_importing_main()
File "C:\Users\isonata\AppData\Local\Programs\Python\Python37\lib\multiprocessing\spawn.py", line 136, in _check_not_importing_main
is not going to be frozen to produce an executable.''')
RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
    This probably means that you are not using fork to start your
    child processes and you have forgotten to use the proper idiom
    in the main module:

        if __name__ == '__main__':
            freeze_support()
            ...

    The "freeze_support()" line can be omitted if the program
    is not going to be frozen to produce an executable.

Process finished with exit code 1
I am not sure the next step for solving the problem

A: Solved, simply put :
if __name__ == "__main__":
        main()

To avoiid reloading the modul every loop.

A: I had similar issue and fixed it by setting 'num_workers' parameter in DataLoader back to zero:
DataLoader(num_workers=0)


text:
Q: Multiple forms for entity instances - symfony3 I'm trying to create a form that would allow a manager to approve a list of time off requests (also planning to have a todo list and want to be able to mark them as done).
I have read [Generate same form type on same page multiple times Symfony2 (as well as several others) and I am close to understanding but I'm fairly to new to Symfony and not clear on what parts of the code should go in what files. I am using a form type and a controller in Symfony3 with Doctrine.
I have list of the entity instances that were returned from a query ($em->createQuery) in the controller and I am looking to produce a form for each entity instance or even two forms per entity (one for approve and one for reject).
The referenced question says you need a loop to display and save them. My intention is to only work on (submit) one at a time. I assume this part of the code would go in the controller?
I am using an indexAction for the controller but using it more like an Edit action since I will be processing forms, so I pass in a Request object and the objects as parameters.
>
class HRMgrController extends Controller
{
    /**
     * Lists all manager role requests and provide a means to approve/deny.
     *
     * @Route("/", name="hrmgr_index")
     * @Method({"GET", "POST"})
     * @Security("has_role('ROLE_APP_MANAGER')")
     */
public function indexAction(Request $request, TimeOffRequest $timeOffRequest)
{
    if (!empty($timeOffRequest)) {
            $form = $this->createForm('CockpitBundle\Form\TORApprovalType', $timeOffRequest);
        print "TOR Id = " . $timeOffRequest->getId() . "
";
        $em = $this->getDoctrine()->getManager();
        $form->handleRequest($request);
        print "Form name = " . $form->getName() . "
";
        if ($form->isSubmitted() && $form->isValid()) {
            if ($form->get('approve')->isClicked()) {
                print "This puppy was approved";
                $timeOffRequest['status'] = 4;
            }
            if ($form->get('reject')->isClicked()) {
                print "This puppy was rejected";
                $timeOffRequest['status'] = 1;
            }
            $this->getDoctrine()->getManager()->flush();
            print "At least its there
";
            // return $this->redirectToRoute('hrmgr_index');
        } else {
            print "did not detect form submission
";
        }
    }

    $emp = new \CockpitBundle\Entity\Employee();

    $date = new \DateTime();
    $year = $date->format('Y');
    $username = $this->getUser()->getUserName();
    $user = $em->getRepository('CockpitBundle:Employee')->findByUsername($username);
    $employees = $em->getRepository('CockpitBundle:Employee')->htmlContact($user);
    $tors = $em->getRepository('CockpitBundle:TimeOffRequest')->findMgrUnapprovedTORs($user->getId());
    $timeoff = "
Unapproved Time Off Requests
";
    $actions = true;

    $torforms = [];
    foreach ($tors as $tor) {
        $target = $this->generateUrl('hrmgr_index',array("tor_id" => $tor->getId()));
        $torforms[] = $this->actionForm($tor,$target)->createView();
    }
    return $this->render('hrmgr/index.html.twig', array(
        'torforms' => $torforms,
    ));

I have the forms working nowbut when I submit them the isSubmitted() doesn't seem to be working. It outputs the "did not detect form submission" currently.
So when I have multiple forms and I submit one, does the handleRequest get the right one? I think I might be confusing two concepts here as well. I recently changed the code to submit the ID of the timeOffRequest as a parameter to the route. It is properly picking that up which allows me to potentially update the form but that part of the code doesn't seem to be working.
I noticed that if I look at the debugger, I get something like:
>   approval_form_2
   [▼
     "reject" => ""
     "_token" => "IE1rGa5c0vaJYk74_ncxgFsoDU7wWlkAAWWjLe3Jr1w"
   ]

if I click the reject button. I get a similar form with "approve" if I click the approve button so it seems like I am close. Also, the proper ID shows up from the route given in the action.
Here is the form generator:
<?php

namespace CockpitBundle\Form;

use CockpitBundle\Entity\Employee;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\ButtonType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class TORApprovalType extends AbstractType
{

    private $nameSuffix = null;
    private $name = 'time_req_approval';
    public function __constructor(string $suffix = null)   {
        //parent::__construct();

        $this->nameSuffix = $this->generateNameSuffix();
    }

    private function generateNameSuffix() {
        if ($this->nameSuffix == null ||  $this->nameSuffix == '') {
            $generator = new SecureRandom();
            //change data to alphanumeric string
            return bin2hex($generator->nextBytes(10));
        }

        return $this->nameSuffix;
    }
    public function setNameSuffix($suffix){
        $this->nameSuffix = $suffix;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // Build your form...
        $builder->add('approve', SubmitType::class, array(
            'label' => "Approve",
            'attr' => array("class"=>"action-approve"),
        ));
        $builder->add('reject', SubmitType::class, array(
            'label' => "Reject",
            'attr' => array("class"=>"action-reject"),
        ));
        //$builder->add('employee');

    }
    public function getName()    {
        if ($this->nameSuffix == null || $this->nameSuffix == "" ) {
            $this->nameSuffix = $this->generateNameSuffix();
        }
        return $this->name .'_'. $this->nameSuffix;
    }
    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'CockpitBundle\Entity\TimeOffRequest'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'cockpitbundle_timeoffrequest';
    }

}

Any clues? (sorry I am on vacation so not particular quick with updates.

A: You can do multiple submit button: check your formtype
    ->add('approve', 'submit')
    ->add('reject', 'submit')

then in your controller
 if ($form->isValid()) {
        // ... do something

        // the save_and_add button was clicked
        if ($form->get('approve')->isClicked()) {
            // probably redirect to the add page again
        }
        if ($form->get('reject')->isClicked()) {
            // probably redirect to the add page again
        }

        // redirect to the show page for the just submitted item
    }

A: I was able to get it working with the following builder.
   $builder->add('approve', SubmitType::class, array(
        'label' => "Approve",
        'attr' => array("class"=>"action-approve"),
    ));
    $builder->add('reject', SubmitType::class, array(
        'label' => "Reject",
        'attr' => array("class"=>"action-reject"),
    ));

Then in the controller form I generate and process the forms as such. Not sure if it is the optimal way but it works find. Of course, this approach redraws the whole list each time, but that is fine for what I'm doing.
class HRMgrController extends Controller
{
    /**
     * Lists all manager role requests and provide a means to approve/deny.
     *
     * @Route("/", name="manager_home")
     * @Method({"GET"})
     * @Security("has_role('ROLE_APP_MANAGER')")
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();
        $emp = new \CockpitBundle\Entity\Employee();
        $employeeSummary = [];
        $date = new \DateTime();
        $year = $date->format('Y');
        $username = $this->getUser()->getUserName();
        $user = $em->getRepository('CockpitBundle:Employee')->findByUsername($username);
        $myemployees = $em->getRepository('CockpitBundle:Employee')->findManagersEmployees($user);
        $torRep = $em->getRepository('CockpitBundle:TimeOffRequest');
        $toas = [];
        $torforms = [];
        foreach ($myemployees as $employee) {
            $tors = $torRep->findAllMine($employee,$year);
            $toas[$employee->getDisplayName()] = $em->getRepository('CockpitBundle:TimeOffAllocation')->getEmpAllocation($employee->getId(),$year);
            $employeeSummary[$employee->getDisplayName()] = $torRep->mySummary($tors,$toas[$employee->getDisplayName()]);
            if (array_key_exists('items',$employeeSummary[$employee->getDisplayName()]['Vacation']['Requested'])) {
                foreach ($employeeSummary[$employee->getDisplayName()]['Vacation']['Requested']['items'] as $tor) {
                    $target = $this->generateUrl('hrmgr_tor_approval',array("tor_id" => $tor->getId()));
                    $torforms[] = $this->actionForm($tor,$target)->createView();
                }
            }
            if (array_key_exists('items',$employeeSummary[$employee->getDisplayName()]['Sick Time']['Requested'])) {
                foreach ($employeeSummary[$employee->getDisplayName()]['Sick Time']['Requested']['items'] as $tor) {
                    $target = $this->generateUrl('hrmgr_tor_approval',array("tor_id" => $tor->getId()));
                    $torforms[] = $this->actionForm($tor,$target)->createView();
                }
            }
            if (array_key_exists('Time Off',$employeeSummary[$employee->getDisplayName()]) &&
                    array_key_exists('items',$employeeSummary[$employee->getDisplayName()]['Time Off']['Requested'])) {
                foreach ($employeeSummary[$employee->getDisplayName()]['Time Off']['Requested']['items'] as $tor) {
                    $target = $this->generateUrl('hrmgr_tor_approval',array("tor_id" => $tor->getId()));
                    $torforms[] = $this->actionForm($tor,$target)->createView();
                }
            }
        }

        return $this->render('hrmgr/index.html.twig', array(
            'employeeSummary' => $employeeSummary,
            'torforms' => $torforms,
            'year' => $year,
        ));
    }
    /**
     * Lists all manager role requests and provide a means to approve/deny.
     *
     * @Route("/{tor_id}", name="hrmgr_tor_approval")
     * @Method({ "POST" })
     * @ParamConverter("timeOffRequest", class="CockpitBundle:TimeOffRequest", options={"id"="tor_id"})
     * @Security("has_role('ROLE_APP_MANAGER')")
     */
    public function approvalAction(Request $request, TimeOffRequest $timeOffRequest)
    {
        if (!empty($timeOffRequest)) {
            $form = $this->createForm('CockpitBundle\Form\TORApprovalType', $timeOffRequest);
            $id = $timeOffRequest->getId();
            $em = $this->getDoctrine()->getManager();
            $form->handleRequest($request);
            $postparams = $request->request->all();

            if (array_key_exists("approval_form_$id",$postparams)) {
                // Form was submitted
                if (array_key_exists("approve",$postparams["approval_form_$id"])) {
                    $status = $em->getReference('CockpitBundle\Entity\TimeOffStatus', 4);
                    $timeOffRequest->setStatus($status);
                    $timeOffRequest->setApprovedDate(new \DateTime);
                    $em->persist($timeOffRequest);
                    $em->flush($timeOffRequest);
                }
                if (array_key_exists("reject",$postparams["approval_form_$id"])) {
                    $status = $em->getReference('CockpitBundle\Entity\TimeOffStatus', 1);
                    $timeOffRequest->setStatus($status);
                    $timeOffRequest->setApprovedDate(new \DateTime);
                    $em->persist($timeOffRequest);
                    $em->flush($timeOffRequest);
                }
            } else {
                print "Form did not exist
";
            }
            return $this->redirectToRoute('manager_home');
        }
    }
    public function actionForm($tor,$target) {
        return $this->get('form.factory')->createNamedBuilder('approval_form_'.$tor->getId(), \CockpitBundle\Form\TORApprovalType::class, $tor,
             array("action"=> $target))->getForm();
    }
}


text:
Q: Erlang: supervisor:terminate_child return error even in latest version I'm trying to use a supervisor with simple_one_for_one RestartStrategy, and I think I have the latest version of Erlang, but still when I try to execute supervisor:terminate_child it ends up with {error,simple_one_for_one}. According to this answer, it should work if my Erlang is version is greater than R14B03 but I can't seem to find the version starting with 'R' anywhere. When I try erlang:system_info(otp_release) in the Erlang shell, it return with "24", which I think is the latest version released in May 2021, but I could see no other reason for this issue. Here is how my supervisor looks:
-module(a_sup).
-behaviour(supervisor).

%% API
-export([start_link/0, init/1]).

start_link() ->
  {ok, supervisor:start_link({local,?MODULE}, ?MODULE, [])}.

init(_Args) ->
  RestartStrategy = {simple_one_for_one, 5, 3600},
  ChildSpec = {
    a_gen_server,
    {a_gen_server, start_link, []},
    permanent,
    brutal_kill,
    worker,
    [a_gen_server]
  },
  {ok, {RestartStrategy,[ChildSpec]}}.

A: You don't show your code for terminating a child, but are you indicating the child to terminate using an identifier instead of a pid? The terminate_child/2 documentation says:

If the supervisor is simple_one_for_one, Id must be the pid() of the
child process. If the specified process is alive, but is not a child
of the specified supervisor, the function returns {error,not_found}.
If the child specification identifier is specified instead of a pid(),
the function returns {error,simple_one_for_one}.

Regarding the version issue: 24.2 is the current Erlang/OTP version at the time of this writing. Version numbers used to start with 'R' but that ended at Erlang/OTP 17.0.


text:
Q: How to POST key/value pairs instead of a JSON Object using Spring for Android? I am trying to use Spring for Android to do a standard HTTP POST to a url where the body of is just a list of parameters (like key-value pairs) and not a JSON object.
I would like the response to be converted from JSON to the Java ResponseObject, but from what I can tell, Spring is also converting my body into JSON as well.
Here is my code:
Map<String, Object> params = new HashMap<String, Object>();
    params.put("client_id", mClientId);
    params.put("state", mState);
    params.put("username", mUsername);
    params.put("password", mPassword);
    return getRestTemplate().postForObject(url, params, ResponseObject.class);

Thank you in advance!

A: Try this
posting simple name value pair list
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name", nameString));
nameValuePairs.add(new BasicNameValuePair("Country", "country name"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
}catch (ClientProtocolException e) {
 // TODO Auto-generated catch block
}

A: Use .exchange()
// Create the request body as a MultiValueMap
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();

body.add("client_id", mClientId); // and so on

// Note the body object as first parameter!
HttpEntity<?> httpEntity = new HttpEntity<Object>(body, requestHeaders);

MyModel model = restTemplate.exchange("/api/url", HttpMethod.POST, httpEntity, MyModel.class);


text:
Q: Two arrays: if a key in the first array is empty, set the same key in the second array to be empty? I have this array that has two $rows:

I'd like the second array's display to be based on the first array but I don't think I have it set up properly:
$rows = &$vars['rows'];
foreach ($rows[0] as $key => $value) {
  if (strpos($key, 'views') === 0 && empty($value)) {
        $rows[1][$key] = '';
        unset($vars['header'][$key]);
  }
}

This is the output from the code, you can see the table doesn't seem aligned properly:

A: You need to loop over the whole array and then loop over the inner data as well. Simply you need two foreach loops.
$rows = $vars;
foreach ($rows as $occ => $outer ) {
    foreach ($outer as $key => $value) {
        if (strpos($key, 'views') === 0 && $value =='') {
            unset($vars[$occ][$key]);
        }
    }
}


text:
Q: Performance Issue when using LazyVGrid I have a very simple app: 4,000 images(400x400 in .jpg) that need to display 3 in a row. All images a stored in file storage and are equal 1/3 of device width so I don't need to resize/rescale it but display as is.
Here is a body code:
var body: some View {
    ScrollView {
        LazyVGrid(columns: Array(repeating: GridItem(.fixed(size), spacing: 1), count: 3),
                  alignment: .center,
                  spacing: 0) {
            ForEach(controller.newAlbums, id: \.self) { album in
                PhotoThumbnailView(filePath: album)
            }
        }
    }
    .task {
        controller.loadUserAlbums()
    }
}

let size = UIScreen.main.bounds.width/3

struct PhotoThumbnailView: View {
    @State private var image: Image?
    @State private var imageFileURL: String

    init(filePath: String) {
        self.imageFileURL = filePath
    }

    func readFromFile(){
        if let uiImage = UIImage(contentsOfFile: imageFileURL) {
            self.image = Image(uiImage: uiImage)
        }
    }

    var body: some View {
        ZStack {
            if let img = image {
                img
            } else {
                Rectangle()
                    .foregroundColor(.clear)
                    .frame(width: size, height: size)
                ProgressView()
            }
        }
        .task({
            readFromFile()
        })
        .onDisappear {
            image = nil
        }
    }
}

The problem is that when I scroll down (even vary slowly) it lagging and the scrolling animation is not smooth. How to resolve the issue above?


text:
Q: How do I impute missing variables in R using dplyr? I would like to impute missing values for a variable given the existing values.
In var2, we notice that there are a lot of NAs.

*

*If any 2 ids are the same, then their values for var2 are the same.

*If the id has no values for var2, like in the case of id==2, then we just output as NA.

It should look from df_old to df_new.
 df_old<- read.table(header = TRUE, text = "
 id  var1  var2
  1  A       12
  1  B       NA
  1  E       NA
  2  G       NA
  2  J       NA
 ")

df_new<- read.table(header = TRUE, text = "
id  var1  var2
 1  A       12
 1  B       12
 1  E       12
 2  G       NA
 2  J       NA
")

I tried take:
df_new<-df_old %>%
        group_by(id) %>%
        mutate(var2=na.omit(var2))

I believe it doesn't work because of the second case. I was also wondering if using ifelse would be okay. Need help thanks!

A: If there is only one var2 value per id available you could simply do:
df_old %>%
  group_by(id) %>%
  mutate(var2 = min(var2, na.rm = TRUE))

Source: local data frame [5 x 3]
Groups: id [2]

     id   var1  var2
  <int> <fctr> <int>
1     1      A    12
2     1      B    12
3     1      E    12
4     2      G    NA
5     2      J    NA

Another option would be:
mutate(var2 = var2[1])

A: We can use data.table, but unlike dplyr, for groups that have all NA, we have to specify NA to return or else it will give Inf
library(data.table)
setDT(df_old)[, var2 := if(any(!is.na(var2))) min(var2, na.rm = TRUE)
            else NA_integer_, by = id]
df_old
#    id var1 var2
#1:  1    A   12
#2:  1    B   12
#3:  1    E   12
#4:  2    G   NA
#5:  2    J   NA

A: By now there is tidyimpute package available in CRAN which looks like it might do the trick
"Functions and methods for imputing missing values (NA) in tables and list
patterned after the tidyverse approach of 'dplyr' and 'rlang'; works with
data.tables as well."
https://cran.r-project.org/web/packages/tidyimpute/tidyimpute.pdf


text:
Q: "no path found" error when pushing to a remote git repository I have been trying to push my first project to github, but no success whatsoever. I have two errors:

*

*When I specify the path of the folder (cd Desktop/folder), I get yhe message:no path found. The name is correct, so how can I overcome this? Also,I am not sure how critical this error is.

*Following the steps in the github tutorial on the freecodecamp website, after push command I get the error: everything is up to date but,in fact, no changes are done to the repository and nothing is uploaded.
I appreciate clear answers because I am not too technical myself and this is my first project to upload.
Many thanks!

A: please find below link which will help you from the very beginning how all process done you will know through conceptually
https://product.hubspot.com/blog/git-and-github-tutorial-for-beginners


text:
Q: MSBuild error - Program does not contain a static 'Main' method suitable for an entry point I have a visual studio solution containing some class library projects and a windows service project.
I am trying to build it using the following msbuild command:
MSBuild SolutionName.sln /t:rebuild /p:Configuration=Release;OutputType=Winexe /clp:ErrorsOnly

However, I am getting the following error:

CSC : error CS5001: Program does not contain a static 'Main' method
  suitable for an entry point [C:..\BusinessObjects.csproj]

Somehow it tries to find an entry point inside a class library project instead of using the windows service project.
I believe if I try to build WindowsService.csproj instead of .sln file then it may fix the issue. However, WindowsService.CsProj does not contain all other dll references so I have to build .sln file.
Is there any other way I can fix this error?

A:
I believe if I try to build WindowsService.csproj instead of .sln file
  then it may fix the issue. However, WindowsService.CsProj does not
  contain all other dll references so I have to build .sln file.
Is there any other way I can fix this error?

Since your just build the whole solution with msbuild command line , it means that the parameters from your command line apply to all projects in the solution.
As your description, you have some class library projects in your solution which does not contains a static Main method, So it cannot be specified as a Windows application.
Projects in VS have three output types: Console Application and Windows Application contains a static Main function while Class Library Application does not contain it.
Conclusion
If you build a whole solution with the command line, you should make sure that all the parameters from the command line apply to all projects.
When you build a single project Windows Service project, just make sure the current project has a static main function and it actually has.
Solution
1) Since your solution contains only one winexe project and other class library projects, please delete OutputType=Winexe in the command line.
MSBuild SolutionName.sln /t:rebuild /p:Configuration=Release /clp:ErrorsOnly

Hope it could help you.


text:
Q: batch renormalization layer keras I am having problems loading the weights of a trained model in Keras, which consists in the layers provided in the following scheme:
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
input_1 (InputLayer)            [(None, 12, 86, 98,  0
__________________________________________________________________________________________________
zero_padding3d (ZeroPadding3D)  (None, 12, 96, 112,  0           input_1[0][0]
__________________________________________________________________________________________________
conv3d (Conv3D)                 (None, 12, 96, 112,  448         zero_padding3d[0][0]
__________________________________________________________________________________________________
add (Add)                       (None, 12, 96, 112,  0           zero_padding3d[0][0]
                                                                 conv3d[0][0]
__________________________________________________________________________________________________
conv3d_1 (Conv3D)               (None, 12, 48, 56, 3 4128        add[0][0]
__________________________________________________________________________________________________
batch_normalization (BatchNorma (None, 12, 48, 56, 3 224         conv3d_1[0][0]
__________________________________________________________________________________________________
conv3d_2 (Conv3D)               (None, 12, 48, 56, 3 27680       batch_normalization[0][0]
__________________________________________________________________________________________________
batch_normalization_1 (BatchNor (None, 12, 48, 56, 3 224         conv3d_2[0][0]
__________________________________________________________________________________________________
conv3d_3 (Conv3D)               (None, 12, 48, 56, 3 27680       batch_normalization_1[0][0]
__________________________________________________________________________________________________
batch_normalization_2 (BatchNor (None, 12, 48, 56, 3 224         conv3d_3[0][0]
__________________________________________________________________________________________________
conv3d_4 (Conv3D)               (None, 12, 48, 56, 3 27680       batch_normalization_2[0][0]
__________________________________________________________________________________________________
batch_normalization_3 (BatchNor (None, 12, 48, 56, 3 224         conv3d_4[0][0]
__________________________________________________________________________________________________
conv3d_5 (Conv3D)               (None, 12, 48, 56, 3 27680       batch_normalization_3[0][0]
__________________________________________________________________________________________________
batch_normalization_4 (BatchNor (None, 12, 48, 56, 3 224         conv3d_5[0][0]
__________________________________________________________________________________________________
conv3d_6 (Conv3D)               (None, 12, 48, 56, 3 27680       batch_normalization_4[0][0]
__________________________________________________________________________________________________
batch_normalization_5 (BatchNor (None, 12, 48, 56, 3 224         conv3d_6[0][0]
__________________________________________________________________________________________________
conv3d_7 (Conv3D)               (None, 12, 48, 56, 3 27680       batch_normalization_5[0][0]
__________________________________________________________________________________________________
batch_normalization_6 (BatchNor (None, 12, 48, 56, 3 224         conv3d_7[0][0]
__________________________________________________________________________________________________
add_1 (Add)                     (None, 12, 48, 56, 3 0           batch_normalization_6[0][0]
                                                                 batch_normalization[0][0]
__________________________________________________________________________________________________
conv3d_8 (Conv3D)               (None, 12, 24, 28, 6 16448       add_1[0][0]
__________________________________________________________________________________________________
batch_normalization_7 (BatchNor (None, 12, 24, 28, 6 448         conv3d_8[0][0]
__________________________________________________________________________________________________
conv3d_9 (Conv3D)               (None, 12, 24, 28, 6 110656      batch_normalization_7[0][0]
__________________________________________________________________________________________________
batch_normalization_8 (BatchNor (None, 12, 24, 28, 6 448         conv3d_9[0][0]
__________________________________________________________________________________________________
conv3d_10 (Conv3D)              (None, 12, 24, 28, 6 110656      batch_normalization_8[0][0]
__________________________________________________________________________________________________
batch_normalization_9 (BatchNor (None, 12, 24, 28, 6 448         conv3d_10[0][0]
__________________________________________________________________________________________________
conv3d_11 (Conv3D)              (None, 12, 24, 28, 6 110656      batch_normalization_9[0][0]
__________________________________________________________________________________________________
batch_normalization_10 (BatchNo (None, 12, 24, 28, 6 448         conv3d_11[0][0]
__________________________________________________________________________________________________
conv3d_12 (Conv3D)              (None, 12, 24, 28, 6 110656      batch_normalization_10[0][0]
__________________________________________________________________________________________________
batch_normalization_11 (BatchNo (None, 12, 24, 28, 6 448         conv3d_12[0][0]
__________________________________________________________________________________________________
conv3d_13 (Conv3D)              (None, 12, 24, 28, 6 110656      batch_normalization_11[0][0]
__________________________________________________________________________________________________
batch_normalization_12 (BatchNo (None, 12, 24, 28, 6 448         conv3d_13[0][0]
__________________________________________________________________________________________________
conv3d_14 (Conv3D)              (None, 12, 24, 28, 6 110656      batch_normalization_12[0][0]
__________________________________________________________________________________________________
batch_normalization_13 (BatchNo (None, 12, 24, 28, 6 448         conv3d_14[0][0]
__________________________________________________________________________________________________
add_2 (Add)                     (None, 12, 24, 28, 6 0           batch_normalization_13[0][0]
                                                                 batch_normalization_7[0][0]
__________________________________________________________________________________________________
conv3d_15 (Conv3D)              (None, 12, 12, 14, 1 65664       add_2[0][0]
__________________________________________________________________________________________________
batch_normalization_14 (BatchNo (None, 12, 12, 14, 1 896         conv3d_15[0][0]
__________________________________________________________________________________________________
conv3d_16 (Conv3D)              (None, 12, 12, 14, 1 442496      batch_normalization_14[0][0]
__________________________________________________________________________________________________
batch_normalization_15 (BatchNo (None, 12, 12, 14, 1 896         conv3d_16[0][0]
__________________________________________________________________________________________________
conv3d_17 (Conv3D)              (None, 12, 12, 14, 1 442496      batch_normalization_15[0][0]
__________________________________________________________________________________________________
batch_normalization_16 (BatchNo (None, 12, 12, 14, 1 896         conv3d_17[0][0]
__________________________________________________________________________________________________
conv3d_18 (Conv3D)              (None, 12, 12, 14, 1 442496      batch_normalization_16[0][0]
__________________________________________________________________________________________________
batch_normalization_17 (BatchNo (None, 12, 12, 14, 1 896         conv3d_18[0][0]
__________________________________________________________________________________________________
conv3d_19 (Conv3D)              (None, 12, 12, 14, 1 442496      batch_normalization_17[0][0]
__________________________________________________________________________________________________
batch_normalization_18 (BatchNo (None, 12, 12, 14, 1 896         conv3d_19[0][0]
__________________________________________________________________________________________________
conv3d_20 (Conv3D)              (None, 12, 12, 14, 1 442496      batch_normalization_18[0][0]
__________________________________________________________________________________________________
batch_normalization_19 (BatchNo (None, 12, 12, 14, 1 896         conv3d_20[0][0]
__________________________________________________________________________________________________
conv3d_21 (Conv3D)              (None, 12, 12, 14, 1 442496      batch_normalization_19[0][0]
__________________________________________________________________________________________________
batch_normalization_20 (BatchNo (None, 12, 12, 14, 1 896         conv3d_21[0][0]
__________________________________________________________________________________________________
add_3 (Add)                     (None, 12, 12, 14, 1 0           batch_normalization_20[0][0]
                                                                 batch_normalization_14[0][0]
__________________________________________________________________________________________________
conv3d_22 (Conv3D)              (None, 12, 6, 7, 256 262400      add_3[0][0]
__________________________________________________________________________________________________
batch_normalization_21 (BatchNo (None, 12, 6, 7, 256 1792        conv3d_22[0][0]
__________________________________________________________________________________________________
conv3d_23 (Conv3D)              (None, 12, 6, 7, 256 65792       batch_normalization_21[0][0]
__________________________________________________________________________________________________
conv3d_24 (Conv3D)              (None, 12, 6, 7, 256 65792       conv3d_23[0][0]
__________________________________________________________________________________________________
conv3d_25 (Conv3D)              (None, 12, 6, 7, 256 65792       conv3d_24[0][0]
__________________________________________________________________________________________________
conv3d_26 (Conv3D)              (None, 12, 6, 7, 256 65792       conv3d_25[0][0]
__________________________________________________________________________________________________
conv3d_27 (Conv3D)              (None, 12, 6, 7, 256 65792       conv3d_26[0][0]
__________________________________________________________________________________________________
conv3d_28 (Conv3D)              (None, 12, 6, 7, 256 65792       conv3d_27[0][0]
__________________________________________________________________________________________________
add_4 (Add)                     (None, 12, 6, 7, 256 0           conv3d_28[0][0]
                                                                 batch_normalization_21[0][0]
__________________________________________________________________________________________________
conv3d_transpose (Conv3DTranspo (None, 12, 12, 14, 2 262400      add_4[0][0]
__________________________________________________________________________________________________
concatenate (Concatenate)       (None, 12, 12, 14, 3 0           conv3d_transpose[0][0]
                                                                 add_3[0][0]
__________________________________________________________________________________________________
conv3d_29 (Conv3D)              (None, 12, 12, 14, 2 2654464     concatenate[0][0]
__________________________________________________________________________________________________
batch_normalization_22 (BatchNo (None, 12, 12, 14, 2 1792        conv3d_29[0][0]
__________________________________________________________________________________________________
conv3d_30 (Conv3D)              (None, 12, 12, 14, 2 1769728     batch_normalization_22[0][0]
__________________________________________________________________________________________________
batch_normalization_23 (BatchNo (None, 12, 12, 14, 2 1792        conv3d_30[0][0]
__________________________________________________________________________________________________
conv3d_31 (Conv3D)              (None, 12, 12, 14, 2 1769728     batch_normalization_23[0][0]
__________________________________________________________________________________________________
batch_normalization_24 (BatchNo (None, 12, 12, 14, 2 1792        conv3d_31[0][0]
__________________________________________________________________________________________________
conv3d_32 (Conv3D)              (None, 12, 12, 14, 2 1769728     batch_normalization_24[0][0]
__________________________________________________________________________________________________
batch_normalization_25 (BatchNo (None, 12, 12, 14, 2 1792        conv3d_32[0][0]
__________________________________________________________________________________________________
conv3d_33 (Conv3D)              (None, 12, 12, 14, 2 1769728     batch_normalization_25[0][0]
__________________________________________________________________________________________________
batch_normalization_26 (BatchNo (None, 12, 12, 14, 2 1792        conv3d_33[0][0]
__________________________________________________________________________________________________
conv3d_34 (Conv3D)              (None, 12, 12, 14, 2 1769728     batch_normalization_26[0][0]
__________________________________________________________________________________________________
batch_normalization_27 (BatchNo (None, 12, 12, 14, 2 1792        conv3d_34[0][0]
__________________________________________________________________________________________________
add_5 (Add)                     (None, 12, 12, 14, 2 0           batch_normalization_27[0][0]
                                                                 conv3d_transpose[0][0]
__________________________________________________________________________________________________
conv3d_transpose_1 (Conv3DTrans (None, 12, 24, 28, 1 131200      add_5[0][0]
__________________________________________________________________________________________________
concatenate_1 (Concatenate)     (None, 12, 24, 28, 1 0           conv3d_transpose_1[0][0]
                                                                 add_2[0][0]
__________________________________________________________________________________________________
conv3d_35 (Conv3D)              (None, 12, 24, 28, 1 663680      concatenate_1[0][0]
__________________________________________________________________________________________________
batch_normalization_28 (BatchNo (None, 12, 24, 28, 1 896         conv3d_35[0][0]
__________________________________________________________________________________________________
conv3d_36 (Conv3D)              (None, 12, 24, 28, 1 442496      batch_normalization_28[0][0]
__________________________________________________________________________________________________
batch_normalization_29 (BatchNo (None, 12, 24, 28, 1 896         conv3d_36[0][0]
__________________________________________________________________________________________________
conv3d_37 (Conv3D)              (None, 12, 24, 28, 1 442496      batch_normalization_29[0][0]
__________________________________________________________________________________________________
batch_normalization_30 (BatchNo (None, 12, 24, 28, 1 896         conv3d_37[0][0]
__________________________________________________________________________________________________
conv3d_38 (Conv3D)              (None, 12, 24, 28, 1 442496      batch_normalization_30[0][0]
__________________________________________________________________________________________________
batch_normalization_31 (BatchNo (None, 12, 24, 28, 1 896         conv3d_38[0][0]
__________________________________________________________________________________________________
conv3d_39 (Conv3D)              (None, 12, 24, 28, 1 442496      batch_normalization_31[0][0]
__________________________________________________________________________________________________
batch_normalization_32 (BatchNo (None, 12, 24, 28, 1 896         conv3d_39[0][0]
__________________________________________________________________________________________________
conv3d_40 (Conv3D)              (None, 12, 24, 28, 1 442496      batch_normalization_32[0][0]
__________________________________________________________________________________________________
batch_normalization_33 (BatchNo (None, 12, 24, 28, 1 896         conv3d_40[0][0]
__________________________________________________________________________________________________
add_6 (Add)                     (None, 12, 24, 28, 1 0           batch_normalization_33[0][0]
                                                                 conv3d_transpose_1[0][0]
__________________________________________________________________________________________________
conv3d_transpose_2 (Conv3DTrans (None, 12, 48, 56, 6 32832       add_6[0][0]
__________________________________________________________________________________________________
concatenate_2 (Concatenate)     (None, 12, 48, 56, 9 0           conv3d_transpose_2[0][0]
                                                                 add_1[0][0]
__________________________________________________________________________________________________
conv3d_41 (Conv3D)              (None, 12, 48, 56, 6 165952      concatenate_2[0][0]
__________________________________________________________________________________________________
batch_normalization_34 (BatchNo (None, 12, 48, 56, 6 448         conv3d_41[0][0]
__________________________________________________________________________________________________
conv3d_42 (Conv3D)              (None, 12, 48, 56, 6 110656      batch_normalization_34[0][0]
__________________________________________________________________________________________________
batch_normalization_35 (BatchNo (None, 12, 48, 56, 6 448         conv3d_42[0][0]
__________________________________________________________________________________________________
conv3d_43 (Conv3D)              (None, 12, 48, 56, 6 110656      batch_normalization_35[0][0]
__________________________________________________________________________________________________
batch_normalization_36 (BatchNo (None, 12, 48, 56, 6 448         conv3d_43[0][0]
__________________________________________________________________________________________________
conv3d_44 (Conv3D)              (None, 12, 48, 56, 6 110656      batch_normalization_36[0][0]
__________________________________________________________________________________________________
batch_normalization_37 (BatchNo (None, 12, 48, 56, 6 448         conv3d_44[0][0]
__________________________________________________________________________________________________
conv3d_45 (Conv3D)              (None, 12, 48, 56, 6 110656      batch_normalization_37[0][0]
__________________________________________________________________________________________________
batch_normalization_38 (BatchNo (None, 12, 48, 56, 6 448         conv3d_45[0][0]
__________________________________________________________________________________________________
conv3d_46 (Conv3D)              (None, 12, 48, 56, 6 110656      batch_normalization_38[0][0]
__________________________________________________________________________________________________
batch_normalization_39 (BatchNo (None, 12, 48, 56, 6 448         conv3d_46[0][0]
__________________________________________________________________________________________________
add_7 (Add)                     (None, 12, 48, 56, 6 0           batch_normalization_39[0][0]
                                                                 conv3d_transpose_2[0][0]
__________________________________________________________________________________________________
conv3d_transpose_3 (Conv3DTrans (None, 12, 96, 112,  8224        add_7[0][0]
__________________________________________________________________________________________________
conv3d_47 (Conv3D)              (None, 12, 96, 112,  33          conv3d_transpose_3[0][0]
__________________________________________________________________________________________________
y_true (InputLayer)             [(None, 12, 86, 98,  0
__________________________________________________________________________________________________
cropping3d (Cropping3D)         (None, 12, 86, 98, 1 0           conv3d_47[0][0]
__________________________________________________________________________________________________
lambda (Lambda)                 ()                   0           y_true[0][0]
                                                                 cropping3d[0][0]
__________________________________________________________________________________________________
add_loss (AddLoss)              ()                   0           lambda[0][0]
==================================================================================================
Total params: 19,793,601
Trainable params: 19,771,041
Non-trainable params: 22,560

It is the same model, but I am not entirely sure why I get thrown the following error:
  File "/projects/.../.../projects/.../.../model/web_app.py", line 177, in generate_mask
    model.load_weights(path + '/.../vnet_46.h5', by_name = False)
  File "/home/.../miniconda3/envs/.../lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py", line 162, in load_weights
    return super(Model, self).load_weights(filepath, by_name)
  File "/home/.../miniconda3/envs/.../lib/python3.7/site-packages/tensorflow/python/keras/engine/network.py", line 1424, in load_weights
    saving.load_weights_from_hdf5_group(f, self.layers)
  File "/home/.../miniconda3/envs/.../lib/python3.7/site-packages/tensorflow/python/keras/saving/hdf5_format.py", line 757, in load_weights_from_hdf5_group
    str(len(weight_values)) + ' elements.')
ValueError: Layer #2 (named "batch_normalization" in the current model) was found to correspond to layer batch_normalization in the save file. However the new layer batch_normalization expects 8 weights, but the saved weights have 7 elements.

I am using tensorflow v1.14.0 and I believe it could be related to the tensorflow version.


text:
Q: how to build a custom jquery ui file I forked the last release of jQuery ui from github and modified the code, and now I want to build it to create a compiled code like google's code.
I see there is a build.xml in the /build directory, which says:
<!--
    jQuery UI Release!

    Call task called 'deploy-release' to build a full release.
    The release built will be stored on 'dist' dir.
-->

I dont know how to call the deploy-release. What should i do to generate the compiled javascript file?

A: The build.xml file looks like an Ant file to me so try using Ant. Also, in build/release/prepare-release, we see this:
# Run the build
echo "Running build..."
ant

So it using Ant.

A: Take a look at the documentation for jQuery. The build process is the same for jQuery UI.

A: The instructions are here
From the root of the jquery-ui repo:
cd build
ant
Currently, you must have Java, Ant, and Node.js installed for it to work.  I recommend using NVM to install node.
Update: the link above is broken and new build instructions are in the README on github: https://github.com/jquery/jquery-ui

A: If you don't like using what the process above...you can minify your JavaScript by cutting-and-pasting right into Google's Closure Compiler.


text:
Q: @Auth and @valid annotation not working together in java 17 I am trying to use @auth and @valid annotation together in one of the APIs in my resource class and it is not being intialized and gives following error at runtime :

Caused by: org.glassfish.jersey.server.model.ModelValidationException:
Validation of the application resource model has failed during
application initialization. [[FATAL] No injection source found for a
parameter of type public javax.ws.rs.core.Response

this is what my api declaration looks like :
@POST
@ApiOperation(value = "Add feature"
@Path("/add/")
@RolesAllowed({"ADMINISTRATORS"})
public Response addTransactionType(@ApiParam(hidden = true) @Auth User user, @Valid CreateRequest request) throws Exception {

whereas the other api method which doesn't have @auth and @valid annotation together works fine, for example :
@GET
@ApiOperation(value = "get detail")

@Path("/detail/{id}")
@RolesAllowed({"USERS"})
public Response get(@ApiParam(hidden = true) @Auth User user, @PathParam("id") int id) throws Exception {

I am using java 17 with dropwizard 2.
I tried changing the order of parameters being passed and removing @valid annotation but nothing worked. Checked if there are multiple apis sharing same path and that doesn't seem to be the case. also have registered the auth binder as well in the app, so that doesn't seem to be the issue as well.


text:
Q: Broken pipe and Device or resource busy errors in a GCP compute instance while transferring data from Google Drive I am having broken pipe issues while transferring a Google drive directory into GCP Google Storage. Steps are as follows. First, a compute instance creates and attaches a disk. Then it scans and requests file by file all the subdirectories and files within the Google Drive root directory. It does this using standard Google libraries google-api-client, google-cloud-storage and also this client library apiclient. Eventually dowloaded data is zipped and uploaded to Google Storage. Download takes some time, a couple of hours, eventually crashing with a [Errno 32] Broken pipe, every time at a different file, about one or two hours into the step. To fix and debug this I am catching the errors with try except BrokenPipeError statements across the script. If I do so, then it crashes with a different error, [Errno 16] Device or resource busy: '/data/'. For reference, /data/ is the name of the mounted attached disk mentioned above. This error, like the previous one, happens at a different file every time, which is very confusing. My understanding is that these two errors are somehow related although I do not fully understand how. Here is a sketch of how this works:
def download_files(service, item, dfilespath):
    if os.path.isfile(dfilespath + "/" + name):
        return
    if item['mimeType'] == 'application/vnd.google-apps.shortcut':
        logger.log('Not supported')
        return
    elif item['mimeType'] in list(MIMETYPE_CONVERSOR.keys()):
        # exported content is limited to 10MB
        request = service.files().export_media(fileId=item['id'], mimeType=MIMETYPE_CONVERSOR[item['mimeType']])
    else:
        request = service.files().get_media(fileId=item['id'])
        fh = io.BytesIO()
        suspicious_item = item['name']
        logger.log(f'io.BytesIO() failed for {suspicious_item}')
        downloader = MediaIoBaseDownload(fh, request)
    done = False
    try:
        while done is False:
            status, done = downloader.next_chunk()
            logger.log("Download %d%%." % int(status.progress() * 100))
    except Exception:
        logger.log('Failed to download file ' + name)
    with io.open(dfilespath + "/" + name, 'wb') as f:
        fh.seek(0)
        f.write(fh.read())

Increasing disk space or type does not fix the issue. I do not know if this arises because of I/O problems with the disk or because of the connection itself to Google Drive. I am inclined to say this seems more like an I/O problem as it says busy resource, but this is just a conjecture. The largest files it has to download are about 1-3 GBs. But again, this error seems to happen at different files every time and not necessarily at large ones (at least that I can tell from logs).


text:
Q: Converting Windows .PRN file (PCL) to PDF I have been succesfully capturing PCL content sent by old machinery to a parallel port and converting it to PDF using GhostPCL for a while.
However, we have some older industrial machinery which is based on Windows 2000 and outputs to a HP Laserjet printer via the parallel port.  Unfortunately, the software on the machine does not allow additional software or printers to be installed.
The problem is that whilst the captured output appears to be PCL graphic data, I have not found any tools which can convert it - GhostPCL attempts, and you can make out the text a little, but it is completely corrupted.
The captured output results in the output from GhostPCL
I can see that the captured output starts with:
ESC E (PCL command for Reset)
ESC &l0L (PCL command to disable skip perforation)
ESC &r1U (*** UNKNOWN ***)
ESC &l1H (PCL command to Feed from tray 2)
ESC *o0M (*** UNKNOWN ***)
ESC &126A (PCL command for A4 portrait paper)
ESC *g8W (PCL command to configure raster data - 8 bytes)

I can see that the captured output has some PCL codes which do not appear in the official documentation, which results in the weird characters at the start of the PDF.
Does anyone know how to convert this file to PDF ?

A: Your description shows an attempt to read a language different to pcl, so was the older system designed to talk to a default printer using Epson ESCAPE encoding. so its a dot printing file that the hardware will position those dots in the correct place and pressure, you could try converting to a bmp then massage the image into a pdf page.

You say an HP is connected but is that the true capture of what it is agreeing to use at runtime?
For example If I attempt to save my HP inkjet print file at time of printing I will get a PDF ! but why since the printer normally cant handle those direct?

What may I find If I look and see the default printing language is not set to a PCL or a PJL one.
There are many pcl language variations so a PRN file ideally should have some compatibility declaration such as @PJL ENTER LANGUAGE = PCLXL ) HP-PCL XL;2; Note this is NOT an HP printer just one that declares the following code will be HP style.
The printer can accept many formats and the system can produce many different formats for one printer. Thus you need to check all the system settings to understand what language is actually in run time use. Are you sure that .PRN is a full load of the conversation between the system & printer as print to file is not always the expected 2 way code.
The best way to ensure you capture true printer driver output is to change the drivers output PORT to a fixed filename and ideally use the correct format extension NOT unspecified .prn or .pcl if it is not such.


text:
Q: Flex and PHP code with IE Cache or POST issue I have a Flex application that uses a rich interface. The user can create data and have it instantly show up in a list of data that they have created. The data is stored in a MySQL database using HTTPService POST requests from the Flex application and PHP forms to handle the data on the server side. For sake of explanation, let's say the data is simply a question. In both Safari and Firefox, the data instantly shows up as it is supposed to as it is added to the database and then called to reload. However, when using IE the data IS added to the database, but it doesn't show up right away as it should. Sometimes it requires that the user empty the cache and other times they may need to quit IE and restart it. However, all times it IS added to the database. The PHP form uses a simple MySQL SELECT statement to get the data from the database.
Are there known issues with IE caching this data for a length of time? Is there any way to make it not do that?

A: I've been using a tool called Fiddler lately, which lets you watch the web traffic on your system, and even modify the requests and responses. In your case, you'll want to install it, and set it up as a reverse proxy so that your flex app communicates through it to the PHP layer.
Once that's set up, you can more easily track what's happening with your data. (I found a JSON plugin for mine that lets me view the JSON structure as a tree, but it natively supports an XML view)
Once you understand and explain the traffic a bit better, I might be able to help you out. It doesn't sound like a 304 HTTP problem. Confirm that the data is being returned to IE.

A: IE is notorious for caching stuff like ajax requests. A general big stick - on important requests that shouldnt be cached, make sure the pragma header is set to no-cache....
so in php call:
    header("Pragma: no-cache");

before content is rendered / returned to the browser. Alternatively add a timestamp as an additional param to an ajax url. Both approaches mean that any intermediate caching services would be busted through (i.e. redis, squid proxies etc.) which could affect your server load.
A more in depth interpretation can be found here:
http://thecodeabode.blogspot.com/2010/10/cache-busting-ajax-requests-in-ie.html


text:
Q: Refrescar token en interceptor Necesito controlar la validez de un token, y regenerarlo si hiciera falta, todo esto usando un interceptor, ¿Cómo puedo hacerlo?.
Mi idea es utilizar la fecha de expiración del token para controlar esto, pero uno de los problemas que tengo, es que a la vez entran dos peticiones al interceptor y parecen no respetarse, consiguiendo que en vez de generar un token, genere 2.
EDITO:

tokenLogin = {
            access_token
            token_type
            userName
            expires
            expires_in
            issued
          }

 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    console.log(req.url);

    if (req.url.includes('token') && !req.url.includes('api/Login/token')) { // PETICION DE PEDIR TOKEN
      return next.handle(req);
    }
    else if (req.url.includes('api/Administracion/')) return next.handle(req);
    else if ((req.url.includes('xxx') || req.url.includes('xxx')
      || req.url.includes('xxx')) && this.variables.loginCorrecto == true) {
      console.log("Peticiones al servicio");

      let request = req.clone({
        setHeaders: {
          authorization: 'Bearer ' + this.variables.tokenLogin.access_token
        }
      });

      return next.handle(request);

    } else {
      // SI NO CONCUERDA CON NINGUNA URL SIGUE SU CURSO
      return next.handle(req);
    }

  }


text:
Q: How to open a folder under a .Zip file In Unix how to open a folder under .zip file using UNIX shell scripting.
Below Syntax is the hierarchy of zip file :
ZipFileName--> Test.Zip --> 01072014(folder name like today date)--> test.txt, *.tif

After unzip of Test.zip i want to open folder location(01072014) ?

A: Q: How to open a folder under a .zip file using Unix shell scripting?
A: Use "gzip", extract to a temp directory, then "cd" into that directory.
NOTE:
This is exactly what happens when you open a .zip file using Windows Explorer - it extracts the contents of the .zip file into a temporary directory under your user profile.

A: If you want to open .gz file without extracting then you can use zcat command.
Suppose you have Test.gz file then you can use
zcat Test.gz

Please ignore if i am not understanding the question correctly.


text:
Q: Strongly minimal set with DMP Recall that a strongly minimal theory $T$ has the Definable Multiplicity Property (DMP) if for all natural $k$, $m$ and $\varphi(\bar{x},\bar{b})$ of rank $k$, multiplicity $m$, there exists a formula $\theta ∈ tp(\bar{b})$ such that for all $\bar{b^{'}}\models\theta$, $rk(\varphi(\bar{x},\bar{b^{'}}))=k$ and $mult(ϕ(\bar{x},\bar{b^{'}})) = m$.
Question. Does every strongly minimal set have a strongly minimal
expansion with DMP?
(Any reference will be appreciated.)

A: The answer is no, there is a counter example by Hasson and Hrushovski, constructed using Fraisse limit. It is described in their article "DMP in strongly minimal sets", J. Symbolic Logic
Volume 72, Issue 3 (2007), 1019-1030.


text:
Q: Inserting into MySQL table using a variable I have long known that one could fetch results from a mysql table and print it as :
(MySQL C API)
MYSQL_RES *result = mysql_store_result(con);

if (result == NULL)
{
  finish_with_error(con);
}

int num_fields = mysql_num_fields(result);
MYSQL_ROW row;
while ((row = mysql_fetch_row(result)))
{
   printf("%s ", row[i] ? row[i] : "NULL");
}

Now suppose I have to copy a database into another, can I do the other way round i.e can I somehow use the row variable to insert into the new database.
If I could do this copying a database would be so easy.
By copying a database I mean I have to create a database that is exactly the same as the original one, with all its data and attributes being the same.

A: I think prepared statements/PDO should work for what you're looking for. Without knowing what your table schema looks like, it's a bit hard to tell you what the statement would look like, but here's some information for the C API.
http://dev.mysql.com/doc/refman/5.1/en/c-api-prepared-statements.html
http://dev.mysql.com/doc/refman/5.0/en/c-api-prepared-statement-data-structures.html
http://dev.mysql.com/doc/refman/5.1/en/sql-syntax-prepared-statements.html


text:
Q: Split with pair of brackets and keep content between I'm trying to split a string in a list of strings. Right now i have to split whenever I see any of these characters:  '.', ';', ':', '?', '!', '( )', '[ ]', '{ }' (keep in mind that I have to mantain whatever is inside the brackets).
To solve it I tried to write
print(re.split("\(([^)]*)\)|[.,;:?!]\s*", "Hello world,this is(example)"))

but as output I get:
['Hello world', None, 'this is', 'example', '']

Omitting the ' ' at the end that I'll solve later, how can I remove the None that appears in the middle of the list?
By the way I can't iterate in the list another time because the program shall work with huge files and I have to make it as fast as possible.
Also I don't have to necessarily use re.split so everything that works will be just fine!
I'm still new at this so I'm sorry if something is incorrect.

A: Not sure if this is fast enough but you could do this:
re.sub(r";|,|:|\(|\)|\[|\]|\?|\.|\{|\}|!", " ", "Hello world,this is(example)").split()


text:
Q: Are many static variables in functions using up to much memory? I want to write a cross-plattform wrapper for some OS specific (Linux/MacOSX/Windows) calls to get the number of cores of the CPU etc. My idea was to put all of them in single functions with static variables, so stuff like the number of cores that does not change will be processed only once.
int getNumCPUCores()
{
    static int numCores = 0;

    if(!numCores)
    {
        // The info is aquired here
    }

    return numCores;
}

Now I wonder if this might be a bad idea, since all these static variables use up memory space whether they are initialized or not.
Or did I misunderstand something?

A: An int is a handful of bytes (four or eight on most modern platforms).  Unless you have millions of static variables or static variables of some really huge type, you don't need to worry about it.

A: No it's fine, as James said.
Furthermore in order to avoid the need to use a mutual-exlusion object (if you plan to use it in a multi-threaded app!) you'd better have a static instance of a class that would assess the number of cores upon construction.


text:
Q: ASP.NET Web Application with Windows Authentication not working inside Web Server Build an Intranet site which is mapped to the sub domain address under Windows Authentication hosted on web server (Windows Server 2012 IIS 8).Authentication works fine when tested outside the web serve which is also under the same domain.
ISSUE: Unable to authenticate my application inside web server using the sub domain address though it prompt of User name & password but does not authenticate because of which it does not resolves external style sheet & Images.
Following are the current setting for ASP.NET Web Application

*

*Web site Address: SubDomain.Domain.xx\SubSite

*Application Pool using Integrated Windows Authentication

*IIS 8 Authentication setting: ASP.NET Impersonation & Windows Authentication status enabled

*Using default IIS port

*IIS binding:  To the default port mapped to SubDomain.Domain.xx with unsigned

*IIS binding: To the default port mapped to Blank with Hosted Server IP address.

Please advice what setting I am missing to sort the issue..

A: First, make sure that you are logging in with the domain, e.g. yourdomain\yourusername.
You could then do with a test page which shows who it thinks you are (Identity). It may be running as the application pool if it's not quite set up right and that account probably doesn't have access to other resources that it needs.
Does your web browser console confirm that this is the error and not just an incorrect path to the files?


text:
Q: Wildcards not being substituted #!/bin/bash
loc=`echo ~/.gvfs/*/DCIM/100_FUJI`
rm -f /mnt/fujifilmA100
ln -s "$loc" /mnt/fujifilmA100

For some reason the variable * doesn't get substituted with the only possible value and gets given the value /home/chris/.gvfs/*/DCIM/100_FUJI. Does anyone have an idea of why?
Please note:

*

*If global expansion fails, the pattern is not substituted. I ran the
commands:
chris@comp2008:~$ loc=``echo ~/.gvfs/*/DCIM/100_FUJI
chris@comp2008:~$ echo $loc
/home/chris/.gvfs/gphoto2 mount on usb%3A001,008/DCIM/100_FUJI
So we can see the expansion should
work

*I have now switched to using:
loc = ``find ~/.gvfs -name 100_FUJI
I am just curious why it doesn't work as is.

*Debugging output using sh -x

echo /home/chris/.gvfs/*/DCIM/100_FUJI
loc=/home/chris/.gvfs/*/DCIM/100_FUJI
rm -f /mnt/fujifilmA100
ln -s /home/chris/.gvfs/*/DCIM/100_FUJI/mnt/fujifilmA100

A: You mentioned in your response to Tactical Vim that you're running this under sudo -- '~' is going to be expanded differently under sudo vs. under your normal user.  Change it to '~chris' or hard code your home directory.

A: Are you sure you entered the .sh file exactly as shown here? I just made a test script doing exactly the same thing as you and it works for me.
Maybe something to do with the strange directory name with spaces, %-signs, and commas?

A: Try running your script under 'sh -x' to see some debug output, perhaps it'll provide a clue. I've never seen echo used in this sort of way, it could be something related to that; does it work if you replace 'echo' with 'ls -d' (or similar, not sure your output) instead?

A: Okay, I modified my script as follows:
loc=`echo ~chris/.gvfs/*/DCIM/`
sudo rm -f /mnt/camera
sudo ln -s "$loc" /mnt/camera

Notice that the sudo's are inside the script


text:
Q: Completion of unimodular rows Is the unimodular row $(x,y,z)$ completable over the ring
$({\mathbb Z}/2{\mathbb Z})[x,y,z,y',z']/\langle x^2+yy'+zz'-1 \rangle$ ?

A: Your question is equivalent to the $n=2$ case of what T.Y. Lam calls "Murthy's $(a,b,c)$ problem" in his book "Serre's problem on projective modules. (This is statement 5.7 on p. 323 in the 2006 edition).
Lam indicates that this is wide open.