text:
Q: mzcdf2peaks does not accepts given data created by mzcdfread in Matlab r2020a So I have the following code and error:
>> data = mzcdfread('sample1.cdf');

Reading filename: sample1.cdf
Number of dimensions: 11   Unlimited Dimension:  8
Number of variables:  12   Number of attributes: 10

Exploring global netCDF attributes:
     acd_ec_version -> 1.0
     dataset_completeness -> C1
     aia_template_revision -> 1.0
     netcdf_revision -> 3.4
     languages -> English
     injection_date_time_stamp -> 20120404170129+-0500
     separation_experiment_type -> Liquid Chromatography
     source_file_reference -> L:\chromatogram\web\sample 1.xy
     detector_unit -> AU
     retention_unit -> seconds

Exploring netCDF dimensions:
                          Name  Length  Dim_ID
                _2_byte_string       2     1
                _4_byte_string       4     2
                _8_byte_string       8     3
               _16_byte_string      16     4
               _32_byte_string      32     5
               _64_byte_string      64     6
              _128_byte_string     128     7
              _255_byte_string     255     8
                  acd_ec_count       0     9
                  error_number       1    10
                  point_number   17999    11

Reading netCDF variables:
                          Name    Type  Dim_ID  NumAtt
                     error_log      2   6 10       0
        detector_maximum_value      5              0
        detector_minimum_value      5              0
        actual_run_time_length      5              0
      actual_sampling_interval      5              0
             actual_delay_time      5              0
               ordinate_values      5     11       1
         uniform_sampling_flag -> Y
           peak_retention_time      5              0
                     peak_name      2              0
                   peak_amount      5              0
                     peak_area      5              0
                   peak_height      5              0
>> mzcdf2peaks(data)
Error using mzcdf2peaks (line 27)
Input structure MZCDFSTRUCT must be created by MZCDFREAD.

It's a simple .cdf file. I want the final output to be:

but as you see mzcdf2peaks function does not work for me and causes this error:
Error using mzcdf2peaks (line 27)
Input structure MZCDFSTRUCT must be created by MZCDFREAD.

I'm following this example where they use the following commands:
mzcdf_struct = mzcdfread('results.cdf');
[peaks,time] = mzcdf2peaks(mzcdf_struct)
figure
hold on

for i = 1:numel(peaks)
    t = repmat(time(i),size(peaks{i},1),1);
    plot3(t,peaks{i}(:,1),peaks{i}(:,2),'color',colors(i,:))
end

view(70,60)
xlabel('Time')
ylabel(mzcdf_struct.mass_axis_label)
zlabel(mzcdf_struct.intensity_axis_label)

When I open sample1.cdf file in Unichrom it works.

You can access the cdf file here: https://files.fm/u/j7yjb23c
So my question is how to get Matlab mzcdf2peaks function working on this dataset?
Is there any other way to achieve the desired output?


text:
Q: Open applications in the background in OS X, I don't want my focus taken from me. Respect my Focus! I'm running El Capitan 10.11.4 on a 2014 Mac Mini.
I'm often running 10-14 apps at one time as I work writing reports, word/excel/Adobe/Safari/iTunes/calendar/etc...
Frequently I want to open another app, I want it to open in the background and go back to word/excel and keep working, but the launching app takes away my focus, sometimes 2 or 3 times. once for the splash screen, once for the open dialogue window, and again after I click 'new document'.
Another situation, I update an app in the background, like 1Password (beta) and every step it takes my focus back to the app being updated.
Is there anything I can do with Unix/Terminal, etc. to force all app activity to be done in the background, or to keep OS to respect my focus?

A: To launch an app in Finder in the background (hidden) you can use a simple Automator service. Open Automator app, select a service that accepts files or folders in Finder and add a Run Shell Script action with following contents:

for f in "$@"
do
    open "$f" --hide
done

Save the service as Open in background. Open System Preferences./ Keyboard / Shortcuts / Services, find your new service and assign a keyboard shortcut you desire. I chose a handy ShiftCmdB. Close System Preferences and test the service and the shortcut.

Nice thing about this is that it works with apps as well as documents.

A: Working on macOS 12.1 (Monterey) with another flag option:
for f in "$@"
do
    open "$f" -gj
done

see this post for more information: Open app in background from Terminal

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jquery Traversing - Seleccionar "Alrededores" Buenas. Quiero a partir del .elemento_seleccionado:

            Col1
            Col2
            Col3

            Iz/Ar
            Arriba
            De/Ar

            Izquierda
            Seleccion
            Derecha

            Iz/Aba
            Abajo
            De/Aba

Poder seleccionar su:

*

*Elemento Arriba

*Elemento Abajo

*Diagonales
Por ahora he podido realizar la seleccion de:

*

*Izquierda
$(".elemento_seleccionado").prev().css("background","cyan");

*Derecha
$(".elemento_seleccionado").next().css("background","orange");

A: Puedes sacar las celdas de la fila actual y obtener el índice de la celda seleccionada a través del método index. A partir de ahí se puede calcular los índices de las celdas a seleccionar en las filas anteriores y siguientes.
Este ejemplo selecciona las celdas alrededor de la celda sobre la que se hace click:

$(function(){
  $('td').click(function(){
    $('td').css('backgroundColor', 'white');
    var $selected= $(this);
    var index = $selected.parent().find('td').index($selected);

    $selected.css('backgroundColor', 'blue');
    $selected.prev().css('backgroundColor', 'green');
    $selected.next().css('backgroundColor', 'green');
    $selected.parent().prev()
    .find('td:eq(' + Math.max(index-1, 0) + ')'
      + ', td:eq(' + index + ')'
      + ', td:eq(' + (index + 1) + ')')
    .css('backgroundColor', 'green');
    $selected.parent().next()
    .find('td:eq(' + Math.max(index-1, 0) + ')'
      + ', td:eq(' + index + ')'
      + ', td:eq(' + (index + 1) + ')')
    .css('backgroundColor', 'green');
  });
});
td{
  border: solid 1px #666666;
  padding: 10px;
}

A: De la siguiente manera podes seleccionar todas las posiciones, borra las que no necesites:
EDITADO
Para que haga la selección no importa cuantas columnas o filas tenga

var index = $(".elemento_seleccionado").parent().find('td').index($(".elemento_seleccionado"));

$(".elemento_seleccionado").parent().prev().find("td:eq("+(index-1)+")").css("background","cyan");//Iz/Ar
$(".elemento_seleccionado").parent().prev().find("td:eq("+index+")").css("background","cyan");//Arriba
$(".elemento_seleccionado").parent().prev().find("td:eq("+(index+1)+")").css("background","cyan");// De/Ar
$(".elemento_seleccionado").prev().css("background","cyan");//Izquierda
$(".elemento_seleccionado").next().css("background","cyan");//Derecha
$(".elemento_seleccionado").parent().next().find("td:eq("+(index-1)+")").css("background","cyan");//Iz/Aba
$(".elemento_seleccionado").parent().next().find("td:eq("+index+")").css("background","cyan");//Abajo
$(".elemento_seleccionado").parent().next().find("td:eq("+(index+1)+")").css("background","cyan");//De/Aba

            Col1
            Col2
            Col3
            Col4
            Col5

            x
            Iz/Ar
            Arriba
            De/Ar
            x
            x

            x
            Izquierda
            Seleccion
            Derecha
            x
            x

            x
            Iz/Aba
            Abajo
            De/Aba
            x
            x


text:
Q: Create custom objects from CSV rows I have the following CSV file:
id;area;zz;nc
1;35.66;2490.8;1
2;65.35;2414.93;1
3;79.05;2269.33;1
4;24.5;2807.68;1
5;19.31;2528.59;1
6;25.51;2596.44;1

where each rows represents a so called Cell object with its id, area, zz, cc.
Consequentially, I have created the following class:
class cells():
    #
    # Initializer / Instance Attributes
    def __init__(self, idm, area,zz,nc):
        self.idm  = idm
        self.area = area

The idea is to create a number of object as the number of cells and to assign to them the attributes according to the data in the file.
The first idea that I have is to read the csv file as a DataFrame and after a list of objects to be populated in a cycle.
As far as I know, python is very inefficient with cycle and I would like to know if there is another way (smart one) to do that.
Thanks,
Diego

A: I don't quite understand what you mean by cycle, but this will create a list of cell objects for each row that you have - given the format your data is in.
Pandas list comprehension over series is a reasonable option, see https://stackoverflow.com/a/55557758/7582537
Try this:
import pandas as pd

class Cell():
    # Initializer / Instance Attributes
    def __init__(self, idm, area, zz, nc):
        self.idm  = idm
        self.area = area

def create_cells(row):
    newcell = Cell(row[0], row[1], row[2], row[3])
    return newcell

file = pd.read_table("your_file.csv", sep=';')
zipp = zip(file['id'], file['area'], file['zz'], file['nc'])
cells = [create_cells(row) for row in zipp]

print(cells)

A: uMdRupert shared a link to an interesting post in his answer, I would recommend checking it out!

I like his idea of using a list comprehension, so I wanted to share a similar method:
import pandas as pd

class Cell:
    def __init__(self, idm, area, zz, nc):
        self.idm = idm
        self.area = area

cell_df = pd.read_csv('../resources/test_cell_data.csv', delimiter=';')
cell_df = cell_df.rename({'id': 'idm'}, axis='columns')

cell_objs_lst = [Cell(*curr_tuple._asdict()) for curr_tuple in cell_df.itertuples(index=False)]

Pandas might be overkill for this task, so here is a dead-simple method which uses the csv module:
import csv

class Cell:
    def __init__(self, idm, area, zz, nc):
        self.idm = idm
        self.area = area

with open('../resources/test_cell_data.csv', newline='') as in_file:
    next(in_file)
    reader = csv.DictReader(in_file, fieldnames=['idm', 'area', 'zz', 'nc'], delimiter=';')
    cells_lst = [Cell(**curr_row) for curr_row in reader]

A: I don't think you need pandas in this case. pandas is overkill if you only need to read a csv file.
either read it directly:
objects = []
next(f) # skip header row
with open('your_file', 'r') as f:
    for row in f:
        objects.append(cells(*row.strip().split(';')))

or using csv module.

A: I don't know your purpose of using object Cells for each row of df. However, I think you may achieve it with df.agg and keep every object in a series
class Cells():
    # Initializer / Instance Attributes
    def __init__(self, idm, area, zz, nc):
        self.idm  = idm
        self.area = area
        self.zz = zz
        self.nc = nc

s = df.agg(lambda x: Cells(*x), axis=1)
print(s)

Output:
0    <__main__.Cells object at 0x09FA38D0>
1    <__main__.Cells object at 0x09FA3510>
2    <__main__.Cells object at 0x09FA3870>
3    <__main__.Cells object at 0x09FA3AF0>
4    <__main__.Cells object at 0x09B27790>
5    <__main__.Cells object at 0x09B27770>
dtype: object

After that you may access each object from indexing of s
In [303]: s[0].__dict__
Out[303]: {'idm': 1.0, 'area': 35.66, 'zz': 2490.8, 'nc': 1.0}

In [304]: s[1].__dict__
Out[304]: {'idm': 2.0, 'area': 65.35, 'zz': 2414.93, 'nc': 1.0}


text:
Q: missing "his" before "tears" and "a couple of feet" I have stumbled onto two sentences in my book and I wonder to know why there is missing "his" before "tears" and "a cople of feet". The texts are

Then, as he tried to drop a couple of feet to the ground, he caught his shirt on a metal shard that hang him up for an instant before tearing loose.
Chad fought tears as he leaned in and pressed his head against his father's chest.

For me it would be OK to say "his tears" and "his couple of feet", because it was his tears and his feet, as well as it was his shirt and his head, but I think it was reason for writer not to write that. Can you explain to me why?

A: The words "couple of feet" refer not to his feet, but to a distance of two feet, or 24 inches (61 centimeters), so "his" doesn't belong there.
You could say "he fought his tears", but it's unnecessary, since it's understood that his own tears are referred to. He can't fight someone else's tears.

A: In the first sentence, it is not referring to his feet. It is referring to feet as distance. He is dropping to the ground from a height of a couple of feet. So his doesn't make sense here. If it was reffering to his feet then "...tried to drop his feet to the ground..." would be correct.
For the second sentence, we tend not to refer to someone as owning tears. You could say fought his tears but it sounds strange. You would say, for example, "a tear rolled down his cheek". It is obvious whose tear it is without saying it explicitly.
(Sidenote "fought back tears" is more common than "fought tears". See ngram: https://books.google.com/ngrams/graph?content=fought+tears%2C+fought+back+tears&year_start=1800&year_end=2019&corpus=26&smoothing=3&direct_url=t1%3B%2Cfought%20tears%3B%2Cc0%3B.t1%3B%2Cfought%20back%20tears%3B%2Cc0)


text:
Q: paypal error Api: /smart/api/order/29B71296JP6358523/capture returned ack: permission_denied (Corr ID: -----) I am using https://www.paypal.com/sdk/js?client-id=ddd&currency=EUR
with frontEnd implementation, On Production I am getting this error.
paypal error Api: /smart/api/order/29B71296JP6358523/capture returned ack: permission_denied (Corr ID: -----)
I am not sure why and when it occurs as i am logging the caught error in OnError method.
Can someone help me out that why is it occuring...


text:
Q: How do I plot words by frequency for a text not in English? I need to obtain Zipf plots (Frequency vs Rank) of non-English texts (a utf-8 encoded text file) using Mathematica. How do I do it?

A: It's pretty simple:
text = ToLowerCase@Import["C:\\Input\\Moby Dick.txt"];
text = StringReplace[
text, {"." -> "", ";" -> "", ":" -> "", "-" -> "", "," -> "", "*" -> "", "" -> ""}];
(*Get rid of extra whitespace*)
text = StringReplace[text, " " .. -> " "];
(*Make a list of words*)
words = StringSplit[text];
(*Tally the frequency of each word*)
tally = SortBy[Tally[words], -#[[2]] &];

Now we have a tally of the frequency of each word. Plotting it is simple:
Index[x_] := Table[{i, x[[i]]}, {i, Length@x}];
points = Index[tally[[All, 2]]];
ListLogLogPlot[points, PlotRange -> Full]


text:
Q: wxpython - HyperTreeList check in which column an event was? My code is an example of an HyperTreeList, i got it working with a pre-defined column which could be edited with an Doubleclick.
I would like to have all columns be able to be edited. So i need to check in which column the doubleclick event was.
How do i do that?
Here is my code so far:
import wx
import wx.lib.agw.hypertreelist as HTL

class MyFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, -1, "HyperTreeList Demo")

        self.tree = HTL.HyperTreeList(self)
        self.tree.AddColumn("First column")
        self.tree.AddColumn("Column 1")
        self.tree.AddColumn("Column 2")
        root = self.tree.AddRoot("Root")
        parent = self.tree.AppendItem(root, "First child")
        child = self.tree.AppendItem(parent, "First Grandchild")
        self.tree.AppendItem(root, "Second child")

        self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnEditItem, self.tree)

    def OnEditItem(self, evt):
        item = self.tree.GetSelection()
        itemParent = item.GetParent()
        if itemParent != None:
            itemParentText = itemParent.GetText()
            if itemParentText == "First child":
                # How to check in which column the event was?
                self.tree.EditLabel(item, 1)

app = wx.App(0)
frame = MyFrame(None)
app.SetTopWindow(frame)
frame.Show()
app.MainLoop()

A: Maybe you can try something like this:
self.tree.GetMainWindow().Bind(wx.EVT_LEFT_DCLICK, self.OnLeftDClick)

def OnLeftDClick(self, event):

    pt = event.GetPosition()
    item, flags, column = self.tree.HitTest(pt)
    if item and (flags & wx.TREE_HITTEST_ONITEMLABEL):
        # Use the column return value as you wish
        self.tree.EditLabel(item, column)

    event.Skip()


text:
Q: Run application in Raspberry Pi with a web browser I would like to build an application Raspberry Pi for controlling a 20 Inch monitor it will display some images.
Long story
Each user have an account (Web based application) and he/she is logged into account and upload some images/videos into his account (Stored AWS S3 buckets).
Later he can connect his Device it includes 20 Inch monitor+Raspberry Pi to this account.
Here the crucial part comes he can able to start some features on this monitor some of are
1.Set up an image slideshow in the monitor.
2.Can able to stop it.
3.Cache images for some times.
ie  he/she control the monitor with a browser.
 Currently  we have Raspberry Pi 3 with RASPBIAN os  and the user web application.
Is it possible to do with Raspberry Pi??


text:
Q: use wsdl with mule I have a web service on a server that it use a wsdl of another company (such as company A).
Now, I want to my web service use mule architected.
I have to starting a mule server. My request should sent such as below algorithm:
My web service -> mule server -> wsdl of company A
And about response:
Wsdl of company A -> mule server -> my web service
I used "web service proxy pattern" and "wsdl redirection" for do that. So by doing this work, wsdl of company A redirected on mule server. I think that I didn't use mule correctly because I just change url address of wsdl. There is a part in wsdl:
<soap:address location="">

And <xsd:schema><xsd:import namespace="">
This location and namespace are url address of company A. when I create stub file from wsdl, there are url address of company A in this files and annotation in stub files.
Configuration:
<pattern:web-service-proxy name="SOAP2SOAPFlow4"
  inboundAddress="http://localhost:8090/sample"
  outboundAddress="http://companyA.com/test"
  wsdlLocation="http://companyA.com/test.asmx?WSDL" />

Running on Mule standalone 3.3.0.
Is my work wrong? What do I change?


text:
Q: my workspace setting.json for unity on VSCode says 'end of file' expected after files.exclude After setting VSCode as my editor and downloading the unity debugger extension, I deleted the original settings.json and replaced it with this one:
 // Configure glob patterns for excluding files and folders.
 "files.exclude": {
    "**/.git": true,
    "**/.DS_Store": true,
    "**/*.meta": true,
    "**/*.*.meta": false,
    "**/*.unity": true,
    "**/*.unityproj": true,
    "**/*.mat": true,
    "**/*.fbx": true,
    "**/*.FBX": true,
    "**/*.tga": true,
    "**/*.cubemap": true,
    "**/*.prefab": true,
    "**/Library": true,
    "**/ProjectSettings": true,
    "**/Temp": true
}

What i want is for only the CS scripts to show and hide the remaining (.unity,.prefab etc...). I found this above code online that's meant to do that but there's an 'end of file expected' message on the colon after the files.exclude. i guess a set of curly brackets is missing somewhere but where in the code is it meant to be?

A: I actually found what was missing and it happened to be that curly brackets also needed to encapsulate the whole code itself. That solved the problem. Here is the corrected code with some extra files to exclude added:
{
    "files.exclude": {
        "**/.git": true,
        "**/.DS_Store": true,
        "**/*.meta":true,
        "**/Library":true,
        "**/obj":true,
        "**/Temp":true,
        "**/ProjectSettings": true,
        "**/*.unityproj": true,
        "**/*.wav": true,
        "**/*.sln": true,
        "**/*.userprefs": true,
        "**/*.prefab": true,
        "**/*mat": true,
        "**/*fbx": true,
        "**/*.unity": true
    }
}


text:
Q: WinForms makes some change on load in designer This is something I have noticed over the years but never bothered with it before. When opening WinForms forms in designer view, VS sets some forms to an unsaved state immediately. This only happens with some forms with a slightly complex hierarchy.
The trouble is, whenever this happens, something about the form has been changed (mostly sutble changes). Usually the alignment of a nested control with anchor properties set. In this particular case, I have SplitPanel with a nested GroupBox with a nested PropertyGrid control.
So every time I run the open the form and save it, this annoying change appears in runtime and can be seen in the designer as well. Have others noticed similar behavior? If so, anyone find a cause and workaround?


text:
Q: Importing excel file with all the conditional formatting rules to epplus I have an excel file which contains lots of data along with icon sets and data bars based on the values in the cell. It looks like this:
I want to import this excel sheet along with the conditional formatting. Is there any library for this?? I went through this http://www.sitecorecleveland.com/resources/blogs-posts/easy_excel_interaction_pt6 but it only imports data not format.
If that's not possible is there code in epplus to have these iconsets in excel sheet. I can have arrows, traffic lights, etc but not these.

A: I dont think EPP supports custom conditional formatting which are stored as "Workbook Extensions" in the xml of the Excel file.  You could copy the xml node of the "extLst" which contains the custom formatting from one worksheet to another.  Just make sure there is nothing else beside the cond formatting xml in the node that you do not want copied in which case you will have to select only the child nodes you want.
To test, i created the following excel sheet (temp.xlsx), did a copy.paste of values only and saved to a new file (temp2.xlsx):

Then ran the following and it successfully copied the formatting over:
public void Custom_Condition_Copy_Test()
{
    //http://stackoverflow.com/questions/28493050/importing-excel-file-with-all-the-conditional-formatting-rules-to-epplus

    //File with custom conditional formatting
    var existingFile = new FileInfo(@"c:\temp\temp.xlsx");

    //Copy of the file with the conditonal formatting removed
    var existingFile2 = new FileInfo(@"c:\temp\temp2.xlsx");

    using (var package = new ExcelPackage(existingFile))
    using (var package2 = new ExcelPackage(existingFile2))
    {
        //Make sure there are document element for the source
        var worksheet = package.Workbook.Worksheets.First();
        var xdoc = worksheet.WorksheetXml;

        if (xdoc.DocumentElement == null)
            return;

        //Make sure there are document element for the destination
        var worksheet2 = package2.Workbook.Worksheets.First();
        var xdoc2 = worksheet2.WorksheetXml;

        if (xdoc2.DocumentElement == null)
            return;

        //get the extension list node 'extLst' from the ws with the formatting
        var extensionlistnode = xdoc
            .DocumentElement
            .GetElementsByTagName("extLst")[0];

        //Create the import node and append it to the end of the xml document
        var newnode = xdoc2.ImportNode(extensionlistnode, true);
        xdoc2.LastChild.AppendChild(newnode);

        package2.Save();

    }
}

Might want to put some try's in there but this should get you close.

UPDATE:  Based on OPs comment.
If you want to be able to add the custom conditional format without the need of the original file that contains it, I see two options.
Option 1, you do it the more "correct" way and use the DocumentFormat.OpenXml namespace.  BUT, this would require you to have the Office Open XML library available which may or may not be so easy depending on the environment you are running this in.  You can get it from here http://www.microsoft.com/en-us/download/details.aspx?id=30425 and it comes with a Reflection tool that can generate the code you want which gets you this:
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
using X14 = DocumentFormat.OpenXml.Office2010.Excel;
using Excel = DocumentFormat.OpenXml.Office.Excel;

......

WorksheetExtensionList worksheetExtensionList1 = new WorksheetExtensionList();

WorksheetExtension worksheetExtension1 = new WorksheetExtension(){ Uri = "{78C0D931-6437-407d-A8EE-F0AAD7539E65}" };
worksheetExtension1.AddNamespaceDeclaration("x14", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main");

X14.ConditionalFormattings conditionalFormattings1 = new X14.ConditionalFormattings();

X14.ConditionalFormatting conditionalFormatting1 = new X14.ConditionalFormatting();
conditionalFormatting1.AddNamespaceDeclaration("xm", "http://schemas.microsoft.com/office/excel/2006/main");

X14.ConditionalFormattingRule conditionalFormattingRule1 = new X14.ConditionalFormattingRule(){ Type = ConditionalFormatValues.IconSet, Priority = 2, Id = "{CD6B2710-0474-449D-881A-22CFE15D011D}" };

X14.IconSet iconSet1 = new X14.IconSet(){ IconSetTypes = X14.IconSetTypeValues.FiveArrows, Custom = true };

X14.ConditionalFormattingValueObject conditionalFormattingValueObject1 = new X14.ConditionalFormattingValueObject(){ Type = X14.ConditionalFormattingValueObjectTypeValues.Percent };
Excel.Formula formula1 = new Excel.Formula();
formula1.Text = "0";

conditionalFormattingValueObject1.Append(formula1);

X14.ConditionalFormattingValueObject conditionalFormattingValueObject2 = new X14.ConditionalFormattingValueObject(){ Type = X14.ConditionalFormattingValueObjectTypeValues.Percent };
Excel.Formula formula2 = new Excel.Formula();
formula2.Text = "20";

conditionalFormattingValueObject2.Append(formula2);

X14.ConditionalFormattingValueObject conditionalFormattingValueObject3 = new X14.ConditionalFormattingValueObject(){ Type = X14.ConditionalFormattingValueObjectTypeValues.Percent };
Excel.Formula formula3 = new Excel.Formula();
formula3.Text = "40";

conditionalFormattingValueObject3.Append(formula3);

X14.ConditionalFormattingValueObject conditionalFormattingValueObject4 = new X14.ConditionalFormattingValueObject(){ Type = X14.ConditionalFormattingValueObjectTypeValues.Percent };
Excel.Formula formula4 = new Excel.Formula();
formula4.Text = "60";

conditionalFormattingValueObject4.Append(formula4);

X14.ConditionalFormattingValueObject conditionalFormattingValueObject5 = new X14.ConditionalFormattingValueObject(){ Type = X14.ConditionalFormattingValueObjectTypeValues.Percent };
Excel.Formula formula5 = new Excel.Formula();
formula5.Text = "80";

conditionalFormattingValueObject5.Append(formula5);
X14.ConditionalFormattingIcon conditionalFormattingIcon1 = new X14.ConditionalFormattingIcon(){ IconSet = X14.IconSetTypeValues.ThreeSymbols, IconId = (UInt32Value)0U };
X14.ConditionalFormattingIcon conditionalFormattingIcon2 = new X14.ConditionalFormattingIcon(){ IconSet = X14.IconSetTypeValues.ThreeTrafficLights1, IconId = (UInt32Value)0U };
X14.ConditionalFormattingIcon conditionalFormattingIcon3 = new X14.ConditionalFormattingIcon(){ IconSet = X14.IconSetTypeValues.ThreeTriangles, IconId = (UInt32Value)0U };
X14.ConditionalFormattingIcon conditionalFormattingIcon4 = new X14.ConditionalFormattingIcon(){ IconSet = X14.IconSetTypeValues.ThreeTriangles, IconId = (UInt32Value)1U };
X14.ConditionalFormattingIcon conditionalFormattingIcon5 = new X14.ConditionalFormattingIcon(){ IconSet = X14.IconSetTypeValues.ThreeTriangles, IconId = (UInt32Value)2U };

iconSet1.Append(conditionalFormattingValueObject1);
iconSet1.Append(conditionalFormattingValueObject2);
iconSet1.Append(conditionalFormattingValueObject3);
iconSet1.Append(conditionalFormattingValueObject4);
iconSet1.Append(conditionalFormattingValueObject5);
iconSet1.Append(conditionalFormattingIcon1);
iconSet1.Append(conditionalFormattingIcon2);
iconSet1.Append(conditionalFormattingIcon3);
iconSet1.Append(conditionalFormattingIcon4);
iconSet1.Append(conditionalFormattingIcon5);

conditionalFormattingRule1.Append(iconSet1);
Excel.ReferenceSequence referenceSequence1 = new Excel.ReferenceSequence();
referenceSequence1.Text = "A1:C201";

conditionalFormatting1.Append(conditionalFormattingRule1);
conditionalFormatting1.Append(referenceSequence1);

conditionalFormattings1.Append(conditionalFormatting1);

worksheetExtension1.Append(conditionalFormattings1);

worksheetExtensionList1.Append(worksheetExtension1);
....
worksheet1.Append(worksheetExtensionList1);

Option 2 would be to do as you are asking and perform string manipulation.  This is much easier but it is a slightly dirty in that you are messing with strings rather then objects but if the only thing you need to set is the cell range that doesnt seem so bad.  I used the test method above to extract the string with = extensionlistnode.OuterXml:
[TestMethod]
public void Custom_Condition_From_String_Test()
{
    //http://stackoverflow.com/questions/28493050/importing-excel-file-with-all-the-conditional-formatting-rules-to-epplus

    //Throw in some data
    var datatable = new DataTable("tblData");
    datatable.Columns.Add(new DataColumn("Col1", typeof(int)));
    datatable.Columns.Add(new DataColumn("Col2", typeof(int)));
    datatable.Columns.Add(new DataColumn("Col3", typeof(int)));

    for (var i = 0; i < 20; i++)
    {
        var row = datatable.NewRow();
        row["Col1"] = i;
        row["Col2"] = i * 10;
        row["Col3"] = i * 100;
        datatable.Rows.Add(row);
    }

    //Copy of the file with the conditonal formatting removed
    var existingFile2 = new FileInfo(@"c:\temp\temp2.xlsx");
    if (existingFile2.Exists)
        existingFile2.Delete();

    using (var package2 = new ExcelPackage(existingFile2))
    {
        //Add the data
        var ws = package2.Workbook.Worksheets.Add("Content");
        ws.Cells.LoadFromDataTable(datatable, true);

        //The XML String extracted from the orginal excel doc using '= extensionlistnode.OuterXml'
        var cellrange = "A1:C201";
        var rawxml = String.Format(
            "<extLst xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\"><ext uri=\"{{78C0D931-6437-407d-A8EE-F0AAD7539E65}}\" xmlns:x14=\"http://schemas.microsoft.com/office/spreadsheetml/2009/9/main\"><x14:conditionalFormattings><x14:conditionalFormatting xmlns:xm=\"http://schemas.microsoft.com/office/excel/2006/main\"><x14:cfRule type=\"iconSet\" priority=\"2\" id=\"{{CD6B2710-0474-449D-881A-22CFE15D011D}}\"><x14:iconSet iconSet=\"5Arrows\" custom=\"1\"><x14:cfvo type=\"percent\"><xm:f>0</xm:f></x14:cfvo><x14:cfvo type=\"percent\"><xm:f>20</xm:f></x14:cfvo><x14:cfvo type=\"percent\"><xm:f>40</xm:f></x14:cfvo><x14:cfvo type=\"percent\"><xm:f>60</xm:f></x14:cfvo><x14:cfvo type=\"percent\"><xm:f>80</xm:f></x14:cfvo><x14:cfIcon iconSet=\"3Symbols\" iconId=\"0\" /><x14:cfIcon iconSet=\"3TrafficLights1\" iconId=\"0\" /><x14:cfIcon iconSet=\"3Triangles\" iconId=\"0\" /><x14:cfIcon iconSet=\"3Triangles\" iconId=\"1\" /><x14:cfIcon iconSet=\"3Triangles\" iconId=\"2\" /></x14:iconSet></x14:cfRule><xm:sqref>{0}</xm:sqref></x14:conditionalFormatting></x14:conditionalFormattings></ext></extLst>"
            , cellrange);

        var newxdoc = new XmlDocument();
        newxdoc.LoadXml(rawxml);

        //Create the import node and append it to the end of the xml document
        var xdoc2 = ws.WorksheetXml;
        var newnode = xdoc2.ImportNode(newxdoc.FirstChild, true);
        xdoc2.LastChild.AppendChild(newnode);

        package2.Save();
    }
}


text:
Q: Azure Active Directory Spring Boot @AuthenticationPrincipal Following this sample: https://github.com/Azure-Samples/ms-identity-java-spring-tutorial/tree/main/1-Authentication/sign-in
To extract token details, we need to use AuthenticationPrincipal and OidcUser object in a request mapping. See the Sample Controller for an example of this app making use of ID Token claims.
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
//...
@GetMapping(path = "/some_path")
public String tokenDetails(@AuthenticationPrincipal OidcUser principal) {
    Map<String, Object> claims = principal.getIdToken().getClaims();
}

In the sample, there´s a button "Id Token Details" that calls "/some_path"
Screen
How to do this without call a button? Is there a way to do this under the covers?
Any help would be greatly appreciated

A: •   I tried to follow the github documentation link as mentioned by you in your question and successfully created the application as below screenshots display: -
Application.yml file: -

Application build execution: -

Application execution opening in browser: -

Thus, as you can see, it executes successfully and runs the springboot java application successfully. But if you want the 'ID Token Details' button to be not there and in its place, you want to display the ID token details to be shown directly, you would want to change the 'href' button class with the below probable HTML classes and scripts extensions, so that the redirection after logging in to the application will directly display the 'https://jwt.ms' page and it will capture the token and decode it accordingly showing the claims held by the token. Kindly refer to the below link for more detailed information: -
How to create an HTML button that acts like a link
  ' <form action="https://google.com">
     <input type="submit" value="Go to Google" />
      </form> '

The above modifications in the '.html' pages of the application should display you the required token details without the button class in HTML pages.


text:
Q: Date picker ASP.NET c# mvc4 How to add a datepicker for this code:
<fieldset>
        <legend>Search criteria</legend>
        @Html.Label("StartDate", "Start Date:")
        @Html.TextBox("StartDate")
        @Html.Label("enddate", "End Date:")
        @Html.TextBox("enddate")
        <input type="submit" value="Apply" />
    </fieldset>

I want to show a datepicker for startdate and one for end date.
Thank you

A: MVC has a built in class datefield which will, upon entering the field, open a module that will allow them to select a date.
<fieldset>
    <legend>Search criteria</legend>
    @Html.LabelFor( model => Model.StartDate, "Start Date:")
    @Html.TextBoxFor( model => Model.StartDate, new {@class = "datefield"})
    @Html.LabelFor( model => Model.EndDate, "End Date:")
    @Html.TextBoxFor( model => Model.EndDate, new {@class = "datefield"})
    <input type="submit" value="Apply" />
</fieldset>

That should solve it.
Someone mentioned using datepicker via JQueryUI, but datefield is something I believe is supported natively in Microsoft's MVC

A: Html 5 solution
If you are intending to use HTML 5 you can simply specify a type on the input as follows:
@Html.TextBox("StartDate", Model.StartDate, new { @class = "datepicker", @type="date" })

Which would render a date control:

JSFiddle
JQuery UI solution
You could also use Jquery UI for this:
 <fieldset>
    <legend>Search criteria</legend>
    @Html.Label("StartDate", "Start Date:")
    @Html.TextBox("StartDate", string.Empty, new { @class = "datepicker" })
    @Html.Label("enddate", "End Date:")
    @Html.TextBox("enddate", string.Empty, new { @class = "datepicker" })
    <input type="submit" value="Apply" />
</fieldset>

<script>
  $(function() {
    $( ".datepicker" ).datepicker();
  });
</script>

The above adds a datepicker class to the TextBox and then runs the javascript to decorate them.
http://jqueryui.com/datepicker/
pls note I have stuck with Textbox but I would use TextBoxFor instead.
Update
See the working example below.
Dot Net Fiddle

A: Just as a additional point to what Hutchonoid was saying. If you want to do model linking you would do the following using TextBoxFor:
@Html.TextBoxFor(model => model.StartDate, new { @class="datefield", @type="date" })

It is important to include the type in the HTML attributes object that you pass in as the second parameter to TextBoxFor otherwise it will not create the input type of date and it will remain a textbox.
Hope this helps someone out. :-)

A: <fieldset>
    <legend>Search criteria</legend>
    @Html.Label("StartDate", "Start Date:")
    @Html.TextBox("StartDate", string.Empty, new { @class = "datepicker" })
    @Html.Label("enddate", "End Date: enter code here")
    @Html.TextBox("enddate", string.Empty, new { @class = "datepicker" })
    <input type="submit" value="Apply" />
</fieldset>
<script>
  $(function() {
    $( ".datepicker" ).datepicker();
  });
</script>

That should solve it.

A: This is the code that worked for me:
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")

    @Scripts.Render("~/bundles/jqueryui")
    @Styles.Render("~/Content/themes/base/css")

    <script type="text/javascript">
        $(document).ready(function () {
            $("#Dob").datepicker({
                changeMonth: true,
                changeYear: true
            });
        });
    </script>
}


text:
Q: How to get the array keys of arrays inside an array I have a collection that has 2 arrays like on this picture:

So there are:
array 63 has two keys 70 and 72
array 64 has key 71

What i want to do is to get the keys 70, 72, 71.
How to get those keys??

A: Try this:
$keys = [];
$collection->each(function ($item) use (&$keys) {
    $keys = array_merge($keys, array_keys($item));
});

A: $keys = $collection->flatMap(function ($item) {
    return array_keys($item);
});

If you think there may be duplicates, tack on a call to unique at the end:
$keys = $collection->flatMap(function ($item) {
    return array_keys($item);
})->unique();


text:
Q: MIPS - Error when printing data into array So im attempting to put numbers 1-200 in an array. The array is at the bottom of the code. I keep getting errors when i try to print this, can anyone spot the error with me putting in the numbers? The numbers in the array are supposed to go from 1-200, so $t3 increments each time. Any advice would be greatly appreciated.

main:
 .text
  lw $t0, numbers_size # loads the size of the array into the loop
  la $t1, numbers   # $t1 gets the number array
  li $t2, 0    # loop control variable
  li $t3, 1    # value stored inside numbers

  li   $v0, 4
  la   $a0, test_2 # print before loop
  syscall

number_for:
  bge  $t2, $t0, end_for
  sw  $t3, ($t1)

  add $t1, $t1, 4
  add $t2, $t2, 1
  add $t3, $t3, 1

  j number_for
end_for:
  lw $t0, numbers_size # loads the size of the array into the loop
  la $t1, numbers   # $t1 gets the number array
  li $t2, 0    # loop control variable

  j print_numbers

.data
test: .asciiz "Printing numbers:"
test_2: .asciiz "Before loop:"

numbers:
 .word 0:200
numbers_size:
 .word 200

A: This may help you:
.text
main:
    lw $t0, numbers_size    # loads the size of the array into the loop
    la $t1, numbers     # $t1 gets the number array
    li $t2, 0           # loop control variable
    li $t3, 1           # value stored inside numbers

    li $v0, 4
    la $a0, test_2  # print before loop
    syscall
    j number_for
    li $v0, 10
    syscall

number_for:
    bge $t2, $t0 end_for
    sw  $t3, ($t1)

    addi $t1, $t1, 4
    addi $t2, $t2, 1
    addi $t3, $t3, 1

    b number_for

end_for:
    lw $t0, numbers_size    # loads the size of the array into the loop
    li $t1, 0
    li $t2, 0           # loop control variable

buc:
    bge $t2, $t0 end
    lw $a0, numbers($t1) # Printing integer from array
    li $v0,1
    syscall

    la $a0, space   #load a space:  " "
    li $v0, 4       #print string
    syscall

    addi $t1, $t1, 4
    addi $t2, $t2, 1
    b buc

end:
    jr $ra

.data
test: .asciiz "Printing numbers:"
test_2: .asciiz "Before loop:\n"
space: .asciiz " "
numbers_size:
    .word 200
numbers:
    .word 0:200


text:
Q: Dateformat won't parse String I am trying to parse a Date represented as a String. An example of the String would be: 20150724T104139.118+02
There is the parsing code:
DateFormat formatter = new SimpleDateFormat(timestampFormat);
return formatter.parse("yyyyMMdd'T'HHmmss'.'SX");

which throws error:
java.text.ParseException: Unparseable date: "20150724T104139.118+02"
at java.text.DateFormat.parse(DateFormat.java:366)
at

The pattern is the same I use when transforming a Date into that string.

A: parse is expecting the date, not the pattern:
new SimpleDateFormat(datePattern).parse(dateToParse)

A: First of all, you have erroneously swapped the SimpleDateFormat string and the string you want to parse the date from. Also the format string doesn't match the example date. You need S three times for the milliseconds. Try the following :
String text = "20150724T104139.118+02";
DateFormat formatter = new SimpleDateFormat("yyyyMMdd'T'HHmmss'.'SSSX");
Date myTime = formatter.parse(text);

A: tl;dr
As long as you are using SimpleDateFormat,  there is nothing wrong with your pattern, yyyyMMdd'T'HHmmss'.'SX.
Just as an aside, you do NOT need to enclose . within (single) quotes i.e. you can simply use yyyyMMdd'T'HHmmss.SX.
What's the problem then?
The problem is that you are passing the pattern, instead of the date-time string, to SimpleDateFormat#parse. Using your pattern, the following code runs successfully:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    public static void main(String[] args) throws ParseException {
        DateFormat formatter = new SimpleDateFormat("yyyyMMdd'T'HHmmss'.'SX");
        Date date = formatter.parse("20150724T104139.118+02");
        // ...
    }
}

More evidence to prove that there is nothing wrong with your pattern to be used with SimpleDateFormat for parsing:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class Main {
    public static void main(String[] args) throws ParseException {
        DateFormat formatter = new SimpleDateFormat("yyyyMMdd'T'HHmmss'.'SX");
        Date date = formatter.parse("20150724T104139.118+02");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HHmmss'.'SSSX");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+02"));
        System.out.println(sdf.format(date));
    }
}

Output:
20150724T104139.118+02

java.time
Note that the legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.
Demo using modern date-time API:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMMdd'T'HHmmss.SSSX", Locale.ENGLISH);
        OffsetDateTime odt = OffsetDateTime.parse("20150724T104139.118+02", dtf);
        System.out.println(odt);
    }
}

Output:
2015-07-24T10:41:39.118+02:00

In case you need an object of java.util.Date from this object of OffsetDateTime, you can do so as follows:
Date date = Date.from(odt.toInstant());

Learn more about the the modern date-time API* from Trail: Date Time.

* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

A: You can try like this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HHmmss'.'sssX");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));  //Set the timezone as per your env if you want
sdf.parse("yourDate");


text:
Q: how to split a const char*? i have
const char* hour = "Wed Mar 23 18:10:57 2016";

I would like to cut "18:10:57" in another new const char*

A: I think what you are looking for is the std::strtok() function. There is a reference here.
You will need to copy your original data into a temporary area that does not have the const attribute. std::strtok() will split your string up according to the delimiter you specify, in this case a single blank character.
Each successive call to std::strtok() will advance a pointer to the next token in the string.


text:
Q: How to use itenary operator? I have conditional $stateParams on $state and i am trying to assign current $stateParams value to paramId. How can i achieve that task using ternary operator?
commonCtrl.js
 var paramId = $stateParams.processId:? $stateParams.assessmentId;

config.js
.state('app.addPrcChallenge', {
            url: '/add/prcChallenge/:processId/:assessmentId?',
            templateUrl: 'views/process/processChallenge.html',
            controller: 'ProcessChallengesCtrl',
            data: {
                authenticate: true
            },

A: You are close. Try this:
var paramId = $stateParams.processId ? $stateParams.processId : $stateParams.assessmentId;

A: Unfortunately javascript doesn't posses a null coalescing operator like C# does but you could achieve pretty much the same effect with this construct:
var paramId = $stateParams.processId || $stateParams.assessmentId;

Basically this means that paramId will equal to $stateParams.processId if it has some value different than undefined and equal to $stateParams.assessmentId otherwise.


text:
Q: How to handle ragged-list type argument in LibraryLink? Given that I have a ragged list as below,
raggedList = {U1, U2, ..., Un}

where, ui is a sublist($i=1,2,\cdots,n$) and their length are distinct. For example,
raggedList =
  {{0.25, 0.25, 0.5, 0.5, 0.75, 0.75, 0.8},
   {0.21, 0.25, 0.3, 0.6, 0.7, 0.8},
   {0.25, 0.3, 0.7, 0.8};

Namely, raggedList is not a tensor. For this case, obviously, I cannot use MArgument_getMTensor(Args[0]) to get that input.

A: You can't. I mean you can't directly. This is not yet supported in LibraryLink, there is a method to parse it via MathLink(now called WSTP), but that's another story. You can however always flatten your ragged array, store the lengths of each sub-array and pass that as another argument too for later formatting.
Another method would be to pad your array with symbols that you know should not appear as elements of your sub-list, things like -1 if you know the matrix is non-negative.
A lot of things are not supported in LibraryLink others include lists of strings and images.


text:
Q: html add meta tag to header after page loaded I want to dynamically add a meta tag to my html header after the page is loaded. I found some solutions to add a meta tag, but the all only work while the page is loading. After the page is loaded once, the dont work anymore.
document.head.innerHTML += '<meta content="test" property="test"/>';

Thats what I tried. But as sayed above this does not work is the page is already loaded.
Is there a solution for this? Maybe something like reload the page?

A: function ready() {
    document.head.innerHTML += '<meta content="test" property="test"/>';
}
document.addEventListener("DOMContentLoaded", ready);

Maybe event DOMContentLoaded is the solution, source: https://javascript.info/onload-ondomcontentloaded.


text: Q: Implement Java aws lambda layers in serverless.yml I am looking for java solution to aws lambda layers in serverless.yml. I could easily see python, nodejs, .net implementations but couldn't find example for Java. Appreciate an example.


text:
Q: Parsing OpenXML with multiple elements of the same name based on attribute Similar to this question but I need to parse based on specific attribute. How do you select only one of the elements with the same name based on the attribute value?
DECLARE @doc int
EXEC sp_xml_preparedocument @doc OUTPUT, N'
<rootnode>
  <group>
    <id>1</id>
     <anothernode lang="de">first string</anothernode>
     <anothernode lang="en">second string</anothernode>
  </group>
  <group>
    <id>1</id>
     <anothernode lang="en">I</anothernode>
     <anothernode lang="de">Ich</anothernode>
  </group>
</rootnode>'

SELECT *
FROM OPENXML (@doc, 'rootnode/group')
WITH
(
    id int 'id',
    anothernode  varchar(30) 'anothernode'
)

EXEC sp_xml_removedocument @doc

Result is:
1   first string
2   Ich

And I need:
1   second string
2   I

A: After some hacking I found that I can get correct result by doing following SELECT:
SELECT *
FROM OPENXML (@doc, 'rootnode/group')
WITH
(
    id int 'id',
    anothernode  varchar(30) 'anothernode[@lang="en"]'
)

Result is:
1   second string
2   I

Main difference is [@lang="en"], which selects specific attribute value.


text:
Q: Contour plot within upper and lower bounds I have a mathematical function $f(p,q)=10^{-10}\frac{p^4}{q^2}$. I want to make a contour plot within the region where $10^{-3}<f(p,q)<10^{+3}$. I have tried the following three codes (one is similar to this one), but their outputs are different. Could you suggest me a better way to draw the contour plot of that function?
ContourPlot[{If[
   10^-3 < (10^-10* (x^4)/y^2) < 10^3, (10^-10* (x^4)/y^2)]}, {x,
  10^-3, 10^3}, {y, -1, 1}, FrameLabel -> {"p", "q"},
 ContourLabels -> True, PlotLegends -> Automatic]

ContourPlot[{ConditionalExpression[(10^-10* (x^4)/y^2),
   10^-3 < (10^-10* (x^4)/y^2) < 10^3]}, {x, 10^-3, 10^3}, {y, -1, 1},
  FrameLabel -> {"p", "q"}, ContourLabels -> True,
 PlotLegends -> Automatic]

RegionPlot[{10^-3 < (10^-10* (x^4)/y^2) < 10^3}, {x, 10^-3,
  10^3}, {y, -1, 1}, FrameLabel -> {"p", "q"},
 PlotLegends -> Automatic]

A: Something happens near y==0...
As a workaround try
 Show[{ContourPlot[(10^-10*(x^4)/y^2), {x, 10^-3, 1000}, {y, 10^-3, 1},
    PlotPoints -> 100 ,
   RegionFunction ->
    Function[{x, y, z}, 10^-3 < (10^-10*(x^4)/y^2) < 10^3]],
  ContourPlot[(10^-10*(x^4)/y^2), {x, 10^-3, 1000}, {y, -1, -10^-3 },
   PlotPoints -> 100 ,
   RegionFunction ->
    Function[{x, y, z}, 10^-3 < (10^-10*(x^4)/y^2) < 10^3]]},
 PlotRange -> All]

Hope it helps!


text:
Q: How do I automatically ignore empty cells (and adjust their role in a later function) in LibreOffice Calc? Let's say I have a pair of four data points:
A   B   C   D
90  80  70  60
90  90      90

In column E, I hope to have a function, something like:
=((A1*4)+(B1*3)+(C1*2)+(D1))/10

How can I adjust this formula so that, if there is ever an empty cell, the formula automatically removes that cell from the formula? In doing so, this should change the denominator of the final formula; if C is an empty cell, I want to divide the entire formula by 8, not by 10 (since C is counted twice in the ultimate 10-count of the formula).

A: This is what SUMPRODUCT may used for.
=SUMPRODUCT(A1:D1,{4,3,2,1})

will calculate A1*4+B1*3+C1*2+D1*1 and if either A1, B1, C1 or D1 is blank this leads to 0 in 0*n then.
And in
=SUMPRODUCT(NOT(ISBLANK(A1:D1)),{4,3,2,1})

the NOT(ISBLANK(A1:D1) leads to {1,1,1,1} if  A1, B1, C1 and D1 are not blank or it leads to {1,1,0,1} if C1 is blank. So the formula leads to 10 (4+3+2+1) if all are not blank and to 8 (4+3+0+1)  if  C1 is blank.
Putting it all together:
=SUMPRODUCT(A1:D1,{4,3,2,1})/SUMPRODUCT(NOT(ISBLANK(A1:D1)),{4,3,2,1})


text:
Q: Q: How to fix apt-get update error Mirror sync in progress? I have difficulties when install postgresql-client.9.4 on debian 10.
printf "deb http://apt.postgresql.org/pub/repos/apt/ buster-pgdg main" > /etc/apt/sources.list.d/pgdg.list

wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add -

apt-get update && apt-get install -y -qq postgresql-client-9.4

result
oot@8854c7bad7ae:/# apt-get update
Hit:1 http://security-cdn.debian.org/debian-security buster/updates InRelease
Hit:2 http://cdn-fastly.deb.debian.org/debian buster InRelease
Hit:3 http://cdn-fastly.deb.debian.org/debian buster-updates InRelease
Get:4 http://apt.postgresql.org/pub/repos/apt buster-pgdg InRelease [46.2 kB]
Get:5 http://apt.postgresql.org/pub/repos/apt buster-pgdg/main amd64 Packages [138 kB]
Err:5 http://apt.postgresql.org/pub/repos/apt buster-pgdg/main amd64 Packages
  File has unexpected size (137678 != 138126). Mirror sync in progress? [IP: 87.238.57.227 80]
  Hashes of expected file:
   - Filesize:138126 [weak]
   - SHA256:8a5dec4b72ef7e16bb0336a385f5072cb4092d5a935ada6095b5c971a9d3420a
   - SHA1:9d30afef3e3590e5adadabd04845fd547f5f88f7 [weak]
   - MD5Sum:ed36fcbcb7d390b2772bc81a12cf786b [weak]
  Release file created at: Mon, 23 Sep 2019 14:11:10 +0000
Fetched 46.2 kB in 3s (15.7 kB/s)

How to fix this error?

A: Well, you may have actually hit it while the remote mirror was synching... in which case, waiting an hour or so, running apt-get clean (or apt clean) and then re-running the original apt-get update (or apt update).
If the error persists, you may want to notify the mirror provider if you can find a contact address, and then simply point your sources.list to a different mirror.

A: If you are using MacOS to run this virtual machine, the solution to this problem is going to "Screen Time" setting and change the settings to "Unrestricted web access".

A: Helping a student university which was trying to run a simple apt-get update on an ubuntu docker container running on MacOS which was facing the same issue I ended up later finding that this issue was caused by "Screen Time", which is a MacOS Parental Control system, which apparently was blocking "certain" requests to the ubuntu repositories but not all.
Since the "firewall" had some restrictions for "adult sites", at some point when it was trying to fetch a hash from the repo, it would get a "blocked" HTML response from Screen Time on the host. This was especially interesting to me since I didn't think with the whole MacOS VM-based Docker subsystem, the HTTP networking within the container within the VM was subject to control by the host system :\

A: This error can also happen when you have the wrong DNS in your /etc/resolv.conf. In my case, Mirror sync error the first few times I tried to use apt. Then it switched to 'NOSPLIT' error.
Salis answered this problem on askubuntu.com. I made the change in my resolv.conf and the errors were solved.

A: When doing this:
sudo apt-get udpate
sudo apt-get upgrade

I ended up with several "Failed to fetch " lines.
My workaround is thus:
mkdir cache
cd cache
sudo apt-get upgrade -y 2>&1 | grep "Failed to fetch " | awk '{print $5}' | xargs -i{} wget {}

sudo dpkg -i *.deb
sudo apt --fix-broken install
sudo apt-get upgrade -y

It my case it looks like my 'apt-cacher-ng' failed to download / cache some packages properly.

A: Running below command fixed the issue instantly -
sudo apt update -oAcquire::AllowInsecureRepositories=true


text:
Q: How to change message details (email body) in MFMailComposeViewController? I seem to have fallen fowl of something that seems like it should be very simple!
How do I now populate an email's body with the strings a user has entered into NSUserDefaults?
Basically there is a button else ware that enters a sting such as 'YES' into NSUserDetaults. How do I make the email body those stored strings.
This is the code I currently have:
- (IBAction)buttonPressed:(id)sender {
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:@"SYS"];
[controller setMessageBody:@"How do I make this the content of NSUSERDEFAULTS?" isHTML:NO];
controller.navigationBar.barStyle = UIBarStyleBlack;
[self presentViewController:controller animated:YES completion:nil];

Any help would be greatly appreciated!
Thanks!
Using your code the strings appear as : Yes, No, Maybe, No way,
How can I alter the format to make them appear
Yes,
No,
Maybe,
No way.
Thanks again for your time!

A: What you want is a line break character, which can be achieved with \n (newline).
NSArray *storedStrings = [[NSUserDefaults standardUserDefaults] objectForKey:@"yourStoredKey"];
NSMutableString *messageBody = [NSMutableString string];
for (NSString *aString in storedStrings) {
    [messageBody appendFormat:@"%@,\n\n", aString];
}
[messageBody deleteCharactersInRange:NSMakeRange(messageBody.length-3, 3)];
[controller setMessageBody:messageBody isHTML:NO];

That line I added right after the for loop will remove the last three characters from the string, i.e. the two newline characters and the comma.

A: Try this method
- (IBAction)buttonPressed:(id)sender {
MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setSubject:@"SYS"];
[controller setMessageBody:[[nsstring stringwithformat@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"yourStoredKey"]]  isHTML:NO];
controller.navigationBar.barStyle = UIBarStyleBlack;
[self presentViewController:controller animated:YES completion:nil];


text:
Q: Using py_compile.compile() from within a Python script I am trying to understand the docs.
My Python script generates Python code that runs much later, so I want to check now if what I generated is valid.
The docs say py_compile.compile(file[, cfile[, dfile[, doraise]]]) and

If doraise is true, a PyCompileError is raised when an error is encountered while compiling file

So, I tried
source = open(generatedScriptPath, 'rt').read() + '\n'

try:
    import py_compile
    x = py_compile.compile(source, '', '', True)

except py_compile.PyCompileError, e:
    print str(e)

but the inner Exception is never hit, instead an outer Exception is being caught:
Traceback (most recent call last):   File
"H:/code/testgen/testGen.py", line 293, in <module>
    x = py_compile.compile(source, '', '', True)   File   "C:\Python27\lib\py_compile.py", line 106, in compile
    with open(file, 'U') as f: IOError: [Errno 2] No such file or   directory: '# This script was auto-generated  ...

How can I fix this? Note that I am open to alternatives, I just want to ask the simplest way. "Is the code I just generated syntactically valid Python?"

A: Read the error message: "No such file or directory".  The first argument is supposed to be a file name to open.  Or read the docs: "The source code is loaded from the file name /file/."  You might prefer the "compile" builtin, which can compile a string of Python.


text:
Q: Problem \include-ing multiple .tex files I am \include-ing multiple .tex files and I am using a package I found on the web for a one-column abstract in a two-column document (long2.sty):
%%
%% This is file `long2.sty'.
%%
%% Author: Tomas "tohecz" Hejda <tohecz@gmail.com>
%%
%% Licenced under LaTeX-Project Public License version 1.3 or newer.
%%
\NeedsTeXFormat{LaTeX2e}[1995/06/01]
\ProvidesPackage{long2}[2012/08/19 v0.1 long2: breakable one-column preamble in a two-column document]

\newlength\longtwo@top
\newlength\longtwo@bottom

\newsavebox\longtwo@box
\def\longtwo@repeat{%
    \longtwo@column[{\@twocolumnfalse
    \ifdim\ht\longtwo@box>1.00\textheight%1
      \begingroup
      \vbadness10000
      \setbox0\vsplit\longtwo@box to 1.00\textheight%1
      \setbox1\vbox{\unvbox\longtwo@box}
      \global\setbox\longtwo@box\vbox{\unvbox1}
      \setbox2\vbox to \textheight{%
        \unvbox0
      }
      \ht2=0.9\textheight
      \box2
      \endgroup
    \else
      \ifdim\ht\longtwo@box>0.84\textheight
        \global\let\longtwo@repeat\clearpage
      \else
        \global\let\longtwo@repeat\relax
      \fi
      \unvbox\longtwo@box
      \vspace{15pt plus 15pt}
    \fi
    }]%
  \longtwo@repeat
}

\long\def\longtwo@[#1]{%
  \begingroup
    \let\longtwo@column\twocolumn
    \let\longtwo@mkttl\maketitle
    \def\maketitle{
      \begingroup
      \let\newpage\relax
      \longtwo@mkttl
      \endgroup
    }
    \longtwo@column[{\@twocolumnfalse
    \global\setbox\longtwo@box\vbox{#1}%
    \ifdim\ht\longtwo@box>\textheight
      \begingroup
      \vbadness10000
      \setbox0\vsplit\longtwo@box to 1.00\textheight%1
      \setbox1\vbox{\unvbox\longtwo@box}%
      \global\setbox\longtwo@box\vbox{\unvbox1}%
      \setbox2\vbox to \textheight{%
        \unvbox0
      }
      \ht2=0.9\textheight
      \box2
      \endgroup
    \else
      \ifdim\ht\longtwo@box>0.87\textheight
        \global\let\longtwo@repeat\clearpage
      \else
        \global\let\longtwo@repeat\relax
      \fi
      \unvbox\longtwo@box
    \fi
    }]%
    \longtwo@repeat
  \endgroup
}

\def\longtwocolumn{\@ifnextchar[\longtwo@\twocolumn}

\endinput
%%
%% End of file `long2.sty'.
%%

The first \include works great, but the abstract of the others gets overlapped the text. Any idea? Is there a way to tell LaTeX to reset everything and start a new document inside another each time I \include a file?
long2.sty is capable of splitting too long abstracts in two pages. That's why I use it.
My code is not very complex, the part with the \include is:
[...]
\pagestyle{fancy}
\clearpage
\resetearcontadores
\include{file1}
\resetearcontadores
\include{file2}
\resetearcontadores
\include{file3}
\resetearcontadores
\include{file4}
\clearpage
\pagestyle{empty}
[...]

The \resetearcontadores command just resets figure, table, etc counters. If you need more code (preamble, body or something) ask me, I just don't know what to show you because the code is very simple.
I know the \twocolumn command accepts an optional argument, but it doesn't split into pages and you can't use any environments.

A: Initial typesetting of section 2.

It would really have helped if you had provided a complete document, as below, to save anyone trying to help having to make one and then try to guess the problem that you are seeing. However...
The problem is unrelated to \include you see the same with \input or in fact with the content all being in one file, however the example below uses include.
The long2 code is clearly aimed at making titlepages and like most LaTeX title handling it is not designed to be used multiple times, as it redefines itself during use.
However if you save an initial definition after loading the package and reset it before each use, it appears to work OK.
Document after adding code to resetting \longtwo@repeat.

\begin{filecontents}{\jobname a.tex}
\begin{longabstract}
AAAAAA AAAAAA AAAAAA
\c

\b\b\c
\end{longabstract}
\section{Something}
\a\a\a\c\b
\end{filecontents}
\begin{filecontents}{\jobname b.tex}
\begin{longabstract}
BBB BBB BBB
\c

\a\a\a\c\b
\end{longabstract}
\section{Something Else}
SSS SSS SSS SSS SSS
\b\c\b\a\a\a
\end{filecontents}

\documentclass[twocolumn,a5paper]{article}
\pdfpagewidth\paperwidth
\pdfpageheight\paperheight
\usepackage{long2,environ}
\def\a{\stepcounter{enumi}One two three four five \roman{enumi}. }
\def\b{Red yellow blue green purple orange. \a\a\a\a}
\def\c{\b\b\a Monday tuesday wednesday thursday friday saturday sunday.
\b\b\b\a England France Germany Spain Poland Canada. \b\b}

\makeatletter
\let\xlongtwo@repeat\longtwo@repeat

\NewEnviron{longabstract}
{\let\longtwo@repeat\xlongtwo@repeat
 \longtwocolumn[\begin{abstract}\BODY\end{abstract}]}{}

\makeatother

\begin{document}
\include{\jobname a}
\include{\jobname b}
\end{document}


text:
Q: How to put these 3 pictures to the left and 3 pictures to the right? I have 6 images in a row and I want to position 3 to the left and 3 to the right.  I tried display: flex and float:left however it just bumped up all the content beneath the section tab up overlapping displays.  How do I split the 6 images in half with text in the middle?

        ***String of Text***

CSS
.open-text > h1 {
    color: #1e3a87;
    border-top: 1px solid white;
    margin-top: 12.5px !important;
    height: 10rem;
    display: flex !important;
    align-items: center !important;
    mix-blend-mode: color-burn;
    display: flex !important;
    align-items: center !important;
    font-family: 'Cinzel Decorative', cursive;
}
.open-text > h1 {
    /*border: 4px solid red;*/
    /*display: flex;*/
    /*justify-content: space-around;*/
    /*float: left;*/
}
.open-text > h1:nth-child(odd) {
    border: 1px solid red;
    /*float: right;*/
}

A: If I understand your question correctly, perhaps this would work for you?
Keep in mind that I've replaced className with class so that the sample below works - remember to revert this if you're rendering this out via JSX:

.open-text > h1 {
    height: 10rem;
    align-items: center;
    justify-content:center; /* Cause "vertical" center alignment */
    flex-direction:row; /* Spread children of h1 along the x-axis */
    display: flex;
}

.open-text > h1 > img {
    flex:1;  /* This causes the image elements to squish down so that
                text comfortably fits */

}

        ***String of Text***

A: Use class="" for class names in html
It can be done using flexbox by seeting the parent to align center items, then you set each item to float accordingly inside your flex box, align-self : start for the left ones, and align-self:end; for the right ones.
Here's an example of how i would ghave done it :

.open-text {
  display:flex;
  align-items:center;
  justify-content:space-around;
}
.open-text h1 {
color: #1e3a87;
display: flex;
align-items: center;
font-family: 'Cinzel Decorative', cursive;
justify-content:space-around;
}
.open-text img {
margin:5px;
}
.open-text .move_to_left {
  align-self:start;
}
.open-text .move_to_right {
  align-self:end;
}
.open-text .string_of_text {
  align-self:center;
}

      ***String of Text***

A: The easiest way to accomplish this is by using the inline-block display property. Here is an example using some colored divs, but it will work the same on your images.
display: inline-block;

JSFiddle: https://jsfiddle.net/chnbL179/


text:
Q: R matching two columns in the same data.frame How can I combind two columns in the same data frame into one column, a simple example would be:
a <- data.frame(id = 1:3, v1 = c('a', NA, NA), v2 = c(NA, 'b', 'c'))
a
  id  v1   v2
   1  a   <NA>
   2 <NA>  b
   3 <NA>  c

And the output I need would be look like this:
a
  id  v1   v2   v3
   1  a   <NA>   a
   2 <NA>  b     b
   3 <NA>  c     c

I found a similar post join matching columns in a data.frame or data.table, but I can not figure it out with my own case, please help, thanks

A: It's not clear exactly what you want.  What happens if v1 and v2 have different values?
This method will prefer the value of v1
a <- data.frame(id = 1:4, v1 = c('a', NA, NA,'d'), v2 = c(NA, 'b', 'c','e'))

a <- as.data.table(a)
a[,v3 := v1]
a[is.na(v1), v3 := v2]

Using traditional data.frame methods:
a$v3 <- as.character(a$v1)
a[is.na(a$v1),"v3"] <- as.character(a[is.na(a$v1),"v2"])

A: Hmm, ifelse() maybe?
> a <- data.frame(id = 1:3, v1 = c('a', NA, NA), v2 = c(NA, 'b', 'c'),
                  stringsAsFactors=FALSE)
> a$v3 <- ifelse(is.na(a$v1), a$v2, a$v1)
> a
  id   v1   v2 v3
1  1    a <NA>  a
2  2 <NA>    b  b
3  3 <NA>    c  c


text:
Q: Deploy linux binaries without internet access and without root? boundaries:

*

*I have a Linux64 (Redhat 6.8) test-server here which I can access via FTP in our intranet. This server has no access to the internet.

*I want to use an SVN command line client and Python with cx_Oracle and an oracle client on that machine

*I don't have root access.

*I don't have much idea of Linux

I thought I will start with the easiest thing which was SVN in my opinion:
My first guess was, that I could just download the binaries for SVN for Redhat 6 on my windows machine and copy them to the Linux machine using FTP.
But what I found here was "yum install subversion" (which does not work due to missing root and internet access) and a file "subversion_installer_1.9.sh" that I got from WANdisco (but which also needs root and internet access again).
Why is that so complicated? I come from a windows world and I am a little bit disappointed at the moment, because I always thought that stuff like this should work quite easy on LINUX (just copying binaries and you are good to go).
What do I overlook?
How would you do that?

A: You can "install" Subversion and Python and cx_Oracle without root access but since you are straying outside of the "normal" approach to things you will find it much more difficult than if you simply followed the "normal" approach. And the "normal" approach is to use a package manager (like yum) which requires root access. The Windows approach is simply different. There have been many arguments over which is "better" but I won't get into that here!

A: Installing something on Linux is as easy as copying binaries.  The difficulty lies with getting the right binaries to copy.  Unlike Windows where the system API (kernel32.dll/user32.dll/gdi32.dll) is extremely consistent and highly compatible between versions, Linux distributions have multiple system APIs (glibc, newlib, uclibc) and more frequent ABI breakage the n in libc.so.n changes.
When you download binaries from a repository hosted by your distribution maintainer, you know that they are built to use the same versions of the various dependencies as every other binary on your system.  There's no such guarantee for binaries obtained from the developer, who may use a totally different distribution.
So the common thing for open source projects such as subversion is to obtain an archive of the source code from the developer, unpack it, run ./configure to customize the makefiles for the system libraries on your system, make to build binaries that use your distro's particular flavor of system libraries, and make install DESTDIR=~/somesoft to install in any directory you have write access to.


text:
Q: WildFly 10 - Caused by: java.lang.NoClassDefFoundError: Failed to link org/apache/maven/settings/building/SettingsSource Been trying to move an application up to WF 10.0 Adding some new maven dependencies.
I have been adding jars to the modules dir and updating the modules.xml file.  This has worked for everything so far, then I hit this.  Ideas?
The Error

Caused by: java.lang.NoClassDefFoundError: Failed to link
org/apache/maven/settings/building/SettingsSource (Module
\"org.apache.maven\" from local module loader @3f49dace (finder:
local module finder @1e397ed7 (roots:
/opt/ngp/wildfly-18.0.1.Final/modules,/opt/ngp/wildfly-18.0.1.Final/modules/system/layers/brms,/opt/ngp/wildfly-18.0.1.Final/modules/system/layers/soa,/opt/ngp/wildfly-18.0.1.Final/modules/system/layers/base))):
org/apache/maven/building/Source"

My modules
My modules.xml file in /opt/ngp/wildfly-18.0.1.Final/modules/system/layers/brms/org/apache/maven/main
ROOT:1124 - main> cat module.xml
<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="org.apache.maven" slot="main">
  <resources>
    <resource-root path="maven-model-3.6.3.jar"/>
    <resource-root path="maven-model-builder-3.6.3.jar"/>
    <resource-root path="maven-repository-metadata-3.6.3.jar"/>
    <resource-root path="maven-resolver-api-1.6.1.jar"/>
    <resource-root path="maven-resolver-impl-1.6.1.jar"/>
    <resource-root path="maven-resolver-provider-3.6.3.jar"/>
    <resource-root path="maven-resolver-spi-1.6.1.jar"/>
    <resource-root path="maven-resolver-util-1.6.1.jar"/>
    <resource-root path="maven-settings-builder-3.6.3.jar"/>
  </resources>

  <dependencies>
    <module name="javax.api" export="false" slot="main" services="import" optional="false"/>
    <module name="org.apache.maven.wagon" export="false" slot="main" services="import" optional="false"/>
    <module name="org.codehouse.plexus" export="false" slot="main" services="import" optional="false"/>
    <module name="org.sonatype.aether" export="false" slot="main" services="import" optional="false"/>
    <module name="org.sonatype.plexus" export="false" slot="main" services="import" optional="false"/>
    <module name="org.sonatype.sisu" export="false" slot="main" services="import" optional="false"/>
  </dependencies>
</module>

The class is there
jar tf maven-settings-builder-3.6.3.jar | grep SettingsSource
org/apache/maven/settings/building/FileSettingsSource.class
> org/apache/maven/settings/building/SettingsSource.class
org/apache/maven/settings/building/StringSettingsSource.class
org/apache/maven/settings/building/UrlSettingsSource.class

A: So it was a versioning thing.  While the class was there, the signature did not match.
Would have been nice if the error message would have been a bit more specific.
maven-aether-provider-3.2.5.jar
maven-artifact-3.2.5.jar
maven-compat-3.2.5.jar
maven-core-3.2.5.jar
maven-model-3.2.5.jar
maven-model-builder-3.2.5.jar
maven-plugin-api-3.2.5.jar
maven-repository-metadata-3.2.5.jar
maven-settings-3.2.5.jar
maven-settings-builder-3.2.5.jar
module.xml
<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.1" name="org.apache.maven" slot="main">

    <resources>
                        <resource-root path="maven-aether-provider-3.2.5.jar"/>
                        <resource-root path="maven-artifact-3.2.5.jar"/>
                        <resource-root path="maven-compat-3.2.5.jar"/>
                        <resource-root path="maven-core-3.2.5.jar"/>
                        <resource-root path="maven-model-builder-3.2.5.jar"/>
                        <resource-root path="maven-model-3.2.5.jar"/>
                        <resource-root path="maven-plugin-api-3.2.5.jar"/>
                        <resource-root path="maven-repository-metadata-3.2.5.jar"/>
                        <resource-root path="maven-settings-builder-3.2.5.jar"/>
                        <resource-root path="maven-settings-3.2.5.jar"/>
              </resources>

    <dependencies>
                    <module name="javax.api" export="false" slot="main" services="import" optional="false"/>
                    <module name="org.apache.maven.wagon" export="false" slot="main" services="import" optional="false"/>
                    <!--<module name="org.codehaus.plexus" export="false" slot="main" services="import" optional="false"/>-->
                    <!--<module name="org.sonatype.aether" export="false" slot="main" services="import" optional="false"/>-->
                     <module name="org.eclipse.aether" export="false" slot="main" services="import" optional="false"/>
                     <module name="org.sonatype.plexus" export="false" slot="main" services="import" optional="false"/>
                     <module name="org.sonatype.sisu" export="false" slot="main" services="import" optional="false"/>
                     <module name="org.eclipse.sisu"/>
                     <module name="com.google.guava" />
              </dependencies>
  </module>


text:
Q: stop faces message being added again in restore view I add some faces message in the post construct.
but when there is navigation from the current page the postconstruct is called again  during restore view phase and adds the faces message again.
is there a way to prevent the faces message from being added during restore phase?
I can check the phase id and not add the message.
but is that the right way ? is there any other way?


text:
Q: PHP syntax error, unexpected '"', expecting T_STRING or T_VARIABLE or T_NUM_STRING Following code gives me the error.
    <?php
echo "$lang_menu["prefs"]";
?>

I'm pretty sure it has something to do with me requesting 2 php variables, no idea how to solve.

A: Replace with
<?php

echo "".$lang_menu['prefs']."";

?>

A: $variables splitted with quotes " :
echo "".$lang_menu['prefs']."";

A: Use this:
<?php
echo "".$lang_menu["prefs"]."";
?>

A: Try this
<?php
 echo "".$lang_menu['prefs']."";
?>

A: Obviously, you cannot write unescaped double quotes in a double-quoted string. And I'd advise against writing unescaped text into HTML and URLs. Try this:
<?php
echo '' . htmlspecialchars($lang_menu["prefs"]) . '';
?>

Edit: A couple of clarifications...

*

*These are valid strings:
$foo = "Hello, World!";
$foo = "Hello, 'World!'";
$foo = "Hello, \"World!\"";

This is not:
$foo = "Hello, "World!"";

*SQL injection, as the word suggests, refers to the database query language called SQL. This code does not contain SQL and it does not interact at all with any database.
So it's nothing about dots or SQL injection. It's about certain characters that have a special meaning in certain semantic contexts. It's about text within text.


text:
Q: Easy to setup, multi-threaded server for my Django Piston API I am writing an API that reads from MySQL and Solr (which can give latencies of 150ms) to provide formatted output. I will be hosting this on a VPS, and I need to choose a web server for this application. It will be used only within localhost (and local LAN in future).
I have these concerns:

*

*Launches multiple worker threads to minimize bottlenecks with consurrent requests (Solr can take 150ms to return a request)

*Can easily respawn when a component crashes and restarting is just a matter of servd -restart

*deploying a new application is as simple as copying a folder to the www directory (or equivalent) so that new requests to this app will be served from then on.

I am not optimizing for performance for now, so I need something easy to setup. And is #3 not possible for a non-load balanced Django app?

A: Gunicorn is very simple to deploy and manage. It has no built-in reloading capability but you could easily use an external utility such as watchdog to monitor a directory and reload gunicorn using kill -HUP <pid>.


text:
Q: Codeigniter Login Script I have a question regarding my codeigniter login script. It's not very complex but it works great. My question is, when a user is logged they get redirected to another part of my website, which is what I want but if that user loggs out, they or (anyone for that matter) still has access to the logged in URL. How do I make it so the URL is private?
For example, anyone has access to the below URL. How do I make sure the URL is private?
mywebsite.com/_states/site/members_area
Thanks Everyone
Site Controller
function validate_credentials()
{
  $this->load->model('model_data');
  $query = $this->model_data->validate_users();
   if($query){
      $data = array(
         'username' => $this->input->post('username'),
         'email' => 'johndoe@some-site.com',
         'is_logged_in' => TRUE
       );
       $this->session->set_userdata($data);

       redirect('site/members_area',$data);
   } else {
      $this->login();
   }

}

Model_data extends CI_Model
function validate_users()
{
  $this->db->where('username', $this->input->post('username'));
  $this->db->where('password', md5($this->input->post('password')));
  $query = $this->db->get('members');

  if ($query->num_rows == 0){
   }

  if ($query->num_rows == 1){
      return true;
   }
}

members_area URL
<?php

echo 'Welcome!'.'
';

$session_id = $this->session->userdata('session_id').'
';
$whatever = $this->session->userdata('is_logged_in').'
';
$email = $this->session->userdata('email').'
';
$username = $this->session->userdata('username').'
';

echo 'This is the session ID = '."$session_id".'
';
echo 'This is the boolean, 1 means true = User Logged In = '."$whatever".'
';
echo 'This is the user "foo" email = '."$email".'
';
echo 'This is the user username = '."$username".'
';
echo anchor('site/logout', 'Logout!');

?>

A: You need to check if the session variable is set:
if($this->session->userdata('is_logged_in')) {
    // The user has logged in
}


text:
Q: Implementing a package returns: Module util does not exist in the Haste module map I am trying to implement this package into my project https://www.npmjs.com/package/feedparser I have literally copy-pasted the example code.
The only thing I changed is

import FeedParser  from 'feedparser';

As a result, I get an error in my metro builder:

Unable to resolve module util
  from/Volumes/DEV-DRIVE/jaco/test/NieuwsApp/node_modules/feedparser/lib/feedparser/index.js:
  Module util does not exist in the Haste module map.

Any Ideas on how to solve this?

A: util is part of the node.js api. feedparser is designed to run in node.js not react native. You may be able to make it work regardless by installing the util package from npm.
npm i --save-dev util


text:
Q: Giving colors to buildings in CityEngine? I am new to CityEngine and using trial version 2011.2.I want to know how the colors are given to buildings?

Cga rule file for buildings I have written is :-
*/

version "2011.2"

attr BUILD_HEIGHT=0

attr Mass_Color = "#ffaa33"

attr opacityvalue=0.6

@StartRule

Lot-->

   extrude(BUILD_HEIGHT)

   color(Mass_Color)

   set(material.opacity,opacityvalue)

Is there something I am doing wrong or missing ?

A: It looks like you need to change color(Mass_Color)
For instance, color("#F00100″) for red.
CityEngine Tutorial Series: Attributes, Rules, and Base Color  has a useful guide.

A: I can't test your cga in 2011.2 but with 2014.1 your code works as expected (colors the buildings).
You could try to use the other usage way of color, i.e. color(255, 170, 51).


text:
Q: How to use csplit command to split a log file by day? I have a log file like bellow:
Jan 01  This the log of this day.
Jan 01  This the log of this day.
Jan 01  This the log of this day.
Jan 01  This the log of this day.
Jan 01  This the log of this day.
Jan 01  This the log of this day.
Jan 01  This the log of this day.
Jan 01  This the log of this day.
Jan 01  This the log of this day.
Jan 01  This the log of this day.
Jan 02  This the log of this day.
Jan 02  This the log of this day.
Jan 02  This the log of this day.
Jan 02  This the log of this day.
Jan 02  This the log of this day.
Jan 02  This the log of this day.
Jan 02  This the log of this day.
Jan 02  This the log of this day.
Jan 02  This the log of this day.
Jan 02  This the log of this day.
Jan 02  This the log of this day.
Jan 03  This the log of this day.
Jan 03  This the log of this day.
Jan 03  This the log of this day.
Jan 03  This the log of this day.
Jan 03  This the log of this day.
Jan 03  This the log of this day.
Jan 03  This the log of this day.
Jan 03  This the log of this day.
Jan 03  This the log of this day.
Jan 03  This the log of this day.
Jan 03  This the log of this day.

How could I split the file by day? I used command:
csplit log /*Jan 01*/ /*Jan 02*/ /*Jan 03*/
but there is error:
csplit: /*Jan: closing delimiter '/' missing

So anyone could please tell me how to fix this? Thanks in advance.

A: The shell sees /*Jan as one argument, and 01*/ as another, and so on.  You need to quote the arguments that have embedded spaces.
csplit log '/*Jan 01*/' '/*Jan 02*/' '/*Jan 03*/'


text:
Q: C - calloc() v. malloc()
Possible Duplicate:
c difference between malloc and calloc

Please explain the significance of this statement,

Another
  difference between the malloc() and
  calloc() functions is that the memory
  allocated by malloc( ) function
  contains garbage values, while memory
  allocated by calloc( ) function
  contains all zeros.

Source ('C' Programming, Salim Y. Amdani)
Thanks

A: calloc(...) is basically malloc + memset(if you want to 0 initialise the memory)
ptr = malloc(sizeof(struct fubar));
memset(ptr, 0, sizeof (struct fubar)); //here we could use some different value instead of 0 whereas calloc always 0 initialises.

When you use malloc to allocate some memory, it's previous contents are not cleared (ie not initialized). You might get random values that were set when machine booted up or you might see some of the memory that belonged to previously running programs but was left uncleared after allocation and program exit.
calloc itself is slower than malloc because you have to spend some time to clear the contents of allocated memory. So if you just need to allocate some memory and then copy some stuff there, you are free to use malloc.

A: From http://wiki.answers.com/Q/Is_it_better_to_use_malloc_or_calloc_to_allocate_memory
malloc() is faster, since calloc() initializes the allocated memory to contain all zeros.  Since you typically would want to use and initialize the memory yourself, this additional benefit of calloc() may not be necessary.

A: It just means that if you allocate memory, with calloc(), whatever you allocate is 0.  i.e. if you allocated space for an array of integers, they'd all be set to 0, whereas with malloc(), the memory there isn't initialized in any way.
You could use calloc in situations where you are just going to do a memset of 0 to the memory anyway.

A: calloc is initializing the memory before you use it, but malloc does not.
Refer to this link:

The calloc() function shall allocate
  unused space for an array of nelem
  elements each of whose size in bytes
  is elsize. The space shall be
  initialized to all bits 0.

With malloc, if you want to guarantee the same effect you'd have to call something like memset to reset the memory, e.g.
char* buffer = (char*)malloc(100);
memset(buffer,0,100);

calloc saves you that extra step.
The significance of initializing memory is that you are getting a variable to a known state rather than an unknown one. So if you are checking a variable, say an array element, for an expected value, then by having pre-initialized the variable ahead of time, you can be sure that the value you are checking isn't garbage. In other words, you can distinguish between garbage and legitimate values.
For example, if you just leave garbage in the variable and you are checking for some value, say 42, then you have no way of knowing if the value was really set to 42 by your program, or if that's just some garbage leftover because you didn't initialize it.


text:
Q: Iron-Router infinite loop onBeforeAction since Meteor 1.0, I have an infinite loop in the hook onBeforeAction. (create_game is called forever)
onBeforeAction: function(){

if(Meteor.userId()){

  Meteor.call('create_game', this.params._id, 1, function(error, result){
    if (error)
    console.log(error);
    else{
     game_sus = result;
     Session.set('gamesolo_id', game_sus);
   }
  });
}
this.next();

},

waitOn: function() { return Meteor.subscribe('game', Session.get('gamesolo_id))}

The infinite loop is due to the session variable cause if I remove it, I do not enter in a loop. I don't know if it's a bug due to the new version or what, but do you have any idea how could I fix this?
I tried with a global variable instead of a session variable, but I do not subscribe with that way.

A: onBeforeAction is reactive so if You set the Session variable in Meteor.call callback then onBeforeAction will run again
you can use onRun for this Session setup


text:
Q: onPause() and onResume() functions while designing the home screen I am designing an Home Screen in which I am showing the applist in a gridview.
There are some animation in the 1st screen of my HOMESCREEN and when you press on a button then a grid is shown.
So, the problem is that;
1)).I opened an application from the gridview,it opens normally but when i exit from that particular application,the BACKButton takes me to the screen of GridView.(It is OKAY).
Now,When I press the HOME Button,It is doing the same work as it does on BACKBUTTON.
I am listening to these butons using dispatchKeyEvent(KeyEvent event) but it is not working with home button..
Logically ,I should not work because this dispatchKeyEvent(KeyEvent event) works for my application not for any other application..
I found some other paths to resolve this problem,
When i open other apps,onPause() and onStop() functions are called in my homescreen,suppose I set a flag over there but by doing this How will I be able to know that after doing his stuff in OTher application user presses HOME BUTTON or BACK BUTTON.

A: You should declare your home activity look like below code
 <activity
            android:name="com.android.launcher2.Launcher"
            android:launchMode="singleTask"
            android:clearTaskOnLaunch="true"
            android:stateNotNeeded="true"
            android:theme="@style/Theme"
            android:windowSoftInputMode="stateUnspecified|adjustPan"
            android:configChanges="locale">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.HOME" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.MONKEY"/>
            </intent-filter>
        </activity>

and declare gridactivity as a normal activity in Manifest
I hope you got solution.

A: dispatchKeyEvent(KeyEvent event) won't be able to catch Home button click. if you want to capture Home button click use onUserLeaveHint().
And to capture back button specifically use onBackPressed().


text:
Q: move files that have the same name of the file they contain Someone very clever (feel irony?) has extracted more than 6000 archives in their own directories, but sometimes the archive contain one file: the same name of the directory it contains.
Example:
mydir(0001)/mydir(0001).txt
mydir(ZREZ)/mydir(ZREZ).txt
mydir(AAEZ)/mydir(AAREZ).txt
mydir(AAEZ)/otherfile.txt
mydir(QQQQ)/mydir(QQQQ).txt
...

Is there a fast way (Unix shell) to compare the file (if there's only one file) and the directory where it's in, and if it's the same (without the extension), move it one directory above and remove the (now empty) directory?
So I should get:
mydir(0001).txt
mydir(ZREZ).txt
mydir(AAEZ)/mydir(AAREZ).txt
mydir(AAEZ)/otherfile.txt
mydir(QQQQ).txt
...

A: You can use a script like this from the parent directory of all those 6000 directories/files:
while IFS= read -d '' -r d; do
    n=$(find "$d" -maxdepth 1 -type f -exec echo . \; | wc -l)
    f="${d}/${d}.txt"
    [[ $n -eq 1 && -f "$f" ]] && mv "$f" "$d/../" && rmdir "$d"
done < <(find . -type d ! -name '.' -print0)

A: This should do the trick. A bit simpler than anubhava's script, but still careful about only moving files and removing dirs if that's the only content.
for x in *; do
  if [[ $(find "$x" | sed 1d | head -n2) == "$x/$x.txt" ]]; then
    mv "$x/$x.txt" . && rmdir "$x"
  fi
done

You can cut-n-paste this to the command line in the parent dir. It loops over all files in that dir (for x in *) and if any of them is itself a directory containing only the single file $x/$x.txt then it will move the file and remove the directory.

A: Here's my script, based on Anubhava's first answer. Sorry for the beginner's style:
#!/bin/bash
# loop & print a folder recusively,
folder_recurse() {
    for i in "$1"/*;do
        if [ -d "$i" ];then
            n=$(find "$i" -maxdepth 1 -exec echo . \; | wc -l)
            d=$(readlink -f "${i}")
            g=$d"/"$(basename "$i")".epub"
            if [[ $n -eq 2 && -f "$g" ]]; then
                echo "Doing: $i"
                mv "$g" "$d/.."
                rmdir "$d"
            fi
            folder_recurse "$i"
    done
}

# try get path from param
path=""
if [ -d "$1" ]; then
    path=$1;
else
    path="/tmp"
fi

echo "base path: $path"
folder_recurse $path

A: You can do it with a one-liner within the parent directory:
for i in */*; do [ -f "${i%/*}/${i%/*}.txt" ] && mv "$i" . && rm -d "${i%/*}"; done

Since there has been interest in a solution that function equally on BSD where there is no rm -d, the same can be accomplished with:
for i in */*; do [ -f "${i%/*}/${i%/*}.txt" ] && mv "$i" . && [ -z "$(ls -A "${i%/*}")" ] && rm -r "${i%/*}"; done

Which, following the mv check whether the remaining directory is empty, and if so, then removes the directory, otherwise leaving the directory unchanged.
output:
drwxr-xr-x 2 david david 4096 Aug 25 16:20 mydir(AAEZ)
-rw-r--r-- 1 david david    0 Aug 25 16:20 mydir(0001).txt
-rw-r--r-- 1 david david    0 Aug 25 16:20 mydir(QQQQ).txt
-rw-r--r-- 1 david david    0 Aug 25 16:20 mydir(ZREZ).txt

mydir\(AAEZ\)/
-rw-r--r-- 1 david david    0 Aug 25 16:20 mydir(AAREZ).txt
-rw-r--r-- 1 david david    0 Aug 25 16:20 otherfile.txt

If needed, you can also test that the directory is empty after moving the file -- before deleting the directory. Shown