text:
Q: I'm getting an error in my android app where it crashes after I press the button I tried implementing a fix that I had followed but go no results, I'm pretty sure it's something small that I'm just not seeing. This is the error from logcat
FATAL EXCEPTION: main
                                                                          Process: com.example.ramos.nester, PID: 11297
                                                                          java.lang.IllegalStateException: Could not find method retrieve (MainActivity)(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'guibutt'
                                                                              at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
                                                                              at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
                                                                              at android.view.View.performClick(View.java:4492)
                                                                              at android.view.View$PerformClick.run(View.java:18568)
                                                                              at android.os.Handler.handleCallback(Handler.java:733)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                              at android.os.Looper.loop(Looper.java:136)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5021)
                                                                              at java.lang.reflect.Method.invokeNative(Native Method)
                                                                              at java.lang.reflect.Method.invoke(Method.java:515)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:827)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:643)
                                                                              at dalvik.system.NativeStart.main(Native Method)
Code
    package com.example.ramos.nester;

import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    public void insert(View view) {
        // Add the code that you want
        // Or do nothing if you want
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void retrieve(View v) {

        Button guibutt = (Button) findViewById(R.id.guibutt);
        TextView software = (TextView) findViewById(R.id.software);
        TextView name = (TextView) findViewById(R.id.name);
        TextView last = (TextView) findViewById(R.id.last);
        TextView device = (TextView) findViewById(R.id.device);
        TextView battery = (TextView) findViewById(R.id.battery);

        final String auth = "Bearer c.I1LDweqMS6Fdc3c2gLPcH8Z1W0B6dDVOXDQ9WYZYdyjoULoUubiB59cGn03mDPmXvaJv1i0Qg2H1mHA3QTmdwKOU9BVePV9MfQgKTcAuNnjddtTgIWR7Ngcz6d7ED7d14whkNuTAE3EC7uS4"; // Update with your token

        OkHttpClient client = new OkHttpClient.Builder()
                .authenticator(new Authenticator() {
                    @Override
                    public Request authenticate(Route route, Response response) throws IOException {
                        return response.request().newBuilder()
                                .header("Authorization", auth)
                                .build();
                    }
                })
                .followRedirects(true)
                .followSslRedirects(true)
                .build();

        Request request = new Request.Builder()
                .url("https://developer-api.nest.com")
                .get()
                .addHeader("content-type", "application/json; charset=UTF-8")
                .addHeader("authorization", auth)
                .build();
        try {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

            StrictMode.setThreadPolicy(policy);
            Response response = client.newCall(request).execute();

            JSONObject json = new JSONObject(response.body().string());
            JSONObject devices = json.getJSONObject("devices");
            JSONObject smoke_co_alarms = devices.getJSONObject("smoke_co_alarms");
            JSONObject alarm = smoke_co_alarms.getJSONObject("pBQ6G56_J-C-VMTeIri1Zl3BtVDjEvJ-");

            String softwaretexterino = alarm.getString("software_version");
            String nametexterino = alarm.getString("name");
            String lasttexterino = alarm.getString("last_connection");
            String devicetexterino = alarm.getString("device_id");
            String betterytexterino = alarm.getString("battery_health");

            software.setText(softwaretexterino);
            name.setText(nametexterino);
            last.setText(lasttexterino);
            device.setText(devicetexterino);
            battery.setText(betterytexterino);

            Thread.sleep(2 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    View.OnClickListener myOnlyhandler = new View.OnClickListener() {
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.guibutt:
                    break;
            }
        }
    };
}

XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        tools:context="com.example.nestapp.MainActivity">

    <Button
            android:text="Click Me For Information"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="36dp" android:id="@+id/guibutt" android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true" android:onClick="retrieve (MainActivity)"/>
    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/software"
            android:layout_marginTop="45dp"
            android:text="Software Version" android:layout_below="@+id/last"
            android:layout_centerHorizontal="true"/>
    <TextView
            android:text="Device ID"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="45dp" android:id="@+id/device" android:layout_above="@+id/battery"
            android:layout_centerHorizontal="true"/>
    <TextView
            android:text="Name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="38dp" android:id="@+id/name"
            android:textAlignment="center"
            android:layout_centerInParent="false" android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"/>
    <TextView
            android:text="Battery Health"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="53dp" android:id="@+id/battery"
            android:layout_above="@+id/last" android:layout_centerHorizontal="true"/>
    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/last"
            android:text="Last Time Period of Connection"
            android:layout_centerVertical="true" android:layout_centerHorizontal="true"/>
</RelativeLayout>

A: I'm new here and my experience with Android is somewhat limited. However, I think that without posting your code it is more difficult to tell what is causing the crash (at least for someone like me).  Adding your code might motivate other people to help you.

A: From what I can figure out from the code you have posted above, this error is popping up due to unavailability of onClick method. I faced a similar problem once where had made use of View class and not used onClick method. Try adding setOnClickListener function in place of retrieve function. It should resolve your error. This is the syntax to make use of View class and OnClick method to detect button click.
btn = (Button)findViewById(R.id.firstButton);
btn.setOnClickListener(new View.OnClickListener()
{
    @Override
    public void onClick(View v)
    {
        //Code goes inside this function.
    }
});

If this does not help, it would be better if you post the XML code of the activity also.


text:
Q: Битрикс: не отображать определенное свойство в детальном просмотре новости Для div'a галереи в детальном просмотре новости нужно устанавливать значение аттрибута data-count из свойства "Сколько фото ставить в ряд?" (MORE_PHOTO_COUNT).
В параметрах компонента в Настройках детального просмотра в поле "Свойства" выбрал это свойство, но мне не нужно, чтобы оно отображалось на странице детального просмотра новости.
"DETAIL_PROPERTY_CODE" => array(
    0 => "ASSIGNMENT",
    1 => "SOLUTION",
    2 => "SERVICES",
    3 => "MORE_PHOTO_COUNT",
    4 => "",
),

Код вывода свойств такой:
<?foreach($arResult["DISPLAY_PROPERTIES"] as $pid=>$arProperty):?>

    <?=$arProperty["NAME"]?>:
        <?if(is_array($arProperty["DISPLAY_VALUE"])):?>
            <?=implode(" / ", $arProperty["DISPLAY_VALUE"]);?>
        <?else:?>
            <?=$arProperty["DISPLAY_VALUE"];?>
        <?endif?>

    <?endforeach?>

Помимо этого свойства есть 3 других, и они должны отображаться. См.скриншот.
Как это сделать правильно?
В файле template.php код подстановки значения для аттрибута data-count такой
<div class="gallery" data-count="<?echo $arResult['DISPLAY_PROPERTIES']['MORE_PHOTO_COUNT']['DISPLAY_VALUE'];?>">
<?
        if(count($arResult["MORE_PHOTO"])>0):?>
        <?foreach($arResult["MORE_PHOTO"] as $PHOTO):?>
<a class="fancybox" data-rel="group" href="<?=$PHOTO["SRC"]?>"  title="<?=$arResult["NAME"]?>"><img alt="<?=$arResult["NAME"]?>" src="<?=$PHOTO["SRC"]?>" title="<?=$arResult["NAME"]?>">
        <?endforeach?>
    <?endif?>

Также добавил файл result_modifier.php, в нем такой код:
<?
$APPLICATION->SetTitle("");
?><?if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();

$arResult["MORE_PHOTO"] = array();
   if(isset($arResult["PROPERTIES"]["MORE_PHOTO"]["VALUE"]) && is_array($arResult["PROPERTIES"]["MORE_PHOTO"]["VALUE"]))
   {
      foreach($arResult["PROPERTIES"]["MORE_PHOTO"]["VALUE"] as $FILE)
      {
         $FILE = CFile::GetFileArray($FILE);
         if(is_array($FILE))
            $arResult["MORE_PHOTO"][]=$FILE;
      }
   }
?>

A: если нужно использовать значение\параметр свойства, которое не нужно отображать, то пользуйтесь массивом PROPERTIES.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to dynamically overlay a set of grouped images from some folder Suppose that we have a dataset of images where each image has the following structure:
foo1.png
foo1_cloud.png
foo1_full.png

foo2.png
foo2_cloud.png
foo2_full.png

...

Now, imagine that those images are all on a somePath folder, our issue is as follows. We want to take those sets of images (i.e., the sets of foo1 or foo2 images), and overlay the images (e.g., foo1.png, foo1_cloud.png and foo1_full.png). However, we would like to do this in a dynamic way. So that, for instance, each time we press a Next or Previous button we can iterate our image dataset across our somePath/ folder.
At the moment, what we have is:

<!doctype html>

  <meta charset="utf-8">

  <title>Title</title>
  <meta name="description" content="Content">
  <meta name="author" content="Content">

  <link rel="stylesheet" href="styles/index.css">

 ‹

 ›

First of all, we need to query each image from the somePath/ folder with respect to the file name. Therefore, we need to guarantee the file names (e.g., <filename>.png, <filename>_cloud.png and <filename>_full.png), so that we can overlay the three files. Second, we need to provide the behaviour of the file update for the next or the previous file names.
So, our question is as follows:
How can we dynamically overlay a set of grouped images from a folder?


text:
Q: Duplicate entries in apache solr index upon reindexing in Drupal I am using apache solr search integration on my Drupal 6 website: govoluntourism.com. I have my search results themed using views and a search-result.tpl.php file.
The search-result.tpl.php contains:
$nid = $result['fields']['nid']['value'];
echo views_embed_view($name = 'search', $display_id = 'default', $nid);

When I add content to my site and run cron, it seems that duplicate entries are being made in the apache index, because I am getting duplicates in the search results only of the content that was previously indexed.
Is this a server-side issue or a mistake in my configuration? Not sure where to go from here.
thanks.
the site is: govoluntourism.com

A: I looked at your site and the duplicate search results all point to the same nodes, so that means you probably don't have actual duplicate content.
The first thing to do if you suspect your index is corrupt and you can't find the problem, is probably to reindex all of your content. You can do that by going here: http://govoluntourism.com/admin/settings/apachesolr/index.
Next, you can choose "Delete the Index", then "Re-index All Content". What this will do is rebuild your entire index from scratch. Note that if you choose "Re-Index All Content", it will happen immediately. If you have cron running, cron will slowly rebuild the index, which will use less resources but take much longer.
Once you have done that you'll have a better idea of what's going on.
If that doesn't work then you probably have an issue with the search results theme customization.

A: Have you tried to query Solr directly? If you have duplicate there, the problem is that you are importing the content duplicate.


text:
Q: Fundamental group of $\mathbb{R}^n\backslash \{0\}$ I am wondering about what the fundamental group of $\mathbb{R}^n \backslash \{0\}$ or more generally $\mathbb{R}^n \backslash U$ where $U$ is a subset of $\mathbb{R}^n$ for $n>1$. For $n=1$ I understand that the fundamental group is not trivial since the resulting space is not simply-connected. In all other case though the space is simply connected. Thus, logic says that the fundamental group is trivial. Therefore how do we classify spaces that we subtract various points out of them. E.g. how we can tell the difference between $\mathbb{R}^n \backslash U$ and $\mathbb{R}^n \backslash V$ for different sets $U,V$ (with different number of elements as well)? Is this the reason we need homology?

A: For $n = 1$, the space $\mathbb{R} \setminus \{0\}$ is the disjoint union of two intervals, so both connected components are contractible and have trivial fundamental group.
When $n = 2$, you can see that $\mathbb{R}^2 \setminus \{0\}$ deformation retracts onto $$S^1 = \{ (x,y) \in \mathbb{R}^2 : x^2 + y^2 = 1 \},$$
the retraction being $z \mapsto \frac{z}{\|z\|}$. This is the standard circle, in particular its fundamental group is $\mathbb{Z}$ as usual. This space is not simply connected as you claimed.
More generally, the space $\mathbb{R}^n \setminus \{0\}$ deformation retracts onto
$$S^{n-1} = \left\{ (x_1, \dots, x_n) \in \mathbb{R}^n : \sum x_i^2 = 1 \right\}.$$
This is the standard $n$-sphere, and it's a classical exercise that this space is simply connected when $n > 2$.
Now when $U \subset \mathbb{R}^n$ is an arbitrary set, even open, you cannot say anything at all about the fundamental group of $\mathbb{R}^n \setminus U$, and not even its homology, without knowing anything about $U$. Indeed it's a theorem of Whitehead that any closed manifold embeds into $\mathbb{R}^n$ for some $n$; if you take $U$ to be the complement of the image of the embedding, you can see that $\mathbb{R}^n \setminus U$ can have pretty much any fundamental group or homology you can imagine (there are some restrictions for closed manifolds of course, but you can imagine even more exotic spaces).

Compared to simply the fundamental group, homology also allows you to detect higher dimensional structure of your space: $\pi_1$ doesn't distinguish the $n$-spheres $S^n$ for $n \ge 2$, but these spaces are intrinsically very different. But the higher homotopy groups $\pi_n$ also detect higher dimensional structure, and do distinguish the $n$-spheres.
From my perspective, the main reason you want to use homology instead of (or in addition to) homotopy groups is because of the Mayer–Vietoris exact sequence, an analog of the Seifert–van Kampen theorem for homology. This allows you to break up your space in smaller pieces. See this question and its excellent answer by Ronnie Brown.

A: You are right, in higher dimensions ($n>2$) the (first) fundamental group of $\mathbb{R}^n$ minus a point is trivial. This is, however, not true for the removal of an arbitrary subset. Think of removing a tubular shape or just a circle from $\mathbb{R}^3$.
Other means of classification are so called higher homotopy groups, where you look at homotopy classes of maps from spheres of any dimension into the space you want to classify. See (almost) any book on algebraic topology.


text:
Q: Coupon API Soap I've a problem with the Coupon API when i make :
$couponCode = "test";

$resultCartCoupon = $proxy->call($sessionId, "cart_coupon.add", array($shoppingCartId, $couponCode));

I always got :
Uncaught SoapFault exception: [1083] Coupon is not valid

if i try the coupon code in the front end there is no problem.
Is there anyone who have ever used this API part with success ?

A: I tried to apply a coupon code via SOAP API and it worked.
Make sure the values you send are valid.
Here is my code:
<?php
$client = new SoapClient('http://magentoroot/api/soap/?wsdl');

$session = $client->login('apiUser', 'apiKey');

$cartId = 29; //make sure this quote exists
$code = 'test'; //make sure this exists and is active on the website with the quote
//apply coupon
$result = $client->call($session, 'cart_coupon.add', array($cartId, $code));

// If you don't need the session anymore
$client->endSession($session);

A:  <?php
 $mage_url = 'http://yoursiteurl/api/soap?wsdl';
 $mage_user= "API_User"; //webservice user login
 $mage_api_key = "API_PASSWORD"; //webservice user pass
 $client = new SoapClient($mage_url);

 $couponCode = 'couponCode'; // a coupon to be apply
 $shoppingCartId = '35'; // a cart Id which i have put test id
 $sessionId = $client->login($mage_user, $mage_api_key);
 $result = $client->call($sessionId,'cart_coupon.add',array($shoppingCartId,$couponCode));

 print_r($result);
?>

The above code gives error that "Uncaught SoapFault exception: [1083] Coupon is not valid". When i debug the core code i came to know that magento cart.create API insert wrong store id in sales_flat_quote table. I have changed the store id value in sales_flat_quote table manually and again run the Coupon API and after that it works perfectly. So here is the my solution. When you create cart id just run the below update query to change the store id.
<?php
 $shoppingCartId = $soap->call( $sessionId, 'cart.create');

 $mageFilename = '../app/Mage.php';
 require_once $mageFilename;
 umask(0);
 Mage::app();

 $db_write1 = Mage::getSingleton('core/resource')->getConnection('core_write');
 $updateQue  = "update sales_flat_quote set store_id='1' where entity_id ='".$shoppingCartId."'";
 $db_write1->query($updateQue);

 // Now run the Coupon API here
?>

Code taken from here : http://chandreshrana.blogspot.com/2015/11/uncaught-soapfault-exception-1083.html


text:
Q: lambda command to give an argument depending on what button is pressed I have a function that searches a directory for .json files. I then have a button created for each .json file found (there is no set number of files). What I want to do if for a user to press the button which contains the file they want to use.
The code i have to try and achieve this is below:
    numLink = 0
    for i in list_of_json_files:
        basename = os.path.basename(str(i))
        filename = os.path.splitext(basename)[0].replace("_", " ")
        Button(loadCreate, text=filename.title(), command=lambda: open_use_existing_rink_book(numLink), pady=5, padx=5).grid(row=n, column=1, pady=5)
        n += 1
        numLink += 1
        print(numLink)

What I thought this would do is give each button a different number for the argument for the function open_use_existing_rink_book(), therefore allowing me to distinguish the button pressed. E.g. if there are 3 .json files (json1, json2, json3) if I click the button that has json2 as the text I want to know that that button has been pressed.
The only other way in which I can think of doing it is by passing the text of the button as the argument for open_use_existing_rink_book(), but I'm not sure how I would do this, maybe with a text variable?

A: You were almost there. The way you are doing it it will always pass the final value of numLink. You have to change your lambda to the below for it to work.
lambda nl=numLink: open_use_existing_rink_book(nl)

The reason why is simple. In your version you are just passing a reference of numLink to your function so, all calls will be to whatever numLink's ultimate value is. In the version I showed you the current value of numLink is being stored in nl and that value is being passed to your function.

A: Ill just add an answer here, because its too long for the comments. Have you tried using the enumerate() function?
for index,i in enumerate(list_of_json_files):
    basename = os.path.basename(str(i))
    filename = os.path.splitext(basename)[0].replace("_", " ")
    Button(loadCreate, text=filename.title(), command=lambda i=index: open_use_existing_rink_book(i), pady=5, padx=5).grid(row=n, column=1, pady=5)
    n += 1
    print(index)

With this you can get rid of numLink as its the exact same thing. Also i dont know why your using n here as its undefined in the code you gave. Anyway keep in mind, you can replace n with index too.
The purpose of enumerate() is, it creates number for each item of the list, so you dont have to go on like a while loop. You can specify the starting number by enumerate(lst,start=1), here it will start the count from one.
Hope this helped you out, do let me know if any errors or doubts.
Cheers


text:
Q: SpriteKit - SKEffectnode Blendmode, Rasterisation, and Frame Rate I'm trying to do some simple lighting in a side scrolling game using an SKEffectnode.
First I make a fullscreen sprite node with gray color, set it's blend mode to additive, and add it as a child to the effect node. Then I add sprite nodes with some light texture, also as children of the effect node. Finally I set the effect node's blend mode to multiply, and add it as a child to my scene. Something like this:
SKEffectNode *effectNode = [[SKEffectNode alloc] init];
SKSpriteNode *overlay = [SKSpriteNode spriteNodeWithColor: [SKColor grayColor] size: [self.size];
SKSpriteNode *light = [SKSpriteNode spriteNodeWithImageNamed: @"LightTexture.png"];
[overlay setBlendMode: SKBlendModeAdd];
[light setBlendMode: SKBlendModeAdd];
[effectNode addChild: overlay];
[effectNode addChild: light];
[effectNode setBlendMode: SKBlendModeMultiply];
[self addChild: effectNode];

So my problem is that the effect node's blend mode doesn't seem to be doing anything. Like it's stuck in alpha blend mode or something. However, if I set shouldRasterize to YES, the blend mode starts working like expected. Does anyone know why this is?
Also adding a fullscreen effect like this, with an effect node, totally destroys the frame rate. Especially if you start moving the effect node (or create a new one every frame). But i don't see any other way of doing lighting like this in sprite kit. I basically want to create a lighting mask every frame, and then multiply it to the scene's frame buffer. Is something like this possible using Sprite Kit? Or should I look into Cocos2d using custom shaders?


text:
Q: Ubuntu showing only 256mb of vram when it should be 1GB I'm having serious problems with my ATI Mobility Radeon HD 5650 (1024mb VRAM). I tried using the "official" proprietary ATI drivers, they bug out the screen and the video card is not even recognized. I'm currently running the default X.org drivers, which recognize it, but only use 256mb of it's VRAM:
01:00.0 VGA compatible controller: Advanced Micro Devices [AMD] nee ATI Madison [Radeon HD 5000M Series] (prog-if 00 [VGA controller])
        Subsystem: Acer Incorporated [ALI] Device 036d
        Flags: bus master, fast devsel, latency 0, IRQ 43
        Memory at a0000000 (64-bit, prefetchable) [size=256M]
        Memory at b4000000 (64-bit, non-prefetchable) [size=128K]
        I/O ports at 3000 [size=256]
        Expansion ROM at b4040000 [disabled] [size=128K]
        Capabilities: [50] Power Management version 3
        Capabilities: [58] Express Legacy Endpoint, MSI 00
        Capabilities: [a0] MSI: Enable+ Count=1/1 Maskable- 64bit+
        Capabilities: [100] Vendor Specific Information: ID=0001 Rev=1 Len=010 <?>
        Kernel driver in use: radeon
        Kernel modules: radeon

I really notice some lack of video performance due to this fact. Is there any fix out there that can make Ubuntu use the full potential of my card. Please help!
PS: Further info I'm using the latest build of Ubuntu 12.10 64bit


text:
Q: Using a const inside of a class - static vs not static I have been trying to use a const as the size of an array inside a class declaration.  I know it works if I use a static const, but I am having trouble understanding why exactly.  More specifically, why can I use const for some data members in a class, but must specify static const for others, as follows:
class Test
{
public:
   static const int size = 10;   // 1. Works. Must be static to use it as size of array
   const int alpha = 20; // 2. Works, but cannot use as size of an array
   const double beta = 10.0; // 3. Works
   static const double gamma = 20.0; // 4. does not compile

   int table[size];  // Works with size, but not alpha
};

I have read many explanations, but have not found an one (or at least one I understand) specifically for what makes case 1 different from case 4, and why I need to make the const static for the array.
Can anyone shed some light on this?
Edit: I'm using VS 2013 if that makes a difference

A: The difference is that:
const int alpha = 20;

is specifying that 20 is the default value which an object's alpha would get if you don't specify any other value.  However the class could easily have a constructor that overrides this, e.g.:
// header file:
struct S
{
    S();
    S(int);
    const int alpha = 20;
};

// .cpp file
S::S(int): alpha(30) { }
S::S(): alpha(40) {}

So the value of alpha could in fact be different for different objects. This means that the size of the object cannot depend on it, because all objects of the same type must have the same size and layout.
However in the case static const int size = 10;, this specifies right then and there that size does have value 10 and nothing later on can supersede this; so this can be used as array sizes and so on.  There is only a single size variable which is separate to any objects of the class.

A:
but have not found an one (or at least one I understand) specifically for what makes case 1 different from case 4,

An array size can only be an integral expression can be computed at compile time. Since gamma is of type double, you cannot use it as the size of an array.

why I need to make the const static for the array.

A non-static member exists only as a member of an object of the class. Its  value is not usable without an object of the class. That throws up a catch-22 situation. You can't define the class without the size. You can't get the size without an object. A static member solves that problem.

A: C++ doesn't allow non-constant values for the size of an array. That's just the way it was designed. Array's size must be determined at compile time.
If you want a dynamically sized array, you need to allocate memory for it (and free it with delete when you're done).


text:
Q: Siri is called repeatedly out of control I face a problem with Iphone 6.
In the middle of work (particularly listening to podcasts), Siri wrongly thinks she is being called, pauses the main work, and starts asking for order.
Edit: "Hey Siri" is not allowed in my settings.

*

*Is it a hardware or software problem?

*Is this a common problem?

*A suggestion for a good way to solve it?


text:
Q: Visual Studio 2022 - ASP.net - Error Creating Control ajax Toolkit ... Page Design I have a Visual Studio 2022 ASP.net application that now displays "Error Creating Control ajax Toolkit" when viewing the Page Design:-

The application references the AjaxControlToolKit:-

And the path is pointing to the Ajax install path:-

The application builds and runs but when viewing the design page I get the "Error Creating Control" messages.
This seems to have started very recently.
Any ideas why?
tia

A: Just to add to my original question It appears that the "Web Live Preview" was the issue.
I set the option back to "Legacy Web Forms Designer" and it seems ok.
I found this similar post here


text:
Q: How to Adapt RecyclerView to D-Pad I am attempting to adapt Android's RecyclerView to a D-Pad for TV use. I am stuck in that I am not sure when to start in the first place. Any input/solutions would be appreciated.
I have tried doing the 'android:focusablle=true' already.


text:
Q: How to solve the transcendental equation $\frac{\zeta'(\alpha)}{\zeta(\alpha)}=-\frac{1}{n}\sum_{i=1}^n\ln x_i$ How can I solve the transcendental equation:
$$\frac{\zeta'(\alpha)}{\zeta(\alpha)}=-\frac{1}{n}\sum_{i=1}^n\ln x_i,$$
where $\displaystyle\zeta(\alpha)=\sum_{m=1}^\infty m^{-\alpha}\;\;\;?$ The values $x_i \in \{1, 2, 3, ..., 63, 64\}$ are given so the solution we are looking for, is $\alpha^*$ that satisfies this equation. This equation is from Clauset's et al paper: "Power-law distributions in empirical data". In other words the problem is: Solve $\alpha$ that satisfies:
$$\frac{\zeta'(\alpha)}{\zeta(\alpha)}=C,$$
where $C$ is constant.
What methods / algorithms should I use? I've been told this should be solved numerically, but I don't explicitly know what method I should use. This equation arises from solving the parameters of discrete power-law distribution.

A: There are no analytical solution to your equation so you must use some numerical scheme. There are many methods to find roots of a function. The simplest one (and usually good enough for most purposes) are

*

*Bisection

*Newton's method / Secant method
I explained the bisection method and Newton's method in this answer. If you are to implement a root finding method yourself then I would suggest you start with bisection: it's the easiest one to implement and there is little that can go wrong (less chance for making mistakes).
If you are allowed to use mathematical software there are many built-in methods (implementing methods like the ones mentioned above). Always use built-in methods if you can. Below are some examples for how you can find a root of a function in some of the most common packages Matlab, Mathematica and Maple. The example is finding the root of $\sin(x)$ close to $x=x_0=3$ (which should give $x=\pi$).
Mathematica's FindRoot:
f     = Sin[x];
x0    = 3;
FindRoot[f[x] == 0, {x, x0}]

MatLab's fzero:
f     = @sin;
x0    = 3;
fzero(f, x0)

Maple's fsolve:
f    := sin(x);
fsolve(f = 0, x, 2..4);

For your spesific question: The function $-\frac{\zeta'(x)}{\zeta(x)}$ is positive and monotonely decreasing on $(1,\infty)$ and asymptotes to $0$ so the function $F(x) = -\frac{\zeta'(x)}{\zeta(x)}-C$ has only one root for any $C > 0$ (see plot below). Any of the methods mentioned above should work to find this root. Using the asymptotics of the $\zeta$-function we can derive approximate solutions for the roots in the limit $C\gg 1$ and $C\ll 1$.
Since $\zeta(x) \approx \frac{1}{x-1}$ close to $x=1$ we get that the root is approximately
$$x \approx \frac{1}{C}~~~~~~\text{for}~~~~~~C\gg 1$$
For large $x$ we have $\zeta(x) \approx 1 + \frac{1}{2^x}$ which gives us that the root is approximately
$$x \approx \frac{\log\left(\frac{1}{C}\right)}{\log(2)}~~~~~~\text{for}~~~~~~C\ll 1$$


text:
Q: Firebase and AngularJS - Insert data into existing child I am making a blog in AngularJS and Firebase, and I want to have comments on my posts and store them. For now, I am keeping comments separately, but I would like to store them under the post I am writing them for.
Right now, my Firebase looks like this:
"Articles" : {
 "-KIe9mOqMepTsAYipSA6" : {
   "emailId" : "mail@mail.com",
   "post" : "Test",
   "title" : "Test"
 },
 "-KIe9pBW1LnwAgCh96Mp" : {
   "emailId" : "mail@mail.com",
   "post" : "potatoes",
   "title" : "potatos"
 }
}

and when I add comment, I want it to look like:
"Articles" : {
 "-KIe9mOqMepTsAYipSA6" : {
   "emailId" : "mail@mail.com",
   "post" : "Test",
   "title" : "Test",
   "name" : "Name:,
   "comment" : "Comment"
 },
 "-KIe9pBW1LnwAgCh96Mp" : {
   "emailId" : "mail@mail.com",
   "post" : "potatoes",
   "title" : "potatos",
   "name" : "Name:",
   "comment" : "Comment"
 }
}

I tried to wrap $push in $update, and all sorts of things, but nothing really worked.
This is my function for adding comments:
$scope.saveComment = function() {
    var name = $scope.article.name;
    var comment = $scope.article.comment;

    var fb = new Firebase("https://blog-2087.firebaseio.com/Articles/");
    var article = $firebase(fb);
    var user = CommonProp.getUser();
    article.$push({ name: name,comment: comment,emailId: user,'.priority': user}).then(function(ref) {
        login.loading = false;
    }, function(error) {
        login.loading = false;
        console.log("Error:", error);
    });
    $('#addCommentModal').modal('hide');
}

Is there any way to do this? Or I have to save it separately?

A: see this closed issue for explanation... https://github.com/firebase/angularfire/issues/402
But you dont need to use $push and I couldn't find it in the documentation either.
I tested, and this should work
article.push({ name: name, comment: comment, emailId: user,'.priority': user}).then(function(ref) {
    login.loading = false;
}, function(error) {
    login.loading = false;
    console.log("Error:", error);
});


text:
Q: How to hide NavigationIcon on toolbar I have following design in my project -
Activity (which have menuitems A, B, C, D)
if we click on menuItem A then a FragmentA opens.I'm adding this fragment on top of activity, So toolbar remains same.
FragmentA onCreateView is -
    @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            rootView =  inflater.inflate(R.layout.fragment_a, container, false)

            Activity.toolbar.setTitle("FragmentA");
            Activity.toolbar.setNavigationIcon(R.drawable.back_icon);

            Activity.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Activity.fragmentManager.popBackStack();
                    Activity.toolbar.setTitle("Activity");
                }
            });
}

So Basically in FragmentA I inflate Back Navigation Icon on toolbar. but i want to hide this icon when switch back to my Activity. I don't have any navigation icon or logo in Activity.

A: This is working fine with me:
getSupportActionBar().setDisplayHomeAsUpEnabled(false);

hope it helps somebody

A: Try setting the NavigationIcon to null while getting back to activity.
Activity.toolbar.setNavigationOnClickListener(new View.OnClickListener( {
    @Override
    public void onClick(View view) {
        Activity.fragmentManager.popBackStack();
        Activity.toolbar.setTitle("Activity");
        Activity.toolbar.setNavigationIcon(null);
    }
});

A: if you want to hide the navigationview icon from the toolbar on any Fragment use that code
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    MainActivity activity = (MainActivity)context;
    Toolbar toolbar = activity.findViewById(R.id.toolbar);
       toolbar.setTitle("Quiz");
       toolbar.setNavigationIcon(null);

}


text:
Q: Display style in text, but at text style size I would like to write $\sum_i$ to be displayed as \displaystyle $\sum_i$ but at the size of $\sum_i$. How can I do that?
I could maybe use a subscript command, but that is not my question. My question is more generic about the display style within the text style at the size of the text style.

A: Use \limits.
\documentclass{article}
\usepackage{mathtools}
\begin{document}
abc $\sum_i$ $\sum\limits_i$ def
\end{document}


text:
Q: Beautifulsoup - pesquisa de href por texto Boa tarde a todos, estou com um problema que ainda não consegui resolver nem encontrei nenhum relacionado.
Se eu tiver:
codigo_pagina = '''

                Something1

Something2

**Something3**
                (anothertext)

soup = BeautifulSoup(codigo_pagina, "lxml")

path = soup.findAll('a', href=True, text="Something3")
print(path)

eu recebo:
>>> [Something3]
que é o que quero.
Mas se Something3 passar para nova linha (como se eu desse um "enter" o href já não é encontrado e não recebo nada:
codigo_pagina = '''

                Something1

Something2

**Something3**
                (anothertext)

Assim já não recebo nada...
>>>

A: Por algum motivo, a estrutura do HTML no PyCharm precisa seguir alguns critérios mesmo.
Testei seu código aqui e consegui fazê-lo funcionar adicionando um \ a cada linha pulada no HTML. Esse backslash diz ao PyCharm que a instrução não acabou e que está continuada na próxima linha.
Segue código completo:
from bs4 import BeautifulSoup

codigo_pagina = '''

\
Something1
\
\

Something2
\
\

\
\
Something3
\

(anothertext)

'''

soup = BeautifulSoup(codigo_pagina, 'lxml')
path = soup.findAll('a', href=True, text="Something3")
print(path)


text:
Q: Can't sign in to Android Studio on macOS When I click "sign in" in top right corner of Android Studio it opens browser when I enter Google Account credentials and everything goes well until last part where I end up with link like below

http://localhost:50889/Callback?code=4/restofcode

Unfortunately browser don't know what to do with this and AS is still waiting for sign in.
I have Android Studio 3.0.1 and macOS 10.13.2.
I've tried to use Safari and Firefox browser.

A: The only way to make this work is to use Google Chrome browser.


text:
Q: iOS - Saving current user - are Keychain and saving to disk mutually exclusive? I want to save a current user of my application, but I'm a bit confused on how I choose between what's necessary for the keychain and what should be saved to disk or even if both or just one should be used.
I'm thinking I should save the user's email and password to keychain, then save the user object (comprised of email, password, name, gender, and uuid) to disk (minus the email and password)
Is this the correct approach? Or should I be doing something else

A: In your case, the data you wish to store is tiny: why not store it all in the keychain? It won't be more effort, and will in the end prove simpler than storing half on disk and half in the keychain. And if the user has keychain sync activated, you benefit from that for free...


text:
Q: Backup Aspx Site Page to Network Drive Did a lot of research and tests but can't find a working solution. I have a few aspx site pages and I want to back them up onto network drive or my c drive because I don't want to lose them. but I cannot find a easy way to back them up.  i have tried trying to download from the site pages but it doesn't show right when i save it outside of SharePoint.  then I tried going to SharePoint designer and extracting the file from there.  it keeps in a aspx file that opens up to code when its save outside of SharePoint.  I may be on the right path but must being missing something. can someone help me?

A: You can use PowerShell cmdlets to do that.
A demo for your reference:
$web = Get-SPWeb "http://sp13/sites/team"
$list = $web.lists["Site Pages"]
$items = $list.items

 foreach($item in $items)
 {

    $ie = new-object -ComObject "InternetExplorer.Application"
    $url = "http://sp13/sites/team/"+ $item.Url
    $ie.silent = $true
    $ie.navigate($url)
    while($ie.Busy) { Start-Sleep -Milliseconds 100 }
    Start-Sleep 10
    $targetFilePath=$item.DisplayName
    $ie.Document.documentElement.innerHTML > "C:\Pages\$targetFilePath.html"
    $ie.Stop()
    $ie.Quit()
 }

More information, you can refer to:
Archive SharePoint aspx pages as html


text:
Q: Geometric Interpretation of Antiderivative?
Could someone please give me a geometric interpretation of the above theorem?

A: Assume that $f:\>\Omega\to{\mathbb C}$ is an analytic function on some domain (connected open set) $\Omega\subset{\mathbb C}$, and that $z_0\in\Omega$ is an arbitrary point in this domain. Then there is a (maybe small) disk $D(z_0)$  centered at $z_0$ which is completely contained in $\Omega$. Using the Taylor development of $f$ at $z_0$, or suitable line integrals together with the CR equations, one can show that the restriction of $f$  to this disk has a primitive, valid in this disk only. This means that there is an analytic function $F_{[z_0]}:\>D(z_0)\to{\mathbb C}$ such  that
$$f(z)={F_{[z_0]}}'(z)\qquad\forall z\in D(z_0)\ .$$
Such a local primitive $F_{[z_0]}$ is not uniquely determined. In fact it is determined exactly up to an additive constant.
Assume that such a construction has been performed at all points $z_0\in\Omega$.
The geometric content of Theorem 18.3.3 above  is the following: When the domain $\Omega$ is simply connected then one can adjust the integration constants of all these local primitives in such a way that a globally defined function
$$F:\quad\Omega\to{\mathbb C}$$
emerges, which is then a global primitive of $f$ on $\Omega$:
$$f(z)=F'(z)\qquad \forall z\in\Omega\ .$$
When $\Omega$ is not simply connected then one cannot guarantee this for every $f:\>\Omega\to{\mathbb C}$. The most prominent example is $\Omega:={\mathbb C}\setminus\{0\}$ (the punctured plane) and
$$f(z):={1\over z}\qquad(z\in\Omega)\ .$$
Here the functions
$$F_{[z_0]}(z):={\rm Log}{z\over z_0}$$
can serve as local primitives near their $z_0$, but it is impossible to concoct a global primitive of $f$ out of these.

A: It's terribly hard to explain geometry without having any pictures on hand, but I'll try my best. I'll be working from the perspective of vector fields ($\mathbb{R}^2 \to \mathbb{R}^2$): specifically, we're going to be working with the vector field $\overline{f} = u-iv$.
Wait, you say! Why work with the conjugate instead of the original $f=u+iv$? We're going to see that $f$ being analytic is equivalent to the vector field $\overline{f}$ having certain very nice properties. Namely, $\overline{f}$ is "curl"-free and divergence-free. This in turn will allow us, on a simply-connected domain, to construct a "potential function" $\Phi$ and a "stream function" $\Psi$ for $\overline{f}$. Finally, when we put together $\Phi + i\Psi$, we'll turn out to have an antiderivative of $f$!
Some notation to start with: Given $z = a+bi$ and $w = c+di$ ($a,b,c,d$ real), write $z \cdot w = ac+bd$ (the dot product) and $z \times w = ad - bc$ (the "cross product", or rather, the 3rd component of the cross product of $(a,b,0)$ and $(c,d,0)$).
First we look at the "curl". By the Cauchy-Riemann equations,
$$
    \nabla \times \overline{f} = - \partial_x v - \partial_y u = 0.
$$
So $\overline{f}$ is a conservative (irrotational) vector field, which means that it has the property that the "work" (line integral) of $\overline{f}$ along any closed curve $\Gamma$ is $0$. (We need the simple-connectedness to make this conclusion!) To put it another way, the work along any path $\gamma$ from $a$ to $b$ depends only on the endpoints $a$ and $b$, not the path taken. With a fixed base point $z_0$, we can define a potential function
\begin{align}
    \Phi(Z) &= (\text{Work of }\overline{f}
                \text{ along any path from }z_0\text{ to }Z) \\
    &= \int_{z_0}^Z \overline{f} \cdot dz
     = \int_{z_0}^Z (u - iv) \cdot (dx + i\,dy)
     = \int_{z_0}^Z u\,dx - v\,dy.
\end{align}
Note that the gradient of $\Phi$ is $\overline{f}$.
Next we look at the divergence. By the Cauchy-Riemann equations again,
$$
    \nabla \cdot \overline{f} = \partial_x u - \partial_y v = 0.
$$
Making use of the simple-connectedness again, $\overline{f}$ is being divergence-free, and so has the property that the "flux" of $\overline{f}$ across any closed curve $\Gamma$ is $0$. Just like the work, the flux across any path $\gamma$ from $a$ to $b$ depends only on the endpoints $a$ and $b$, not the path taken. We can then define a "stream function"
\begin{align}
    \Psi(Z) &= (\text{Flux of }\overline{f}
                \text{ across any path from }z_0\text{ to }Z) \\
    &= \int_{z_0}^Z \overline{f} \cdot (-i\,dz)
     = \int_{z_0}^Z (u - iv) \cdot (dy - i\,dx)
     = \int_{z_0}^Z u\,dy + v\,dx.
\end{align}
(Minor note: I've implicitly made a choice of orientation for the flux.) This is also equal to
$$
    \int_{z_0}^Z (i\overline{f}) \cdot dz;
$$
in particular, the gradient of $\Psi$ is $i\overline{f}$.

Now we finally get to the geometry. When we make a plot of the vector field $\overline{f}$, we can draw a family of equipotentials: level curves of the potential function $\Phi$. We can also draw a family of streamlines: level curves of the stream function $\Psi$.
Choose the levels to be the multiples of some very small constant $k > 0$. If you plot these equipotentials and streamlines together on diagram, you'll see that the equipotentials and streamlines

*

*intersect at right angles,

and even more importantly,

*form a grid of small (approximate-)squares.

Why? Because the gradients $\nabla \Phi = \overline{f}$ and $\nabla \Psi = i\overline{f}$ are (1) perpendicular and (2) have the same magnitude.
Now define $F = \Phi + i\Psi$. Geometrically, $F$ is the mapping which sends the equipotentials and streamlines of the vector field $\overline{f}$ to vertical and horizontal lines (respectively). Of course, the horizontal and vertical lines are all equally spaced (with spacing $k$). So they, too,

*

*intersect at right angles

*form a grid of small (actual) squares.

The function $F$ maps a grid of small "squares" to a grid of small squares. That means it's analytic.
Let's find its derivative. The gradient of $\Phi$ at a point $z$ is $\overline{f(z)}$; let's call that $Re^{-i\phi}$. Traveling a distance of $k/R$ in the gradient direction $e^{-i\phi}$ (i.e. the direction perpendicular to the equipotential through $z$) increases the potential from $\Phi(z)$ to $\Phi(z)+k$. On the other hand, the direction of $\nabla\Phi$ is the direction perpendicular to $\nabla\Psi$. So traveling $(k/R)e^{-i\phi}$ won't change $\Psi$ - it's in the direction along the streamline through $z$.
Putting these together, changing $z$ by $(k/R)e^{-i\phi}$ causes $F$ to change by $k$. Remember, this is in the limit as $k \to 0$. So we've determined the value of $F'(z)$: the derivative of $F$ at $z$ is $Re^{i\phi}=f(z)$. Hence, $F$ is indeed an antiderivative of $f$.
Finally, we'll relate $F$ to the formula you're probably used to:
\begin{align}
    \int_{z_0}^z f(z) \, dz &= \int_{z_0}^z (u+iv)(dx+i\,dy) \\
    &= \int_{z_0}^z (u\,dx - v\,dy) + i(u\,dy + v\,dx) \\
    &= \Phi(z) + i\Psi(z) \\
    &= F(z).
\end{align}
Now you see the innocent looking formula $F(z)=\int_{z_0}^z f(z)\,dz$ hides a great deal of physical and geometric content. It all has to do with the vector field $\overline{f}$.

For a less condensed and more picture-ful exposition (you need to see the figures! you need to see the figures!), please pick up a copy of Needham's Visual Complex Analysis. This post is greatly indebted to the book, and almost entirely based on the chapter "Vector Fields and Complex Integration".


text:
Q: Does PyCharm have an option to automatically add all unambiguous imports? Intellij has an option to add unambiguous imports on the fly. I have not seen this behavior in PyCharm: does it exist as a Settings / Preference that I have overlooked?  The option that would seem to cover this is already selected:

However any imports that are needed always result in a popup / Import Assist for every new import.  I would like the feature included in the Amazon Lambda Editor.  When I pasted in the the unzip functionality code the editor automatically added all of the required imports

Now why would a simple lambda editor be able to do this while the premiere PyCharm does not?  I do wonder if I were missing some option/setting.


text:
Q: Pygame: Image not moving I have been learning to use PyGame from pythonprogramming.net. I am currently on moving images on a window:
https://pythonprogramming.net/pygame-tutorial-moving-images-key-input/?completed=/displaying-images-pygame/
Here's the code I am running, in case the site is down when you check it out. For some reason, I don't know why, the car image isn't moving. I had typed everything out when I was following the video and when I noticed it didn't work, I copied and pasted the still couldn't get the predicted performance. I printed out the event to debug (This is the only line that I added and isn't on the code copied from the site).
import pygame

pygame.init()

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('A bit Racey')

black = (0,0,0)
white = (255,255,255)

clock = pygame.time.Clock()
crashed = False
carImg = pygame.image.load('racecar.png')

def car(x,y):
    gameDisplay.blit(carImg, (x,y))

x =  (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
car_speed = 0

while not crashed:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True

        ############################
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x_change = -5
            elif event.key == pygame.K_RIGHT:
                x_change = 5
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                x_change = 0
        ######################
    ##
    x += x_change
   ##
    gameDisplay.fill(white)
    car(x,y)

    print(event) # added for debugging

    pygame.display.update()
    clock.tick(60)

pygame.quit()
quit()

I used Spyder but had the window that popped up freeze on me and I had to quit Spyder on my Mac.I switched to PyCharm and the terminal and found that there was no freezing in both but still no movement.
The printed out put on the terminal was:
libpng warning: iCCP: known incorrect sRGB profile
<Event(4-MouseMotion {'pos': (364, 569), 'rel': (364, 569), 'buttons': (0, 0, 0)})>
<Event(5-MouseButtonDown {'pos': (364, 569), 'button': 1})>
<Event(6-MouseButtonUp {'pos': (364, 569), 'button': 1})>
<Event(4-MouseMotion {'pos': (491, 27), 'rel': (127, -542), 'buttons': (0, 0, 0)})>
^[[D^[[D^[[D^[[D^[[D^[[D^[[D^[[D<Event(5-MouseButtonDown {'pos': (491, 27), 'button': 1})>
<Event(6-MouseButtonUp {'pos': (491, 27), 'button': 1})>
^[[D^[[D^[[D<Event(5-MouseButtonDown {'pos': (491, 27), 'button': 1})>
<Event(6-MouseButtonUp {'pos': (491, 27), 'button': 1})>
<Event(5-MouseButtonDown {'pos': (491, 27), 'button': 1})>
<Event(6-MouseButtonUp {'pos': (491, 27), 'button': 1})>
<Event(5-MouseButtonDown {'pos': (491, 27), 'button': 1})>
<Event(6-MouseButtonUp {'pos': (491, 27), 'button': 1})>
<Event(5-MouseButtonDown {'pos': (491, 27), 'button': 1})>
<Event(6-MouseButtonUp {'pos': (491, 27), 'button': 1})>
<Event(5-MouseButtonDown {'pos': (491, 27), 'button': 1})>
<Event(6-MouseButtonUp {'pos': (491, 27), 'button': 1})>
<Event(5-MouseButtonDown {'pos': (491, 27), 'button': 1})>
<Event(6-MouseButtonUp {'pos': (491, 27), 'button': 1})>
<Event(5-MouseButtonDown {'pos': (491, 27), 'button': 1})>
<Event(6-MouseButtonUp {'pos': (491, 27), 'button': 1})>
<Event(5-MouseButtonDown {'pos': (491, 27), 'button': 1})>
<Event(6-MouseButtonUp {'pos': (491, 27), 'button': 1})>
<Event(5-MouseButtonDown {'pos': (491, 27), 'button': 1})>
<Event(6-MouseButtonUp {'pos': (491, 27), 'button': 1})>
<Event(5-MouseButtonDown {'pos': (491, 27), 'button': 1})>
<Event(6-MouseButtonUp {'pos': (491, 27), 'button': 1})>
^[[D^[[D^[[D^[[C^[[C<Event(5-MouseButtonDown {'pos': (491, 27), 'button': 1})>
<Event(6-MouseButtonUp {'pos': (491, 27), 'button': 1})>
<Event(5-MouseButtonDown {'pos': (491, 27), 'button': 1})>
<Event(12-Quit {})>

I understand that the first line of the code is a warning from How do I disable the libpng warning? (python, pygame) and shouldn't affect the code in this manner.

A: Sorry it has been a while I guess they have changed some things now that I am reading the documentation.  It has changed a whole lot I thoroughly apoligize. One thing I would like to point out is it is a good practice to fill in the background before the game starts. I will look more into this I am going to test it myself.
Edit: I have just tested it and for me it works completely fine. It may be your keyboard layout but, my only thought would be, did you select the window?


text:
Q: pandas to_datetime parsing wrong year I'm coming across something that is almost certainly a stupid mistake on my part, but I can't seem to figure out what's going on.
Essentially, I have a series of dates as strings in the format "%d-%b-%y", such as 26-Sep-05. When I go to convert them to datetime, the year is sometimes correct, but sometimes it is not.
E.g.:
dates = ['26-Sep-05', '26-Sep-05', '15-Jun-70', '5-Dec-94', '9-Jan-61', '8-Feb-55']

pd.to_datetime(dates, format="%d-%b-%y")
DatetimeIndex(['2005-09-26', '2005-09-26', '1970-06-15', '1994-12-05',
               '2061-01-09', '2055-02-08'],
              dtype='datetime64[ns]', freq=None)

The last two entries, which get returned as 2061 and 2055 for the years, are wrong. But this works fine for the 15-Jun-70 entry. What's going on here?

A: You can write a simple function to correct this parsing of wrong year as stated below:
import datetime

def fix_date(x):

    if x.year > 1989:

        year = x.year - 100

    else:

        year = x.year

    return datetime.date(year,x.month,x.day)

df['date_column'] = data['date_column'].apply(fix_date)

Hope this helps..

A: That seems to be the behavior of the Python library datetime, I did a test to see where the cutoff is 68 - 69:
datetime.datetime.strptime('31-Dec-68', '%d-%b-%y').date()
>>> datetime.date(2068, 12, 31)

datetime.datetime.strptime('1-Jan-69', '%d-%b-%y').date()
>>> datetime.date(1969, 1, 1)

Two digits year ambiguity
So it seems that anything with the %y year below 69 will be attributed a century of 2000, and 69 upwards get 1900
The %y two digits can only go from 00 to 99 which is going to be ambiguous if we start crossing centuries.
If there is no overlap, you could manually process it and annotate the century (kill the ambiguity)
I suggest you process your data manually and specify the century, e.g. you can decide that anything in your data that has the year between 17 and 68 is attributed to 1917 - 1968 (instead of 2017 - 2068).
If you have overlap then you can't process with insufficient year information, unless e.g. you have some ordered data and a reference
If you have overlap e.g. you have data from both 2016 and 1916 and both were logged as '16', that's ambiguous and there isn't sufficient information to parse this, unless the data is ordered by date in which case you can use heuristics to switch the century as you parse it.

A: from the docs

Year 2000 (Y2K) issues: Python depends on the platform's C library,
  which generally doesn't have year 2000 issues, since all dates and
  times are represented internally as seconds since the epoch. Function
  strptime() can parse 2-digit years when given %y format code. When
  2-digit years are parsed, they are converted according to the POSIX
  and ISO C standards: values 69–99 are mapped to 1969–1999, and values
  0–68 are mapped to 2000–2068.

A: For anyone looking for a quick and dirty code snippet to fix these cases, this worked for me:
from datetime import timedelta, date
col = 'date'
df[col] = pd.to_datetime(df[col])
future = df[col] > date(year=2050,month=1,day=1)
df.loc[future, col] -= timedelta(days=365.25*100)

You may need to tune the threshold date closer to the present depending on the earliest dates in your data.

A: Another quick solution to the problem:-
import pandas as pd
import numpy as np
dates = pd.DataFrame(['26-Sep-05', '26-Sep-05', '15-Jun-70', '5-Dec-94', '9-Jan-61', '8-Feb-55'])

for i in dates:
    tempyear=pd.to_numeric(dates[i].str[-2:])
    dates["temp_year"]=np.where((tempyear>=44)&(tempyear<=99),tempyear+1900,tempyear+2000).astype(str)
    dates["temp_month"]=dates[i].str[:-2]
    dates["temp_flyr"]=dates["temp_month"]+dates["temp_year"]
    dates["pddt"]=pd.to_datetime(dates.temp_flyr.str.upper(), format='%d-%b-%Y', yearfirst=False)
    tempdrops=["temp_year","temp_month","temp_flyr",i]
    dates.drop(tempdrops, axis=1, inplace=True)

And the output is as follows, here I have converted the output to pandas datetime format from object using pd.to_datetime
    pddt
0   2005-09-26
1   2005-09-26
2   1970-06-15
3   1994-12-05
4   1961-01-09
5   1955-02-08

As mentioned in some other answers this works best if there is no overlap between the dates of the two centuries.

A: If running into the same problem using a pandas DataFrame, try using the current year or year greater than a particular year, then apply a lambda function similar to below:
df["column"] = df["column"].apply(lambda x: x - dt.timedelta(days=365*100) if x > dt.datetime.now() else x)

or
df["column"] = df["column"].apply(lambda x: x - dt.timedelta(days=365*100) if x > 2022 else x)


text:
Q: Python AST assign node attribute error Following the docs here, and the answers in this answer and this, I have this code
source = r'C:\path\to\file\test.py'
with tokenize.open(source) as f:
    readFile = f.read()

class Py2Neko(ast.NodeVisitor):
    def generic_visit(self, node):
        #print(type(node).__name__)
        ast.NodeVisitor.generic_visit(self, node)

    def visit_Assign(self, node):
        try:
            print("Assign :", node.value.id, node.lineno, node.col_offset)
        except AttributeError:
            print('Attribute Error:', node.lineno, node.col_offset)
        ast.NodeVisitor.generic_visit(self, node)

node = ast.parse(file_contents)
v = Py2Neko()
v.visit(node)

For example, when I run it on this python file:
import os

def __init__(self, latitude, longitude, depth, magnitude):
    self.latitude = latitude
    self.longitude = longitude
    self.depth = depth
    self.magnitude = magnitude

def __str__(self):
    depth = self.depth
    if depth == -1:
        depth = 'unknown'

    magnitude = self.magnitude
    if magnitude == -1:
        depth = 'unknown'

I get this output:
Assign : latitude 9 1
Assign : longitude 10 1
Assign : depth 11 1
Assign : magnitude 12 1
Attribute Error: 16 1
Attribute Error: 18 2
Attribute Error: 20 1
Attribute Error: 22 2

I do not understand why (for example) on line 16 column 2 the depth = self.depth raises an attribute error when I am attempting node.value.id.
I am interested in being able to fetch that value id name for each of the assign statements, including cases like the above where where an attribute error occurs.


text:
Q: How to export R data frame into code for sharing? I'm trying to write a question for Stack Overflow, and I need to include a data frame so that my data can be replicated. I would like to take a data.frame object, and output code. I.e., I want to take this data.frame:
> dat
  a b
1 1 4
2 2 5
3 3 6

And turn it into this code without having to write it all out myself:
> dat <- data.frame(a=c(1,2,3),b=c(4,5,6))

My data.frame is very large, and I need to have a large number of observations for my question to make sense. Therefore it would be great if there is a package that will write that code out for me.
Thanks a lot for any and all advice.

A: Please use dput function:
dput(dat)

If your data.frame is huge, you need to sample it.
And first, if not yet done, please read How to make a great R reproducible example?

A: dput(dataframeName)

in your case: dput(dat)


text:
Q: Why was this post deleted? Array evaluating to nil
Was it an issue of low-quality/someone-just-doesn't-know-Ruby?
(I was one of the post answerers, I'm aware of the post's content--I'm asking about this post specifically, not reasons-in-general, so to see it I guess you need some amount of SO rep.)

A: The poster flagged it and asked for it to be deleted. casperOne obliged.


text:
Q: How to get commented string using regular expression in PHP? I am trying to get commented strings in my code using regular expression in php.
Let's say I have following string.
$string = "
   ///
   ///test
   ///
";

I use preg_match_all for regular expression function.
when I put $string to preg_match_all, it displays
Warning: preg_match() [function.preg-match]: Unknown modifier 'string' in /home/document/public_html/test.php on line 10
I guess it is because I have modifiers(/) in $string.
How do I get around this?
Actual Code
$string = "
///<summary
///aaa
///
";

$pattern = "/\/\/\/\/\/\/.*\/\/\/</summary";

preg_match($pattern,$a,$match);

A: You don't have to use / as delimiters. So try this:
$pattern = '~///\s*///.*///~s';

A: It would be easier to use a preg_match_all and do
/\/\/\/.*/

instead.  That would match all lines that have /// at the beginning


text:
Q: Get notified if an element has changed is there any chance to trigger an event whenever an element changed by WHATEVER? The reason could be the user entered something, of course this gets triggered. But I would also need to react on the situation when f. e. an other ajax-script leads to a change of an element, ad DIV or SPAN for example.
The Change-Event is not triggered in this situation, so any hint how to get this solved?

A:
is there any chance to trigger an event whenever an element changed by WHATEVER?

Yes, on modern browsers you can use mutation observers (spec | MDN). Some older browsers may support the older, now-deprecated mutation events. There are even a couple of bridging projects like this one that implement mutation observers on older browsers using mutation events, so for instance you could use one of those to get mutation observers back in IE9 (which partially supported mutation events).
Barring a browser supporting mutation observers or mutation events, sadly, your only option is polling (blech).


text:
Q: CakePHP 3 Getting a Associated table from another table I have 3 tables Product Styles Details
Product < Styles        < details
id      < product_id FK < styles_id FK

My relationships so far are
//ProductTable
$this->hasMany('Styles', [
        'foreignKey' => 'product_id'
    ]);

//StyleTable
 $this->belongsTo('Products', [
        'foreignKey' => 'product_id'
    ]);
$this->hasMany('Details', [
        'foreignKey' => 'style_id'
    ]);
//Detail
$this->belongsTo('Styles', [
        'foreignKey' => 'style_id'
    ]);

In my details controller under index(), I add
$this->paginate = [
        'contain' => ['Styles', 'Products']
    ];

Styles work, but Products doesn't work. I get an error
Details is not associated with Product. That makes sense I didn't define it in the Details Table. I'm not sure how to start, or what it is called.
A far left join?
I have tried
//Detail Table
$this->belongsTo('Product', [
        'foreignKey' => 'product_style_id',
        'targetForeignKey' => 'product_id',
        'joinTable' => 'product_styles'
    ]);

thank you

A: I was able to figure it out
 'contain' => ['Styles', 'Styles.Products']

This works


text:
Q: Rewriting loop without breaks Below is the code that I want to replicate without using break
///
while True:
    choice = input("Is it time to choose(Y/N)? ")
    if choice.upper() == "N":
        break
    idx = random.randint(0, len(contents))
    fnd = False
    for i in range(3):
        for j in range(3):
            if table[i][j] == contents[idx]:
                table[i][j] = "SEEN"
                fnd = True
                break
        if fnd:
            break
    won = check_win(table)
    print_table(table)
    if won:
        print("The game has been won!!")
        break

Can't figure out, already tried using variables but can't make it work

A: You can use a flag instead:
w_flag = True
while w_flag:
    choice = input("Is it time to choose(Y/N)? ")
    if choice.upper() == "N":
        w_flag = False

    if w_flag:
        idx = random.randint(0, len(contents))
        fnd = False
        i,j = 0,0
        i_flag = True
        while i < 3 and i_flag:
            j_flag = True
            while j < 3 and j_flag:
                if table[i][j] == contents[idx]:
                    table[i][j] = "SEEN"
                    fnd = True
                    j_flag = False
                j += 1
            if fnd:
                i_flag = False
            i += 1

        won = check_win(table)
        print_table(table)
        if won:
            print("The game has been won!!")
            w_flag = False

A: Let's handle this case by case. (I'm leaving initializing variables up to you, btw.)
while True:
    choice = input("Is it time to choose(Y/N)? ")
    if choice.upper() == "N":
        break

The above break statement could be removed by having a playing variable. Change while True: to while playing, and then set playing to false if the player chooses; put the rest of the loop body in the else branch.
    idx = random.randint(0, len(contents))
    fnd = False
    for i in range(3):
        for j in range(3):
            if table[i][j] == contents[idx]:
                table[i][j] = "SEEN"
                fnd = True
                break
        if fnd:
            break

I'm taking the above two break statements to be independent of the top-level while loop, as that's the way it's currently coded. You could re-code these as two nested while loops that increment counters- while i < 3 && !fnd and while j < 3 && !fnd, though that's messy. The inner one could also be handled with index()
    won = check_win(table)
    print_table(table)
    if won:
        print("The game has been won!!")
        break

This last one is the easiest: Just change the loop condition to while playing && !won
That's messy, but it should be equivalent. I might be able to make it cleaner if I knew what you were trying to do with the code as a whole.


text:
Q: Can I specify a path to Python.h for sip-4.18.1 when running 'make' command? I am trying to configure sip-4.18.1 on RHEL 7. I have downloaded/installed/configured Python3.5.2.
When I run 'make' inside sip directory I get this error:

gcc -c -pipe -fPIC -O2 -Wall -W -DNDEBUG -I. -I/usr/include/python2.7 -o siplib.o siplib.c
  siplib.c:20:20: fatal error: Python.h: No such file or directory
   #include

Which I would understand to mean that there is Python 2.7 at least downloaded to this machine, but it doesn't look to be configured.
Is there any way I can specify a path for sip to look for Python.h when running 'make'?

A: Maybe you need to install python-dev and/or python3-dev
sudo apt-get install python-dev
sudo apt-get install python3-dev


text:
Q: NSButton rendering issues when displayed over NSImageView I have a NSButton sibling on top of a NSImageView.
Whenever I click the window, there are some rendering issues. It looks like this:

As you can see, the white edges are the problem.
Strangely, this problem even persists if I override drawRect:.
Nothing gets rendered at all, but whenever I click it, those white edges appear.
Also, when the background-image changes, the button gets redrawn and the edges disappear.
Any idea what might cause this?

EDIT
I found out that this actually happens with every single instance of NSView
and it actually clears part of the buffer (you can see the desktop wallpaper):

EDIT 2
I also just found out that this does not happen if I layer-back the windows content-view.

A: Well, this question was impossible for anyone to answer.
My window had a custom contentView, which was just drawing a view with rounded corners.
Instead of using self.bounds, I used dirtyRect to draw the background.
So when the contentView wanted to redraw the background of the controls that were updated, those rounded corners were cut out.


text:
Q: GraphQL query to filter GraphCMS posts I'm working on a GraphCMS site in React and would like to set up a GraphQL query to filter posts. We have this query setup which works and fetches all posts (adoptions) :
export const allAdoptions = gql`
  query allAdoptions($first: Int!, $skip: Int!) {
    allAdoptions(orderBy: date_DESC, first: $first, skip: $skip) {
        id
        name
        date
        image {
          handle
        }
        desc
        sex
        species
        neutered
    },
    _allAdoptionsMeta {
      count
    }
  }
`

The code is available here : https://github.com/foxreymann/foranimals/blob/master/src/components/Adoptions.js
We'd like to set up a filter component to get posts by species: "Cat" for example, and we've tried just modifying the above query for species: "Cat" with no luck. Any advice much appreciated, thanks

A: Did you check: https://graphcms.com/docs/api_simple/#filtering-entries?
It should work like this:
query {
  allAdoptions(
    filter: {
      species: "maine-coon"
    }
  ) {
    id
    name
  }
}

Michael


text:
Q: read input & save in shared memory in Socket in C I work on the server side Socket  (use Telnet client) in Linux. Client input a line with command(GET/PUT/DEL, key and an associated value (spaces to seperate in between). This key-value pair is then passed accordingly on to the function(GET/PUT/DEL), which saves the data in the shared memory (keyValueStore).
Expected client side: (> is the output from Server)
GET key1
    > GET:key1:key_nonexistent
PUT key1 value1
    > PUT:key1:value1
PUT key2 value2
    > PUT:key2:value2
DEL key2
    > DEL:key2:key_deleted

Questions:
1/ i tried to use strtok() and keyValueStore to seperate & save the tokens in a normal c file, but how should I do (or transform) it into the data transfer communication between server and client?
2/ when or where should I call the command functions (e.g. int put(char* key, char* value) )? in server.c after reading the input but before giving output?
Any advices is appreicated. Thanks for your kindness!
server.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define BUFSIZE 1024 // Buffer Size
#define TRUE 1
#define PORT 5678

int main() {

    int rfd; // Create-Descriptor
    int cfd; // Connection-Descriptor (accept)

    struct sockaddr_in client;
    socklen_t client_len;
    char in[BUFSIZE];
    int bytes_read;

    // 1. socket()
    rfd = socket(AF_INET, SOCK_STREAM, 0);
    if (rfd < 0 ){
        fprintf(stderr, "Error\n");
        exit(-1);
    }

    //Initialize the server address by the port and IP
    struct sockaddr_in server;
    memset(&server, '\0', sizeof(server));
    server.sin_family = AF_INET; // Internet address family: v4 address
    server.sin_addr.s_addr = INADDR_ANY; // Server IP address
    server.sin_port = htons(PORT); // Server port

    // 2. bind()
    int brt = bind(rfd, (struct sockaddr *) &server, sizeof(server));
    if (brt < 0 ){
        fprintf(stderr, "Error\n");
        exit(-1);
    }

    // 3. listen() = listen for connections
    int lrt = listen(rfd, 5);
    if (lrt < 0 ){
        fprintf(stderr, "Error\n");
        exit(-1);
    }

    while (1) {

        // 4. accept()
        cfd = accept(rfd, (struct sockaddr *) &client, &client_len);

        // read() = read from a socket (Client's data)
        bytes_read = read(cfd, in, BUFSIZE);

        while (bytes_read > 0) {
            printf("sending back the %d bytes I received...\n", bytes_read);
            // write() = write data on a socket (Client's data)
            write(cfd, in, bytes_read);
            bytes_read = read(cfd, in, BUFSIZE);
        }

        close(cfd);
    }
    close(rfd);
}

Input.c
#include <stdio.h>
#include <string.h>
#include <stdio.h>
#define MAX_ARRAY 100

int main() {

    typedef struct Value_ {
        char key[MAX_ARRAY];
        char value[MAX_ARRAY];
    } KeyStorage;
    KeyStorage storageKey[MAX_ARRAY];

    char client_input[MAX_ARRAY];
    char *argv[3];
    char *token;
    int count = 0;
    while (1) {
        printf("Input: ");
        gets(client_input);

//get the first token
        token = strtok(client_input, " ");
        int i = 0;
//walk through other tokens
        while (token != NULL) {
            argv[i] = token;
            i++;
            token = strtok(NULL, " ");
        }
        argv[i] = NULL; //argv ends with NULL

        // arg[0] = command z.B. GET, PUT
        printf("Commend: %s\n", argv[0]);

        strcpy(storageKey[count].key, argv[1]);
        printf("Key: %s\n", storageKey[count].key);

        strcpy(storageKey[count].value, argv[2]);
        printf("Value: %s\n", storageKey[count].value);

        count++;

        if (strcmp(argv[0], "QUIT") == 0) {
            break;
        }
    }
    return 0;
}

A: There are a number of errors in your code. I have fixed all to build a working example. Of course, this is not your complete application and there is even a lot of room for enhancements.
I developed and tested my code with MSVC2019 under Windows but I used a #define to isolate Windows specific code so it should compile and run correctly under Linux as well (I have not tested that).
The main problem your code had is a misunderstanding of TCP connection. It is a stream oriented connection and you must assemble "command lines" yourself, receiving one character at a time.
It is only when a line is complete that you can parse it to detect the command sent by the client. I made simple: only one command "exit" does something (close the connection). Everything else is simply ignored.
I made line assembling the easy way. That means that there is no edit possible. Backspace, delete, cursor keys and more and input as any other characters and doesn't work a a user would expect. You should take care of that.
Finally, I kept the code close to what you used. This code is single user. It accept a connection, accept commands from it and only accept a new connection once the first is closed. This is not normally the way to create a server program. To make it multiuser, you should use non-blocking socket and select() or use multi-threading.
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <sys/types.h>
    #ifdef WIN32
    #include <WinSock2.h>
    #include <io.h>
    typedef int socklen_t;
    #pragma warning(disable : 4996)  // No warning for deprecated function names such as read() and write()
    #else
    #include <unistd.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #define closesocket close
    #endif

    #define BUFSIZE 1024 // Buffer Size
    #define TRUE 1
    #define PORT 5678

    int main(int argc, char *argv[])
    {
    #ifdef WIN32
        int iResult;
        WSADATA wsaData;

        // Initialize Winsock
        iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
        if (iResult != 0) {
            printf("WSAStartup failed: %d\n", iResult);
            return 1;
        }
    #endif

        int rfd; // Create-Descriptor
        int cfd; // Connection-Descriptor (accept)

        struct sockaddr_in client;
        socklen_t client_len;
        char in[BUFSIZE];
        int bytes_read;

        // 1. socket()
        rfd = socket(AF_INET, SOCK_STREAM, 0);
        if (rfd < 0) {
            fprintf(stderr, "Error\n");
            exit(-1);
        }

        // Initialize the server address by the port and IP
        struct sockaddr_in server;
        memset(&server, '\0', sizeof(server));
        server.sin_family = AF_INET; // Internet address family: v4 address
        server.sin_addr.s_addr = INADDR_ANY; // Server IP address
        server.sin_port = htons(PORT); // Server port

        // 2. bind()
        int brt = bind(rfd, (struct sockaddr*)&server, sizeof(server));
        if (brt < 0) {
            fprintf(stderr, "Error\n");
            exit(-1);
        }

        // 3. listen() = listen for connections
        int lrt = listen(rfd, 5);
        if (lrt < 0) {
            fprintf(stderr, "Error\n");
            exit(-1);
        }

        while (1) {
            client_len = sizeof(client);
            cfd = accept(rfd, (struct sockaddr*)&client, &client_len);
            if (cfd < 0) {
                fprintf(stderr, "accept failed with error %d\n", WSAGetLastError());
                exit(-1);
            }
            printf("Client connected\n");

            while (1) {
/*
                // Send prompt to client
                char* prompt = "> ";
                if (send(cfd, prompt, strlen(prompt), 0) <= 0) {
                    fprintf(stderr, "send() failed with error %d\n", WSAGetLastError());
                    exit(1);
                }
*/
                // read a line from a socket (Client's data)
                int bytes_idx = -1;
                while (1) {
                    if (bytes_idx >= (int)sizeof(in)) {
                        fprintf(stderr, "input buffer overflow\n");
                        break;
                    }
                    // Receive on byte (character) at a time
                    bytes_read = recv(cfd, &in[++bytes_idx], 1, 0);
                    if (bytes_read <= 0)  // Check error or no data read
                        break;
    /*
                    printf("sending back the %d bytes I received...\n", bytes_read);
                    if (send(cfd, &in[bytes_idx], 1, 0) <= 0) {
                        fprintf(stderr, "send() failed with error %d\n", WSAGetLastError());
                        exit(1);
                    }
    */
                    if (in[bytes_idx] == '\n') {
                        // Received a complete line, including CRLF
                        // Remove ending CR
                        bytes_idx--;
                        if ((bytes_idx >= 0) && (in[bytes_idx] == '\r'))
                            in[bytes_idx] = 0;
                        break;
                    }
                }
                if (bytes_idx > 0) {   // Check for empty line
                    printf("Received \"%s\"\n", in);
                    // Check for client command
                    if (stricmp(in, "exit") == 0)
                        break;
                    else {
                        printf("Client sent unknown command\n");
                    }
                }
            }
            closesocket(cfd);
            printf("Client disconnected\n");
        }
        closesocket(rfd);

    #ifdef WIN32
        WSACleanup();
    #endif
    }


text:
Q: Azure queue with 20 fixed values I have multiple functions running multiple instances. I need each instance to take a unique id from a queue. The id's should stay in the queue forever so functions just keeps taking the id that was used latest. I tried with a SQL table with no luck.
UPDATE [dbo].[AppRegistrations]
SET LastUsed = CURRENT_TIMESTAMP
OUTPUT INSERTED.*
WHERE Id = (SELECT TOP (1) Id
            FROM [dbo].[AppRegistrations]
            ORDER BY LastUsed
            )

I also tried following with a row lock:
BEGIN TRAN
declare @id int
declare @name as nvarchar(512)
declare @applicationId as nvarchar(512)
declare @applicationKey as nvarchar(512)
declare @lastUsed as datetime

select top 1 @id=id,@name=name,@applicationId=[ApplicationId],@applicationKey=[ApplicationKey],@lastUsed=LastUsed from [dbo].[AppRegistrations] WITH (updlock,readpast) order by LastUsed
Update [dbo].[AppRegistrations] set LastUsed=getdate() where id=@id
select @id as Id,@name as Name, @applicationId as ApplicationId,@applicationKey as ApplicationKey,@lastUsed as LastUSed
COMMIT TRAN

Both of the samples above very often ends up with functions running with same id. So they dont work properly. It could be a SQL table is not best option. I have tried thinking some kind of azure queue. Can some one provide a strategy og sample on how to achive this scenario. All ideas are welcome.


text:
Q: How to disable shipping method based on item count and a certain category I have been looking for a way to condtionally disable two shipping methods

*

*table rate

*distance rate

Based on the item count.
By item count I do not mean quantity, I mean how many different products are in the cart. IE 2 Lamps and 3 tables in the cart would be an item count of 2 and a combined quantity of 5.
I would also like to ensure this rule is in effect for a certain category only.
I tried:
function hide_shipping_count_based( $rates, $package ) {

    // Set count variable
    $cart_count = 0;

    // Calculate cart's total
    foreach( WC()->cart->cart_contents as $key => $value) {
        $cart_count ++;
    }

    // only if the weight is over 150lbs find / remove specific carrier
    if( $cart_count > 2 ) {
        // loop through all of the available rates

        unset( $rates[ 'distance_rate' ] );
        unset( $rates[ 'table_rate' ] );

    }

    return $rates;
}

add_filter( 'woocommerce_package_rates', 'hide_shipping_count_based', 10, 2 );

A: You could use the following, explanation with comments added in the code
Conditions that must be met in this code are:

*

*At least 3 line items in cart

*1 or more products belong to the 'categorie-1' category

*'distance_rate' and/or 'table_rate' become unset if the previous 2 conditions are met

function hide_shipping_count_based( $rates, $package ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    // Count line items
    $count =  count( $package['contents'] );

    // Set variable
    $found = false;

    // Set term (category)
    $term = 'categorie-1';

    // Check count
    if( $count > 2 ) {

        // Loop through line items
        foreach( $package['contents'] as $line_item ) {
            // Get product id
            $product_id = $line_item['product_id'];

            // Check for category
            if ( has_term( $term, 'product_cat', $product_id ) ) {
                $found = true;
                break;
            }
        }
    }

    // True
    if ( $found ) {
        // Loop trough rates
        foreach ( $rates as $rate_key => $rate ) {
            // Targeting
            if ( in_array( $rate->method_id, array( 'distance_rate', 'table_rate' ) ) ) {
                unset( $rates[$rate_key] );
            }
        }
    }

    return $rates;
}
add_filter( 'woocommerce_package_rates', 'hide_shipping_count_based', 100, 2 );


text:
Q: Angular *NgFor iterate strings in an array to Table TD tags I have created an angular page which retrieves JSON data from a backend.
The Json output is formatted like
fields
0   "count"
1   "Date"
2   "Status"
rows
0   "["2","2019-11-21","Operate"]"
1   "["3","2019-12-12","Maintain"]"
________________________________________________

{
    "fields":
        ["count","Date","Status"],
    "rows":
        [
            "["2","2019-11-21","Operate"]",
            "["3","2019-12-12","Maintain"]"
        ],
    "id":
        0
}

I want to create a table on my frontend using the values from fields as the headers and the values from rows as the cells. For example
_____________________________
| count |   Date   | Status |
|---------------------------|
|   2   |2019-11-21| Operate|
|   3   |2019-12-12|Maintain|
-----------------------------

However when calling the data I am getting these results
| count                       |   Date   | Status |
|-------------------------------------------------|
|["2","2019-11-21","Operate"] |          |        |
|["3","2019-12-12","Maintain"]|          |        |
---------------------------------------------------

My html code for the table is as follows

        {{field}}

            {{item}}

My Model
export class AppDetail {
    public fields: string[];
    public rows: string[][];
}

My Component
public getSealData() {

    this.sealidService.getSplunkData(this.idValue).subscribe(data => {
      this.appDetail = data as AppDetail;

      console.log(data.fields);
      console.log(data.rows);

    })

  }

EDIT
Now that I am iterating between the  and  I am getting the following error message in console
ERROR Error: Cannot find a differ supporting object of type String

I am assuming that related to my model?
EDIT
Turns out I am not getting an array of arrays, but an array of strings. It looks like there was some decoding going on but the actual JSON looks more like this
"fields":
    ["count","Date","Status"],
 "rows":
    ["[\"2\",\"2019-11-21\",\"Operate\"]", "[\"3\",\"2019-12-12\",\"Maintain\"]"],

So the errors I am getting is due to the string values not being iterate-able.
Console.log output console.log(data.rows)
0: "["2","2019-11-21","Operate"]"
1: "["2","2019-12-02","Maintain"]"

RESOLVED - I will have to work with the owner of the backend data in order to get the proper format in which the response Saurabh's answer will be applicable.

A: Working demo
you can do like this:
Iterate on rows, row element itself are array than again iterate on those to render td

      {{item}}


text:
Q: Button from other layout not respond I´m working on two layouts: the main one and another one (a card layout). I included the card layout inside the main layout, with the following code:
  <include
        android:id="@+id/miPrueba"
        layout="@layout/card_product_details"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:elevation="10dp"
        android:layout_margin="15dp"/>

This works fine, but I have buttons in my main layout and I need to use them. When I try to find them, using findViewByIdid from my card layout, I use this code:
   View view = LayoutInflater.from(getApplication()).inflate(R.layout.card_product_details, null);
   Button prueba = (Buttton) view.findViewById(R.id.buttonId);
    prueba.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Toast por defecto", Toast.LENGTH_SHORT).show();
        }
    });

What I get is nothing, no error, no null pointer exception, nothing. Simple, it does not respond when I click it.
How I can solve it?

A: Need more of your code but from what you have given the reason you are having this problem is that the card doesn't have the button buttonId
When you are creating
View view = LayoutInflater.from(getApplication()).inflate(R.layout.card_product_details, null);


text:
Q: Group strings that have the same words but in a different order I have an example concatenated text field (please see sample data below) that is created from two or three different fields, however there is no guarantee that the order of the words will be the same. I would like to create a new dataset where fields with the same words, regardless of order, are collapsed. However, since I do not know in advance what words will be concatenated together, the code will have to recognize that all words in both strings match.
Code for example data:
var1<-c("BLUE|RED","RED|BLUE","WHITE|BLACK|ORANGE","BLACK|WHITE|ORANGE")
freq<-c(1,1,1,1)
have<-as.data.frame(cbind(var1,freq))

Have:
var1                 freq
BLUE|RED              1
RED|BLUE              1
WHITE|BLACK|ORANGE    1
BLACK|WHITE|ORANGE    1

How can I collapse the data into what I want below?
color               freq
BLUE|RED              2
WHITE|BLACK|ORANGE    2

A: data.frame(table(sapply(strsplit(have$var1, '\\|'),
             function(x)paste(sort(x), collapse = '|'))))

                Var1 Freq
1 BLACK|ORANGE|WHITE    2
2           BLUE|RED    2

In the world of piping: R > 4.0
have$var1 |>
  strsplit('\\|')|>
  sapply(\(x)paste0(sort(x), collapse = "|"))|>
  table()|>
  data.frame()

A: Here is a tidyverse approach:
library(dplyr)
library(tidyr)

have %>%
  group_by(id=row_number()) %>%
  separate_rows(var1) %>%
  arrange(var1, .by_group = TRUE) %>%
  mutate(var1 = paste(var1, collapse = "|")) %>%
  slice(1) %>%
  ungroup() %>%
  count(var1, name = "freq")

  var1                freq
  <chr>              <int>
1 BLACK|ORANGE|WHITE     2
2 BLUE|RED               2


text:
Q: Firefox .net user authentication not working I want the TaskBar object to be hidden when someone is not logged in
Here's my code:
if (HttpContext.Current.User.Identity.IsAuthenticated == false){TaskBar.Visible = false;}

This works perfectly in IE and Chrome, but for some reason, the TaskBar still shows up in Firefox when no one is logged in. I tried clearing firefox's cache, hoping that that was it, but it wasn't. Is there a more "cross-browser" friendly way of doing this?
[EDIT] The taskbar is a custom user control that I made, and uses no javascript. I just want to set its visibility to false.
[EDIT 2] Here's the code for the taskbar. Its been edited quite a bit for anonymity, so try and keep that in mind. And there are even more user controls attached to it. I'm not going to post the code for those, because I'm not the one who programmed them.
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TaskBar.ascx.cs" Inherits="~.TaskBar" %>

<%@ Register TagPrefix="act" TagName="CallPopup" Src="~/Call.ascx" %>
<%@ Register TagPrefix="act" TagName="EmailPopup" Src="~/Email.ascx" %>
<%@ Register TagPrefix="act" TagName="NotePopup" Src="~/Note.ascx" %>
<%@ Register TagPrefix="act" TagName="SurveyPopup" Src="~/Survey.ascx" %>
<%@ Register TagPrefix="act" TagName="TaskPopup" Src="~/Task.ascx" %>

<asp:Label ID="label" runat="server" Text=""></asp:Label>

        <asp:ImageButton runat="server" ID="tasksButton" ImageUrl="~/check.png"  />

        <act:CallPopup ID="pcCall" runat="server" />

        <act:EmailPopup ID="pcEmail" runat="server" />

        <act:NotePopup ID="pcNote" runat="server" />

        <act:TaskPopup ID="pcTask" runat="server" />

[EDIT 3]
Alright, so here's a bit more on the issue that I just figured out. The way the program is set up is so that users are able to check "Keep Me Logged In", which the program will then do. So I think the issue is actually that Firefox isn't letting the user logout. I have tried clicking our Logout button, and it only doesn't work in Firefox. Maybe that will help push this question forward.
Here's the code for the logout:
<asp:LoginStatus ID="HeadLoginStatus" runat="server" LogoutAction="Redirect" LogoutText="Log Out" LogoutPageUrl="~/Login.aspx" />

We're using a basic AnonymousTemplate and LoggedInTemplate system. (I'm not completely sure what all else is needed to describe the login system, sorry...still new at this)

A: Have you used something like Fiddler or Firebug to check whether Firefox is sending the authentication cookie and whether logging out is clearing the cookie correctly?
HttpContext.Current.User.Identity.IsAuthenticated == false is perfectly valid for checking if the user is authenticated.
Simon

A: The issue is a Javascript error elsewhere in the page, and its not allowing the user to click the logout button, therefore no cookies are being cleared or postbacks occuring. I'm closing this question, since it's no longer relevant.


text:
Q: React + Redux - Component doesn't update after state change Hi I have a React+Redux app. It consists of header and login form. After user sucessfully logins I want the logout button to be displayed in the header. However right now  it seems react renders header before login action takes place and unless I refresh page logout button is not displayed.
My login form
class LoginForm extends React.Component {

    constructor(props) {
        super(props);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleSubmit = (e, {setFieldError, setSubmitting}) => {
        const {username, password} = e;
        if (username && password) {
            loginService
                .login(username, password)
                .then(
                    success => {
                        const data = success.data;
                        if (success.status === 200 && data.success === true) {
                            return {...data.user, password: password};
                        } else if (success.status === 400) {
                            window.location.reload();
                        }
                        const error = (!data.success && "Wrong credentials") || success.statusText;
                        return Promise.reject(error);
                    }
                )
                .then(
                    auth => {
                        this.props.login(auth)
                    },
                    error => {
                        if (error.response.status === 400) {
                            setFieldError("username", "Zły login lub hasło");
                            setFieldError("password", "   ");
                            setSubmitting(false);
                        }
                    }
                )
        }
    };

    render() {
        return (
            <Formik ...
        )
}

function mapState(state) {
    const {session} = state;
    return {session}
}

const connectedLoginForm = connect(mapState, {login: loginActions.login})(LoginForm);
export {connectedLoginForm as LoginForm};

My login action which is dispatched after user press login button
export const loginActions = {
    login
};

function login(data) {
    const session = {
        id: data.id,
        username: data.email,
        password: data.password
    };
    loginService.saveSessionData(session);
    return dispatch => {
        dispatch({type: loginConstants.LOGGED_IN, payload: session});
        history.push('/');
    }
}

My login reducer
const session = loginService.getSessionData();
const initialState = session ? {session} : {};

export function login(state = initialState, action) {
    if (action.type === loginConstants.LOGGED_IN) {
        return {
            session: action.payload
        };
    } else {
        return state
    }
}

My header class which is not rendered properly
class Header extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isLogged: this.props.isLogged,
            showText: true
        };
        this.updatePredicate = this.updatePredicate.bind(this);
    };

    componentDidMount() {
        this.updatePredicate();
        window.addEventListener("resize", this.updatePredicate);
    }

    componentWillUnmount() {
        window.removeEventListener("resize", this.updatePredicate);
    }

    updatePredicate() {
        this.setState({showText: window.innerWidth > 319});
    }

    render() {
        return (
            <MDBNavbar color="white" light expand="md" className={'mt-0'} style={{marginTop: "0px"}} fixed={'top'}>
                <MDBNavbarBrand href={'/'}>

                        {AppName}

                </MDBNavbarBrand>
                {this.state.isLogged &&
                <MDBNavbarNav right>
                    <MDBNavItem>
                        <MDBNavLink to="/logout">
                            <MDBIcon icon="sign-out-alt"/>
                            {this.state.showText && Wyloguj się}
                        </MDBNavLink>
                    </MDBNavItem>
                </MDBNavbarNav>
                }
            </MDBNavbar>
        );
    }
}

function mapState(state) {
    const {session} = state.login;
    return {isLogged: !(typeof session === 'undefined')}
}

const connectedHeader = connect(mapState)(Header);
export {connectedHeader as Header};

What can be the reason ?

A: constructor executes only once, so when you set isLogged,
this.state = {
   isLogged: this.props.isLogged,
   showText: true
};

isLogged will not get changed when next props are received.
You have two ways here.

*

*The simplest one is, directly use this.props.isLogged for you condition like,

{this.props.isLogged &&
    <MDBNavbarNav right>
        <MDBNavItem>
            <MDBNavLink to="/logout">
                <MDBIcon icon="sign-out-alt"/>
                {this.state.showText && Wyloguj się}
            </MDBNavLink>
        </MDBNavItem>
    </MDBNavbarNav>
}

*Another way is manually update the state when you recieve new props using componentDidUpdate
componentDidUpdate(nextProps){
  if(nextProps.isLogged !== this.props.isLogged){
     this.setState({isLogged: this.props.isLogged})
  }
}