text:
Q: Programmatically Setting Public Property in Class Ctor I want to programmatically set a public property within a class' constructor in PowerShell V5.0. The test class has many public properties that are to be filled in depending on the object passed to the class' constructor (lovingly referred to as '$something')
I thought it'd save a lot of code if I created an array of public property names which was accessible and iterate through them, as the setting the value of the public properties is just calling the same method on the $something object passed to it.
Tried using the Set-Variable cmdlet on every scope (I thought it'd be local scope). It could be done manually setting each public property in the constructor, but I'd love to be able to shorten it if possible.
    Class TestClass
    {
        [STRING]$PublicProperty
        [STRING]$PublicProperty1
        ... ... ... #Loads more properties
        [STRING]$PublicProperty50
        #An array that contains name for public properties
        [ARRAY]$ArrayOfPublicProperties = @("PublicProperty", "PublicProperty1"...)

        TestClass($something)
        {
            foreach ($property in $this.ArrayOfPublicProperties)
            {
                Set-Variable -Name "$($property.Name)" -Scope Local -Value $($something.GetValue(#blablabla))
            }
        }
    }

I expect to be able to iterate through the public array (it's gross code, but it works for the situation I'm in and I don't know enough to think of any other ways) and set the variable using the Set-Variable cmdlet. Instead it doesn't set anything. I'm sure I've done something similar in the past, programmatically creating and setting variables etc... idk.
Pls to help

A: Set-Variable only works with regular variables, not with properties.
You must use reflection via .psobject.properties, which also obviates the need for the $ArrayOfPublicProperties helper property:
Class TestClass
{
    [string]$PublicProperty
    [string]$PublicProperty1
    # ...

    TestClass($something)
    {
        # Loop over all properties of this class.
        foreach ($prop in $this.psobject.Properties)
        {
          $prop.Value = $something.GetValue(#blablabla)
        }
    }
}

Note, however, that PowerShell conveniently allows constructing and initializing objects by a way of a cast from a hashtable or (custom) object that have matching properties.
Caveats: For this to work:

*

*the class must either have NO constructor (i.e., implicitly support only the parameter-less default constructor),

*OR, if there are constructors:

*

*a parameter-less constructor must exist too.

*

*Symptom, if that condition isn't met: a type-conversion error: Cannot convert ... to type ...

*AND there's not also a single-argument constructor (implicitly) typed [object] or [hashtable] (with a hashtable cast argument, [psobject] / [pscustomobject] is fine, however).

*

*Symptom, if that condition isn't met: the single-argument constructor is called.

*The set of property names  of the input hashtable / object must be a subset of the target class' properties; in other words: the input object mustn't contain properties that aren't also present in the target class, but not all target-class properties must be present.
Applied to your example (note that there's no longer an explicit constructor, because the original constructor, TestClass($something), would defeat the feature, due to $something being implicitly [object]- typed):
Class TestClass
{
    [string]$PublicProperty
    [string]$PublicProperty1
    # ...
    # Note: NO (explicit) constructor is defined.
}

# Construct a [TestClass] instance and initialize its properties
# from a hashtable, using a cast.
[TestClass] @{ PublicProperty = 'p0'; PublicProperty1 = 'p1'}


text:
Q: Domain names on 2 similar windows domains (active directory) I am fairly new to windows administration (Server 2008r2), but I am putting together a new environment, and am setting up active directory domains.
I have broken my system into 2 parts, management (mgt) and operational (ops).
They are both parts of the same system, but their availability needs are a bit different.
I decided to call my system "vmnet".
I created 2 domains, vmnet.ops and vmnet.mgt.
I assumed that these would be completely separate domains, much like .com and .org websites.
Unfortunately, as I was configuring a file share on vmnet.mgt, I realized that a user with the same name on vmnet.ops did NOT have to enter credentials to access the share.
So:
1) Folder on a mgt domain server shared to jake@vmnet.mgt via windows share.
2) Logged into a ops domain workstation (jake@vmnet.ops), and try to access the shared folder.
3) It lets me in with no entry of credentials.
4) Looking at the shared folder permissions from the vmnet.ops box, it says it is shared with jake@vmnet.ops
5) Looking  at the actual shared folder from the vmnet.mgt machine, it claims it is shared with only jake@vmnet.mgt.
There seems to be overlap here. Different domains, should have completely different UID? No overlap at all?
Or have I messed up, and vmnet.ops and vmnet.mgt are the same domain, and the .mgt/.ops are irrelevant?

A: If there is a jake user on each domain with the same password, jake from one domain will be able to access shares on the other domain because the password is the same.  It works like this:

*

*If jake@domain1 is accessing resources in domain1, a password is not sent to the system hosting the resource because jake got a security token when he logged in to the domain, and the security token is used to gain access.

*If jake@domain1 is accessing resources that are NOT on domain1 (i.e., in domain2, or a system that isn't in a domain), it will pass jakes username and password to the other system, and if the credentials match for a jake user on that domain or computer, then jake will get access to those resources.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to render RichEdit Text to a canvas by keeping font smoothness  i am trying to render RichEdit to a bitmap. I want to make backgrond tranparent.
I could achieve that by the code above. The problem is that when i set bitmap as tranparent
only the transparent color becomes transparent. Is there any way to handle the pixels on the edge
which are diffrent from background color and also different from font color. i mean making the  pixels
semi-tranparent on the edge which makes a smooth view.
    Graphics::TBitmap *bitmap = new Graphics::TBitmap();
    bitmap->Width = RichEdit1->Width ;
    bitmap->Height = RichEdit1->Height ;

    TRect BoundingBox(0,0,RichEdit1->Width, RichEdit1->Height) ;

    // Render RichEdit to bitmap
    TFormatRange formatRange;
    int twipsPerPixel = 1440 / Screen->PixelsPerInch;

    formatRange.hdc = bitmap->Canvas->Handle;
    formatRange.hdcTarget = bitmap->Canvas->Handle;
    formatRange.chrg.cpMin = 0;
    formatRange.chrg.cpMax = -1;

    formatRange.rc.top = 2 * twipsPerPixel;
    formatRange.rc.bottom = (BoundingBox.Height() - 4) * twipsPerPixel + formatRange.rc.top;
    formatRange.rc.left = 2 * twipsPerPixel;
    formatRange.rc.right = (BoundingBox.Width() - 4) * twipsPerPixel;

    // Measure text's height.
    RichEdit1->Perform(EM_FORMATRANGE, 0, 0);
    RichEdit1->Perform(EM_FORMATRANGE, 0, (LPARAM) &formatRange);

    formatRange.rc.bottom = (BoundingBox.Height() - 4) * twipsPerPixel + formatRange.rc.top;
    formatRange.rc.left = 2 * twipsPerPixel;
    formatRange.rc.right = (BoundingBox.Width() - 4) * twipsPerPixel;

    formatRange.rcPage = formatRange.rc;

    /**
    * Draw..
    **************************************************************************/
    RichEdit1->Perform(EM_FORMATRANGE, 1, (LPARAM) &formatRange);
    RichEdit1->Perform(EM_FORMATRANGE, 0, 0);

   // Draw background
   // Use different background color to see the trasparency problem
   this->Canvas->Brush->Color = clRed ;
   this->Canvas->Rectangle(0,0,RichEdit1->Width , RichEdit1->Height );

   // Draw the transparent bitmap
   bitmap->Transparent = true ;
   bitmap->TransparentColor = RichEdit1->Color ;
   this->Canvas->Draw(0,0,bitmap);

Thanx.

A: Font smoothing works with partial transparency using an alpha channel. The Transparent and TransparentColor properties of TBitmap are therefore not applicable.
You haven't said which version of the C++ Builder/VCL you are using, but more modern versions have better support for partial transparency than some of the older ones.
To get this to work you will need to set the PixelFormat of your bitmap to be pf32bit. You may also need to set AlphaFormat to afDefined.
If you can't get TBitmap to do what you need then you'll have to revert to GDI commands to create a suitable HBITMAP. You can at least assign that to the Handle property of a TBitmap and usually from there everything behaves.
Note that I am not a user of C++ Builder but do know the VCL from Delphi.
UPDATE
I tried this out in Delphi and the following worked fine for me:
procedure TForm4.Button1ClickBMP(Sender: TObject);
var
  BMP: TBitmap;
  fmtRange: TFormatRange;
  intPPI, Flags: Integer;
begin
  BMP := TBitmap.Create;
  Try
    BMP.PixelFormat := pf32bit;
    BMP.SetSize(RichEdit1.Width, RichEdit1.Height);

    FillChar(fmtRange, SizeOf(fmtRange), 0);
    with fmtRange do begin
      hDC := BMP.Canvas.Handle;
      hdcTarget := hDC;
      intPPI := Screen.PixelsPerInch;
      rc := Rect(
        0,
        0,
        RichEdit1.Width*1440 div intPPI,
        RichEdit1.Height*1440 div intPPI
      );
      rcPage := rc;
      chrg.cpMin := 0;
      chrg.cpMax := -1;
    end;
    Flags := 1;
    RichEdit1.Perform(EM_FORMATRANGE, Flags, Longint(@fmtRange));
    RichEdit1.Perform(EM_FORMATRANGE, 0, 0);
    BMP.SaveToFile('c:\desktop\test.bmp');
  Finally
    FreeAndNil(BMP);
  End;
end;

The output looks like this, blown up somewhat to see the anti-aliasing:

I hope this helps, because it looks like you are very nearly there!

A: As David has answered already, sub-pixel antialiasing requires knowledge of the background colour. This is explained in more detailed in this answer. In essence, when you do sub-pixel anti-aliasing you treat the three colour channels as having different spatial offsets (which is where the apparent increase in resolution comes from). This means they need different alpha values, but of course there is only one alpha channel.
You can of course do regular full-pixel grayscale antialiasing over a transparent background. Perhaps this would be good enough? Some of the other answers in the question linked above suggest ways to achieve this. Have a look at ANTIALIASED_QUALITY (vs. CLEARTYPE_QUALITY) in the LOGFONT structure. (I haven't tried this.)


text:
Q: How to send multiple FormData objects to server using AJAX and access those objects on the server I am trying to develop a page where teachers can go and create quizzes for their students. To meet this end, there are two forms on the page. One form is for creating the actual quiz and the other is for creating the questions that go on the quiz.
Everytime the teacher adds a question to the quiz, a JS function is called which saves the question data locally in a FormData object, which is then placed into an array of questions. Keep in mind that one of the inputs on the question form is a file input.
When the teacher finally submits the quiz, I use an AJAX call that sends two items to the server: a FormData object containing the quiz data and an array of FormData objects containing the information about the questions on the quiz.
My question is: how do I access these different objects on the server? I am using CakePHP so my initial thought was $this->request->data["quiz"] and $this->request->data["questions"], but I keep getting a "index quiz/question not found" error. Is there a better way for me to be sending this data? Many many thanks to any help you can provide.
Javascript
var questions = [];
var currentQuizQuestion = 0;

function saveNewQuestion()
{
    var formData = new FormData(document.getElementById("inputQuestionForm"));
    questions[currentQuizQuestion] = formData;
    currentQuizQuestion++;
}

function saveQuiz()
{
    var quizData = new FormData(document.getElementById("inputQuizForm"));
    $.ajax({
        type: "POST",
        url: "create",
        data:
        {
            quiz: quizData,
            questions: questions
        },
        processData: false,
        contentType: false
    });
}

CakePHP
public function create()
{
    if($this->request->is("post"))
    {
        $quiz = $this->request->data["quiz"];
        $questions = $this->request->data["questions"];
        ...
    }
}


text:
Q: Laravel Vue DELETE method not supported for this route. Supported methods: GET, HEAD I have the following code in my actions.js.
export const deleteUser = ({ dispatch }, payload) => {
    console.log("El numero de id es js: ", payload.id);
    return axios
        .delete(window.urls.user.delete(payload.id))
        .then(respone => {
            dispatch("fetchUsers");
            return Promise.resolve();
        })
        .catch(error => {
            return Promise.reject(error);
        });
};

api.php
Route::delete('/{user}', [
    'uses' => 'UserController@destroy',
    'middleware' => 'permission:user.delete',
    'can:delete,user'
]);

config.blade.php
user: {
            index : '/user',
            store: '/user',
            update: function(userid){
                return '/user/' + userid
            },
            delete: function(id){
                return '/user/' + id;
            }
        },

Controller
public function destroy(Request $request, $id)
{
    $user = User::find($id);
    $user->delete();
}

A: I think the problem is your user route definition. Assuming you don't use route grouping instead of
Route::delete('/{user}', [
            'uses' => 'UserController@destroy',
            'middleware' => 'permission:user.delete',
            'can:delete,user'
        ]);

you should try:
Route::delete('/user/{user}', [
            'uses' => 'UserController@destroy',
            'middleware' => 'permission:user.delete',
            'can:delete,user'
        ]);


text:
Q: NullPointerException in XMLEntityManager when trying to compile an xml schema with xjc / ant I'm seeing an exception, seemingly inside some sun classes, when trying to compile an xml schema.
I've compiled this schema many times before, so I don't suspect the schema of being problematic.  I think something may have changed in my java VM, perhaps with the latest upgrade.  I have no doubt that upgrading to jaxb 2.0 would fix the problem, since I tried it.  However, we have to stick to jaxb 1.0 due to a bug in the JAXB-RI XJC.

Macbook: ant -f build-response.xml
Buildfile: /Users/matt/workspace/resources/build-response.xml

compilexjc:
     [echo] Compiling the schema...
      [xjc] Compiling file:/Users/matt/workspace/schemas/response/partner_response.xsd and others

BUILD FAILED
/Users/matt/workspace/resources/build-response.xml:34: java.lang.NullPointerException
    at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.reset(XMLEntityManager.java:1550)
    at com.sun.org.apache.xerces.internal.parsers.BasicParserConfiguration.reset(BasicParserConfiguration.java:503)
    at com.sun.org.apache.xerces.internal.impl.xs.opti.SchemaParsingConfig.reset(SchemaParsingConfig.java:541)
    at com.sun.org.apache.xerces.internal.impl.xs.opti.SchemaParsingConfig.parse(SchemaParsingConfig.java:408)
    at com.sun.org.apache.xerces.internal.impl.xs.opti.SchemaParsingConfig.parse(SchemaParsingConfig.java:491)
    at com.sun.org.apache.xerces.internal.impl.xs.opti.SchemaDOMParser.parse(SchemaDOMParser.java:510)
    at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.getSchemaDocument(XSDHandler.java:1802)
    at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.parseSchema(XSDHandler.java:531)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.loadSchema(XMLSchemaLoader.java:556)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.loadGrammar(XMLSchemaLoader.java:523)
    at com.sun.org.apache.xerces.internal.parsers.XMLGrammarPreparser.preparseGrammar(XMLGrammarPreparser.java:202)
    at com.sun.tools.xjc.reader.xmlschema.parser.SchemaConstraintChecker.check(SchemaConstraintChecker.java:78)
    at com.sun.tools.xjc.GrammarLoader.loadXMLSchema(GrammarLoader.java:330)
    at com.sun.tools.xjc.GrammarLoader.load(GrammarLoader.java:127)
    at com.sun.tools.xjc.GrammarLoader.load(GrammarLoader.java:76)
    at com.sun.tools.xjc.XJCTask._doXJC(XJCTask.java:358)
    at com.sun.tools.xjc.XJCTask.doXJC(XJCTask.java:307)
    at com.sun.tools.xjc.XJCTask.execute(XJCTask.java:247)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
    at org.apache.tools.ant.Task.perform(Task.java:348)
    at org.apache.tools.ant.Target.execute(Target.java:435)
    at org.apache.tools.ant.Target.performTasks(Target.java:456)
    at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1393)
    at org.apache.tools.ant.Project.executeTarget(Project.java:1364)
    at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
    at org.apache.tools.ant.Project.executeTargets(Project.java:1248)
    at org.apache.tools.ant.Main.runBuild(Main.java:851)
    at org.apache.tools.ant.Main.startAnt(Main.java:235)
    at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
    at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)

Total time: 1 second

My build-response.xml file looks like this:
<project name="ERRequest" default="compilexjc" basedir=".">
 <target name="init">
  <tstamp/>
 </target>

<!-- Configure the context path for this application -->
<property name="appname" value="WPI" />
<property name="apppath" value="." />
<property name="path" value="${apppath}"/>

<property name="tmp" value="../tmp_response"/>

<!-- Configure properties to access the Manager application -->
<property file="build.properties"/>

<path id="classpath">
<fileset dir="${LIBS_JARPATH}" includes="*.jar" />
<fileset dir="${JAXB_LIB}" includes="*.jar" />
</path>

<!-- Configure the custom Ant tasks for the Manager application -->
<taskdef name="xjc" classname="com.sun.tools.xjc.XJCTask">
  <classpath refid="classpath" />
</taskdef>

<!--compile Java source files-->
<target name="compilexjc" description="Generate Java source files from XSD">
  <mkdir dir="${tmp}"/>
 <echo message="Compiling the schema..." />
<xjc target="${tmp}" package="com.mycompany.binding.response"> <!--exception is thrown here-->
    <schema dir="../schemas">
        <include name="response/response.xsd"/>
          <include name="response/partner_response.xsd"/>
      </schema>
      <produces dir="${tmp}" includes="**/*.java"/>
  </xjc>
  <copy todir="${tmp}">
    <fileset dir="${tmp}">
        <include name="**/*.properties"/>
    </fileset>
</copy>
</target>

The XJC classes are located in jaxb-xjc.jar which is in the classpath.  Here is the meta info for that jar:
Implementation-Version: 1.0.5
Specification-Title: Java Architecture for XML Binding
Specification-Version: 1.0

A: The solution was to upgrade jaxb to version 2.2.7. I couldn't resolve it in jaxb 1.0.
In fact it was more complicated than that, since there is a bug in the JAXB-RI 2.2.7 which I had to patch.  See this question and answer.


text:
Q: Excel graph legend doesn't match markers I've formatted the markers of a chart using VBA:
Dim sc As SeriesCollection
Set sc = MySheet.ChartObjects("MyChart").Chart.SeriesCollection

Dim p As Point, s As Series
For Each s In sc
    For Each p In s.Points
        p.Format.Fill.ForeColor.RGB = s.Format.Line.ForeColor.RGB
        p.Format.Fill.BackColor.RGB = s.Format.Line.ForeColor.RGB
        p.MarkerSize = 3
    Next p
Next s

However, the markers in the chart area don't match up with the markers in the legend (the border colour is the same, but the fill colour in the legend is different). Note the colour inside the boxes on the right (the legend):

I've looked around at a few different properties of the Chart family, but can't find what controls this. The Point properties MarkerBackgroundColor and MarkerForegroundColor seemed likely, but don't fix it. How can I fix this?

A: Since you were looping the seriescollection, you could simply do all the markers in one go:
For Each s In sc
    s.MarkerBackgroundColor = s.Border.Color
    s.MarkerSize = 3
Next s

A: Found with a bit more digging:
Worksheet.ChartObjects(Index).Chart.Item(Index).Format.Fill.ForeColor.RGB

Pretty lengthy!


text:
Q: Pandas, Memory error when trying to substract two arrays I'd been working with a large dataset with shape (345602,12) doing all sorts of analysis with scikitlearn. I had no problems until I ran the RandomForestRegressor:
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    test_size=0.4,
                                                    random_state=1)

forest = RandomForestRegressor(n_estimators=100,
                               criterion='mse',
                               random_state=1,
                                n_jobs=-1)

forest.fit(X_train, y_train)
y_train_pred = forest.predict(X_train)
y_test_pred = forest.predict(X_test)

This part works, resulting in:
print(y_train.shape, y_train_pred.shape)
(207361,1) (207361,)

print(y_test.shape, y_test_pred.shape)
(138241,1) (138241,)

Then, when I tried to simply substract them:
A=y_train_pred - y_train
B=y_test_pred - y_test

That is the point where it crashes.

MemoryError: Unable to allocate 320. GiB for an array with shape
  (207361, 207361) and data type float64

I find this very strange since I was using this tool with a smaller dataset without any problems.

A: Well, I found the issue, it was an easy one. The problem is on the shape of the arrays.
RandomForestRegressor returned the predictions as an r rows and the non-data as one of c columns. Therefore, when substracting, pandas was creating a matrix of rxc instead of a single dimension array.
The error is solved by transposing one of pairs of values.
A=y_train_pred - np.transpose(y_train)
B=y_test_pred - np.transpose(y_test)


text:
Q: Maple - Integration returns undefined for very simple and possible integrations This is a question about maple producing undefined errors.
The code below should give the result 0 but instead maple chooses to label it "undefined".
(nj*(nj-1))*(int(N^(ni+nj-2),N=-1..1));
ni:=0;  nj:=0;

Since nj=0 you can see quite clearly that even before the integral, the answer is 0 x integral.
The integral is possible to do and doing it by hand it gives you (-1/N) evaluated between 1 and -1
so substituting in (-1/1)-(-1/-1) which is -1-1 = -2).
The overall answer is given by 0x-2 which is 0.
Maple returns undefined.
However if you take a subsection of that code (just the integral)
 (int(N^(ni+nj-2),N=-1..1)) or even (int(N^(-2),N=-1..1))

then maple returns infinity.
Neither of these are correct.
Can anyone explain to me why this happens?
I think others are likely to come across a similar issue because it is such a simple maple procedure. Yet it gives a confusing result.

A: As was already shared in the comments, 0 times infinity is undefined, see e.g. Why is infinity multiplied by zero not an easy zero answer
To still keep your Maple sheet as intact as possible, you can always include if-statements in the code, which is really easy
if nj = 0 then
 #do something
end if;

However, you should always check if you are doing the right thing mathematically, as Maple does output Undefined for a reason!


text:
Q: How to modify this batch script to delete oldest subfolders instead of files in a directory? The following batch file can be invoked by running limitdirsize.bat c:\example 4000000 to limit C:\example to 4GB. It works well when dealing with a folder containing only files.
When run, it deletes the oldest files in the directory until the size of the folder is 4GB.
@echo off
setlocal enabledelayedexpansion
set /a targetsize=%2
call :foldersize %1
for /F "tokens=*" %%F in ('dir /A-D /OD /B %1\*.*') do (
  if !sz! geq !targetsize! (
    call :filesize %1\%%F
    del %1\%%F
    set /a sz = !sz! - !kb!
  ) else (
    echo Done... %1 size is now !sz! KB
    goto :eof
  )
)
echo Not completely done... %1 size is still !sz! KB
goto :eof

:filesize
set /a kb = %~z1 / 1024
goto :eof

:foldersize
set sz=0
for %%F in (%1\*.*) do (
  set /a kb = %%~zF / 1024
  set /a sz = !sz! + !kb!
)
goto :eof

I would like to limit the size of a directory which contains only subdirectories.
The batch script for determining subdirectory size would be
:foldersizerecurse
set sz=0
for /F %%F in ('dir /OD /B *.*') do (
  set /a kb = %%~zF / 1024
  set /a sz = !sz! + !kb!
  echo %%F %%~zF !kb! !sz!
)
goto :eof

According to the author of this code:

you need to pipe the 'dir /S' command output to sort and sort by date

For clarity: :foldersize calculates the size of the folder being cleaned, and everything between line 4 and that function is for recognizing older files and deleting them until the desired size of the directory is reached.


text:
Q: How to DOM made select element value from one javascript function to another I want to ask that how can I call the value of select option which i made in the selectInput function and and now i want to call the value of select option value in searchPanel function i made selectInput function return type still i unable to call the value
    function searchPanel() {
           const div = document.createElement("div");

           div.appendChild(selectInput());
     }

     function selectInput() {
        const select = document.createElement("select");
        select.className = `form-control form-control-sm mb-3`;
        select.id = "disposal-type";
        select.setAttribute("name", "disposal");

              const option_Case = document.createElement("option");
              option_Case.appendChild(document.createTextNode("Case"));
              option_Case.setAttribute("value", "Case");
              select.appendChild(option_Case);

              const option_Petition = document.createElement("option");
              option_Petition.appendChild(document.createTextNode("Petition"));
              option_Petition.setAttribute("value", "Petition");
              select.appendChild(option_Petition);

       return select;
      }

A: Can you try to call the selectInput() before div.appenchild and store it in a constant and then use it.
function searchPanel() {
  const div = document.createElement("div");
  const select = selectInput();
  div.appendChild(select);
}

A: Your selectInput function is returning the select DOM object correctly.
If you want to check the select option values, you may iterate over select options and use options array property to access its values.
const select = selectInput();

for (var i = 0; i < select.length; i++) {
    var option = select.options[i];
    alert(option.text + " " + option.value);
}

To display it on the screen:
If you want this select to appear on the screen, you should attach it to the document object as follows:
document.body.appendChild(div);

Also, call the searchPanel method in the body tag using onload event attribute.
<body onload="searchPanel()"></body>


text:
Q: How to remove characters from an excel sheet? My overall problem is that I have a large Excel file(Column A-S, 85000 rows) that I want to convert to XML.  The data in the cells is all text.
The process I'm using now is to manually save the excel file as csv, then parse that in my own c# program to turn it into XML.  If you have better recommendations, please recommend. I've searched SO and the only fast methods I found for converting straight to XML require my data to be all numeric.
(Tried reading cell by cell, would have taken 3 days to process)
So, unless you can recommend a different way for me to approach the problem, I want to be able to programmatically remove all commas, <, >, ', and " from the excel sheet.

A: There are many options to read/edit/create Excel files:
MS provides the free OpenXML SDK V 2.0 - see http://msdn.microsoft.com/en-us/library/bb448854%28office.14%29.aspx (XLSX only)
This can read+write MS Office files (including Excel).
Another free option see http://www.codeproject.com/KB/office/OpenXML.aspx (XLSX only)
IF you need more like handling older Excel versions (like XLS, not only XLSX), rendering, creating PDFs, formulas etc. then there are different free and commercial libraries like ClosedXML (free, XLSX  only), EPPlus (free, XLSX only), Aspose.Cells, SpreadsheetGear, LibXL and Flexcel etc.
Another option is Interop which requires Excel to be installed locally BUT Interop is not supported in sever-scenarios by MS.
Any library-based approach to deal with the Excel-file directly is way faster than Interop in my experience...

A: I would use a combination of Microsoft.Office.Interop.Excel and XmlSerializer to get the job done.
This is in light of the fact that a) you're using a console appilcation, and b) the interop assemblies are easy to integrate to the solution (just References->Add).
I'm assuming that you have a copy of Excel installed in the machine runnning the process (you mentioned you manually open the workbook currently, hence the assumption).
The code would look something like this:
The serializable layer:
public class TestClass
{
    public List<TestLineItem> LineItems { get; set; }

    public TestClass()
    {
        LineItems = new List<TestLineItem>();
    }
}

public class TestLineItem
{
    private string SanitizeText(string input)
    {
        return input.Replace(",", "")
            .Replace(".", "")
            .Replace("<", "")
            .Replace(">", "")
            .Replace("'", "")
            .Replace("\"", "");
    }

    private string m_field1;
    private string m_field2;

    public string Field1
    {
        get { return m_field1; }
        set { m_field1 = SanitizeText(value); }
    }

    public string Field2
    {
        get { return m_field2; }
        set { m_field2 = SanitizeText(value); }
    }

    public decimal Field3 { get; set; }

    public TestLineItem() { }

    public TestLineItem(object field1, object field2, object field3)
    {
        m_field1 = (field1 ?? "").ToString();
        m_field2 = (field2 ?? "").ToString();

        if (field3 == null || field3.ToString() == "")
            Field3 = 0m;
        else
            Field3 = Convert.ToDecimal(field3.ToString());
    }
}

Then open the worksheet and load into a 2D array:
// using OExcel = Microsoft.Office.Interop.Excel;
var app = new OEXcel.Application();
var wbPath = Path.Combine(
    Environment.GetFolderPath(
        Environment.SpecialFolder.MyDocuments), "Book1.xls");

var wb = app.Workbooks.Open(wbPath);
var ws = (OEXcel.Worksheet)wb.ActiveSheet;

// there are better ways to do this...
// this one's just off the top of my head
var rngTopLine = ws.get_Range("A1", "C1");
var rngEndLine = rngTopLine.get_End(OEXcel.XlDirection.xlDown);
var rngData = ws.get_Range(rngTopLine, rngEndLine);
var arrayData = (object[,])rngData.Value2;

var tc = new TestClass();

// since you're enumerating an array, the operation will run much faster
// than reading the worksheet line by line.
for (int i = arrayData.GetLowerBound(0); i <= arrayData.GetUpperBound(0); i++)
{
    tc.LineItems.Add(
        new TestLineItem(arrayData[i, 1], arrayData[i, 2], arrayData[i, 3]));
}

var xs = new XmlSerializer(typeof(TestClass));
var fs = File.Create(Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
    "Book1.xml"));
xs.Serialize(fs, tc);

wb.Close();
app.Quit();

The generated XML output will look something like this:
<TestClass>
  <LineItems>
    <TestLineItem>
      <Field1>test1</Field1>
      <Field2>some&lt;encoded&gt; stuff here</Field2>
      <Field3>123456.789</Field3>
    </TestLineItem>
    <TestLineItem>
      <Field1>test2</Field1>
      <Field2>testing some commas, and periods.</Field2>
      <Field3>23456789.12</Field3>
    </TestLineItem>
    <TestLineItem>
      <Field1>test3</Field1>
      <Field2>text in &quot;quotes&quot; and &#39;single quotes&#39;</Field2>
      <Field3>0</Field3>
    </TestLineItem>
  </LineItems>
</TestClass>


text:
Q: Devise token auth not returning the Set-Cookie header on different domain I have a rails 4 backend using DeviseTokenAuth and an AngularJS frontend using ngTokenAuth.
When frontend and backend are deployed on the same domain the authentication works perfectly.
When testing on localhost, with both the backend and the frontend running on localhost on two different ports the sign_in request completes with 200 OK but the response doesn't contain Set-Cookie header and so the client remains unauthenticated for the following requests.
Down here you can see a copy of the headers received in the sign_in response in both scenarios.
The problem is the same also if I try to authenticate from a frontend running locally to the RAILS backend deployed on server.
The CORS headers are configured like this on the server and everything seems fine to me about cross origin:
config.middleware.insert_before 0, "Rack::Cors" do
    allow do
    origins '*'
    resource '*', :headers => :any, :methods => [:get, :post, :options]
    end
end

Deployed on server
Accept-Ranges:bytes
Access-Control-Allow-Credentials:true
Access-Control-Allow-Methods:GET, POST, OPTIONS
Access-Control-Allow-Origin:example.org
Access-Control-Expose-Headers:
Access-Control-Max-Age:1728000
access-token:XXXXXXXXXXOI9s2x0IuVMA
Age:0
Cache-Control:max-age=0, private, must-revalidate
client:XXXXXXXXXXAP2TsoBZTnjg
Connection:keep-alive
Content-Type:application/json; charset=utf-8
Date:Thu, 04 May 2017 09:28:17 GMT
ETag:W/"XXXXXXXXXXc86bb292d476d2366d3742"
expiry:1495099697
Server:nginx/1.10.0 (Ubuntu)
Set-Cookie:_differenthood_session=ZE1NWndTUUVmMkNDbWRWckNNbkpKdWh6SVdaVTFlaGN6XXXXXXXXXXcrb2EzSGd3SFQvN2h3Z2IxOE9BMVYrTjV6YmsvRXpWNmN4T213R2V3MEJ1WWc9PS0tbU01Ymt6YkdOc0VIUTFCK1NUVFlMZz09--861a3aebd1d79f224d9ad810a88e5d5f23e114c0; path=/; HttpOnly
token-type:Bearer
Transfer-Encoding:chunked
uid:login@email.com
Vary:Origin
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN
X-Request-Id:c935b76c-d173-48ce-b21c-5e694845148b
X-Runtime:0.629113
X-XSS-Protection:1; mode=block

Testing on localhost
Access-Control-Allow-Credentials:true
Access-Control-Allow-Methods:GET, POST, OPTIONS
Access-Control-Allow-Origin:http://localhost:9000
Access-Control-Expose-Headers:
Access-Control-Max-Age:1728000
Access-Token:XXXXXXXXXXXAiR5CQmwYpQ
Cache-Control:max-age=0, private, must-revalidate
Client:XXXXXXXXXXq2UC7GXE0qbw
Connection:Keep-Alive
Content-Length:418
Content-Type:application/json; charset=utf-8
Date:Thu, 04 May 2017 09:27:20 GMT
Etag:W/"XXXXXXXXXX37381b8c1637b2ea1bba96"
Expiry:1495099640
Server:WEBrick/1.3.1 (Ruby/2.2.6/2016-11-15)
Token-Type:Bearer
Uid:login@email.com
Vary:Origin
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN
X-Request-Id:3ef1f652-b29f-4fe7-bbb9-3de47f1acddf
X-Runtime:0.653264
X-Xss-Protection:1; mode=block

A: Nevermind sorry.
I read the documentation deeper  (https://github.com/lynndylanhurley/devise_token_auth#cors) and found the suggested CORS configuration that fixed the problem for me.
By adding:
:expose  => ['access-token', 'expiry', 'token-type', 'uid', 'client'],

to the CORS configuration posted in the question, the problem is resolved.


text:
Q: How to get total content of string? I have passed a printf formated string to a function and try to separate the content of that string by using sscanf(). But following is the problem with the use of this function.
i have called the function as follws:
int var = -1;
ostringstream ossi;
ossi << "myContent";
std::string detailString = "my first line \n
                            the secon dline content is alos present \n
                             also we are also get s sdjhf sf"
myFunction("What value: %d \n  My content: %s \n Detail Content: %s", var, ossi.str().c_str(),  detailString.c_str());

The implementation is as follows:
void myFunction(const char * format, ...)
{

    int var;
    char myContent[10000];
    char detailContent[50000];
    if (sscanf(myString, "What value: %d \n My content: %s \n Detail Content: %s", &var, cmyContent, detailContent) == 3)
    {
      std::cout<<" #### "<<std::endl;
      std::cout<<"var value is :"<<var<<std::endl;
      std::cout<<"My content is :"<<myContent<<std::endl;
      std::cout<<"detailContent is :"<<detailContent<<std::endl;
      std::cout<<" #### "<<std::endl;
    }
}

with above function im getting out put as follows:
var value is : -1
My content is : myContent
detailContent is : my first line

instead of getting total content of third argument(i.e detailContent) it gets only first line.
any suggestion to get complete content of string.
Thansk in advance.

A: Variable arguments in C and C++ doesn't work the way you seem to think it works. See this link for a tutorial on how to use variable arguments.
Or check out the manual page for stdarg.

A: I guess that what you are trying to do is:
char buf[1024] = {};
sprintf(buf, "What value: %d \n  My content: %s \n Detail Content: %s", var, ossi.str().c_str(),  detailString.c_str());
myFunction(buf); // not using variable arguments at all

Even then the function will probably not do what you want. To enable better answers, please write down what you are trying to achieve.
Note: the use of sprintf and sscanf in C++ is not encouraged as they are insecure.


text:
Q: List Highlighted files to a file list. (Windows Batch) Is it possible (In windows batch) to list a bunch of highlighted files to a file list. Is there an Environment Variable for it?

A: You may want to play with %* variable of batch.
Drag-and-drop one or more files on a batch and it should get it:
echo %*

Note: You can also use %1, %2, %3 ... but this is limited to %9.


text:
Q: Redirect duplicate url in htaccess I have duplicate urls and i need to do some redirection in htaccess
Examples:
Original Urls are :
www.mywebsite.com/listofgames/pacman.html
www.mywebsite.com/listofgames/nintendo.html
www.mywebsite.com/listofgames/snake.html

I have about 1000 games name
Example of duplicate urls :
www.mywebsite.com/listofgames/1/pacman.html
www.mywebsite.com/listofgames/1521/pacman.html
www.mywebsite.com/listofgames/52154/pacman.html
www.mywebsite.com/listofgames/abc/pacman.html
www.mywebsite.com/listofgames/opq/pacman.html
www.mywebsite.com/listofgames/opq/1/2/35/pacman.html
www.mywebsite.com/listofgames/154/3562/snake.html
www.mywebsite.com/listofgames/2541/snake.html
www.mywebsite.com/listofgames/524/snake.html
www.mywebsite.com/listofgames/absc/gtar/15/nintendo.html
www.mywebsite.com/listofgames/nije/nintendo.html

I need to redirect them to original urls
So
www.mywebsite.com/listofgames/anynumber/mygamesname.html
www.mywebsite.com/listofgames/anyword/mygamesname.html
www.mywebsite.com/listofgames/anyword/anynumber/anyword/mygamesname.html

Must be redirected to
www.mywebsite.com/listofgames/mygamesname.html

A: You may try this:
Options +FollowSymlinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} ^/listofgames/.*/([^\.]+)\.html/?  [NC]
RewriteRule .*    listofgames/%1.html                    [R=301,L]

Redirects permanently
http://www.mywebsite.com/listofgames/any/number/of/folders/mygamesname.html
with or without trailing slash.
To:
http://www.mywebsite.com/listofgames/mygamesname.html
Effectively removing the segment path between /listofgames/ folder and the HTML file.
String listofgames and extension html are assumed to be fixed, while mygamesname is assumed to be variable.
The incoming URL structure has to be kept for the rule-set to work: Last string inside the URL must be the HTML file.
For silent mapping, remove R=301 from [R=301,L]


text:
Q: Is there a way to see every time NSLog is called and the content of the NSLog? Ideally I'd like to setup a selector to see every time NSLog is called in my app, and to get the output of that NSLog. NSLog might be called by an SDK I'm using and I'd like to be able to see the output of those logs from within my app. Is that possible?

A: What you want is a Symbolic breakpoint.
Navigate to the Breakpoints tab in Xcode and use the + button in the bottom left corner to add one.
When the breakpoint is added, it should automatically come up with a window that allows you to enter the conditions on which you want it to pause execution. You can use NSLog as the symbol.
As for calling a custom function of your own, you can attempt to do that by adding an action in that breakpoint and utilise the debugger's ability to call into your own code by passing in the arguments that are available to the debugger e.g. $arg1.

A: So I dont think it is possible to simply replace every instance of NSLog with something else... but you could do something like this:
#define NSLog MyLog

void MyLog(NSString *format, ...) NS_FORMAT_FUNCTION(1,2);
void MyLog(NSString *format, ...)
{
    va_list list;
    va_start(list,format);
    NSLogv(format,list);
    va_end(list);

    va_start(list,format);
    vfprintf(stderr,[format UTF8String], list);
    va_end(list);
}

int main(int argc, const char * argv[]) {

    NSLog(@"hello %s\n","world");

    return 0;
}

My example uses 2 va_lists to log with an NSLog like NSLogv and vfprintf to log to an open FILE * stream (stderr in this case)... you could also probably more simply format an NSString (as vfprintf can't print NS objects)...
I tried a little bit to try to re-assign NSLog with dlsym which would be process wide, rather than just when the macro is expanded... I couldn't get it to work but I am not a dynamic linker expert.


text:
Q: Swift Singleton access in Objective-C triggers EXC_BAD_INSTRUCTION (EXC_I386_INVOP) I've created a singleton object in Swift 4.2 and am attempting to access it (call a couple methods) in an Objective-C class. However, when calling the instance in Objective-C, the app crashes with the following:

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

My Swift singleton definition isn't anything unusual, and it works fine when called only from other Swift classes. Here's what it looks like:
@objc public static let sharedManager = SessionManager()

It doesn't seem to be an issue with language interoperability in the project either: non-singleton files don't cause a crash when accessed from Objective-C. I'm also not sure that this Objective-C code is so wild that it should be causing it either:
// Have attempted both flavors here, the crash is coming from the call to "sharedManager", which the runtime thinks is nil
SessionManager *manager = [SessionManager sharedManager];
[manager setSession:nil];

Any ideas on how to fix this? What am I missing? Why would the singleton instance ever be nil?

Edit: I've attempted expanding the implementation of the Swift Singleton to this, and its still not working:
@objc final class SessionManager: NSObject {
    @objc public static let _sharedManager = SessionManager()
        private override init() {
        super.init()
    }

    @objc public class func sharedManager() -> SessionManager {
        return SessionManager._sharedManager
    }
}

A: When accessing a Singleton in Objective-C for the first time, each variable stored in the class must be initialized.
I found that what was happening (and what made this so frustrating) was that one of the objects being initialized made calls back to the singleton object in its own initializer -- thus forming an infinite loop that the runtime couldn't exit.

If you're coming here from Google... when creating a Singleton object with non-optional variables, make sure that the initializers for the variables make no references to the singleton from which they are being initialized. Basically, avoid inadvertently creating infinite loops.

UPDATE: A bug report radar has been filed with the Swift team.


text:
Q: Java: RegEx Problem (using the '.' all character symbol) I have some document stored as a large String. In the String I have some inline XML tags and I want to get out the words inbetween the tags. The documents may also contain HTML tags, as the documents are often web sites.
Example Document:

"< tr > My name is < b >< PERSON >Bobby< /PERSON >< /b >, I live in the USA."

Current RegEx:
Pattern p = Pattern.compile("<(LOCATION|PERSON|ORGANIZATION)>[\\w[ '\"/\\!%$\\(\\)\\-\\+]]*</(LOCATION|PERSON|ORGANIZATION)>");

Matcher m = p.matcher("I'm <PERSON>Graham Brown</PERSON> I went to the <LOCATION>USA'S</LOCATION>");

while(m.find()){
    System.out.println(m.group());
}

Result = < PERSON >Bobby< /PERSON > < LOCATION >USA< /LOCATION >

This works fine with pretty much most puntuation and grammer, but the Regex should allow any character pattern to be found between the tags. When I try using '.' (any character), as below it returns the whole String.

"< tr > My name is < b >< PERSON >Bobby< /PERSON >< /b >, I live in the USA."

 Pattern p = Pattern.compile("<(LOCATION|PERSON|ORGANIZATION)>.</(LOCATION|PERSON|ORGANIZATION)>");

How do I return any characters between the angular openinng and closing tags?
EDIT: Thanks for your responses. Just and for helping get the correct answer.
For clarification I have marked Named Entites using NER. If you are unware of what this is please see some of the papers I have referenced at the bottom.
All I am interested in is getting the text between the three opening and closing tags. There are no other tags and the documents are not XML files and I am not parsing all the HTML tags nor I am I interested in them. All I am interested in is parsing the XML tags that I have created hence I though RegEx would be the simplest way to do so.
Papers to be added later...

A: Put a question mark after .*? for non-greedy processes.
Pattern p = Pattern.compile("<(LOCATION|PERSON|ORGANIZATION)>.*?</(LOCATION|PERSON|ORGANIZATION)>");

PS: I am just correcting your regex, but it does not mean it's the solution. Using parsers are always better idea.

A: Please use an XML parser for XML snippets. It's the right tool for your problem.
Edit:
And use a HTML sanitizer to preprocess the HTML file. Additionally define a strict XML schema for the XML to ensure the XML structure.


text:
Q: Is there any way to automatically perform test cases on an android application? Is there any way to automatically perform test cases on an Android application?
When you finish an android application, you need to test all of the features of the app, in other words you need validation. But since there are so many tests which need to be performed, you need something like a robot to test all of the features.
This is important especially when you have some changes in the code in the future. So all test cases should be repeated and it takes a long time to manually perform such tests.
How do you validate your app? Do you have a robot to automatically perform test cases or you do it manually?

A: Yes, we can preform automation testing of android mobile application using tool Appium and Selenium. Most imp thing is that Appium and Selenium are open source.
Using appium we can perform automation testing for this we required followings.

*

*Appium Server.
http://appium.io/

*Selenium Stand-alone Web Driver.
enter link description here

*Java or python or ruby and many more but given are popular.

*Debug apk and android studio

*Android real device

*Java client
enter link description here

*Any IDE such as Android studio or eclipse.

After that we have to set environment in windows or mac application and we have write script to for each functionality.
It is easy to write and use. I guess it was help full and download link are given.


text:
Q: Trouble with reading from text file My goal is to have a program that saves 6 variables (q,d,n,p,tc,td) in a text file each time one is updated (Success) and when reopened will automatically set the variables based on the text file. So if tc equaled 13 when it last closed, if I opened it a week later it would still equal 13. (assuming the text file goes un-touched)
The problem happens when I try to run this bit of code:
:Load
set v=0
FOR /F "usebackq delims=" %%a in ("SavedData.txt") do (
set /a var+=1
set var!v!=%%a
)
set q=%var1%
set d=%var2%
set n=%var3%
set p=%var4%
set td=%var5%
set tc=%var6%
goto main

it gives the following error:
9 was unexpected at this time.

Any ideas? (btw, when the error was displayed none of the values equaled 9)
EDIT: I got it working, but now each variable has an extra space at the end which I want removed so it can function properly.
I got it working by typing set /a v+=1 instead of set /a var+=1

A: I don't think the error message is occurring where you think it is, but I do see a bug in your code. You are incrementing var when you intend to increment v. I don't see how that bug can give the error message you describe, but it obviously will cause problems, and could possibly lead to the error elsewhere in your code.
Your Load routine could be much simpler.
:Load
<"SavedData.txt" (for %%V in (q d n p td tc) do set /p "%%V=")

A: As dbenham said, your load routine could be much simpler. This answer will not discuss how to get it simpler as you should probably just look up (assuming debnham's answer gets more upvotes than mine). What this answer will tell you is why you have extra spaces in your variable's values.
Now, the only reason I can think of why this is happening is because somewhere in your code (probably the :save sequence), you have code looking like this:
echo value_of_q >> "SavedData.txt"
::More stuff here...

The problem is the space before the end of your statement (echo value_of_q) and the redirection (>> "SavedData.txt"). This would append the output of your command (including any spaces) to the end of SavedData.txt.
Now, you could avoid this by one of two options (or both).
Option 1.
You trim the spaces. Make it echo value_of_q>> "SavedData.txt instead of what you had.
Option 2.
Assuming the values of the variables are on separate lines, you can remove the delims option within your for loop (you can also remove the usebackq option as well).
So, your for loop will look more like...
for /f "usebackq" %%i in ("SavedData.txt") do (
    ::Rest of your code here...
    ::Oh, and your code blocks should be indented as well.
)

As you can see, I changed the %%a to %%i, this isn't necessary for your loop, but it is good practice as it may keep away errors in the future.
Hope that helps.

A: A much simpler approach is to make the save file a .bat one instead of a .txt file by including complete set commands instead of just variable values; this have the advantage that the load code does not rely on the order of the saved values (nor the save code either). For example, this would be the code to save the variables:
:Save
(for %%v in (q d n p td tc) do echo set %%v=!%%v!) > "SavedData.bat"

And this would be the code to recover the saved values:
:Load
call "SavedData.bat"

Antonio


text:
Q: gstreamer mixer, mix 2 rtsp streams side by side with gst-launch -> timestamping problem occurred I am trying to display two streams side by side with gst-launch.
It occurs an error, but the streams are displayed.
gstbasesink.c(2902): gst_base_sink_is_too_late (): /GstPipeline:pipeline0/GstAutoVideoSink:autovideosink0/GstXvImageSink:autovideosink0-actual-sink-xvimage:
Single rtsp source is displayed correctly.
I tried to the parameter latency to 500, no success.
gst-launch-1.0 -e \
videomixer name=mix \
    sink_0::xpos=0   sink_0::ypos=0  sink_0::alpha=0\
    sink_1::xpos=640   sink_1::ypos=0 \
rtspsrc location=rtsp://192.168.9.20:554/axis-media/media.amp user-id=username user-pw=password latency=150 \
! decodebin max-size-time=30000000000 \
! videoconvert ! videoscale \
! video/x-raw,width=640,height=480 \
! mix.sink_1 \
rtspsrc location=rtsp://192.168.9.24:554/axis-media/media.amp user-id=username user-pw=password latency=150 \
! decodebin max-size-time=30000000000 \
! videoconvert ! videoscale \
! video/x-raw,width=640,height=480 \
! mix.sink_2 \
mix. ! queue ! videoconvert ! autovideosink

I want to create a mosaic of four rtsp streams.
Please give me help in resolving the problem. Thanks in advance.

A: The solution is to use:
mix. ! queue ! videoconvert ! xvimagesink sync=false```


text:
Q: How does maximumAge of GetGeopositionAsync work? One of the overloaded method of Geolocator.GetGeopositionAsync() takes 2 parameters. maximumAge and timeout. I got the use of timeout. But concept of maximumAge is still unclear to me.
MSDN says:
The maximum acceptable age of cached location data.
If I set maximumAge to TimeSpan.FromHours(1), which of the following does it mean?

*

*In a active session of my app, if I request again for location, it will return from cache

*If I restart my app and then query for location, and time since last query is still less than an hour, it will return from cache.

*If some other app has requested for location in last one hour and my app requests for location, it will return from cache.

Basically my question is, is the cache storing the location is maintained for a

*

*particular session of the app

*app as a whole, i.e. for all sessions

*or its global


text:
Q: Check whether prime or not in Prolog I'm trying to learn Prolog and I've found an example where I need to implement a program to check whether a number is prime or not with a single predicate.
The logic I'm trying to follow is to make a recursive rule to divide by all the number less than that predicate till it reaches the base case which is either X>2 because 0 and 1 aren't primes and divisible by itself
My code till now is :
isPrime(2).
isPrime(X):-
    X>2, %0,1 aren't primes
    1 is mod(X,2),

Can someone help ?

A: It's pretty easy provided you don't care about efficiency.
isPrime(X) :-
  X > 1,
  succ(X0, X),
  \+ (between(2, X0, N), 0 is X mod N).

:)


text:
Q: Are tag edits of less than 6 characters supposed to be allowed Now that the retag feture has been merged with the edit feature tag edits also have to be over 6 characters? A question can legitimately have only one character in tags? Is this an intended side effect of the change? For How to check whether STL iterator points at anything? if I click the edit link, then remove valid I get the error edits must be at least 6 charicters. My browser is Safari on iOS 6.0.

A: Yes, they should be.  Retagging doesn't character count.  If not it's a bug and report as such, and perhaps the supporting text should be clearer.


text:
Q: OpenSSH not respecting $HOME when searching for ssh config files I'm writing some integration tests, that test SSH connections between servers.
For the time being the tests are run from people's laptops. In order not to muck around in the user's (the user running the tests) ~/.ssh/config I create a temporary directory with a bespoke ./tmp/.ssh/config file just for the tests. Then I export HOME=/path/to/tmp. Unfortunately, I've found that openssh doesn't use $HOME to search for an ssh config or identity files.
This is ok if I'm ssh-ing directly to a host, because I can just explicitly set my config using the -F flag. However, if I'm ssh-ing through a bastion and I have a proxycommand, ssh does not pass that configuration file down to my proxycommand. So, if my bespoke ssh config uses a different default username (for example), that configuration won't be used for the proxycommand.
I "could" modify the proxycommand as well (to take an ssh config file as an argument), however, I'd like to know if it's possible to get openssh to look for the config/identity files in a different location just by use of environment variables (without having to pass the configuration file down to each subsequent downstream command). I can change my ssh-agent using SSH_AUTH_SOCK so I was hoping to be able to change the config file directory as well.

A: According to the source code, ssh gets the home directory from the password file and then, if it does not succeed, from the HOME environment variable.
What you can do is add an Include to every user's ~/.ssh/config, say ~/tmp/user/.ssh/config.
If the file to be included does not exist, ssh will not complain. But if it exists and is readable, it will include it. That should allow you to do the tests without messing too much with their files.
Notice that it poses a security risk. Anybody knowing those paths will be able to inject local configurations for other users if you don't secure them well.


text:
Q: Hashes vs. Multiple Params? It is very common in Ruby to see methods that receive a hash of parameters instead of just passing the parameters to the method.
My question is - when do you use parameters for your method and when do you use a parameters hash?
Is it right to say that it is a good practice to use a parameter hash when the method has more than one or two parameters?

A: I use parameter hashes whenever they represent a set of options that semantically belong together. Any other parameters which are direct (often required) arguments to the function, I pass one by one.

A: You may want to use a hash when there are many optional params, or when you want to accept arbitrary params, as you can see in many rails's methods.

A: if you have more than 2 arguements. you should start thinking of using hash.
This is  good practise clearly explained in clean code link text

A: One obvious use case is when you are overriding a method in a child class, you should use hash parameters for the parent method's parameters for when you call it.

A: On another note, and this is not only related to Ruby but to all languages:
In APIs which are in flux, it is sometimes useful to declare some or all parameters to a function as a single parameters object (in Ruby these could be hashes, in C structs, and so on), so as to maintain API stability should the set of accepted arguments change in future versions. However, the obvious downside is that readability is drastically reduced, and I would never use this "pattern" unless I'd really really have to.


text:
Q: Sql Server Database project error for return type of user defined function I've was trying to create a user defined function in the Sql Server Database project in visual studio 2017, but I encountered a strange error during build time.  This error was generated by the auto sql code builder:
RETURNS /* Error: Unsupported type. */

Which was accompanied by this message:
"SQL80001: Incorrect syntax near 'AS'.  Expecting DOUBLE, ID, NATIONAL, QUOTED_ID, TABLE, or VARIABLE."
Has anyone else encountered this issue before?  I've looked in many forums and help sites, and this issue seems to have occurred to many, but I couldn't find any fixes regarding user return types, specifically DataTables.
Does anyone know why this occurs or how to fix it?
Here is my code that generated the error:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions
{
    public static DataTable getDailyEmpHrs(String strGroupName)
    {
        DataSet dsEmp = new DataSet("myEmpHrs");

        dsEmp.Tables["myEmpHrs"].Columns.Add("ccnumber", typeof(int));
        dsEmp.Tables["myEmpHrs"].Columns.Add("ccname", typeof(string));
        dsEmp.Tables["myEmpHrs"].Columns.Add("cccode", typeof(string));

        DataTable dsTable = dsEmp.Tables["myEmpHrs"];

        return dsTable;
    }
};

And Visual Studio generates this code:
----------------------------------------------------------------------------
--    This code was generated by a tool.
--
--    Changes to this file may cause incorrect behavior and will be lost if
--    the code is regenerated.
----------------------------------------------------------------------------

CREATE FUNCTION [dbo].[getDailyEmpHrs] (@strGroupName [nvarchar](MAX))
RETURNS /* Error: Unsupported type. */
AS EXTERNAL NAME [project].[UserDefinedFunctions].[getDailyEmpHrs];

Go

// Generated Assembly Stuff below here

A: You are trying to create a scalar (single value) UDF but the c# returns a table.
There is no data type.
It would be RETURNS TABLE if anything
But honestly, why have a UDF for this? What advantages do you think you will have?


text:
Q: Using CustomCredentialsAuthProvider in JsonServiceClient I try to implement my own custom CredentialsAuthProvider. The server seems to work fine with the following implementation:
public class MyCustomCredentialsAuthProvider : CredentialsAuthProvider
{
    public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
    {
        if (userName == "testuser" && password == "1234")
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens,
                                                Dictionary<string, string> authInfo)
    {
        session.FirstName = "Testuser Joe Doe";

        authService.SaveSession(session, SessionExpiry);
        return null;
    }

}

When I call on my Browser http://localhost:8088/auth/credentials?UserName=testuser&Password=1234 I get back a page containing a session ID and the testuser Joe Doe. Looks fine.
Now I try to call this from my Windows WPF client. I have created a Login Page and a LoginViewModel class since I implement the MVVM pattern. But I do not understand, what I really have to set the provider property in the Authenticate class to.
In my WPF class I have the following:
public partial class App : Application
{
    public JsonServiceClient ServiceClient { get; private set; }

    public App()
    {
        this.InitializeComponent();
    }
    // ....
}

And then in my LoginViewModel I have a Login() method which is a RelayCommand implementation of the login button like so (The form contains also a field where you have to enter the name of the application server since there is more than one. This is why I compose the baseUri in the handler):
    private void Login()
    {
        var baseUri = $"http://{AppServer}:8088";
        ((App)Application.Current).InitServiceClient(baseUri);
        var client = ((App) Application.Current).ServiceClient;

        //var response = client.Send<AuthResponse>(new Auth { UserName = "Test", Password = "TestPassword" });
        var authResponse = client.Post(new Authenticate
        {
            provider = CredentialsAuthProvider.Name, // <-- WHAT SHOULD THIS BE???
            UserName = "testuser",
            Password = "1234",
            RememberMe = true,
        });
        // ....
    }

CredentialsAuthProvider is unknown by the compiler. What do I need to pass here and what assemblies do I need? So far I have:

*

*ServiceStack.Ckient

*ServiceStack.Interfaces

*ServiceStack.Text

*MyService.ServiceModel  //DLL containing the DTOs etc., NO implementations

What am I missing and doing wrong here?

A: CredentialsAuthProvider.Name just provides typed access to the "credentials" string literal, which you can use in its place, e.g:
var authResponse = client.Post(new Authenticate
{
    provider = "credentials",
    UserName = "testuser",
    Password = "1234",
    RememberMe = true,
});

You can find the list of Auth provider literals in the Authentication docs.


text:
Q: Why does it print 12345 not 01234? It has to be output like this 01234
for(int i = 0;i < 5; i++, System.out.print(i));

or
for(int i = 0;i < 5; System.out.print(i))
    i++;

Output: 12345

A: for(int i = 0;i < 5; System.out.print(i))
    i++;

Is equivalent to the following while loop:
{
  int i = 0;
  while (i < 5) {
    i += 1;
    System.out.print(i);
  }
}

i is always incremented before it is printed. Same goes for i++, System.out.print(i): i is already incremented before it is printed. And I don't need to mention that 0 + 1 = 1.

A: It's pretty easy, you just need to understand what you're writing.
It should go like:
for(int i=0;i<5;i++){ //"i" is increased at the end of the loop
    System.out.print(i) //prints "i", which is zero and will increase up to 4
}

And that's it


text:
Q: Terraform with Azure Key Vault to get secret value Is there any way to get the value of a secret from Azure Key Vault?
Doesn't look like value gets exposed in the key vault secret object here.

A: I've been working on this to get password from key vault secret. The code below worked for me , Give it a try.
data "azurerm_key_vault" "terrakv" {
  name                = "terrakv" // KeyVault name
  resource_group_name = "mykv" // resourceGroup
}

data "azurerm_key_vault_secret" "kvsecret" {
name = "secret" // Name of secret
key_vault_id = data.azurerm_key_vault.terrakv.id
}

os_profile {
computer_name  = "vm-01"
admin_username = "testadmin"
admin_password = data.azurerm_key_vault_secret.kvsecret.value // Toget actual value
}

I hope it will help you for sure.

A: Now you can do it with azurerm_key_vault_secret data source.
I'm enjoying without any scripting.
data "azurerm_key_vault" "example" {
  name                = "mykeyvault"
  resource_group_name = "some-resource-group"
}

data "azurerm_key_vault_secret" "test" {
  name      = "secret-sauce"
  key_vault_id = data.azurerm_key_vault.example.id

  # vault_uri is deprecated in latest azurerm, use key_vault_id instead.
  # vault_uri = "https://mykeyvault.vault.azure.net/"
}

output "secret_value" {
  value = "${data.azurerm_key_vault_secret.test.value}"
}

A:
Is there any way to get the value of a secret from Azure Key Vault?

As a workaround, we can use PowerShell to get this value, like this:
$a = Get-AzureKeyVaultSecret -VaultName "jasonkey" -Name "jason"
$a.SecretValueText

A: You first need to create a data resource to the azure key vault to get the key vault resource ID:
data "azurerm_key_vault" "keyvault" {
  name                = "${var.keyvault_name}"
  resource_group_name = "${var.resourcegroup_name}"
}

And then use azurerm_key_vault_secret to get the secret with the key vault resource Id:
data "azurerm_key_vault_secret" "win_admin_pass" {
  name         = "${var.secret_name}"
  key_vault_id = "${data.azurerm_key_vault.keyvault.id}"
}

Please note that the use of vault_uri in azurerm_key_vault_secret is deprecated and not recommended.

A: Unfortunately, this is not currently possible in Terraform. Terraform will only output the secret ID and version. If you need to retrieve azure keyvault secrets, the best method is to use the Azure-CLI, or Powershell if that's not available.
Using Azure-CLI (2.0)
az keyvault secret show --vault-name <vault-name> --name <secret-name>

Syntax:
az keyvault secret show --name
                        --vault-name
                        [--version]

For more, see: Managing Azure Keyvault Secrets with Azure-CLi

Using Powershell: Get-AzureKeyVaultSecret
get-azurekeyvaultsecret -vaultName "<vault-name>" -name "<secret-name>"

A: I have a key vault and I need a few secrets from it so this is my approach.
I've used for-each approach
data "azurerm_key_vault" "keyvault_devops" {
 name                = "keyVaultName"
 resource_group_name = "resourceGroupName"
}

data "azurerm_key_vault_secrets" "global_devops" {
 key_vault_id = data.azurerm_key_vault.keyvault_devops.id
}

data "azurerm_key_vault_secret" "global_devops" {
 for_each     = toset(data.azurerm_key_vault_secrets.global_devops.names)
 name         = each.key
 key_vault_id = data.azurerm_key_vault.global_devops.id
}

Then I use it like this :
value           = data.azurerm_key_vault_secret.global_devops["secret-name"].value


text:
Q: how to make a dynamic text show the correct sentence in react when deleting a component (custom html element) In React, upon deleting a component, I want to make a dynamic sentence shows the correct sentence like this in app.js:
 let awesomePhrase = '';
    if (!this.state.showPersons) {
      awesomePhrase = 'Nobody is here, it seems :/';
    }
    if (this.state.showPersons && this.state.persons.length === 2) {
      awesomePhrase = "All aboard :D";
    }
    if (!this.state.persons.filter(p => p.id === 1)) {
      awesomePhrase = "Where's Matin?!";
    }
    if (!this.state.persons.filter(p => p.id === 2)) {
      awesomePhrase = "Where's Mobin?!";
    }

It doesn't show any of the sentence when I delete id 1 or id 2.That is, neither "where's Matin?!" nor "Where's Mobin?!".
But the two first sentences work fine.

(EDIT: every piece of code below is within app.js, the main file)
For deleting:
deleteHandler = index => {
    const persons = [...this.state.persons].filter(
      person => person.id !== index
    );
    this.setState({ persons });
  };

The State:
state = {
    persons: [
      { id: 1, name: 'Matin', age: 27 },
      { id: 2, name: 'Mobin', age: 26 }
    ],
    showPersons: false,
    ...
};

The component within the render of the class:
 {this.state.persons.map(person => {
            return (
              <Person
                key={person.id}
                name={person.name}
                age={person.age}
                click={() => this.deleteHandler(person.id)}
              />
            );
  })}

the part of render where dynamic text is used:
return (

  ...

{awesomePhrase}

  ...

)

A: The problem with your code is the filter function. Filter will return an empty array if no elements passed the test, and in Javascript, an empty array is not a falsy value.
The condition !this.state.persons.filter(p => p.id === 2) will always be false.
The proper function to use in this situation is Array.some, which return a boolean value depends on the result of the test function.
Be aware of the return type and the falsiness / truthiness in Javascript.

A: I think I found a workaround
instead of filter I used find, and tried to check them within deleteHandler method. Also added an independent awesomePhrase to State.
So:

  deleteHandler = index => {
    const persons = [...this.state.persons].filter(
      person => person.id !== index
    );

    if (persons.length === 0) {
      this.setState({ awesomePhrase: 'where did they all gone?' });
    }

    if (persons.find(p => p.name === 'Matin')) {
      this.setState({ awesomePhrase: 'Where is Mobin?' });
    }
    if (persons.find(p => p.name === 'Mobin')) {
      this.setState({ awesomePhrase: 'Where is Matin?' });
    }

    this.setState({ persons });
  };

  state = {
    persons: [
      { id: 1, name: 'Matin', age: 27 },
      { id: 2, name: 'Mobin', age: 26 }
    ],
    ...,
    showPersons: false,
    mobin: true,
    awesomePhrase: ''
  };

 return (

        ...

{this.state.awesomePhrase || awesomePhrase}

        ...

    );

I'd welcome any suggestion to help improve my code further or correct it properly. I just made it work now.


text:
Q: Cassandra nodetool snapshot creates snapshot directory but not in the data directory specified I am using Cassandra nodetool to take a snapshot .
The way i use it is, cd to $CASSANDRA_HOME and then do bin/nodetool snapshot . It says a snapshot directory has been created but I don't find in the data directory.
What am I doing wrong?

A: Snapshots are in $DATA_DIR/$KEYSPACE/$COLUMN_FAMILY/snapshots/.


text:
Q: Slick 2.0 MultiDBCakeExample AutoInc "into" function I found many old posts on how the "old" AutoInc function works, but there is almost no post on how the new AutoInc function actually works.
https://github.com/slick/slick-examples/blob/master/src/main/scala/com/typesafe/slick/examples/lifted/MultiDBCakeExample.scala
There are two private AutoInc functions defined with User and Picture:
private val picturesAutoInc = pictures
    returning pictures.map(_.id) into { case (p, id) => p.copy(id = id) }

private val usersAutoInc = users.map(u => (u.name, u.pictureId))
    returning users.map(_.id) into {
    case (_, id) => id
}

I found the returning method on http://slick.typesafe.com/doc/2.0.0/queries.html#inserting
But what is this into function? What does it do? What does it take into?
This is my class and how should I write my own autoInc?
  case class Label (id: Option[Int] = None, tag_name: String)

  class Labels (tag: Tag) extends Table[Label](tag, "Labels") {
    def id = column[Option[Int]]("TAG_ID", O.PrimaryKey, O.AutoInc)
    def tag_name = column[String]("TAG_NAME")

    def * = (id, tag_name) <> (Label.tupled, Label.unapply _)
  }

A: It allows you to map the inserted values and generated keys into a desired target value.
It was undocumented up until now. I created a PR with documentation: https://github.com/slick/slick/pull/687
Also note the corresponding unit test: https://github.com/slick/slick/blob/master/slick-testkit/src/main/scala/com/typesafe/slick/testkit/tests/InsertTest.scala#L59


text:
Q: Symfony 2.1 - problems loading assets and an exception thrown by assetic This is a bit frustrating.  According to Symfony best practices, a bundle's web assets (images, css, js) should be placed in src/vendor/path/to/bundle/Resources/public.  Running app/console assets:install copies the contents of that public folder to web/bundles/bundlename.  In the official documentation, Twig templates are shown to grab these assets with code like:
{% block stylesheets %}
    <link rel="stylesheet" type="text/css" href="{{ asset('/css/styles.css') }}
{% endblock %}

When I try it, instead of magically grabbing my assets from web/bundles/bundlename/css/styles.css, it instead just goes for web/css/styles.css.  Is this expected behavior?  The official documentation is less than clear about this.
In order to try to combat this issue, I tried embracing assetic's ability to dynamically serve assets.  I tried:
{% stylesheets '@mybundle/Resources/public/css/*' %}
    <link rel="stylesheet" type="text/css" href="{{ asset_url }}" />
{% endstylesheets %}

But got the following exception:

An exception has been thrown during the compilation of a template ("You must add mybundle to the assetic.bundle config to use the {% stylesheets %} tag in mybundle:Home:index.html.twig.") in "/home/kevin/www/src/mybundle/Resources/views/Home/index.html.twig

The official Symfony documentation makes it appear that it should work out of the box with no configuration necessary.
So, TLDR:

*

*Am I not understanding how assets should be loaded?

*How do I address the assetic exception?

A: To fix the assetic exception you need to configure your bundle in your config.yml like this:
assetic:
    bundles: [ MyAwesomeBundle ]

The {{ asset(...) }} twig function will serve files relative from your web root.
You use app/console assets:install to install static assets within your web root and you can later easily point to them using the asset function like this {{ asset('/mybundle/css/site.css') }}


text:
Q: Wrong behavior of Inverse Fourier Transform of DiracDelta[x]/x The following fails to compute:
InverseFourierTransform[DiracDelta[w]/w, w, x]

But if we add a,
InverseFourierTransform[DiracDelta[w]/w + a, w, x]

It evaluates the way as if DiracDelta[w]/w were zero.
Given that inverse Fourier transform is a linear operator, if the first result is unknown, so should be the second result as well.
The problem arose when I was investigating the following operator:
I InverseFourierTransform[FourierTransform[f[t], t, w]/w, w, x]

When f[t]=1/t the result was correct. But when it was 1/t+t^2 or 1/t+t, the result was totally the same, dispite the whole operator is linear.


text:
Q: why create .h and .cpp headers I came across this implementation of some code which requires us to create a header and then #include it in our source code.
So my question is why we need to create a .cpp file along with the .h and what all compilations we should to in order to use the header file in a test program

A: If your program is small enough that it's reasonable to put the whole thing in a single .cpp file, you don't really need a header file.  But larger programs are usually divided into multiple .cpp files, and header files are used for code that needs to be included in more than one .cpp file.
Even in a multi-file project, headers aren't strictly necessary — you could just copy-and-paste things like class definitions and function declarations into each .cpp file that needs them.  But they have to match exactly, which means that whenever you wanted to change one of those things, you'd have to find all the copies and change them all in the same way, which is extremely inconvenient and very prone to mistakes.  Using #include lets you keep a single copy of that code in a header file, instead of having to put duplicate copies into lots of .cpp files.


text:
Q: Last element of the array is always NaN even though I used Number() function Kindly help me investigate my function below since I'm stuck and still having a hard time figuring it out.
All is well until it reaches the last column on the nested FOR loop. The last column of each row's values are only "0". However, I used the Number() function to make the cell values(i.e. "0") a number but I keep on getting NaN for the last element of the SUM & COUNT arrays.
colCount = 326 while rowCount = 374.
sum.length and count.length should really be ONLY 325 since the headers are unnecessary and the first column is just composed of time stamps. I was able to .push(0) successfully until the nested FOR loop changed the result of the last element to NaN.
function processDataToDictionary(csv) {
    var allTextLines = csv.split(/\r\n|\n/);

    var csvArray = [];

    for (let i = 0; i < allTextLines.length - 1; i++) {
        var row = allTextLines[i].split(',');

        csvArray.push(row);
    }

    var colCount = csvArray[0].length;
    var rowCount = csvArray.length;

    //Arrays of values
    var count = [];
    var sum = [];
    var average = [];
    var headers = [];

    for (let i = 1; i < colCount; i++) {
        var current = csvArray[0][i].replace(/"/g, '');
        sum.push(0);
        count.push(0);

        headers[i] = current;
    }

    for (let i = 1; i < rowCount; i++) {

        for (let j = 1; j < colCount; j++) {
            // Remove the quotes from your array
            current = csvArray[i][j].replace(/"/g, '');

            // Added the Method IsNullOrWhiteSpace
            if (!isNullOrWhitespace(current)) {
                // Parse as double not int to account for dec. values
                sum[j] += Number(current);
                count[j]++;
            }
        }
    }

    for (let i = 0; i < colCount; i++) {
        average.push((sum[i] + 0.0) / count[i]);
    }

    for (let i = 1; i < colCount; i++) {
     // create an empty array

        dictionary[headers[i]] = average[i];
    }

    return dictionary;

}

function isNullOrWhitespace(input) {

    if (input == " ") {

        return true;

    } else {

        return false;
    }
}

A: This gives you a dictionary (Object) with the columns names as keys and numbers that appear to be the correct averages as values. But one must still check whether there is a fault in the logic somewhere and the averages are not correct in fact.
function processDataToDictionary(csv) {

function isNullOrWhitespace(input) {

    if (input === " ") {

        return true;

    } else if (input === null) {

        return true;

    //} else if (input === undefined) {

        //return true;

    }   else {

        return false;
    }
}

var allTextLines = csv.split(/\r\n|\n/);

    var csvArray = [];

    for (let i = 0; i < allTextLines.length - 1; i++) {
        var row = allTextLines[i].split(',');

        csvArray.push(row);
    }

    var colCount = csvArray[0].length;
    var rowCount = csvArray.length;

    //Arrays of values
    var count = [];
    var sum = [];
    var average = [];
    var headers = [];

    for (let i = 1; i < colCount; i++) {
        var current = csvArray[0][i].replace(/"/g, '');
        sum.push(0);
        count.push(0);

        headers[i] = current;
    }

    /**** I added these two lines ****/
    sum.push(0);
    count.push(0);

for (let i = 1; i < rowCount; i++) {

        for (let j = 1; j < colCount ; j++) {

            // Remove the quotes from your array
            current = csvArray[i][j].replace(/"/g, '');

            // Added the Method IsNullOrWhiteSpace
            if (!isNullOrWhitespace(current)) {
                // Parse as double not int to account for dec. values
                sum[j] += Number(current);
                count[j]++;
            }
        }
    }

     for (let i = 0; i < colCount; i++) {
        average.push((sum[i] + 0.0) / count[i]);
    }

// I added this line:
dictionary = {};

 for (let i = 1; i < colCount; i++) {

        dictionary[headers[i]] = average[i];
    }

    return dictionary;

}

Let me know if this works out for you. You can loop through the values with: for (let key in dictionary) {console.log("key: " + key + " , value: " + dictionary[key]);} . Regards!


text:
Q: NSMutableArray initWithCapacity failing I'm trying to initialize an NSMutableArray and it's not working correctly. Subsequent access to the array throws an exception saying "index 0 beyond bounds for empty array." A breakpoint following the initialization line says that my array has a location in memory, but that it has 0 objects
Here's my attempt at the moment:
in my .h
@interface SomeInterface : NSObject
{
@private
    NSMutableArray *myArr;
}

in my .m
- (id) initWithHeight: (int) height
{
    self = [super init];
    if (self)
    {
        self->myArr = [[NSMutableArray alloc] initWithCapacity:height];
    }
    return self;
}

The breakpoint shows myArr = (NSMutableArray *) 0x######## 0 objects
Does anyone know how to properly initialize an NSMutableArray?

A: initWithCapacity: does not create objects in your array, so the debugger isn't lying - your array is empty until you add objects to it, either by using addObject: or by initializing it with objects in the first place.

A: as yonix pointed you are not creating any objects, here an example that adds your object:
.h
#import <Foundation/Foundation.h>

@interface Ssuti : NSObject
{
    NSMutableArray *_myArr;
}

@property (nonatomic, assign) NSMutableArray *myArr;

- (id) initWithHeight: (int) height;

@end

.m
#import "Ssuti.h"

@implementation Ssuti

@synthesize myArr = _myArr;

- (void)dealloc {
     [super dealloc];
}

- (id) initWithHeight: (int) height
{
    self = [super init];
    if (self)
    {
        self.myArr = [NSMutableArray array];

        [self.myArr addObject:[NSNumber numberWithInt:height]];

        NSLog(@"myArr :: %@", self.myArr);
    }
    return self;
}

@end

then in the ViewController you call it:
Ssuti *mySssuti = [[Ssuti alloc]initWithHeight:345];

    [mySssuti release];

;)


text:
Q: How kubelet knows what to do? I'm trying to understand how kubelet watches changes from api server. I found a note over syncLoop function
// kubernetes/pkg/kubelet/kubelet.go
// syncLoop is the main loop for processing changes. It watches for changes from
// three channels (file, apiserver, and http) and creates a union of them. For
// any new change seen, will run a sync against desired state and running state. If
// no changes are seen to the configuration, will synchronize the last known desired
// state every sync-frequency seconds. Never returns.

Does kubelet pulls events or api server pushes events to kubelet?

A: The kubelet is the primary "node agent" that runs on each node. It can register the node with the apiserver using one of: the hostname; a flag to override the hostname; or specific logic for a cloud provider.
On the Kubelet polling: The API server pushes events to kubelet. Actually, the API server supports a "watch" mode, which uses the WebSocket protocol. In this way the Kubelet is notified of any change to Pods with the Hostname equal to the hostname of the Kubelet.
Kubelet can obtain Pod configurations required by the local node in multiple ways. The most important way is Apiserver. As indicated in the comments, the syncLoop function is the major cycle of Kubelet. This function listens on the updates, obtains the latest Pod configurations, and synchronizes the running state and desired state. In this way, all Pods on the local node can run in the expected states. Actually, syncLoop only encapsulates syncLoopIteration, while the synchronization operation is carried out by syncLoopIteration.
Refer Understanding the Kubelet Core Execution Frame for more information.


text:
Q: drag and drop event in fullcalendar Currently i am having problem with drag and drop event in fullcalendar: i don't know how to handle it!
Description the problem:

*

*I want only the blue line to be dragged and dropped, and the remaining lines are not dragged (because the blue part is the admin's part to confirm the division of work, and the rest is for the user):
my calendar

*after drag and drop it will look like this:

Before before

Expected: after

*

*I want after onclick column will start dragging the blue line from the click position

Here is my code:

var calendarEl = document.getElementById("calendar");
    var events = [];

    let calendar = new Calendar(calendarEl, {
        plugins: [interactionPlugin, resourceTimelinePlugin],
        initialView: "resourceTimelineDay",
        headerToolbar: {
            left: "",
            center: "title",
            right: "prev,next today",
        },
        height: "auto",
        locale: "ja",
        editable: true,
        resourceAreaColumns: [{
                field: 'title',
                headerContent: 'スタッフ'
            },
            {
                field: 'count',
                headerContent: '出勤回数'
            }
        ],
        resourceAreaWidth: "190px",
        views: {
            resourceTimelineDay: {
                slotDuration: "00:15:00",
                slotMinWidth: "10",
            },
        },
        eventDidMount: function(view, element) {
            var currentdate = view.intervalStart;
            $('.datetime-picker').datepicker().datepicker('setDate', new Date(currentdate));
        },
        resources: [{
                id: "1",
                title: "佐藤",
                count: "10",
                eventColor: "#b6d7a8"
            },
            {
                id: "2",
                title: "山田",
                count: "12",
                eventColor: "#ffe5e5"
            },
            {
                id: "3",
                title: "田中",
                count: "3",
                eventColor: "#bbd6ee"
            },
            {
                id: "4",
                title: "鈴木",
                count: "5",
                eventColor: "#e7e6e6"
            },
        ],
        // リソースごとのイベントを定義
        events: [{
                resourceId: "1",
                title: "",
                start: "2022-08-10T09:00:00",
                end: "2022-08-10T15:00:00",
            },
            {
                resourceId: "2",
                title: "",
                start: "2022-08-10T00:00:00",
                end: "2022-08-10T24:00:00",
            },
            {
                resourceId: "3",
                title: "",
                start: "2022-08-10T00:00:00",
                end: "2022-08-10T24:00:00",
            },
            {
                resourceId: "4",
                title: "",
                start: "2022-08-10T00:00:00",
                end: "2022-08-10T24:00:00",
            },
        ],
    });
    calendar.render();

Thanks all !


text:
Q: How to use digest authentication in Tomcat 8.5? I am trying to use the manager application that comes with Tomcat 8.5. However, every time that I try to log on with the password of "test" for the user "admin", it does not work.  If I plug in the exact MD5 hash that I obtained from digest.bat, I am able to log in.
Has anyone managed to get this working appropriately?
server.xml
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase" digest="md5" />
              <CredentialHandler className="org.apache.catalina.realm.MessageDigestCredentialHandler" algorithm="MD5" />
        </Realm>

tomcat-users.xml
<?xml version='1.0' encoding='cp1252'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<tomcat-users xmlns="http://tomcat.apache.org/xml"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
              version="1.0">

<user username="admin" password="41858d1250c84a1bfb882bcb02b85ba8" roles="admin-gui,manager-gui" />
<user username="test" password="test" roles="manager-gui,admin-gui" />
</tomcat-users>

tomcat webapp manager web.xml excerpt
  <!-- Define the Login Configuration for this Application -->
  <login-config>
    <auth-method>DIGEST</auth-method>
    <realm-name>TEST</realm-name>
    <!--<realm-name>Tomcat Manager Application</realm-name>-->
  </login-config>

digest.bat output
.\digest.bat -a MD5 -s 0 admin:TEST:test
admin:TEST:test:41858d1250c84a1bfb882bcb02b85ba8

A: Mine worked by following your steps except by placing the CredentialHandler inside the Realm:
<Realm className="org.apache.catalina.realm.LockOutRealm">
   <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase">
      <CredentialHandler className="org.apache.catalina.realm.MessageDigestCredentialHandler" algorithm="MD5" />
   </Realm>
</Realm>

A: Here's how you do it in 4 simple steps.  Some of the above advice was missing some of the steps (like Step # 4).  Also, -s 0 (salt 0) when generating the hash will work also.
1) Generate password:
/bin>digest.bat -s 0 -a sha-256
Example:
/bin>digest.bat -s 0 -a sha-256 admin
Password to use is:
8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918
*Important note: You must use "-s 0 "(salt 0) or it won't work.
2) paste password above into your tomcat-users.xml file.
Example:
<!-- for password "admin" -->
<user username="tomcat" password="8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918" roles="manager-gui,manager,admin"></user>

3) configure server.xml to use SHA-256 digest hashed based passwords:
<Realm className="org.apache.catalina.realm.LockOutRealm">
    <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase">
        <CredentialHandler className="org.apache.catalina.realm.MessageDigestCredentialHandler" algorithm="SHA-256" />
    </Realm>
</Realm>

4) configure your web.xml to use "DIGEST" passwords and update RealmName to match above (in the HTMLManager section)
 <catalina_home>/webapps/manager\WEB-INF\web.xml

    <login-config>
        <auth-method>DIGEST</auth-method>
        <realm-name>UserDatabase</realm-name>
    </login-config>

Full context:
  <servlet>
    <servlet-name>HTMLManager</servlet-name>
    <servlet-class>org.apache.catalina.manager.HTMLManagerServlet</servlet-class>
    <init-param>
      <param-name>debug</param-name>
      <param-value>2</param-value>
    </init-param>

… SNIPPED_FOR_BREVITY ...

    <login-config>
    <auth-method>DIGEST</auth-method>
    <realm-name>UserDatabase</realm-name>
  </login-config>

    <multipart-config>
      <!-- 50MB max -->
      <max-file-size>52428800</max-file-size>
      <max-request-size>52428800</max-request-size>
      <file-size-threshold>0</file-size-threshold>
    </multipart-config>
  </servlet>

A: **** Password digest process has been change to tomcat 8.5 version; it has been modified then how it was in tomcat earlier versions
Here is the tomcat password digest process for Tomcat 8.5.x ( we are using algorithm SHA-256 and SHA-512)
1. Change in $CATALINA_BASE/conf/server.xml file:
    a. From
         <Realm className="org.apache.catalina.realm.LockOutRealm">
                <!-- This Realm uses the UserDatabase configured in the global JNDI
                     resources under the key "UserDatabase".  Any edits
                     that are performed against this UserDatabase are immediately
                     available for use by the Realm.  -->
                <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
                        resourceName="UserDatabase"/>
             </Realm>
    b. To
         <Realm className="org.apache.catalina.realm.LockOutRealm">
                <!-- This Realm uses the UserDatabase configured in the global JNDI
                     resources under the key "UserDatabase".  Any edits
                     that are performed against this UserDatabase are immediately
                     available for use by the Realm.  -->
                <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
                        resourceName="UserDatabase">
                                <CredentialHandler className="org.apache.catalina.realm.MessageDigestCredentialHandler" algorithm="sha-512" />
                </Realm>
             </Realm>
2. Create digest password:
    a. Go to location $CATALINA_BASE/bin/ and run digest.sh
        i. For sha-256:
        [root@aa22 bin]# ./digest.sh -a sha-256 -h org.apache.catalina.realm.MessageDigestCredentialHandler xxxxxxxx
        xxxxxxxx:5327b745a19144e34ca40128219ab660b09ff9cf866222c1850a5e7a716db669$1$b4b734709246d25373a730cad709151db47920f79e1a1d65f6772d1307216f1b

        ii. For sha-512:
        [root@aa12 bin]# ./digest.sh -a sha-512 -h org.apache.catalina.realm.MessageDigestCredentialHandler xxxxxxxx
        xxxxxxxx:d92d95ae2fab83ca1eafae3b900ae9ab2115eac644935fb35a5973c3032dbcc7$1$c1f8e55b0beb771198ab46a69e1559ae145f172226d6f11ee91d67fde361717ca7498f48e486e4267e810b64e0a9096b16311ddc85b746c0019088462975bc9f

3. Now copy digested password to $CATALINA_BASE/conf/tomcat-users.xml
    a. Replace the plain text password with this digested password and restart tomcat. Make sure; you are using same algo name in server.xml; by which you digested the plain test password.
4. End

A: I don't think that it is not easy to choose the algorithm if using DIGEST. (At least I failed...)
 According the docs https://tomcat.apache.org/tomcat-8.5-doc/realm-howto.html#Digested_Passwords --
"If using digested passwords with DIGEST authentication, the cleartext used to generate the digest is different and the digest must use one iteration of the MD5 algorithm with no salt." Sounds for me that you have to use md5 at least once. It would be much easier to get rid of md5 with form based auth etc.


text:
Q: Securing an API called by the end users of a client I am building an API meant to be sold to various clients. These clients will be given an API Key or something similar and they'll use the API in a widget on their website.
The end users of the clients' website must be able to use the widget anonymously (no login).
Workflow:

My current idea is to have the Client's server retrieve a temporary key and use that in the webpage. The End user's browser will use that temporary key to call our API.
Is there any reason why this is not a good practice and/or insecure?
Or is there a better good practice solution? Can I for exmaple use OAuth 2 for this?

A: You need to secure your API from the clients app. So, for that you can use OAuth 2 with Client Credentials grant type and setup each client as an app so they each get their own set of key/secret credentials.
Since you don't know anything about the end user, but still need to track them, require an endUserId custom header on every request to your API and you'll just have to trust the client to provide you with a valid id for the end user making the request.
To setup OAuth, use an existing library or OAuth service. I don't recommend writing your own. If you can spend some money, Okta and Auth0 are good choices. If your API is written in .net, you can use IdentityServer as a free option.


text:
Q: How many Write Ops is neccessary to write blob data(byte array) on appengine datastore? I realized it is very expensive to create many new entities(and properties), so I decided to store data chunk (~50kb, zipped Json)in one entity as byte array (blob) to Datastore.
However, I have no idea how many write/read ops might be neccessary to write/read blob data. I wonder whether it is depends on size of blob data or it is just constant write/read ops.
Thank you in advance :)

A: blobstore data is stored data

Stored Data (billable)
  The total amount of data stored in datastore entities and corresponding indexes, in the task queue, and in the Blobstore.

So you like entities you pay by read, write and not by size
https://developers.google.com/appengine/docs/quotas#Datastore
Costs: https://developers.google.com/appengine/docs/billing

*

*Entity Get (per entity)   1 Read

*New Entity Put (per entity, regardless of entity size)    2 Writes + 2 Writes per indexed property value + 1 Write per composite index value

*Existing Entity Put (per entity)  1 Write + 4 Writes per modified indexed property value + 2 Writes per modified composite index value

*Entity Delete (per entity)    2 Writes + 2 Writes per indexed property value + 1 Write per composite index value

*Query 1 Read + 1 Read per entity retrieved

*Query (keys only) 1 Read + 1 Small per entity retrieved

*Key allocation (per key)  1 Small

*

*Write    $0.10 per 100k operations

*Read    $0.07 per 100k operations

*Small    $0.01 per 100k operations

Also consider storage costs

*

*Stored Data (Blobstore)  gigabytes per month $0.13  [free limit 5 gb]

*Stored Data (Datastore)  gigabytes per month $0.24  [free limit 1 gb]


text:
Q: Is it possible to ping from a source IP address to a destination IP address in C#? I have been tasked with verifying the connectivity between various devices that I can't query directly. The way the C programmers did it in the past was to create a batch file with lines like:
ping -n 5 -S [Source Address] [Destination Address] >> OutputFile.txt
Then they run the batch file and open the output file and parse the results to find out if it worked.
In C# I know I can simply write:
Ping pinger = new Ping();
PingReply reply = pinger.Send(DestinationAddress);
and check reply.Status for IPStatus.Success
But this does not specify the source address. I have searched but I haven't been able to find a way to do anything like the command line shown above in C#. Is there no new and better way than this old kluge?