text:
Q: The type or namespace name does not exist in the namespace 'System.Web.Mvc' Buiding MVC3 solution went well but have got an error in browser:
Compiler Error Message: CS0234: The type or namespace name 'Html' does not exist in the namespace 'System.Web.Mvc' (are you missing an assembly reference?)
Source Error:
Line 25:         <add namespace="System.Web.Mvc" />
Line 26:         <!--<add namespace="System.Web.Mvc.Ajax" />-->
Line 27:         <add namespace="System.Web.Mvc.Html" />
Line 28:         <add namespace="System.Web.Routing" />
Line 29:         <add namespace="System.Web.WebPages" />

I have installed packets for the solution with NuGet and set up for all projects MVC3. Does MVC3 include libraries System.Web.Mvc.Ajax,  System.Web.Mvc.Html and others? Why am I getting the error?

In References folder, I have System.Web.Mvc
Runtime version: v4.0.30319,
Version: 3.0.0.0

Web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=152368
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
    <add key="webpages:Version" value="1.0.0.0" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" />
    </authentication>
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <httpRuntime targetFramework="4.5" encoderType="System.Web.Security.AntiXss.AntiXssEncoder, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    <machineKey compatibilityMode="Framework45" />
    <profile defaultProvider="DefaultProfileProvider">
      <providers>
        <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </profile>
    <membership defaultProvider="DefaultMembershipProvider">
      <providers>
        <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <roleManager defaultProvider="DefaultRoleProvider">
      <providers>
        <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </roleManager>
    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
      </providers>
    </sessionState>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityFramework>
  <connectionStrings>
    <add name="EFDbContext" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=SportStore;Integrated Security=True;Pooling=False;" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

MSDN the System.Web.Mvc namespace
file packages.config:
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="EntityFramework" version="5.0.0-rc" />
  <package id="jQuery" version="1.7.2" />
  <package id="jQuery.UI.Combined" version="1.8.11" />
  <package id="jQuery.Validation" version="1.9" />
  <package id="Microsoft.AspNet.Mvc" version="3.0.20105.1" />
  <package id="Microsoft.AspNet.Providers.Core" version="1.0" />
  <package id="Microsoft.AspNet.Providers.LocalDB" version="1.0" />
  <package id="Microsoft.AspNet.Razor" version="1.0.20105.408" />
  <package id="Microsoft.AspNet.WebPages" version="1.0.20105.408" />
  <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" />
  <package id="Modernizr" version="2.0.6" />
  <package id="Moq" version="4.0.10827" />
  <package id="Ninject" version="3.0.1.10" />
</packages>

A: I downloaded an mvc 5 project and the offending issue pointing at
<add namespace="System.Web.Mvc.Ajax" />

With this error message:
CS0234: The type or namespace name 'Ajax' does not exist in the namespace 'System.Web.Mvc' (are you missing an assembly reference?)

-- >  in which I came to this webpage and tried a clean and a few things above etc...
What worked for me was just to
Manage Nuget and Update all the packages.  Then it worked fine.

A: Running the following command in the nuget package manager fixed it for me:
update-package microsoft.aspnet.mvc -reinstall

A: For whatever reason, TWO of my solutions have web projects that spontaneously uninstalled asp.net MVC somehow. I installed it from Nuget and now they both work again. This happened after a recent batch of windows updates that included .net framework updates for the version I was using (4.5.1).
Edit: From the .Net Web Development and Tools Blog:
Microsoft Asp.Net MVC Security Update MS14-059 broke my build!

A: This answer is rather late given the question date, but someone may find it useful.
None of the above solutions worked for me in Visual Studio 2012 on a local project, Net Framework 4.5 MVC 4. For context, I was following a tutorial on creating a barebones Web Api on CodeProject (http://www.codeproject.com/Articles/615805/Creating-a-Clean-Minimal-Footprint-ASP-NET-WebAPI) when I ran into this problem.
What did work for me was explicitly adding "System.Web.Mvc" to my application's references, even though the application already did reference "System.Web".

A: Clean your solution and then set the property of those files to Copy Local = True.
To set the Copy Local property to True or False
In Solution Explorer, click the Show All Files button to display the References node.

*

*Open the References node for the project.

*Right-click a reference in the References list, and click Properties.
The properties associated with that reference appear in a list in the Properties window.

*In the Properties window, change the Copy Local property to True or False.

A: I had the same issue, but none of the above worked for me. They did put me in to the right direction though.
For example when I set the "Copy Local" to "true" for System.Web.Mvc reference, it automatically sets it back to False.
I have multiple projects which  depend on the System.Web.Mvc reference in my solution, but only one caused this problem.
In VS 2012 this reference is labeled with the yellow attention triangle.
Find this reference => remove it => re-add it
That fixed it for me.
Hope this helps

A: This one normally catches me when I run from IIS and the app pool for the default site is set to .NET version 2.0. When using IIS from visual studio it creates a virtual directory but still runs under the default site's app pool.
If using the build in web server, right click on your web project, go to properties and make sure you're running it under the right version of .NET.
On IIS check the .NET version on your app pool.
Following on from my last comment about how the project was created - are you correctly including the assemblies, as below (taken from the default web.config file generated by the MVC3 project template in VS10):
<compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
</compilation>

A: You need to update MVC.

*

*Go to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution

*Click on "Updates"

*Update "Microsoft ASP.NET MVC"

*Rebuild Solution

A: View and check the reference paths in your csproj.
I had removed references to System.Web.Mvc (and others) and readded them to a custom path. C:\Project\OurWebReferences
However, after doing this, the reference path in the still csproj did not change.
WAS
<Reference Include="System.Web.Mvc, Version=4.0.0.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>..\..\..\..\OurWebProject\bin\Debug\System.Web.Mvc.dll</HintPath>
</Reference>

Changed to manually
<Reference Include="System.Web.Mvc, Version=4.0.0.1, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
        <HintPath>..\..\..\..\OurWebReferences\System.Web.Mvc.dll</HintPath>
</Reference>

Paths are an example only.

A: For me, the solution was to ensure all projects were building for the same CPU - in my case x86

A: I have a project that does this whenever I build with the View open.  As soon as I closed the view, the error goes away and the build succeeds.  Very strange.

A: I had the same problem - my scenario was that I was referencing the new System.Web.Mvc.dll from a lib folder and I did not have "Copy Local" set to true.  The application was then reverting back to the version in the GAC which didn't have the correct namespaces (Html, Ajax etc) in it and was giving me the run time error.

A: Copy Local = True was solve for one of my projects. But in another project, I get the same error, tried to set Copy Local = true, but it not solve my problem. Changing the Target framework from 4.5.1 to 4.5 in Project Properties Helped with this.

A: I did something really stupid (and maybe you did too).
I was trying to call System.Web.Mvc.Html.Partial("<Partial Page>")
System.Web.Mvc.Html is a namespace and not a class and I didn't read my error message so well, so I interpreted my error as the class Html does not exist in the namespace System.Web.Mvc and that's how I ended up here (stupid I know).
All I needed to do was add a using statement @using System.Web.Mvc.Html to my page and then @Html.Partial worked as expected.

A: My solution was under Manage Nuget Packages for Solution... -- I had umpteen updates to do for quite a few packages.
Let me back up a half step and say that I screwed myself over because I moved the solution and projects from one folder to another... so things were already out of whack compared to where the projects thought things out to be. Everything moved over just fine, but apparently Nuget becomes confused unless you use a different approach than I did.
Back to the solution... I simply went to Manage Nuget Packages for Solution... >> Updates >> Microsoft and .NET and hit the Update All button.
Everything was back to normal and happy.

A: if any of above not solves your problem just set properties of System.Web.Mvc.dll to copy local ture.
it will solves

A: I had the same problem, but in my case was originated by other factor. I write this to help other people with the same problem.
I have a solutions with multiple projects. two of them work with the System.Web.Mvc, Normally our reference was pointing to external packages where we controlled the used version. For some reason one of the project reference goes to GAC and point to the GAC dll (version 4.0.0.1) and the program got the error.
To correct it:
Simple check if the references to System.Web.Mvc point to the same dll in the same directory path.
I hope that help.

A: I have deleted System.Web.dll from Bin frolder of my site.

A: I had this problem, setting copy local on and off etc did not work.
The project was not using nuget so fixes around that were out of the question also.
The fix for me was to install MVC 3 (which I did through the web platform installer).
I suspect this will become more of a solution for people as the .net framework continues to advance and people don't have the older MVC stuff installed.

A: It's likely that setting your DLL to CopyLocal/true or any of the other major fixes for this will fix your issue, but here is another edge-case that caught me for 20 minutes of wasted time.
When you add your namespaces to your Views/Web.config, ensure they are cased correctly:
  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="THE.NameSpace" />
        <add namespace="THE.Namespace" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

A: Ok so a lot of people seem to be experiencing this issue. My problem was caused by references having paths to the bin folders of other projects, or referencing dlls from system folders. The project was about 6 years old and the previous developers had decided that this was the way they were going to reference their libraries.
The solution was to go through every reference and check the paths, then remove the reference and add it using NuGet. For any package that wasn't on NuGet I created another folder alongside packages and put the dll in there in the same layout as NuGet would.
I also had to go through the config files and make sure the correct version of the packages was being used. A long and painful process!

A: I had the same problem, none of the solutions worked for me, Finally I removed the System.Web.MVC and added again Then everything was back to normal and my problem solved.

A: As so often happens, all of the radical steps in the other answers were unnecessary for me.  Instead, I had an error which wasn't being flagged correctly.  My advice is to read the message before doing anything too drastic!
The error said:

The file quoted was a temporary file - not much use there.  But when I did a global search for the offending view model vmPayConfirm I found this:

Once I corrected this error (I'd used the wrong namespace to reference the view model) everything worked perfectly!


text:
Q: Separar cadena y llenar columnas con sql estoy trabajando con cadenas de texto que están almacenadas en una tabla, pero debo extraer algunos datos para unas consultas.
Por ahora tengo esto:
---------------------------------
archivo         |Folio    |Fecha|
T_0203_20200908 |T        |     |
T_0203_20200908 |0203     |     |
T_0203_20200908 |20200908 |     |

Ya me separa los datos por el caracter '_' , pero todos los pone en las misma columna con esto:
 SELECT nombre_archivo,
        t.n.value('.','CHAR(100)') as Data
    FROM
    (
        SELECT nombre_archivo,
          CAST ('<M>' + REPLACE(nombre_archivo, '_', '</M><M>') + '</M>' AS XML) AS Data
        FROM  ArchivosOK
    )  AS A CROSS APPLY Data.nodes ('/M') AS t(n);

Y para acomodar los datos en las demás columnas, he tratado lo siguiente:
  SELECT nombre_archivo,
            t.n.value('col[2]','CHAR(100)') as Folio
            t.n.value('col[3]','CHAR(100)') as Fecha
        FROM
        (
            SELECT nombre_archivo,
              CAST(('<rows><row><col>' + REPLACE(REPLACE(nombre_archivo,'_','</col></row><row>
              <col>'),'_','</col><col>') + '</col></row></rows>') AS XML) As Data
        FROM  ArchivosOK
    )  AS A CROSS APPLY Data.nodes ('/rows/row') AS t(n);

el resultado que espero es :
  ---------------------------------
    archivo         |Folio    |Fecha    |
    T_0203_20200908 |0203     |20200908 |
    T_0204_20200909 |0204     |20200908 |
    T_0205_20200906 |0205     |20200906 |

pero eso me manda todo null, ¿Me podrían sugerir alguna de forma de hacerlo? Gracias.

A: Para extraer segmentos separados por el caracter '_' en SQL Server, puedes valerte de las funciones charindex y substring.
Con charindex encuentras la posición de cada caracter y con substring obtienes las subcadenas delimitadas por estas posiciones.
Aunque se podría escribir todo en una sola sentencia (difícil de leer). Yo sugiero escribir primero un CTE que nos dé las posiciones de los caracteres de interés y finalmente escribir la sentencia que extrae las partes de la cadena, pues esto es más fácil de leer (y de mantener):
Por ejemplo:
with
ArchivosOK as (
select *
  from (values ('T_0203_20200908')
             , ('T_0204_20200909')
             , ('T_0205_20200906')
        ) q1 (archivo)
)
,
ArchivoConSeparador as (
select   Archivo
       , charindex('_', Archivo) Separador1
       , charindex('_', Archivo, charindex('_', Archivo) + 1) Separador2
  from ArchivosOK
)
select  Archivo
      , substring(Archivo, Separador1 + 1, Separador2 - Separador1 - 1) Folio
      , substring(Archivo, Separador2 + 1, 10) Fecha
  from ArchivoConSeparador;

Nos dará el resultado que buscas:
Archivo         Folio           Fecha
--------------- --------------- ----------
T_0203_20200908 0203            20200908
T_0204_20200909 0204            20200909
T_0205_20200906 0205            20200906

(3 rows affected)

Completion time: 2020-10-12T08:33:45.7895890-06:00

redpajama_set_name: RedPajamaStackExchange


text:
Q: two models in blade template in laravel I have two models, model1 and model2 . I am using this models in blade template and I don't want to use controller for getting value.
 @php
    $school = App\Models\Model1::all()
    $department = App\Models\Model2::all()
@endphp

<select name="school">
     <option value="" selected="">school</option>
         @foreach($school as $val)
         <option value="">{{$val->name}}</option>
          @endforeach
</select>

<select name="departments">
     <option value="" selected="">department</option>
       @foreach($department as $val)
        <option value="">{{$val->name}}</option>
         @endforeach
</select>

But I am getting this error:
syntax error, unexpected '$department' (T_VARIABLE)

But when I call only one model, the data shows perfectly. How can i solve this problem?

A: I think you forgot the semicolon.
@php
   $school = App\Models\Model1::all();
   $department = App\Models\Model2::all();
@endphp


text:
Q: Get type of rails model? If I have a user model.
sample_user = User.all.first
Is there a way in Ruby to get type back in a String? Something like:
typeof(sample_user) == "User"

A: sample_user.class.name

will give you "User"

A: You can do it multiple ways :
1st :
sample_user.is_a? User

2nd :
sample_user.class.to_s == "User"

and more :). But if you want to check class type with object. Then 1st One would be good.

A: If you are doing comparison, use #kind_of? or #is_a?
sample_user = User.first

sample_user.kind_of? User
#=> true

sample_user.is_a? User
#=> true


text:
Q: WSO2 APIM Custom sequences for non published APIs / Setting variable We have defined a default custom sequence for managing different gateways, as described here
We have installed the sequence as explained in the doc Creating Global Conection
The sequence only read 2 variables from environment, and uses to build the endpoint URL. This is the code:
<sequence xmlns="http://ws.apache.org/ns/synapse" name="WSO2AM--Ext--In">
        <property name="uri.var.host" expression="get-property('system','host')" />
        <property name="uri.var.port" expression="get-property('system','port')" />
</sequence>

This is working fine with Published API, but if we degrade the API to prototype (for using directly without subscription), it doesn't work.
We have tried:

*

*To install it as a Message Mediaton Policy at API level

*Setting the parameter in the
/repository/resources/api_templates/prototype_template.xml In
sequence
The error when we test reports empty host name (as it tries to read the variable, and it's empty)
Do you know how to set environment variables in prototyped environment?

A: When the API is deployed in "Prototype Endpoint" uses the velocity_template.xml for creating the API implementation.
This template generate different code for PROTOTYPE and PUBLISHED APIs.
I have forced to include the APIManagerExtensionHandler (which is the handler processing the Custom Extension Sequence), adding the following in velocity template (after the handler adding loop).
patch --forward $WSO2_PATH/$1/repository/resources/api_templates/velocity_template.xml <<EOF
*** velocity_template.xml   2018-06-02 11:04:42.474476581 +0200
--- velocity_template.xml.patched   2018-06-02 11:07:28.495395384 +0200
***************
*** 361,366 ****
--- 361,369 ----
      #end
  </handler>
  #end
+ #if(\$apiStatus == 'PROTOTYPED')
+ <handler class="org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler"/>
+ #end
  </handlers>
          #end
          #end
EOF


text:
Q: Asterisk in the argument name with C preprocessor I want to implement cross-platform build of my DLL with mingw32/VC.
At the moment everything is perfect with mingw side. However I have to wrap several things in macro for VC (it is built as /TC), for example:
void __attribute__((fastcall)) do1 (  A*, B , C, D );
bool __attribute__((fastcall)) ( *do2 ) ( E*, F );

The first one is simple, just a macro:
#ifdef __MINGW32__
    #define __FASTCALL__ __attribute__((fastcall))
#elif _MSC_VER
    #define __FASTCALL__ __fastcall
#else
    #error "unsupported compiler"
#endif

The problem comes with the second one. Calling convention with a function pointer should looks like
bool ( __fastcall *do2 ) ( E*, F );

I tried the following macro (I skipped ifdef part):
#define __FASTCALLP__(func) (__attribute__((fastcall))(*##func))
#define __FASTCALLP__(func) (__fastcall *##func)

or if pass function name with asterisk:
#define __FASTCALLP__(func) (__attribute__((fastcall))(##func))
#define __FASTCALLP__(func) (__fastcall ##func)

Both failed with

error: pasting "*" and "function_name" does not give a valid
  preprocessing token

May I wrong at my approach at all? Or I have to ifdef the whole code blocks or separate it to different files?

A: The problem is with the Concatenation-Operator ##. It will produce a new preprocessor token by concatenating the left- and right-hand-side, which does not exists (*do2 is no defined token)
Simply omit it and write like this (omitting #ifdefs):
#define __FASTCALL__(func) (__attribute__((fastcall))(func))
#define __FASTCALL__(func) (__fastcall func)

and use like this:
bool __FASTCALL__(do1)(A*, B , C, D);
bool __FASTCALL__(*do2)(E*, F);


text:
Q: How to preserve the format when writing to csv using pandas? I have a text file like this:
id,name,sex,
1,Sam,M,
2,Ann,F,
3,Peter,
4,Ben,M,

Then, I read the file:
    df = pd.read_csv('data.csv')
After that, I write it to another file:
    df.to_csv('new_data.csv', index = False)
Then, I get
id,name,sex,Unnamed: 3
1,Sam,M,
2,Ann,F,
3,Peter,,
4,Ben,M,

You see that there are two commas instead of one in the fourth line.
How to preserve the format when using pd.to_csv?

A: pandas is preserving the format - the 3d row has no sex, and as such the csv should have an empty column - that is why you get to commas, since you are separating an empty column.
Your original text file was not a valid csv file.
What you want to do is something else, which is not write a valid csv file - you will have to do this yourself, I do not know of any existing method to create your format.

A: The problem in your code is that you have a comma after the sex column in your file. So read_csv thinks it's a new column, which has no name and data.
df= pd.read_csv('data.csv')
df

id  name    sex Unnamed: 3
0   1   Sam M   NaN
1   2   Ann F   NaN
2   3   Peter   NaN NaN
3   4   Ben M   NaN

Hence you have an extra Unnamed column. So when you write the to_csv, it adds two empty values in the 3rd row and hence why, two ,.
Try:
df = pd.read_csv('data.csv', use_cols = ['id', 'name', 'sex'])
df.to_csv('new_data.csv', index = False)


text:
Q: How to separate strings in a list in python? Ok i have this ['state1', ',', 'state2,st6'] and I want it to be like this
[['state1'], ['state2'], ['st6']] or ['state1', 'state2', 'st6']

I dont understand lists that great and i tried myself and always the same, list has no attribute split, lstrip etc. Any ideas?

A: I would do, these are called list comprehensions:
>>> original = ['state1', ',', 'state2,st6']
>>> [[item] for string in original for item in string.split(',') if item]
[['state1'], ['state2'], ['st6']]

or if you don't want nested lists:
>>> [item for string in original for item in string.split(',') if item]
['state1', 'state2', 'st6']

A: I have seen ur previous version of same question ..i think above answers can only split if there is comma only . if u want to remove any symbol .. u can use this and different implementaion to learn

import re
data=['state1', ',', 'state2','|','st6']
p = r"^[\w'-]+$"

 > def f(x):
    >     if re.search(p, x):
    >         return True
    >
    > print filter(f,data)

output :
> ['state1', 'state2', 'st6']

A: I would join the list to string then split:
>>> a = ['state1', ',', 'state2,st6']
>>> [[i] for i in ''.join(a).split(',')]
[['state1'], ['state2'], ['st6']]


text:
Q: How to convert float to 4 byte hex value without pack in python I give a number in lineEdit text area. This lineEdit gets float numbers form the users.
userValue gives me this float number.
print(type(userValue)) gives me "str" type.
If the users enter the number like a 0.9 , I need to convert this float number to 4 byte, I did this converting with this line : list(struct.pack('<f', float(userValue)))
But this value return double precision value. When I return the data from the hexToFloat or another device code HexToFloatConverter I get as a 0.8999999999212 number. How can I convert float to hex whit correct 4 bytes without struct.pack using ?
What is the another method return 0.9 number to 4 byte hex value correctly ?
def hexToFloat(self,hexArray = []):
    ba = bytes(hexArray)
    return (struct.unpack('<f', ba)[0])

This is another device code :
float HexToFloatConverter(uint8_t *hexArray)
{
 float convertedValue = 0.0;
 memcpy(&convertedValue,hexArray, sizeof(convertedValue));
 return convertedValue;
}

A: Floating point math is hard. 0.89999... is a valid representation for 0.9 in floating point math. The problem is with floats rather than with struct.pack.
You would need to clean up the number yourself:
import struct
def pack_float(my_float: float) -> bytes:
    return struct.pack('<f', my_float)

def unpack_float(my_bytes: bytes) -> float:
    unpacked_float = struct.unpack_from('<f', my_bytes)[0]
    rounded = round(unpacked_float, ndigits=2)
    return rounded

packed = pack_float(0.9)
unpacked = unpack_float(packed)
print(unpacked)

# Outputs 0.9

This will be fine for numbers with a 'few' significant digits (I think 5 significant figures or 2 decimal places is mostly accurate).
If you need more accuracy/precision, you'll need to adjust one of your requirements.
As an example, using the 8 byte decimal d double format, its mostly accurate at 14 significant figures or 6 decimal places:
import struct
def pack_float(my_float: float) -> bytes:
    return struct.pack('d', my_float)

def unpack_float(my_bytes: bytes) -> float:
    unpacked_float = struct.unpack_from('<f', my_bytes)[0]
    rounded = round(unpacked_float, ndigits=6)
    return rounded

packed = pack_float(0.9)
unpacked = unpack_float(packed)
print(unpacked)

# Outputs 0.9


text:
Q: How do you represent an object when you need to know which subtype you're working with? I have some data that I need to represent in a form. As an example, it might look like this (in psuedo-json):
[
    {
        "value1" : "int"
        "value2" : "{1, 2, 3, 4, 5}"
        "value3" : "int"
    }
    {
        "value1" : "{1, 3, 5}"
    }
]

So when I display the first form, the user should have an integer text field, a combobox, and another text field to fill out, but the second should only have a combobox. In my model, I'm viewing this as each Form has a List<FormElement> so that I can properly iterate over each form element to generate the GUI. But now I have the problem of needing the specific type of FormElement each time I use the list.
I've tried to model this like so (psuedo-code):
class Form {
    List<FormElement> integerField
}

class FormElement {
    String message
    Integer value
    FormType type
}

enum FormType {
    ENUMERATED,
    INTEGER
}

And then I could simply perform the checks in non-model code, but I'd still need a way to attach the possible values for enumerated types to the enumerated objects. So I thought of doing something like this:
class Form {
    FormElement integerField
}

abstract class FormElement {
    String message
    Integer value
    boolean validate(Integer value)
}

class EnumElement extends FormElement {
    List<String> values
    boolean validate(Integer value) { return value in values }
}

class IntegerElement extends FormElement {
    boolean validate(Integer value) { return true }
}

Now this does work. However, in my code, I have to do type casting all over, something like so (or I could "avoid" the type casting with an enum like before):
void generateField(FormElement element) {
    makeLabel(element.message)
    if (element instanceof EnumElement) {
        makeCombobox(((EnumElement) element).values);
    } else if (element instanceof IntegerElement) {
        makeNumericTextField()
    }
}

I get the feeling that there has to be a better way to do this.

In a more complicated example, it could be that the field should restrict to integers, or to floats, or be arbitrary strings, or be an enumerated combobox, or be a checkbox for a boolean, a "spreadsheet" for a matrix, xml for an arbitrary object, etc. There has to be a better way than repeating the "switch" everywhere I need to use the type.

A: the classic way is to use a Factory class with your switch
Factory.Create(data)
{
    switch data.class
    case : combo
       return new Combo(data)
    ....

}

this can be made more generic using reflection until you end up with a dependency injection container
container.Register<FormElement,Combo>().Named("combo")

container.Resolve<FormElement>().WithName(data.type).WithConstructionParameter(data)

A: Instead of checking and invoking specific makeComboBox vs. makeNumericTextField, consider invoking a generic constructUI, which would be a virtual method on the base class FormElement that is overridden by the various subclasses, each of which does the equivalent.
The idea behind OOP is to instruct the object to do something useful on its own and return to you (base or abstract) types so you don't have to deal with the switching (or if...else ifing).  We put the "do something useful" method in the base class, and have it take parameters and return values that are also equally abstract.  The trick to doing this when you have the "check what subclass to see how to proceed" code smell is to find the right abstraction to put in the base class.  In this case, I'd suggest something that creates the user interface element.


text:
Q: Cannot get speech-arrow on text box pointing toward user and bot messages for each of their messages I need to get a speech arrow included within my chatbot to point at where the message has been sent from.  I have not found anything relating to this within any of the docs, but I have seen this design implemented in several of the example images within the same docs.
To clarify, my text chat is rounded without anything jutting out to indicate who sent the message.  The effect I am going for is what is seen in the 'test in web chat' section of the azure docs listed here: https://learn.microsoft.com/en-us/azure/cognitive-services/luis/luis-nodejs-tutorial-build-bot-framework-sample

A: I've determined that this is not possible using the current customization abilities of Web Chat v4. It looks like you've already found the GitHub issue where progress on this feature can be tracked: https://github.com/Microsoft/BotFramework-WebChat/issues/1658


text:
Q: Which articulation is correct for natural things (cold, green, day, time) - A or The? I am making the photobook, there are sceneries and one sentence phrases on the pages.
I am not an English speaker, and in my language, there are no such things as articles whatsoever. This question, what is the correct way to write it in English?
I have written it one way first, but now I am totally confusing.
A day is increasing in January. it is not the specific day, it is a day in general. So does the cold, that comes at once. Would it be something specific, I would know, though there are such notions as cold, frost, day, time, I am completely lost with the correct articulation here.
Please help
Also, I appreciate if the correct word for cold is found.
In the 1.sentence the speech is about the chill, and in the 3rd, about freeze (the worst cold, when the temperature falls far below zero C). I cannot use "cold" word in both places but am unsure about words chill and freeze in this context.
Unsure about 11. fieldwork. I mean the agricultural work in fields.
Eugene

*

*Cold comes unexpectedly (quickly). Frost covers everything and grows on trees.

*Snow covers the ground with a thick blanket.

*Cold comes rapidly, so does the darkest time.

*A day is increasing and the sun is shining.

*The low sun casts long shadows, but the coldest time is still to come.

*The coldest time comes suddenly.

*Winter is gradually leaving (declining).

*White snow is melting.

*The snow cover melted, revealing the bare ground.

*Green is in a hurry to take its place.

*Fieldwork has begun.

*Crops and vegetation grow rapidly.

I have added a new text completing the book

*Dandelions cover the ground with a yellow carpet.

*In the middle of Summer, you can read all night long.

*July is called "the month of hay" in Finnish.

*So, autumn has come and so the harvest time.

*"Golden Autumn" comes with its bright colors, rich yellow and red colors, clear azure sky.

*Harvest is taken in bins, and everything is ready for winter.

Explanations - 17. Golden autumn is really nice, but last year leaves have fallen while still green because of the frost. The season change in northern Europe happens very quickly and does not last more than a week or maximum two. It could be snow snow snow time till May, and then everything would melt in under a week when the Warm wind brings suddenly the very warm air from the South. This is why I have written "suddenly", "rapidly", every change in the season does happen within a couple of days. You go to the bed in "fallgold", and wake up in the winter season. One snow storm makes the scenery.
Winter and Spring do really rush and there are "white nights" and "dark time" in December, at least in the local language. It looks almost "evil" when the sun is very low, the sky is almost black and suddenly turns red.

A: The rule is: "a" is an indefinite article, while "the" is a definite article. You use "a" when you're referring to any object of that type. You use "the" when you're referring to a specific object of that type.

Day is increasing in January. it is not the specific day, it is a day in general

Since you are not referring to a specific day, you would use the indefinite article: "A day".

So does the cold, that comes at once.

There is only one cold that is coming, so you would use the definite article: "The cold".

*

*Cold comes unexpectedly (quickly). Frost covers everything and grows on trees.

"The" is correct here, because when you say "cold", you are referring to the weather, and there's only one weather. The complete sentence, including implied words, is: "The cold [weather] comes unexpectedly [quickly]."
You are also correct to say that "Frost covers everything", but "and grows on trees" is very metaphorical. Frost doesn't actually grow, because it is not alive. So, although this is not grammatically wrong, if you wanted to avoid the metaphorical language, you would need to swap "grows" for "forms".

*Snow covers the ground with a thick blanket.

This is technically correct, but it would sound better to invert the order of the sentence so that it becomes: "A thick blanket of snow covers the ground."

*Cold comes rapidly, so does the darkest time.

This is understandable, but sounds weird, especially the second half of the sentence. It's difficult for me to rephrase when I only have limited context, but maybe try something like: "The cold comes rapidly, bringing shorter days."
"The darkest time" is not clear, and sounds more like a metaphor for evil than a literal reference to a shortening of the period of daylight during the winter.

*A day is increasing and the sun is shining.

It is not a single (albeit indefinite) day that is increasing here; it is the length of all days. So, perhaps try: "The days are getting longer, and the sun is shining." Or, invert the order: "The sun is shining, and the days are getting longer."

*The low sun casts long shadows, but the coldest time is still to come.

This is entirely correct.

*The coldest time comes suddenly.

This is also grammatically correct, but sounds a bit weird to me. The use of a superlative here ("coldest") is jarring. How can the weather suddenly be the coldest it is ever going to get? That's just not how weather patterns work.
Consider just saying: "Suddenly, it is cold.", or "Suddenly, the cold is upon us."

*Winter is gradually leaving (declining).

Correct as far as it goes, but it begs the question of what is coming next.
"Declining" doesn't work here at all (wrong connotation), but "leaving" is okay. "Fading" or "receding" would be better. This still begs the question of what is coming next. Perhaps consider, "Winter is gradually fading into spring."

*White snow is melting.

Technically correct, but the use of the adjective "white" here sounds odd—what other color of snow is there? (I mean, there are other colors of snow, but that's probably not the message you want to convey.) Keep it simple: "The snow is melting."
If you want to keep the word "white" in there, consider returning to your previous metaphor: "The white blanket of snow is melting."

*The snow cover melted, revealing the bare ground.

You should use present perfect tense here: "The snow cover has melted..."
I also think "barren" is more appropriate in this context, since the snow covering throughout winter has killed most of the vegetation: "...revealing the barren ground."

*Green is in a hurry to take its place.

Correct. Very metaphorical, but that is surely intentional.
If you wanted to use an article for "green", the definite article ("the") is appropriate. But it is not necessary here, and simpler to omit it.

*Fieldwork has begun.

"Fieldwork" sounds odd here. Try being more explicit: "The planting season has begun." Or, to keep consistent with your breathless pace: "The planting season is in full swing."

*Crops and vegetation grow rapidly.

Correct, but kind of loses the previous metaphorical feel. To keep the metaphor established on the previous pages, consider something like: "Fields of green quickly cover the once-barren soil."

More generally, I'm not sure why you're trying to rush everything. Why is everything happening "rapidly" or "quickly"? For a photo album, don't be afraid to slow the pace down and let the viewer take a breath, lingering on the page and enjoying the photos.


text:
Q: Convert CROSS APPLY in DB2 database I am trying to convert the below MSSQL query into DB2 query.
But i am facing issues . I got to know "CROSS APPLY" doesnt exist for DB2
SQL Server query:
SELECT DISTINCT p.ID,
p.COMPANY,
p.NAME,
format(d.startTime, 'yyyy-MM-dd HH:mm:ss.fff')
FROM PROCESS p
CROSS APPLY (SELECT MAX(END_TIME) AS startTime FROM PROCESS WHERE ID = (SELECT MAX(ID) FROM PROCESS)) AS d
WHERE p.ID = (SELECT MAX(ID) FROM PROCESS)

Error:

Error: com.ibm.db2.jcc.c.SqlException: DB2 SQL error: SQLCODE: -104, SQLSTATE: 42601, SQLERRMC: APPLY;N process
CROSS;JOIN

How the above query can be converted into DB2 query format?

A: The SQL Server manual says that a CROSS APPLY is used with table functions.
https://learn.microsoft.com/en-us/sql/t-sql/queries/from-transact-sql?view=sql-server-ver15#using-apply

That the right_table_source can use a table-valued function that takes a column from the left_table_source as one of the arguments of the function.

Your example does not use any, so I assume it is simply the equivalent to a CROSS JOIN in Db2.
By the way, this statement would likely get the same result (assuming COMPANY and NAME are the same for a given ID)
SELECT
    ID
,   COMPANY
,   NAME
,   format(END_TIME, 'yyyy-MM-dd HH:mm:ss.fff')
FROM
(   SELECT *
    ,   ROW_NUMBER() OVER(ORDER BY ID DESC, END_TIME DESC) AS RN
    FROM
        PROCESS p
)
WHERE
    RN = 1

This might or might not be more optimal at execution time

A: The DB2 equivalent is the terribly named TABLE operator.  The name makes it very challenging to find documentation.
See if this works for your query.
SELECT DISTINCT p.ID,
    p.COMPANY,
    p.NAME
FROM PROCESS p
JOIN TABLE (
        SELECT ID
            ,MAX(END_TIME) AS startTime
        FROM PROCESS
        WHERE ID = (
                SELECT MAX(ID)
                FROM PROCESS
                )
        GROUP BY ID
        ) AS D
ON P.ID = D.ID

However, I've found CTEs in DB2 to be very effective.  In SQL Server, a CTE is almost like a layer applied to a query, similar to a view.  The expressions in the CTE are generally combined with the underlying statements and executed as a single statement.
I'm not a DB2 expert, but it seems to me that a CTE is materialized to an internal table and the result is combined with the remaining statements.
With the same query, data and indexes, DB2 and SQL Server can have very different performance when CTEs are involved.


text:
Q: Where to trap failed connection on WCF calling class? I'm trying to write a class that encapsulates WCF calls (the client is Silverlight, if it matters). It all works swimmingly, but I'm not sure how to trap a connection failure, as if the server won't respond. It would appear that bit of work happens somewhere in the resulting code from ChannelFactory, but I'm not sure. General code review is welcome also. :)
Bottom line, surrounding the creation of the channel, or the begin or async result delegate in try/catch doesn't trap a failed connection. I'd like to have that catch run the ServiceCallError event.
public class ServiceCaller : IDisposable
{
    private IFeedService _channel;

    public ServiceCaller()
    {
        var elements = new List<BindingElement>();
        elements.Add(new BinaryMessageEncodingBindingElement());
        elements.Add(new HttpTransportBindingElement());
        var binding = new CustomBinding(elements);
        var endpointAddress = new EndpointAddress(App.GetRootUrl() + "Feed.svc");
        _channel = new ChannelFactory<IFeedService>(binding, endpointAddress).CreateChannel();
    }

    public void MakeCall(DateTime lastTime, Dictionary<string, string> context)
    {
        AsyncCallback asyncCallBack = delegate(IAsyncResult result)
        {
            var items = ((IFeedService)result.AsyncState).EndGet(result);
            if (ItemsRetrieved != null)
                ItemsRetrieved(this, new ServiceCallerEventArgs(items));
        };
        _channel.BeginGet(lastTime, context, asyncCallBack, _channel);
    }

    public event ItemsRetrievedEventHandler ItemsRetrieved;
    public event ServiceCallErrorHandler ServiceCallError;

    public delegate void ItemsRetrievedEventHandler(object sender, ServiceCallerEventArgs e);

    public delegate void ServiceCallErrorHandler(object sender, ServiceCallErrorEventArgs e);

    public void Dispose()
    {
        _channel.Close();
        _channel.Dispose();
    }
}

Here's the stack trace, for those who are curious:
 An AsyncCallback threw an exception.
at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
   at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously, Exception exception)
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.OnGetResponse(IAsyncResult result)
   at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClassd.<InvokeGetResponseCallback>b__b(Object state2)
   at System.Threading._ThreadPoolWaitCallback.WaitCallback_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallbackInternal(_ThreadPoolWaitCallback tpWaitCallBack)
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback(Object state)

To make this happen, I fire up the app in the browser, then I kill the Web server process from Visual Studio. In a test environment, I get the same thing by killing the network connection for the client system.
Here's the FULL exception's ToString():
System.Exception: An AsyncCallback threw an exception. ---> System.Exception: An AsyncCallback threw an exception. ---> System.ServiceModel.CommunicationException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
   at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
   at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClass5.<EndGetResponse>b__4(Object sendState)
   at System.Net.Browser.AsyncHelper.<>c__DisplayClass2.<BeginOnUI>b__0(Object sendState)
   --- End of inner exception stack trace ---
   at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
   at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)
   --- End of inner exception stack trace ---
   at System.ServiceModel.Channels.Remoting.RealProxy.Invoke(Object[] args)
   at proxy_2.EndGet(IAsyncResult )
   at CoasterBuzz.Feed.Client.ServiceCaller.<MakeCall>b__0(IAsyncResult result)
   at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
   --- End of inner exception stack trace ---
   at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
   at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously, Exception exception)
   at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.CallComplete(Boolean completedSynchronously, Exception exception)
   at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.FinishSend(IAsyncResult result, Boolean completedSynchronously)
   at System.ServiceModel.Channels.ServiceChannel.SendAsyncResult.SendCallback(IAsyncResult result)
   at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
   --- End of inner exception stack trace ---
   at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously)
   at System.ServiceModel.AsyncResult.Complete(Boolean completedSynchronously, Exception exception)
   at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.OnGetResponse(IAsyncResult result)
   at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClassd.<InvokeGetResponseCallback>b__b(Object state2)
   at System.Threading._ThreadPoolWaitCallback.WaitCallback_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallbackInternal(_ThreadPoolWaitCallback tpWaitCallBack)
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback(Object state)

By the way, the only way I can catch this at all is to use app level UnhandledException event in the SL client.

A: Jeff, I'm not entirely certain from your question how you are simulating a connection failure.  I am assuming that "as if the server won't respond" means you are looking for some kind of timeout error.  You are probably simulating a non-responsive server by forcing a slow response from your service call using Thread.Sleep() on the server side.  Right?  Close enough?
I had a similar project, so I tested this out and was able to trap a timeout and other exceptions successfully.  I think perhaps you weren't seeing these exceptions because your custom binding had a very long default timeout and you may not have waited long enough.
To explain, WCF timeouts are controlled by the binding configuration.  Looking at your code, you are creating your own custom binding like this:
var elements = new List<BindingElement>();
elements.Add(new BinaryMessageEncodingBindingElement());
elements.Add(new HttpTransportBindingElement());
var binding = new CustomBinding(elements);

If you set a breakpoint there and inspect the custom binding you created, you will see it has a one minute SendTimeout by default.  I suspect you were either not waiting long enough or not setting your service's simulated timeout long enough, so you were not able to catch a timeout exception.
Here are some code changes to demonstrate.  First, to set the timeout on the binding:
var binding = new CustomBinding(elements);
//Set the timeout to something reasonable for your service
//This will fail very quickly
binding.SendTimeout = TimeSpan.FromSeconds(1);

Finally, to catch the exceptions and raise the correct events, you can update your AsyncCallback delegate as follows.  The exception is thrown when EndGet() is called.
AsyncCallback asyncCallBack = delegate(IAsyncResult result)
{
    IFeedService service = ((IFeedService)result.AsyncState);
    try
    {
        var items = service.EndGet(result);
        ItemsRetrieved(this, EventArgs.Empty);
    }
    catch (System.TimeoutException ex)
    {
        //Handles timeout
        ServiceCallError(this, EventArgs.Empty);
    }
    catch (System.ServiceModel.CommunicationException ex)
    {
        //Handles a number of failures:
        //  Lack of cross-domain policy on target site
        //  Exception thrown by a service
        ServiceCallError(this, EventArgs.Empty);
    }
    catch (System.Exception ex)
    {
        //Handles any other errors here
        ServiceCallError(this, EventArgs.Empty);
    }
};

As far as a general code review, I would recommend that you avoid hard-coding your binding configuration.  You can instead declare your endpoint configuration (including reasonable timeouts) in your ServiceReferences.ClientConfig file and new up your channel factory with the endpoint name like this:
new ChannelFactory<IFeedService>("feedServiceEndpoint");

That should make the app more maintainable over time.
I hope this helps.
Jerry
Updated:
Jeff,
Please take a look at this code and the comments within for more explanation of what is happening here.  The MakeCall() method is creating a function (delegate) that is being passed to the BeginGet() method.  That function is later executed when the service responds.
Please make the changes suggested and set breakpoints at the lines starting with "AsyncCallback asyncCallback" and "var items".  You will see the first pass through the debugger merely declares the code (function/delegate) to execute when the service responds and the second pass is the actual processing of that response, starting at the inside of your delegate declaration.  This means the outer try/catch will not be in scope when the response of the service call is processed.
public void MakeCall(DateTime lastTime, Dictionary<string, string> context)
{
    try
    {
        AsyncCallback asyncCallBack = delegate(IAsyncResult result)
        {
            try
            {
                var items = ((IFeedService)result.AsyncState).EndGet(result);
                if (ItemsRetrieved != null)
                    ItemsRetrieved(this, new ServiceCallerEventArgs(items));
            }
            catch (Exception ex)
            {
                //This will catch errors from the service call
            }
        };
        _channel.BeginGet(lastTime, context, asyncCallBack, _channel);
    }
    catch(Exception ex)
    {
        //This will not catch an error coming back from the service.  It will
        //catch only errors in the act of calling the service asynchronously.

        //The communication with the service and response is handled on a different
        //thread, so this try/catch will be out of scope when that executes.

        //So, at this point in the execution, you have declared a delegate
        //(actually an anonymous delegate the compiler will turn into a hidden class)
        //which describes some code that will be executed when the service responds.

        //You can see this in action by setting a breakpoint just inside the delegate
        //at the line starting with "var items".  It will not be hit until the service
        // responds (or doesn't respond in a timeout situation).
    }
}

Jerry

A: I've encountered a similar problem before. The main problem is with the way IDisposable is implemented on instances of your proxy/channel. The way I've solved it is shown in the code below, where IDirector is my service contract:
public class ProxyWrapper : IDisposable
{
    private IDirector proxy;
    private ChannelFactory<IDirector> factory;
    int callCount = 0;

    public ProxyWrapper()
    {
        factory = new ChannelFactory<IDirector>();

        proxy = factory.CreateChannel();
    }

    public IDirector Proxy
    {
        get
        {
            if (callCount > 0)
                throw new InvalidOperationException("The proxy can only be accessed once for every ProxyWrapper instance. You must create a new ProxyWrapper instance for each service request.");
            // only allow the proxy/channel to be used for one call.

            callCount++;
            return proxy;
        }
    }

    public void Dispose()
    {
        IClientChannel channel = (IClientChannel)proxy;

        try
        {
            if (channel.State != CommunicationState.Faulted)
            {
                channel.Close();
            }
            else
            {
                channel.Abort();
            }
        }
        catch (CommunicationException)
        {
            channel.Abort();
        }
        catch (TimeoutException)
        {
            channel.Abort();
        }
        catch (Exception)
        {
            channel.Abort();
            throw;
        }
        finally
        {
            channel = null;
            proxy = null;
        }
    }
}

The way to use the above class is as follows:
    public static void Login(string userName, string password)
    {
        using (ProxyWrapper wrapper = new ProxyWrapper())
        {
            currentSession = wrapper.Proxy.Login(userName, password);
        }
    }

Because the ProxyWrapper class implements IDisposable, if we use an instance of the ProxyWrapper class inside a using block, the Dispose() method is guaranteed to be called, even if an exception is thrown. The code in the Dispose() method will handle all cases and states of the proxy/channel. You can then add your error-handling / logging / event delegate code in this method.
Read the following blog entry for more info, and for a more generic version of the code above: http://bloggingabout.net/blogs/erwyn/archive/2006/12/09/WCF-Service-Proxy-Helper.aspx

A: To catch communications errors with the server, I'd suggest putting the call to .CreateChannel() into a try...catch and handle things like CommunicationException and TimeoutExceptions there.
Also, one nuggest of general advice: creating the ChannelFactory is quite an expensive operation, so you might want to do this separately and store that reference to the ChannelFactory object somewhere.
If you need to create and possibly re-create the channel from the ChannelFactory, you can then use that stored / cached instance of the ChannelFactory over and over again without having to create that all the time.
But other than that, I would think you're doing quite fine here!
Marc

A: Your ChannelFactory instance is going to be in the "Aborted" state when this timeout occurs.  You'll find that the exception is being thrown not when the exception happens in the call, but when you call _channel.Dispose().
You'll need to guard against this exception somehow.  The simplest way would be to put a try/catch around the contents of your dispose method, but it would be better if you checked the state of the _channel instance before trying to close/dispose.
This is why you are still getting the exception - it's not being handled here.
Update:
Based on your stack trace, it looks like the framework is trying to execute your callback delegate and is getting an exception there.  You responded elsewhere that try/catching the contents of your delegate doesn't solve the issue... what about inner exceptions?  What is the full output of TheException.ToString()?
I trolled through the .NET Framework and it is indeed allowed to travel all the way back to the threadpool (at least in the stacktrace you have here) which would cause an unhandled exception and your thread to die.  If worse comes to worse, you can always take over the threading... spin up your own thread and inside call the service synchronously, rather than using the builtin async pattern (unless this is a WCF Duplex type of communication, which I don't think it is).
I still think the full exception information (if there is anything more) might be useful.

A: Jeff, please show us your code when you try to put a try/catch block around the EndGet call. It's hard to believe that doesn't catch an exception, and seeing it will help me believe.
Also, as part of this experiment, get rid of the UnhandledException event handler. I think you're catching this exception as soon as the BrowserHttpRequest realizes there's a 404. I think that without the UnhandledException event, a try/catch around EndGet will catch the exception, if any. I think you're picking up an intermediate state of the exception handling process.
I'd also like to see you put a System.Debugger.Break or something immediately after the EndGet call.

A: Am I right in thinking that you have designed your ServiceCaller class so that you can call it in a using block?
If yes, then that's the problem. The WCF channel classes have been designed in such a way as to make it extremely difficult to write completely general disposing code that caters for all possible error conditions. If it were simple, then the channel classes themselves would be safe to dispose and you wouldn't need a wrapper class.
The only safe way I have found to date is to encapsulate not the dispose logic, but the entire call sequence, thus:
public static void Invoke<TContract>(ChannelFactory<TContract> factory, Action<TContract> action) where TContract : class {

    var proxy = (IClientChannel) factory.CreateChannel();
    bool success = false;
    try {
        action((TContract) proxy);
        proxy.Close();
        success = true;
    } finally {
        if(!success) {
            proxy.Abort();
        }
    }
}

I know that's a synchronous call, but the principle is the same. Instead of you trying to deduce whether you should call Close or Abort, you determine it in advance based on how far through the call you managed to get before it fell over.
Note - only the actual channel needs this special treatment. You can dispose of the factory any way you like AFAIK.

A: I think that the problem is in the way you have designed service caller.
The channel is opened when service caller is created. This means that the channel can timeout and there is nothing in your code that can recover from the timeount.
I would move the creation and closing of the channel to the make call method.
You can do a try catch around the begin get and around the contents of the callback.


text:
Q: SSL for 'pointed domains' I have a website a.example which has an SSL certificate through CloudFlare.
I also have a website b.example which is pointing to a.example via an A record in the DNS (it points to the IP address of a.example).
When I visit b.example, I also want HTTPS, can I get it to work with my certificiate from a.example?

A: No. Certificates are per domain. You need either 2 certificates, each one  with one name or a certificate with both names in it.
Otherwise if I replace in your question the two sites by Apple and Microsoft respectively, do you see the problem if the certificate for one can be used for the other?


text:
Q: Reach static files under application within website using IIS I have multiple ASP.NET apps deployed within the Default Web Site in IIS (8). Their virtual directories set up like: App1, App2, so I reach them as localhost/App1/... , localhost/App2/... , they work well.
I want to load a javascript file like below in the masterpage file in the header tag in one of my apps:
<script src="/Script/myfile.js" type="text/javascript"></script>

When I open the page, I get errors in the console as my files cannot be found, because it search for the file at localhost/Script/ instead of localhost/App1/Script/
Is there a way to set the root directory to be the app's root directory containing the virtual path to the app?
I don't want to hardcore the /App1 string to the begin of the js files path, because the app is deployed more times, with different Application names under different websites, and I have many js files too.
With the example below, I had also no success:
<script type="text/javascript" src="<%# Page.ResolveClientUrl("~/Script/myfile.js") %>"></script>

But if I changed the <%# %> tag to <%= %> , then it worked on some page, but anothers threw error:
"Only content controls are allowed directly in a content page that contains content controls". For this error, I found a solution to change the <%= %> to <%# %> , which not worked for me, it made my js files not working again on any page.
Any ideas?

A: I found that the solution using the code below works (it's in my masterpage's head tag):
<script type="text/javascript" src="<%# Page.ResolveClientUrl("~/Script/myfile.js") %>"></script>

But I need to put the code below into the masterpage's pageload method:
if(!IsPostBack)
        this.Page.DataBind();

Without this, the file won't be loaded, that's why it didn't work for me for the first time.
Hope it helps someone.


text:
Q: android double layout objects in compound view When you create a compound view and inflate an xml layout file for it like this:
public class CompundLayout extends LinearLayout{...}

this inflates an xml with root like this:
<LinearLayout ... />

you end up with a layout hierarchy with a LinearLayout inside a LinearLayout (or so I concluded when defining a tag string to the layout object in the xml cased my app to crash).
Am I wrong? is there a better way to do this and prevent this double layout?

A: There is a better way to avoid the double layout, alter your xml layout to replace the LinearLayout container with a "merge" container. Your xml layout will look something like this afterwards:
<merge xmlns:android="http://schemas.android.com/apk/res/android">
    <TextView ... />
    <EditText ... />
    ...
</merge>


text:
Q: How to add buttons to a ListBox? In my project, I'm adding a ListBox whose items are retrieved from a database. What I want to do is to add a button to the right of each item on the ListBox that, when pressed, deletes that item from the database and refreshes the ListBox.
Now, getting the button to do that will be easy (quite possibly a Click() event on the button), but my problem is that I can't find a way to actually add a button to the ListBox.
Does anyone know how to do this?
BTW this is in a VB desktop app project.

A: There's an article on the msdn about putting controls into DataGridViews. Check this out and see if it gets you any closer to what you want.
http://msdn.microsoft.com/en-us/library/7tas5c80.aspx

A: A DataGridView would be an easier solution, it already includes all the functionality you require. Simply add a text column and a button column, then you can subscribe to the Cell ContentClick event For example:
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
    'your database code here
    DataGridView1.Rows.RemoveAt(e.RowIndex)
End Sub


text:
Q: How to read boolean (true/false) of all functions in an array I'm having a hard time reading the return Boolean value of a number of functions I added to an array. I want to read it such that if any of the functions in the array reads false it returns false to the parent function.
Here's a sample of the code I'm running:
function validate(){
    var function1 = functionA();
    var function2 = functionB();
    var function3 = functionC();
    var function4 = functionD();
    var result = new Array;
    result.push(function1);
    result.push(function2);
    result.push(function3);
    result.push(function4);
    if (result.some(false)) {
        return false;
    } else {
        return true;
    }
}

I get the "false is not a function" error while debugging, Is there any work around that wont totally change this structure, if not lay whatever idea you have it would still be helpful. Thank you.

A: You should pass a function to some()

function validate(){
    var function1 = functionA();
    var function2 = functionB();
    var function3 = functionC();
    var function4 = functionD();
    var result = new Array;
    result.push(function1);
    result.push(function2);
    result.push(function3);
    result.push(function4);
    if (result.some(f => !f)) {
        return false;
    } else {
        return true;
    }
}
console.log(validate());
function functionA(){
  return true;
}
function functionB(){
  return false;
}
function functionC(){
  return true;
}
function functionD(){
  return true;
}

A: You could take the function references in an array and call them in the callback for checking.
function validate() {
    var conditionChecks = [functionA, functionB, functionC, functionD];
    return !conditionChecks.some(fn => fn());
}

A: Array.some() argument should be a function.
var array = [1, 2, 3, 4, 5];

var even = function(element) {
  // checks whether an element is even
  return element % 2 === 0;
};

console.log(array.some(even));
// expected output: true

Check out the docs:
https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Array/some

A: The issue is because some() is expecting a function, not a boolean. To fix this, provide a function to that method which interrogates each element of the array and returns your required value.
Also note that the logic can be made much more succinct:

function validate() {
  var result = [functionA(), functionB()];
  return !result.some(v => !v);
}

function functionA() {
  return true;
}

function functionB() {
  return false;
}

console.log(validate());

A: Array.some()

Expects a callback to evaluate your array, not a boolean.
If you provide it with a function like this:
function callback(el) {
  return el
}

And pass it instead of false, your example will work.

A: As the error states, some requires a function to evaluate.
function checkIfFalse(valToCheck){
    return valToCheck === false;
}

Use this function in your some call like this:
if (result.some(checkIfFalse)) {
        return false;
    } else {
        return true;
    }


text:
Q: controlling an element from inside of another element in css hello there I'm facing now a problem with controlling an element from inside of a different element .
for example if I want to control the appearance of an element inside of footer by hovering over another element in header .
i hope you have the answer and thanks in advance

A: One way to do this is, for example, if you have a li with a link inside and you want to change the color of the link when the li is hovered on, you could do this:

ul li:hover a {
  color: green;
}

/* only for presentation */
ul li {
  width: 100px;
  height: 50px;
  box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2);
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

    Link

if you wanted to affect totally random elements as you said, you can do this:

/* ----- This is all extra styling ----- */
body {
  background-color: #121212;
}

.header {
  position: fixed;
  background-color: rgb(31, 33, 34);
  width: 100%;
  color: white;
  font-family: arial;
  text-align: center;
}

.footer {
  position: absolute;
  top: 90%;
  background-color: rgb(31, 33, 34);
  width: 100%;
  color: white;
  font-family: arial;
  text-align: center;
}
/* ----- This is all extra styling ----- */

.header:hover + .footer {
  background-color: red;
}
<!DOCTYPE html>

My Website

Hover on the header to change my color


text:
Q: Dynamic Buttons are not triggering in aspx.cs page I have recently started making a mock webstore for an assignment and have unfortunately hit a road bump over a button. I have tried MULTIPLE ways to implement a button that would trigger a function via my server. However, I cannot get the button to trigger via the server side no matter how I implement a button. Below is my code for my aspx.cs page. Note the AddPanel() function is where I am trying to add each panel to my webpage with the corresponding css. If yall need the css as well I'm more than happy to provide it. Any help is appreciated. I also kept all the comment's of variations I have tried to get my button to work.
Homepage.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Homepage : System.Web.UI.Page
{
private List<Item> theItems;
protected void Page_Load(object sender, EventArgs e)
{
    if(theItems == null)
    {
        theItems = new List<Item>();
    }
    Item it = new Item("img/demo/1.jpg", "img/demo/thumb1.jpg", "Hard Drive 500GB", "Nothing but the highest quality of hard drives.", 600.50, "#1", 2);
    theItems.Add(it);
    it = new Item("img/demo/2.jpg", "img/demo/thumb2.jpg", "External Blu Ray", "You like blu ray? We can play Blu ray.", 200.00, "#2", 8);
    theItems.Add(it);
    it = new Item("img/demo/3.jpg", "img/demo/thumb3.jpg", "Fancy Phone", "Wanna call someone? You need a phone to do it!", 499.99, "#3", 2);
    theItems.Add(it);
    it = new Item("img/demo/4.jpg", "img/demo/thumb4.jpg", "Throwable Frisbee", "Who needs a laptop when you have a frisbee!", 2000.99, "#4", 2);
    theItems.Add(it);
    it = new Item("img/demo/5.jpg", "img/demo/thumb5.jpg", "Test Div", "This is a test div yo lets hope it works", 5.01, "#5", 5);
    theItems.Add(it);
    AddPanel();
}

//public void AddPanel(string imgSrc, string thmbSrc, string label, string description, string href, double price)
public void AddPanel()
{
    int count = 1;
    Button btn = new Button();
    foreach(Item item in theItems)
    {

        string btnID = "button" + count;
        btn.ID = btnID;
        btn.Text = "Add To Cart";
        btn.Click += new EventHandler(addToCart);

        string pane = @"

" + item.Label + "

" + item.Description + "
";
        pane += @"
Add to Cart

";
        //pane += @"
""

";
        //pane += @"
< asp:Button ID = """+btnID+@""" runat = ""server"" Text = ""Add To Cart"" />

";
        //pane += @"
<input type=""button"" id="""+ btnID + @""" runat=""server"" text=""Add To Cart"" onServerClick=""addToCart()""></button>

";
            //pane += @"
Add to Cart

";
            this.panes.InnerHtml += pane;
            string paneNav = @"
 " + item.Label + "" + "$" + item.Price + "
";
            this.innerPaneNav.InnerHtml += paneNav;
            count++;
        }

    }

    public void addToCart(object sender, EventArgs e)
    {
        string s;
    s = "It worked!"; // this is where I have a breakpoint to see if the     code was triggered
    }
}

A: If you create the button by c# code behind, You can not add this by html Codes! To adding button created to the panel you need to add this:
btn.Click += new EventHandler(addToCart); // your code
pane.Controls.Add(btn); //adding created button to server side control (pane)


text:
Q: On the difficulty of the new mathematics GRE exam I have read a lot of various threads on both this website and other website claiming that the GRE mathematics exam has become exceedingly difficult over the years. For example, the document available at the link goes as far as to claim that the official practice tests available are next to useless.
However, I have been unable to find any resource that concretely substantiates this claim. Therefore, I'm hoping students who have taken the exam in the recent past could comment/answer on this post to explain their experience with the exam, and how the exam has become difficult in terms of content, difficulty of questions etc. Moreover, I think it would be great if someone could gives examples of various questions that have appeared in the recent past to substantiate the claim. I suppose discussing exam questions from a test administered months ago isn't against any rules.
This way, I suppose, students who wish to take the exam in the near future will be able to better prepare for the exam.

A: It seems like they asked a lot of single variable calculus stuff. It was pretty challenging.  I was a TA in 1991 when I took it for the third time and my score finally went up from the 64% to the 88%.  I was probably teaching alot of first year calculus and, as a friend so winsomely put it,  "it gets cherry when you teach it"...  I was going for the NSF fellowship.   Still not good enough to get it... I didn't really need the fellowship, I had a TAship.  I didn't get my phd.   Didn't write my thesis...
I really don't know about other years. ..


text:
Q: Replace string at particular position in function In PHP? I want to Print some dynamically data from my function to passing string in function like this.
My Function
function mysql_funX_Repeter($query,$itemtemplet)
{
    $this->mysql_funX_connect();

    $result = mysql_query($query) or die("Repeter Query Error.");
    if (!$result)
    {
        $message = 'ERROR:' . mysql_error();
        return $message;
    }
    else
    {
        $newtempelt = str_replace("Eval", '$row', $itemtemplet);
        while ($row = mysql_fetch_array($result))
        {

            echo $newtempelt;
        }
    }
}

Passing Value In Function

<?php
$rptvalue="
Eval['name']
";
$myFun->mysql_funX_Repeter("Select name from tbldemo",$rptvalue);
?>

My Output

*

*$row['name']

*$row['name']

*$row['name']

I want Output

*

*raj

*ram

*prince
But it's Show me only variable but not show it's database value.
How to solve this...!!!

A: I would change a little bit your method.
function mysql_funX_Repeter($query,$itemtemplet)
{
    $this->mysql_funX_connect();

    $result = mysql_query($query) or die("Repeter Query Error.");
    if (!$result)
    {
        $message = 'ERROR:' . mysql_error();
        return $message;
    }
    else
    {
        while ($row = mysql_fetch_array($result))
        {

            echo "
".$row[$itemtemplet]."
";
        }
    }
}

And of course, your method invokation:

<?php
$rptvalue="name";
$myFun->mysql_funX_Repeter("Select ".$rptvalue." from tbldemo",$rptvalue);
?>

And that's how I'd do it to avoid nasty evals. :)

A: function mysql_funX_Repeter($query,$itemtemplet)
 {
  $html='';
  $this->mysql_funX_connect();
  $result = mysql_query($query) or die("Repeter Query Error.");
  $num_rows=mysql_num_rows($result);
  if($num_rows){
    while ($row = mysql_fetch_array($result))
    {
        $newtempelt = str_replace("Eval", $row['column_name'], $itemtemplet);
        $html.="
".$newtempelt."
";
    }
  }
  return $html;
}

//calling method mysql_funX_Repeter

<?php
$rptvalue="name";
echo $myFun->mysql_funX_Repeter("Select ".$rptvalue." from tbldemo",$rptvalue);
?>

A: Developer My Problem Was Solved.
Thanks for Reply.
My Function
//This Repeter Function Created By Priyank Patel
function mysql_funX_Repeter($query,$itemtemplet)
{
    $this->mysql_funX_connect();

    $result = mysql_query($query) or die("Repeter Query Error.");
    if (!$result)
    {
        $message = 'ERROR:' . mysql_error();
        return $message;
    }
    else
    {
        preg_match_all('/{([^}]*)}/', $itemtemplet, $matches);
        $select = '';
        while($row = mysql_fetch_assoc($result)){
            $aux = $itemtemplet;

            for($i = 0; $i < count($matches[0]); $i++){
                $aux = str_replace($matches[0][$i], $row[$matches[1][$i]],$aux);
            }
            $select .= $aux."\n";
        }
        mysql_close();
        return $select;
    }
}

Calling Style

<?php $templet="
{name}
";echo $myFun->mysql_funX_Repeter("Select * from tbldemo",$templet);?>


text:
Q: Client side logging for javascript web applications that extends console.log() I have been searching the internet for a clean solution regarding client side logging for a javascript apps and have not come across an obvious choice.
My code is written with console.log(). I was hoping to find a javascript plugin that over-rides console.log(), such that i dont need to change my code, and also extends it so I can do things like programatically get the last 10 log lines to show the user?
Should I just over-ride console.log() in my application so that apart from printing to the console, it saves the logs to a global array?
I am writing mobile web apps.

A: Yes. You can just override console.log function. Simple example:
var logs = [];
console.log = function(value) {
    logs.push(value);
}

And to access all parameters given to function you can use arguments object.


text:
Q: Why does Qt VS Tools throw exception "Illegal characters in path" when trying to add a Qt version to Visual Studio 2019? I've installed a couple versions of Qt compatible with VS2019 along with newest Qt Creator, and Qt VS Tools extension, so I could use IDE I'm comfortable with. But I can't add any Qt version into VS Tools, it just outputs:
--- qmake(7068): started D:\PROGRAMY\QT\6.3.0\MSVC2019_64\bin\qmake.exe
--- qmake: Querying persistent properties
--- qmake(7068): exit code 0 (67 msecs)

vcvars: D:\Programy\Visual_Studio_2019\VC\Auxiliary\Build\vcvars64.bat
Exception "Illegal characters in path.":
   at System.IO.Path.CheckInvalidPathChars(String path, Boolean checkAdditional)
   at System.IO.Path.Combine(String path1, String path2)
   at QtVsTools.Core.HelperFunctions.<>c.<SetVCVars>b__77_1(String path)
   at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
   at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
   at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
   at QtVsTools.Core.HelperFunctions.SetVCVars(VersionInformation VersionInfo, ProcessStartInfo startInfo)
   at QtVsTools.Core.QMake.Run(Boolean setVCVars)
Error reading VS project settings

Stacktrace:
   at QtVsTools.Core.VersionInformation..ctor(String qtDirIn)
   at QtVsTools.Core.VersionInformation.Get(String qtDir)
   at QtVsTools.Options.QtVersionsPage.SaveSettingsToStorage() in C:\dev\source\qtlabs\vstools\QtVsTools.Package\Options\QtVersionsPage.cs:line 93

I'm new to Qt, but I've googled a bit and found that Qt doesn't like spaces in filepaths. But I have no idea which filepath could it be.
My Qt qmake Executable location is D:\Programy\Qt\6.3.0\msvc2019_64\bin
vcvars64.bat location: D:\Programy\Visual_Studio_2019\VC\Auxiliary\Build
Visual compiler: D:\Programy\Visual_Studio_2019\VC\Tools\MSVC\14.29.30133\bin\Hostx64\x64
Qt debugger: C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\cdb.exe
Qt CMake: D:\Programy\Qt\Tools\CMake_64\bin\cmake.exe


text:
Q: Using Menu key as modifier in X I would like my Menu key (keycode 135) to act both as the regular context menu key when pressed alone, and also to have it emulate my XF86Audio* multimedia keys when used as a modifier, e.g. Menu+PgUp would emulate XF86AudioRaiseVolume.
I would be fine with setting the key combinations in KDE's Global Shortcuts instead of having them apply to all of X, but I'm not sure how to achieve either.

A: Components needed: xmodmap, xcape, xbindkeys.
xmodmap -e "keycode 135 = Hyper_R"
xmodmap -e "add mod3 = Hyper_R"
xmodmap -e "keycode any = Menu" # this is needed for xcape
xcape -e "Hyper_R=Menu" # for single key press on menu key

~/.xbindkeysrc:
# map Menu+Pause as Mute
"xdotool keyup Hyper_R keyup Pause key --clearmodifiers XF86AudioMute keydown Hyper_R key Control"
    Mod3 + Pause

# map Menu+PgUp as Volume+

"xdotool keyup Hyper_R keyup Prior key --clearmodifiers XF86AudioMute keydown Hyper_R key Control"
    Mod3 + Prior

# etc.

The reason for such complicated xdotool call is:

*

*keyup Hyper_R keyup Pause - keys needs to be cleared, otherwise XF86AudioMute is sent while they're pressed and is not recognized as lone keypress

*keydown Hyper_R - so that the combination key (Pause in this case) can be pressed several times, useful for XF86AudioRaiseVolume for example

*key Control - so that xcape doesn't detect fake keydown Hyper_R and subsequent real key release, to avoid triggering Menu function

xdotools calls can be externed to some bash script, like:
#!/bin/bash

case "$1" in
"up")
    KEY="XF86AudioRaiseVolume"
    SHORT="Prior"
    ;;
"down")
    KEY="XF86AudioLowerVolume"
    SHORT="Next"
    ;;
"mute")
    KEY="XF86AudioMute"
    SHORT="Pause"
    ;;
"next")
    KEY="XF86AudioNext"
    SHORT="End"
    ;;
"prev")
    KEY="XF86AudioPrev"
    SHORT="Delete"
    ;;
"playpause")
    KEY="XF86AudioPlay"
    SHORT="Insert"
    ;;
"stop")
    KEY="XF86AudioStop"
    SHORT="Home"
    ;;
esac

xdotool keyup Hyper_R keyup $SHORT key $KEY keydown Hyper_R key Control


text:
Q: Nginx regex rule for caching images override the root location block My nginx setup contains the following location rules:
    location ~*  \.(jpg|jpeg|png|gif|ico|css|js|pdf)$ {
        expires 7d;
    }

    location /data/ {
            root /mnt/data;
    }

The problem is, when I try to access one of the following files (jpg | jpeg | png | gif | ico | css | js | pdf) in the /data/ folder I get 404 Not Found error, cause the first location rule overrides the second. I tried to do something like this:
    location ~* /data/.*\.jpg$ {
            root /mnt/data;
            expires 7d;
    }

But this doesn't seems to work. Could you please help me what solutions are available for me in this case?

A: Solutions are:
#1 Rule duplication
location ~*  \.(jpg|jpeg|png|gif|ico|css|js|pdf)$ {
    expires 7d;
}

location /data/ {
    root /mnt/data;

    location ~*  \.(jpg|jpeg|png|gif|ico|css|js|pdf)$ {
        expires 7d;
    }
}

#2 Symlink
You can create a symlink: $document_root/data -> /mnt/data.


text:
Q: How to pass flags to mobile Chrome using Selenoid Docker images I am trying to have Chrome launch without the "Welcome to Chrome" screen and can't seem to figure out the correct way to do so using Selenoid with the provided Android Docker images.
I used the automate_android.sh to create the container image and followed all the prompts, deviating from the default only when asked for version numbers and when it asked if I wanted to install Chrome.
Chrome will load but regardless of what I put in my test, I can't seem to get it to bypass the welcome screen.
Currently my config looks like this:
const merge = require('deepmerge');
const wdioConf = require('./wdio.conf.js');

exports.config = merge(wdioConf.config, {
  capabilities: [
        {
            version: '8.1',
            browserName: 'android',
            chromedriverArgs: {
              args: [ '--disable-fre', '--no-default-browser-check', '--no-first-run' ],
            },
            "selenoid:options" :
            {
              skin: "WVGA854",
              enableVNC: true,
              enableLog: true
            }
        }
    ]
}, {clone: false});

I have tried changing chromedriverArgs to "goog:chromeOptions" and chromeOptions.  Ive tried moving all three combinations inside the "selenoid:options" as well.
I suspect I am just doing something wrong but would appreciate any assist anyone can provide.
Versions
Selenoid: 1.9.1
Android: 8.1 and 8.0
WebdriverIO: 5.4.19
Docker: 18.09.2, build 6247962

A: You have to use chrome as browserName. This is how Appium works.


text:
Q: Let $X_{n}$, $n \geq 0$, be the two-state Markov chain. Find a) $P_0(T_0=n)$
b) $P_0(T_1=n)$

In class my we were learning about hitting times. $$T_a; \text{stands for the first time we hit state}\ \textit{"a"} \\\\
T_a=min\{n\ |n>0\ \text{and} \ X_n=a\}$$ My professor defined $$P_0(T_0=n)=P(T_0=n|X_0=0)$$ where we
  as hitting state zero in n-steps, $n\geq 0$.  For a 2-state Markov chain we know, $$P(0,0)=1-p\
> \ \ P(0,1)=p\ \ \ P(1,1)=1-q\ \ \ P(1,0)=q$$ so I let n=4 and found
  each probability to see if there was a pattern that I could show for
  the general case, but I think this approach is wrong. I would like
  help and/or hints with both parts, if that's not to much trouble.

A: there are two states, 0 and 1. you start at 0 and don't end up there again until move $n$. From markovianity, the answer is
$$
\pi(0) \cdot  P(0,1) \cdot  \underbrace{  P(1,1)  \cdots P(1,1)}_{n-2}  \cdot P(1,0)
$$


text: Q: Leaflet autoPan not panning enough vertically I have popups on markers activating successfully and autoPan is set to true by default. The map is panning successfully horizontally to ensure a popup is visible when the marker is close to the edge of the map. It is panning vertically (down), but not enough. Its like it thinks the map is taller than it is. Or thinks more of the map is visible than actually is. The result is the popup is not fully visible. I could pad the pan, but I would like to figure why its not panning enough by itself. Thanks.


text:
Q: How to return to the previous statement after catching an error instead of restarting the whole program in Java? I recently started learning Java as I have a keen interest in programming. I am currently creating an application that calculates a person's BMI.
Question: Is there a way to return to the previous statement when the user has made a mistake on instead of restarting the whole program (EG: when the line Please enter your weight in pounds executed, the user input a non-integer value and an error prompts out saying Invalid Input, it will then return to the previous line that the user made an error -> Please enter your weight in pounds executed).
If yes, how so?
import java.util.Scanner;
import java.text.DecimalFormat;

public class Body_Mass_Calculation {
    private static int gender, inputAnswer;
    private static boolean wenttocatch;
    private static double myBMI, heightInch, weightPound, weightKilo, heightMeter;
    private static Scanner input_1 = new Scanner(System.in);
    private static DecimalFormat df2 = new DecimalFormat("#.##");

    //Questions + Calculation
    static void myMethod() {
        try {
            System.out.println("Please enter gender. 1-- Male  2--Female");

            gender = input_1.nextInt();

            while (gender > 2 || gender < 1) {
                System.out.println("Invalid input!");
                System.out.println("Please enter gender. 1-- Male  2--Female");

                gender = input_1.nextInt();
            }

            if (gender == 1 || gender == 2) {
                System.out.println("Please enter your height in inches. ");
                heightInch = input_1.nextInt();

                System.out.println("Please enter your weight in pounds. ");
                weightPound = input_1.nextInt();

                heightMeter = heightInch * 0.0254;
                weightKilo = weightPound * 0.45359237;
                myBMI = weightKilo / (heightMeter * heightMeter);
            }
            if (gender == 1) {
                if (myBMI >= 27.8)
                    System.out.println("Your body-mass-index is " + df2.format(myBMI) + " this is considered high ! \n \n");
                else
                    System.out.println("Your body-mass-index is " + df2.format(myBMI) + " this is not considered high ! \n \n");
            }

            if (gender == 2) {
                if (myBMI >= 27.3)
                    System.out.println("Your body-mass-index is " + df2.format(myBMI) + " this is considered high ! \n \n");
                else
                    System.out.println("Your body-mass-index is " + df2.format(myBMI) + " this is not considered high! \n \n");
            }

            System.out.println("Do you wish to continue? Enter: 1 -> Yes,  2 -> No.");
            inputAnswer = input_1.nextInt();

            System.out.println("Invalid Input !");

            if (inputAnswer == 2) {           //If input = 2, Program executes line below
                System.out.println("Thank You for using this shitty app !");
                System.exit(2);
            } else if (inputAnswer == 1) {
                myMethod();

            }

        } catch
        (Exception e) {
            input_1.next();
            wenttocatch = true;
            System.out.println("Invalid input !");
            input_1.nextLine();
            myMethod();
        }
    }

    public static void main(String[] args) {
        //Executes Function/Method
        System.out.println("Welcome   ! \n ");
        myMethod();
    }
}

A: No, you can't. The solution is to write a method that takes care of it. Instead of writing a ton of code and repeating yourself, you use a method to encapsulate some functionality, so that you can invoke it a lot without copying code. For example, instead of:
System.out.println("Please enter gender. 1-- Male  2--Female");
gender = input_1.nextInt();
while (gender > 2 || gender < 1) {
    System.out.println("Invalid input!");
    gender = input_1.nextInt();
}

you really just want to write something like:
gender = askInt("Please enter gender. 1-- Male  2-- Female", 1, 2);

where the askInt is a method you write which takes the text you want to show as prompt, along with the smallest and largest valid value.
Now that you have this function, you can expand its functionalities and all the code that uses this function gets the functionality automatically. So, if you add 'catch invalid input exceptions and re-ask' functionality to this one method, ALL the questions get it.
int askInt(String prompt, int min, int max) {
    int result;
    while (true) {
        System.out.println(prompt);
        result = input.nextInt();
        if (result >= min && result <= max) return result;
        System.out.println("Invalid input!");
    }
}

This basic loop will keep looping until the if clause is triggered, causing the method to return, which is the only way out. You can now add handling for NumberFormatException within this one method, within the while loop. You can't go back to the line that caused the problem, but you can go forward, and in a while loop, going forward automatically jumps back to the start (i.e., that's how to go 'backwards'). So, we mix a while loop (which can go backwards) and a catch block, and that's how to solve the problem. And then we put all this in a method, so that we can write this code only once, instead of having to repeat it every time.

A: You can do it by using a do { _code1 } while (_condition) which execute the _code until _condition is false.
And _code1 is a try {}catch which will catch any exception (error) thrown from inside the try {} block.Here the exception (error) is thrown if the user enters a character instead of a digit.
System.out.println("Please enter gender. 1-- Male  2--Female");

int gender = 0 ;
do {
    try {
        if (gender == -1) {
            System.out.println("Invalid input!");
            System.out.println("Please enter gender. 1-- Male  2--Female");
        }

        gender = input_1.nextInt () ;

    }catch (Exception e){
        gender = -1 ;
    }

}while (gender > 2 || gender < 1);


text:
Q: When is $(X, \mathcal{T}_{trivial})$ Hausdorff?
When is $(X, \mathcal{T}_{trivial})$ Hausdorff?

Recall: $\mathcal{T}_{trivial} = \{\varnothing, X\}$
I want to say that this space is Hausdorff is $X$ is a singleton
But I can't actually produce two open sets that satisfy the condition:

$\forall x,y \in X$, there exists disjoint $U, V \in
\mathcal{T}_{trivial}$ such that $x \in U$ and $y \in V$

Suppose $X = \{x\}$, then yes we have a $x \in U = \{x\}$, but do we have $y \in \varnothing$, since $\varnothing$ is empty?, or is the condition trivially satisified since there is only one point?

A: I think the question is easier to solve if we write the negative of the statement:

A topological space $(X,\mathcal T)$ is not Hausdorff if $\exists x,y\in X$ with $x\neq y\,$ s.t. $\forall U,V\in\mathcal T$ with  $x\in U$ and $y\in V$ then $U\cap V\neq\emptyset$

Alternatively we can write:

A topological space $(X,\mathcal T)$ is Hausdorff if $\nexists x,y\in X$ with $x\neq y\,$ s.t. $\forall U,V\in\mathcal T$ with  $x\in U$ and $y\in V$ then $U\cap V\neq\emptyset$

A: There are no pairs of distinct points $x$ and $y$ to test the Hausdorff hypothesis on. This makes the statement voidly true:
Hausdorffness of the space $(X,\mathscr{T})$ means (put formally):
$$\forall x\in X \forall y \in Y: (x \neq y) \rightarrow (\exists U \in \mathscr{T} \exists V \in \mathscr{T} : (U \cap V = \emptyset) \land (x \in U) \land (y \in V))$$
The implication is true because the antecedent $x \neq y$ is always false (and false implies anything is true).