text:
Q: HTTP Status 404 - Could not find resource for relative : of full path: RESTEasy I have already spent hours on solving the following problem:
I have a Maven Project with the following web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>xy</display-name>

    <servlet-mapping>
        <servlet-name>resteasy-servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

    <!-- Auto scan REST service -->
    <context-param>
        <param-name>resteasy.scan</param-name>
        <param-value>true</param-value>
    </context-param>

        <!-- this should be the same URL pattern as the servlet-mapping property  -->
    <context-param>
        <param-name>resteasy.servlet.mapping.prefix</param-name>
        <param-value>/rest</param-value>
    </context-param>

    <listener>
        <listener-class> org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
    </listener>

    <servlet>
        <servlet-name>resteasy-servlet</servlet-name>
        <servlet-class>
            org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
        </servlet-class>
    </servlet>

</web-app>

My Java class looks as follows:
@Path("/file")
public class File
{
    @POST
    @Path("/upload")
    @Consumes("multipart/form-data")
    public Response uploadFile(@MultipartForm Multipart form) {}

After Project-> Run as -> Run on Server the correct index.jsp is shown.

When I click a button for uploading the file I get the error:
HTTP Status 404 - Could not find resource for relative : /file/upload of full path: http://localhost:8080/Projectname/rest/file/upload
What I aleady did:

*

*clean project

*update Maven

*Run as -> Maven -> clean install (build sucess)

*delete Tomcat and installed it again

*disabled autoscan and added "File" manually

Furthermore I get warnings that some jars cannot be found on the Tomcat path (/Tomcat8/wtpwebapps/Projectname/WEB-INF/lib/activation-1.1.jar (No such file or directory - but it is available in the pom.xml and under target->Projectname->WEB-INF->lib)
I use resteasy-jaxrs version 2.2.1.GA
I appreciate any help :)

A: Try below points.

*

*Try adding the package name in web.xml inorder for rest easy to scan the class files for JAX-RS annotations. Checkout scan resteasy resources by package name

*Make sure to set the correct Content-Type while calling the REST endpoint. I.e, multipart/form-data


text:
Q: Counting rows from a GROUP BY query using an index I'm using sqlite 3.8.2 and I want to count the row from that query:
    SELECT artist
      FROM media
  GROUP BY artist

Note: that query is quite fast because it's using a index media_idx_14 on the artist column
So the query that I need is:
  SELECT count (*)
    FROM (
        SELECT artist
          FROM media
      GROUP BY artist
    )

The issue is that this query doesn't perform as fast as it should.
Here's the query plan:
SCAN TABLE media USING INDEX media_idx_14
SCAN SUBQUERY 1

My query does a table SCAN while all the info it needs is already in the index.
Is there a way to improve my query to get rid of the inefficient table SCAN?

A: I would recommend trying this query:
SELECT COUNT(DISTINCT artist)
FROM media

redpajama_set_name: RedPajamaStackExchange


text:
Q: My stored procedure is too slow My stored procedure is too slow. Can I make it faster?
ALTER PROCEDURE [dbo].[CalBuyAvg]
    @companyCode INT
AS
BEGIN
    BEGIN TRANSACTION CalBuyAvg

    DELETE FROM dbo.tmpCalSood
    WHERE CompanyCode = @companyCode

    DECLARE @id INT
    DECLARE @previd INT
    DECLARE @prvBuyAvg DECIMAL(18,0)
    DECLARE @prvKcode INT

    DECLARE db_cursor CURSOR FOR
         SELECT Id, LAG(Id) OVER (ORDER BY kalaCode, Tarikh, id) prevId
         FROM dbo.CalMandeVW
         ORDER BY kalaCode, Tarikh, id

    OPEN db_cursor

    FETCH NEXT FROM db_cursor INTO @id, @previd

    WHILE @@FETCH_STATUS = 0
    BEGIN
        SELECT @prvKcode = KalaCode, @prvBuyAvg = buyAvg
        FROM dbo.TmpCalSood
        WHERE id = @previd

        INSERT INTO dbo.TmpCalSood ([Id], [Tarikh], [KalaCode], [kalaType], [Varede], [fiVarede], [SumVarede],
                                    SaleMali, AnbarCode, pType, pCode, ProjectCode, CompanyCode,
                                    Sadere, fiSadere, SumSadere, Mandeh, LastMande , buyavg)
            SELECT
                [Id], [tarikh], [KalaCode], 0, [Varede], [fiVarede], [sumVarede],
                SaleMali, AnbarCode, pType, pCode, ProjectCode, CompanyCode,
                Sadere, fiSadere, SumSadere, Mandeh, lastMande,
                CASE
                   WHEN lastMande = 0
                      THEN dbo.CalMandeVW.fiVarede
                      ELSE
                         CASE
                            WHEN varede = 0
                               THEN
                                  CASE
                                     WHEN @prvKcode = kalaCode
                                        THEN @prvBuyAvg
                                        ELSE 0
                                  END
                               ELSE
                                  CASE
                                     WHEN @prvKcode = kalaCode
                                        THEN ((sumVarede) + (LastMande*@prvBuyAvg)) / (varede+lastMande)
                                        ELSE dbo.CalMandeVW.fiVarede
                                  END
                         END
                END AS newbuyAvg
            FROM
                dbo.CalMandeVW
            WHERE
                id = @id

        FETCH NEXT FROM db_cursor INTO @id, @previd
    END

    CLOSE db_cursor
    DEALLOCATE db_cursor;

    COMMIT
    RETURN 1
END

A: Cursors are performance killers.
Use
INSERT...INTO....SELECT

Syntax for better performance


text:
Q: Как такая реализация ЧПУ влияет на скорость сайта? Хотел сделать так. Из этого:
http://localhost/site/f2.php?fa=5

получить
http://localhost/site/red   (т.е. red имеет fa=5 )

Обычным способом через регулярные выражения у меня не выходит и я сделал извращенно:
RewriteEngine On

RewriteRule red f2.php?fa=5
RewriteRule blue f2.php?fa=6
RewriteRule white f2.php?fa=2 (и т.д. у меня может получиться сотни таких строк)
..........

Я понимаю, что это дурдом и так никто не делает... но если это работает и если на скорость сайта не влияет то почему нет.. хотел узнать, если у меня таких строк в htaccess будет примерно 500 штук, это повлияет на скорость сайта или еще как-нибудь?
Мне просто очень надо, чтобы человек мог набрать короткий адрес в адресной строке и найти то, что надо ему... и еще я понимаю, что если он будет обычным образом щелкать, то все равно в адр. строке будет писаться   http://localhost/site/f2.php?fa=5... ну и пусть, зато может ввести покороче и попасть туда же... что вы об этом думаете? спасибо!введите код здесь
A: я делаю так, и основным входом у меня index.php
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ index.php?route=$1 [L,QSA]

url можно разбить через explode, в вашем случае http://localhost/site/red, догадываюсь что нужно вытащить с базы какие-то данные по условию где столбец таблицы имеет значение red, то набросав код можно получить такое, url останется красивым, и не надо 100500 записей в .htaccess, вот примерно как это выглядит

<?php
if(isset($_GET['route']))
    {
        $exp = explode($_GET['route'], '/')
        if($exp[0] == 'site')
        {
            $sql = mysql_query("select * from `table` where `name` = '". $exp[1] ."'") or die(mysql_error());
            while($row = mysql_fetch_assoc($sql))
            {
                echo $row['id'].$row['value'];
            }
        }
    }
?>

?>


text:
Q: Is it possible to timestamp a cell when in its adjacent cell, a comment is added or a new reply is added to the comment? I know its very much possible to timestamp a cell when other cells are edited/changed/equals to a specific value.
So I kinda need to know is it feasible to timestamp when comments are added/edited/replied in its adjacent cell.
Any help or support links would be helpful.
Best,

A: You can't get Comments via apps script.  You can get Notes with apps script.  Editing a Note or a Comment does not trigger an onEdit event so it would be hard to timestamp it.


text:
Q: Align content in an attribute table to the bottom of the frame I have an attribute table in a page in one frame with a certain dimension (width/height). The content of this table is not enough to fill the height of the frame and is aligned to the top. Is any of this possible?
1) keeping the fixed dimensions of the frame, align the content of the table to the bottom of the frame?
2) having the frame height automatically calculated based on the content? (i.e. based on the number of rows?)

The table is filtered using the expression "ref_pln" = attribute(@atlas_feature,'ref_pln'), so the table displays rows if the value of their "ref_pln" attribute is equal to the value of the "ref_pln" being evaluated by the atlas.
How can I fill "table count" in the atlas using this filter?

A: How to make frame height automatically calculated based on the number of table rows

*

*Add a field to the atlas layer, "table_count". Populate this field with the number of CSV table rows that will be displayed on the table in the print composer.

*

*If the table is filtered by "show only features intersecting atlas feature,"

Install the RefFunctions plugin to enable the intersecting_geom_count() function. Use this expression in the field calculator to fill "table_count":
 intersecting_geom_count('CSVlayer')

*

*If the table is filtered by some other way, use an expression based on the table filter. Eg, with the table filter "ref_pln" = attribute(@atlas_feature,'ref_pln'), use the aggregate count function to count the number of table rows where the ref_pln value in the table matches the ref_pln value in the atlas layer:
aggregate( 'CSVlayer', 'count', "ref_pln","ref_pln" = attribute(@parent,'ref_pln'))

*Then set the table height using data-defined settings.

Use an expression that multiplies the height of each row by the number of rows in the table. Eg if the rows are each 4mm tall:
4 * attribute(@atlas_feature , 'table_count')


text:
Q: Convert string decimal to int I have a string "246246.246" that I'd like to pass to the IConvertable interface, ToInt16, ToInt32, ToIn64.  What is the best way to parse a string with decimal places to an integer?
This is a solution, but is there a better solution?
string value = "34690.42724";
Convert.ToInt64(Convert.ToDouble(value));

A: To do this discounting rounding you could do:
Convert.ToInt64(Math.Floor(Convert.ToDouble(value)));

If you need to round you could replace Math.Floor with Math.Round.
Edit: Since you mentioned in a comment that you'll be rounding:
Convert.ToInt64(Math.Round(Convert.ToDouble(value)));

If you have to worry about localization/globalization then as @xls said you should apply a CultureInfo in the conversions.
Edit 2: Alternative method using a string function (not terribly elegant IMO - maybe it could be elegantized with a predicate function):
Convert.ToInt64(value.Substring(0, value.IndexOf('.') > 0 ? value.IndexOf('.') : value.Length));

A: If you are really worry about accuracy but not about speed then decimal type would be better.
(long)Math.Round(decimal.Parse(value));

A: You should not have to Round the value as ToInt64(double) returns the rounded version already
        string value = "246246.246";
        Convert.ToInt64(Convert.ToDouble(value));

A: Assuming this string comes from user input, you probably want to catch number styling. Run it through a reusable function like so...
int? ConvertToNumber(string value)
{
   if (value == string.Empty) return null;

   try
   {
       var dec = decimal.Parse(value,
           NumberStyles.AllowDecimalPoint |
           NumberStyles.Number |
           NumberStyles.AllowThousands);

       return (int)Math.Round(dec);
   }
   catch (Exception ex)
   {
       Console.WriteLine("Please input a number.");
       return null;
   }
}

A: The code below is to convert decimal Amount to Kobo value, which is needed when integrating to a payment gateway needing the amount in kobo's or cent.
public static void Main(string[] args)
{
  decimal amount = 50.567890m;

  int koboValue = 0;

  String[] values =  amount.ToString("0.##").Split('.');

  int wholeNumber = Convert.ToInt32(values[0]);

  if(values.Count() > 1){
        koboValue = Convert.ToInt32(string.Join(string.Empty,values));
  }else{
        koboValue = wholeNumber * 100;
  }

  Console.WriteLine(koboValue);
}


text:
Q: Using date as index in output file I have several excel files with their filename differentiated by different dates. I have to concatenate all these files with their filename dates being as the index columns. I have written the following code below:
path = r"C:\\Users\\atcs\\Desktop\\data science\\files\\1-Danny Jones KPI's\\Source\\"
fileName =  glob.glob(os.path.join(path, "*.xlsx"))
df = (pd.read_excel(f, header=None, sheetname = "YTD Summary_4") for f in fileName)
k = (re.search("([0-9]{1,2}\-[0-9]{1,2}\-[0-9]{4})", fileName))
concatenated_df   = pd.concat(df, index=k)
concatenated_df.to_csv('tableau7.csv')

What i have done here is first defined a directory then assigned all files containing xlsx files to filename. I defined filename in a datadrame, used regular expression to get date from filename and assign it to variable k. now i concatenate the file to get the output csv file. But the code somehow gives an error: TypeError: expected string or bytes-like object. Can somebody help me what i am doing wrong.

A: You can use:
#simplify for add *.xlsx to path
path = r"C:\\Users\\atcs\\Desktop\\data science\\files\\1-Danny Jones KPI's\\Source\\*.xlsx"
fileName =  glob.glob(path)
#create list of DataFrames dfs
dfs = [pd.read_excel(f, header=None, sheetname = "YTD Summary_4") for f in fileName]
#add parameter keys for filenames, remove second level of multiindex
concatenated_df = pd.concat(dfs, keys=fileName).reset_index(level=1, drop=True)
#extract dates and convert to DatetimeIndex
pat = '([0-9]{1,2}\-[0-9]{1,2}\-[0-9]{4})'
concatenated_df.index = pd.to_datetime(concatenated_df.index.str.extract(pat, expand=False))
print (concatenated_df)

A: A little mod,
path = r"C:\\Users\\atcs\\Desktop\\data science\\files\\1-Danny Jones KPI's\\Source\\*.xlsx"
fileName =  glob.glob(path)
l = []
for f in fileName:
    df = pd.read_excel(f, header=None, sheetname = "YTD Summary_4")
    df['date'] = f
    l.append(df)
concatenated_df   = pd.concat(l).set_index('date')
concatenated_df.to_csv('tableau7.csv')


text:
Q: List depends on value selection I have 2 combobox. Both comboBox value are from dataset.
cb1 contain numeric list eg : 10, 20, 30
cb2 contain numeric list eg : 10.2, 11.3, 20.5, 24.8, 34.5
Cb2 list must be filtered upon cb1 selection

eg : 10 -> 10.2,11.3    20 -> 20.5, 24.8     30 -> 34.5

How do I code these using vb.net? Im uisng mssql where all the data store in table and visual studio 2005 vb.net
cb1 = BilletSize
cb2 = BilletUnitWt

EDIT:
Code tried so far
Private Sub cbBilletSize_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbBilletSize.SelectedIndexChanged
    Dim SqlStr As String SqlStr = "SELECT tbBilletUnitWt.BilletUnitWtCode FROM tbBilletUnitWt WHERE tbBilletUnitWt.BilletSizeCode = " & Me.cbBilletSize.SelectedValue & ";"
    Me.cbUnitWt.SelectedValue.RowSource = SqlStr Me.cbUnitWt.SelectedValue.Requery()
End Sub

A: I gave this a quick try with lists instead of datasets. Can you see if you can adapt this to make it work for you?
I think you should mostly just have to replace the list operation with the equivalent dataset operation...
Public Class Form1

    Dim combobox1Items As List(Of Integer) = New List(Of Integer)
    Dim combobox2Items As List(Of Double) = New List(Of Double)

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        Me.combobox1Items.Add(10)
        Me.combobox1Items.Add(20)
        Me.combobox1Items.Add(30)

        Me.combobox2Items.Add(10.2)
        Me.combobox2Items.Add(11.3)
        Me.combobox2Items.Add(20.5)
        Me.combobox2Items.Add(24.8)
        Me.combobox2Items.Add(34.5)

        With Me.ComboBox1
            .DataSource = Me.combobox1Items
        End With

    End Sub

    Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged

        Dim bindingList As New List(Of Double)

        For Each item As Double In Me.combobox2Items
            If item > CInt(Me.ComboBox1.Items(Me.ComboBox1.SelectedIndex)) Then
                Call bindingList.Add(item)
            End If
        Next

        With Me.ComboBox2
            .DataSource = bindingList
        End With

    End Sub

End Class


text:
Q: Magento2.2.2: UI Component Grid Filter Issue-Please explain getCollection function with excluded and selected how related with ui-grid? Magento2.2.2 UI Component Grid Filter Issue.
Please explain getCollection function with excluded and selected how related with UI-grid
\Magento\Ui\Component\MassAction\Filter

public function getCollection(AbstractDb $collection)
{
    $selected = $this->request->getParam(static::SELECTED_PARAM);
    $excluded = $this->request->getParam(static::EXCLUDED_PARAM);

    $isExcludedIdsValid = (is_array($excluded) && !empty($excluded));
    $isSelectedIdsValid = (is_array($selected) && !empty($selected));

    if ('false' !== $excluded) {
        if (!$isExcludedIdsValid && !$isSelectedIdsValid) {
            throw new LocalizedException(__('Please select item(s).'));
        }
    }
    /** @var \Magento\Customer\Model\ResourceModel\Customer\Collection $collection */
    $idsArray = $this->getFilterIds();
    if (!empty($idsArray)) {
        $collection->addFieldToFilter(
            $collection->getIdFieldName(),
            ['in' => $idsArray]
        );
    }
    return $collection;
}

here what is the selected and excluded parameter and how it related with our admin UI-grid?


text:
Q: how to get values from script element want to get some values from html script element with HTML Agility
Need to output these values : "KMN Gang Azet T-Shirt Fast" and "https://www.30grad.shop/item/images/11296/3000x3000/azet-kmngang-shirt-fastlife.jpg"
I already got the script element but can't get the values.
  (function(){var pinto_primary_url='/xjs/_/js/k\x3dxjs.il.en_US.mTcJQn619Nc.O/m\x3dcdos,r,jsa,csi,dbm,cr,d,ivg,dgm,ish,qtf,ivw/am\x3dAACYGj0C/rt\x3dj/d\x3d1/t\x3dzcms/rs\x3dACT90oERgo7cd2pKPZNXIWg1CpAwZ14CoQ';var _expids='201794,1354277,1354722,1354916,1355527,1355736,1355922,1356032,1356078,1356343,1356470,1356555,4029815,4031109,4038214,4038394,4041776,4043492,4045096,4045293,4045841,4047140,4047454,4048347,4048980,4050750,4051887,4056126,4056682,4058016,4061666,4061980,4062724,4064468,4064796,4069829,4076999,4078430,4078588,4080760,4081039,4081165,4082230,4083113,4097153,4097922,4097929,4098733,4098740,4098752,4102238,4103474,4103845,4103861,4104202,4104258,4106085,4106647,4109293,4109316,4109490,4110086,4110931,4112243,4113217,4115289,4115624,4115697,4116349,4116724,4116731,4116926,4116935,4117328,4117980,4118227,4118798,4119032,4119034,4119036,4120415,4120660,4120911,4121035,4121518,4122382,4123645,4124091,4124850,4125837,4126200,4127095,4127445,4127744,4128586,4129001,4129002,4129555,4129559,4129633,4130362,4130560,4131073,4131247,4131370,4131834,4132528,4132785,4132956,4133063,4133064,4133090,4133114,4133416,4133755,4134271,4134919,4134946,4135085,4135089,4135249,4135404,4135576,4135744,4135934,4136073,4136235,4136562,4136627,4137099,4137110,4137415,4137461,4137462,4137597,4137646,4138341,4138344,4138431,4138853,4139394,4139435,4139701,4139928,4140117,4140241,4140464,4140786,4140798,4141393,4141520,4141581,4141683,4141725,4141729,4142231,4142326,4142328,4142420,4142492,4142494,4142503,4142504,4142558,4142560,4142574,4142607,4142610,4142729,4143112,4143132,4143224,4143246,4143318,4143578,10200083,10202524,10202535,10202543,10202562,41317155';var pinto_module_config='{\x22/1S6iw\x22:{},\x2210Kacw\x22:{},\x22ADSBcg\x22:{},\x22Fa+7Pw\x22:{},\x22NpA8BQ\x22:{},\x22WZXAwQ\x22:{},\x22YFCs/g\x22:{},\x22aWiv7g\x22:{},\x22cdos\x22:{\x22bih\x22:877,\x22biw\x22:1760,\x22cdobsel\x22:false,\x22dpr\x22:\x221\x22},\x22cr\x22:{\x22eup\x22:false,\x22qir\x22:false,\x22rctj\x22:true,\x22ref\x22:false,\x22uff\x22:false},\x22csi\x22:{\x22acsi\x22:true,\x22dlm\x22:true,\x22jsmf\x22:true},\x22d\x22:{},\x22gf\x22:{\x22pid\x22:196},\x22hmvvig\x22:{},\x22jsa\x22:{\x22csi\x22:true,\x22csir\x22:100},\x22r\x22:{},\x22sx\x22:{},\x22v0BWCA\x22:{}}';var ctx=["root",[["t-a2hICACK35I","is_NJKM1C840","r-is_NJKM1C840",[["global_config",null,null,null,null,[null,"[\"AOvVaw3piykki21tcS6pJhxrjznh\\u0026ust\\u003d1511885221974957\",null,0,null,0,null,null,null,0,null,null,null,1,1,1,1,0,1,null,null,null,null,null,null,null,null,0,0,0,null,null,null,0,null,null,0,0,null,null,1,null,400,null,null,null,1,null,0,null,null,null,null,0,0,\"NONE\",null,4,\"Related image\",7,0,\"%1$d\\u0026nbsp;\\u0026#215;\\u0026nbsp;%2$d\",0,null,null,null,null,null,0,null,0,\"#222\",0,1,null,1,null,0,null,null,null,null,null,0,null,0,0,0]\n"]
]
,["group_config",null,null,null,null,[null,"[null,null,null,null,1,null,null,1]\n"]
]
,["image_group",null,null,null,null,[null,"[[[0,\"mdba4buxuK9BKM:\",[\"https://encrypted-tbn0.gstatic.com/images?q\\u003dtbn:ANd9GcRR2V_IL-Zh_LdrVzgBgvq6zcL68YSL01zNGsQJxXTo2cpXaqVz6A\",256,197]\n,[\"https://www.30grad.shop/item/images/11296/3000x3000/azet-kmngang-shirt-fastlife.jpg\",3000,2315]\n,null,0,{\"2001\":[]\n,\"2003\":[null,\"RXXHApKYqqq7RM\",\"https://www.30grad.shop/hersteller/kmn-gang/\",\"KMN Gang | 30° Shop\",\"KMN Gang Azet T-Shirt Fast Life\",null,null,null,null,null,null,null,\"30° Merchandise Shop\"]\n}]\n]\n]\n"]
]
]
]
,["t-cuCqGEujB5w","ik5Gk2IHW4Sw","r-ik5Gk2IHW4Sw",[["enable_close_for_background",null,null,null,null,[null,null,null,null,1]
]
,["initial_open",null,null,null,null,[null,null,null,null,null,0]
]
,["remain_in_lightbox_container",null,null,null,null,[null,null,null,null,0]
]
,["ux",null,null,null,null,[null,"[{\"220802553\":1}]\n"]
]
,["gsa",null,null,null,null,[null,"[{\"46740956\":0,\"244399487\":0}]\n"]
]
]
]
,["t-RHI35lUscno","iIJTpCvJ03LA","r-iIJTpCvJ03LA"]
,["t-3mFqq0A9uuY","iy1_jPBsPPco","r-iy1_jPBsPPco",[["hide_label_on_focus",null,null,null,null,[null,null,null,null,0]
]
]
]
,["t-mqWFpp0vPaI","i7Nj7DN5Ak3M","r-i7Nj7DN5Ak3M"]
,["t-mqWFpp0vPaI","i_DjAejc9SK4","r-i_DjAejc9SK4"]
,["t-mqWFpp0vPaI","iUYK6IKmz8Cg","r-iUYK6IKmz8Cg"]
]
]
;window._ = this;window._DumpException = function(e){throw e;};google.xjsu = pinto_primary_url;google.kEXPI = _expids;google.pmc = JSON.parse(pinto_module_config);google.jsc.x(ctx);})();

C# code
        HtmlAgilityPack.HtmlDocument htmlDocument = new HtmlAgilityPack.HtmlDocument();
        htmlDocument.LoadHtml(pagesourceCode);

        var nodes = htmlDocument.DocumentNode.SelectNodes("//script");

A: As far as I know, you can't access Javascript code using Html Agility pack. It's for HTML itself.
In fact, let me rephrase it, you can access the body of a javascript which is enclosed in <script> tags, but you will not mine that data out of it as you have it.
You would probably need to serialize the object by stripping the function and variable declarations as then you'll be able to treat it as JSON. Alternatively you can use regex... but good luck with that with the provided structure.


text:
Q: Duration.between() doesn't work the way I want to I want the exact duration in hours between dates. The between-method seems to only consider the difference in whole hours. Why is that and what can I do/use instead?
Duration dur = Duration.between(
    LocalDateTime.of(2020, 5, 20, 12, 00), LocalDateTime.of(2020, 5, 20, 16, 45));

float durH = dur.toHours();

System.out.println(durH);

This code gives me 4.0 but what I want is 4.75.

A: Try: (float) duration.toMinutes() / Duration.ofHours(1).toMinutes()

A: Duration#toHours returns a long. You only see it as 4.0 because you store it as float and it gets implicitly converted.
What you want it to take the minutes part via Duration#toMinutesPart, divide it by 60 (as float) and add it to the hours:
System.out.println((dur.toHours() + dur.toMinutesPart()/60f)); // prints 4.75

Note that this breaks down when there is a shift in the calendar and the hour does not have 60 seconds. There are numerous instances in the world where a minute doesn't have 60 seconds - leap seconds come to mind first and foremost, but also others. Therefore, it is recommended to display such times as 4:45 and not converting them to decimal.

A: This works just fine.
double durH = dur.toMinutes()/60.;
// or
double durH = dur.toMinutes()/60.f;

System.out.println(durH);

prints
4.75

A: Duration duration = Duration.between(LocalDateTime.of(2020, 5, 20, 12, 00), LocalDateTime.of(2020, 5, 20, 16, 45));
float hourWithDecimals = (float) duration.toMinutes() / Duration.ofHours(1).toMinutes();

System.out.println(hourWithDecimals);

Obtaining a more precise value in minutes duration.toMinutes(), "cast it" to hours without using any magic number through Duration.ofHours(1).toMinutes().

A: You need to cast to float before division, like this:
public static void main(String[] args) {

    Duration dur = Duration.between(LocalDateTime.of(2020, 5, 20, 12, 00), LocalDateTime.of(2020, 5, 20, 16, 45));

    double durh = (double)dur.toMinutes()/60;

    System.out.println(durh);
}

Because dur.toMinutes() return a long number.

A: The method Duration#toHours

[...] returns the total number of hours in the duration by dividing the number of seconds by 3600.

As the method returns the result as long, the fractional part is cut off.
You can get the fractional part by doing the same thing explicitly:
Duration dur = Duration.between(
    LocalDateTime.of(2020, 5, 20, 12, 00), LocalDateTime.of(2020, 5, 20, 16, 45));

double durH = dur.toSeconds() / 3600.0;

System.out.println(durH); // gives 4.75

You have to divide by a double or float, otherwise you have an integer division.


text:
Q: Convert one Hindi language number to Arabic language number I have come across one question
Hindi numeric set Integer value in Swift
It was about how we can convert Hindi to English any number value.
Curious about to know how we can convert one language number to another language number
Like Example: trying to convert Hindi Language number to the Arabic language
Here is the code I have tried in the playground :
let string = "४"

let intParse1 = Int(string)

let numberFormat = NumberFormatter()
numberFormat.locale = Locale(identifier: "ar")

if let getOP = numberFormat.number(from: string) {
    print("output is: ", getOP)
}

Here is the output it is showing in the English only

I have searched for this problem but not found this kind of specific solution so posting a new question for it.
Note: Not looking for any static conversion extension or that kind of function.
EDIT:
I don't want this kind of solution
convert arabic String to english number in Swift
EDIT 2:
I want to know about why we have to convert to it first to a number and then convert it to Arabic?, Means it is necessary to convert it first to English?

A: Explanation :
NumberFormatter converts the number into another language number, not a string of a language to other language. So first we have to convert one language number number and then to another language number.
Doc Explanation : Reference

Instances of NumberFormatter format the textual representation of cells that contain NSNumber objects and convert textual representations of numeric values into NSNumber objects. The representation encompasses integers, floats, and doubles; floats and doubles can be formatted to a specified decimal position. NumberFormatter objects can also impose ranges on the numeric values cells can accept.

Directly use this extension for Swift 4:
extension String {
    func convertToArbic () -> String? {
        let formatter = NumberFormatter()
        formatter.locale = Locale(identifier: "hi")
        guard let number = formatter.number(from:self ) else{
            return nil
        }
        formatter.locale = Locale(identifier: "ar")
        guard let number2 = formatter.string(from: number) else{
            return nil
        }
        return number2
    }
}

// use
let string = "४"
if let arbNumber = string.convertToArbic() {
    print(arbNumber)
}
else{
    print("Unable to get arabic number")
}

Output:

A: Try Following code :
let Formatter = NumberFormatter()
Formatter.locale = Locale(identifier: "EN")
if let hindiNumber = Formatter.number(from: "४") {
    Formatter.locale =  Locale(identifier: "ar")
    let formattedNumber = Formatter.string(from: hindiNumber)
    print(formattedNumber!)
}

A: A more generic solution, which lets you convert from and to any locale
extension NSNumber {
    static func from(value: String, localeIdentifier: String) -> NSNumber? {
        let numberFormatter = NumberFormatter()
        numberFormatter.locale = Locale(identifier: localeIdentifier)

        return numberFormatter.number(from: value)
    }

    func to(localeIdentifier: String) -> String {
        let numberFormatter = NumberFormatter()
        numberFormatter.locale = Locale(identifier: localeIdentifier)

        return numberFormatter.string(from: self) ?? "<undefined>"
    }
}

print("४ is the number \(NSNumber.from(value: "४", localeIdentifier: "hi")!)")
print("5 is \(NSNumber(value: 5).to(localeIdentifier: "ar")) in arabic")

The output will be:
४ is the number 4
5 is ٥ in arabic

ANSWER TO EDIT 2:
Numeric string values are nothing but a representation of the numeric value. NumberFormatter always uses the numeric value as the point of truth and uses it to be able to transform to a different locale. That's why you MUST convert to the numeric value first if you use this class.
However, you can write your own function that has no knowledge of the numeric value and just maps between strings to convert the numeric values, for example:
var hindiToArabicMap: [String: String] = ["४": "٥"]
print("४ in arabic is \(hindiToArabicMap["४"]!)")

The output will be:
४ in arabic is ٥


text:
Q: Why can't I get jGrowl or Sliding Message library working? I'm trying to get a delayed message to slide in from the right side of the screen after a delay, so I tried two different libraries without success. Neither library does anything.
jQuery Sliding Messages Method
<script type="text/javascript" src="/sites/all/libraries/jquery-sliding-message/jquery.slidingmessage.js"></script>
<script type="text/javascript">
(function ($) {
  'use strict';
  Drupal.behaviors.flyoutMessage = {
    attach: function(context, settings) {
      var options = {id: 'message_from_top',
                     position: 'right',
                     size: 300,
                     backgroundColor: 'red',
                     delay: 1500,
                     speed: 500,
                     fontSize: '30px'
                    };
      $.showMessage("Hello world!", options);
    },
  };
})(jQuery);
</script>

jGrowl Method
<script type="text/javascript" src="/sites/all/libraries/jGrowl/jquery.jgrowl.js"></script>
<script type="text/javascript">
(function ($) {
  Drupal.behaviors.showAnnouncement = {
    attach: function (context, settings) {
      $.jGrowl("Hello world!", { sticky: true });
    },
  };
})(jQuery);
</script>

I checked the source, and there is no "Hello world!" message anywhere to be found, and no errors in the console either. I have tried this on two different websites to be sure.


text:
Q: I am trying to dynamically create a Mui icon using React.createElement. However, React lowercases the element. Is there a way to keep case? I am getting service.icon from JSON, so it looks like so
[
  {
    "icon": "AdminPanelSettingsIcon",
  }
]

I am using React.createElement() like so,
data.map((service) => {
  let icon = React.createElement(
    service.icon,
    { key: service.icon },
    null);
});

my output is  <adminpanelsettingsicon></adminpanelsettingsicon>
is there anyway to keep case, or convert to PascalCase so it renders like so <AdminPanelSettingsIcon></AdminPanelSettingsIcon>
Note: Is there anyway to dynamically display mui icons based on specified JSON aka api call.

A: The docs specify:
React.createElement(
  type,
  [props],
  [...children]
)

The type argument can be either a tag name string (such as 'div' or
'span'), a React component type (a class or a function), or a React
fragment type.

You're attempting to create an element using the string "AdminPanelSettingsIcon". Instead you should be attempting this by passing in the class:
React.createElement(AdminPanelSettingsIcon)

You can do this by converting your list to use classes as the value:
[
  {
    // The value is a class now, not a string
    "icon": AdminPanelSettingsIcon,
  }
]

A: Update:
If you are using https://www.npmjs.com/package/@material-ui/icons (or any other library), you can dynamically import all of the components like this:
//Preparing, it should run inside async function
let maps = {}
let listIcon = [];
await import('@material-ui/icons').then(res => {
      listIcon = res
})

for(let icon of listIcon){
    maps[icon.constructor.name.toLowerCase()] = icon;
}

//Render
data.map((service) => {
    const component = maps[service.icon] || DefaultComponent;
    let icon = React.createElement(
        component,
        { key: component },
        null);
});

Original answer:
If the API output is predictable (service.icon is just a component of the components you defined)
You can do this:
//Import...

//Defined maps
const maps = {
    "adminpanelsettingsicon": AdminPanelSettingsIcon,
    "adminpanelsettingsicon2": AdminPanelSettingsIcon2,
    "adminpanelsettingsicon3": AdminPanelSettingsIcon3,
}

//Render
data.map((service) => {
    const component = maps[service.icon] || DefaultComponent;
    let icon = React.createElement(
        component,
        { key: component },
        null);
});

It'll work as you wish

A: Simple way to do this,
In your .jsx file :
import Icon from '@mui/material/Icon';

export default function MyComponent() {
  const iconName = `home`
  return (<Icon>{iconName}</Icon>);
}

As a prerequisite, you must include this line in yout index.html
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

Voilà !
Sources :

*

*Mui DOC


text:
Q: Nuxtjs - images can be loaded from HTML but not from css/scss files Images on my page can be read from HTML file (for example when I have src tag and enter the relative path to image). For example:

But when I load image as background via css/scss files, they're not loaded. For example, this doesnt load image:

background-image: url("/assets/theme/css/images/close.svg");

@include vendor('background-image', ('linear-gradient(to top, #{$overlay}, #{$overlay})', url("/assets/theme/images/banner.jpg")));

background-image: -moz-linear-gradient(to top, rgba(48, 54, 57, 0.2), rgba(48, 54, 57, 0.2)), url("/assets/theme/images/banner.jpg");

I have installed file-loader and url-loader. If I push file-loader and url-loader in extend section in nuxt.config, then images are not loaded from HTML too.

A: You are using absolute path in the CSS files and nuxt doesn't translate them. Change the address to use @ alias:
 background-image: url("@/assets/theme/css/images/close.svg");

A: This worked for me from either assets or static folder
.class-name {
  background-image: url('~static/images/image-name.jpg');
}

.class-name {
  background-image: url('~/static/images/image-name.jpg');
}

.class-name {
  background-image: url('~@/static/images/image-name.jpg');
}


text:
Q: background overly pseudo z-index Hello I've tried to create background-color overlay using pseudo element but the problem that the inner content like h2 (in this example) will be under the background overlay, I know that I can give h2 position relative and z-index but I was ask if there are a way let me to write less codes:

.breadCrumbs{
    width:100%;
    padding:20px 0;
    position:relative;
    background-image:url('http://store6.up-00.com/2017-04/149189733741781.jpg');
    background-size:cover;
    background-attachment:fixed;
}
.breadCrumbs:after{
    content:'';
    position:absolute;
    width:100%;
    height:100%;
    top:0;
    left:0;
    background-color:rgba(51, 51, 51, 0.60);
}
.breadCrumbs h2{
    margin-bottom:30px;
    color:#ffffff;
    font-size:40px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Contact

Home

Pages

Contact

A: Use before instead of after.

.breadCrumbs{
    width:100%;
    padding:20px 0;
    position:relative;
    background-image:url('http://store6.up-00.com/2017-04/149189733741781.jpg');
    background-size:cover;
    background-attachment:fixed;
}
.breadCrumbs:before{
    content:'';
    position:absolute;
    width:100%;
    height:100%;
    top:0;
    left:0;
    background-color:rgba(51, 51, 51, 0.60);

}
.breadCrumbs h2{
    margin-bottom:30px;
    color:#ffffff;
    font-size:40px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Contact

Home

Pages

Contact

A: I do something like this:

.breadCrumbs{
    width:100%;
    padding:20px 0;
    position:relative;
    background-image:url('http://store6.up-00.com/2017-04/149189733741781.jpg');
    background-size:cover;
    background-attachment:fixed;
}
.breadCrumbs h2{
    margin-bottom:30px;
    color:#ffffff;
    font-size:40px;
}
.bg {
    content:'';
    position:absolute;
    width:100%;
    height:100%;
    top:0;
    left:0;
    background-color:rgba(51, 51, 51, 0.60);
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Contact

Home

Pages

Contact

There are also some other solutions but they are more error prone by old browsers.


text:
Q: How to remove shortcut directory bookmarks in homes creen? How can I remove shortcut directory bookmarks in home screen ?
I follow the steps here and "Contrato Carlos" was not there to be removed.

A: In your case just click Desbloquear do lançador (Unlock from launcher). In Ubuntu >= 18.10 it's rather Remove from favorites. Keep in mind that it will be still visible on your dock while it's opened.


text:
Q: Detail view give an error object referance not set to an object in asp.net mvc? I m working with asp.net with MVC code-first approaches.
I m learning MVC
first, I create a

*

*database and

*then create model class and then

*context class

*controller method

record successfully created in the database but I want to get detail of the record but get an error object reference not set to an object
when I click details then give an error object reference not set to an object??
ContextStudent.cs  //context class
using System.Data.Entity;

namespace MvcPracTech
{
    public class ContextStudent:DbContext
    {
        public ContextStudent():base("conn")
        {

        }

        public DbSet<students> stud { get; set; }
    }

HomeController.cs

        [HttpGet]                        //reload the page and get data
        public ActionResult create()
        {
            return View();
        }

        [HttpPost]                         //send the data to second action method
        public ActionResult create(students stud)
        {
            context.stud.Add(stud);
            context.SaveChanges();
            return View();
        }
        [HttpGet]                   //here i m write get method because i want to get the data
        public ActionResult Details(int id)
        {
            var details = context.stud.Find(id);
            return View();

        }

details.cshtml
Details view:

Details

students

            @Html.DisplayNameFor(model => model.name)

            @Html.DisplayFor(model => model.name)

            @Html.DisplayNameFor(model => model.address)

            @Html.DisplayFor(model => model.address)

    @Html.ActionLink("Edit", "Edit", new { id = Model.id }) |       //here get error  object referance not set an objectws
    @Html.ActionLink("Back to List", "Index")

please, help??
what I m missing in above programme??

A: In the line where you are getting the error, try changing "Model.id" to "model.id"


text:
Q: c# EMULATOR - WIFI Is there an alternative to test the WIFI environment? The c# windows mobile EMULATOR does not have radio abilities. I don't have a windows mobile phone. What should I do? Isn't there any other alternative?

A: The radio stack and how the driver supports the hardware varies widely from device to device.  I flat out wouldn't trust any emulation of WiFi under WinMo 6.x or ealier.  You must test on a physical device, and I'd highly recommend that you test on the actual hardware you're targeting.  The only thing more troublesome than WiFi on pre-Phone Windows Mobile was dealing with power states.

A: There are communities wiling to test beta software. Find a windows mobile one, they have phones


text:
Q: Printing out Highest Mark and Name of student So i have to input 10 names and marks into two arrays, and print out the best students name and marks. I am still new to java, i can only print out the max mark from the array, but how am i going to link it to the students name?
import java.util.Scanner;
public class storeMarks  {
    public static void main (String[]args){

        Scanner tomato = new Scanner(System.in);

        double max;
        double marks[];
        marks= new double[10];
        int i;

        for(i=0; i<10; i++) {
            System.out.println("Enter marks: ");
            marks[i]=tomato.nextDouble();
        }
        max = marks[0];
        for(i = 0; i < 10; i++) {
            if(max < marks[i]) {
                max = marks[i];
            }
        }
        System.out.println("Highest marks:"+max);
    }
}

A: I created a class student:
public class Student {

    private double mark;
    private String name;

    public Student()
    {
        mark = 0;
        name = "";
    }

    public Student(int mark, String name)
    {
        this.mark = mark;
        this.name = name;
    }

    public double getMark()
    {
        return mark;
    }
    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public void setMark(double mark)
    {
        this.mark = mark;
    }

}

then I edited your code in main
public static void main(String[] args) {
    // TODO code application logic here

    ArrayList<Student> studs = new ArrayList<Student>();
    for(int i=0; i< 3; i++)
    {
        studs.add(new Student());
    }

    Scanner tomato = new Scanner(System.in);

    double max;
    int i;

    for(i=0; i<3; i++) {
         System.out.println("Enter name of student: ");
        studs.get(i).setName(tomato.nextLine());
        System.out.println("Enter marks: ");
        studs.get(i).setMark(tomato.nextDouble());
        tomato.nextLine();
    }
    int position = 0;
    max = studs.get(0).getMark();
    for(i = 0; i < 3; i++) {
        if(max < studs.get(i).getMark()) {
            max = studs.get(i).getMark();
            position = i;
        }
    }
    System.out.println("Highest marks:"+studs.get(position).getMark() + " student name " + studs.get(position).getName());
}

however, it is not the simplest choice
Edit: Simplier
   public static void main(String[] args) {
    // TODO code application logic here

    Scanner tomato = new Scanner(System.in);
    double[] marks = new double[10];
    String[] names = new String[10];
    double max;
    int i;

    for(i=0; i<3; i++) {
         System.out.println("Enter name of student: ");
        names[i] = (tomato.nextLine());
        System.out.println("Enter marks: ");
        marks[i] = tomato.nextDouble();
        tomato.nextLine();
    }
    int position = 0;
    max = marks[i];
    for(i = 0; i < 3; i++) {
        if(max < marks[i]) {
            max = marks[i];
            position = i;
        }
    }
    System.out.println("Highest marks:"+ marks[position] + " student name " + names[position]);
}


text:
Q: 'quarkus.oidc.auth-server-url' property must be configured. only when running the quarkus app on docker TOPIC
I'm running a quarkus application and I want to connect it with a keycloak server deployed on another host.
the keycloak server is working with other services means no problems in there.
The keycloak server is exposing this hostname: flitch.hostname.com. So the url to connect to it is
QUARKUS_OIDC_AUTH_SERVER_URL=http://flitch.hostame.com/realms/realmname
When running the quarkus project locally everything works fine, I can manage users, auth, tokens....
PROBLEM
But the when creating an image and running it on a the docker container it throws an error: 'quarkus.oidc.auth-server-url' property must be configured
DEBUGGING

*

*QUARKUS_OIDC_ENABLED=false ( disabled the OIDC ) then running the project in the container, results to server is running well, in the mean time I've sent a curl request from the container bash to the QUARKUS_OIDC_AUTH_SERVER_URL it returns a success reponse with the appropriate json response. also tried printenv inside the container and all env vars exists and are set correctly.

*Changed the correct url to any other url e.g.http://flitch.hostame.com/auth/realms/realmname/ in the container it logs an error message saying the server url is unreachable or denied, alongside the old error of 'quarkus.oidc.auth-server-url' property must be configured
FILES
application.properties
# OIDC Configuration
    quarkus.keycloak.devservices.realm-path=${QUARKUS_KEYCLOAK_DEVSERVICES_REALM_PATH}
quarkus.oidc.client-id=${QUARKUS_OIDC_CLIENT_ID}
quarkus.oidc.credentials.jwt.signature-algorithm=${QUARKUS_OIDC_CREDENTIALS_JWT_SIGNATURE_ALGORITHM}
quarkus.oidc.enabled=${QUARKUS_OIDC_ENABLED}
quarkus.oidc.auth-role-mapper.authentication.verify-access-token=${QUARKUS_OIDC_AUTH_ROLE_MAPPER_AUTHENTICATION_VERIFY_ACCESS_TOKEN}
quarkus.oidc.auth-server-url=${QUARKUS_OIDC_AUTH_SERVER_URL}
%prod.quarkus.oidc.auth-server-url=${QUARKUS_OIDC_AUTH_SERVER_URL}
%dev.quarkus.oidc.auth-server-url=${QUARKUS_OIDC_AUTH_SERVER_URL}
%test.quarkus.oidc.auth-server-url=${QUARKUS_OIDC_AUTH_SERVER_URL}
quarkus.oidc.auth-role-mapper.authentication.cookie-force-secure=${QUARKUS_OIDC_AUTH_ROLE_MAPPER_AUTHENTICATION_COOKIE_FORCE_SECURE}

.env
QUARKUS_OIDC_AUTH_SERVER_URL=http://flitch.hostame.com/realms/realmname
_DEV_QUARKUS_OIDC_AUTH_SERVER_URL=http://flitch.hostame.com/realms/realmname
_TEST_QUARKUS_OIDC_AUTH_SERVER_URL=http://flitch.hostame.com/realms/realmname
_PROD_QUARKUS_OIDC_AUTH_SERVER_URL=http://flitch.hostame.com/realms/realmname
QUARKUS_OIDC_CLIENT_ID=account
QUARKUS_OIDC_CREDENTIALS_JWT_SIGNATURE_ALGORITHM=****
QUARKUS_OIDC_ENABLED=true
QUARKUS_OIDC_AUTH_ROLE_MAPPER_AUTHENTICATION_VERIFY_ACCESS_TOKEN=true
QUARKUS_LIVE_RELOAD_INSTRUMENTATION=true
JAVAX_VALIDATION_ENABLE=true
QUARKUS_CONFIG_PATH=.env
QUARKUS_OIDC_AUTH_ROLE_MAPPER_AUTHENTICATION_COOKIE_FORCE_SECURE=false
QUARKUS_KEYCLOAK_DEVSERVICES_REALM_PATH=keycloak.json
QUARKUS_KEYCLOAK_REALM=realmname
QUARKUS_KEYCLOAK_DEVSERVICES_SHOW_LOGS=true

docker-compose.yml
version: "3.7"
services:
  quarkus:
    image: quarkus/quarkus-project
    container_name: quarkus_project_container
    restart: always
    network_mode: "host"
    build:
      context: $PWD
      dockerfile: ./src/main/docker/Dockerfile.jvm
    env_file: .env
    ports:
      - 5005:5005
      - 8080:8080

And docker file is the default one generated by quarkus:
FROM registry.access.redhat.com/ubi8/openjdk-17:1.14

ENV LANGUAGE='en_US:en'

# We make four distinct layers so if there are application changes the library layers can be re-used
COPY --chown=185 target/quarkus-app/lib/ /deployments/lib/
COPY --chown=185 target/quarkus-app/*.jar /deployments/
COPY --chown=185 target/quarkus-app/app/ /deployments/app/
COPY --chown=185 target/quarkus-app/quarkus/ /deployments/quarkus/

EXPOSE 8080
USER 185
ENV JAVA_OPTS="-Dquarkus.http.host=0.0.0.0 -Ddebug -Djava.util.logging.manager=org.jboss.logmanager.LogManager"
ENV JAVA_DEBUG="true"
ENV JAVA_APP_JAR="/deployments/quarkus-run.jar"


text:
Q: How to achieve parallel processing to improve processing time Presently i am using springbatch to process csv and excel files in below manner.

*

*Reader(will parse csv/excel files and male pojo)

*Processor (will hit Db whether this record is there in DB or not )

*Writer(will push the pojo to message queue)

In real time i have 50k + records to process for which my code almost taking 25 minutes. I want to improve processing time by implementing parallel processing(so that in parallel we can process the same in less time).
But i have no clue how to achieve parallel processing with Spring Batch. Can any one guide me how to do it or any suggestions to improve processing time.
@Bean
    public TaskExecutor taskExecutor(){
        return new SimpleAsyncTaskExecutor("CSV-Async-batch");
    }

    @Bean(name="csvjob")
    public Job job(JobBuilderFactory jobBuilderFactory,StepBuilderFactory stepBuilderFactory,ItemReader<List<CSVPojo>> itemReader,ItemProcessor<List<CSVPojo>,CsvWrapperPojo> itemProcessor,AmqpItemWriter<CsvWrapperPojo> itemWriter){
        Step step=stepBuilderFactory.get("ETL-CSV").<List<CSVPojo>,CsvWrapperPojo>chunk(100)
                .reader(itemReader)
                .processor(itemProcessor)
                .writer(itemWriter)
                .taskExecutor(taskExecutor())
                .throttleLimit(40)
                .build();

        Job csvJob= jobBuilderFactory.get("ETL").incrementer(new RunIdIncrementer())
        .start(step).build();

====Reader for SynchronizedItemStreamReader=================
@Component
public class Reader extends SynchronizedItemStreamReader<List<CSVPojo>> {

    public static MultipartFile reqFile=null;
    List<CSVPojo> result = new ArrayList<CSVPojo>();

    @Autowired
    private CSVProcessService csvProcessService;

    public static boolean batchJobState ;

    /*public Reader(MultipartFile file){

        this.reqFile=file;
    }*/

    public void setDelegate(ItemStreamReader<List<CSVPojo>> delegate){

        /*try {
            this.read();
        } catch (UnexpectedInputException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NonTransientResourceException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/
    }

    @Override
    public List<CSVPojo> read() throws Exception, UnexpectedInputException,
            ParseException, NonTransientResourceException {
        // TODO Auto-generated method stub
        if(!batchJobState){
        result=csvProcessService.processCSVFile(reqFile);
        System.out.println("in batch job reader");
        batchJobState=true;
        return result;
        }
        return null;
    }

}

Thanks in advance!!!

A: You can use the partitioning technique to partition input files and process them in parallel. This is explained in details in the Partitioning section of the reference documentation.
You can also look at the Local partitioning sample and the Remote partitioning sample in the spring-batch-samples module.
There are similar questions to this one, I'm adding them here for reference:

*

*Spring batch- Parallel processing

*Best Spring batch scaling strategy
Hope this helps.


text:
Q: What is required to use a Windows form application use a SQL Server database through network? What is required to use a Windows form application use a SQL Server database thrugh network?
I want to install a SQL Server on 1 PC that has a Windows XP OS as a server. And, through a network I want the application to connect to a database.
So, I know that I should setup .Net Framework 4.0 to the application and I did a deployment to my project. I don't know if I need any application to install to do this connection like a server application or not?
Thanks in advance

A: The usual suspects / problems to access SQL remotely are:

*

*Enable TCP/IP protocol in SQL server

*Open up firewall to let SQL traffic through (usually port 1433)

*Configure SQL server to allow remote connections, run Browser Service

*Use the right credentials to address your SQL server instance

A: There are four basic things that are required...

*

*There are limits on installing
server software on a desktop OS
(Traditional SQL server will not
install on XP) So you need to understand what you can install and where.

*In your application there are choices as to "how to connect", but my experience is you want to use the .Net SQLClient

*You need an understanding of how to
invoke an sql statement on the
server through direct sql or stored
procedures.

*You need to understand what to expect in return from a query (nothing, scalar value, returned parameters, recordset...) and what to do with it when you get it...
For more information, please post examples of what you have tried, what the result was and what (specifically) you are trying to accomplish.
Edit after comment from @Marziana
As I read you comment I believe there are two questions:

*

*How do I deploy the database to a
new server?

*How do I connect my window forms
application to that new database?
1) Out of your original question, installing MS SQL server (standard edition) will NOT install on MS Windows XP. You need a Windows Server Software installation onto which you may install SQL Server. Your other option is to install a lesser edition of SQL Server to install on XP (such as SQL Desktop Edition, Evaluation Edition or Personal Edition).
2) The "Connection String" is the directive to the connection object telling what server to locate (and what instance of SQL on that server), which database to attach to on that server (the "initial catalog"), the security model to implement and the credentials (Username/password) to use if not using "integrated" security). If you "hard coded" your connection string then that makes it impossible to change the connection string to adapt to a new database server/dbname/credentials.
Beyond that your question is overly broad for a more direct answer.

A: SqlConnection myConnection = new SqlConnection("user id=username;" +
                                       "password=password;server=serverurl;" +
                                       "Trusted_Connection=yes;" +
                                       "database=database; " +
                                       "connection timeout=30");

http://www.codeproject.com/KB/database/sql_in_csharp.aspx
Try that.


text:
Q: Google Books API Cover images over HTTPS fails due to certificate error Starting yesterday requests to cover images via https began failing with

ERR_INSECURE_RESPONSE.

For example:
https://www.googleapis.com/books/v1/volumes/zaRoX10_UsMC
When trying to access the https version of the thumbnail:
https://bks1.books.google.com/books/content?id=zaRoX10_UsMC&printsec=frontcover&img=1&zoom=1&edge=curl&imgtk=AFLRE72edPPkxV6QHjzfmvf2sug_dIzxNCI02YJVAnqRe6xPdaL1GDx5m-h_2nqbzj2ZJ_krgtSW245c0-gwIF85xUi5rJ2-v07QuQl9ker6apIdeJi27W9RVadaCBwaCqxsQPy-1rt9&source=gbs_api
In Chrome this returns a response of NET::ERR_CERT_COMMON_NAME_INVALID
Safari and Firefox also are unable to load the resource due to a certificate error.

A: Remove the sub-sub-domain, or the encryption:

*

*This is an encrypted version of the image at https://books.google.com, and

*This is an unencrypted version at http://bk1.books.google.com
Their certificate covers wildcard.google.com but not wildcard.wildcard.google.com.  Just speculating I'd guess that bks1 is one of a pool of servers behind books.


text:
Q: Can't connect to local MySQL server through socket (error 2002) i get one error when i try to connect to Mysql server with
mysql -u root -p

error
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (111)

yesterday it worked without any problems


text:
Q: Nginx Config For React and Node App Proxying to Wrong Path I've setup a server with an Nginx config for a React frontend and Node backend.
The Node app serves as an API for the react app.
The node routes for /api/... are getting passed to the following path: /client/public/api/...  This results in a 404.
I understand what may be adding this, I assume the root definition has the /client/public/ path definition. But cannot find a solution around it with the Nginx Config, attached below.
The /client/public/ part of the path string should not be in the uri of the request URL.
server {
  listen                80;
  server_name           www.domain.com;

  root                  /var/www/site_folder/client/public;

  index                 index.html;

  location ~* \.(jpg|jpeg|gif|css|png|js|ico|html)$ {
    access_log          off;
    expires             max;
  }

  location /api/(.*)$ {
    proxy_pass          http://localhost:5000;
  }

  location ~ /\.ht {
    deny                all;
  }
}

A: Try the following location block:
    location /api/ {
        proxy_pass http://localhost:5000/;
    }

Do not miss the trailing slash of the proxy_pass directive parameter! You can find description of this construction behavior here.


text:
Q: R: pick up values based on a given timestamp and save as a new file I have a very large dataset (i.e., measurements) over the past one year. The dataset were collected at 1-min interval. I realized that the difference at 1-min interval is larger than its system error. So, I want to pick up measurements that collected every 1 hour.
How to pick up measurements at 2015-07-08 02:30:00, 2015-07-08 04:30:00, ... etc?
The dataset looks like this:
          timestamp      tr      ts
 1   2015-07-08 02:29:00 1938.23 1978.62
 2   2015-07-08 02:30:00 1936.74 1979.25
 3   2015-07-08 02:31:00 1937.14 1978.99
 4   2015-07-08 02:32:00 1937.66 1978.83
 5   2015-07-08 02:33:00 1937.19 1979.15
 6   2015-07-08 02:45:00 1937.00 1979.00
 7   2015-07-08 02:46:00 1937.75 1979.29
 8   2015-07-08 02:47:00 1937.84 1978.44
 9   2015-07-08 02:48:00 1937.47 1979.17
 10  2015-07-08 02:49:00 1937.82 1978.68
 11  2015-07-08 02:50:00 1937.55 1979.60
 12  2015-07-08 02:51:00 1937.55 1979.13
 13  2015-07-08 02:52:00 1937.65 1979.12
 14  2015-07-08 02:53:00 1937.56 1978.28
 15  2015-07-08 02:54:00 1937.38 1978.99
 16  2015-07-08 02:58:00 1937.86 1978.61
 17  2015-07-08 02:59:00 1937.78 1978.85
 18  2015-07-08 03:00:00 1937.71 1978.68
 19  2015-07-08 03:01:00 1937.14 1979.04
 20  2015-07-08 03:02:00 1936.86 1979.43

Thanks a lot.

A: Especially when you have a large dataset, I highly recommend data.table
 (both speed and usability).
The data.table-solution would be something like this (I assume that you want to have the values for the half-hour and not the average over the past hour):
library(data.table)
dat <- data.table(df) # convert data.frame to data.table
# if timestamp is not POSIXct
# dat[, timestamp := as.POSIXct(timestamp)] # or use the package fasttime

# filter for entries where the time is half past.
filtered.dat <- dat[format(timestamp, "%M") == 30]

Does that help you?


text:
Q: Update TinyMCE textarea value on Fancybox close I'm trying to update the content of a TinyMCE textarea when the user closes a child Fancybox window. This is the function that executes on close which works because my alert is displaying:
$(".popup").fancybox({
          'afterClose': function (){
             var content = $('#profile').html('NEW CONTENT');
            // document.getElementById('profile').value = $_returnvalue;

             alert($_returnvalue);
        },
        });
    });

When I put the following line in function document ready it works so I am guessing it is something to do with TinyMCE updating after page load? Grateful for any help.
var content = $('#profile').html('NEW CONTENT');


text:
Q: the asynctask function is not recognizing the result value I am accessing via AsyncTask the JSON, but in the onPostExecute, the String result is not getting the result value.
I would like it to read json and return the value "perfil", after that, send new to the main activity
credits Google Translate....
Acess MainActivity to MecanismoString
String login = textousuario.getText().toString();
            String senha = textosenha.getText().toString();
            String urllogin = "http...."
            String tipo = "";
            MecanismoString mecanismoString = new MecanismoString(this, this);
            mecanismoString.execute(tipo, urllogin, login, senha);

Asynctask MecanismoString
public class MecanismoString extends AsyncTask <String, String, String> {

    private Interfacestring Interfacestring;
    private RequestQueue requestQueue;
    private StringRequest request;
    private Interfacestring execinterface;

    String usuario, senha, result;

    Context context;
    Toast toast;

    public MecanismoString (Context context, Interfacestring execinterface){
        this.context = context;
        this.Interfacestring = execinterface;
    }

    @Override
    public String doInBackground(String... params) {

        Log.i("Script", "1 ->" + params[0]);
        Log.i("Script", "2 ->" + params[1]);
        Log.i("Script", "3 ->" + params[2]);
        Log.i("Script", "4 ->" + params[3]);

        usuario = params[2];
        senha = params[3];

        requestQueue = Volley.newRequestQueue(context);

        request = new StringRequest(Request.Method.POST, params[1], new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);

                    result = jsonObject.getString("perfil");

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> hashMap = new HashMap<String, String>();
                hashMap.put("login", usuario);
                hashMap.put("senha", senha);

                return hashMap;
            }
        };

        requestQueue.add(request);

        return (result);
    }

    @Override
    protected void onPostExecute(String result) {

        execinterface.carregarString(result);

    }

}

code that returns the value of MecanismoString
public void carregarString(String result) {

        Toast.makeText(context.getApplicationContext(),
                result,
                Toast.LENGTH_SHORT) .show();

    }

Error Log
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: ic.eng.br.eunaobra, PID: 13735
    java.lang.NullPointerException: Attempt to invoke interface method 'void ic.eng.br.eunaobra.Interfacestring.carregarString(java.lang.String)' on a null object reference
        at ic.eng.br.eunaobra.MecanismoString.onPostExecute(MecanismoString.java:94)
        at ic.eng.br.eunaobra.MecanismoString.onPostExecute(MecanismoString.java:22)
        at android.os.AsyncTask.finish(AsyncTask.java:695)
        at android.os.AsyncTask.-wrap1(Unknown Source:0)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6944)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
    (HTTPLog)-Static: isSBSettingEnabled false
I/qtaguid: Untagging socket 76 failed errno=-22
W/NetworkManagementSocketTagger: untagSocket(76) failed with errno -22
Application terminated.

A: please pass a correct context and execinterface object :
MecanismoString mecanismoString = new MecanismoString(MainActivity.this, correct execinterface object);

please remove getApplicationContext() from carregarString()since you already have a context:
 public void carregarString(String result) {
        Toast.makeText(context,result,Toast.LENGTH_SHORT) .show();
    }


text:
Q: Passing Children Styling Down to a Styled Component I am making a generalized version of a styled component to replace duplicated code in my codebase. The component looks something like this:
const CustomDiv = styled.div`
  display:flex;
  b {
     padding-right:5px
   }
`;

const DivWrapper = ({style, children}) => {
  return (
    <CustomDiv style={style}>
      {children}
    </CustomDiv>
  );
};

I want to be use this "DivWrapper" in other places of the code base but be able to change the b padding in other places when using it. I tried extending it like this:
const SuperCustomDiv = styled(CustomDiv)`
  b {
    padding-right:10px
  }
`;

I am using the styled components library for React.

A: You can achieve this by using css props and passing props from the styled-component to the CSS. So, we create styled CSS with some property, then this style place to both styled components. With props, we will pass the value to main style.
import styled, { css } from "styled-components";

const PaddingStyle = (value) => css`
  padding-right: ${value}px;
`;

export const SuperCustomDiv = styled.b`
  ${PaddingStyle((props) => props.padding)}
`;

export const CustomDiv = styled.div`
  display: flex;
  b {
    ${PaddingStyle((props) => props.padding)}
  }
`;

export const DivWrapper = ({ padding = 50, children }) => {
  return (
    <CustomDiv as="div" padding={padding}>
      Name: {children}
    </CustomDiv>
  );
};

export default function App() {
  return (

      <DivWrapper>John Doe</DivWrapper>
      <SuperCustomDiv padding={30}>Super</SuperCustomDiv>
      John Smith

  );
}


text:
Q: Retrieve image from SQLSERVER database using webservice without handlers? I want to know is there any method to retrieve image from SqlServer without using handlers in web services[Asp.net]?
I am currently using this code
In my webservice.cs file
 public class WebService : System.Web.Services.WebService {

        SqlConnection con = new SqlConnection();
        public WebService () {
            con.ConnectionString = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
            if (con.State == ConnectionState.Closed)
            {
                con.Open();

            }
            //Uncomment the following line if using designed components
            //InitializeComponent();
        }

        [WebMethod]
        public string HelloWorld() {
            return "Hello World";
        }
        [WebMethod]
        public void Save_Image(Int32 id, Byte[] ar)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "insert tbimages values(@imageid,@imagename)";
            cmd.Connection = con;
            cmd.Parameters.Add("@imageid", SqlDbType.Int).Value = id;
            cmd.Parameters.Add("@imagename", SqlDbType.Image).Value = ar;
            cmd.ExecuteNonQuery();
            cmd.Dispose();
        }
        [WebMethod]

        public Byte[] Ret_Image(Int32 id)
        {
            SqlCommand cmd =new SqlCommand();
            cmd.CommandText="Select * from tbimages where imageid=@imageid";
            cmd.Connection = con;
            cmd.Parameters.Add("@imageid",SqlDbType.Int).Value = id;
           SqlDataReader dr = cmd.ExecuteReader();
            dr.Read();
            Byte[] ar = (Byte[])(dr[1]);
            dr.Close();
            cmd.Dispose();
            return ar;

           }
    }

and in my sample website where i am using/consuming web services i am using this code i.e. in default.aspx.cs file
public partial class _Default : System.Web.UI.Page
{
    xyz.WebService obj = new xyz.WebService();
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Int32 In = FileUpload1.PostedFile.ContentLength;
        Byte[] ar = new Byte[In];
        FileStream fs = new FileStream(FileUpload1.PostedFile.FileName, FileMode.Open, FileAccess.ReadWrite);
        fs.Read(ar, 0, In - 1);
        fs.Close();
        obj.Save_Image(Convert.ToInt32(TextBox1.Text), ar);
        TextBox1.Text = string.Empty;
        TextBox1.Focus();

    }
   protected void Button2_Click(object sender, EventArgs e)
    {
        Byte[] ar = obj.Ret_Image(Convert.ToInt32(TextBox3.Text));
        string st = Server.MapPath("ar");
        FileStream fs = new FileStream(st, FileMode.Create, FileAccess.Write);
        fs.Write(ar, 0, ar.Length - 1);
        fs.Close();
        Image1.ImageUrl = st;
    }
}

According to me this  line [string st = Server.MapPath("ar");] in protected void Button2_Click(object sender, EventArgs e) should be changed but i don't know which command i have to use

Below code is of design of default.aspx file**
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

    <form id="form1" runat="server">

    Image Id:
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

    Image Path:
    <asp:FileUpload ID="FileUpload1" runat="server" />

<asp:Button ID ="Button1" runat="server"
            Text="Upload" onclick="Button1_Click" />

 Enter Image ID
    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>

<asp:Button ID="Button2" runat="server"
            onclick="Button2_Click" Text="Retrieve Image" />

        <asp:Image ID="Image1" runat="server" />

    </form>

Database table name is tbimages
having two columns

*

*imageid [datatype-  Int]

2. imagename [datatype -- Image]
This is my first post so if i have any mistakes, please mention it also.

A: You can always save the image path/url in the database and retrieve it later when you need it. Place the image url in the html  source tag. Please refer to example below :
<img src="<% image url %>">

Hope this helps!


text:
Q: magento , error with the file field in a Form while editing My form contain a file field for image uploading.
   protected function _prepareForm()
   {
       $form = new Varien_Data_Form();
       $this->setForm($form);
       $fieldset = $form->addFieldset('image_form', array('legend'=>'Image  Informations'));

        $fieldset->addField('img_label', 'text',
                       array(
                          'label' => 'Label',
                          'class' => 'required-entry',
                          'required' => true,
                          'name' => 'img_label',

                    ));
        $fieldset->addField('img_src', 'file',
                         array(
                             'label' => 'Upload Image',
                             'class' => 'required-entry',
                             'required' => false,
                             'name' => 'img_src',
                            ));

        $fieldset->addField('img_desc', 'textarea',
                    array(
                        'label'     => 'Description',
                        'required' => false,
                        'name' => 'img_desc',
                 ));

        $fieldset->addField('img_link', 'text',
                    array(
                        'label'     => 'Link',
                        'required' => false,
                        'name' => 'img_link',
                ));

 if ( Mage::registry('image_data') )
 {
    $form->setValues(Mage::registry('image_data')->getData());
  }
  return parent::_prepareForm();
 }

I only save the file name in my DB, not the whole URL, and whene i'm editing, the field value contain just the image name. If I do not make any changes (image) :

*

*Magento validation detect the field as empty.

Can you help please !
Thanks

A: Try changing addField('img_src', 'file'... to
$fieldset->addField('img_src', 'image', array(
      'label'     => Mage::helper('tag')->__('Upload Image'),
      'required'  => true,
      'name'      => 'img_src',
));


text:
Q: SQL match column value from one table with column values in another without joining I have 2 tables.
One is the task table
 Task Table
WONumber table
WONumber table
Now I need to look for wonumber from the wonumber table and look for the taskname in the task table.
Basically joining the two tables.
I tried this query but it doesnt work
select * from task at t
join wonumber as w
on t.taskname like '%'+w.wonumber+'%'

but this produces like 70000 rows and slows down the database and I have to restart it.
There should be a way to look for one table value in another when both tables are not related.

A: This is for sure bad DB design but if you are sure that task.taskName ends with #*** and wonumber.wonumber starts with # then you can improve performance (a little) using
select * from task at t
join wonumber as w
on t.taskname like '%'+w.wonumber --no trailing '%'

A: Try this if the data pattern is guaranteed to be consistent (# followed by tasknumber in both tables) and that this pattern is at the end in the "Task" table and that there are no spaces at the end.
Select * from
(
Select t.*, Right(t.taskname, Patindex('%#%', t.taskname ) + 1 ) as TaskNum
From Task t
) a INNER JOIN WonNumber w
on a.TaskNum = w.wonumber

BTW you are getting into these odd situations because of a poor db design that Tasknumber should be in its seperate column in both tables and this would be a simple super fast inner join query. So Iam essentially extracting the tasknumber column as a seperate column from the task table so that I can use it to join with the Wonnumber table. HTH !


text:
Q: Better approach to handle multiple editable fields in a block - Angular 4 I have a block of div inside there are several elements which are editable. (snapshot 1 ) On click of 'edit' option the label showing the text should be hidden and corresponding input field be visible (snapshot 2)
This is my approach:
Add a method each on every editable button and write a corresponding method  which will hide the label and show the textbox and vice verse.
But then I'll have to repeat this behaviour for all the editable fields. Is there a better approach? For e.g in Jquery I could just add a common class to all of the edit buttons and and attach a method on click of it.

Sample Code (Of course, I can make this better but just see the approach):

  External ID
  {{externalId}}
  <input class="form-control" type="text" name=""
  [(ngModel)]="externalId" *ngIf="glyphExternalId!=='glyphicon glyphicon-pencil'">

  <input type="checkbox" name="iccEnabled" id="iccEnabled">ICC Enabled

glyphExternalId="glyphicon glyphicon-pencil"
  updateExternalId(){
    this.glyphExternalId = this.glyphExternalId == 'glyphicon glyphicon-pencil'? 'glyphicon glyphicon-ok': 'glyphicon glyphicon-pencil';

  }
Similarly for each of the editable items


text:
Q: jquery validator plugin with display:none form elements I'm using the validator plugin found here to validate a form.
Problem I'm having is if I put the following around a form input element the validation fails:

<input type="text" name="test" />

I need this because I'm using other UI control layers for the input elements and don't want them visible.
It works on inline and block elements, but I need it to be hidden. Is there anyway to get around this?
Thanks for any feedback
Update:
I'm mostly validating select option fields, with django (ie: {{form.select_option_element}} )
So effectively:

    {{form.select_option_element}}

...doesn't work
Right after posting I seem to solve it with:

     {{form.select_option_element}}

It then allows me to validate the field.

A: From the 1.9.0 Change Log of jQuery Validate:

*

*Fixed #189 - :hidden elements are now ignored by default

To turn it back on simply do the following:
$(document).ready(function(){
    $.validator.setDefaults({
        ignore: []
    });
});

Make sure that this appears before you call the actual validation plugin in your code.
I hope this helps!

A: I like the answer of @dSquared but unfortunately 'ignore'-property will be reseted for every form's validator on page. In some cases it doesnt need.
I use this way:
$(document).ready(function () {

    var $form = $("#some-form");

    $form.validate().settings.ignore = []; // ! Say to validator dont ignore hidden-elements on concrete form.

    $('#button-send').click(function () {
        if ($form.valid()) { .. }
    });

    // !! apply plugin's initializers which will hide origin elements (it can be CLEditor or Choosen plugins)
});

A: Have you tried adding the style attribute to the input element? So instead of wrapping it with a div, try:
<input type="text" name="test" value="" style="display: none;" />

A: There are two things you can do.
1) you can statically set value, which does not fail validation, for this input field like

<input type="text" name="test" value="default" />

2) If you want to neglate this value in your validation method.
I would appreciate if you could provide more detail code.

A: Another form to solve this problem is changing the display: none to visibility: hidden.
Eg: <input type="text" name="test" value="" style="visibility: hidden;" />


text:
Q: slicing column in numpy array and creating new matrix I have to concatenate columns of numpy matrix to create new matrix. I have 2 codes. One is working fine. Other is giving me trouble. The one working fine is
x = np.array(range(24))
x = x.reshape((3,4,2))
y = np.array(range(100,124))
y = y.reshape((3,4,2))
z = np.concatenate((x,y))

Now result is 6,4,2 if axis =0 it si 3,8,2 if axis=1 and 3,4,4 if axis=2. But look at another code:
a=np.array(([1,2,3],[4,5,6],[7,8,9])
b=a[:,1] # took one column
c=a[:,0] # again took 1 column
d=np.concatenate((b,c))

If I provide axis=0 result is 1x6. If I provide axis=1 it is again 1,6. I want in 1 case 1,6 in another 3,2. ie
[2,1],[5,4],[8,7]

and in another 2,3 ie
[2,5,8],[1,4,7]

I am wondering why concatenate is not working for me?

A: Use vstack
>>> import numpy as np
>>> a=np.array(([1,2,3],[4,5,6],[7,8,9]))
>>> b=a[:,1] # took one column
>>> c=a[:,0] # again took 1 column
>>> np.vstack((b,c))
array([[2, 5, 8],
       [1, 4, 7]])

Use np.transpose if necessary


text:
Q: Gunicorn Nginx host two websites - Gunicorn creates a sock file only for one I have a Ubuntu server on which I'm trying to host two Django applications using Gunicorn and Nginx.
When I have only one website hosted all works fine. Gunicorn creates a .sock file and nginx redirects to it.
The problem I have is that I have a gunicorn config file for the second site and that doesn't create a .sock file therefore I get a bad gateway error.
Here are my files:
Gunicorn.conf
description "David Bien com application"

start on runlevel [2345]
stop on runlevel [!2345]

respawn
setuid ubuntu
setgid www-data
chdir /home/ubuntu/davidbien

exec venv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/davidbien/davidbien.sock davidbiencom.wsgi:application

The above file works fine. The second one:
Gunicorn1.conf
description "Projects"

start on runlevel [2345]
stop on runlevel [!2345]

respawn
setuid ubuntu
setgid www-data
chdir /home/user/dbprojects

exec virtual/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/dbprojects/dbproject.sock dbproject.wsgi:application

This one doesn't create the .sock file. I tried restarting gunicorn and even tried running the second file only by running sudo service gunicorn1 start but I get:
start: Job failed to start

In the logs there's nothing mentioning the second file running.
What am I doing wrong?

A: Ok, I just noticed a typo in my config file
chdir /home/user/dbprojects

Should be ubuntu no user. This can be closed.


text:
Q: Calc expected value of 5 random number with uniform distribution Assume we have a random numbers $\sim U(0,100)$.
Then the expected value of that number will be: $\int_{0}^{100} \frac{x}{100}$ = 50.5
Now assume we have 5 random numbers $\sim U(0,100)$.
How can I calculate what would be the expected value of the maximal number?
Thanks.

A: You need to learn about order statistics:
https://en.wikipedia.org/wiki/Order_statistics
The maximum of five independent observations is the fifth order statistic (of that sample). In your case, that will have a certain (scaled) beta distribution. You can find the datails in wikipedia above. In your case it will be (100 multiplied by) a beta(5,1)-variable, with expectation $100 \cdot \frac{5}{6}$.

A: Suppose $X_1, X_2, \dots, X_n$ form a random sample of size $n$ from some distribution with p.d.f. $f$, and c.d.f. $F$, then let:
$$
Y = max\{X_1, X_2, \dots, X_n\}
$$
Then the c.d.f. of $Y$ is given by
\begin{align*}
   G(y) & =  \text{Pr}(Y \le y) = \text{Pr}(X_1 \le y, X_2 \le y, \dots, X_n \le y)\\
   & = \text{Pr}(X_1 \le y)\text{Pr}(X_2 \le y)\dots\text{Pr}(X_n \le y) \\
   & = F(y)F(y)\dots F(y) = [F(y)]^n
\end{align*}
The first line says $y$ must be greater or equal to all $n$ samples. The second line follows from the independence of each sample. Then the p.d.f. of $Y$ is
$$
g(y) = n[F(y)]^{n - 1}f(y)
$$
which is just the derivative of $F$.


text:
Q: Migrating Struts1  tag I am in process to migrate some Struts1 code to Struts2 and confused about migration of below tags.
Struts1:
<logic: notEmpty name="newsListForm" property="generalNews.list">
    <logic:iterate id="generalNews"
        name="newsListForm"
        property="generalNews.list"
        type="com.ab.NewsDTO"
        indexId="rowCount">
        <%
            if(rowCount.longValue() % 2 == 0){
             bgcolor = "#FFFFF";
            }else{
             bgcolor = "#EEEEE";
            }
        %>
     </logic: iterate>
    </logic: notEmpty>

I have migrated above code as:
Struts2
<s:if test="(newsListBean.generalNews.list != null)">
 <s:iterator id="generalNews"
            values="generalNews.list"
            status="incrementer">
    <s:if test="#incrementer.even==true">
<% pageContext.setAttribute("bgcolor","#FFFFFF")%>
</s:if>
 <s:else>
<% pageContext.setAttribute("bgcolor","#EEEEEE")%>
</s:else>
>

</s:iterator>
</s:if>

Is it a correct way to migrate these iterate & <logic:notEmpty> tags?

A: No, it's not correct. The original code use tags and scriptlet code to generate some text which is probably a JavaScript code.
But converted code doesn't do it. Instead it is used to set a page context attribute.

A: Somewhat off-topic, but related: there's a way, way cleaner way to do this by using proper CSS.
First have classes for the row colors: this is something you should have anyway rather than wedging presentation definitions into JSP code:

Then use those to construct classnames for whatever it is you need (here, likely s):
<s:iterator id="generalNews" values="generalNews.list" status="stat">

</s:iterator>

(Roughly; this is from memory.)


text:
Q: A function with non-vanishing derivative at a point gives a coordinate chart at the point. Let $M$ be a smooth manifold and let $p\in M$. Suppose we have $f\in C^\infty(M)$ such that $df(p)\neq 0$. Then there exists $U\ni p$ open and $x^i\in C^\infty(U)$, $i\in \{2,\dots,n\}$, such that $(U,(f,x^2,\dots,x^n))$ is a chart at $p$.

I think one can the use the rank theorem directly. That is, there exists a chart $(V,x)$ such that  $f|_{V}=x^1$. So $(V,(f,x^2,\dots,x^n))$ (the original chart) does the trick and we are done.
Is this very short answer correct?
Alternatively, I though of using another argument (similar to part of the proof of the rank theorem)
Take a chart $(V,x)$ and reorder coordinate so that $\partial_1 f(p)\neq 0$. Define a map $\phi:V\to\mathbb R^n$ by $\phi(p)=(f(p),x^2(p),\dots,x^n(p))$. Then we have
$$D\phi(p) =\begin{bmatrix}
\partial_1 f(p)& \mathbf{0}\\
\mathbf 0& \delta^i_j
\end{bmatrix}
$$
Thus, $D\phi$ is non-singular at $p$ (it is just the identity), hence, by the inverse function theorem, it is local diffeomorphism over some $U\subset V$. Thus, $(U,\phi=(f,x^2,\dots,x^n))$ is a chart.
Is any of these two answers correct?
Thanks in advance!

A: Your second approach is the correct one (though $D\phi(p)$ is not necessarily the identity as you claim). The first approach doesn't even prove anything. Just because at a single point we have $f(p)=x^1(p)$, it doesn't mean you can replace $x^1$ with $f$ (not even in a small neighborhood of $p$). Also, you didn't use the assumption $df(p)\neq 0$ (and clearly by dropping this hypothesis, the claim becomes false, as shown by the counterexample $f=0$).
For example, say our manifold is the trivial $M=\Bbb{R}^2$, and let $(x^1,x^2)$ be the usual Cartesian coordinate chart. Let's say $p=(0,0)$, and $f:M\to\Bbb{R}$, $f(a,b)=b$, i.e $f=x^2$. Then, $df=dx^2$ is in fact nowhere vanishing, and at the specific point $p$, we have $f(p)=x^1(p)=0$. Imagine what would happen if we were to replace $x^1$ with $f$; we'd get $(f,x^2)=(x^2,x^2)$, which is obviously not a diffeomorphism, no matter how small of a neighborhood of $p=(0,0)$ you restrict to.