text:
Q: Sys.WebForms.PageRequestManagerParserErrorException The Following code on test.ascx.cs file (Web User Control)
protected void lnkOrderDetail_Command(object sender, CommandEventArgs e)
    {
      Telerik.Web.UI.GridDataItem item = gvAllDocuments.Items[int.Parse(e.CommandArgument.ToString())];
                string FileName = item["documentFileName"].Text;
                string PathString = @"C:\Documents\";
                string SubPath = PathString + Utils.GetUserName() + "\\" + FileName;
                FileInfo FileInfo1 = new FileInfo(SubPath);

                Response.ClearContent();
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName + "");
                Response.ContentType = "text/HTML";
                Response.AddHeader("Content-Length", FileInfo1.Length.ToString());

                Response.TransmitFile(SubPath);
                Response.End();
}

<asp:UpdatePanel ID="UpdatePanelDocuments" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:Button ID="ViewDocumentsButton" runat="server" Text="View/Upload Documents" OnClick="ViewDocumentsButton_Click" />

        <asp:PlaceHolder ID="UploadPlaceHolder" runat="server" Visible="false">

            <asp:Label Text="Document Type  :" runat="server" ID="DocuemntLabel"></asp:Label>

            <asp:Label Text="File :" runat="server" ID="FileLabel"></asp:Label>
           <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:RegularExpressionValidator ID="uplValidator" runat="server" ControlToValidate="FileUpload1"
                ErrorMessage=".png, jpg & pdf formats are allowed"
                ValidationExpression="(.+\.([Pp][Nn][Gg])|.+\.([Jj][Pp][Gg])|.+\.([Pp][Dd][Ff]))"></asp:RegularExpressionValidator>
            <asp:CustomValidator ID="customValidatorUpload" runat="server" ErrorMessage="" ControlToValidate="FileUpload1" ClientValidationFunction="setUploadButtonState();" />

            <asp:Button ID="btnUpload" runat="server" Text="Upload file" OnClick="Upload" Enabled="false" />
</asp:Label>

            <telerik:RadGrid ID="gvAllDocuments" runat="server" AutoGenerateColumns="false"
                AllowFilteringByColumn="true" RegisterWithScriptManager="true"
                AllowPaging="true" PageSize="10">
                <GroupingSettings CaseSensitive="false" />
                <MasterTableView CommandItemSettings-ShowExportToExcelButton="false" CommandItemSettings-ShowRefreshButton="false" CommandItemSettings-ShowAddNewRecordButton="false" CommandItemDisplay="Top">
                    <Columns>

                        <telerik:GridBoundColumn DataField="fileType" HeaderText="File Type" Visible="false"></telerik:GridBoundColumn>
                        <telerik:GridTemplateColumn>
                            <ItemTemplate>
                                <asp:Button ID="lnkOrderDetail" runat="server" Text="View" CommandArgument='<%#Container.ItemIndex%>' OnCommand="lnkOrderDetail_Command"></asp:Button>
                            </ItemTemplate>
                        </telerik:GridTemplateColumn>
                    </Columns>
                </MasterTableView>
                <ClientSettings>
                    <Resizing AllowResizeToFit="true" />
                </ClientSettings>
            </telerik:RadGrid>
        </asp:PlaceHolder>
    </ContentTemplate>
     <Triggers>
                <asp:PostBackTrigger ControlID="btnUpload" />
            </Triggers>

</asp:UpdatePanel>

TransmitFile did not do anything ?!
I get the following error on web-console

Error: Sys.WebForms.PageRequestManagerParserErrorException: The
  message received from the server could not be parsed. Common causes
  for this error are when the response is modified by calls to
  Response.Write(), response filters, HttpModules, or server trace is
  enabled.
Details: Error parsing near '����N\Exif

A: this working fine for me because the button is include Telerik grid
I add the following :
<Triggers>
             <asp:PostBackTrigger ControlID="gvAllDocuments" />
  </Triggers>


text:
Q: Передача имени ссылки в php файл Имеется множество ссылок вида
name1
name2
name3
name4
.....

Эти ссылки являются столбцом таблицы и ведут на один и тот же файл, который является особой формой.
Мне нужно в файле на который они ведут (nameofFile.php) получить имя ссылки (допустим name1), на которую нажал пользовать при переходе, чтобы вывести данные по этому названию (name1). Подскажите, пожалуйста, как это реализовать. С js особо не знаком
Вывод данных ссылок:
for ($i = 0; $i < $fields=count($row); $i++) {
            if($i==0){
                echo '' . $row[$i] . '	';
            }
            else{
                echo '' . $row[$i] . '	';
            }
        }

A: Получить "имя ссылки" напрямую в том виде, в каком говорите вы - невозможно (без JS по крайней мере). Но ничего не мешает добавить к ссылкам еще один параметр и передавать через него name:
for ($i = 0; $i < $fields=count($row); $i++) {
    if($i==0){
        echo '' . $row[$i] . '	';
    } echo {
        '' . $row[$i] . '	';
    }
}

А в nameOfFile.php получаете этот параметр таким образом
$name = urldecode($_GET['name']);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find IL instruction by address from exception stacktrace I have an exception stacktrace from xamarin-android release build. There no filenames and line numbers:

System.NullReferenceException: Object reference not set to an instance
  of an object
      at Test.Foo (Test.Bar bar) <0x995f8000 + 0x00248> in  <filename unknown>:0
      at ...

Is it possible to find IL code by address (0x995f8000 + 0x00248) in DLL that triggers this exception?


text:
Q: Expected single matching bean but found 3: objectMapper,halObjectMapper,_halObjectMapper in junitTest I'm having a problem with my testing. I'm using java spring and trying to run junit test to check if my server is alive.
This the test I'm trying:
  @RunWith(SpringJUnit4ClassRunner::class)
  @ContextConfiguration(classes = arrayOf(ServiceContext::class,DatabaseContext::class))
@Transactional
open class newtest : AbstractTestController(){

 @Test
fun echoTest() {
    mockMvc.perform(get("/echo").contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk)
  }
}

This is the AbstractTestController class that my newtest class is extending:
@WebAppConfiguration
abstract class AbstractTestController : DatabaseInitializedTest() {

 @Autowired
lateinit var webAppContext: WebApplicationContext

 lateinit var mockMvc: MockMvc

@Autowired
lateinit var authHelper: OAuthHelper

@Autowired
private lateinit var userService: UserService

fun adminToken(username: String) = authHelper.addBearerToken(userService.getUserByUsername(username), *AuthoritiesService.adminAuthorities.toTypedArray())

fun clientItToken(username: String) = authHelper.addBearerToken(userService.getUserByUsername(username), *AuthoritiesService.clientItAuthorities.toTypedArray())
fun clientManagerToken(username: String) = authHelper.addBearerToken(userService.getUserByUsername(username), *AuthoritiesService.clientManagerAuthorities.toTypedArray())

 fun endUserToken(username: String) = authHelper.addBearerToken(userService.getUserByUsername(username), *AuthoritiesService.endUserAuthorities.toTypedArray())

@Autowired
lateinit var mapper: ObjectMapper

 fun <T> ResultActions.and200ReturnClass(clazz: TypeReference<T>): ResultActions {
if (this.andReturn().response.status == HttpServletResponse.SC_OK
    && this.andReturn().response.contentAsString.isNotEmpty()) {
  mapper.readValue<T>(this.andReturn().response.contentAsString, clazz)!!
  }
return this
}

 @Before
fun initialize() {
mockMvc = MockMvcBuilders
    .webAppContextSetup(webAppContext)
    .apply<DefaultMockMvcBuilder>(SecurityMockMvcConfigurers.springSecurity())
    .alwaysDo<DefaultMockMvcBuilder>(MockMvcResultHandlers.print())
    .build()
   }
}

My configuration:
   @Configuration
  @Import(value = *arrayOf(
    OAuth2ServerConfiguration::class,
    OAuth2ServerConfiguration.AuthorizationServerConfiguration::class,
    OAuth2ServerConfiguration.ResourceServerConfiguration::class,
    SecurityConfig::class,
    OAuthHelper::class,
    WebConfig::class,
    DatabaseInitializator::class,
    LowerCaser::class))

 @ComponentScan("com.hyg","com.hyg.service", "com.hyg.web", "com.hyg.utils")
 @EnableAutoConfiguration
 @EnableAspectJAutoProxy(proxyTargetClass = true)
 open class ServiceContext

@Configuration
@EnableJpaRepositories("com.hyg")
@EnableTransactionManagement
@EnableAutoConfiguration
@PropertySource("classpath:application.properties")
open class DatabaseContext {

 val DATA_PACKAGE = "com.hyg.data"
 val INTERCEPTOR_KEY = "hibernate.ejb.interceptor"

 @Value("\${spring.datasource.username:${Const.NONE}}")
 lateinit var username: String

 @Value("\${spring.datasource.url}")
 lateinit var url: String

 @Value("\${spring.datasource.driverClassName}")
 lateinit var driverClass: String

  @Value("\${spring.datasource.password}")
  lateinit var password: String

 @Bean
 @Primary
 open fun objectMapper(): ObjectMapper {
 val mapper = ObjectMapper()
 mapper.registerModule(KotlinModule())
 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true)
 mapper.configure(MapperFeature.USE_STD_BEAN_NAMING, true)
 mapper.configure(DeserializationFeature.ACCEPT_FLOAT_AS_INT, false)
 mapper.registerModule(JavaTimeModule())

 mapper.registerModule(localDateTimeSerializer())
 return mapper
   }

@Bean
open fun localDateTimeSerializer(): SimpleModule {
val localDateTimeSerializer = SimpleModule()
val serializer = LocalDateTimeSerializer(
        DateTimeFormatter.ofPattern(Const.DATE_TIME_PATTERN))

val deserializer = LocalDateTimeDeserializer(
        DateTimeFormatter.ofPattern(Const.DATE_TIME_PATTERN))

localDateTimeSerializer.addSerializer(LocalDateTime::class.java, serializer)
localDateTimeSerializer.addDeserializer(LocalDateTime::class.java, deserializer)

return localDateTimeSerializer
 }

 @Bean
 open fun dataSource(): DataSource {

  val ds =  DataSourceBuilder.create().driverClassName(driverClass).username(username).password(password).url(url).build()
val proxy = ProxyDataSource()
proxy.setDataSource(ds)
proxy.setListener(DataSourceQueryCountListener())
return proxy
 }

 @Bean
  open fun entityManagerFactory(
      factory: EntityManagerFactoryBuilder, dataSource: DataSource,
      properties: JpaProperties): LocalContainerEntityManagerFactoryBean {
val jpaProperties = HashMap<String, Any>()
jpaProperties.putAll(properties.getHibernateProperties(dataSource))
jpaProperties.put(INTERCEPTOR_KEY, hibernateInterceptor())
return factory.dataSource(dataSource).packages(DATA_PACKAGE)
        .properties(jpaProperties as MutableMap<String, *>)
        .build()
   }

 @Bean
open fun hibernateInterceptor(): HibernateStatisticsInterceptor {
  return HibernateStatisticsInterceptor()
}

@Bean
open fun requestStatisticsInterceptor(): RequestStatisticsInterceptor {
  return RequestStatisticsInterceptor()
   }
 }

This is the full Error I'm getting:
   2017-11-17 20:03:52.477  WARN   --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration$$EnhancerBySpringCGLIB$$ecfe2bfa]: Constructor threw exception; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.fasterxml.jackson.databind.ObjectMapper' available: expected single matching bean but found 3: objectMapper,halObjectMapper,_halObjectMapper
 2017-11-17 20:03:52.477  INFO   --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown
2017-11-17 20:03:52.499  INFO   --- [           main] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2017-11-17 20:03:52.508 ERROR   --- [           main] o.s.test.context.TestContextManager      : Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener@6b19b79] to prepare test instance [com.hyginex.Integration.newtest@7a08da83]

java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
 Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration$$EnhancerBySpringCGLIB$$ecfe2bfa]: Constructor threw exception; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.fasterxml.jackson.databind.ObjectMapper' available: expected single matching bean but found 3: objectMapper,halObjectMapper,_halObjectMapper
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:279)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1154)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1056)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.test.context.web.AbstractGenericWebContextLoader.loadContext(AbstractGenericWebContextLoader.java:134)
at org.springframework.test.context.web.AbstractGenericWebContextLoader.loadContext(AbstractGenericWebContextLoader.java:61)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:251)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 24 common frames omitted
 Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration$$EnhancerBySpringCGLIB$$ecfe2bfa]: Constructor threw exception; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.fasterxml.jackson.databind.ObjectMapper' available: expected single matching bean but found 3: objectMapper,halObjectMapper,_halObjectMapper
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:122)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:271)
... 41 common frames omitted
 Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.fasterxml.jackson.databind.ObjectMapper' available: expected single matching bean but found 3: objectMapper,halObjectMapper,_halObjectMapper
at org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:172)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1114)
at org.springframework.beans.factory.support.DefaultListableBeanFactory$DependencyObjectProvider.getIfAvailable(DefaultListableBeanFactory.java:1643)
at org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration.<init>(EndpointMBeanExportAutoConfiguration.java:63)
at org.springframework.boot.actuate.autoconfigure.EndpointMBeanExportAutoConfiguration$$EnhancerBySpringCGLIB$$ecfe2bfa.<init>(<generated>)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
... 43 common frames omitted

Hope it will help to solve my problem.
I tried so far to put @Primary on the Bean that make the ObjectMapper or to add those annotation @Order
  @ConditionalOnMissingBean but it didn't work...
Thank you

A: You have several beans with the type ObjectMapper in the Spring Context. Try to add the annotation @Qualifier("objectMapper") for mapper (in AbstractTestController) or rename it to objectMapper:
@WebAppConfiguration
abstract class AbstractTestController : DatabaseInitializedTest() {
...
@Qualifier("objectMapper")
@Autowired
lateinit var mapper: ObjectMapper
...
}

or
@WebAppConfiguration
abstract class AbstractTestController : DatabaseInitializedTest() {
...
@Autowired
lateinit var objectMapper: ObjectMapper
...
}


text:
Q: System.InvalidOperationException in C# WPF I want to move a rectangle in WPF application using the following code. However, I am getting the following error:
System.InvalidOperationException: Cannot use a DependencyObject that belongs to a different thread
I looked at other problems in stackoverflow but nothing worked.
public partial class MainWindow : Window
{
    private Rectangle rect;
    int count = 1;
    Timer timer;

    public MainWindow()
    {
        InitializeComponent();
        Rectangle movedRectangle = new Rectangle();
        movedRectangle.Width = 200;
        movedRectangle.Height = 50;
        movedRectangle.Fill = Brushes.Blue;
        movedRectangle.Opacity = 0.5;
        TranslateTransform translateTransform1 = new TranslateTransform(50, 20);
        movedRectangle.RenderTransform = translateTransform1;

        this.can.Children.Add(movedRectangle);
        this.rect = movedRectangle;

        timer = new Timer(500);
        timer.Elapsed += OnTimedEvent;
        timer.Enabled = true;
    }

    private void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        count++;
        TranslateTransform translateTransform1 = new TranslateTransform(50 + count * 2, 20);
        this.rect.Dispatcher.Invoke(new Action(()=>
            rect.RenderTransform = translateTransform1));

        //this.can.UpdateLayout();
        this.can.Dispatcher.Invoke(new Action(()=>
            this.can.UpdateLayout()
            ));

    }

A: You are constructing a TranslateTransform (which is a DependencyObject) outside the UI thread. Easy fix:
        this.rect.Dispatcher.Invoke(new Action(
            () =>
            {
                TranslateTransform translateTransform1 = new TranslateTransform(50 + count * 2, 20);
                rect.RenderTransform = translateTransform1;
            }));

Arguably a better fix: use a DispatcherTimer instead and get rid of all your Dispatcher.Invoke calls.

A: I would suggest you to use DispatcherTimer than a normal timer.
Please see the below solution. enjoy.
Note: for DispatcherTimer you will need to add the assembly reference for System.Windows.Threading
public partial class MainWindow : Window
{
    private Rectangle rect;
    int count = 1;
    private DispatcherTimer timer = null;

    public MainWindow()
    {
        InitializeComponent();
        Rectangle movedRectangle = new Rectangle();
        movedRectangle.Width = 200;
        movedRectangle.Height = 50;
        movedRectangle.Fill = Brushes.Blue;
        movedRectangle.Opacity = 0.5;
        TranslateTransform translateTransform1 = new TranslateTransform(50, 20);
        movedRectangle.RenderTransform = translateTransform1;

        this.can.Children.Add(movedRectangle);
        this.rect = movedRectangle;

        timer = new DispatcherTimer();
        timer.Interval = new TimeSpan(0, 0, 0, 0, 500);
        timer.Tick += timer_Tick;
        timer.Start();
        timer.IsEnabled = true;

    }

    void timer_Tick(object sender, EventArgs e)
    {
        count++;
        TranslateTransform translateTransform1 = new TranslateTransform(50 + count * 2, 20);
        Dispatcher.BeginInvoke(new Action<TranslateTransform>(delegate(TranslateTransform t1)
            {
                rect.RenderTransform = t1;
                this.can.UpdateLayout();
            }), System.Windows.Threading.DispatcherPriority.Render, translateTransform1);
    }
}


text:
Q: Add new nation into nation's list in Magento 2.3.5 I want to add a new country Northern Ireland with the country code XI in Magento 2.3.5 Admin. any idea for this?
I already tried with this -

Add new country in default country dropdown in Magento 2.3.5

I found the same answer everywhere but it does not work for me so please help me with this.

if I want to update the data in "ICUDATA-region" so can it be
possible?

A: Create a module
module registration file
Vendor/NorthernIreland/registration.php
<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Vendor_NorthernIreland',
    __DIR__
);

module initialization file
Vendor/NorthernIreland/etc/module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Vendor_NorthernIreland" >
        <sequence>
            <module name="Magento_Directory"/>
        </sequence>
    </module>
</config>

file di, register plugin
Vendor/NorthernIreland/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Framework\Locale\TranslatedLists">
        <plugin name="vendor_northernireland" type="Vendor\NorthernIreland\Plugin\Framework\Locale\TranslatedListsPlugin"/>
    </type>
</config>

plugin
Vendor/NorthernIreland/Plugin/Framework/Locale/TranslatedListsPlugin.php
<?php

namespace Vendor\NorthernIreland\Plugin\Framework\Locale;

use Magento\Framework\Locale\ListsInterface;

/**
 * @inheritdoc
 */
class TranslatedListsPlugin
{
    /**
     * @inheritdoc
     */
    public function aroundGetCountryTranslation(
        ListsInterface $subject,
        callable $proceed,
        $value,
        $locale = null
    ) {
        if ($value == 'XI') {
            /* need to add $locale selector */
            return 'Northern Ireland';
        }
        return $proceed($value, $locale);
    }
}

db path, add code XI to directory_country table
Vendor/NorthernIreland/Setup/Patch/Data/AddDataForNorthernIreland.php
<?php

namespace Vendor\NorthernIreland\Setup\Patch\Data;

use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\Setup\Patch\DataPatchInterface;
use Magento\Framework\Setup\Patch\PatchVersionInterface;

/**
 * Class AddDataForNorthernIreland
 */
class AddDataForNorthernIreland implements DataPatchInterface, PatchVersionInterface
{
    /**
     * @var ModuleDataSetupInterface
     */
    private $moduleDataSetup;

    /**
     * @param ModuleDataSetupInterface $moduleDataSetup
     */
    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup
    ) {
        $this->moduleDataSetup = $moduleDataSetup;
    }

    /**
     * {@inheritdoc}
     */
    public function apply()
    {
        /**
         * Fill table directory/country
         */
        $data = [
            ['XI', 'XI', 'XI'] //iso3_code ???
        ];

        $columns = ['country_id', 'iso2_code', 'iso3_code'];
        $this->moduleDataSetup->getConnection()->insertArray(
            $this->moduleDataSetup->getTable('directory_country'),
            $columns,
            $data
        );
    }

    /**
     * {@inheritdoc}
     */
    public static function getDependencies()
    {
        return [];
    }

    /**
     * {@inheritdoc}
     */
    public static function getVersion()
    {
        return '2.0.0';
    }

    /**
     * {@inheritdoc}
     */
    public function getAliases()
    {
        return [];
    }
}

then run console commands
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy (optional)

check your system configuration (Stores/Setting/Configuration/General/General/Country Options), Northern Ireland should appear on all listings in this section.
I hope this helps you.

A: @vitalii hi
$data = [['XI', 'XI', 'XII'],['ZB', 'ZB', 'ZBB'] ];
to add multiple countries we have to do something like this ??
I have created the same extension with the help of Magento link https://support.magento.com/hc/en-us/articles/360057988152-How-to-add-a-new-country-to-Magento-2-
but I have already added countries code to the table instead of creating patch
but in may case plugin giving error on return
    return $proceed($value, $locale);

this return syntax error as $value have not value why ?
please help me


text:
Q: string class disposable method private void test()
{
    string tst = null;
    try
    {
        tst = "abc";
    }
    catch (Exception)
    {
        throw;
    }
    finally
    {
        tst = null;
    }
}

My query is - Is it meaningful to type tst = null; in the finally block as the string class doesn't have the disposable method ?

A: It doesn't have any effect, as tst goes out of scope immediately after the finally.
And this has nothing to do with Dispose.

A: No this is not necessary. The variable tst does no longer exists, when test() returns.

A: Even if string implemented IDisposable, setting a variable to null wouldn't call the Dispose method. It's utterly pointless, as is the catch block with the throw.
If you see code like this in a codebase you're maintaining, rip it out and have a quiet word with whoever put it in there in the first place.


text:
Q: boost graph library adjacency_list: maintain EdgeList sorted by EdgeProperties I'm trying to use a std::multiset container with strict weak ordering on the EdgeProperties for the EdgeList template parameter of boost::adacency_list
namespace boost {

struct propOrderedMultisetS { };
template <class ValueType>
struct container_gen<propOrderedMultisetS,ValueType> {
    struct less {
        bool operator() (const ValueType& lhs, const ValueType& rhs) const {
            return (lhs.get_property() < rhs.get_property());
        };
    };
    typedef std::multiset<ValueType, less> type;
};

struct MyVertexProp { int v; };
struct MyEdgeProp {
    bool operator<(const MyEdgeProp& rhs) const {
        return this->weight < rhs.weight;
    }
    double weight;
}

typedef adjacency_list<listS, listS, undirectedS, MyVertexProp, MyEdgeProp,
 no_property, propOrderedMultisetS> PropOrderedGraph;
}

using namespace boost;
int main() {
    PropOrderedGraph g;

    // ... adding some vertices and edges

    for (auto e_range=edges(g); e_range.first != e_range.second; ++e_range.first) {
        // works! prints the edges ordered by weight
        std::cout << g[*e_range.first].weight << std::endl;
    }

    for (auto v_range=vertices(g); v_range.first != v_range.second; ++v_range.first) {
        // works! prints all vertices (random order)
        std::cout << g[*v_range.first].v << std::endl;
    }

    auto first_vertex = *vertices(g).first;
    for (auto adj_v_range=adjacent_vertices(first_vertex, g); adj_v_range.first != adj_v_range.second; ++adj_v_range.first) {
        // problem: dereferencing causes compiler error, see below
        std::cout << g[*adj_v_range.first].v << std::endl;
    }

    return 0;
}

Dereferencing the iterator in the third for-loop causes a compiler error:

/usr/include/boost/graph/detail/adjacency_list.hpp:293:69: error: invalid initialization of reference of type 'MyEdgeProp&' from expression of type 'const MyEdgeProp'
         inline Property& get_property() { return m_iter->get_property(); }

Any ideas how I could fix that error or how else I could accomplish the task?

A: I changed the graph library and now am using LEMON, which provides a class IterableValueMap for my task.


text:
Q: Running cpi example of MVAPICH2 by mpirun_rsh failed I am a new user of MVAPICH2, and I encountered troubles when I started with it.
First, I think I have installed it successfully, through this:
    ./configure --disable-fortran --enable-cuda
    make -j 4
    make install
There were not errors.
But when I attempted to run the example of cpi in the directory of example, I encountered like this:

*

*I could connect node gpu-cluster-1 and gpu-cluster-4 through ssh without password;

*I run the cpi example separately on gpu-cluster-1 and gpu-cluster-4 using mpirun_rsh, and it worked OK, just like  this:
run@gpu-cluster-1:~/mvapich2-2.1rc1/examples$ mpirun_rsh -ssh -np 2 gpu-cluster-1 gpu-cluster-1 ./cpi
Process 0 of 2 is on gpu-cluster-1
Process 1 of 2 is on gpu-cluster-1
pi is approximately 3.1415926544231318, Error is 0.0000000008333387
wall clock time = 0.000089
run@gpu-cluster-4:~/mvapich2-2.1rc1/examples$ mpirun_rsh -ssh -np 2 gpu-cluster-4 gpu-cluster-4 ./cpi
Process 0 of 2 is on gpu-cluster-4
Process 1 of 2 is on gpu-cluster-4
pi is approximately 3.1415926544231318, Error is 0.0000000008333387
wall clock time = 0.000134

*I run the cpi example both on gpu-cluster-1 and gpu-cluster-4 using mpiexec, and it worked OK, just like this:
run@gpu-cluster-1:~/mvapich2-2.1rc1/examples$ mpiexec -np 2 -f hostfile ./cpi
Process 0 of 2 is on gpu-cluster-1
Process 1 of 2 is on gpu-cluster-4
pi is approximately 3.1415926544231318, Error is 0.0000000008333387
wall clock time = 0.000352
The content in hostfile is "gpu-cluster-1\ngpu-cluster-4"

*But, when I run cpi example, using mpirun_rsh, borh on gpu-cluster-1 and gpu-cluster-4, problem came out:
run@gpu-cluster-1:~/mvapich2-2.1rc1/examples$ mpirun_rsh -ssh -np 2 -hostfile hostfile ./cpi
Process 1 of 2 is on gpu-cluster-4
-----------------It stuck here, not going on ------------------------
After a long time, I press Ctrl + C, and it present this:
^C[gpu-cluster-1:mpirun_rsh][signal_processor] Caught signal 2, killing job
run@gpu-cluster-1:~/mvapich2-2.1rc1/examples$ [gpu-cluster-4:mpispawn_1][read_size] Unexpected End-Of-File on file descriptor 6. MPI process died?
[gpu-cluster-4:mpispawn_1][read_size] Unexpected End-Of-File on file descriptor 6. MPI process died?
[gpu-cluster-4:mpispawn_1][handle_mt_peer] Error while reading PMI socket. MPI process died?
[gpu-cluster-4:mpispawn_1][report_error] connect() failed: Connection refused (111)
I have been confused for a long time, could you give me some help to resolve this problems?
Here is the code of cpi example:

#include "mpi.h"
#include <stdio.h>
#include <math.h>

double f(double);

double f(double a)
{
    return (4.0 / (1.0 + a*a));
}

int main(int argc,char *argv[])
{
    int    n, myid, numprocs, i;
    double PI25DT = 3.141592653589793238462643;
    double mypi, pi, h, sum, x;
    double startwtime = 0.0, endwtime;
    int    namelen;
    char   processor_name[MPI_MAX_PROCESSOR_NAME];

    MPI_Init(&argc,&argv);
    MPI_Comm_size(MPI_COMM_WORLD,&numprocs);
    MPI_Comm_rank(MPI_COMM_WORLD,&myid);
    MPI_Get_processor_name(processor_name,&namelen);

    fprintf(stdout,"Process %d of %d is on %s\n",
    myid, numprocs, processor_name);
    fflush(stdout);

    n = 10000;          /* default # of rectangles */
    if (myid == 0)
    startwtime = MPI_Wtime();

    MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);

    h   = 1.0 / (double) n;
    sum = 0.0;
    /* A slightly better approach starts from large i and works back */
    for (i = myid + 1; i <= n; i += numprocs)
    {
        x = h * ((double)i - 0.5);
        sum += f(x);
    }
    mypi = h * sum;

    MPI_Reduce(&mypi, &pi, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);

    if (myid == 0) {
        endwtime = MPI_Wtime();
        printf("pi is approximately %.16f, Error is %.16f\n",
               pi, fabs(pi - PI25DT));
        printf("wall clock time = %f\n", endwtime-startwtime);
        fflush(stdout);
    }

    MPI_Finalize();
    return 0;
}


text:
Q: Why alternative keywords are not famous in place of in-built ascii operators? In the list of C++ keywords, there are alternatives for the operators, such as:
&&  and
&=  and_eq
&   bitand
|   bitor
~   compl
!   not
!=  not_eq
||  or
|=  or_eq
^   xor
^=  xor_eq

In fact I personally find:
if(not s.empty())

more intuitive than,
if(!s.empty())

In many scripting language such words are the only option.
Why are not they famous in C++ over the operators? Is there anything to do with coding style or is it just a matter of taste.


text:
Q: Transferring an SQL Processor License to a virtual hosted environment
Possible Duplicate:
Can you help me with my software licensing question?

My company is currently hosting a service in-house, and we want to move to an externally hosted environment.
We would then be using a virtual server. I understand that this might be spread across multiple machines, but from my perspective as a customer, this layer is abstracted away - I shouldn't know or care about the hardware that the OS is hosted on.
We have a licensed edition of SQL Server 2008. This is one Processor license.
Will it be a violation of the licensing agreement to use this in a virtual environment?
From the reference guide here it says

When licensed Per Processor
With
  Workgroup, Web, and Standard editions,
  for each server to which you have
  assigned the required number of per
  processor licenses, you may run, at
  any one time, any number of instances
  of the server software in physical and
  virtual operating system environments
  on the licensed server. However, the
  total number of physical and virtual
  processors used by those operating
  system environments cannot exceed the
  number of software licenses assigned
  to that server  For enterprise edition
  there is an added option: if all
  physical processors in a machine have
  been licensed, then you may run
  unlimited instances of SQL server 2008
  in one physical and an unlimited
  number of virtual operating
  environments on that same machine.

I'm having trouble getting my head around this. Would I theoretically have to get a license for every processor in this virtual environment (which is effectively impossible because I have no way of knowing how many processors there actually are)? Or can I just say that it's hosted on one "virtual" server, so that's OK?

A: http://download.microsoft.com/download/1/e/6/1e68f92c-f334-4517-b610-e4dee946ef91/2008%20SQL%20Licensing%20overview%20final.docx uses the phrase 'A Processor License is required for each processor installed on each operating system environment running SQL Server', so I'd say it's fine.


text:
Q: CreateWindow on windows 8 seems to create window too large I'm calling CreateWindowEx (below) on Windows 8.1 with a size of 1920x1080 (native res) and the resulting window is much larger (maybe 2 times larger).
    HWND windowHandle;

    DWORD style = WS_POPUP;
    DWORD exStyle = WS_EX_APPWINDOW;

    RECT rect;
    SetRect(&rect, left, top, right, bottom);
    ::AdjustWindowRectEx(&rect, style, false, exStyle);

    windowHandle =
    ::CreateWindowEx(
        WS_EX_APPWINDOW,
        title,              //name of the window class
        title,              //title
        style,              //style flags
        left, top, right - left, bottom - top,
        NULL,               //parent window
        NULL,               //menu
        applicationHandle,  //handle to application (given at WinMain)
        NULL);

I've read in the documentation that the size parameters are expected in device units. My hunch is that this is the cause of the issue but I'm finding no documentation on how to convert or specify in the appropriate units or disable it so that I can specify in pixels.
FYI The device is a Surface Pro II.

A: For anyone arriving from Google, I added:
SetProcessDpiAwareness(PROCESS_DPI_AWARENESS::PROCESS_SYSTEM_DPI_AWARE)
before my call to
CreateWindow()
The documentation doesn't mention which lib to link against but it should be shcore.lib.


text:
Q: Email verification after sign up I tried using devise gem following this : http://guides.railsgirls.com/devise/ it doesn't tell us how to send email verification mail. i read this : https://github.com/plataformatec/devise too but didn't really understand it. so i am making my own verification.

*

*make hash from user email and salt.

*send that hash to user email using mailer

*ask user to enter the hash sent to his email and if matches then user account is verified.

how bad implementation of email verification is this?

A: You can do that easily using Devise, all you need is to add Confirmable module to devise, refer to this official devise solution to tackle this thing
https://github.com/plataformatec/devise/wiki/How-To:-Add-:confirmable-to-Users


text:
Q: Find lines covering points on 2D space I have a list of points x,y. Mission is to find the smallest number of lines that goes through them (but one line goes by maximum 5 points). The other thing is that it doesn't have to be exact line, Line is good even if it's not exactly on the point, can be 8x or|and 8y away from point.
Any help would be awesome.
[20,50],
[15,37],
[29,77],
[24,120],
[12,60],
[27,53],
[11,24],
[53,34],
[43,23]

I have to do it in C# or Python. The points can be diffrent they will be random.


text:
Q: Load data in form and update row in database I load in table form data from mysql. So far so good. Now I have made button called Update which open new page where I can update single row in database. The problem is that when I open the update form all the fields are empty and if I want to update just some row and leave blank other fields they are updated as blank in database also which is normal. How can I populate the info into update form?
This is what I use currently to update some record in database.
File edit.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $id = null;
        if ( !empty($_GET['id']))
        {
            $id = $_REQUEST['id'];
        }
        if ( null==$id )
        {
           echo "null==$id";
        }
        // keep track post values
            $name = $_POST['name'];
            $image = $_POST['image'];
            $image_big = $_POST['image_big'];
            $description = $_POST['description'];

                   // update data
           $pdo = Database::connect();
           $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
           $sql = "UPDATE food set name = ?, image = ?, image_big = ?, description = ? WHERE id = ?";
                    $q = $pdo->prepare($sql);
                    $q->execute(array($name, $image, $image_big, $description, $id));
                    Database::disconnect();
                    echo "Updated!";

          // html form

If I leave for example name empty and put some new data in all other fields when I hit Update button in database name will be blank.
Updated with part of the html form

          Име
            <input id="name" name="name" placeholder="Name" class="form-control" type="text">

Other fields are the same..

A: In this case please try to put something like this on the <input> field where you check if field is empty and asign.(Didn't tested it)
value="<?php echo !empty($name)?$name:'';?>"

So your form fields will become like

      Name
        <input value="<?php echo !empty($name)?$name:'';?>" id="name" name="name" placeholder="Name" class="form-control" type="text">


text:
Q: Negating params in a Spring controller's RequestMapping
Hi,
I've got two methods in my controller and I'm trying to get one method to fire if a parameter is a certain value and the other method if the parameter is not that value.  My "not" method is firing when the param equals the certain value.
According to (my understanding of) this I'm writing the expression correctly.  Here are the signatures of the two methods:
@RequestMapping(value = "/doit", params= {"output=grouped", "display!=1"})
public @ResponseBody HashMap<String, Object> doSomething(
@RequestParam("text") String text,
@RequestParam("display") String display)
{
  // this method runs if display=1 but why?
}

@RequestMapping(value = "/doit", params= {"output=grouped", "display=1"})
public @ResponseBody HashMap<String, Object> doSomethingElse(
@RequestParam("text") String text)
{
  // this method is not being called when display=1...why not?
}

I have Spring debug logging enabled and I see where Spring converts the parameter to a RequestParam String with value '1'.  In the very next line, though, it decides to map it to the wrong method.
What am I doing wrong?
Thanks!

A: It is not your fault: it is a Bug SPR-8059. At the moment it is fixed in Version 3.1M2 and svn Trunk rev 4408.
A workaround would be not to use != in @RequestMapping. Instead you have to do it with an if by hand:
@RequestMapping(value = "/doit", params= {"output=grouped")
public @ResponseBody HashMap<String, Object> acceptAll(
   @RequestParam("text") String text,
   @RequestParam("display") String display) {
  if("1".equals(display) {
      return doSomethingElse(text);
  } else {
      return doSomething(text,display);
  }
}


text:
Q: Cordova/Phonegap File plugin, Overwrite index.html on pause event Using Cordova/Phonegap, is it possible to save the state of the index.html file as the user leaves it using the onPause event so it it remains up-to-date.
This would very much work the same as the "SaveAs" command in application software.
If it is how? And what plugin do I require?
Thanks in advance.


text:
Q: Use the Mean Value Theorem to show that the only answers for $5^x -3^x =4^x -2^x$ are $1$ and $0$ That question is equivalent to proving that $f(x)=5^x+2^x-3^x-4^x$ have only two roots, $0$ and $1$. But that's everything I've made so far.

A: Following the hint by Tob Ernack let $f(y)=(y+2)^x-y^x$ then by MVT
$$\frac{f(3)-f(2)}{3-2}=f'(c)=0 \quad,\quad c\in(2,3)$$
$$f'(c)=x(c+2)^{x-1}-xc^{x-1}=x\big((c+2)^{x-1}-c^{x-1}\big)=0$$
that is

*

*$x=0$

*$(c+2)^{x-1}=c^{x-1}\Rightarrow (x-1)\log (c+2)=(x-1)\log c\\\Rightarrow x-1=0$


text:
Q: When I use Auto Layout to choose each cell's height (so they're dynamic) it mostly works, but some cells are a little short. Why is this? Example project: http://cl.ly/2j0A1J203f3h
I'm trying to use Auto Layout to dynamically determine each cell's height so some cell's can hold more content than others. To do this I'm using this Stackoverflow answer and the accompanying GitHub example.
I have a UITableViewCell subclass called CSPostCell that I created in the Storyboard and put a UILabel in with a maximum of 5 lines of text in the label.
Just for example purposes, I'm only having two cells in the table and as such two different pieces of text for the labels (one's longer) which is set up in cellForRowAtIndexPath::
- (CSPostCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CSPostCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SelfPostCell" forIndexPath:indexPath];
    cell.postTitle.text = indexPath.row == 0 ? @"Short title" : @"Long long long title. Holy crap this is one long title. When does it end? Oh right now.";
    [cell setNeedsUpdateConstraints];

    return cell;
}

I then return the height of each cell as such:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CSPostCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SelfPostCell"];

    cell.postTitle.text = indexPath.row == 0 ? @"Short title" : @"Long long long title. Holy crap this is one long title. When does it end? Oh right now.";
    cell.postTitle.preferredMaxLayoutWidth = tableView.bounds.size.width - 40;

    [cell setNeedsUpdateConstraints];
    [cell updateConstraintsIfNeeded];
    [cell.contentView setNeedsLayout];
    [cell.contentView layoutIfNeeded];

    CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

    return height;
}

Which is more or less an exact copy from the GitHub repo example.
However, when I run the app in the simulator, it doesn't quite work as it should. The heights are dynamic and adjust for longer pieces of text, but not enough that the text doesn't get cut off. See the image below:

In that above case the second cell's label should show another line to finish off the text, but it gets cut off.
Why is it not showing all the text?

A: This simplified code worked well for me, with just one slight fudge of 2 points. All the calls to updateConstraints seem to be unnecessary. I'm not sure why you need the fudge factor -- maybe some padding in the label? I tested it with different length strings and different font sizes, and it always worked correctly.
- (CSPostCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CSPostCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SelfPostCell" forIndexPath:indexPath];
    cell.postTitle.text = indexPath.row == 0 ? @"Short title" : @"Long long long title. Holy crap this is one long title. When does it end? Oh right now.";
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CSPostCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SelfPostCell"];
    cell.postTitle.text = indexPath.row == 0 ? @"Short title" : @"Long long long title. Holy crap this is one long title. When does it end? Oh right now.";
    cell.postTitle.preferredMaxLayoutWidth = tableView.bounds.size.width - 40;
    CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    return height + 2;
}


text: Q: Rails Background jobs uses all CPU memory and blocks UI actions I am using resque gem to process background jobs for import and exports task (Asynchronous). These jobs were using almost all CPU memory if import/export task increasing and it blocks UI(Web) actions also. I am not sure what is the best way to optimize this?


text:
Q: Android Java open activity after email sent Im trying to start a new activity AFTER the email is sent
I use the following to invoke the default email client
this.startActivity(Intent
.createChooser(emailIntent, "Send mail..."));

This works fine and starts the email app when you send the message it reurns you to the activity it starts from
I want to then start a new activity( the main Screen) and then close the previous one
I inserted the following
Intent myIntent = new Intent(view.getContext(), Activity1.class);
startActivityForResult(myIntent, 0);
finish();

This works but the email screen is hidden behind the new activity and i have to quit the app to send the email
is there a way of starting the activity after the email is sent?
Im using gmail as the client
Any help appreciated
Mark

A: Unfortunately I didn't find any info that when you start email client with starActivityForResult() it returns with some result code whether user send email or cancel that action. Gmail sent activity is started within your activity stack so you end up starting two activities, gmail app as second.

A: Hope this will help you
Intent email = new Intent(Intent.ACTION_SEND);
    email.putExtra(Intent.EXTRA_EMAIL,new String[] { "tony@mail.com"});
    email.putExtra(Intent.EXTRA_SUBJECT,"Test");
    email.putExtra(Intent.EXTRA_TEXT,"sent a message using for testing ");

    email.setType("message/rfc822");

    startActivityForResult(Intent.createChooser(email, "Choose an Email client:"),
                        1);

You need onActivityResult method like below

protected void onActivityResult(int requestCode, int
  resultCode, Intent data) {
if(requestCode == MY_REQUEST_CODE) {
    if(resultCode == RESULT_OK) {

    } else {

        Intent ingoHome = new Intent(current.this,
                newclass.class);

        startActivity(ingoHome);

    }
}

finish();

}


text:
Q: Toplink Validation with Ant fails due to SessionLoaderExceptions I'm trying to integrate toplink's session exports with my build process (Apache Ant). I've been working from the example here:
http://download.oracle.com/docs/cd/E14571_01/web.1111/b32441/mw.htm
My Ant init target and the session validation target are shown below:
<!-- ============
init Target
============== -->
<target name="init">

<property name = "toplink.home" value = "C:/APPS/OC4J/toplink"/>
<property name = "oracle.home" value = "C:/APPS/OC4J"/>
<property name = "toplink.log.dir" value = "${basedir}/../toplinklogs"/>

<property name = "toplink.mwp.dir" value = "${basedir}/../java/mwb"/>
<property name = "toplink.sessions.dir" value = "${basedir}/config"/>
<property name = " myProject.classes" value = "${basedir}/../java/classes "/>

<path id = "database.classpath">
<pathelement path = "${oracle.home}/lib/dms.jar"/>
</path>

<path id = "toplink.classpath">
<pathelement path = "${toplink.home}/jlib/toplink.jar"/>
<pathelement path = "${oracle.home}/j2ee/home/lib/ejb.jar"/>
<pathelement path = "${oracle.home}/lib/xmlparserv2.jar"/>
<pathelement path = "${toplink.home}/jlib/antlr.jar"/>
</path>
<path id = "mw.classpath">
<pathelement path = "${toplink.home}/jlib/tlmwcore.jar"/>
<pathelement path = "${toplink.home}/jlib/toplinkmw.jar"/>
</path>
<path id = "mwplatforms.classpath">
<pathelement path = "${toplink.home}/config"/>
</path>

<typedef file = "${basedir}/toplink-ant-lib.xml" classpathref = "mw.classpath" uri = "toplinklib" />
</target>

<!-- ======================
validate session Target
======================= -->
<target name="validate.session" depends="export.project" if="export-completed">
<toplink:session.validate
sessionsfile = "${basedir}/../java/src/aquila/administrator/accounting/config/toplink/AccountingMapping.xml"
sessionname = "AccountingMapping"
property = "session-valid"
classpathref = "toplink.classpath"
classpath = "${myProject.classes}" >

<toplink:classpath refid = "mw.classpath" />
<toplink:classpath refid = "database.classpath" />

<toplink:loginspec refid = "loginSpec" />
</toplink:session.validate>
</target>

I get the following Errors from ant:
validate.session:
[toplink:session.validate] An error occured while validating project:
[toplink:session.validate] Exception Description: Several [3] SessionLoaderExceptions were thrown:

BUILD FAILED
C:\Eclipse\Administrator\ant\example.xml:105: An error occured while validating project:
Exception Description: Several [3] SessionLoaderExceptions were thrown:

When I turn on verbose mode in ant I can see more details of the error:
Local Exception Stack:
Exception [TOPLINK-9001] (Oracle TopLink - 10g Release 3 (10.1.3.0.0) (Build 060118)): oracle.toplink.exceptions.SessionLoaderException
Exception Description: Unknown tag name: [toplink:login] in XML node: [toplink:object-persistence].
Internal Exception: java.lang.NoSuchMethodException: oracle.toplink.tools.sessionconfiguration.XMLLoader.process_toplink:login_Tag(org.w3c.dom.Node, oracle.toplink.tools.sessionconfiguration.XMLLoader$ObjectHolder)

Local Exception Stack:
Exception [TOPLINK-9001] (Oracle TopLink - 10g Release 3 (10.1.3.0.0) (Build 060118)): oracle.toplink.exceptions.SessionLoaderException
Exception Description: Unknown tag name: [opm:class-mapping-descriptors] in XML node: [toplink:object-persistence].
Internal Exception: java.lang.NoSuchMethodException: oracle.toplink.tools.sessionconfiguration.XMLLoader.process_opm:class_mapping_descriptors_Tag(org.w3c.dom.Node, oracle.toplink.tools.sessionconfiguration.XMLLoader$ObjectHolder)

Local Exception Stack:
Exception [TOPLINK-9001] (Oracle TopLink - 10g Release 3 (10.1.3.0.0) (Build 060118)): oracle.toplink.exceptions.SessionLoaderException
Exception Description: Unknown tag name: [opm:name] in XML node: [toplink:object-persistence].
Internal Exception: java.lang.NoSuchMethodException: oracle.toplink.tools.sessionconfiguration.XMLLoader.process_opm:name_Tag(org.w3c.dom.Node, oracle.toplink.tools.sessionconfiguration.XMLLoader$ObjectHolder)

The 3 errors shown above correspond to the 3 tags at the same level in the session.xml file. I have tested this validation process with a session.xml file generated from the workbench and that failed too. Since its a NoSuchMethodException it looks like my ant process isn't finding the oracle.toplink.tools.sessionconfiguration.XMLLoader class, but that is in toplink.jar which is in the class path.
Any help appreciated

A: Purely based on the names of your files it appears you are attempting to load a mapping metadata file (aka project.xml) as a Sessions metadata file.  The XMLLoader is only used to load Session config files (aka "sessions.xml").


text:
Q: Why did a large comparison become 1 line of assembler code? Following a suggestion in a comment here, I'm trying to understand how does Compiler Explorer work. My input is the following piece of code:
int main() {
    double x,y,x0,y0,x1,y1;
    x = 10;
    y = 10;
    x0 = 5;
    y0 = 5;
    x1 = 15;
    y1 = 15;
    if (x > x0 && x < x1 && y > y0 && y < y1)
        return 1;
    return 0;
}

The result is:
    mov     eax, 1
    ret

I have learned the basics of assembler many years ago, but I don't know if, or how, this makes any sense. Does it? (What I was trying to find is if adding an "else" between the two returns would have any difference in performance. According to this site, it doesn't. But am I getting it right?)

A: The condition is true. The compiler optimizes it out; it generates code for return 1;.


text:
Q: What is the fastest way to open urls in new tabs via Selenium - Python? I want to create a python script to open up a lot tabs
import os
import selenium
from selenium import webdriver

driver =webdriver.Chrome('/usr/local/bin/chromedriver')
driver.execute_script("window.open('http://www.msn.com');")
driver.execute_script("window.open('http://www.cnn.com');")
driver.execute_script("window.open('http://www.yahoo.com');")
driver.execute_script("window.open('https://www.apple.com');")
driver.execute_script("window.open('https://www.google.com');")
driver.execute_script("window.open('https://www.stackoverflow.com');")

# driver.quit()

When I run I get

Is what I have right now is the fastest way?

I used to have this
# -*- coding: utf-8 -*-

import os
import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver =webdriver.Chrome('/usr/local/bin/chromedriver')

#1
driver.get("http://msn.com")

#2
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't')
driver.switch_to.window(driver.window_handles[-1])
driver.get("http://cnn.com")

#3
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't')
driver.switch_to.window(driver.window_handles[-1])
driver.get("http://www.yahoo.com")

#4
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't')
driver.switch_to.window(driver.window_handles[-1])
driver.get("https://www.apple.com")

#5
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't')
driver.switch_to.window(driver.window_handles[-1])
driver.get("https://www.google.com")

#6
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't')
driver.switch_to.window(driver.window_handles[-1])
driver.get("https://www.stackoverflow.com")

It works but it is painfully slow.

I start with 6 now, but I want to load 100 tabs.
Also, how do I get rid of my first weird looking tab?
I am even sure why it is there.

A: Upgrade the chromedriver(>2.25)/chrome browser(>55.0) on your MAC to remove the empty data; tab.
You can use threading or multiprocessing to speed up the process.
from multiprocessing import Process
import os
import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver =webdriver.Chrome('/usr/local/bin/chromedriver')
driver.get("http://msn.com")
def func1():
  print 'launching: MSN'
 driver.execute_script("window.open('http://www.msn.com');")

def func2():
  print 'launching: CNN'
  driver.execute_script("window.open('http://www.cnn.com');")

if __name__ == '__main__':
  p1 = Process(target=func1)
  p1.start()
  p2 = Process(target=func2)
  p2.start()
  p1.join()
  p2.join()

def runInParallel(*fns):
  proc = []
  for fn in fns:
    p = Process(target=fn)
    p.start()
    proc.append(p)
  for p in proc:
    p.join()

runInParallel(func1, func2)

Depending on how many CPUs you have, the load of the machine, the timing of many things happening in the computer will have an influence on the time the threads/process start. Also, since the processes are started right after creation, the overhead of creating a process also has to be calculated in the time difference you see.

A: So we already have have 2 approaches at out disposal to open New TAB with Selenium.
Your previous approach with send_keys(Keys.COMMAND + 't') is bound to consume more time as we switch_to.window() and get("http://www.url.com") too. Hence slower.
Your current approach with execute_script is bound to be faster as we are simply injecting Java Scripts to open new TAB s with URL s.
Now, the reason you see a Blank Window is because once you initialized the browser through :
driver =webdriver.Chrome('/usr/local/bin/chromedriver')

After this, we haven't invoked the get() method to open any URL. Rather we have straight taken help of JavascriptExecutor to open NEW TAB s. Hence the first TAB remains unused.

Update :
To bring the unused TAB into the play, we can access the first of the URL s through the first TAB invoking get() method as follows :
driver =webdriver.Chrome('/usr/local/bin/chromedriver')
driver.get("http://www.msn.com")
driver.execute_script("window.open('http://www.cnn.com');")
driver.execute_script("window.open('http://www.yahoo.com');")
driver.execute_script("window.open('https://www.apple.com');")
driver.execute_script("window.open('https://www.google.com');")
driver.execute_script("window.open('https://www.stackoverflow.com');")

Summary :
To open a New Blank TAB you can use the following line of code :
driver.execute_script("window.open('','_blank');")

To open a New TAB with url you can use the following line of code :
driver.execute_script("window.open('http://facebook.com/');")


text:
Q: Replacing recursion with iteration I have a recursive function which I need to convert to an iterative function but I am quite stuck. Can anyone help or point me in the right direction?
f :: Int -> Int
f(0) = 5
f(1) = 8
f(2) = 3
f(n) = (f(n-3)) * (f(n-1))

Cheers

A: The following code snippet should do the trick:
int output[1000];
output[0] = 5;
output[1] = 8;
output[2] = 3;

for (int i=3; i < 1000; ++i) {
    output[i] = output[i-3] * output[i-1];
}

Bonus: Implementing your function non-recursively in this manner is called dynamic programming.

A: This looks like it works. Essentially it keeps the most recent 3 numbers and walks them upwards until we hit n.
public int rf(int n) {
    return n == 0 ? 5
            : n == 1 ? 8
                    : n == 2 ? 3
                            : rf(n - 3) * rf(n - 1);
}

public int nrf(int n) {
    int[] v = {5, 8, 3};
    int x = n == 0 ? 5
            : n == 1 ? 8
                    : n == 2 ? 3
                            : 0;
    for (int i = 2; i < n; i++) {
        x = v[0] * v[2];
        v[0] = v[1];
        v[1] = v[2];
        v[2] = x;
    }
    return x;
}

public void test() {
    for (int i = 0; i < 10; i++) {
        System.out.println(rf(i) + " = " + nrf(i));
    }
}

Correctly prints:
5 = 5
8 = 8
3 = 3
15 = 15
120 = 120
360 = 360
5400 = 5400
648000 = 648000
233280000 = 233280000
1286582272 = 1286582272


text:
Q: Grails plugins not downloading from Eclipse - Luna I am just setting up my Grails/Groovy STS suite in Eclipse. I created a new Grails Project, and when I right click on the project and select Grails -> Refresh Dependencies, it is failing to download dependencies (error log below) and hence doesn't build my project.
I think it could be a proxy issue, but I never had a proxy setup in my Eclipse and I always download Spring suites/and all other plugins from update sites or Market place just fine, so can't be a proxy issue.
In addition, I did not check all the urls, but some urls printed to the console are in fact throwing 404 error! It is the latest installation of STS, and how come it is looking at the wrong locations? Do I need to do anything?
Any thoughts?
(first few lines of error messages from console)
Starting process on MYPC/XXX.XXX.XXX.XX
Loading Grails 2.4.3
|Configuring classpath
:: problems summary ::
:::: WARNINGS
    Host repo.grails.org not found. url=http://repo.grails.org/grails/plugins/org/grails/plugins/tomcat/2.4.3/tomcat-2.4.3.pom
    Host repo.grails.org not found. url=http://repo.grails.org/grails/plugins/org/grails/plugins/tomcat/2.4.3/tomcat-2.4.3.zip
    Host repo1.maven.org not found. url=http://repo1.maven.org/maven2/org/grails/plugins/tomcat/2.4.3/tomcat-2.4.3.pom
    Host repo1.maven.org not found. url=http://repo1.maven.org/maven2/org/grails/plugins/tomcat/2.4.3/tomcat-2.4.3.zip
    Host snapshots.repository.codehaus.org not found. url=http://snapshots.repository.codehaus.org/org/grails/plugins/tomcat/2.4.3/tomcat-2.4.3.pom
    Host snapshots.repository.codehaus.org not found. url=http://snapshots.repository.codehaus.org/org/grails/plugins/tomcat/2.4.3/tomcat-2.4.3.zip
    Host repository.codehaus.org not found. url=http://repository.codehaus.org/org/grails/plugins/tomcat/2.4.3/tomcat-2.4.3.pom
    Host repository.codehaus.org not found. url=http://repository.codehaus.org/org/grails/plugins/tomcat/2.4.3/tomcat-2.4.3.zip
    Host download.java.net not found. url=http://download.java.net/maven/2/org/grails/plugins/tomcat/2.4.3/tomcat-2.4.3.pom
    Host download.java.net not found. url=http://download.java.net/maven/2/org/grails/plugins/tomcat/2.4.3/tomcat-2.4.3.zip
    Host repository.jboss.com not found. url=http://repository.jboss.com/maven2/org/grails/plugins/tomcat/2.4.3/tomcat-2.4.3.pom
    Host repository.jboss.com not found. url=http://repository.jboss.com/maven2/org/grails/plugins/tomcat/2.4.3/tomcat-2.4.3.zip
        module not found: org.grails.plugins#tomcat;2.4.3
    ==== grailsPlugins: tried
      -- artifact org.grails.plugins#tomcat;2.4.3!tomcat.zip:
      Y:\workspaces_trunk\GMon\lib\tomcat-2.4.3.zip
    ==== grailsHome: tried
      C:\Programs\eclipse-java-luna-SR1-win32-x86_64\grails-2.4.3\lib\org.grails.plugins\tomcat\ivy-2.4.3.xml
      -- artifact org.grails.plugins#tomcat;2.4.3!tomcat.zip:
      C:\Programs\eclipse-java-luna-SR1-win32-x86_64\grails-2.4.3\lib\org.grails.plugins\tomcat\jars\tomcat-2.4.3.zip
      C:\Programs\eclipse-java-luna-SR1-win32-x86_64\grails-2.4.3\lib\org.grails.plugins\tomcat\bundles\tomcat-2.4.3.zip
    ==== grailsHome: tried
      C:\Programs\eclipse-java-luna-SR1-win32-x86_64\grails-2.4.3\dist\tomcat-2.4.3.pom
      -- artifact org.grails.plugins#tomcat;2.4.3!tomcat.zip:
      C:\Programs\eclipse-java-luna-SR1-win32-x86_64\grails-2.4.3\dist\tomcat-2.4.3.zip
    ==== grailsHome: tried
      C:\Users\rp48085\.grails\2.4.3\cached-installed-plugins\tomcat-2.4.3.xml
      -- artifact org.grails.plugins#tomcat;2.4.3!tomcat.zip:
      C:\Users\rp48085\.grails\2.4.3\cached-installed-plugins\tomcat-2.4.3.zip
    ==== grailsHome: tried
      C:\Programs\eclipse-java-luna-SR1-win32-x86_64\grails-2.4.3\plugins\tomcat-2.4.3.pom
      -- artifact org.grails.plugins#tomcat;2.4.3!tomcat.zip:
      C:\Programs\eclipse-java-luna-SR1-win32-x86_64\grails-2.4.3\plugins\tomcat-2.4.3.zip
    ==== grailsCentral: tried
      http://repo.grails.org/grails/plugins/org/grails/plugins/tomcat/2.4.3/tomcat-2.4.3.pom
      -- artifact org.grails.plugins#tomcat;2.4.3!tomcat.zip:

A: I resolved it by running "grails add-proxy" and "grails set-proxy" commands one after the other. I have tried setting the proxy settings in Eclipse->Window->Preferences, as thats how I have always done to get plugins/downloads going from Eclipse. But grails apparently doesn't use these settings, so it needs to be given proxy settings using the above commands.


text:
Q: What happens if I delete an icloud backup? Ok so, I currently have filled up 2 tb of icloud storage. If I delete an iphone's backup from icloud, will that also delete all the data that is stored in icloud for that iphone? What I mean by this is, all of the old data that may not be on my iphone now will be gone? Or is a backup just a copy of the data on the iphone? If I delete the backup from icloud to make more space for a new backup will I still have all my data on my iphone?

A: A backup is just a copy of data on your iPhone, yes. However some types of data on your phone are not stored in iCloud Backup, but rather in other parts of iCloud or similar services. This includes for example photos in iCloud Photos, files in iCloud Drive, and Contacts, Calendars, Bookmarks, Mail, Notes, Health Data and Voice Memos in iCloud.
Deleting a backup from iCloud will not delete the data on your iPhone.
If you delete all the backups of your phone, you'll only have the data on your phone. Data that was previously stored only in the backups, and that is not stored on your phone or in other cloud services, will now be gone.


text:
Q: Please How to Solve ADP API Connection Problem(Error : Status-58) I have Download ADP Client Connection Folder From This Link :
https://github.com/adplabs/adp-connection-php
Message:
Communication Error
Status:
58
Response:
could not load PEM client certificate, OpenSSL error error:02001003:system library:fopen:No such process, (no key found, wrong pass phrase, or wrong file format?)
$ADP_APIROOT  = "https://iat-api.adp.com/";

//--------------------------------------------------------------------------------------
// The location, on disk, of the certificate for the server.
//--------------------------------------------------------------------------------------
$ADP_CERTFILE = __DIR__ . "/certs/apiclient_iat.pem";

//--------------------------------------------------------------------------------------
// The location, on disk, of the public key of the  server
//--------------------------------------------------------------------------------------
$ADP_KEYFILE  = __DIR__ . "/certs/apiclient_iat.key";

//--------------------------------------------------------------------------------------
// Client ID and Secrets for each Grant Type
//--------------------------------------------------------------------------------------

// Client Credentials

$ADP_CC_CLIENTID = "88a73992-07f2-4714-ab4b-de782acd9c4d";
$ADP_CC_CLSECRET = "a130adb7-aa51-49ac-9d02-0d4036b63541";

// Authorization Code

$ADP_AC_CLIENTID = "ec762f06-7410-4f6d-aa82-969902c1836a";
$ADP_AC_CLSECRET = "6daf2cd7-4604-46c0-ab43-a645a6571d34";

// Redirect Callback for authorization code calls

$ADP_REDIRECTURL = "http://localhost:8889/callback";

My Accepted Result Is Correctly Connect With ADP.


text:
Q: Using JQuery.serializeArray with MaskMoney Unmask So, I'm making an AJAX call like so (this is Clojure but the problem was the same under pure JS):
(POST (str "/input/" spreadsheet "?")
                {:params        (.serializeArray (jquery (str "#" page)))
                 :format        :json
                 :handler       render-spreadsheet
                :error-handler error-handler})

The problem is that I have MaskMoney components on-screen, and they return their formatting, so $1,234.56 comes back as $1,234.56 and not 1234.56.
MaskMoney has an unmask function that returns the raw value, but I think that requires me to re-do .serializeArray, which I'd prefer not to.
So:
1) How do I get .serializeArray and .unmask to play together?
2) If not, should I just find the .serializeArray code, and copy-and-paste it so that I can include the recalcitrant unmask call?


text: Q: Где лучше хранить временные ключи? Работаю с API. При авторизации приходит временный токен, который действует один час. Скажите, пожалуйста, где его лучше хранить этот токен и время его действия?. В базе там, в кэше, или в сессии.


text:
Q: Calculating a weighted correlation using different vector weights for each variable in R I would like to calculate a weighted correlation between two variables having different weights.
Some example data:
DF = data.frame(
  x = c(-0.3, 0.3, -0.18, 0.02, 0.07, 0.11, 0.20, 0.8, 0.3, -0.4),
  x_weight = c(50, 40, 70, 5, 15, 30, 32, 13, 9, 19),
  y = c(-0.6, 0.25, 0.1, 0.3, 0.3, -0.05, -0.5, 1, 0.05, -0.6),
  y_weight = c(70, 8, 10, 39, 9, 49, 90, 77, 23, 75)
)
DF

I read about cov.wt in the stats package, but it only allows input for one vector of weights. Essentially I'm looking for similar inputs as wtd.t.test, but to calculate a correlation instead.
Thank you for your help!

A: You can calculate the weighted correlation between two variables using the following formula Formulas are based on the definition of weighted covariance and correlation.
First, calculate the weighted means for the two variables using the weights:
mu_x = sum(DF$x * DF$x_weight) / sum(DF$x_weight)
mu_y = sum(DF$y * DF$y_weight) / sum(DF$y_weight)

Next, calculate the weighted covariance between the two variables:
cov_xy = sum((DF$x - mu_x) * (DF$y - mu_y) * DF$x_weight * DF$y_weight) / sum(DF$x_weight * DF$y_weight)

Finally, calculate the weighted correlation between the two variables:
cor_xy = cov_xy / (sqrt(sum((DF$x - mu_x)^2 * DF$x_weight) / sum(DF$x_weight)) * sqrt(sum((DF$y - mu_y)^2 * DF$y_weight) / sum(DF$y_weight)))


text:
Q: Could someone please tweak this php code for me? Drupal code I found this code to work on my Drupal site. It outputs the taxonomy terms in a comma separated list.
It successfully builds my taxonomy list to look like this:
Business, Entertainment, Leisure
While that's great, its using the same names to link itself in the url and so I get this:
www.yourdomain.com/category/Business
How can I make only the term name in the url lowercase to get it like this?
www.yourdomain.com/category/business
I believe I have to use this: string strtolower ( string $str ) but I'm not very php savvy. So where do I start?
    function phptemplate_preprocess_node(&$vars) {

      // Taxonomy hook to show comma separated terms
      if (module_exists('taxonomy')) {
        $term_links = array();
        foreach ($vars['node']->taxonomy as $term) {
          $term_links[] = l($term->name, 'category/' . $term->name,
            array(
              'attributes' => array(
                'title' => $term->description
            )));
        }
        $vars['node_terms'] = implode(', ', $term_links);
      }

}

Thanks for any help!

A: You're on the right track with the strtolower() function, just apply it like so:
$term_links[] = l($term->name, 'category/' . strtolower($term->name),

A: Please try
$term_links[] = l($term->name, 'category/' . strtolower($term->name),

It should work perfectly.


text:
Q: Convert byte array of base64 encoding back to ASCII I am working on a web application that displays questions contained in json format sent by a Java rest endpoint. The questions have a text element but can also containt attachments in binary form (e.g picture, or movie) (see screenshot1). On the server the data is defined in XML which is used to generate the Java Classes using the tool xjc.

Now the general part of the application (that is displaying the questions) works BUT Im having troubles showing the pictures with the data URL technique  because the base64 binary is stored as an array of bytes. So instead of ASCII characters I get signed integers when I feed the value attribute into the img tag:
(`<img src="data:image/jpeg;base64,-119,80,78,71,13`<img)

This is visible if I open the debug perspective on the Java endpoint and check the variable of a question (see screenshot2).

Now, my initial thought was to change the data type of value from byte[] to String but as I am merely extending the base64 type of XML I am doubting that this is a wise thing to do.
I'd be grateful for your thoughts on this
The xsd file for content which is an element of "attachment"
<xs:element name="content">
<xs:complexType>
    <xs:simpleContent>
        <xs:extension base="xs:base64Binary">
            <xs:attribute name="filename" type="xs:string" use="required"/>
            <xs:attribute ref="xml:lang"/>
        </xs:extension>
    </xs:simpleContent>
</xs:complexType>

An example definition of a question
<question id="q1" type="yesno">
    <text>Is the organizations...?</text>
    <attachments>
        <attachment id="q1a1pic" mime="image/jpeg">
            <content filename="image.jpg" xml:lang="de>iVB....cut....
            </content>
        </attachments>
    </attachments>
</question>

The generated class Content:
public class Content {

@XmlValue
protected byte[] value;

A: Turns out a custom XML Adapter was the missing puzzle piece. You can extend the javax.xml.bind.annotation.adapters XMLAdapter class and implements marshal() and unmarshal() to perform the transformation.
public class Base64Adapter extends XmlAdapter<byte[], String> {

  @Override
  public String unmarshal(byte[] v) throws Exception {
    return Base64.getEncoder().encodeToString(v);
  }

  @Override
  public byte[] marshal(String v) throws Exception {
    return Base64.getDecoder().decode(v);
  }
}

Afterwards, recompile the classes with xjc including the new Adapter in the bindings parameter: "xjc.exe" -d "app\platform\src\main\java" -b src/main/resources/XMLBinding.xjc -p example.company.com src\main\resources\model.xsd

See the API for more details.


text:
Q: Could not load qml included in qrc I am setting up a simple project, which uses qml, qrc and conf files
But it always failed when run engine.load(url), saying that main.qml does not exist.
cmake file is like following, project structure shows in the screenshot, is there anyother place that I need to check?
cmake_minimum_required(VERSION 3.16)

project(Qml-Material-Imp VERSION 0.1 LANGUAGES CXX)

set(CMAKE_AUTOMOC ON)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(Qt6 6.2 COMPONENTS Quick REQUIRED)

qt_add_executable(appQml-Material-Imp
    main.cpp
    qml.qrc
)

set_target_properties(appQml-Material-Imp PROPERTIES
    MACOSX_BUNDLE_GUI_IDENTIFIER my.example.com
    MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION}
    MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}
    MACOSX_BUNDLE TRUE
    WIN32_EXECUTABLE TRUE
)

target_compile_definitions(appQml-Material-Imp
    PRIVATE $<$<OR:$<CONFIG:Debug>,$<CONFIG:RelWithDebInfo>>:QT_QML_DEBUG>)
target_link_libraries(appQml-Material-Imp
    PRIVATE Qt6::Quick)

A: I managed to make it with qmake instead and stayed with it


text:
Q: Weird call of Class_Terminate I really don't know why this is happening:
This hier is a little presentation wrapper:
' Class PPTGenPresentation

Private m_Presentation As Presentation

Public Sub Class_Initialize()
    Set m_Presentation = Nothing
End Sub

Public Sub Class_Terminate()
    If Not m_Presentation Is Nothing Then
        m_Presentation.Close
    End If
End Sub

Public Sub Initialize(ByVal presentationPath As String)
    On Error GoTo Error

    Set m_Presentation = Presentations.Open(presentationPath, , , msoFalse)

    Exit Sub
Error:
    MsgBox ("Could not open " & presentationPath)
End Sub

Public Property Get Instance() As Presentation
    ' After this line Class_Terminate() gets called somehow ..
    Instance = m_Presentation
End Property

After I opened the ppt I want to access the actual presentation by accessing the property:
For Each filePath In filePaths
    Set safePresentation = New PPTGenPresentation
    safePresentation.Initialize (filePath)

    Dim tmp As Presentation
    Set tmp = savePresentation.Instance

    For Each oSlide In tmp.Slides
        Set oShape = oSlide.Shapes(1)

        If oShape.HasTextFrame Then
            If oShape.TextFrame.HasText Then
                MsgBox oShape.TextFrame
            End If
        End If
    Next
Next

But after accessing the property Instance, somehow Class_terminate gets called.
I have no idea why ths is happening. Could somebody explain to me what the problem is?

A: I have added comments to your code.
Basically, when you use set=new to overwrite an object (as happens in each subsequent iteration through your For Each loop) the previous object has either one of two situations from a theoretical standpoint:

*

*The reference is lost but the object exists and now creates a memory leak

*The object is automatically cleaned up and destroyed when the reference is gone

VBA automatically causes the second to be true. When you use "New" again, the first presentation no longer will have any way to refer to it, and so it is cleaned up and destroyed. This calls Class_Terminate
Just a note, in other languages without this sort of code you have now would start causing memory leaks (such as C++).
For Each filePath In filePaths
    'Each subsequent iteration the following basically happens:
    'when you set the presentation to a new one, you are effectively
    'ending the previous version. So for example, the following *basically* happens:

    ' if not safePresentation is nothing then set safePresentation=nothing

    Set safePresentation = New PPTGenPresentation
    safePresentation.Initialize (filePath)

    Dim tmp As Presentation
    Set tmp = savePresentation.Instance

    For Each oSlide In tmp.Slides
        Set oShape = oSlide.Shapes(1)

    Next
Next

To solve this, move Set safePresentation = New PPTGenPresentation above your For Each loop.

A: It gets called as you have a syntax error in your code and I suspect that you have On Error Resume Next in the calling code.
Public Property Get Instance() As Presentation
    ' After this line Class_Terminate() gets called somehow ..
    Instance = m_Presentation
End Property

Generates an error, which is suppressed by the resume next, try:
Public Property Get Instance() As Presentation
    ' After this line Class_Terminate() gets called somehow ..
    Set Instance = m_Presentation
End Property

You'd be much better off not suppressing errors, and certainly not when testing


text:
Q: If $x^2\equiv a\pmod n$, then $(n-x)^2\equiv a\pmod n$
Given that $x$ is a solution to $x^{2}\equiv a \pmod n$, show that $y=n-x$ is also a solution.

Please don't solve, just give me a hint.

A: Hint Expand $y^2 = (n - x)^2$ modulo $n$.
(This is perhaps easier to see intuitively if we recall that $$n - x \equiv -x \bmod n,$$ in which case we can write $$(-x)^2 \equiv a \bmod n,$$ which bears a close resemblance to the real analogue of the statement.)

A: Just expand $y^2=(n-x)^2$ and fill in the expression. The rest should be straightforward.

A: ${\rm mod}\ n\!:\ \color{#c00}{\overbrace{n\!-\!x}^{\large n \color{black}{ \,\equiv\,0}}\equiv -x}\Rightarrow (\color{#c00}{n\!-\!x})^2\equiv (\color{#c00}{-x})^2 \equiv x^2 \equiv a\ $ by   basic Congruence Rules.
Remark $\ $ Generally, by the linked congruence rules, congruences are preserved by replacing arguments of sums and products by any congruent argument.


text:
Q: Symfony messenger set prefetch_count for rabbitmq It is possible set option "prefetch_count"in symfony messenger?
I migrate from RabbitMqBundle to Symfony Messenger and not see this option.
RabbitMqBundle can configre it like below
consumers:
    upload_picture:
        connection:       default
        exchange_options: {name: 'upload-picture', type: direct}
        queue_options:    {name: 'upload-picture'}
        callback:         upload_picture_service
        qos_options:      {prefetch_size: 0, prefetch_count: 1, global: false}

But how to set prefetch_count in messenger.yml ?


text:
Q: GetBlob count for azure blob storage block file I have uploaded a 6 GiB file into Azure Blob storage Hot Tier, as 4 MiB blocks.
When I Put the file, it will create (6000/4) PutBlock * 1 PutBlockList call. which is 1501 API calls.
However, when I try to download the file, does it make 1500 GetBlob calls or just one GetBlob (or any other API calls) ?
What all are the API calls that happen when I try to download a large file of 4 MiB block size and how many of those API calls contribute to the cost?
I am not able to find a conclusive reference to this question in the documentation.

A: If you are  using BlobClient.download() method in JS SDK @azure/storage-blob, the method will always try to download a blob with one request. If the file is large, it may meet error with the request, then it will retry to continue on downloading from the end offset of downloaded content from the last request.


text:
Q: phpmailer prints long list of details (CLIENT -> SERVER) when sending email I have got a script working with PHPMailer.
When i run it to send an email, the PHPMailer send the email successfully.
But ALSO echo long list of email sending information (CLIENT -> SERVER) like:
SERVER -> CLIENT: 220-server.mywebsitese.com ESMTP Exim 4.84 #2 Tue, 27 Jan 2015 08:37:57 +0200 220-We do not authorize the use of this system to transport unsolicited, 220 and/or bulk e-mail.
CLIENT -> SERVER: EHLO www.mywebsite.com
SERVER -> CLIENT: 250-server.mywebsite.com Hello server.mywebsite.com [xx.xxx.xx.xx]250-SIZE 52428800250-8B9uLITMIME250-PIPELINING250-AUTH PLAIN LOGIN250-STARTTLS250 HELP
CLIENT -> SERVER: AUTH LOGIN
SERVER -> CLIENT: 334 VXNlcm5h9uLbWU6
CLIENT -> SERVER: bm9yZXBseUBsZWJh9uLbm9uLWxvdHRvLmNvbQ==
SERVER -> CLIENT: 334 UGFzc39uLdvcmQ6
.
.
.
.Very
.
.
.Long
.
.
.List of SERVER -> CLIENT / CLIENT SERVER
.
Message sent!

The script activated by:
            if (!$mail->send()) {
            echo "Mailer Error: " . $mail->ErrorInfo;
            } else {
            echo "Message sent!";

What I really want is to only send the email, print MESSAGE SENT, no need of this long list..
Is this easily done?
Thanks

A: This seems to be debug information. Try to disable debugging by setting SMTPDebug to 0 right after you have created an instance of PHPMailer:
$mail = new PHPMailer();
$mail->SMTPDebug = 0;

A: Use $mail->SMTPDebug = 0;, it worked for me!

A: PHPMailer has 4 levels for debugging. Debugging closes with 0.

*

*SMTP::DEBUG_OFF (0): Disable debugging (you can also leave this out completely, 0 is the default).

*SMTP::DEBUG_CLIENT (1): Output messages sent by the client.

*SMTP::DEBUG_SERVER (2): as 1, plus responses received from the server (this is the most useful setting).

*SMTP::DEBUG_CONNECTION (3): as 2, plus more information about the initial connection - this level can help diagnose STARTTLS failures.

*SMTP::DEBUG_LOWLEVEL (4): as 3, plus even lower-level information, very verbose, don't use for debugging SMTP, only low-level problems.

For more detailed information, you can view PHPMailer's official github account.


text:
Q: cocoapods framework much slower in my app than in example I don't think that it's specific to that framework, but with TOMSMorphingLabel it's very obvious: I saw that the animations are very slow on my iPhone 5 (no problems on my iPhone 7+) and then I tried out the example from the website: those animations ran smoothly as expected.
What could be the reason for this? There are no other operations running in the background, may that have to do something with Build Settings, the 32bit architecture or something like that?

A: TOMSMorphingLabel is working at expected speed in my iPhone5s , iPhone6 & iPhone7 even in simulator of iPhone5. I don't find any issue with the framework.
The speed may be slow due to low memory on your device or low processing capacity. Please try testing it in 5s. See if the problem is reproduced or not. If the speed gets slow in lower end devices like iPhone 5 then definitely the processor and memory of the device are at fault.

A: you can also have a look at LTMorphingLabel which may be more performant.
LTMorphingLabel
more performance than the other. :)


text:
Q: function calling a system call wrapper not pushed onto stack So, I was working with a typical project of mine. For that I wrote the following program:
/***************************demo.c*************************/
#include <stdio.h>
#include <unistd.h>
void foo(int x)
{
    getpid();
    open();
    getpid();

}
int main()
{
    int x;
    foo(10);
}

and I statically compiled it as follows:
$gcc -g -static demo.c -o demo

I tried to stack trace using gdb:
(gdb) list
1       /***************************demo.c*************************/
2       #include <stdio.h>
3       #include <unistd.h>
4       void foo(int x)
5       {
6           getpid();
7           open();
8           getpid();
9
10      }
(gdb)
11      int main()
12      {
13          int x;
14          foo(10);
15      }
(gdb) start
Temporary breakpoint 1 at 0x401773: file demo.c, line 14.
Starting program: /home/abhishek/Documents/Security_Project/bin/backend_v2/demo

Temporary breakpoint 1, main () at demo.c:14
14          foo(10);
(gdb) s
foo (x=10) at demo.c:6
6           getpid();
(gdb) backtrace
#0  foo (x=10) at demo.c:6
#1  0x000000000040177d in main () at demo.c:14
(gdb)

But to my astonishment, why isn't something like the following shown?
#   0x0000000000401759 in foo (x=10) at demo.c:6

I tried to use ptrace(PTRACE_PEEKDATA,... and ptrace(PTRACE_GETREGS,... to get hold of rip, and rbp and then peeking into memory of attached child process as follows:
long return_addr=ptrace(PTRACE_PEEKDATA, pid,regs.rbp+8,0);
    long next_rbp=ptrace(PTRACE_PEEKDATA, pid, regs.rbp,0);
    while(next_rbp>0){
        // printf("rbp  = 0x%lx", next_rbp);
        // getchar();
        printf("0x%lx\t", return_addr);
        addr_on_stk.insert(return_addr);
        return_addr=ptrace(PTRACE_PEEKDATA, pid, next_rbp+8,0);
        next_rbp=ptrace(PTRACE_PEEKDATA, pid, next_rbp,0);
    }

To which I get the following output during the first iteration stopping at the first system call, (ignoring the initial 14 syscall made to setup the program, I mean stopping it at getpid syscall)
Trace back of the addresses on stack is as follows:
0x44673b
0x40177d
0x401bba

apparently what I see is :
Dump of assembler code for function getpid:
   0x0000000000446730 <+0>:     endbr64
   0x0000000000446734 <+4>:     mov    $0x27,%eax
   0x0000000000446739 <+9>:     syscall
   0x000000000044673b <+11>:    ret  <----------------------- first address
End of assembler dump.

Dump of assembler code for function main:
   0x000000000040176b <+0>:     endbr64
   0x000000000040176f <+4>:     push   %rbp
   0x0000000000401770 <+5>:     mov    %rsp,%rbp
   0x0000000000401773 <+8>:     mov    $0xa,%edi
   0x0000000000401778 <+13>:    call   0x401745 <foo>
   0x000000000040177d <+18>:    mov    $0x0,%eax     <-------------- second address
   0x0000000000401782 <+23>:    pop    %rbp
   0x0000000000401783 <+24>:    ret
End of assembler dump.

   0x401bba <__libc_start_call_main+106>:       mov    %eax,%edi
(gdb) disassemble __libc_start_call_main
Dump of assembler code for function __libc_start_call_main:
   0x0000000000401b50 <+0>:     push   %rax
   0x0000000000401b51 <+1>:     pop    %rax
   0x0000000000401b52 <+2>:     sub    $0x98,%rsp
   0x0000000000401b59 <+9>:     mov    %rdi,0x8(%rsp)
   0x0000000000401b5e <+14>:    lea    0x20(%rsp),%rdi
   0x0000000000401b63 <+19>:    mov    %esi,0x14(%rsp)
   0x0000000000401b67 <+23>:    mov    %rdx,0x18(%rsp)
   0x0000000000401b6c <+28>:    call   0x409ed0 <_setjmp>
   0x0000000000401b71 <+33>:    endbr64
   0x0000000000401b75 <+37>:    test   %eax,%eax
   0x0000000000401b77 <+39>:    jne    0x401bc1 <__libc_start_call_main+113>
   0x0000000000401b79 <+41>:    mov    %fs:0x300,%rax
   0x0000000000401b82 <+50>:    mov    %rax,0x68(%rsp)
   0x0000000000401b87 <+55>:    mov    %fs:0x2f8,%rax
   0x0000000000401b90 <+64>:    mov    %rax,0x70(%rsp)
   0x0000000000401b95 <+69>:    lea    0x20(%rsp),%rax
   0x0000000000401b9a <+74>:    mov    %rax,%fs:0x300
   0x0000000000401ba3 <+83>:    mov    0xca686(%rip),%rdx        # 0x4cc230 <environ>
   0x0000000000401baa <+90>:    mov    0x14(%rsp),%edi
   0x0000000000401bae <+94>:    mov    0x18(%rsp),%rsi
   0x0000000000401bb3 <+99>:    mov    0x8(%rsp),%rax
   0x0000000000401bb8 <+104>:   call   *%rax
   0x0000000000401bba <+106>:   mov    %eax,%edi   <------------------------third address
   0x0000000000401bbc <+108>:   call   0x40aa80 <exit>
   0x0000000000401bc1 <+113>:   call   0x414520 <__nptl_deallocate_tsd>
   0x0000000000401bc6 <+118>:   lock decl 0xc3b33(%rip)        # 0x4c5700 <__nptl_nthreads>
   0x0000000000401bcd <+125>:   sete   %al
   0x0000000000401bd0 <+128>:   test   %al,%al
   0x0000000000401bd2 <+130>:   jne    0x401be8 <__libc_start_call_main+152>
   0x0000000000401bd4 <+132>:   mov    $0x3c,%edx
   0x0000000000401bd9 <+137>:   nopl   0x0(%rax)
   0x0000000000401be0 <+144>:   xor    %edi,%edi
   0x0000000000401be2 <+146>:   mov    %edx,%eax
   0x0000000000401be4 <+148>:   syscall
   0x0000000000401be6 <+150>:   jmp    0x401be0 <__libc_start_call_main+144>
   0x0000000000401be8 <+152>:   xor    %edi,%edi
   0x0000000000401bea <+154>:   jmp    0x401bbc <__libc_start_call_main+108>
End of assembler dump.
(gdb)

All the return addresses foo is found.
My question is when the getpid syscall is intercepted, it is down in the glibc wrapper of getpid as shown. But why isn't the function foo's frame formally placed on the stack?
[I mean, by the time is syscall is intercepted by PTRACE, push rbp instruction should have been performed and rbp should point to the old rbp on stack and just below it (i.e. rbp+8), shall have the return address of getpid for foo().]

A:
But to my astonishment, why isn't something like the following shown?
#   0x0000000000401759 in foo (x=10) at demo.c:61

That is a GDB artifact -- it doesn't show the pc for the frame if that frame has debug info and and you are stopped at the beginning of the line.
If you do catch syscall getpid and do backtrace from there, you would see:
(gdb) bt
#0  0x000000000044353b in getpid ()
#1  0x0000000000401665 in foo (x=10) at demo.c:5
#2  0x0000000000401685 in main () at demo.c:13

Compare with the output from lldb:
(lldb) bt
* thread #1, name = 'a.out', stop reason = breakpoint 1.1
  * frame #0: 0x0000000000401660 a.out`foo(x=10) at demo.c:5:5
    frame #1: 0x0000000000401685 a.out`main at demo.c:13:5
    frame #2: 0x0000000000401a0a a.out`__libc_start_call_main + 106
    frame #3: 0x00000000004030b7 a.out`__libc_start_main_impl + 2327
    frame #4: 0x0000000000401555 a.out`_start + 37

Also, if you compile your code without -g and break on foo, you would see this:
Breakpoint 1, 0x0000000000401659 in foo ()
(gdb) bt
#0  0x0000000000401659 in foo ()
#1  0x0000000000401685 in main ()

But why is the function foo's frame formally placed on the stack?

I think you mean: why isn't foos frame placed on the stack.

I mean, by the time is syscall is intercepted by PTRACE, push rbp instruction should have been performed and rbp should point to the old rbp on stack and just below it (i.e. rbp+8), shall have the return address of getpid for foo()

What you expect would have happened IFF the getpid wrapper used a frame pointer (i.e. had the push %rbp; mov %rsp,%rbp in its prolog). But it doesn't (as is clear from disassembly), and so the rbp value just before the actual getpid system call is the same as it was in foo.


text:
Q: Getting error while trying to install Hyperic server I am trying to install the latest version of Hyperic (4.6.6) on centos machine and getting this error.
>        /home/hq/agent-4.6.6/bin/hq-agent.sh start Installing the server... Unpacking server to: /home/hq... Creating server
> configuration files... Using "small" installing profile... Copying
> binaries and libraries to server installation... Copying server
> configuration file... Copying server db-upgrade files... Copying
> server libs... Setting up server database... Loading taskdefs...
> Taskdefs loaded Loading taskdefs... Taskdefs loaded
> -------------------------------------------------------------------------------- An ERROR occurred, the installation cannot continue. FATAL EXCEPTION
> at /home/hq/hyperic-hq-installer-4.6.6/installer/data/setup.xml:523: :
> The following error occurred while executing this line:
> /home/hq/hyperic-hq-installer-4.6.6/installer/data/setup.xml:532: The
> following error occurred while executing this line:
> /home/hq/hyperic-hq-installer-4.6.6/installer/data/setup.xml:777: The
> following error occurred while executing this line:
> /home/hq/hyperic-hq-installer-4.6.6/installer/data/setup-db-MySQL.xml:16:
> The following error occurred while executing this line:
> /home/hq/hyperic-hq-installer-4.6.6/installer/data/setup-db-hibernate.xml:94:
> org.hibernate.tool.hbm2x.ExporterException: Errors while performing
> Hbm2DDLExporter
> -------------------------------------------------------------------------------- Deleting temporary JRE

I have already looked for the DB connection and everything is fine. I tried to google search, but didn't find any help anywhere.
I know you might need more info, so feel free to comment and I will update whatever I can.

A: The problem was with the Mysql Version.
I was using mysql version 5.5 and Hyperic somehow wasn't supporting it.
I tried the installation with the Mysql Version 5.1, and it worked like charm.
Hope this post will help someone who is trying to get a solution for this.


text:
Q: Calculating haystack size of a string I want to create a poor-mans version of a password complexity checker. I determine the rough character set the password is using and its length. The search space would then be: charset ^ length. In order to compare this against a single value I want the smallest x that when used as the exponent of 2 is larger than the search space. In more mathy language I want this:
given a and b find the smallest x where a^b < 2^x;
My math sucks. Is there a quick and easy way to calculate this?

A: Maybe my math doesn't suck quite that much.
  2^x == a^b
= define a = 2^c, c = 2loga
  2^x == 2^c^b
=
  2^x == 2^c*b
=
  x == c*b
=
  x == 2loga * b

A: You can solve the equation by using logarithms. Taking the logarithms on both sides yields
x > b * log(a) / log(2)

If you want to find the smallest integer such that the equation holds we can round up the right hand side. In python this can be implemented as
import math

def find_x(a, b):
    return math.ceil(b * math.log(a) / math.log(2))


text:
Q: How to find out if a given resource of a JID is online/offline with smack How can I tell that a juliet@verona.it/balkony (full JID!) is online/still available with smack?

A: Subscribe to juliet@verona.it's presence, go online by sending your own presence in, and see if you get a presence stanza back.  Querying for presence doesn't actually make much sense; think of it as stepping into the flow of juliet's presence at a certain point in time.