text:
Q: How to make enemies fall at random on pygame? I want enemies to randomly fall from the sky on my game and I do not know how to do this.
I was using this youtube video: Falling Objects in Pygame.
import pygame, random

pygame.init()

screen_width = 800
screen_height = 600

window = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Test')
time = pygame.time.Clock()
bg_color1 = (135, 142, 142)  # MAIN BG COLOR
bg_color2 = (255, 0, 0)  # red
bg_color3 = (255, 255, 0)  # yellow
UFO = pygame.image.load('ufo.png')
bg_pic = pygame.image.load('Letsgo.jpg')
clock = pygame.time.Clock()
playerImg = pygame.image.load('enemy.png')
playerX = random.randrange(0, screen_width)
playerY = -50
playerX_change = 0
player_speed = 5

def player(x, y):
    window.blit(playerImg, (playerX, playerY))

crashed = False

rect = UFO.get_rect()
obstacle = pygame.Rect(400, 200, 80, 80)

menu = True
playerY = playerY + player_speed
if playerY > screen_height:
    playerX = random.randrange(0,screen_width)
    playerY = -10

def ufo(x, y):
    window.blit(UFO, (x, y))

while menu:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            quit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                menu = False
    window.fill((0, 0, 0))
    time.tick(30)
    window.blit(bg_pic, (0, 0))
    pygame.display.update()
x = (screen_width * 0.45)
y = (screen_height * 0.8)
x_change = 0
car_speed = 0
y_change = 0

while not crashed:
    x += x_change
    if x < 0:
        x = 0
    elif x > screen_width - UFO.get_width():
        x = screen_width - UFO.get_width()

    y += y_change
    if y < 0:
        y = 0
    elif y > screen_height - UFO.get_height():
        y = screen_height - UFO.get_height()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True

        ############SIDE TO SIDE################
        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
        ###########UP AND DOWN#################
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                y_change = -5
            elif event.key == pygame.K_DOWN:
                y_change = 5
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                y_change = 0
    ##
    x += x_change
    y += y_change
    ##
    window.fill(bg_color1)
    ufo(x, y)
    player(playerX, playerY)
    pygame.display.update()
    clock.tick(100)

pygame.quit()
quit()

So the code that was supposed to make the image fall was this
if playerY > screen_height:
    playerX = random.randrange(0,screen_width)
    playerY = -10

A: Move the following code:
if playerY > screen_height:
playerX = random.randrange(0,screen_width)
playerY = -10

To here so it can be within the game loop:
 for event in pygame.event.get():
    if event.type == pygame.QUIT:
        crashed = True

    ############SIDE TO SIDE################
    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
    ###########UP AND DOWN#################
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_UP:
            y_change = -5
        elif event.key == pygame.K_DOWN:
            y_change = 5
    if event.type == pygame.KEYUP:
        if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
            y_change = 0

  if playerY > screen_height:
    playerX = random.randrange(0,screen_width)
    playerY = -10


text:
Q: All possible possible directed graphs in V={1,2,3} I got this exercise :

Give an example of three different directed graphs on V = {1, 2, 3}
where the edges (1, 2) and (1, 3) exist. Write both the adjacency-list and adjacency-
matrix representation for each.

I find only this two:

G = {(1,2), (1,3)}
G = {(1,2), (1,3), (2,3)}

What I miss? Something like that is valid: G = {(1,2), (1,3), (3,2)} ?

A: It's a directed graph, which means all links are one-way. If you want to be able to go from 1 to 2 and from 2 to 1, you need two links, (1,2) and (2,1) - that's part of the definition of a directed graph.
With that, enumerate all possible links for a graph of 3 vertexes:

*

*(1,2)

*(2,1)

*(1,3)
...

Once you enumerate all possible links in such a graph, you can pick and choose unique sets of those links to make into multiple graphs, subject to the constraints given to you by the exercise.
For instance, here are a couple graphs:

*

*{(1,2)}

*{(2,1)}

*{(1,3)}

*{(3,1)}

*{(3,2), (2,1), (1,3)}

...
You already have two out of three requested answers and you need a third graph to complete the exercise. You need to give answers that include two provided links. Why not give as an answer a graph that has every link in it? A graph of every link must contain the two requested links, right?

redpajama_set_name: RedPajamaStackExchange


text:
Q: mutual information and minimal communication required for generating correlation Let $X$,$Y$ be two stochastic variables with probability distribution $\rho(X,Y)$. The
mutual information, $I(X;Y)$, represents the information shared by the two variables. This intuitive interpretation of $I(X;Y)$ suggests the following question. Given $\rho(X,Y)$, is there a process
$X\rightarrow Z\rightarrow Y$ so that the entropy of $Z$ is equal to the mutual information $I(X;Y)$?
Indeed, the minimal amount of information contained in $Z$ should be the information strictly necessary for reproducing the correlations between $X$ and $Y$. It is easy to show that $E(Z)\ge I(X;Y)$, but it is not clear to me if the strict equality can be reached for any $\rho(X,Y)$.

A: I have found this paper that is closely related with my question:
"The communication complexity of Correlation" by P. Harsha, R. Jain, D. McAllester, J. Radhakrishnan, IEEE Transactions on Information Theory 56, 438 (2010).
In this paper, it is shown that the communication cost required for generating
correlation can be very close to the mutual information. Indeed, it is proved
that the communication cost is smaller or equal to the mutual information, I, plus
2 log(I+1). The authors consider a scenario where random resources are shared
by the parties.

A: I don't claim to be an expert on this topic, and I apologize if the following misses the point.  It seems to me that your question may be addressed by the work of Gács and Körner, "Common information is far less than mutual information" [Problems Control Inform. Theory 2 (1973) 149-162].  I haven't actually seen this paper but am relying on (the title and) the description in a paper of Hammer, Romashchenko, Shen, and Vereshchagin, "Inequalities for Shannon Entropy and Kolmogorov Complexity" at
http://www.lif.univ-mrs.fr/~ashen/mathtext/inequal/final.pdf (Wayback Machine).

A: Try looking at the Wyner common information.
Link
It's not exactly the same thing, but it's a little closer to what you're discussing than the Gács-Körner common information.  The measure "V" (for Virgil) between random variables $X$ and $Y$ might capture what you want.  It isn't the same thing as the Wyner common information, but it might be what you want---
$V(X:Y) \equiv \min_{Q} H(Q)$ under constraint that $I(X:Y|Q)=0$.


text:
Q: Why do all users start in /root instead of their home directories after su as root? I feel like this should be straightforward but I've never seen anyone ask this that I can tell. The situation is pretty straight forward. Whenever I become a user, ie su user it always starts in /root directory instead of it's home directory. Let me show you.
[root@st-test2 ~]# grep "postgres" /etc/passwd
postgres:x:26:26:PostgreSQL Server:/var/lib/pgsql/:/bin/bash
[root@st-test2 ~]# su postgres
bash-4.2$ pwd
/root
[root@st-test2 ~]# ls -lhart /var/lib |grep postgres
drwx------.  4 postgres postgres   86 May  5 16:07 pgsql

So, you can see that the postgres user's home directory exists and that its set in /etc/passwd...but for some reason, they start in the root directory. This happens with every user that I have created and I have no idea why. I can't say that I've ever seen this happen before either.

A: If you only give a username as argument, su changes user without changing much else:

For backward compatibility, su defaults to not change the current
directory and to only set the environment variables HOME and
SHELL (plus USER and LOGNAME if the target user is not root).

So su postgres stays in the same directory. However since HOME is set to the new user's home directory, cd will take you to the right place.
To log in and start from the user's default directory, you need to ask su to start a login shell set up appropriately:
su -l postgres

or its common synonym,
su - postgres

A: Your employer may have changed this because Debian changed the su behavior since Buster. NewInBuster I also created the alias su='su -'


text:
Q: ViewPager with PagerAdapter in Fragment disapper when onRusume When the app start, the viewPager shows correctly, but when I change the fragment then switch back, the viewPager shows nothing. How can I fix the problem?
The structure is FragmentActivity>Fragment>(ViewPager with PagerAdapter)
When the app start.
before
After I switch to other fragment and back.
after
Here is the code.
public class BuyFragment extends Fragment {

private final Float REFRESH_TRIGGER_DISTANCE = 100f; //pixel
private final Float iMAGE_HW_RATE = 0.4f;

ViewPager viewPager;
CustomPagerAdapter pagerAdapter;
ArrayList<String> adPaths;
DisplayMetrics metric;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    inflater.inflate(R.layout.fragment_buy, container);
    metric = new DisplayMetrics();
    getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
    return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onResume() {
    initViewPager();
    initScrollView();
    super.onResume();
}
private void initViewPager() {
    viewPager = (ViewPager) getActivity().findViewById(R.id.viewpager_buy);
    adPaths = EntityUtil.getADPaths();
    pagerAdapter = new CustomPagerAdapter(getActivity(), adPaths);
    viewPager.setAdapter(pagerAdapter);
    int width  = metric.widthPixels;
    int height = Integer.parseInt(new java.text.DecimalFormat("0").format(width * iMAGE_HW_RATE));
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);
    viewPager.setLayoutParams(params);
    params.setMargins(0, 10, 0, 0);
    params.addRule(RelativeLayout.BELOW, R.id.layout_buy_category);
    CirclePageIndicator pageIndicator = (CirclePageIndicator) getActivity().findViewById(R.id.viewpagerindicator_buy);
    pageIndicator.setViewPager(viewPager);
}
private void initScrollView() {
    final PullToRefreshScrollView pullToRefreshScrollView = (PullToRefreshScrollView) getActivity().findViewById(R.id.layout_buy_refresh);
    pullToRefreshScrollView.setOnRefreshListener(new OnRefreshListener<ScrollView>() {
        @Override
        public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
            pagerAdapter.clearPicassoCache(adPaths);
            refreshView.onRefreshComplete();
        }
    });
}

}
The fragment_buy.xml file.
<?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:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/grey_200"
    tools:context=".activity.MainActivity" xmlns:app="http://schemas.android.com/apk/res/com.liuchang">

    <LinearLayout
        android:id="@+id/layout_buy_titlebar"
        android:layout_width="fill_parent"
        android:layout_height="50dip"
        android:layout_alignParentTop="true"
        android:background="@color/teal_500"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btn_localize"
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@color/teal_500"
            android:onClick="toLocalizeActivity"
            android:text="城市"
            android:textColor="@color/white" />

        <TextView
            android:layout_width="0dip"
            android:layout_height="match_parent"
            android:layout_marginBottom="12dip"
            android:layout_marginLeft="20dip"
            android:layout_marginRight="20dip"
            android:layout_marginTop="12dip"
            android:layout_weight="3"
            android:background="@drawable/corner_bg"
            android:clickable="true"
            android:gravity="center"
            android:onClick="toSearchActivity"
            android:text="请输入药店或药品名称"
            android:textColor="@color/black" />
    </LinearLayout>

    <com.handmark.pulltorefresh.library.PullToRefreshScrollView
        xmlns:ptr="http://schemas.android.com/apk/res-auto"
        android:id="@+id/layout_buy_refresh"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/layout_buy_titlebar" >

        <ScrollView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" >

            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" >

                <LinearLayout
                    android:id="@+id/layout_buy_category"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical" >

            ...several buttons...

                </LinearLayout>

                <android.support.v4.view.ViewPager
                    android:id="@+id/viewpager_buy"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_below="@id/layout_buy_category" />

                <com.viewpagerindicator.CirclePageIndicator
                    android:id="@+id/viewpagerindicator_buy"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@id/viewpager_buy"
                    android:layout_marginTop="5dip"
                    app:fillColor="@color/teal_500" />
            </RelativeLayout>
        </ScrollView>
    </com.handmark.pulltorefresh.library.PullToRefreshScrollView>

</RelativeLayout>

A: Change onCreateView & onResume method don't set layout & adapter related.
in OnCreateView you missed to return inflated view. Here  i have updated onCreateView method after inflating view call initScrollView();  & initViewPager();
You can also call those two method in onViewCreated method of Fragment.But here I given answer with onCreateView
Once try below code & let me know if anything
public class BuyFragment extends Fragment {

        private final Float REFRESH_TRIGGER_DISTANCE = 100f; //pixel
        private final Float iMAGE_HW_RATE = 0.4f;
        private View fragmentView;
        ViewPager viewPager;
        CustomPagerAdapter pagerAdapter;
        ArrayList<String> adPaths;
        DisplayMetrics metric;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            if (fragmentView == null)
                fragmentView = inflater.inflate(R.layout.fragment_buy, container, false);
            metric = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
            initViewPager();
            initScrollView();
            return fragmentView;
        }

        @Override
        public void onResume() {
            super.onResume();
        }

        private void initViewPager() {
            if (fragmentView != null) {
                viewPager = (ViewPager) fragmentView.findViewById(R.id.viewpager_buy);
                adPaths = EntityUtil.getADPaths();
                pagerAdapter = new CustomPagerAdapter(getActivity(), adPaths);
                viewPager.setAdapter(pagerAdapter);
                int width = metric.widthPixels;
                int height = Integer.parseInt(new java.text.DecimalFormat("0").format(width * iMAGE_HW_RATE));
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);
                viewPager.setLayoutParams(params);
                params.setMargins(0, 10, 0, 0);
                params.addRule(RelativeLayout.BELOW, R.id.layout_buy_category);
                CirclePageIndicator pageIndicator = (CirclePageIndicator) fragmentView.findViewById(R.id.viewpagerindicator_buy);
                pageIndicator.setViewPager(viewPager);
            }
        }

        private void initScrollView() {
            if (fragmentView != null) {
                final PullToRefreshScrollView pullToRefreshScrollView = (PullToRefreshScrollView) fragmentView.findViewById(R.id.layout_buy_refresh);
                pullToRefreshScrollView.setOnRefreshListener(new OnRefreshListener<ScrollView>() {
                    @Override
                    public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                        pagerAdapter.clearPicassoCache(adPaths);
                        refreshView.onRefreshComplete();
                    }
                });
            }
        }
    }

A: Since your ViewPager is inside Fragment and not activity, you should use getChildFragmentManager() instead of getActivity().getSupportFragmentManager(); whereever possible in adapter or in reference to adapter.


text:
Q: Фильтрация ListView из EditText Не могу разобраться с фильтрацией в ListView. Фильтрация происходит правильно (находит нужное количество), но выводит не те, которые нужно (например не 1, 3 и 5), а первые из списка(1-3).
MainActivity:
private EditText etSearch; // Строка для поиска

private List<Passenger> list; // лист объектов
private List<Passenger> allPassenger; // буферный лист для всех объектов

private ListView lv; //ListView
private ArrayAdapter<Passenger> adapter; // адаптер

...

etSearch = (EditText)findViewById(R.id.etSearch);

// инициализация массивов элементов
list = new ArrayList<>();
lv = (ListView)findViewById(R.id.lvPassengers);
adapter = new PassengerAdapter(this);

...
// заполнение массивов объектами
list.add(new Passenger(id, surname, numberCar, typeCar, positionTypeCar, terminal, positionTerminals, date));
allPassenger = new ArrayList<>(list);

 // вывод колличества объектов
 tvAll.setText(String.valueOf(adapter.getCount()));
 lv.setAdapter(adapter);
 // поиск через EditText
 etSearch.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
            adapter.getFilter().filter(cs);
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
        }
    });

Класс Passenger:
public class Passenger {
    public final int id;
    public final String surname;
    public final String numberCar;
    public final String typeCar;
    public final int positionTypeCar;
    public final String terminal;
    public final int positionTerminal;
    public final String date;

    public Passenger(int id, String surname, String numberCar, String typeCar, int positionTypeCar, String terminal, int positionTerminal, String date) {
        this.id = id;
        this.surname = surname;
        this.numberCar = numberCar;
        this.typeCar = typeCar;
        this.positionTypeCar = positionTypeCar;
        this.terminal = terminal;
        this.positionTerminal = positionTerminal;
        this.date = date;
    }
}

Адаптер и фильтр:
private class PassengerAdapter extends ArrayAdapter<Passenger> implements Filterable {
    public PassengerAdapter(Context context) {
        super(context, R.layout.list_item, list);
    }

    @Override
    public int getCount (){
      return list.size();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Passenger passenger = getItem(position);

        if (convertView == null) {
            convertView = LayoutInflater.from(getContext())
                    .inflate(R.layout.list_item, null);
        }
        ((TextView) convertView.findViewById(R.id.surname))
                .setText(passenger.surname);
        ((TextView) convertView.findViewById(R.id.numberCar))
                .setText(passenger.numberCar);
        ((TextView) convertView.findViewById(R.id.typeCar))
                .setText(passenger.typeCar);
        ((TextView) convertView.findViewById(R.id.date))
                .setText(passenger.date);
        ((TextView) convertView.findViewById(R.id.terminal))
                .setText(passenger.terminal);
        return convertView;
    }
    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults result = new FilterResults();
                if(constraint == null || constraint.length() == 0){
                    result.values = allPassenger;
                    result.count = allPassenger.size();
                }
                else{
                    ArrayList<Passenger> filteredList = new ArrayList<>();
                    for(Passenger p: allPassenger){
                        if(p.surname.toLowerCase().contains(constraint))
                            filteredList.add(p); //Где то здесь ошибка
                    }
                    result.values = filteredList;
                    result.count = filteredList.size();
                }
                return result;
            }

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                list = (ArrayList<Passenger>) results.values;
                tvAll.setText(String.valueOf(results.count));
                notifyDataSetChanged();
            }
        };
        return filter;
    }
}

A: Нашла ошибку! Как всегда из-за не внимательности, забыла добавить метод getItem() в адаптер. Вот исправленный адаптер:
    private class PassengerAdapter extends ArrayAdapter<Passenger> implements Filterable {
    public PassengerAdapter(Context context) {
        super(context, R.layout.list_item, list);
    }

    @Override
    public Passenger getItem(int position) {
        return list.get(position);
    }

    @Override
    public int getCount (){
      return list.size();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = LayoutInflater.from(getContext())
                    .inflate(R.layout.list_item, null);
        }
        Passenger passenger = getItem(position);
        ((TextView) convertView.findViewById(R.id.surname))
                .setText(passenger.surname);
        ((TextView) convertView.findViewById(R.id.numberCar))
                .setText(passenger.numberCar);
        ((TextView) convertView.findViewById(R.id.typeCar))
                .setText(passenger.typeCar);
        ((TextView) convertView.findViewById(R.id.date))
                .setText(passenger.date);
        ((TextView) convertView.findViewById(R.id.terminal))
                .setText(passenger.terminal);
        return convertView;
    }
    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults result = new FilterResults();
                if(constraint == null || constraint.length() == 0){
                    result.values = allPassenger;
                    result.count = allPassenger.size();
                }
                else{
                    ArrayList<Passenger> filteredList = new ArrayList<>();
                    for(Passenger p: allPassenger){
                        if(p.surname.toLowerCase().contains(constraint))
                            filteredList.add(p);
                    }
                    result.values = filteredList;
                    result.count = filteredList.size();
                }
                return result;
            }

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                list = (ArrayList<Passenger>) results.values;
                tvAll.setText(String.valueOf(results.count));
                notifyDataSetChanged();
            }
        };
        return filter;
    }
}


text:
Q: OpenGL implementing skybox in a deferred renderer I am trying to figure out how to render a skybox in a deferred renderer so that it can be included in post processing effects, However my Geometry stage is in view space and unfortunately the skybox in this stage will be effected by it's position relative to the light as any object would (it behaves like large box located very far from the light source and shows up very dark).
my setup  without trying to incorporate the skybox in post processing is as follows:
1:(bind FBO) Render Geometry to color, normal, position FBO texture attachments (unbind FBO).
2:(bind FBO) Render the scene and calculate lighting in screen space.(unbind FBO)
3:(bind FBO) apply post processing effects (unbind FBO)
4: blit the Geometry FBO's depth buffer to the default frame buffer
5: render skybox.
I've tried to switch step 5 with 3
like this:
2:(bind FBO) Render the scene and calculate lighting in screen space.
5: render skybox
(unbind FBO)
3:(bind FBO) apply post processing effects (unbind FBO)
4: blit the Geometry FBO's depth buffer to the default frame buffer
but obviously the skybox has no depth information about the scene and renders on top of the lighting stage. And if I try to do any depth blitting between 2 and 5, I believe I am making invalid GL calls because I'm already bound to an FBO while calling
 GL30.glBindFramebuffer(GL30.GL_READ_FRAMEBUFFER, DeferredFBO.fbo_handle);
 GL30.glBindFramebuffer(GL30.GL_DRAW_FRAMEBUFFER, 0); // Write to default
                                                            // framebuffer or a skybox framebuffer

    GL30.glBlitFramebuffer(0, 0, DisplayManager.Width,
            DisplayManager.Height, 0, 0, DisplayManager.Width,
            DisplayManager.Height, GL11.GL_DEPTH_BUFFER_BIT,
            GL11.GL_NEAREST);

A: So I came up with a really easy hacky solution to this problem without having to incorporate any texture barriers or messing with the depth or color buffers.
I actually render the Skybox Geometry in the Geometry pass of the Deferred Rendering process,  I render the skybox and set a flag in the fragment shader to color my skybox, remembering to modify the view matrix to remove the translation with another uniform flag in the vertex Shader. In the fragment shader I set the skybox color as such. Here is a basic summary without pasting all of the code.
layout (binding = 4) uniform samplerCube cubeMap;
uniform float SkyRender;
void main(){
if(SkyRender){
vec4 SkyColor = texture(cubeMap, skyTexCoords);
gAlbedoSpec.rgb = SkyColor.rgb;
gAlbedoSpec.a = -1;
}else{
gAlbedoSpec.rgb = texture(DiffuseTexture, TexCoords);
gAlbedoSpec.a =   texture(SpecularTexture, TexCoords).r;
}

I set the alpha component of my skybox in the Color buffer as a flag for my Lighting pass. Here I set it to to -1.
In my lighting pass I simply choose to color my box with Diffuse Only instead of adding lighting calculations if my gAlbedoSpec alpha value is -1.
if(Diffuse.a > -1){
FragColor = SphereNormal * vec4(Dlighting, 1.0)+vec4(Slighting, 1.0);
}else{
FragColor = Diffuse ;
}

It's fairly simple and doesn't require much code and gets the job done.

A: Then give it the depth information it lacks.
When you rendered your scene in step 1, you used a depth buffer. So when you draw your skybox, you need an FBO that uses that same depth buffer. But this FBO also needs to use the color image that you rendered to in step 2.
Now, this FBO cannot be the same FBO you used in step 2. Why?
Because that would be undefined behavior. Presumably, step 2 reads from your depth buffer to reconstruct the position (if this is not the case, then you can just attach the depth buffer to the FBO from step 2. But then again, you're also wasting tons of performance). But that depth buffer is also attached to the FBO. And that makes it undefined behavior. Even if you're not writing to the depth, it is still undefined under OpenGL.
So you will need another FBO, which has the depth buffer from step 1 with the color buffer from step 2.
Unless you have access to OpenGL 4.5/ARB_texture_barrier/NV_texture_barrier. With that feature, it becomes defined behavior if you use write masks to turn off writes to the depth buffer. All you need to do is issue a glTextureBarrier before performing step 2. So you don't need another FBO if you have that.
In either case, keep the depth test enabled when rendering your skybox, but turn off depth writing. This will allow fragments behind your actual world to be culled, but the depth of the skybox fragments will be infinitely far away.


text:
Q: GlusterFS storage for docker images I have a docker swarm with 10 docker worker nodes and i'm experiencing issues with docker images storage (in thin pool). It keeps getting full as i got rather small disks (30GB-60GB).
The error:
Thin Pool has 7330 free data blocks which is less than minimum required 8455 free data blocks. Create more free space in thin pool or use dm.min_free_space option to change behavior

Because of that, cleaning strategy has to be aggressive, meaning deleting all images three times a day. This aggressive cleaning strategy results in broken pulls ( when cleaning happens at the same time when someone is pulling an image) and that developers cannot use cached images - instead they need to download the images that just got deleted by cleaning mechanism.
However, there is an option to use GlusterFs storage and i want to mount glusterFS volumes to each docker node and use them to create thin pool for docker images and /var/lib/docker.
I'm looking for guide how to do that exactly. Have anyone tried that?
P.S. I made my research about shared storage for docker images between multiple docker nodes and it seems its not possible, as stated here. However mounting separate volumes to each docker node should be possible.


text:
Q: PHP date time to Unix time Stamp How can I convert string "M-d-Y::H:i:s" to unix timestamp in php. I just realized manipulating date and time must be the most time consuming entity in any programming language.
Trivial Question: Why do you think there isn't any universal date time format. Why are there so many variations of same data? AArrhh.

A: The OOP way (requires PHP >= 5.3.0):
$dt = DateTime::createFromFormat("M-d-Y::H:i:s", $input);
$ts = $dt->getTimestamp();

You should of course check the return value of createFromFormat (it's false if an error occurs) but you should also definitely check DateTime::getLastErrors(); otherwise you might be surprised if e.g. your input has a day of "Jan 32". See my answer here for more info.

A: i have this issue   service unavailable (with message) ResponseText: Error: Call to a member function getTimestamp() on boolean How to fixed this issue.


text:
Q: Drawing bezier curve in Java I need to create a simple Java program, that draws a bezier curve pixel by pixel through any amount of points. At the moment, everything seems to be ok except that the curve always ends at x=0 y=0 coordinates.
Screenshot 1

Screenshot 2

I need it to end at the last point. My brain is not quite working today, so I'm looking for some help.
Here is what I have:
private void drawScene(){

    precision = Float.parseFloat(this.jTextField4.getText());
    //Clears the screen and draws X and Y lines
    g.setColor(Color.white);
    g.fillRect(0, 0, pWidth, pHeight);

    g.setColor(Color.gray);
    g.drawLine(0, offsetY, pWidth, offsetY);
    g.drawLine(offsetX, 0, offsetX, pHeight);
    //Drawing the points
    if(pointCount > 0){
        for(int i = 0;i<pointCount;i++){
            g.setColor(Color.red);
            g.drawString(String.valueOf(i+1), points[i].x + offsetX, points[i].y - 6 + offsetY);
            g.drawOval(points[i].x + offsetX, points[i].y - 6 + offsetY, 3, 3);
        }
    }
    //Drawing the curve
    if(pointCount > 1){
        float t = 0;
        while(t <= 1){
            g.setColor(Color.gray);
            this.besierCurvePixel(t);
            t += precision;
        }
    }
}

//Factorial
private static int fact(int n) {
    int fact = 1;
    for (int i = 1; i <= n; i++) {
        fact *= i;
    }
    return fact;
}
//Bernstein polynomial
private static double bernstein(float t, int n, int i){

   return (fact(n) / (fact(i) * fact(n-i))) * Math.pow(1-t, n-i) * Math.pow(t, i);
}

private void besierCurvePixel(float t){

    double bPoly[] = new double[pointCount];

    for(int i = 0; i < pointCount; i++){
        bPoly[i] = bernstein(t, pointCount, i+1);
    }

    double sumX = 0;
    double sumY = 0;

    for(int i = 0; i < pointCount;  i++){
        sumX += bPoly[i] * points[i].x;
        sumY += bPoly[i] * points[i].y;
    }

    int x, y;
    x = (int) Math.round(sumX);
    y = (int) Math.round(sumY);

    g.drawLine(x + offsetX, y + offsetY, x + offsetX, y + offsetY);

}

This is the method for adding the points (pointCount is 0 initially):
    points[pointCount] = new Point();
    points[pointCount].x = evt.getX() - this.offsetX;
    points[pointCount].y = evt.getY() - this.offsetY;
    pointCount++;

    this.drawScene();

A: The problem was here
for(int i = 0; i < pointCount; i++){
    bPoly[i] = bernstein(t, pointCount, i+1);
}

The second parameter in the bernstein method was incorrect. Basically If I have 3 points, it should be 2 not 3;
bPoly[i] = bernstein(t, pointCount-1, i+1);

A: Where does "pointcount" get set (and to what)?
Have you tried stepping through your code to see why it continues after reaching the last point?
Is it possible that you are stepping through a loop 1 extra time, which is why the last point would have a destination set to (0,0)?
Could you set the number of steps for the app to make to each point?
Hopefully I am bringing up points to help you find your answer
*Edit: If I had to guess- you are accidentally adding an additional point of (0,0) to points[]; Here is where I am seeing it go to (0,0) after the last point:
for(int i = 0; i < pointCount;  i++){
    sumX += bPoly[i] * **points[i]**.x;
    sumY += bPoly[i] * **points[i]**.y;
}

Edit: Glad you were able to fix it, and hopefully i helped with finding that issue. Best of luck in the future!


text:
Q: How to rotate packed quadwords in xmm register? Given an 128-bit xmm register that is packed with two quadwords (i.e. two 64-bit integers):
     ╭──────────────────┬──────────────────╮
xmm0 │ ffeeddccbbaa9988 │ 7766554433221100 │
     ╰──────────────────┴──────────────────╯

How can i perform a rotate on the individual quadwords? For example:
prorqw xmm0, 32   // rotate right packed quadwords

     ╭──────────────────┬──────────────────╮
xmm0 │ bbaa9988ffeeddcc │ 3322110077665544 │
     ╰──────────────────┴──────────────────╯

I know SSE2 provides:

*

*PSHUFW: shuffle packed words (16-bits)

*PSHUFD: shuffle packed doublewords (32-bits)

Although i don't know what the instructions do, nor is there a quadword (64-bit) version.
Bonus Question
How would you perform a ROR of an xmm register - assuming packed data of other sizes?

*

*Rotate Right Packed doublewords by 16-bits:
     ╭──────────┬──────────┬──────────┬──────────╮
xmm0 │ ffeeddcc │ bbaa9988 │ 77665544 │ 33221100 │
     ╰──────────┴──────────┴──────────┴──────────╯
                        ⇓
     ╭──────────┬──────────┬──────────┬──────────╮
xmm0 │ ddccffee │ 9988bbaa │ 55447766 │ 11003322 │
     ╰──────────┴──────────┴──────────┴──────────╯

*Rotate Right Packed Words by 8-bits:
     ╭──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────╮
xmm0 │ ffee │ ddcc │ bbaa │ 9988 │ 7766 │ 5544 │ 3322 │ 1100 │
     ╰──────┴──────┴──────┴──────┴──────┴──────┴──────┴──────╯
                        ⇓
     ╭──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────╮
xmm0 │ eeff │ ccdd │ aabb │ 8899 │ 6677 │ 4455 │ 2233 │ 0011 │
     ╰──────┴──────┴──────┴──────┴──────┴──────┴──────┴──────╯

Extra bonus question
How would you perform the above if it was a 256-bit ymm register?
     ╭──────────────────────────────────┬──────────────────────────────────╮
ymm0 │ 2f2e2d2c2b2a29282726252423222120 │ ffeeddccbbaa99887766554433221100 │ packed doublequadwords
     ╰──────────────────────────────────┴──────────────────────────────────╯
     ╭──────────────────┬──────────────────┬──────────────────┬──────────────────╮
ymm0 │ 2f2e2d2c2b2a2928 │ 2726252423222120 │ ffeeddccbbaa9988 │ 7766554433221100 │ packed quadwords
     ╰──────────────────┴──────────────────┴──────────────────┴──────────────────╯
     ╭──────────┬──────────┬──────────┬──────────┬──────────┬──────────┬──────────┬──────────╮
ymm0 │ 2f2e2d2c │ 2b2a2928 │ 27262524 │ 23222120 │ ffeeddcc │ bbaa9988 │ 77665544 │ 33221100 │ packed doublewords
     ╰──────────┴──────────┴──────────┴──────────┴──────────┴──────────┴──────────┴──────────╯
     ╭──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────┬──────╮
ymm0 │ 2f2e │ 2d2c │ 2b2a │ 2928 │ 2726 │ 2524 │ 2322 │ 2120 │ ffee │ ddcc │ bbaa │ 9988 │ 7766 │ 5544 │ 3322 │ 1100 │ packed words
     ╰──────┴──────┴──────┴──────┴──────┴──────┴──────┴──────┴──────┴──────┴──────┴──────┴──────┴──────┴──────┴──────╯

Bonus Reading

*

*Intel Intrinsics Guide

*X86 Opcode and Instruction Reference Home

*Rotation or Shifting with x86/x64 Assembly

*PSHUFW explanation?

A: If the rotate count is a multiple of 8, you can use byte shuffles.  SSSE3 pshufb with a control mask can handle any other multiple of 8 in one instruction.
SSE2 pshufd can handle count=32, swapping the two halves of each qword: _MM_SHUFFLE(2,3, 0,1), or in asm pshufd xmm0, xmm0, 0b10_11_00_01 (NASM supports _ as an optional separator, like C++11 for numeric literals.)
SSE2 pshuflw + pshufhw for multiple-of-16 counts is not bad for a version of your function without SSSE3, but you need separate shuffles for the low/high qword.  (An imm8 control byte only holds four 2-bit fields.)  Or with AVX2, for the odd/even qwords within each lane.

If the rotate count is not a multiple of 8, there's AVX512F vprolq zmm0, zmm1, 13 and vprorq.  Also available in variable-count version, with per-element counts from another vector instead of an immediate.  vprolvq / vprorvq.  Also available in dword granularity, but not word or byte.

Otherwise with only SSE2 and a count that's not a multiple of 16 you need left+right shift + OR to actually implement in asm the common way of expressing a rotate in C as (x << n) | (x >> (64-n)).  (Best practices for circular shift (rotate) operations in C++ points out ways to work around the potential C UB from out of range shift counts, which isn't a problem with intrinsics or asm because the behaviour of asm and intrinsics is well-defined by Intel: SIMD shifts saturate the shift count, instead of masking it like scalar shifts.)
SSE2 has shifts with granularity as small as 16-bit, so you can do that directly.
For byte granularity, you'd need extra masking to zero out bits that shifted between bytes in a word.  Efficient way of rotating a byte inside an AVX register.  Or use tricks like pmullw with a vector of power-of-2 elements, allowing variable counts per element.  (Where AVX2 normally only has variable-count shifts for dword/qword).

A: Although i asked about performing rotate right, one subset of ROR is when you perform ROR of two 64-bits value by exactly 32 bits. This makes your arbitrary rotate turn into a simple swap of the high and the low 32-bits:

Knowing that you're simply performing a 32-bit (i.e. doubleword) swap, you can use another instruction:

*

*pshufd: Shuffle Packed Doublewords

The encoding of the instruction is tricky, and Intel does its best to obfuscate the documentation. The idea is that you can treat the 128-bit xmm as 32-bit doublewords, and push them to wherever you like:

The encoding is tricky:
pshufd xmm0, xmm0, 0x02030001

Because i'm pushing four doublewords around, the mask is made up of four chunks:

02 03 00 01

These are arranged left-to-right, telling you the index of where that 32-bit doubleword should be shuffled to:

If you are rotating 64-bit quadwords, that are packed into an xmm register, by exactly 32-bits, you can use:
pshufd xmm0, xmm0, 0x02030001 //rotate packed quadwords by 32-bits¹

RotateRight(16)
Now what if:

*

*rather than ROR(32) of the 64-bit quadwords packed into xmm

*i wanted to ROR(16)

We can apply the same trick. Assume that the 64-bit quadwords are divided into 16-bit words, and shuffle them:

pshufw xmm0, xmm0, 0x0605040702010003 //shuffle packed words¹

Except pshufw cannot operate on xmm registers. So i've talked myself to a standstill.
RotateRight(24)
Now what if:

*

*rather than ROR(32) of the 64-bit quadwords packed into xmm

*i wanted to ROR(24)

We can apply the same things. Assume that the 64-bit quadwords are divided into 8-bit words....
pshufb xmm0, xmm0, something  //shuffle packed bytes
Well, i'll pick this up tomorrow. For now i'm tired.  I was hoping to just type in the one line of code; instead it's been a four-hour slog of pain. I just assumed people would have all these basic operations documented by now; the CPU has been around for at least 3 years.
RotateRight(1)
Yeah, later.
Footnotes
¹I think. I'm not sure i got the encoding right.


text:
Q: How to do a DropDownListFor where the options have ids? I am trying to replicate a simple thing when it is done in straight up html, where a dropdown designed for the user to select a color has select options with colored backgrounds. By assigning id type css one can easily get this to work.
<style type="text/css">
  #red {background: #ff0000;}
  #orange {background: #ffaa00;}
  #yellow {background: #ffff00;}
  #green {background: #00ff50;}
  #purple {background: #9932CD;}
  #blue {background: #0000ff;}
  #brown {background: #8B4513;}
</style>

<body>
<div id=container>
    <select id='selected' onchange='changeColor(this.value);'>
        <option id='red' value='#ff0000'>Red</option>
        <option id='orange' value='#ffaa00'>Orange</option>
        <option id='yellow' value='#ffff00'>Yellow</option>
        <option id='green' value='#00ff50'>Green</option>
        <option id='purple' value='#9932CD'>Purple</option>
        <option id='blue' value='#0000ff'>Blue</option>
        <option id='brown' value='#8B4513'>Brown</option>
    </select>
</div>
</body>

I would like to do this in MVC4 using a DropDownListFor() but don't know how to insert the id attribute/value pairs in the options. Here is my current mvc code:
@Html.DropDownListFor(
    m => Model.Item.Id,
    new SelectList(Model.Items, "Id", "Name", Model.Item.Id),
    new { @class = "selectStatus", onchange = "changeColor(this)" })

The model here is a class with Id and Name properties.
public class Item
{
    public int Id { get; set; }

    public string Name { get; set; }
}

I would hope the answer is simple, but it eludes me. I thank you for your help in advance.

A: on your controller build your drop down list and assing it to your model
List<SelectListItem> ls = new List<SelectListItem>();
foreach(var temp in YourRecords){
    ls.Add(new SelectListItem() { Text = temp.Text, Value = temp.Value });
}

ViewModel.DropDownList = ls;

then on your view
@Html.DropDownListFor(x => x.Item.Id, Model.DropDownList, new { @class = "selectStatus"})


text:
Q: How to use BCrypt for RSA (asymmetric encryption) I'm trying to make simple working example of encryption and decryption with BCrypt but I'm can't get it to work because I don't understand exactly how.
From BCryptEncrypt Function, Microsoft Docs:
NTSTATUS BCryptEncrypt(
  BCRYPT_KEY_HANDLE hKey,
  PUCHAR            pbInput,
  ULONG             cbInput,
  VOID              *pPaddingInfo,
  PUCHAR            pbIV,
  ULONG             cbIV,
  PUCHAR            pbOutput,
  ULONG             cbOutput,
  ULONG             *pcbResult,
  ULONG             dwFlags
);

I generated a simple 512bit key pair on 8gwifi.org:
string Public_Key = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJSNbUhCkU9RuY99L8kC2WRJ8TBES3WX1u9wYlANvUFU/h7lU8VNOWI8dNGCQ6UbK2ypHFom+Zm4BaG1zokwcUkCAwEAAQ==";
string Private_Key = "MIIBOgIBAAJBAJSNbUhCkU9RuY99L8kC2WRJ8TBES3WX1u9wYlANvUFU/h7lU8VNOWI8dNGCQ6UbK2ypHFom+Zm4BaG1zokwcUkCAwEAAQJAZ9bwZAl8L5jt//o/E+C0+2Cggt/Ka5nG+bpyTok8GNTyaG+Prmz/QCYdI3VuYdONdfAPm3jLwtbK9wTt1E8HAQIhAM8jg1nwjN9+nhPyFo0F+2o8y47mq1kHnCn+gqAdW8MhAiEAt5gQcCqX2Y5KbmMoqtQ+4RIEHQ8HD+fyGqxWUhVpESkCIEtylQJqgvVZCj0bnakqN6Q/lqlrTZg1FGWbZXrqlqThAiEAilt5v94Jc7Ws2AW4Rw0OmfVGzlNd4hnNNVa88r0Z4gkCIGfFy2H8pGxHxg1GKE2mSZAfpRMyjqeq119S3t/bhqY2";
string Encrypt_Me = "Hello World";

To be honest I don't understand exactly how to use this function for this situation, I tried searching a simple example but couldn't find any.
Thank you.

A: There is an sample here: https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/007a0e26-7fc0-4079-9b63-2ad23f866836/bug-in-rsa-encryptiondecryption-using-cng?forum=windowssdk
Please note that the first byte of encrypted data should not exceed 0xb6. And there is a detailed explanation in the post.
Take encryption as an example,
First, use BCryptOpenAlgorithmProvider to load and initialize a CNG provider that specify RSA.
#define NT_SUCCESS(Status)          (((NTSTATUS)(Status)) >= 0)
status = BCryptOpenAlgorithmProvider(&hAlgorithm,
    BCRYPT_RSA_ALGORITHM,
    NULL,
    0);
if (!NT_SUCCESS(status)) {
    printf("Failed to get algorithm provider..status : %08x\n", status);
    goto cleanup;
}

Then, BCryptImportKeyPair
status = BCryptImportKeyPair(hAlgorithm,
    NULL,
    BCRYPT_RSAPUBLIC_BLOB,
    &hKey,
    PublicKey,
    PublicKeySize,
    BCRYPT_NO_KEY_VALIDATION);
if (!NT_SUCCESS(status)) {
    printf("Failed to import Private key..status : %08x\n", status);
    goto cleanup;
}

To get Encrypted Buffer Size:
status = BCryptEncrypt(hKey,
    InputData,
    InputDataSize,
    NULL,
    NULL,
    0,
    NULL,
    0,
    &EncryptedBufferSize,
    0
);
if (!NT_SUCCESS(status)) {
    printf("Failed to get required size of buffer..status : %08x\n", status);
    goto cleanup;
}

encryptedBuffer = (PUCHAR)HeapAlloc(GetProcessHeap(), 0, encryptedBufferSize);
if (encryptedBuffer == NULL) {
    printf("failed to allocate memory for blindedFEKBuffer\n");
    goto cleanup;
}

Encrypte Data:
status = BCryptEncrypt(hKey,
    InputData,
    InputDataSize,
    NULL,
    NULL,
    0,
    encryptedBuffer,
    encryptedBufferSize,
    &encryptedBufferSize,
    0
);

if (!NT_SUCCESS(status)) {
    printf("Failed encrypt data..status : %08x\n", status);
    goto cleanup;
}
cleanup:
if (hKey)
    BCryptDestroyKey(hKey);
if (hAlgorithm)
    BCryptCloseAlgorithmProvider(hAlgorithm, 0);


text:
Q: Create side-by-side environments in Latex I am trying to create three environments that are beside one another and do not fill the entire page as seen in the attached image. Within each environment, I am trying to add the cvref function, attached is the necessary cls code.
test.cls
\NeedsTeXFormat{LaTeX2e}[1995/12/01]
\@ifl@t@r\fmtversion{2018/04/01}{\UseRawInputEncoding}{}
\ProvidesClass{altacv}[2018/07/27 AltaCV v1.1.4, yet another alternative class for a résumé/curriculum vitae.]
\newif\if@academicons
\DeclareOption{academicons}{\@academiconstrue}
%% v1.1.3: Choice of round/square photo
\newif\if@normalphoto
\DeclareOption{normalphoto}{\@normalphototrue}
\DeclareOption*{\PassOptionsToClass{\CurrentOption}{extarticle}}
\ProcessOptions\relax

\LoadClass{extarticle}

\RequirePackage[margin=2cm]{geometry}
\RequirePackage{fontawesome}

%% v1.1: Optionally load academicons
\if@academicons
  %% Patch to make academicons compilable with XeLaTeX
  \ExplSyntaxOn
  \msg_redirect_name:nnn { fontspec } { font-not-found } { none }
  \ExplSyntaxOff
  \RequirePackage{academicons}
  \newfontfamily{\AI}{academicons.ttf}
\fi

\RequirePackage{xcolor}

\colorlet{accent}{blue!70!black}
\colorlet{heading}{black}
\colorlet{emphasis}{black}
\colorlet{body}{black!80!white}
\newcommand{\itemmarker}{{\small\textbullet}}
\newcommand{\ratingmarker}{\faCircle}

\RequirePackage{tikz}
\usetikzlibrary{arrows}
\RequirePackage[skins]{tcolorbox}
\RequirePackage{enumitem}
\setlist{leftmargin=*,labelsep=0.5em,nosep,itemsep=0.25\baselineskip,after=\vskip0.25\baselineskip}
\setlist[itemize]{label=\itemmarker}
\RequirePackage{graphicx}
\RequirePackage{etoolbox}
\RequirePackage{dashrule}
\RequirePackage{multirow,tabularx}
\RequirePackage{changepage}
% \RequirePackage{marginfix}

\setlength{\parindent}{0pt}
\newcommand{\divider}{\textcolor{body!30}{\hdashrule{\linewidth}{0.6pt}{0.5ex}}\medskip}

\newenvironment{fullwidth}{%
  \begin{adjustwidth}{}{\dimexpr-\marginparwidth-\marginparsep\relax}}
  {\end{adjustwidth}}

\newcommand{\emailsymbol}{\faAt}
\newcommand{\phonesymbol}{\faPhone}
\newcommand{\homepagesymbol}{\faChain}
\newcommand{\locationsymbol}{\faMapMarker}
\newcommand{\linkedinsymbol}{\faLinkedin}
\newcommand{\twittersymbol}{\faTwitter}
\newcommand{\githubsymbol}{\faGithub}
\newcommand{\orcidsymbol}{\aiOrcid}
\newcommand{\mailsymbol}{\faEnvelope}

\newcommand{\printinfo}[2]{\mbox{\textcolor{accent}{\normalfont #1}\hspace{0.5em}#2\hspace{2em}}}
\newcommand{\weblinks}[3]{\mbox{\textcolor{accent}{\normalfont #1}\hspace{0.5em}{\href{#2}{#3}}\hspace{2em}}}
\newcommand{\name}[1]{\def\@name{#1}}
\newcommand{\tagline}[1]{\def\@tagline{#1}}
\newcommand{\photo}[2]{\def\@photo{#2}\def\@photodiameter{#1}}
\newcommand{\email}[2]{\weblinks{\emailsymbol}{#1}{#2}}
\newcommand{\mailaddress}[1]{\printinfo{\mailsymbol}{#1}}
\newcommand{\phone}[1]{\printinfo{\phonesymbol}{#1}}
\newcommand{\homepage}[2]{\weblinks{\homepagesymbol}{#1}{#2}}
\newcommand{\twitter}[1]{\printinfo{\twittersymbol}{#1}}
\newcommand{\linkedin}[2]{\weblinks{\linkedinsymbol}{#1}{#2}}
\newcommand{\github}[2]{\weblinks{\githubsymbol}{#1}{#2}}
\newcommand{\orcid}[1]{\printinfo{\orcidsymbol}{#1}}
\newcommand{\location}[1]{\printinfo{\locationsymbol}{#1}}

\newcommand{\cvsection}[2][]{%
  \bigskip%
  \ifstrequal{#1}{}{}{\marginpar{\vspace*{\dimexpr1pt-\baselineskip}\raggedright\input{#1}}}%
  {\color{heading}\LARGE\bfseries\MakeUppercase{#2}}\\[-1ex]%
  {\color{heading}\rule{\linewidth}{2pt}\par}\medskip
}

\newcommand{\cvref}[4]{%
  \smallskip
  \textcolor{emphasis}{\textbf{#1}}\par
  \smallskip\normalsize
  \ifstrequal{#2}{}{}{
  \textbf{\color{accent}#2}\par
  \smallskip}
  \begin{description}[font=\color{accent},style=multiline,leftmargin=1.25em]
  \item[\small\normalfont\mailsymbol] #3
  \item[\small\normalfont\phonesymbol] #4
  \end{description}
  \medskip
%   \medskip
}

\newenvironment{cvcolumn}[1]{\begin{minipage}[t]{#1}\raggedright}{\end{minipage}}

\RequirePackage[backend=biber,style=authoryear,sorting=ydnt]{biblatex}
%% For removing numbering entirely when using a numeric style
% \setlength{\bibhang}{1em}
% \DeclareFieldFormat{labelnumberwidth}{\makebox[\bibhang][l]{\itemmarker}}
% \setlength{\biblabelsep}{0pt}
\defbibheading{pubtype}{\cvsubsection{#1}}
\renewcommand{\bibsetup}{\vspace*{-\baselineskip}}
\AtEveryBibitem{\makebox[\bibhang][l]{\itemmarker}}
\setlength{\bibitemsep}{0.25\baselineskip}

% v1.1.2: make it easier to add a sidebar aligned with top of next page
\RequirePackage{afterpage}
\newcommand{\addsidebar}[2][]{\marginpar{%
  \ifstrequal{#1}{}{}{\vspace*{#1}}%
  \input{#2}}%
}
\newcommand{\addnextpagesidebar}[2][]{\afterpage{\addsidebar[#1]{#2}}}

\AtBeginDocument{%
  \pagestyle{empty}
  \color{body}
  \raggedright
}

It is called in the following snippet:
test.tex
\PassOptionsToPackage{dvipsnames}{xcolor}
\documentclass[10pt,letterpaper]{altacv}
\geometry{left=1cm,right=9cm,marginparwidth=6.8cm,marginparsep=1.2cm,top=1.25cm,bottom=1.25cm,footskip=2\baselineskip}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[default]{lato}
\definecolor{Mulberry}{HTML}{72243D}
\definecolor{SlateGrey}{HTML}{2E2E2E}
\definecolor{LightGrey}{HTML}{666666}
\colorlet{heading}{Sepia}
\colorlet{accent}{Mulberry}
\colorlet{emphasis}{SlateGrey}
\colorlet{body}{LightGrey}
\renewcommand{\itemmarker}{{\small\textbullet}}
\renewcommand{\ratingmarker}{\faCircle}
\usepackage[hidelinks]{hyperref}
\begin{document}
\begin{fullwidth}
    \cvsection{References}
    \begin{minipage}[t]{0.5\textwidth}
        \begin{flushleft}
            \cvref{test}{test}{\href {mailto:test}{test}}{test}
        \end{flushleft}
    \end{minipage}
    \begin{minipage}[t]{0.5\textwidth}
        \begin{center}
            \cvref{test}{test}{\href {mailto:test}{test}}{test}
        \end{center}
    \end{minipage}
    \begin{minipage}[t]{0.5\textwidth}
        \begin{flushright}
            \cvref{test}{test}{\href {mailto:test}{test}}{test}
        \end{flushright}
    \end{minipage}
\end{fullwidth}
  \medskip
\end{document}

Any guidance would be greatly appreciated. I tried a tabular environment, but it won't let me use the cvref function within the cells.
Using minipages, I get the following result:

A: You weren't entirely clear about what the problem was, but I'm assuming you want the email address and phone number to use the same kind of aligning as the lines above them, so the first set is flushleft, the second centered, and the third flushright? (I'm not crazy about that arrangement, but I'm assuming it's what you want?)
If so, you shouldn't define \cvref to put those in a description environment.
Just as a first stab, you might want to redefine \cvref as follows:
\newcommand{\cvref}[4]{%
  \smallskip
  \textcolor{emphasis}{\textbf{#1}}\par
  \smallskip\normalsize
  \ifstrequal{#2}{}{}{
  \textbf{\color{accent}#2}\par
  \smallskip}
  {\color{accent}%
      {\small\normalfont\mailsymbol} #3\par
      {\small\normalfont\phonesymbol} #4\par%
  }%
  \medskip%
}

I'd also use 0.33\linewidth rather than 0.5\textwidth for the minipages, so that they take up the entire width, but I suppose that depends a bit on how the rest of the CV is going to look and what you want lined up.

But if want to keep it as 0.5\textwidth you get:


text:
Q: How to populate a drop down with values from JavaScript? I added a button to the ribbon toolbar button in my extension to the Tridion CMS. On click of the button a popup page will display with two drop downs. By changing the values in the first drop down control I should populate the values for second drop down control. In my case I am using ASP drop down list control. For the time being I will hard code the values to be populated to the second drop down in java script. For this requirement I am using the following code but I am not able to populate the value (Not Identifying the  tag).
Java script code:
ABC.WCMS.RTFExtension.Popups.ButtonPopup.prototype._populate = function () {
    var selectedValue = $('#functionalcomponent').value;//First dropdown selected value
    var dropdownId = $("#Dd");//Second Dropdown Control

        switch (selectedValue) {

            case "Home Ware":
                dropdownId.append($("<option> </option>").val("Select Sub-Category").html(""));
                dropdownId.append($("<option> </option>").val("Air-Conditioners/Coolers").html("Air-Conditioners/Coolers"));
                break;
            case "Education":
                dropdownId.append($("<option> </option>").val("Select Sub-Category").html(""));
                dropdownId.append($("<option> </option>").val("Colleges").html("Colleges"));
                break;
            default:
                dropdownId.append($("<option> </option>").val("Select Sub-Category").html(""));
                dropdownId.append($("<option> </option>").val("No Value").html("No Value"));

        }
    return true;
}

ASPX Controls:
<%--Dropdown1--%>
<asp:DropDownList ID="functionalcomponent" runat="server"></asp:DropDownList>
<%--Dropdown2--%>
<asp:DropDownList ID="Dd" runat="server"></asp:DropDownList>

How can I populate the values for second drop down from external JavaScript file?

A: Rather than adding values on demand, you may use the approach below:

*

*Add all the items beforehand to the DOM.

*Hide the required items using jQuery logic.
You may refer the following post for a hint Hide options in a select list using jQuery
Please take a look at jQuery disable SELECT options based on Radio selected (Need support for all browsers) also

A: I recently worked on a GUI extension where we populated a drop down based on the value of another drop down.  When I populate using javascript I have the following code:
$j(c.SystemDropDown).append("<option value=\"" + value + "\">" + value + "</option>");

As you can see my example appends the whole <option> tag, where as yours is specified using the .val(), perhaps you could try this way?
The version I have is working great :)


text:
Q: Getting the values key in an array I'm experiencing som difficulties to check if a key exists in an array or not. What I want to do is:
if(array_key_exists('hello',$myArray)) {
   do stuff;
}

or:
if(isset($myArray['hello'])) {
   do stuff;
}

But I think I am doing this in the wrong way, or something like that. I use variables as my keynames, so when I set the array key and value I do it something like this:
//myArray = an array with some random words
foreach($myArray as $item) {
    if($item == 'hello') {
        //Create a new array to put stuff in
        $myNewArray[$item] = 1;
    }
}

However, if I later want to check if if the key 'hello' exists (using a variable again, in an array, just for the sake of it):
$item[0] = 'hello';
$item[1] = 'hello again sir';

if(array_key_exists($item[0], $myNewArray)) {
    echo 'The key exists!';
} else {
    echo 'The key does not exists';
}

//Output: The key does not exists

So – any ideas on what I am doing wrong? Any good ways to approach this problem? And please note; I've already tried to use to put the needle between single quotation marks.
Update:
Some output using var_dump() in my real code - http://pastebin.com/5N1ZWC9f - Still not really getting why it doesn't work as it should?

A: The function var_dump() can always give you good insight into what exactly is in your array. That should help debugging your code. As for your example code, I think the problem is you're checking $myArray where I think you want to be checking $myNewArray;
if(array_key_exists($item[0],$myNewArray)) {
    echo 'The key exists!';
} else {
    echo 'The key does not exists';
}

A: In your last part:
if(array_key_exists($item[0],$myArray)) {
    echo 'The key exists!';
} else {
    echo 'The key does not exists';
}

You are searching in $myArray, not in $myNewArray. But that might not be your actual code.
What do you see as keys in $myNewArray if you do:
print_r($myNewArray);

If 'hello' is there as key, then the script should echo 'The key exists!'

A: I think you are checking a key pair value. So 'Hello' is the value and '0' is the key. Try setting up the array as:
$myArray = ('hello' => 'This is the value');

if (array_key_exists('hello',$myArray) {
echo 'I exist!';
}

Try that.

A: Found out that the value wasn't a string, but an SimpleXML object, which made so that I couldn't compare them (naturally...). Beginners mistake from my side.


text:
Q: Using for comprehension in Scala def combinations(occurrences: List[(Char,Int)]): List[List[(Char,Int)]] = occurrences match {
  case Nil => Nil
  case x :: xs => for(z <- combinations(xs); y <- occ(x)) yield (y :: z)
}

def occ(e: (Char, Int)): List[(Char, Int)] = (for(i <- 0 to e._2) yield (e._1, i)).toList

Hi,
I can't find any flaw in the above snippet but it still giving me List() for any input.

A: You're first for comprehension will always yield a Nil at the end of your recursion which will force the rest of your recursion to be Nil. Here's a slightly modified version that works, though it gives a List[(Char, Int)] instead of a List[List[(Char, Int)]]:
def combinations(occurrences: List[(Char,Int)]): List[(Char,Int)] = occurrences match {
  case Nil => Nil
  case x :: xs => (for { z <- combinations(xs) } yield z) ::: occ(x)
}

If the first part of your for comprehension returns Nil, then it won't evaluate the rest of it and will just return Nil. I've changed things around a bit, so now even if it does evaluate to Nil, it will be combined with the results of occ.

A: Well, I think you are pretty close to the answer. The most important thing is to consider what is the right return value in case of Nil.
  def combinations(occurrences: Occurrences): List[Occurrences] = occurrences match {
    case Nil => List(List())
    case x :: xs =>
      for {
        z <- combinations(xs)
        n <- 0 to x._2
      } yield (if (n == 0) z else (x._1, n) :: z)
  }

A: def combinations(occurrences: List[(Char,Int)]): List[List[(Char,Int)]] = occurrences match {
  case Nil => List(List())
  case x :: xs => for(z <- combinations(xs); y <- occ(x)) yield (y :: z)
}

def occ(e: (Char, Int)): List[(Char, Int)] = (for(i <- 0 to e._2) yield (e._1, i)).toList

This has solved my problem!!!


text:
Q: Compare two databases and see which one is not in the other Now I have one database with a new names. It is set up as Objects like this:
class Users: Object {

    @objc dynamic var userID = ""
    @objc dynamic var username = ""
    @objc dynamic var inputDate = Date()

    override static func primaryKey() -> String? {
        return "userID"
    }
}

I have a refresh button, and when that button is pressed, it will retrieve a new list of names. When the new list is retrieved, some of the names may be deleted. How can I detect which userID's has been removed? Or should I save the new list as new objects, example class Users2: Object { and compare those two objects/databases? - any tips?

A: Here's a high level solution involving Swift 4 Set's
Assuming we start with two arrays of people, one with the existing data and the second with new data where some of the people in the first array were removed.
let array1 = ["Kirk", "Spock", "Bones", "Scotty"]
let array2 = ["Kirk",          "Bones", "Scotty"]

convert the arrays to sets
let s1 = Set(array1)
let s2 = Set(array2)

then to find which people where removed we use the Set operation .subtracting on the sets.
let removedPeopleSet = s1.subtracting(s2)
print(removedPeopleSet)

and the result
["Spock"]

One gotcha here is that sets are unordered, so you'll need to sort when converting to an array, if needed.
This technique can be used directly on your objects because they are ObjC objects and conform to hashable/equatable which is required when working with Sets.


text:
Q: SQL Oracle query to calculate subtotal I am googling to find proper way to make subtotals in Oracle SQL. Recording to this i make query
select model,  sifra, velicina, sum(nvl(magacin,0)) as suma
from podmornica
where model ='30001'
group by  sifra, velicina, cube (model)
order by model, sifra, velicina

I have table podmornica with columns:model,  sifra, velicina, magacin
But it doesn't work. Every second row in column model is null, and at the end  not calculate sum. How to solve this?
    Thanks
P.S. In one MODEL we have variations of SIFRA, i wan't as result to have subtotals for each SIFRA for one model (in this case model is 30001). Like below
MODEL  SIFRA     VELICINA  SUMA

30001  3000101      0        1
30001  3000102      0        2
30001  3000103      0        5
______________________________
30001                        8

A: This appears to be a good time to use group by grouping sets...
SELECT MODEL,  SIFRA,     VELICINA,  sum(nvl(magacin,0)) as SUMA
FROM podmornica
WHERE model ='30001'
GROUP BY GROUPING SETS ((MODEL, SIFRA, VELICINA), (Model))

Group by the model, sifra and velicina to get the detail rows. with magacin summed by those 3 fields...
Group by model so that the sum total is shown for a given model.
Alternatively if you wanted to add a column, you could show the total on every line for the model by adding a sum(magacin) over (partition by model) as sumB  to the select.  This approach is using an analytic/window function.

A: It might be hard to find exactly what you want, but I think you need to cube all the columns:
select model, rgrupa, sifra, velicina, sum(nvl(magacin,0)) as suma
from podmornica
where model ='30001'
group by cube(model, rgrupa, sifra, velicina)
order by model,rgrupa, sifra, velicina


text:
Q: comparison of value on basis of key in list of maps I have a map of string to String, and I want to sort the maps based on thier value for the kay F, but my code fails doing so. please advise.
    Map<String, String> h = null;
    Map<String, String> h1 = null;
    Map<String, String> h2 = null;
    listSummaryMap = new ArrayList<Map<String, String>>();

    h = new HashMap<String, String>();
    h.put("SUCCESS", "27");
    h.put("TOTAL_HOTELS", "86");
    h.put("F", "86");
    h.put("RESERVATION_MODE", "86");
    h.put("PARTNER_NAME", "86");

    h1 = new HashMap<String, String>();
    h1.put("SUCCESS", "27");
    h1.put("TOTAL_HOTELS", "86");
    h1.put("F", "36");
    h1.put("RESERVATION_MODE", "86");
    h1.put("PARTNER_NAME", "86");

    h2 = new HashMap<String, String>();
    h2.put("SUCCESS", "27");
    h2.put("TOTAL_HOTELS", "86");
    h2.put("F", "28");
    h2.put("RESERVATION_MODE", "86");
    h2.put("PARTNER_NAME", "86");

    listSummaryMap .add(h);
    listSummaryMap .add(h1);
    listSummaryMap .add(h2);

    Collections.sort(listSummaryMap , new Comparator<Map<String, String>>() {
        @Override
        public int compare(Map<String, String> o1, Map<String, String> o2) {
            return o2.get("F").compareTo(o1.get("F"));
        }
    });

A: Convert the Strings to Integers and compare as Integers :
    public int compare(Map<String, String> o1, Map<String, String> o2) {
        return Integer.valueOf(o2.get("F")).compareTo(Integer.valueOf(o1.get("F")));
    }

This is assuming the "F" key is always present in the Maps, and its value can always be parsed to an Integer.
BTW, I don't see where you add the Maps to listSummaryMap. Did you forget to include that code in your question?

A: Need to convert String to integer first and then compare will work like this.
Collections.sort(listSummaryMap , new Comparator<Map<String, String>>() {
            @Override
            public int compare(Map<String, String> o1, Map<String, String> o2) {
                Integer a=Integer.parseInt(o2.get("F"));
                Integer b=Integer.parseInt(o1.get("F"));
                return b.compareTo(a);
            }
        });

A: You forgot to add the maps to your list and the map h3 is never initialized. That taken apart your code already works as is but sorts the maps from the highest id to the lowest. If you change your comparison line to that:
Collections.sort(listSummaryMap , new Comparator<Map<String, String>>() {
    @Override
    public int compare(Map<String, String> o1, Map<String, String> o2) {
        return o1.get("F").compareTo(o2.get("F"));
    }
});

Then it will sort your maps by "F" from the lowest to the highest value.
Hope it helps


text:
Q: Add multiple labels through code I am coding a social networking app using Xamarin in Visual Studio, its a portable project with an Android and iOS project.
When the MainPage class is navigated to it opens a URL and reads the page and saves it as a string. I need it to split at every "". I'm thinking I should use a for loop but I don't know what to do next. I would like each chunk to have its own layout box, I have yet to learn which layout to use and what each one is best for. In each box, it would have a label (content) and possibly an image (if the post comes with one, it would be a URL so it would open the URL and display that image)
Basically for each one I want to be able to edit the following
for(string chunk : data.split("<br/">){
    <Layout?>
    <label Text="*Content from the current chunk*"/>
    if(*contains image*){
    <image>*Open url and display the image*</image>
    }
    </Layout?>
}

This is also all inside of a scrollview so they all scroll together...

A: Parsing of chunk strings not shown.
MainPage.xaml:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:StackOverflow1"
             x:Class="StackOverflow1.MainPage"
             Appearing="ContentPage_Appearing">
    <ScrollView>
        <StackLayout x:Name="mainStackLayout" />
    </ScrollView>
</ContentPage>

MainPage.xaml.cs:
    // ...
    public partial class MainPage : ContentPage
    {
        private List<Chunk> chunks = new List<Chunk>();

        // ...

        private void ContentPage_Appearing(object sender, EventArgs e)
        {
            StackLayout childLayout;

            foreach (Chunk chunk in chunks)
            {
                childLayout = new StackLayout();

                Image image = new Image() { Source = chunk.url, HorizontalOptions = LayoutOptions.Start };
                Label label = new Label() { Text = chunk.text, HorizontalOptions = LayoutOptions.Start };

                childLayout.Children.Add(image);
                childLayout.Children.Add(label);

                mainStackLayout.Children.Add(childLayout);
            }
        }
    }
    // ...


text:
Q: Unsemantic grid framework doesn't seem to create gutters This question relates to the Unsemantic Grid Framework (unsemantic.com).
This is my html:
<!DOCTYPE html>

    <link rel="stylesheet" href="css/unsemantic-grid-responsive-no-ie7.css" />

            30%

            70%

This is the CSS portion of unsemantinc that deals with defining the key aspects:
  .grid-container:before, .clearfix:before,
  .grid-container:after,
  .clearfix:after {
    content: ".";
    display: block;
    overflow: hidden;
    visibility: hidden;
    font-size: 0;
    line-height: 0;
    width: 0;
    height: 0;
  }

  .grid-container:after, .clearfix:after {
    clear: both;
  }

  .grid-container {
    margin-left: auto;
    margin-right: auto;
    max-width: 1200px;
    padding-left: 10px;
    padding-right: 10px;
  }

  .grid-5, .mobile-grid-5, .grid-10, .mobile-grid-10, .grid-15, .mobile-grid-15, .grid-20, .mobile-grid-20, .grid-25, .mobile-grid-25, .grid-30, .mobile-grid-30, .grid-35, .mobile-grid-35, .grid-40, .mobile-grid-40, .grid-45, .mobile-grid-45, .grid-50, .mobile-grid-50, .grid-55, .mobile-grid-55, .grid-60, .mobile-grid-60, .grid-65, .mobile-grid-65, .grid-70, .mobile-grid-70, .grid-75, .mobile-grid-75, .grid-80, .mobile-grid-80, .grid-85, .mobile-grid-85, .grid-90, .mobile-grid-90, .grid-95, .mobile-grid-95, .grid-100, .mobile-grid-100, .grid-33, .mobile-grid-33, .grid-66, .mobile-grid-66 {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    padding-left: 10px;
    padding-right: 10px;
  }

  .grid-parent {
    padding-left: 0;
    padding-right: 0;
  }

I use the unsemantic-grid-responsive-no-ie7.css file. In theory, this should create two divs side by side, one taking 30% width and the other 70% width. Between them, there should be a 20px gutter or space if you will (as per the Unsemantic) specs.
However, I can't seem to get the gutter. The divs just stick together.
Any thoughts?

A: The gutter is added as padding, not as a margin.
2 columns (with background colour applied) inside a container, won't have a visible 20px gutter. The container will have 10px padding each side, and the content of each column will have 10px padding each side.
If you want a visible gutter you'll need to nest an additional div, or similar.

A: For a margin-based gutter, you can use the prefix-{width} or suffix-{width} classes.

 content

 content

should give you two columns with 5% between them.


text:
Q: UniversalImageLoader "ImageView is reused" in ViewPager I have a problem using UIL with ViewPager. I call displayImage(...) in instantiateItem method of pagerAdapter (just like in the sample project in UIL github repo).
But, since ViewPager is reusing ImageViews, it defines the same ImageView for previous, current and next pages. So when I create the PagerAdapter, first instantiateItem() is called 3 times and then displayImage() is called 3 times. But since the ImageView is reused and associated with third page, I get "ImageView is reused for another image. Task is cancelled." and only the third page's image is loaded.  The first two are cancelled.
However, the UIL sample project doesn't face this problem. I looked through the whole sample project and couldn't see any difference with mine. So I'm really confused.
Here's my code snippet:
private class PhotoPagerAdapter extends PagerAdapter {
    private LayoutInflater inflater;
    private DisplayImageOptions options;

    PhotoPagerAdapter() {
        inflater = getActivity().getLayoutInflater();

        options = new DisplayImageOptions.Builder()
                .showImageOnFail(R.drawable.ic_error)
                .resetViewBeforeLoading(true)
                .cacheOnDisc(true)
                .imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .displayer(new FadeInBitmapDisplayer(300)).build();
    }

    ...

    @Override
    public Object instantiateItem(ViewGroup view, int position) {
        View imageLayout = inflater.inflate(R.layout.item_pager_image, view, false);
        ImageViewTouch imageView = (ImageViewTouch) imageLayout.findViewById(R.id.image);

        final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);

        ((ActivityViewPager) getActivity()).imageLoader.displayImage(imageURLs.get(position), imageView, options, null);

        ...

    }
}


text:
Q: hide pygame window on OSX Pressing command-H in OSX immediately hides the active window. How do I achieve the same effect, programmatically, from Python? Specifically, I'd like to find a particular window that my application creates and then be able to show & hide it programmatically.
I already know how to do this with pywin32 but I'm afraid my expertise there doesn't quite cover OSX as well.
If it helps, the window in question is one created by pygame. I know that pygame has pygame.display.iconify() but that doesn't satisfy my requirements - the window doesn't disappear immediately, but rather the disappearance is animated, and there's no corresponding "uniconify" function that I can find.

A: Well, this ended up working. When I want to hide the window, I do pygame.display.quit() and make my code properly handle not having a display. When I want to show it, I do pygame.display.set_mode(...) with the former resolution.
The net effect is that of hiding & showing the window. Unfortunately the window gets created in a different spot than where it started, and although apparently you can tell SDL to create the window in a particular spot, I haven't been able to find a way to get the window's location...


text:
Q: Access problem to a control's value in javascript
i have a problem with accessing a control's value in JavaScript.

        Kullanici Adi:

        <asp:TextBox ID="txtKullanici" Text="" runat="server" />

        Sifre :

        <asp:TextBox ID="txtSifre" Text="" runat="server" TextMode="Password" />

I can access to txtSifre's text but i can't access to txtKullaniciAdi's text. There is my accessing code:
    var Sifre = $("#<%=txtSifre.ClientID %>").val();
    var Kul =  $("#<%=txtKullanici.ClientID %>").val();

Do you have any idea?
Çağın

A: Are you setting the TextBox txtKullanici.Visible=false in the codebehind?
This would force ASP.NET NOT to render the control which would explain that you can't find it in the html.
If not, show us the html of the textbox control (something like <input type="text" id="...">)


text:
Q: Get or read version in asp.net for application deployed with octopus I'm using TeamCity and Octopus Deploy to deploy an Asp.Net app
I want to show the version number that was used when the app was deployed
In teamcity I'm generating the version number using the vcs number
How can I read that info from asp.net or how can I save it for later retrieval?

A: The version is stamped onto your libraries (as long as you set the version number prior to building them).
This version number can be accessed at runtime:
string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();

You can also use the assembly version number in Octopus Deploy. This works with Team City, VSTS, and so on. This means the version displayed in Octopus, Team City, and the application itself will all match up and you'll avoid confusion.


text:
Q: To get table name and details using just the column name in mysql database can anyone help me in getting the table name and details from an SQL database whose column name is just known to me ?

A: As mentioned in the comments you can get information about your table from the INFORMATION_SCHEMA
SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = 'your-column-name'


text:
Q: Copy comma-delimited file from S3 with FREGEXPARSER I would like to understand if I can use fregexparser() in the COPY command  for a comma delimited file, and if yes, how the pattern of the parser should be written.
Suppose I am trying to load data to a table like this:
CREATE TABLE public.Corporate_Accounts
(
    Corporate_Account_GK varchar(1000),
    Corporate_Account_Name varchar(1000),
    Country_Symbol varchar(1000),
    Country_Key varchar(1000)
}

and the data is loaded from a text comma-delimited file, how the copy command should look like?


text:
Q: structure packing and performance penalty struct struct_s { char a; int b; };

I want to ask how packing a structure to 1 byte aligned into 32 bit machine result into speed reduction while reading and writing it. As i know structure packing to 1 byte aligned result into store structure members one after the other and still we can read it in 1 clock cycle. so how it result into extra cycle usage with packing ?


text:
Q: How to detect if user clicked on that div? What i want is to check if user clicked anywhere in specific div. If not do something. I tried this:
handleClick(event){
        var clickedComponent = event.target;
        console.log(event.target,'adsadasdas');
        var inside = false;
        do {
            if (clickedComponent === this._eref.nativeElement) {
                inside = true;
            }
            clickedComponent = clickedComponent.parentNode;
        } while (clickedComponent);
        if(inside){
            console.log('inside');
        }else{
            console.log('outside');
        }
    }

Problem with this is that i have *ngIf on some elements so event.target is sometime false. So now i added a wrapper around and i want to check if user clicked inside that wrapper.

A: Look at this Directive credits to - https://christianliebel.com/2016/05/angular-2-a-simple-click-outside-directive/
import {Directive, ElementRef, Output, EventEmitter, HostListener} from '@angular/core';

@Directive({
    selector: '[clickOutside]'
})
export class ClickOutsideDirective {
    constructor(private _elementRef : ElementRef) {
    }

    @Output()
    public clickOutside = new EventEmitter();

    @HostListener('document:click', ['$event.target'])
    public onClick(targetElement) {
        const clickedInside = this._elementRef.nativeElement.contains(targetElement);
        if (!clickedInside) {
            this.clickOutside.emit(null);
        }
    }
}

Also Look at this plunker
Update
import { Subscription } from 'rxjs/Subscription';

A: why you just use in the view the following?
<div *ngIf="cond" (click)="myEventHandler"></div>

and in the controler
myEventHandler(){
//do something
}


text:
Q: Why is my MERN app not displaying after deploying on HEROKU My MERN app was successfully deployed on heroku. However, when I navigate to the URL, I get this error  "{"status":"fail","message":"can't find / on this server"}". While I was in the process of deploying the MERN app. I put the client-side folder in the server folder.
Below is an image of my folder structure
Here is the code in my app.js
const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const AppError = require('./utils/appError');
const globalErrorHandler = require('./controllers/errorController');

const app = express();
app.use(cors());

const serviceUserRoute = require('./routes/serviceUserRoutes');
const carerRoute = require('./routes/carerRoutes');
const getPrivateDataRoute = require('./routes/privateRoute');
const taskRoute = require('./routes/taskRoute');
const visitRoute = require('./routes/visitRoute');
const visitInformationRoute = require('./routes/visitInformationRoute');

//MIDDLEWARES
if (process.env.NODE_ENV === 'development') {
  app.use(morgan('dev'));
}

app.use(express.json());

// custom middleware
app.use((req, res, next) => {
  // eslint-disable-next-line prettier/prettier
  console.log('middleware');
  next();
});

app.use((req, res, next) => {
  req.requestTime = new Date().toISOString();

  next();
});

app.use('/api/v1/serviceusers', serviceUserRoute);
app.use('/api/v1/carers', carerRoute);
app.use('/api/v1/task', taskRoute);
app.use('/api/v1/visit', visitRoute);
app.use('/api/v1/visitInformation', visitInformationRoute);
app.use('/api/v1/private', getPrivateDataRoute);

app.all('*', (req, res, next) => {
  next(new AppError(`can't find ${req.originalUrl} on this server`, 404));
});

app.use(globalErrorHandler);

module.exports = app;

Here is an image of the code in my server.js

What am I doing wrong?

A: I added the code below to find the path to my static files in my application.
if (process.env.NODE_ENV === 'production') {
  app.use(express.static('client/build'));
  app.get('*', (req, res) => {
    let filePath = path.resolve(__dirname, 'client/build', 'index.html');
    res.sendFile(filePath);
  });
}


text:
Q: Opencart 500 server error I am getting such an error at image below while OpenCart complete the pay option. How could this be solved?
hi when I want to click Continue button to continue the order after i finish my payment method then it goes to Checkout Confirmation" The continue button to checkout confirmation does not function it freeze like no action to take. but i look in code. i go to some javascript code. to continue it i try to trace which action it will take i think this javascript
They have the same problem with me. They have solved the problem here, but I do not know how they do it Opencart Fatal error: Opencart Fatal error: Call to a member function get() on a non-object


text:
Q: Save data from text file to SQL database I have some data in a text file in the following format:
Cat 3 24 2 2 4 6 4 7 6 0 0
Dog 18 0 8 2 42 6 6 4 5 8 0
Mouse 8 1 2 2 4 6 4 7 6 0 0
Rabbit 8 10 8 26 46 2 6 7 6 10 0

I would like to write a Ruby script which can take this data and store it in SQLite database where the table's columns will be : Name, Value1, Value2, Value3,...., Value11. And the rows are each piece of data on every line of the file, so the first row of the table will be: Cat, 3, 24, 2, 2, 4, 6, 4, 7, 6, 0, 0.
I have my class for Data set up as follows:
require 'dm-core'
require 'dm-migrations'

DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/development.db")

class Data
  include DataMapper::Resource
  property :id, Serial
  property :name, String
  property :value1, Integer
  property :value2, Integer
  property :value3, Integer
  property :value4, Integer
  property :value5, Integer
  property :value6, Integer
  property :value7, Integer
  property :value8, Integer
  property :value9, Integer
  property :value10, Integer
  property :value11, Integer
end

DataMapper.finalize
DataMapper.auto_upgrade!

In my app.rb I'm trying to write down the logic that can parse this data and create and write it to the database. I'm also using Sinatra for this. How do I go about doing that?
EDIT: Updated app.rb file
require 'sinatra'
require 'slim'
require 'sass'
require './Names'
require 'rubygems'
require 'data_mapper'

get '/' do

  File.readlines("data.txt").each do |line|
    name, *values = line.split
    params = {:name => name}
    values.each_with_index do |value, i|
      params[:"value#{i+1}"] = value
    end
    my_data = Names.new params #class renamed to Names
    my_data.save
  end

end

When I do this I get a NoMethodError - undefined method `validators' for Names:Class.

A: This is a start :
File.readlines('data.txt').each_with_index do |line, i|
  name, *values = line.split
  values.map!{|v| v.to_i}
  puts i
  puts name
  puts values.inspect
end

You get the index, the name and the values for each row.
It returns :
0
Cat
[3, 24, 2, 2, 4, 6, 4, 7, 6, 0, 0]

1
Dog
[18, 0, 8, 2, 42, 6, 6, 4, 5, 8, 0]

2
Mouse
[8, 1, 2, 2, 4, 6, 4, 7, 6, 0, 0]

3
Rabbit
[8, 10, 8, 26, 46, 2, 6, 7, 6, 10, 0]

Now that you have the desired variables, you can write them into your database.
To do so, you can create a params Hash with the expected attributes for your Data :
File.readlines('data.txt').each do |line|
  name, *values = line.split
  params = {:name => name}
  values.each_with_index do |value, i|
    params[:"value#{i+1}"] = value
  end
  my_data = MyData.new params
  my_data.save
end

puts MyData.count # => 4

NOTE: Do not call your class Data, it is already defined in Ruby and you will get weird errors.
Stand-alone Example
Everything put together :
require 'dm-core'
require 'dm-migrations'

# Initialize Database

DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/development.db")

class MyData
  include DataMapper::Resource
  property :id, Serial
  property :name, String
  property :value1, Integer
  property :value2, Integer
  property :value3, Integer
  property :value4, Integer
  property :value5, Integer
  property :value6, Integer
  property :value7, Integer
  property :value8, Integer
  property :value9, Integer
  property :value10, Integer
  property :value11, Integer
end

DataMapper.finalize
DataMapper.auto_upgrade!

# Parse file and save data in DB

File.foreach('data.txt') do |line|
  name, *values = line.split
  params = { name: name }
  values.each_with_index do |value, i|
    params[:"value#{i + 1}"] = value
  end
  MyData.create params
end

puts MyData.count # => 4, then 8, then 12, ...


text:
Q: Create Sliding Window DataFrames with Timestamps I need to create dataframes using a sliding window for multiple 24-hour dataframes covering the span of 2021-01-01 00:00:00 to 2021-12-31 23:56:00. Each interval between dataframes is 6 hours (hence start/end hours are 00,06,12,18). Doing this manually wouldnt be scalable, any input would be appreciated.
For example df1, df3, df5, and df7 will have Timestamp column with 24 hours of data.
start = '2021-01-01 00:00:00'
end = '2021-01-01 23:56:00'
df1 = main_df[(main_df.Timestamp >= start) & (main_df.Timestamp <= end)]

start = '2021-01-01 06:00:00'
end = '2021-01-02 05:56:00'
df3 = main_df[(main_df.Timestamp >= start) & (main_df.Timestamp <= end)]

start = '2021-01-01 12:00:00'
end = '2021-01-02 11:56:00'
df5 = main_df[(main_df.Timestamp >= start) & (main_df.Timestamp <= end)]

start = '2021-01-01 18:00:00'
end = '2021-01-02 17:56:00'
df7 = main_df[(main_df.Timestamp >= start) & (main_df.Timestamp <= end)]

The last dataframe dfx should have 24-hours being the last Timestamp = '2021-12-31 23:56:00'
start = '2021-12-31 00:00:00'
end = '2021-12-31 23:56:00'
dfx = main_df[(main_df.Timestamp >= start) & (main_df.Timestamp <= end)]

A: One way to go about is to repeat your data 4 times, assign each with a label being the starting timestamp, then group:
freq = 6

periods = 24 // freq
shifted = pd.to_timedelta(np.arange(0,24,freq), unit='H')
group = df.Timestamp.dt.floor(f'{freq}H')

groups = pd.concat([
    df.assign(start=group-shift) for shift in shifted
]).groupby('start')

l = len(groups)

for i,(k,d) in enumerate(groups) :
    # only select the full sliding windows
    if periods - 1 <= i< l - periods:
        display(d)

you would get some thing like this:
              Timestamp      start
0   2021-01-01 00:00:00 2021-01-01
1   2021-01-01 00:04:00 2021-01-01
2   2021-01-01 00:08:00 2021-01-01
3   2021-01-01 00:12:00 2021-01-01
4   2021-01-01 00:16:00 2021-01-01
..                  ...        ...
355 2021-01-01 23:40:00 2021-01-01
356 2021-01-01 23:44:00 2021-01-01
357 2021-01-01 23:48:00 2021-01-01
358 2021-01-01 23:52:00 2021-01-01
359 2021-01-01 23:56:00 2021-01-01

A: This works to create two lists of the start and end times that I need. For each of these pairs I will filter the 2021 dataframe down to a single 24-hour time period. The create_df_windows function follows the 2021 calendar year.
def create_df_windows():
  start_list = []
  end_list = []
  for a1 in [str(1).zfill(2),str(2).zfill(2),str(3).zfill(2),str(4).zfill(2),str(5).zfill(2),str(6).zfill(2),str(7).zfill(2),str(8).zfill(2),str(9).zfill(2),10,11,12]:
    if (a1 == str(1).zfill(2) or a1 == str(3).zfill(2) or a1 == str(5).zfill(2) or a1 == str(7).zfill(2) or a1 == str(8).zfill(2) or a1 == str(10).zfill(2) or a1 == str(12).zfill(2)):
      for a2 in [str(1).zfill(2),str(2).zfill(2),str(3).zfill(2),str(4).zfill(2),str(5).zfill(2),str(6).zfill(2),str(7).zfill(2),str(8).zfill(2),str(9).zfill(2),10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]:
        for b1, b2 in zip([str(0).zfill(2),str(6).zfill(2),12,18], [23,str(5).zfill(2),11,17]):
          start = '2021-{d1}-{d2} {t1}:00:00'.format(d1 = a1, d2 = a2, t1 = b1)
          end = '2021-{d1}-{d3} {t2}:56:00'.format(d1 = a1, d3 = a2, t2 = b2)
          start_list.append(pd.to_datetime(start, infer_datetime_format=True))
          end_list.append(pd.to_datetime(end, infer_datetime_format=True))
    elif a1 == str(2).zfill(2): #Feb
      for a2 in [str(1).zfill(2),str(2).zfill(2),str(3).zfill(2),str(4).zfill(2),str(5).zfill(2),str(6).zfill(2),str(7).zfill(2),str(8).zfill(2),str(9).zfill(2),10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28]:
        for b1, b2 in zip([str(0).zfill(2),str(6).zfill(2),12,18], [23,str(5).zfill(2),11,17]):
          start = '2021-{d1}-{d2} {t1}:00:00'.format(d1 = a1, d2 = a2, t1 = b1)
          end = '2021-{d1}-{d3} {t2}:56:00'.format(d1 = a1, d3 = a2, t2 = b2)
          start_list.append(pd.to_datetime(start, infer_datetime_format=True))
          end_list.append(pd.to_datetime(end, infer_datetime_format=True))
    else:
      for a2 in [str(1).zfill(2),str(2).zfill(2),str(3).zfill(2),str(4).zfill(2),str(5).zfill(2),str(6).zfill(2),str(7).zfill(2),str(8).zfill(2),str(9).zfill(2),10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30]:
        for b1, b2 in zip([str(0).zfill(2),str(6).zfill(2),12,18], [23,str(5).zfill(2),11,17]):
          start = '2021-{d1}-{d2} {t1}:00:00'.format(d1 = a1, d2 = a2, t1 = b1)
          end = '2021-{d1}-{d3} {t2}:56:00'.format(d1 = a1, d3 = a2, t2 = b2)
          start_list.append(pd.to_datetime(start, infer_datetime_format=True))
          end_list.append(pd.to_datetime(end, infer_datetime_format=True))

  start_list.append(pd.to_datetime('2021-12-31 00:00:00', infer_datetime_format=True))
  end_list.append(pd.to_datetime('2021-12-31 23:56:00', infer_datetime_format=True))

  end_list2 = []
  for i in end_list:
    dt = pd.to_datetime(i, infer_datetime_format=True)+timedelta(days=1)
    end_list2.append(dt)
  end_list2[0] = pd.to_datetime(end_list2[0], infer_datetime_format=True)-timedelta(days=1)
  return start_list, end_list2


text:
Q: Pullback of cartesian fibration preserves cartesian morphisms? Let $$P:X \rightarrow B$$ be a cartesian fibration of ordinary one category.  Let $F:C \rightarrow B$ be an arbitrary functor.  Let $$Y \xrightarrow{F^*P} C$$
be the pullback of $P$ along $F$. Then it is claimed (p16 line 1) that

A morphism in $Y$ is cartesian wrt $F^*P$ iff its projection to $X$ is cartesian wrt $P$.

I see if the projection to $X$ is cartesian wrt $P$, then the original morphism in $Y$ is cartesian. But I don't see the converse. May someone elaborate?

A: Suppose $(u,\phi) : (c,x)\to (c',x')$ is a morphism in $Y$. We want to show that $(u,\phi)$ is cartesian if and only if $\phi$ is cartesian.
Let $(v,\psi) : (c'',x'')\to (c',x')$ be another morphism in $Y$.
Then by definition, $(u,\phi)$ is cartesian if and only if for all morphisms $(v,\psi)$,
and all
$w : c'' \to c$ such that $v = uw$ there is a unique morphism $\chi : x''\to x$ such that
(i) $\psi = \phi\chi$, and (ii) $(w,\chi)$ is a morphism of $Y$.
Note that (ii) is equivalent to saying that $F(w) = P(\chi)$.
Thus if $\phi$ is a cartesian morphism, then as you claim, we can lift $F(w)$ to produce a unique $\chi$ demonstrating that $(u,\phi)$ is cartesian.
For the converse, which is what you've asked about, we do the following.
Let $\phi' : x'''\to x'$ be a cartesian lift of $P(\phi)$.
Then by the first case $(u,\phi')$ is cartesian. Thus since both $(u,\phi)$ and $(u,\phi')$ are cartesian with the same projection and codomain, there is a unique isomorphism between them. (I.e. an isomorphism $(\alpha,\beta)$, with $\alpha : u\to u$ and $\beta : x\to x'''$).Thus since $\phi'$ is cartesian, $\phi$ must also be cartesian.


text:
Q: Phase, Isochrons, Isochrons map and Lift at the moment i read the following paper:
https://arxiv.org/pdf/1512.04436v1.pdf
I have some questions about it and i hope someone can help me. On page 4/5 they introduce isochrons and the isochron map. What is the meaning of $\mathbb{R}\bmod T$ ? In other literature, they use $[0,T)$, $S^1$ or the quotient space $\mathbb{R}/\mathbb{Z}$ (or $\mathbb{R}/T\mathbb{Z}$). But
if it means $[0,T)$, i cant see that the isochron map is $C^k$. Isn´t there a problem with the total derivative at $x\in W $ with $\theta(x)=0$?
if it means $S^1$ then the dimensions of e.g. the Hessian matrix doesnt fit in the context (see page 6, Theorem 2 .3 (2.19)).
if it means $\mathbb{R}/\mathbb{Z}$. How can i get the Hessian matrix?
Note that they use modT in (2.13).
Thanks, Sebastian.


text:
Q: How to bind for loop data to An Array Here I'm trying to loop through my data but how can I bind this loop data to an Array?
 var ArrayData = this.Volunter[0];

Here I bind my data to ArrayData and I loop through this data
for (var i = 0; i < ArrayData.length; i++) {
    var AmtContrybuted = ArrayData[i].AmountContr
    var YearDedClaim = ArrayData[i].AmountContr;
    var AllowableYears = ArrayData[i].AllowableYear;
    if (YearDedClaim < AllowableYears) {
        var AmtElegible =AmtContrybuted/AllowableYears
    } else {
        ArrayData[i].amounteligible == 0;
    }
}

How can I bind this data to an ArrayData?


text:
Q: Solving an inequality with $\sqrt{\log(x)/ x}$ and $\log(x)/ x$ I am looking for a simpler version of the following inequality:
$\sqrt{\log(x)/ 2x}$ +$3\log(x)/ x-a\le 0$
$x$ is a variable and $a$ is constant ($0<a\le 0.1$).
Generally, is there any facts that reduces $\sqrt{c_1\log(x)/x}$ +$c_2\log(x)/ x$ to a simpler version ($c_1$ and $c_2$ are constants)?
Thanks

A: Hints: Define $$y = \sqrt{\frac{\log x}{x}}$$ then the inequality becomes
$$\frac{y}{\sqrt{2}} + 3y^2 - a\leq 0$$
or equivalently
$$3\left(y + \frac{1}{6\sqrt{2}}\right)^2 \leq a + \frac{1}{24}$$
Now solve for the range of $y$ for which this is satisfied. Then solve for $x$, but remember that we must have $x\geq 1 \to y\geq 0$ in order for $y$ to be well-defined (since $\log x < 0$ for $0<x<1$ and the square root of a negative number is no good).


text:
Q: How to relocate vector table and change starting addressin cortexm3 using uvision(Keil)? I'm using a STM32F107 cortex m3 microcontroller. I'm using the Keil uvision IDE for the project. I have an application which is running properly at the starting location i.e 0x0800 0000. If I change the starting location to 0x0800 4000 the application is not working properly. I made changes to the vector table location using this function as such:
NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x8004000)

i.e changed SCB->VTOR = 0x8004000 to this location.
But even after doing this interrupt is not happening. Should I do anything more to make this project work?

A: You should not use NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x8004000), use NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x4000). The second argument is the "offset", not the absolute address.

A: Add the below instruction just after the HAL_Init();
SCB->VTOR = (FLASH_BASE | 0x4000);
You also need to update the interrupt vector address in the STM32F1xc_flash.icf file as below.
define symbol ICFEDIT_intvec_start = 0x08004000;

A: I did this for my STM32L496, and it was important to set the new vector table before calling HAL_Init(), because it calls HAL_MspInit(), which may use the SysTick to measure timeouts while setting up some peripherals.