text:
Q: Haskell - My own zip3 function Is there a better way to re-create this function? It compiles fine.
This is what I have:
zip3' :: [a] -> [b] -> [c] -> [(a,b,c)]
zip3' [] _ _ = []
zip3' _ [] _ = []
zip3' _ _ [] = []
zip3' (a:as) (b:bs) (c:cs) = (a,b,c) : zip3' as bs cs

I'm just wondering if there is a better way to summarize this:
zip3' [] _ _ = []
zip3' _ [] _ = []
zip3' _ _ [] = []

A: There's nothing inherently wrong with your approach, but you can collapse the first three cases into a catch-all at the end.
zip3' :: [a] -> [b] -> [c] -> [(a,b,c)]
zip3' (a:as) (b:bs) (c:cs) = (a,b,c) : zip3' as bs cs
zip3' _ _ _ = []

In fact, this is how GHC does it.

A: It works fine. If you want to make the program shorter, you can write:
zip3' :: [a] -> [b] -> [c] -> [(a,b,c)]
zip3' (a:as) (b:bs) (c:cs) = (a,b,c) : zip3' as bs cs
zip3' _      _      _ = []

Since the first line will only fail to fire if there is at least one of the three lists that is not (_:_) (so []). But this is sometimes seen as an anti-pattern, since in a very unlike event that one adds a constructor to the list data type, this might end up with an empty list (whereas in that case, we perhaps better get an error). I agree that for lists this is close to impossible: a lot of libraries and programs would no longer work. But in general it is not uncommon that you for instance design a data type, and later change your mind and add an extra constructor.
If we inspect the source code of zip3 :: [a] -> [b] -> [c] -> [(a,b,c)], then we see it is implemented that way [source]:

zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
-- Specification
-- zip3 =  zipWith3 (,,)
zip3 (a:as) (b:bs) (c:cs) = (a,b,c) : zip3 as bs cs
zip3 _      _      _      = []

For some reason zip itself is implemented in the "question" style [source]:

zip :: [a] -> [b] -> [(a,b)]
zip []     _bs    = []
zip _as    []     = []
zip (a:as) (b:bs) = (a,b) : zip as bs


text:
Q: Jquery option add url to button I am trying to get the following to work, but for some reason it isn't and I just can't seem to see why. What I am trying to do is when someone selects an option in the form, it applies the download url to the button.
    <form class="form-horizontal">
          <select class="relationship" id="Relationship">
          <option>Select Form</option>
          <option>for me</option>
          <option>for another</option>
          </select>

     Download Form
</form>

A: Try changing the download href dynamically instead using attr.
$(function(){
    $(".relationship").on('change', function(){
        if( $(this).val() == "for me" ) {
            $("a.download").attr('href', 'form1.pdf');
        }

        else if ($(this).val() == "for another") {
            $("a.download").attr('href', 'form2.pdf');
        }
    });
});

And the fiddle

A: $(document).ready(function(){
    $('.download').click(function(e){
        e.preventDefault();
        window.location = ($('.relationship').val() == 'for me') ? 'form1.pdf' : 'form2.pdf';
    });
});

A: You must cpecify options value in the select like this:
<form class="form-horizontal">
  <select class="relationship" id="Relationship" onchange="$('.download').attr('href', $(this).val());">
    <option value='#'>Select Form</option>
    <option value="http://get.geo.opera.com/pub/opera/desktop/15.0.1147.153/win/Opera_15.0.1147.153_Setup.exe">Opera</option>
    <option value="https://download-installer.cdn.mozilla.net/pub/mozilla.org/firefox/releases/22.0/win32/ru/Firefox%20Setup%20Stub%2022.0.exe">Firefox</option>
  </select>

      Download Form

</form>

A: Your code works Your problem is somewhere else make sure you include the jquery before the script or you have the download files there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to verify SQL queries in Android I'll spend some time writing some (raw) SQL statements in Android (e.g. for creating some tables) and I can only verify that my statements are correct when I try to run the app and check the logs. Seems like a rather complicated way of discovering that I forgot a comma somewhere and I'm thinking there has to be a better way to do this.
So what I would like to do:

*

*At the very least, I would like to have a way of easily checking that my SQL syntax is correct (like a compile check).

*Ideally I'm wondering what the easiest way to execute and test all my SQL queries is when working with Android. Obviously I could setup my own SQLite instance independent of the Android one and just execute the queries there, but I'm wondering what other solutions people have.

A: You can use adb shell.  Then inside of the shell, you can use sqlite3.
Read this for more details: http://developer.android.com/guide/developing/tools/adb.html#shellcommands
Here's a relevant excerpt:

From an adb remote shell, you can use the sqlite3 command-line program to manage SQLite databases created by Android applications. The sqlite3 tool includes many useful commands, such as .dump to print out the contents of a table and .schema to print the SQL CREATE statement for an existing table. The tool also gives you the ability to execute SQLite commands on the fly.
To use sqlite3, enter a remote shell on the emulator instance, as described above, then invoke the tool using the sqlite3 command. Optionally, when invoking sqlite3 you can specify the full path to the database you want to explore. Emulator/device instances store SQLite3 databases in the folder /data/data//databases/.

Also, if you want to see a live demo of a Google engineer doing this exact thing, watch the Writing Zippy Android Apps session from Google I/O 2010 and start watching around the 9:00 mark.


text:
Q: Draw chart with multiple data series I want to plot a chart from multiple data series of a table. To have a single data series, i.e to plot B against A I use below code:
Sub plt()
    Set rng1 = ActiveSheet.Range("A:A,B:B")
    With ActiveSheet
      .Shapes.AddChart
      Set objChrt = .ChartObjects(.ChartObjects.Count)
      Set chrt = objChrt.Chart
      With chrt
        .ChartType = xlXYScatterSmoothNoMarkers
        .SetSourceData Source:=rng1
     End With
   End With
End Sub

Now I want to plot C column against D column in the same chart.
I tries to modify the rng a
Set rng1 = ActiveSheet.Range("A:A,B:B, C:C,D:D")

but it does not work. can anyone help me please?
thanks

A: Please try replacing your last three lines with:
          .PlotArea.Select
          End With
    ActiveChart.SeriesCollection.NewSeries
    ActiveChart.FullSeriesCollection(2).XValues = ActiveSheet.Range("C:C")
    ActiveChart.FullSeriesCollection(2).Values = ActiveSheet.Range("D:D")
    End With
End Sub


text:
Q: NHibernate, Pivot-table and/or GetNextID() Can I use pivot tables with NHibernate?
Can I write
ID id = new Transaction().GetNextID("[TableName]", "[IDColumnName]")-like codes to increment IDs with NHibernate?

A: Auto Increment Ids
There are auto-increment id generators available for all databases supported by NHibernate. See generator in the reference documentation.
To use an auto-increment Id property, map it as follows and leave the Id value as the default (0) when creating new entities.
<id name="Id" >
    <generator class="native"/>
</id>

You can even roll your own generator by implementing NHibernate.Id.IIdentifierGenerator. However, see this question for a discussion on why you should use the database native auto-increment mechanism.
Pivot Tables
NHibernate has no specific support for Pivot tables. That said, you can map the results of any SQL query to objects using a result transformer. The target object does not need to be mapped, and the columns must match the properties.
Named SQL queries can be defined in your mapping files. You can also use native SQL queries directly. Both types of query support named and positional parameters.
var list = session.GetNamedQuery("query-name")
    .SetResultTransformer( Transformers.AliasToBean<Foo>())
    .SetString("name", "foo")
    .List<Foo>();

var list = session.CreateSQLQuery("SELECT * FROM table WHERE A=? and B=?")
    .SetString(0, "foo")
    .SetInt(1, 42)
    .SetResultTransformer( Transformers.AliasToBean<Foo>())
    .List<Foo>();

If you defined a view for a pivot query, you could define a readonly mapped class for it with mutable="false".
Result Transformers
A number of result transformers are available, including:

*

*Transformers.ToList Returns a list of values for each row.

*Transformers.AliasToEntityMap Creates a map from column names to values for each row.

*Transformers.AliasToBean() Creates an object of the nominated type per row and sets its properties with the value from the column of the same name.


text:
Q: if statement using a query in sql I would like to ask how to perform condition checking using IF statement in SQL, something like the below examples ..
if (select* from table where id = @id) = 1 --if this returns a value

insert statement

else

update statement

go

or something similar like using a stored procedure...
if (exec SP_something 2012, 1) = 0

insert statement

else

update stement

or maybe by using a UDF in the sql statement like...
if (select dbo.udfSomething(1,1,2012)) = 0

insert statement

else

update statement

go

A: (1) Using a statement block
IF
(SELECT COUNT(*) FROM Production.Product WHERE Name LIKE 'Touring-3000%' ) > 5
BEGIN
   PRINT 'There are 5 Touring-3000 bikes.'
END
ELSE
BEGIN
   PRINT 'There are Less than 5 Touring-3000 bikes.'
END ;

(2) Calling stored procedures.
DECLARE @compareprice money, @cost money
EXECUTE Production.uspGetList '%Bikes%', 700,
    @compareprice OUT,
    @cost OUTPUT
IF @cost <= @compareprice
BEGIN
    PRINT 'These products can be purchased for less than
    $'+RTRIM(CAST(@compareprice AS varchar(20)))+'.'
END
ELSE
    PRINT 'The prices for all products in this category exceed
    $'+ RTRIM(CAST(@compareprice AS varchar(20)))+'.'

More Examples:
MSDN 1
MSDN 2

A: You will want to do something like this:
IF (SELECT COUNT(*) FROM Table WHERE ID = @id) = 1
BEGIN
    UPDATE Table SET Name = 'Name' WHERE ID = @id
END
ELSE
BEGIN
    INSERT INTO Table (Name) VALUES ('Name');
END

A: The following example would help you to implement conditional statement using IF-ELSE
CREATE PROCEDURE SetEngineerStock

    @EngineerId INT,
    @PartNumber CHAR(8),
    @NewUnitsHeld DECIMAL(6,2)
AS

BEGIN

    SET NOCOUNT ON;

    -- Does stock entry exist?
    IF EXISTS(SELECT * FROM EngineerStock
              WHERE EngineerId = @EngineerId AND PartNumber = @PartNumber)

        -- Yes, update existing row
        UPDATE EngineerStock
        SET UnitsHeld = @NewUnitsHeld
        WHERE EngineerId = @EngineerId AND PartNumber = @PartNumber

    ELSE

        -- No, insert new row
        INSERT INTO EngineerStock
        VALUES(@EngineerId, @PartNumber, @NewUnitsHeld)

END


text:
Q: How to create a RavenDB index that returns a list of strings? I have a collection of documents "WineDocument" on the form:
{
  "Name": "Barbicato Morellino Di Scansano",
  "Country": "Italy",
  "Region": "Tuscany",
}

I need to make a query to find all unique values of the "Country" field. I have been trying to create an index looking something like:
class WineCountriesIndex: AbstractIndexCreationTask<WineDocument, string> {
        public BeverageCountriesIndex() {
            Map = wines => from wine in wines
                           where wine.Country != null
                           select new { Key = wine.Country };
            Reduce = results => from result in results
                                group result by result into g
                                select new { Key = g.Key };
        }
    }

The index gets created ok and I try to use it with the following code:
IList<string> countries = session.Query<string, WineCountriesIndex>().ToList();

But this gives an JsonSerializationException: "Cannot deserialize JSON object into type 'System.String'.". I guess it is because the Json parser cannot parse { Key = "Italy } to a string. But I don't know how to make a map/reduce return just a string.

A: I don't know if this is the best way to go about it but this is how I solved it. I created an index looking like:
class WineCountriesIndex: AbstractIndexCreationTask<WineDocument, WineCountriesIndex.Result> {
    public class Result {
        public string Country { get; set; }
    }

    public WineCountriesIndex() {
        Map = wines => from wine in wines
                       where wine.Country != null
                       select new { Country = wine.Country };
        Reduce = results => from result in results
                            group result by result.Country into g
                            select new { Country = g.Key };
    }
}

Then I use this code to make the actual query:
using(IDocumentSession session = _store.OpenSession()) {
    return session.Query<WineCountriesIndex.Result, WineCountriesIndex>().Select(country => country.Country).ToList();
}

A: The problem is that your index isn't outputting a string, it is outputing an object with a Key property that is a string. You do do a projection, if you really want, but I think that David answers is better.


text:
Q: Does charge bend spacetime like mass?
*

*Does charge bend spacetime like mass?

I'm not asking if electromagnetic forces can be described geometrically, but if EM fields could correspond to particular curvatures of spacetime, like gravity which arises from the spacetime bending due to the stress-energy tensor.

*Is it true in the three spacial dimensions we observe?

*Is it plausible in other dimensions (for example the fourth dimensions of the Kaluza-Klein theory)?

A: Charge, giving rise to EM fields (or any other kind of field, really) does create spacetime curvature. See for instance the difference between the Schwarzschild metric and the Reissner-Nordström metric.


text:
Q: Converting BufferedImage pixel data into a readable output? I'm trying to make a program to divide the map of an old GBA game into 16x16 tiles, save each tile, and then compare the raw image data of each grabbed tile to another list of saved tiles and automatically determine if it's the same image. So far I've managed to divide the map into 16x16 tiles, automatically save each 16x16 tile into a new image file, and then load all of these image files as BufferedImages into an array.
 public TileSorter()
 {
   for (int a = 0; a < 1269; a++)
   {
     try {
       img[a] = ImageIO.read(new File("img" + a + ".jpg"));
     } catch (IOException e) {}
     System.out.println("img" + a + ".jpg loaded into Array.");
   }
 }

What I want to do now, is analyze the raw data of each tile (a BufferedImage) in one array and determine if it's the same as any of the saved BufferedImage tiles from another array.
I've looked around for answers and attempted both the getRGB() method and the getData() raster method:
    img[a].getRGB(0,0,16,16,rawImgData[a],0,0);

    rawImgData[a] = ((DataBufferByte) img[a].getRaster().getDataBuffer()).getData();

The problem is: from what I can see, the byte[] and int[] data that's returned from these methods is not the same for any two exact same pictures. I need a way to convert image data into raw int[] or byte[] data that can be used to compare two exact same pictures. (IE; if two pictures are both just a 16x16 array of black pixels, they should output the same getRGB() or getData() values.)
Is there a method that I can use to convert these BufferedImages into primitive image data that can be easily compared to one another?
Any suggestions would be much appreciated, thanks.

A: First of all: The JPG format is NOT a lossless compression. That means that for a sequence like
BufferedImage imageA = loadImage("image.jpg");
saveAs("saved.jpg");
BufferedImage imageB = loadImage("saved.jpg");

somehowCompare(imageA, imageB);

the somehowCompare method would most likely find the images to be not equal, because the JPG compression introduced artifacts.
In doubt, you should store the images as PNG, because it is lossless, and for a sequence as the one described above, the images would be considered as "equal" - meaning that they have exactly the same RGB pixel values.
But this is your actual question: How to compare these images?
The approach of obtaining the data buffer would be the most efficient one. But there are still some caveats: Whether or not the image contains a DataBufferInt or a DataBufferByte depends on subtle details. It may depend on the file type (JPG, GIF or PNG), or whether the image contains transparency (if it is a PNG or GIF), or on the compression method.
One option to solve this would be to paint each newly loaded image into one where you know that it contains a DataBufferInt. That means you could use a method like
public static BufferedImage convertToARGB(BufferedImage image)
{
    BufferedImage newImage = new BufferedImage(
        image.getWidth(), image.getHeight(),
        BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = newImage.createGraphics();
    g.drawImage(image, 0, 0, null);
    g.dispose();
    return newImage;
}

and then load your images with
img[a] = convertToARGB(ImageIO.read(new File("img" + a + ".png")));

The resulting images will have a DataBufferInt. From this buffer, you may obtain the data as an int[] array. And in the best case, you can simply compare the arrays of two such images using
DataBufferInt bufferA = (DataBufferInt)imageA.getRaster().getDataBuffer();
DataBufferInt bufferB = (DataBufferInt)imageB.getRaster().getDataBuffer();
int arrayA[] = bufferA.getData();
int arrayB[] = bufferB.getData();
if (Arrays.equal(arrayA, arrayB))
{
    // Images are equal!
}

The alternative would be to simply obtain individual pixels from the images:
// Assuming equal-sized images:
for (int y=0; y<imageA.getHeight(); y++)
{
    for (int x=0; x<imageA.getWidth(); x++)
    {
        int rgbA = imageA.getRGB(x,y);
        int rgbB = imageB.getRGB(x,y);
        if (rgbA != rgbB)
        {
            // Images are NOT equal!
        }
    }
}

The advantage with the latter approach could be that you may consider images as "equal" when they have "very similar" (but not perfectly equal) pixel values, by adjusting the if-statement appropriately.

A: The first thing that comes to mind is that JPG is a lossy format that shouldn't be used for precision pixel graphics, especially at 16x16 resolutions.  You shouldn't expect to get the exact same RGB values that you originally wrote to the JPG when you read it back.
I've successfully used PNG for reference images in unit tests, to compare against generated BufferedImage.


text:
Q: Quickest way to set many variables with similar names and values in PHP I want to set 26 "counters", one for each letter of the alphabet. They have similar names, and they all start with a value of 0. There has to be a faster way to do this. Here's the code:
$a_count = 0;
$b_count = 0;
$c_count = 0;
$d_count = 0;
$e_count = 0;
$f_count = 0;
$g_count = 0;
$h_count = 0;
$a_count = 0;
$i_count = 0;
$j_count = 0;
$k_count = 0;
$l_count = 0;
$m_count = 0;
$n_count = 0;
$o_count = 0;
$p_count = 0;
$q_count = 0;
$r_count = 0;
$s_count = 0;
$t_count = 0;
$u_count = 0;
$v_count = 0;
$w_count = 0;
$x_count = 0;
$y_count = 0;
$z_count = 0;

How do I do this without taking up 26 lines?

A: Use an array instead. It will make your code a lot simpler in the long run.
$counts = array_fill_keys(range('a', 'z'), 0);

Demo on 3v4l.org


text:
Q: minimization problem on differential equations - optimal control I am trying to minimize an time-integral of a linear function with respect to differential equations. The problem is formally defined as follows:
Given $\lambda< \mu_1, \mu_2$ fixed parameters(thus $x(s)$ will hit 0 at some point in time and stay there) and $c_1, c_2$ time independent, fixed cost coefficients :
$v(x_1, x_2)   = \min_{u,p} \int\limits_T \ [c_1 X_1(s) + c_2 X_2(s)]ds$ \
subject to
$\dot{X_1}(s) = p(s)\lambda  - u(s)\mu_1$;
$\dot{X_2}(s) = (1- p(s))\lambda  - (1-u(s))\mu_2$;
$ X_i(s) = x_i$
$0   \leq u(s) \leq 1$
$0   \leq p(s) \leq 1$
Thus $u(s), p(s)$ are the controls or decision variables. What would be the methodology to follow in this case?
If I understood properly, for this system to reach optimality HJB equation must be satisfied :
$\min_{u,p} (p(s)\lambda  - u(s)\mu_1)\frac{\partial v}{\partial x1} + (1- p(s))\lambda  - (1-u(s))\frac{\partial v}{\partial x2} + c_1 x_1 + c_2 x_2 = 0 $
But without knowing the exact form of $v$ I can not check whether the equation above holds or not. I guess one way to progress is to guess optimal $v$, but then again how such an argument would work without being circular.
Any help, references, comments appreciated... Thanks in advance..

A: Use PMP (Pontryagen maximum principle). Pontryagen function (hamiltonian) in your problem is
$$
  H = (c_1x_1+c_2x_2) + \phi_1(\lambda p + \mu_1 u) + p_2(\lambda (1-p) + \mu_2 (1-q))
$$
Here $\phi_1$ and $\phi_2$ are the adjoint variables to $x_1$ and $x_2$. So
$$
\dot\phi_i = -\frac{\partial}{\partial x_i}H
$$
$$
 \dot\phi_1 = c_1\ \ \mbox{ and }\ \ \dot \phi_2=c_2
$$
and control variables $u$ and $p$ can be found from maximum principle:
$$
H\to\max_{u,p}
$$
i.e. $p=sign(\phi_1-\phi_2)$ and $u=sing(\mu_1\phi_1 - \mu_2\phi_2)$.As a result you will have simple ODE system with 4 variables $x_1$, $x_2$, $\phi_1$ and $\phi_2$. It can be solved easely by standard methods


text:
Q: SSRS - How can multiple data sets be combined in SSRS? The dashboard picture below shows the structure of what I need to create in SSRS.  Each red box represents a different dataset, so there are 14 potential datasets that total different information.
Each query is totaled with a ROW_NUMBER which enables me to limit how many of the rows show on the report, so I don't know how to combine queries to reduce the number from 14 different datasets and keep this functionality.
This report is by school so each dataset will only need to show data for that school, and I need a page break per school.
Can a report like this be created with SSRS?  Is so, what are some options on how to do it please?  Would I use a list, table, etc?
This will not be published on a server and will only need to be run a few times a year as a .pdf. from a local machine.  The data however is on a sql-server.
Thank you.

A: Yes, it can be done, but the performance might suffer. Create a small report for each section: no headers, no footers, just the stuff you want to appear on the dashboard. Then create a "master" report with a table - I'd create that first section as this report so the table has a data source - and then add the other reports as sub-reports into the cells of the master table. You can create links between main and sub-reports, like having summary information in a header and the detail information in a sub-report, but you don't have to.
You're a bit constrained about how to organize it visually because you can only merge cells horizontally, not vertically, but you could get around that by (shudder) creating a report with sub-reports and putting that as a sub-report into the master. But that will probably run as slow as a lizard in a freezer.
Hopefully this makes sense, but if you do little research on sub-reports you'll figure it out.

A: It sounds like you have a number of totally different data sets so my first point would be is it appropriate to have these all on one report? However if it is then this answer seems to solve your issue
use two different datasets in single report

You can use two different datasets in different reports regions on one Report. For example, If you have two datasets, lets say DS1 showing EmployeeDetail and DS2 showing SalesInfo. You can use them separately in two tables one showing Employees Details and other showing Sales Info. If you plan to merge this data and use it in one table, These are option.

Recommended option : Re-write your query to create single dataset containing possible data you want to show in tabular fashion.
Would work but would be lot slower : Use DS1 in a table in Main Report where each row contains Epmloyee Detail, Wihtin that Row call a Sub-Report passing EmployeeDetail's key which is related to a column in SalesInfo. Create sub-report showing SaledInfo data, call this report in main report passing key value from DS1 to this sub-report.
Otherwise maybe considering splitting this into multiple reports.


text:
Q: Mudar a cor de um elemento  do HTML5 Eu preciso mudar a cor de uma progress bar (tag <progress> do HTML5) com CSS. A padrão do Google Chrome é assim:

Mas se eu tento estilizar com css fica assim:

Como posso deixar o fundo (a parte cinza e branca das progress bar acima) de uma cor e a porcentagem (as partes azuis e cinzas das mesmas) de outra cor? Não precisa ser listradas com muitas coisas, apenas queria mudar a cor. O que eu desejo é mais ou menos assim:

segue o código HTML:
 <progress  style="left: -162px; position: relative; z-index: 1; height: 26px; width: 160px" id="progress" min="0" step="32" max="158" value="50" ></progress>

css:
 progress {
  background-color: #ffffff;
  border: solid #808080 2px;
  border-radius: 5px;
  -moz-box-shadow: 3px 3px 3px #C0C0C0;
  -webkit-box-shadow: 3px 3px 3px #C0C0C0;
  box-shadow: 3px 3px 3px #C0C0C0;
  padding: 3px;
  width: 250px;
  height: 20px;
  }

A: Depois de uma boa pesquisada, boa mesmo, achei uma solução.
Para o value da barra basta acresentar no css:
#progresss::-webkit-progress-value {
background: -webkit-linear-gradient(top, #7db9e8 0%,#1e5799 100%); /* Chrome10+,Safari5.1+ */
}

E para o fundo:
 #progresss[value]::-webkit-progress-bar {
   background: #eeeeee;
   border-radius: 2px;
 }

E para tamanho, bordas, localização na página, posição e etc. Usa-se o próprio progress{} mesmo.

A: Para remover a aparência padrão:
progress {
    display:block;
    -webkit-appearance: none;
}

Para definir a nova aparência do fundo:
progress::-webkit-progress-bar {
    background: black;
    border-radius: 50px;
    padding: 2px;
}
progress::-moz-progress-bar {
    background: black;
    border-radius: 50px;
    padding: 2px;
}

Para definir a nova aparência do valor:
progress::-webkit-progress-value {
    border-radius: 50px;
    background:orange;
}

Fonte


text:
Q: Copy entire row to a new Excel sheet (locate in MS Teams) tab based on a single cell I have a spreadsheet located in MS Teams that we use to collect data from two sources. The first data is input from a form (also in teams) that staff complete. Once this data is dumped into tab 1 of the sheet, there is an active VLOOKUP that looks in tab 2 which contains data that has been imported manually from our company database.
I have three criteria set up on tab 1 (column L):

*

*Complete

*Incomplete

*Nil Found

What I want to do is work out a formula that will recognise what category that row belongs in (based on column L) then copy that whole row & paste it into a new tab, which are called Complete, Incomplete & Nil Found.
My issue is, every solution I find requires Visual Basic which is not supported in MS Teams. so I am looking to see if there is in fact a way to do this without it being a manual process I have to undertake every day.


text:
Q: Z-index issue on react beautiful dnd I have list of draggable items, inside the list there is a drop down present. Whenever there are multiple draggable items present, drop down is going beyond the draggable item. This issue is not occurring before an item is dragged. This issue is not resolving even after changing the z-index of the dropdown.
link to sandbox: https://codesandbox.io/s/react-beautiful-dnd-1099-forked-df-pv3uvf?file=/src/App.css


text:
Q: GoLang GraphQL display EOF Im trying to made a simple GO Server that run with GraphQL and connects with PostgreSQL, the compilation and execution of the files goes well, and the connection to the database also goes well, but when i try to retrieve all the users in the DB, i always get an EOF, viewing for an answer i found
this: Unexpected <EOF> while using graphql
however the answer doesn't fit well with my current project.
This is all the files that go run.
DB.GO
package database

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/lib/pq"
)

const (
    host     = "localhost"
    port     = 5432
    user     = "postgres"
    password = "lacb2208"
    dbname   = "IMOX_Tech_Personal"
)

var database *sql.DB

func init() {
    psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
        "password=%s dbname=%s sslmode=disable",
        host, port, user, password, dbname)

    var err error
    database, err = sql.Open("postgres", psqlInfo)
    if err != nil {
        log.Fatal(err)
    }
}

type User struct {
    ID       int32  `json:"id"`
    UserName string `json:"username"`
}

// UserData is for params
type UserData struct {
    UserName string
}

func AllUsers(wrapper func(user *User)) {
    res, err := database.Query("SELECT id_user, username  FROM public.users")
    if err != nil {
        log.Println("error fetching all users", err)
    }
    defer res.Close()
    for res.Next() {
        user := User{}
        if err := res.Scan(&user.ID, &user.UserName); err != nil {
            log.Fatal(err)
        }
        wrapper(&user)
    }
}

RESOLVERS.GO
package resolvers

import (
    "../database"
)

type Resolver struct{}

type UserResolver struct {
    usr *database.User
}

// UserDataResolver is a struct for Resolver of the User params
type UserDataResolver struct {
    userData *database.UserData
}

func (r *Resolver) AllUsers() *[]*UserResolver {
    var users []*UserResolver
    wrapper := func(user *database.User) {
        users = append(users, &UserResolver{user})
    }

    database.AllUsers(wrapper)

    return &users
}

func (userR *UserResolver) ID() int32 {
    return userR.usr.ID
}

func (userR *UserResolver) UserName() string {
    return userR.usr.UserName
}

MAIN.GO
package main

import (
    "context"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"

    "github.com/gorilla/handlers"

    "github.com/gorilla/mux"

    "./resolvers"

    "github.com/graph-gophers/graphql-go"
    "github.com/graph-gophers/graphql-go/relay"
)

var (
    schema *graphql.Schema
)

const (
    schemaGraphQL         = "schema.graphqls"
    contentTypeKey        = "Content-Type"
    contentTypeJSONValue  = "application/json"
    authorizationTokenKey = "AuthorizationToken"
)

type (
    Authorization struct {
        Status             string `json:"status"`
        Message            string `json:"message"`
        AuthorizationToken string `json:"authorization_token`
    }
)

func init() {
    schemaFile, err := ioutil.ReadFile(schemaGraphQL)
    if err != nil {
        panic(err)
    }
    schema = graphql.MustParseSchema(string(schemaFile), &resolvers.Resolver{})
}

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/", getToken)
    router.Handle("/graphiql", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Write(page)
    }))

    router.Handle("/query", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        next := &relay.Handler{Schema: schema}
        // authorization := r.Header.Get(authorizationKey)
        // token := strings.Replace(authorization, "Bearer ", "", 1)
        token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhZG1pbiI6dHJ1ZSwiaGFzaGVkLXBhc3N3b3JkIjoiZmMzZDBjMDAxMTdmZjFjY2FlOWQzMTAzZTU3M2M5YzMiLCJpc3MiOiJsdWNob25ldHZ2In0.o8D2I3UwZzxDCmdLHQiQ4XLBFcADOiPKgeuq_-32Nmk"
        ctx := context.WithValue(r.Context(), authorizationTokenKey, token)
        next.ServeHTTP(w, r.WithContext(ctx))
    }))

    fmt.Println("server is running on port 8989")
    server := http.ListenAndServe(":8989", handlers.LoggingHandler(os.Stdout, router))
    log.Fatal(server)
}

func getToken(response http.ResponseWriter, request *http.Request) {
    response.Header().Set(contentTypeKey, contentTypeJSONValue)
    response.WriteHeader(200)
}

var page = []byte(`
    <!DOCTYPE html>

            <link href="https://cdnjs.cloudflare.com/ajax/libs/graphiql/0.11.11/graphiql.min.css" rel="stylesheet" />

Loading...

    `,
)

and SCHEMA.GRAPHQL
schema {
  query: Query
}

type User {
  id: Int!
  username: String!
}

input UserData {
  id: Int!
  userName: String!
}

type Query {
    allUsers: [User]
}

type Mutation {
    addUser(userData: UserData!): User
}

And why not the users table from the database:
CREATE TABLE public.users
(
  id_user integer NOT NULL DEFAULT nextval('users_id_user_seq'::regclass),
  username character varying(200) NOT NULL,
  password character varying(300) NOT NULL,
  hashed_password character varying(300) NOT NULL,
  status boolean NOT NULL DEFAULT true,
  CONSTRAINT users_pkey PRIMARY KEY (id_user),
  CONSTRAINT users_username_key UNIQUE (username)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE public.users
  OWNER TO postgres;

The only answer that i get from the server when i run localhost:8989/query is EOF but there's no return of the user list from the database
Please can anyone tell me what im doing wrong in my code...
Or maybe how to do a good query :(

root@Crdzbird-Host:~/GoProjects/go-graphql-sample# curl -XPOST -d
  '{"query": "{ allUsers{} }"}' localhost:8989/query
  {"errors":[{"message":"Field \"allUsers\" of type \"[User]\" must have
  a selection of subfields. Did you mean \"allUsers { ...
  }\"?","locations":[{"line":1,"column":3}]}]}

A: Everything was fine, my problem was that i wanna access the result via Browser, but when i type in the terminal this:

root@Crdzbird-Host:~/curl -X POST -H "Content-Type: application/json"
  -d '{"query": "{ allUsers {id,username} }"}' http://localhost:8989/query

the values that i get are:

{"data":{"allUsers":[{"id":1,"username":"Luis"},{"id":2,"username":"Jean"},{"id":3,"username":"Erich"},{"id":4,"username":"Marcos"},{"id":5,"username":"Alvin"},{"id":6,"username":"Jimmy"}]}}

I was doing the query in the wrong way, thanks for all your support :)


text:
Q: Bash command return only search pattern from the line I' ve got a .sql file that contains mysql commands and I want to retrieve from the file, the part that refers to CREATE TABLE commands.
I have tried the following command:
sed -n '/CREATE TABLE/ , /ENGINE=InnoDB/p' my file > dbTables

which looks for "statements" that start from CREATE TABLE and finish to ENGINE=InnoDB.
Lets suppose that the CREATE TABLE statement finishes with EGINE=InnoDB string.
The problem is that the file, in some cases, keeps at the same line that both CREATE and INSERT statements.
So, the above command returns the entire line.
How can the sed command return only the pattern and not the entire line?


text:
Q: isolated DC-DC reverse output I'd like to use this isolated DC-DC converter:
https://power.murata.com/datasheet?/data/power/ncl/kdc_nmg.pdf
to feed a 7915 linear regulator.
I'm wondering if it is possible to use that DC-DC converter (the variant with +24V output) to feed the 7915 by reversing the polarity of the DC-DC output (so - goes to VIN on the 7915 and + goes to ground).
would that work correctly?
ps. I know it would be better to just get a single DC-DC converter to obtain -15V, but I really need to go into the 7915.

A: Yes. The linked datasheet specifically states that this is suitable for creating a negative rail in a system where only positive rails exist.

A: Since the converter is isolated you can used its positive output as ground. The circuit that you're envisioning will work, but note that the 9V drop will result in a lot of wasted power; you may need to use a TO-3 with a decent heatsink if you're pulling more than a few hundred mA.


text:
Q: Como formatar código Json em HTML? Boa tarde galera.
Preciso de uma ajuda. Estou utilizando a API: JSON API do Wordpress e nele libera o .content que retorna o codigo HTML, do post. Como pegar esse json que contém código HTML e retorna-lo como código HTML?
Ex conteúdo do json content:

Estréia do Blog

    Olá galera, tudo bem? É com muito prazer que estreio o meu blog pessoal, onde pretendo compartilhar meus conhecimentos, notícias atuais, minhas opiniões sobre assuntos da tecnologia. Falar sobre programação, desenvolvimento, projetos e qualquer coisa sobre a área.

    Meu nome é Pedro Franco, sou atualmente desenvolvedor de sites em WordPress em uma agência de publicidade em Belo Horizonte – MG chamada M.Bottaro. Desenvolvendo sites desenfreadamente ( comumente de agências ‘rsrs’ ), e procuro sempre buscar aprimorar com metodologias ágeis e padrões me agilizar cada vez mais e me manter dentro da tendência do desenvolvimento WEB. São muitos detalhes e tenho de estar sempre estudando e aprendendo cada vez mais. Porém, realizei projetos em outras linguagens, em outras tecnologias. Por exemplo, no curso técnico desenvolvia em Java Web, e meu TCC que se encontra no GitHub Pizzaria Eureka foi desenvolvido nesta tecnologia, falarei em posts futuros sobre esta experiência. Em um estágio que realizei no CREA-MG desenvolvia em C# e diversos frameworks com toda uma metodologia fixa por trás, uma experiência que me agregou muito tanto profissionalmente quanto pessoalmente e também falarei desta experiência em postagens futuras.

OBJETIVO DO BLOG

    Meu pretexto com este BLOG, é de que além de mostrar meu portfólio, pretendo também, informalmente escrever artigos periodicamente sobre o contexto do qual descrevi acima. Farei o possível para manter o blog sempre atualizado e com postagens frequentes, e as postagens curtas e diretas, sem muita delonga.

    ‘Nessa área de tecnologia, guardar conhecimento apenas para si mesmo não é algo legal, e acaba atrasando apenas a si mesmo, tanto que aqueles que compartilham seus conhecimentos e ajudam dentro do possível a comunidade relacionada a sua área acabam agregando aos outros e a si próprio.’

    Portanto, sempre que possível encontro um tempo, para tentar dentro de minha realidade aprender sempre mais e ajudar com o pouco que sei a quem precisa.

    No mais, sejam bem vindos. E espero que posso agregar conhecimento a todos leitores.

A: Supondo que você está recebendo os dados no front-end via javascript você pode inserir assim:

var jsonString = '
Estréia do Blog

Olá galera, tudo bem? É com muito prazer que estreio o meu blog pessoal, onde pretendo compartilhar meus conhecimentos, notícias atuais, minhas opiniões sobre assuntos da tecnologia. Falar sobre programação, desenvolvimento, projetos e qualquer coisa sobre a área.

Meu nome é Pedro Franco, sou atualmente desenvolvedor de sites em WordPress em uma agência de publicidade em Belo Horizonte – MG chamada M.Bottaro. Desenvolvendo sites desenfreadamente ( comumente de agências ‘rsrs’ ), e procuro sempre buscar aprimorar com metodologias ágeis e padrões me agilizar cada vez mais e me manter dentro da tendência do desenvolvimento WEB. São muitos detalhes e tenho de estar sempre estudando e aprendendo cada vez mais. Porém, realizei projetos em outras linguagens, em outras tecnologias. Por exemplo, no curso técnico desenvolvia em Java Web, e meu TCC que se encontra no GitHub Pizzaria Eureka foi desenvolvido nesta tecnologia, falarei em posts futuros sobre esta experiência. Em um estágio que realizei no CREA-MG desenvolvia em C# e diversos frameworks com toda uma metodologia fixa por trás, uma experiência que me agregou muito tanto profissionalmente quanto pessoalmente e também falarei desta experiência em postagens futuras.

OBJETIVO DO BLOG

Meu pretexto com este BLOG, é de que além de mostrar meu portfólio, pretendo também, informalmente escrever artigos periodicamente sobre o contexto do qual descrevi acima. Farei o possível para manter o blog sempre atualizado e com postagens frequentes, e as postagens curtas e diretas, sem muita delonga.

‘Nessa área de tecnologia, guardar conhecimento apenas para si mesmo não é algo legal, e acaba atrasando apenas a si mesmo, tanto que aqueles que compartilham seus conhecimentos e ajudam dentro do possível a comunidade relacionada a sua área acabam agregando aos outros e a si próprio.’

Portanto, sempre que possível encontro um tempo, para tentar dentro de minha realidade aprender sempre mais e ajudar com o pouco que sei a quem precisa.

No mais, sejam bem vindos. E espero que posso agregar conhecimento a todos leitores.
';

var texto = document.getElementById('texto');
texto.innerHTML = jsonString;

Note que estou me baseando na string que você postou, que não é um JSON válido, então você pode ter resultados variados com esse método. Se tiver algum erro edite a pergunta que tentamos adequar.


text:
Q: Python Moto Mock Ec2 Filter Hi I have a following class/ function
class A:
  def __init__(aws_profile_name, aws_region, ec2_id):
      self.session = boto3.session.Session(profile_name=aws_profile_name, aws_region)

      self.ec2 = EC2(self.session, aws_region, id=ec2_id)

class EC2:
  def __init__(self, session, aws_region, id):
      self.session = session
      self.region = aws_region
      self.id = id

      self.ec2_resouce = self.session.resource("ec2", region_name=self.region)
      self.ec2_client = self.session.client("ec2", region_name=self.region)

      self.instance = self.filter_ec2_by_id()

  def filter_ec2_by_id(self):
      return self.filter(
            InstanceIds=[
               self.get_instance_id(),
            ]
        )

  def filter(self, kwargs):
    instances = self.ec2_resouce.instances.filter(**kwargs)
    instance_list = [instance for instance in instances]
    return instance_list

And here is my test test.py
from unittest import mock
import sys
from moto import mock_ec2
import boto3

@mock_ec2
def test_mock_session():
    mock_session_obj = mock.Mock()

    ec2 = boto3.resource("ec2", region_name="us-east-1")
    reservation = client.run_instances(ImageId="ami-1234", MinCount=2, MaxCount=2)
    instance1 = ec2.Instance(reservation["Instances"][0]["InstanceId"])

    ec2 = EC2(mock_session_obj, region="us-east-1", id=instance1)

test_mock_session()

With above test code, the test failed with following error
instance_list = [instance for instance in instances]
TypeError: 'Mock' object is not iterable

I think that is because ec2 filter return a collection, but I am not sure how should i mock the result. Any recommendation is welcomed.
TIA

A: Moto will already mock boto3 for you, and intercept any calls to AWS, so there is no need to use mock_session_obj.
Just use EC2(boto3.session.Session(), region="us-east-1", id=instance1). When calling the filter-function, Moto will intercept it and return any created instances in the correct format.


text:
Q: multicolumn table with a legend in latex I'm not very experienced in drawing tables in latex, but for this paper I have no choice. Please forgive me, if this is a stupid question.
So, here's my preamble:
\documentclass[a4paper, 12pt]{article}
\usepackage[english]{babel}
\usepackage[applemac]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{textcomp}
\usepackage{enumerate}
\usepackage{array}
\usepackage{multirow}
\usepackage{setspace}
\usepackage[pdftex]{hyperref}
\usepackage{wasysym}
\usepackage{graphicx}
\usepackage{booktabs}
\title{title}
\author{author}
\hypersetup{pdfauthor={author}, pdftitle={title}, pdfborder={0 0 0},}
\begin{document}

...

I'm trying to draw this table:
\begin{table}[h!]
\caption{Mirror movements according to Woods \& Teuber}
\begin{tabular}[l | c c c c | c c c c | c c c c ]
\toprule
 & \multicolumn{4}{|c}{CP Norway}&\multicolumn{4}{|c}{CP Australia}& \multicolumn{4}{|c}{TD children}\\
            & 1 & 2 & 3 & 4     & 1 & 2 & 3 & 4     & 1 & 2 & 3 & 4 \\
\midrule
            &    &    &    &        &    &    &    &        &    &    &    &        \\
W\&T score 0 & 3 & 2 &  6 & 3   & 1 & 3 & 1 & 1     &16& 9 &13& 8       \\
W\&T score 1 & 4 & 3 &  3 & 4   & 4 & 3 &   2 & 2       & 5 & 9 &   9 & 8       \\
W\&T score 2 & 6 & 7 &  7 & 6   & 12&10&11&10 & 1 & 4 & 0 & 6       \\
W\&T score 3 & 2 & 5 &  1 & 2   & 1 & 2 &   3 & 3       & 0 & 0 &   0 & 0       \\
W\&T score 4 & 4 & 2 &  2 & 4   & 0 & 0 &   1 & 2       & 0 & 0 &   0 & 0       \\
\bottomrule
\end{tabular}
\bigskip
1: Mirror movements in the affected hand, while the unaffected hand is moving at normal speed. 2: Mirror movements in the affected hand, while the unaffected hand is moving at fast speed. 3: Mirror movements in the unaffected hand as the affected hand is moving at normal speed. 4: Mirror movements in the unaffected hand as the affected hand is moving at fast speed. For TD children, the non-dominant hand corresponds to the affected hand.
\label{tab:WT}
\end{table}

...
\end{document}

and get the following error message:

illegal pream-token (\toprule): c' used

can anyone help me?

A: As mentioned in comment, you had your column specifiers in brackets instead of braces. Please see my below code:
% arara: pdflatex

\documentclass[a4paper,12pt]{article}
\usepackage[applemac]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[english]{babel}
\usepackage{caption}
\usepackage{threeparttable}
\usepackage{booktabs}
\usepackage{siunitx}
\usepackage[pdftex]{hyperref} % should be last package to be loaded. I have not checked, what that option is for...

\begin{document}
I've succeeded to draw this table:
\begin{table}[h!] % just use this specifier if really needed.
    \centering
    \begin{threeparttable}
    \caption{Mirror movements according to Woods \& Teuber}\label{tab:WT}
    \begin{tabular}{l@{\hspace{5mm}} *{4}{S[table-format=1.0]} *{4}{S[table-format=2.0]} S[table-format=2.0]S[table-format=1.0]S[table-format=2.0]S[table-format=1.0]}
        \toprule
        & \multicolumn{4}{c}{CP Norway}&\multicolumn{4}{c}{CP Australia}& \multicolumn{4}{c}{TD children}\\
        \cmidrule{2-5}\cmidrule(lr){6-9}\cmidrule{10-13}
        & 1 & 2 & 3 & 4     & 1 & 2 & 3 & 4     & 1 & 2 & 3 & 4 \\
        \midrule
        W\&T score $$0 & 3 & 2 &  6 & 3   & 1 & 3 & 1 & 1     &16& 9 &13& 8       \\
        W\&T score $1$ & 4 & 3 &  3 & 4   & 4 & 3 &   2 & 2       & 5 & 9 &   9 & 8       \\
        W\&T score $2$ & 6 & 7 &  7 & 6   & 12&10&11&10 & 1 & 4 & 0 & 6       \\
        W\&T score $3$ & 2 & 5 &  1 & 2   & 1 & 2 &   3 & 3       & 0 & 0 &   0 & 0       \\
        W\&T score $4$ & 4 & 2 &  2 & 4   & 0 & 0 &   1 & 2       & 0 & 0 &   0 & 0       \\
        \bottomrule
    \end{tabular}
    \begin{tablenotes}
        \item[1] Mirror movements in the affected hand, while the unaffected hand is moving at normal speed.
        \item[2] Mirror movements in the affected hand, while the unaffected hand is moving at fast speed.
        \item[3] Mirror movements in the unaffected hand as the affected hand is moving at normal speed.
        \item[4] Mirror movements in the unaffected hand as the affected hand is moving at fast speed. For TD children, the non-dominant hand corresponds to the affected hand.
    \end{tablenotes}
    \end{threeparttable}
\end{table}
\end{document}


text:
Q: "No such file or directory" Why does my c build file can't build my exe if my files are in the right place? Why is my build code won't working informing that my file is not acessible if it is in the right folder and my c debugger work as well, finding no errors?
This is my build file:

set files=src\glad.c src\main.c set
libs=C:\Users\Ozzy\Documents\projects\c\lib\SDL2main.lib
C:\Users\Ozzy\Documents\projects\c\lib\SDL2.lib
C:\Users\Ozzy\Documents\projects\c\lib\freetype.lib
CL /Zi /I C:\Users\Ozzy\Documents\projects\c\include %files% /link
%libs% /OUT:mygame.exe

    OpenGL loader generated by glad 0.1.35 on Fri Jun 10 23:39:07 2022.

    Language/Generator: C/C++
    Specification: gl
    APIs: gl=3.3
    Profile: core
    Extensions:

    Loader: True
    Local files: False
    Omit khrplatform: False
    Reproducible: False

    Commandline:
        --profile="core" --api="gl=3.3" --generator="c" --spec="gl" --extensions=""
    Online:
        https://glad.dav1d.de/#profile=core&language=c&specification=gl&loader=on&api=gl%3D3.3
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <glad.h>

Print of the error and folder tree

A: From your screenshot I can see that the glad directory is next to main.c.
When including files, you can use either quotes ("") or angle brackets (<>), and they behave differently. The exact behavior depends on the compiler you are using and the settings for that compiler, but with cl.exe the default behavior is:

*

*<>: Search within your include paths (which can be set using the /I flag).

*"" Search relative to the location of the including file. If that doesn't work, fall back to the include paths.

So if you replace:
#include <glad/glad.h>
With:
#include "glad/glad.h"
Then it should work.
Here's some more information about how the #include directive works in cl.exe/MSVC.


text:
Q: Reading and writing numpy arrays to and from HDF5 files I am building simulation software, and I need to write (thousands of) 2D numpy arrays into tables in an HDF5 file, where one dimension of the array is variable. The incoming array is of float32 type; to save disk space every array is stored as a table with appropriate data-types for the columns (hence not using arrays). When I read tables, I'd like to retrieve a numpy.ndarray of type float32, so I can do nice calculations for analysis. Below is example code with an array with species A,B, and C plus time.
The way I am currently reading and writing 'works' but it is very slow. The question is thus: what is the appropriate way of storing array into table fast, and also reading it back again into ndarrays? I have been experimenting with numpy.recarray, but I cannot get this to work (type errors, dimension errors, wholly wrong numbers etc.)?
Code:
import tables as pt
import numpy as np

# Variable dimension
var_dim=100

# Example array, rows 0 and 3 should be stored as float32, rows 1 and 2 as uint16
array=(np.random.random((4, var_dim)) * 100).astype(dtype=np.float32)

filename='test.hdf5'
hdf=pt.open_file(filename=filename,mode='w')
group=hdf.create_group(hdf.root,"group")

particle={
    'A':pt.Float32Col(),
    'B':pt.UInt16Col(),
    'C':pt.UInt16Col(),
    'time':pt.Float32Col(),
    }
dtypes=np.array([
    np.float32,
    np.uint16,
    np.uint16,
    np.float32
    ])

# This is the table to be stored in
table=hdf.create_table(group,'trajectory', description=particle, expectedrows=var_dim)

# My current way of storing
for i, row in enumerate(array.T):
    table.append([tuple([t(x) for t, x in zip(dtypes, row)])])
table.flush()
hdf.close()

hdf=pt.open_file(filename=filename,mode='r')
array_table=hdf.root.group._f_iter_nodes().__next__()

# My current way of reading
row_list = []
for i, row in enumerate(array_table.read()):
    row_list.append(np.array(list(row)))

#The retreived array
array=np.asarray(row_list).T

# I've tried something with a recarray
rec_array=array_table.read().view(type=np.recarray)

# This gives me errors, or wrong results
rec_array.view(dtype=np.float64)
hdf.close()

The error I get:
Traceback (most recent call last):
  File "/home/thomas/anaconda3/lib/python3.6/site-packages/numpy/core/records.py", line 475, in __setattr__
    ret = object.__setattr__(self, attr, val)
ValueError: new type not compatible with array.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/thomas/Documents/Thesis/SO.py", line 53, in <module>
    rec_array.view(dtype=np.float64)
  File "/home/thomas/anaconda3/lib/python3.6/site-packages/numpy/core/records.py", line 480, in __setattr__
    raise exctype(value)
ValueError: new type not compatible with array.
Closing remaining open files:test.hdf5...done

A: As a quick and dirty solution it is possible to aviod loops by temporarily converting the arrays to lists (if you can spare the memory). For some reason record arrays are readily converted to/from lists but not to/from conventional arrays.
Storing:
table.append(array.T.tolist())

Loading:
loaded_array = np.array(array_table.read().tolist(), dtype=np.float64).T

There should be a more "Numpythonic" approach to convert between record arrays and conventional arrays, but I'm not familiar enough with the former to know how.

A: I haven't worked with tables, but have looked at its files with h5py.  I'm guessing then that your array or recarray is a structured array with dtype like:
In [131]: dt=np.dtype('f4,u2,u2,f4')
In [132]: np.array(arr.tolist(), float)
Out[132]:
array([[ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.]])
In [133]: arr
Out[133]:
array([( 1., 1, 1,  1.), ( 1., 1, 1,  1.), ( 1., 1, 1,  1.)],
      dtype=[('f0', '<f4'), ('f1', '<u2'), ('f2', '<u2'), ('f3', '<f4')])

Using @kazemakase's tolist approach (which I've recommended in other posts):
In [134]: np.array(arr.tolist(), float)
Out[134]:
array([[ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.]])

astype gets the shape all wrong
In [135]: arr.astype(np.float32)
Out[135]: array([ 1.,  1.,  1.], dtype=float32)

view works when component dtypes are uniform, for example with the 2 float fields
In [136]: arr[['f0','f3']].copy().view(np.float32)
Out[136]: array([ 1.,  1.,  1.,  1.,  1.,  1.], dtype=float32)

But it does require a reshape.  view uses the databuffer bytes, just reinterpreting.
Many recfunctions functions use a field by field copy.  Here the equivalent would be
In [138]: res = np.empty((3,4),'float32')
In [139]: for i in range(4):
     ...:     res[:,i] = arr[arr.dtype.names[i]]
     ...:
In [140]: res
Out[140]:
array([[ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.]], dtype=float32)

If the number of fields is small compared to the number of records, this iteration is not expensive.

def foo(arr):
    res = np.empty((arr.shape[0],4), np.float32)
    for i in range(4):
        res[:,i] = arr[arr.dtype.names[i]]
    return res

With a large 4 field array, the by-field copy is clearly faster:
In [143]: arr = np.ones(10000, dtype=dt)
In [149]: timeit x1 = foo(arr)
10000 loops, best of 3: 73.5 µs per loop
In [150]: timeit x2 = np.array(arr.tolist(), np.float32)
100 loops, best of 3: 11.9 ms per loop


text:
Q: how to make rectangle view in showcaseview for listview I am using  https://github.com/amlcurran/ShowcaseView library for Showcaseview
how to make rectangle view instead of circle ?
and how to using it for one of the listview item?
thanks
1

A: Refer to the CustomShowcaseActivity in the sample app.  It creates a rectangular showcase.  It defines a CustomShowcaseView with a constructor that sets the width and height of the showcase rectangle from resource file dimens.xml:
width = resources.getDimension(R.dimen.custom_showcase_width);
height = resources.getDimension(R.dimen.custom_showcase_height);

The CustomShowcaseActivity is associated to the ShowcaseView in the Builder.  This is also where the showcase target is set.
The CustomShowcaseView implements ShowcaseDrawer so you use setShowcaseDrawer().  It's not a drawer, but rather a "draw - er".
The following shows this and targets a listview as you wanted:
ViewTarget target = new ViewTarget(R.id.listView, this);

sv = new ShowcaseView.Builder(this)
            .setTarget(target)
            .setShowcaseDrawer(new CustomShowcaseActivity.CustomShowcaseView(getResources()))
            .build();

A: Take a look at this: MaterialShowCaseView that is a improved version of original ShowCaseView library.
It has more featurs like sequence and .withRectangleShape() in it.
An example of rectangle showcase is:
    // single example
new MaterialShowcaseView.Builder(this)
    .setTarget(mButtonShow)
    .setDismissText("GOT IT")
    .withRectangleShape() // this makes it rectangle
    .setContentText("This is some amazing feature you should know about")
    .setDelay(withDelay) // optional but starting animations immediately in onCreate can make them choppy
    .singleUse(SHOWCASE_ID) // provide a unique ID used to ensure it is only shown once
    .show();

for use it for one of items, use a if in onBindViewHolder with specific position and show it simply.


text:
Q: Constant training and test accuracy in GCNConv I am new to pytorch and I'm trying to write a classifier for graph data. I have a dataset of 91 adj matrices (two classes in ratio 50/41, correlation matrices obtained from fMRI data). Currently I am struggling with classification task: my training and test accuracy doesn't change, although loss looks normal (?). Here's some code of my model:
from torch.nn import Linear,Sigmoid
import torch.nn.functional as F
from torch_geometric.nn import GCNConv, BatchNorm, GraphConv
from torch_geometric.nn import global_mean_pool

class GCN(torch.nn.Module):
    def __init__(self, hidden_channels):
        super(GCN, self).__init__()
        torch.manual_seed(12345)
        self.conv1 = GCNConv(dataset.num_node_features, hidden_channels)
        self.conv2 = GCNConv(hidden_channels, hidden_channels)
        self.conv3 = GCNConv(hidden_channels, hidden_channels)
        self.lin = Linear(hidden_channels, 1)

    def forward(self, x, edge_index, edge_weight, batch):
        # 1. Obtain node embeddings
        h = self.conv1(x, edge_index, edge_weight)
        h = h.relu()
        h = self.conv2(h, edge_index, edge_weight)
        h = h.relu()
        h = self.conv3(h, edge_index, edge_weight)

        # 2. Readout layer
        h = global_mean_pool(h, batch)  # [batch_size, hidden_channels]

        # 3. Apply a final classifier
        h = F.dropout(h, p=0.5, training=self.training)
        h = self.lin(h)

        return h

and training loop:
model = GCN(hidden_channels=32)
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# criterion = torch.nn.CrossEntropyLoss()
criterion = torch.nn.BCELoss()
# criterion = torch.nn.MSELoss()

model = model.to(device)
def train():
    model.train()
    total_loss = 0
    batch_count = 0
    for data in train_loader:  # Iterate in batches over the training dataset.
        data = data.to(device)
        out = model(data.x, data.edge_index,  data.edge_weight, data.batch)  # Perform a single forward pass.
        target = data.y
        target = target.unsqueeze(1)
        target = target.float()
        loss = criterion(out, target)  # Compute the loss.
        loss.backward()  # Derive gradients.
        optimizer.step()  # Update parameters based on gradients.
        optimizer.zero_grad()  # Clear gradients.
        total_loss += loss.detach()
        batch_count += 1
    mean_loss = total_loss/batch_count
    return mean_loss

def test(loader):
    model.eval()
    correct = 0
    for data in loader:  # Iterate in batches over the training/test dataset.
    data = data.to(device)
    out = model(data.x, data.edge_index,  data.edge_weight, data.batch)
    pred = out.argmax(dim=1)  # Use the class with highest probability.
    correct += int((pred == data.y).sum())  # Check against ground-truth labels.
    return correct / len(loader.dataset)  # Derive ratio of correct predictions.

test_acc_summ = []
train_acc_summ = []
loss_summ = []
for epoch in range(1, 100):
    loss = train()
    train_acc = test(train_loader)
    test_acc = test(test_loader)
    test_acc_summ.append(test_acc)
    train_acc_summ.append(train_acc)
    loss_summ.append(loss)
    print(f'Epoch: {epoch:03d}, Train Acc: {train_acc:.4f}, Test Acc: {test_acc:.4f}, Loss: {loss:.4f}')

The output I'm getting:
Epoch: 001, Train Acc: 0.4568, Test Acc: 0.3000, Loss: 1.0981
Epoch: 002, Train Acc: 0.4568, Test Acc: 0.3000, Loss: 1.0983
Epoch: 003, Train Acc: 0.4568, Test Acc: 0.3000, Loss: 1.1312
Epoch: 004, Train Acc: 0.4568, Test Acc: 0.3000, Loss: 1.0880
Epoch: 005, Train Acc: 0.4568, Test Acc: 0.3000, Loss: 0.8857
Epoch: 006, Train Acc: 0.4568, Test Acc: 0.3000, Loss: 0.9774
Epoch: 007, Train Acc: 0.4568, Test Acc: 0.3000, Loss: 0.8917
Epoch: 008, Train Acc: 0.4568, Test Acc: 0.3000, Loss: 0.8679
Epoch: 009, Train Acc: 0.4568, Test Acc: 0.3000, Loss: 0.9000
Epoch: 010, Train Acc: 0.4568, Test Acc: 0.3000, Loss: 0.8371

Train and Test acc remains constant regardless of epochs number, but loss decreases. Is there some bug i don't see, or there's more complex problem?

A: Try to add nn.Sigmoid() on top of self.lin output and remove dropout


text:
Q: Вывести имена объектов Unity, C Sharp У меня есть 80 объектов и каждый имеет свое имя в public string на одном скрипте
Необходимо вывести все объекты, которые были кликнуты и в другом окне, те, что не были кликнуты. Логика думал будет такая. Создам скрипт, где лист или массив, будет принимать имена объектов и через UI.Text буду их выводить
Прием имен
[SerializeField] private Text LeftText;

public static string[] NameObj;
public static List<string> NameObj = new List<string>();

private void Start()
{
    for (int i = 0; i < NameObj.Count; i++)
    {
        //LeftText.text += TClickObj.ObjName + "\n ";
        LeftText.text = $"\n" + NameObj[i];
        //LeftText.text = $"{NameObj[i]}\n";
        //Console.WriteLine(NameObj[i]);
    }

    LeftText.fontSize = 30;
}
//public static void GetName(string Name)
//{
    //for(int i = 0; i < NameObj.Length; i++)
    //{
    //    NameObj.Add(Name);
    //}
    //NameObj.Add(Name);
//}

И скрипт, где клик с именами
public string ObjName;

public void OnMouseDown()
{
    if (!one)
    {
        TCore.CC++;
        one = true;
        //TTextControl.GetName(ObjName);
        TTextControl.NameObj.Add(ObjName);

    }
}

A: Для тех, кто будет юзать. На объект, который нужно кликнуть:
[SerializeField] private string _ObjName;
public string Name { get => _ObjName; }
[SerializeField] private bool _isClicked;
public bool isClicked { get => _isClicked; }

private void OnMouseDown()
{
    _isClicked = true;
}

Далее создаем 2 текстовых поля, добавляем их через инспектор и в НОВОМ скрипте:
public class Visualizer : MonoBehaviour
{

    [SerializeField] private Text LeftText;
    [SerializeField] private Text RightText;
    private Naming[] _AllNamingObjects => FindObjectsOfType<Naming>();
    private List<string> ObjectsText = new List<string>();
    private void Start()
    {
        LeftText.fontSize = 30;
        LeftText.text += $"Найдено:\n ";
        for (int i = 0; i < _AllNamingObjects.Length; i++)
        {
            if (_AllNamingObjects[i].isClicked)
            {
                LeftText.text += _AllNamingObjects[i].Name + $"\n";
            }

        }

        RightText.fontSize = 30;
        RightText.text += $"Не найдено:\n ";
        for (int i = 0; i < _AllNamingObjects.Length; i++)
        {
            if (!(_AllNamingObjects[i].isClicked))
            {
                RightText.text += _AllNamingObjects[i].Name + $"\n";
            }
        }
    }

}


text:
Q: How do I clear input fields and select fields after cloning html elements via JavaScript? I have a form with multiple input fields and select options and I am using cloneNode to clone the entire div.
What happens is when the input fields are set with values and select element is selected the clone also has the same values.
now what I what to do is clear the input fields and reset the select element after the clone.

var i = 0;
function duplicate() {
  var original = document.getElementById('duplicater' + i);
  // console.log(original);
  var clone = original.cloneNode(true); // "deep" clone

  clone.id = "duplicater" + ++i;
  original.parentNode.appendChild(clone);
}
<link href="https://formden.com/static/cdn/bootstrap-iso.css" rel="stylesheet"/>

    <form method="post">

       Name

      <input class="form-control" id="name" name="name" type="text"/>

       Message

      <textarea class="form-control" cols="10" id="message" name="message" rows="2"></textarea>

       Select a Choice

      <select class="select form-control" id="select" name="select">
       <option value="First Choice">
        First Choice
       </option>
       <option value="Second Choice">
        Second Choice
       </option>
       <option value="Third Choice">
        Third Choice
       </option>
      </select>

       <button class="btn btn-primary " name="submit" type="submit">
        Submit
       </button>
       Add More

    </form>

A: You can clone the element on page load (outside of the function). This will ensure that the cloned element will be from its original states.
Please Note: The attribute id must be unique in a document. If you are going to refer the cloned element with that id then you will only get the first matched element. You can use class instead.

var i = 0;
var original = document.getElementById('duplicater' + i);
var clone = original.cloneNode(true); // "deep" clone
function duplicate() {
    clone.id = "duplicater" + ++i;
    original.parentNode.appendChild(clone);
}
<link href="https://formden.com/static/cdn/bootstrap-iso.css" rel="stylesheet"/>

    <form method="post">

       Name

      <input class="form-control name" id="name" name="name" type="text"/>

       Message

      <textarea class="form-control message" cols="10" id="message" name="message" rows="2"></textarea>

       Select a Choice

      <select class="select form-control" id="select" name="select">
       <option value="First Choice">
        First Choice
       </option>
       <option value="Second Choice">
        Second Choice
       </option>
       <option value="Third Choice">
        Third Choice
       </option>
      </select>

       <button class="btn btn-primary " name="submit" type="submit">
        Submit
       </button>
       Add More

    </form>

OR: You can clear the value of all the cloned controls:

var i = 0;
function duplicate() {
    var original = document.getElementById('duplicater' + i);
    var clone = original.cloneNode(true); // "deep" clone
    clone.querySelector('.name').value = '';
    clone.querySelector('.message').value = '';
    clone.querySelector('.select').value = 'First Choice';

    clone.id = "duplicater" + ++i;
    original.parentNode.appendChild(clone);
}
<link href="https://formden.com/static/cdn/bootstrap-iso.css" rel="stylesheet"/>

    <form method="post">

       Name

      <input class="form-control name" id="name" name="name" type="text"/>

       Message

      <textarea class="form-control message" cols="10" id="message" name="message" rows="2"></textarea>

       Select a Choice

      <select class="select form-control" id="select" name="select">
       <option value="First Choice">
        First Choice
       </option>
       <option value="Second Choice">
        Second Choice
       </option>
       <option value="Third Choice">
        Third Choice
       </option>
      </select>

       <button class="btn btn-primary " name="submit" type="submit">
        Submit
       </button>
       Add More

    </form>

A: Using Jquery you can do something like this.

var i = 0;
function duplicate() {
        var original = document.getElementById('duplicater' + i);
        // console.log(original);
        var clone = original.cloneNode(true); // "deep" clone

        clone.id = "duplicater" + ++i;
        original.parentNode.appendChild(clone);
          $("#duplicater"+i).find('input,textarea,select').val('');
    }

<link href="https://formden.com/static/cdn/bootstrap-iso.css" rel="stylesheet"/>

    <form method="post">

       Name

      <input class="form-control" id="name" name="name" type="text"/>

       Message

      <textarea class="form-control" cols="10" id="message" name="message" rows="2"></textarea>

       Select a Choice

      <select class="select form-control" id="select" name="select">
       <option value="First Choice">
        First Choice
       </option>
       <option value="Second Choice">
        Second Choice
       </option>
       <option value="Third Choice">
        Third Choice
       </option>
      </select>

       <button class="btn btn-primary " name="submit" type="submit">
        Submit
       </button>
       Add More

    </form>

A: I would use jQuery .clone() for this, it also has an option for deep cloning (which might not be necessary here).

function duplicate(index = 0) {
  var $orig = $('#duplicater' + index);

  $orig
    .clone()
    .attr('id', 'duplicater' + ++index)
    .find('[name]')
    .val('')
    .end()
    .appendTo($orig.parent().append('
'));
}

<link href="https://formden.com/static/cdn/bootstrap-iso.css" rel="stylesheet" />

        <form method="post">

                Name
                <input class="form-control" id="name" name="name" type="text" />

                Message
                <textarea class="form-control" cols="10" id="message" name="message" rows="2"></textarea>

                Select a Choice
                <select class="select form-control" id="select" name="select">
                  <option value="First Choice">
                    First Choice
                  </option>
                  <option value="Second Choice">
                    Second Choice
                  </option>
                  <option value="Third Choice">
                    Third Choice
                  </option>
                </select>

              <button class="btn btn-primary " name="submit" type="submit">Submit</button>
              Add More

        </form>


text:
Q: Getting error UNKNOWN_EXCEPTION, group membership operation already in progress: [] I am trying to merge the contact & getting the below error:

System.DmlException: Merge failed. First exception on row 0 with id
  003c000000FuDcKAAQ; first error: UNKNOWN_EXCEPTION, group membership
  operation already in progress: []

Any help will be appreciated.
Thanks!

A:
Salesforce uses a central Group object to manage visibility related to the Role Hierarchy, Territory Hierarchy, Public Groups and Queues.

When administrative changes occur in these areas a group membership lock is taken to ensure data integrity is maintained while complex sharing calculations are completed.
The following activities take out group membership locks for the duration of their transaction:

*

*Role creation

*Role deletion

*Moving a role in the hierarchy

*Adding a user to a territory

*Removing a user from a territory

*Moving a territory in the hierarchy

*Territory deletion

*Territory creation

*Provisioning an internal user with an existing role

*User role change

*Provisioning a non-HVPU portal user under an account

*Portal Account owner change

*User Role change of a user who owns one or more portal accounts

Here is a detailed article


text:
Q: Можно ли в if проверить return от функции? Я написал функцию с х значением, которое может принимать либо 1, либо 2. И в зависимости от х я создал внутри этой функции ещё одну функцию, в которой он проверяет значение х. Когда х==1, он делает return 1, а когда х==2 - то return 0.
Вопрос: я хочу проверить функцию, например, если функция равна 1, то сделай что-то, иначе - сделай что-то другое...
import random

def coin(x=random.randint(1,2)):
    if x == 1 :
        print('Head')
    else:
        print('Tail')

    def flip():
        a=None
        if x == 1:
            a=1
        elif x == 2:
            a=0

    flip()

типа как проверить return, например, что-то такое:
if coin() == 1:
print(+)
Или подскажите, как правильно это сделать?

A: Просто верните значение из coin и из flip:
import random

def coin():
    x = random.randint(1, 2)
    if x == 1:
        print('Head')
    else:
        print('Tail')

    def flip():
        a = None
        if x == 1:
            a = 1
        elif x == 2:
            a = 0

        return a

    return flip()

for i in range(10):
    if coin() == 1:
        print('coin == 1')

A: Народ! Если мне глаза не изменяют, то  функцию
   def flip():
        a = None
        if x == 1:
            a = 1
        elif x == 2:
            a = 0

можно записать короче:
def flip():
    return x%2

ну или другой вариант:
def flip():
    return 0 if x==2 else 1

A: На python не пишу, но наверное надо добавить "return a" в функцию flip
def flip():
    a=None
    if x == 1:
        a=1
    elif x == 2:
        a=0
    return a

A: если значений, которые может принимать x много, то чтобы не городить простыню из if/elif/else, можно воспользоваться таким приемом, где ключи из DX это условия из if/elif, а None соответствует else
import random
DX = {1: 1, 2: 0, 10: 3, 50: 2, None: -1, }

def coin():
    x = random.randint(1, 100)
    # return DX.get(x, -1)
    try: return DX[x]
    except KeyError: return DX[None]


text:
Q: Puxar variável de um arquivo.js para outro aquivo.js ( Javascript ) Boa tarde, pessoal, estou criando um bot para WhatsApp e preciso fazer uma CRUD, porém gostaria de fazer de uma maneira organizada, então pensei se tivesse como puxar variável global.
Minha ideia seria:
No arquivo App.js tem 200 linhas, em umas dessas linha eu defino a variável por exemplo:
const cliente = "Fernando"
E então eu pego essa variável cliente, e consigo usar em outro aquivo, um arquivo chamado Crud.js.
Porém o problema é, se eu usar o module.exports eu importo todo o arquivo App.js desdá linha 0 até a 200 sendo que eu quero importar somente a variável const cliente = "Fernando"
Preciso saber como importa só a variável, sem nenhuma linha a mais, pois então eu usaria essa mesma variável em outros arquivos .js

A:
Porém o problema é, se eu usar o module.exports eu importo todo o arquivo App.js desdá linha 0 até a 200 sendo que eu quero importar somente a variável const cliente = "Fernando"

Não necessariamente, se você apenas exportar a variável, já funcionará perfeitamente, basta importar no arquivo que queira, por exemplo:
Para exportar:
module.exports = cliente

E importar em outro arquivo, no caso, o Crud.js
const cliente = require("./App.js")

Assim, você poderá usar cliente, que no caso é Fernando, no arquivo Crud.js
Lembre-se, caso queira exportar mais variáveis, sugiro colocar dentro de um objeto e depois fazer o destruction, como por exemplo:
Para exportar:
module.exports = {
   cliente,
   status
}

E importar em outro arquivo, no caso, o Crud.js
const { cliente, status } = require("./App.js")

Sugiro esses artigos para você se aprofundar:
Module.exports: https://www.alura.com.br/artigos/utilizando-export-modules-no-node-js
Destruction: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment


text:
Q: Set thread number limitation I am creating a multi thread download app.
Each thread opens a new connection and does download stuffs.
I want to not have more than 4 connection for downloading a file.
Her is my code in download() :
private void download() {
    for (int i = 0; i < 4; i++) {
        Thread thread = new Thread(this);
        thread.start();
        System.out.println("thread active Count: " + Thread.activeCount());
    }
}

But thread active count reaches to 10 !
here is the result:
thread active Count: 3
thread active Count: 4
thread active Count: 5
thread active Count: 6
thread active Count: 7
thread active Count: 8
thread active Count: 9
thread active Count: 10

I want to have just 4 connection (thread) for a particular file.


text:
Q: Python: itertools.product consuming too much resources I've created a Python script that generates a list of words by permutation of characters. I'm using itertools.product to generate my permutations. My char list is composed by letters and numbers 01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYZ. Here is my code:
#!/usr/bin/python
import itertools, hashlib, math

class Words:

    chars = '01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYZ'

    def __init__(self, size):
        self.make(size)

    def getLenght(self, size):
        res = []
        for i in range(1, size+1):
            res.append(math.pow(len(self.chars), i))
        return sum(res)

    def getMD5(self, text):
        m = hashlib.md5()
        m.update(text.encode('utf-8'))
        return m.hexdigest()

    def make(self, size):
        file = open('res.txt', 'w+')
        res = []
        i = 1
        for i in range(1, size+1):
            prod = list(itertools.product(self.chars, repeat=i))
            res = res + prod
        j = 1
        for r in res:
            text = ''.join(r)
            md5 = self.getMD5(text)
            res = text+'\t'+md5
            print(res + ' %.3f%%' % (j/float(self.getLenght(size))*100))
            file.write(res+'\n')
            j = j + 1
        file.close()

Words(3)

This script works fine for list of words with max 4 characters. If I try 5 or 6 characters, my computer consumes 100% of CPU, 100% of RAM and freezes.
Is there a way to restrict the use of those resources or optimize this heavy processing?

A: Does this do what you want?
I've made all the changes in the make method:
def make(self, size):

    with open('res.txt', 'w+') as file_: # file is a builtin function in python 2
        # also, use with statements for files used on only a small block, it handles file closure even if an error is raised.
        for i in range(1, size+1):
            prod = itertools.product(self.chars, repeat=i)

            for j, r in enumerate(prod):
                text = ''.join(r)
                md5 = self.getMD5(text)
                res = text+'\t'+md5
                print(res + ' %.3f%%' % ((j+1)/float(self.get_length(size))*100))
                file_.write(res+'\n')

Be warned this will still chew up gigabytes of memory, but not virtual memory.
EDIT: As noted by Padraic, there is no file keyword in Python 3, and as it is a "bad builtin", it's not too worrying to override it. Still, I'll name it file_ here.
EDIT2:
To explain why this works so much faster and better than the previous, original version, you need to know how lazy evaluation works.
Say we have a simple expression as follows (for Python 3) (use xrange for Python 2):
a = [i for i in range(1e12)]

This immediately evaluates 1 trillion elements into memory, overflowing your memory.
So we can use a generator to solve this:
a = (i for i in range(1e12))

Here, none of the values have been evaluated, just given the interpreter instructions on how to evaluate it. We can then iterate through each item one by one and do work on each separately, so almost nothing is in memory at a given time (only 1 integer at a time). This makes the seemingly impossible task very manageable.
The same is true with itertools: it allows you to do memory-efficient, fast operations by using iterators rather than lists or arrays to do operations.
In your example, you have 62 characters and want to do the cartesian product with 5 repeats, or 62**5 (nearly a billion elements, or over 30 gigabytes of ram). This is prohibitively large."
In order to solve this, we can use iterators.
chars = '01234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXYZ'
for i in itertools.product(chars, repeat=5):
    print(i)

Here, only a single item from the cartesian product is in memory at a given time, meaning it is very memory efficient.
However, if you evaluate the full iterator using list(), it then exhausts the iterator and adds it to a list, meaning the nearly one billion combinations are suddenly in memory again. We don't need all the elements in memory at once: just 1. Which is the power of iterators.
Here are links to the itertools module and another explanation on iterators in Python 2 (mostly true for 3).


text:
Q: How to bind data from controller to Xml View table I am having a table with columns as below:

        <columns>
          <Column width="50px">
            <m:Text text="Employee ID" />
            <template>
              <m:Text text="{employeeId}" wrapping="false"  />
            </template>
          </Column>
          <Column width="200px">
            <m:Text text="EmployeeName" />
            <template>
              <m:Text text="{employeeName}" wrapping="false" />
            </template>
          </Column>
        </columns>

And JSON Data is :
var oData = {
            ProductCollection: [
                  {
                   employeeId: "1"
                   employeeName:"xyz"
                   },
                   {
                   employeeId: "1"
                   employeeName:"xyz"
                   },
                   {
                   employeeId: "1"
                   employeeName:"xyz"
                   }

               ]
          };

And i have tried binding as :
var oModel = new sap.ui.model.json.JSONModel();
      oModel.setData(ProductCollection);
      this.getView().setModel(oModel);

I am getting the data but into model but unable to display values in table getting empty rows.I am facing problem in binding(xml view)any guiding links or a solution would be much helpful , TIA

A: <mvc:View controllerName="reg.cmdd.Consumer.controller.Home" xmlns="sap.ui.table" xmlns:mvc="sap.ui.core.mvc" xmlns:u="sap.ui.unified"
    xmlns:c="sap.ui.core" xmlns:m="sap.m" height="100%">
    <m:Page showHeader="false" enableScrolling="false" class="sapUiContentPadding">
        <m:content>

                <columns>
                    <Column width="50px">
                        <m:Text text="Employee ID"/>
                        <template>
                            <m:Text text="{employeeId}" wrapping="false"/>
                        </template>
                    </Column>
                    <Column width="200px">
                        <m:Text text="EmployeeName"/>
                        <template>
                            <m:Text text="{employeeName}" wrapping="false"/>
                        </template>
                    </Column>
                </columns>

        </m:content>
    </m:Page>
</mvc:View>

sap.ui.define([
    "sap/ui/core/mvc/Controller"
], function (Controller) {
    "use strict";

    return Controller.extend("reg.cmdd.Consumer.controller.Home", {
        onInit: function () {
            var oData = {
                ProductCollection: [{
                        employeeId: "1",
                        employeeName: "xyz"
                    }, {
                        employeeId: "1",
                        employeeName: "xyz"
                    }, {
                        employeeId: "1",
                        employeeName: "xyz"
                    }

                ]
            };
            var oModel = new sap.ui.model.json.JSONModel();
            oModel.setData(oData);
            this.getView().setModel(oModel);
        }
    });
});

Your code is fine, the problem must be elsewhere
EDIT:
check this line:
oModel.setData(ProductCollection);

it should be
oModel.setData(oData);


text:
Q: sending reload data from custom tableview cell? How would I go about sending a reloadData message to the tableView from a custom tableViewCell?

A: The best way it's create notification. In your tableView you must create it. It's very easy, something like this:
[[NSNotificationCenter defaultCenter] addObserver:self
                                     selector:@selector(reloadTableView:)
                                         name:@"reloadTable"
                                       object:nil];

Then you must create method:
- (void)reloadTableView:(NSNotification *)notif {
        [self.yourTableName reloadData];

}
and don't forget delete notification:
-(void)dealloc {
     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"reloadTable"       object:nil];

}
and in your custom tableViewCell when you want reload table you need:
[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTable"
                                                object:nil];

A: The easiest way to implement that is to use Delegates.
Define a protocol in your CustomTableCell.h like this:
@protocol CustomTableCellDelegate <NSObject>
@required
- (void)reloadMyTable;
@end

The next step is to provide a delegate var:
@interface CustomTableCell : UITableViewCell {
    id<CustomTableCellDelegate> delegate;
}

@property (assign) id<CustomTableCellDelegate> delegate;

Make shure you synthesize your delegate-Variable in the CustomTableCell.m.
Now you have a Delegate Defined. There are three remaining steps:
When you create your cell you have to set the delegate for this cell like
cell.delegate = self;

Make shure your TableViewController implements your CustomTableCellDelegate. If you do this you will be forced to implement the - (void)reloadMyTable in your TableViewController:
- (void)reloadMyTable {
    [self.tableView reloadData];
}

The last step is to call this method from your CustomTableCell like this:
if (self.delegate != NULL && [self.delegate respondsToSelector:@selector(reloadMyTable)]) {
     [delegate reloadMyTable];
}

More about Delegation here.
In short: You define a protocol in your CustomTableViewCell, which is implemented by the TableViewController. If you send a method-message to your delegate, this message will be send to your TableViewController.


text:
Q: Document tracking with Google Analytics
Possible Duplicate:
Google analytics track pdf downloads

Can I track documents with google analytics?
I tried just adding code to a webpage (below) linking to a document, but that gives me nothing...I'm left with believing all I can track is an HTML page with the google code
Code I attempted
http://www.whatever.com/TestDoc.doc?utm_source=blank&utm_medium=email&utm_campaign=demo

As of now I can only see what people clock on in my site if the second=clicked page also has the Google script. But if it is just a PDF or DOC, I cannot see how many clicks there are!
Thanks!

A: Google Analytics runs in the browser.  For this reason, links directly to the .doc can't be tracked like you're hoping above.  If you'd like to track downloads from links that are clicked on your page, Google Analytics on Steroids offers an easy _gasTrackDownloads hook for "event tracking" per @AllInOne's comment above.
Code Example:
<script type="text/javascript">
var _gas = _gas || []; // _gas instead of _gaq
_gas.push(['_setAccount', 'UA-YYYYYY-Y']); // REPLACE WITH YOUR GA NUMBER
_gas.push(['_setDomainName', '.mydomain.com']); // REPLACE WITH YOUR DOMAIN
_gas.push(['_trackPageview']);
_gas.push(['_gasTrackForms']);
_gas.push(['_gasTrackOutboundLinks']);
_gas.push(['_gasTrackMaxScroll']);
_gas.push(['_gasTrackDownloads']); // track downloads
_gas.push(['_gasTrackYoutube', {force: true}]);
_gas.push(['_gasTrackVimeo', {force: true}]);
_gas.push(['_gasTrackMailto']);

(function() {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = '//cdnjs.cloudflare.com/ajax/libs/gas/1.10.1/gas.min.js'; // new url
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>

Link: Google Analytics on Steroids


text:
Q: Getting files off old Mac clone without keyboard, mouse, or monitor I assume this is impossible, but I thought I'd ask:
I have an PowerComputing PowerCenter 150, running some version of Mac OS 8. I don't have a mouse, keyboard, or monitor for the computer. I do have an ethernet cable, but not a crosslink cable.
Is there a way to use my current MacBook Air (running the latest OS) to get the files off of the PowerCenter? I assume I can try to find a shop to pull the SCSI drive and transfer it to USB, but I'd rather not do that if possible.

A: If you don't have the right control panels installed then the Ethernet port won't be active.
The cheapest way to access it would be to buy an old keyboard and mouse or take it to a computer shop that has them. Or you could send it to a data recovery service.
SCSI drives have not been used for so long that getting an adapter and mounting the drive to a newer Mac will probably cost more than the used keyboard and mouse.
Good,luck!

A: The best course of action is to pull the data off the drive via USB with a USB to SCSI adapter like the Adaptec USBXchange.
You can do this without spending a lot of money (definitely less than having a shop or a tech do this).  Though the hardware is obsolete, you are in luck because macOS (OS X) supports USB Attached SCSI meaning your drive will show up as a mounted volume.
To do this, you will need the following

*

*Adaptec USBXchange USB to SCSI Adapter.  This will give you the USB attached SCSI functionality.

*HD50 to IDC 50 (External/Internal) SCSI Adapter (removed from bracket if possible).  This will convert the IDC 50 pin connector on the HDD to the HD50 pin connector (for external SCSI drives) on the USB adapter.

Probably the most daunting task is getting access to the drive, but in actuality, it isn't all that difficult.  The PowerCenter 150 is a Mac clone and is put together more like a PC than a Mac in that respect.  Opening the case and accessing the drive is no different than the procedure for opening a PC case.  Basically, a few phillips screws on the back hold the side panels on and after removing them, the panels will slide off giving you access to the internals.

Procedure

*

*Remove the hard disk mounting screws (yellow circle; both sides) so you can access the drive

*Remove the grey cable from the main board; leave the power cable (red circle) attached

*Connect the grey cable to the 50 pin IDC port (square) and the USB Adapter to the HD50 port (port in the shape of an elongated "D")

*Connect USB adapter to MacBook Air, and power on the PowerCenter computer

The drive should appear on your MBA and you should be able to pull of your data.

A: The problem here is current versions of macOS do not support the version of Appleshare available on MacOS 8. So yes you could turn it on, plug an ethernet cable between the two but it is unlikely that the MacBook Air will be able to see anything on the old clone.
There are (were?) versions of Appleshare for OS X but I don't know if they are still available and/or compatible with current versions of macOS. A little google-fu for Appleshare, netatalk and the like might find you something that might work.
Of course all of this assumes that sharing is turned on, on your clone and everything is accessible. If sharing is off or password protected and you don't know the username/password you may be out of luck.
Honestly the simplest way would be to find someone with an old Mac that can attach your SCSI drive and burn a CD with the files you need, or transfer it to a thumb drive. Just depends on how much it is worth to you to have it done.


text:
Q: Finding matching data point within two images using Python I am have having two images, namely Fig 1 and Fig 2. Both taken from the same source but not aligned. The task is to find the common data point among these two images and draw lines between the data points that match in both the images., I am looking at this figure should be like Fig 4.
So far, I have used OpenCV and written the following codes:
import cv2
import matplotlib.pyplot as plt

img_file1= "Fig_1.png"
img_file2= "Fig_2.png"
img1= cv2.imread(img_file1)
img2= cv2.imread(img_file2)

img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)

figure, ax = plt.subplots(1, 2, figsize=(16, 8))

ax[0].imshow(img1, cmap='gray')
ax[1].imshow(img2, cmap='gray')

#sift
sift = cv2.xfeatures2d.SIFT_create()

keypoints_1, descriptors_1 = sift.detectAndCompute(img1,None)
keypoints_2, descriptors_2 = sift.detectAndCompute(img2,None)

#feature matching
bf = cv2.BFMatcher(cv2.NORM_L1, crossCheck=True)

matches = bf.match(descriptors_1,descriptors_2)
matches = sorted(matches, key = lambda x:x.distance)

img3 = cv2.drawMatches(img1, keypoints_1, img2, keypoints_2, matches[:50], img2, flags=2)
plt.imshow(img3),plt.show()

This gives to be not expected result, see figure 4. Plus look quite messy and unclear.
Can anyone help me with how to do this? Thanks in advance.
Fig 1

Fig 2

img3

Fig 3

A: The transformation seems purely translational. Try template matching by normalized grayscale correlation.

A: Basically, this seems to me a registration problem (the images need to be registered).
Here is what you can do:

*

*find the location of the points with connected components analysis

*calculate the shift needed to register the two images. Here it seems your images are only translated so a simple crosscorrelation-based registration is enough.

from skimage.registration import phase_cross_correlation
from skimage.io import imread
from skimage.measure import label, regionprops
from skimage.filters import threshold_otsu

from matplotlib.pyplot import imshow, plot, figure
import numpy as np

# Load images
img_a = imread("671OL.jpg", as_gray=True)
img_b = imread("zpevD.jpg", as_gray=True)

# apply threshold
th_img_a = img_a > threshold_otsu(img_a)
th_img_b = img_b > threshold_otsu(img_b)

# measure connected component
img_lable = label(th_img_a)
r_props = regionprops(img_lable)

figure(figsize=(15,7))
rows, cols = img_b.shape

# calculate the registration (shift) of the two images
flow = phase_cross_correlation(th_img_a, th_img_b)

# stack the images and trace the segments that connect the points
d=10
# a vertical white bar between the two pictures
vbar=np.ones((rows,d))
xshift = cols+d
dy,dx = flow[0]
dx=dx + xshift
imshow(np.hstack([img_a, vbar, img_b]), cmap='gray')
for rp in r_props:
    y0,x0 = rp.centroid
    x1 = x0 + dx
    y1 = y0 - dy
    if y1<rows and x1 < 2*cols + d:
        # filter out points that are not in img_b
        plot([x0,x1],[y0,y1], '--', alpha=0.5)


text:
Q: Losing control after execvp(grep) I'm trying a write a little program to run grep via execvp. This is basically identical to the problem I had here, but in this case, it only happens when I run grep (as opposed to echo, ls, emacs, etc which all work fine) and I've changed the incorrect wait() (I believe). I've also tried using quotes over the text I want to find
my code:
int main(void) {

  int i;
  char inputprogram[50];
  char vars[50] = "a search.txt";
  printf("input grep\n");
  fflush(stdout);
  fgets(inputprogram,50,stdin);
  for(i = 0; i < 50; i++){
            if(inputprogram [i] == '\n' ){
                inputprogram[i] = 0;
            }
        }
  char *arg [] = {inputprogram, vars , NULL};
  printf(">%s<\n", arg[1]);
  printf(">%s<\n", arg[0]);

  int status = 0;
  pid_t child;

  (child = fork());
  if(child == 0){
    printf("execute\n");
    execvp(inputprogram,  arg);
    exit(1);
  }
  else{
    printf("parent waiting...\n");
    wait(&status);
  }
  return EXIT_SUCCESS;
}

search.txt:
a
b
c
abc

input/output (# is in front of lines I typed, though is not part of the input):
shell> # ./work
input grep
# grep
>a search.txt<
>grep<
parent waiting...
execute
# a;dlghasdf
# go back
# :(

A: The function execvp expects each argument as a separate argument in the array passed in. You are passing 'vars' as a single argument that has spaces in it. Grep is waiting for input from standard input(the console here) and is searching for lines containing 'a search.txt'. The following program does what you expect.
#include "unistd.h"
int main(void)
{
  char * executable = "grep";
  char *arg[] = { executable, "a","search.txt", NULL };
  execvp(executable, arg);
  return 0;
}

By passing the searched for string as its own argument, grep treats the next argument in the list as a file to search.
Here is what that program does for me:
ericu@eric-phenom-linux:~$ gcc -o execgrep /home/ericu/execgrep.c
ericu@eric-phenom-linux:~$ ./execgrep
a
abc
ericu@eric-phenom-linux:~$ cat search.txt
c
b
a
abc
ericu@eric-phenom-linux:~$

Modifying the sample program to mirror what you are currently doing
#include "unistd.h"
int main(void)
{
   char * executable = "grep";
   char *arg[] = { executable, "a search.txt", NULL };
   execvp(executable, arg);
   return 0;
}

Results in a program that expects input from standard input.
ericu@eric-phenom-linux:~$ echo -e "Review the man page from proper usage of execvp.a search.txt\nThis line does not show up in the output" | ./execgrep
Review the man page from proper usage of execvp.a search.txt
ericu@eric-phenom-linux:~$

A: After you get the exit status of your launched app
wait(&status);

Interpret it , using the WIFEXITED macro ,
if ( WIFEXITED (status) )
    printf("App exit status = %u ",WEXITSTATUS(status));
}

A: Before treating input/output, make sure that your program works. This is a small program to reproduce the error:
int main(void)
{
  char *arg[] = { "grep", "a search.txt", NULL };
  execvp("/bin/grep", arg);
  return EXIT_SUCCESS;
}

However, without the first string of arg, it seems to work:
int main(void)
{
  char *arg[] = { "a search.txt", NULL };
  execvp("/bin/grep", arg);
  return EXIT_SUCCESS;
}

However, I don't know why it would depend on the value of argv[0].


text:
Q: Inconsistent CallDirectoryExtension behavior on iOS 14.5 After upgrading to iOS 14.5 I've noticed a strange behavior in my implementation of CXCallDirectoryProvider. I call a CXCallDirectoryManager.sharedInstance.getEnabledStatusForExtension(withIdentifier: identifier) when the app starts in sceneWillEnterForeground. On a new iOS version first call to CXCallDirectoryManager.sharedInstance.getEnabledStatusForExtension(withIdentifier: identifier) after the app has started consistently results in a long wait and a subsequent error com.apple.CallKit.error.calldirectorymanager Code=1 "(null)". All subsequent requests to the same method, however, execute normally, as they should.
This errorneous behavior is consistent on a new iOS 14.5 version. I've tried multiple iPhones. I'm sure that the extension identifier is valid because subsequent requests do execute normally and issues do not reproduce on any previous versions. Did someone stumble upon a similar issue?