text:
Q: For a dictionary compare both key and value with the values in a list I have the following structures:
prev = { 'alpha:10.2': '145', 'teta:180': '198', 'eltira:140': '222', 'ronta:23.14':220}
now = ['alpha:10.3','teta:180', 'eltira:142']

and the following code:
   old = []
    for k, v in prev.iteritems():
     if k not in now:
       old.append(v)

So if the key from the dict prev is not found in the list now, I add the value to the old list.
Result 'old= [ '145', '222']`
But, I want to check also which part doesn't correspond from the key. I'm inclined to use namedtuple.
Package = collections.namedtuple('Package', 'name version')

for k, v in prev.items():
  name, version = k.split(':')
  Package(name=k, version='v')

*

*if the name corresponds but the version not, do the same as above.

*if the name is not found add it to a new list old_names, but also do as above.

The issue is that if k not in now will not work. I can do it with two loops and three ifs but maybe there is an option to do it more clean.
Expecting output:
old=[ '145', '222']
old_names=['ronta']

A:
I have splitted the 'now' list and converted it to a dictionary (name:version) which takes a single iteration. Later, the values from the dictionary can be accessed in constant time for further operations.

prev = { 'alpha:10.2': '145', 'teta:180': '198', 'eltira:140': '222', 'old:1. 43':'150'}
now = ['alpha:10.3','teta:180', 'eltira:142']

now_dict = {}
old = []
old_names = []

for items in now:
  temp0,temp1 = items.split(':')
  now_dict[temp0] = temp1

for k,v in prev.items():
   name,version = k.split(':')
   if name not in now_dict.keys():
      old_names.append(name)
      old.append(v)
      continue

   if version != now_dict[name]:
      old.append(v)
      continue

   else:
     continue

if __name__ == '__main__':
  print(old_names)
  print(old)

A: Here is a way to do it:
prev = { 'alpha:10.2': '145', 'teta:180': '198', 'eltira:140': '222', 'zeta:12.1' : '334'}
now = ['alpha:10.3','teta:180', 'eltira:142']

now_splited = [nk.split(":") for nk in now]

old = []
old_name = []
for k, v in prev.items():
    if k not in new_key:
        old_n, old_v = k.split(":")
        name = any(map(lambda n : n[0] == old_n, now_splited))
        version = any(map(lambda n : n[1] == old_v, now_splited))
        if name and not version:
            old.append(v)
        elif not name:
            old_name.append(old_n
            old.append(old_v))

Results :
>>> print(old, old_name)
['145', '222', '334'] ['zeta']

A: You can make now a dict by maping operator.methodcaller to it and wrapping it in dict() then a comprehension will be easy using the same method on prev:
splitter = operator.methodcaller('split', ':')
now_dict, kv_map = dict(map(splitter, now)), map(splitter, prev)

old = [prev[':'.join((k,v))] for k, v in kv_map if k in now_dict]
old_names = [n for n, v in kv_map if n not in now_dict]

Results:
#old
['145', '198', '222']
#old_names
[]


text:
Q: VBA add FreezePanes to open file I'm stuck. Try to add FreezePanes to all my excel files.
I have 28 folders "municipalities" in each folder 16 files: 1first, 2second,...
All filese Excel 2003 formats, and are divided into two types - with a figure in the title and without. Each file has several pages.
In parent directory i create file "base" in each two pages "municipalities" and "FilesList" and macro "Sub AddTo Freeze()"
Sub addToFreeze()
    x% = firstDataBaseString
    Do While Application.Workbooks(thisFileName).Worksheets("municipalities").Cells(x, 2) <> Empty
        y% = firstDataBaseString
        actMun$ = Application.Workbooks(thisFileName).Worksheets("municipalities").Cells(x, 2)
        Do While Application.Workbooks(thisFileName).Worksheets("FilesList").Cells(y, 1) <> Empty
            actFile$ = TrimFormats(Application.Workbooks(thisFileName).Worksheets("FilesList").Cells(y, 1)) & addedToMunicipal & ".xls"
            openWaN$ = ThisWorkbook.Path & Application.PathSeparator & actMun & Application.PathSeparator & actFile
            Dim fileHaveNum As Boolean
            fileHaveNum = HasNumber(Application.Workbooks(thisFileName).Worksheets("FilesList").Cells(y, 1))
            If FileExists(openWaN) Then
                Dim openApp As Excel.Application
                Set openApp = New Excel.Application
                openApp.DisplayAlerts = False
                openApp.Visible = True
                openApp.ScreenUpdating = False
                Dim openBook As Workbook
                Set openBook = openApp.Workbooks.Open(openWaN)
                For Each ws In openBook.Worksheets
                    ws.Unprotect Password:="P$n177"
                    afName$ = TrimFormats(actFile)
                    sName$ = ws.Name
                    Workbooks(afName).Worksheets(sName).Activate
                    If fileHaveNum Then
                        Range("G4:G4").Select
                        ActiveWindow.FreezePanes = True
                    Else
                        Range("G6:G6").Select
                        ActiveWindow.FreezePanes = True
                    End If
                    ws.Protect Password:="P$n177"
                Next
                openBook.Close SaveChanges:=True
                openApp.ScreenUpdating = True
                openApp.Quit
            End If
            y = y + 1
        Loop
    x = x + 1
    Loop

End Sub

Every tyme when i try run macro his say "Subscript out of range". Or add FreezePanese to my "base" file....

A: Solution:
Dont use
Dim openApp As Excel.Application
Set openApp = New Excel.Application
Dim openBook As Workbook
Set openBook = openApp.Workbooks.Open(openWaN)

Need use
Dim openBook As Workbook
Set openBook = Workbooks.Open(openWaN)
Workbooks(openBook.Name).Activate

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL - INSERT DELAYED <- deprecated What now? I've just been looking at the MySQL doc's https://dev.mysql.com/doc/refman/5.7/en/insert-delayed.html
I was intending to use an INSERT DELAYED, but I see that this has been deprecated.
I still need this functionality for compatibility with some PHP code that is handling some very large data transfers. I'm quite happy to update my PHP but I have no idea how to achieve the same functionality now.
How would we achieve the same outcome as traditional INSERT DELAYED now that it's deprecated?

A: According to the MySQL 5.5. Documentation

INSERT DELAYED works only with MyISAM, MEMORY, ARCHIVE, and BLACKHOLE tables. For engines that do not support DELAYED, an error occurs.

You could downgrade to MySQL 5.5 (Of course, I am joking). I have three suggestions. Please look into them.
SUGGESTION #1
You could setup MySQL Replication and perform the following

*

*Bulk insert into a table on the Master whose storage engine is BLACKHOLE.

*The same table on the Slave would be InnoDB. Perform your SELECTs on the Slave

*See my 3.5-year-old post How to do something like UPDATE DELAYED in MySQL
SUGGESTION #2
Tuning the InnoDB Environment to handle faster writes. Please see my 4.5-year-old posts How to use insert delay with the InnoDB engine and use less connection for insert statements? and Mysql load from infile stuck waiting on hard drive
SUGGESTION #3
Customize the bulk insert to use extended inserts that load a fixed number of  rows at a time like a mysqldump does.

A: I take your question to mean, that you need to defer work until after a given period of time.
In these circumstances, I would use a queue and defer my queue job for the required time.
As an example https://laravel.com/docs/5.3/queues#delayed-dispatching
Though from the docs "queued to be inserted when the table is not in use by any other thread" is not achievable as is via this method, you would need to implement this functionality in your job if it is required.


text:
Q: Editext values getting cleared while moving from one activity to another activity I have three edittext and one button in Main Activity.
If I click button in MainActivity it will move to Activity2. And, if click button in Activity2 it will move back to Main activity. The MainActivity edittext values getting cleared if I go back MainActivity.
I need to save the edittext values. Is there any way to do this except Shared Preferences.
Main Activity
public class MainActivity extends AppCompatActivity {

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

        Button bt1 = findViewById(R.id.btn1);

        final EditText et1 = findViewById(R.id.et1);
        final EditText et2 = findViewById(R.id.et2);
        final EditText et3 = findViewById(R.id.et3);

        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(),Activity2.class);
                startActivity(intent);
            }
        });

    }
}

Activity2
public class Activity2 extends AppCompatActivity {

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

        Button bt2 = findViewById(R.id.btn2);

        bt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(),MainActivity.class);
                startActivity(intent);
            }
        });

    }
}


text:
Q: Group by on substring in a cell I have a table with column name message and this column contains the values in a fixed format like below.
Format:-
QU FRASELH  .CPHBOSK LH/050840  COR MVT

What i need is to count no of messages based on group by on 2nd substring (e.g FRASELH in above case)
SELECT COUNT(*), ORIGIN_QUEUE
FROM info
where TIME_STAMP >='2016-10-05 00:00:00'and TIME_STAMP<= '2016-10-06 00:00:00'
group by (????)

Thanks in advance.

A:
@EmilHolub fixed format means values in each cell for message column are having same format. for example one cell has 4 values (first substring has 2 character _space_2nd substring has 6 character_space and so on).now this format is fixed for all cells under message column.

Given that it should be sufficient to do:
SELECT substr(ORIGIN_QUEUE,4,6) COUNT(*),
FROM info
where TIME_STAMP >='2016-10-05 00:00:00'and TIME_STAMP<= '2016-10-06 00:00:00'
group by substr(ORIGIN_QUEUE,4,6)

It will group your values based on the 4th to 9th character in the ORIGIN_QUEUE string.


text:
Q: iOS webview gets stuck in a scroll state and JavaScript doesn't respond I'm finding that I'm having problems with iOS webviews. I have a webview which is longer than my ipod4's screen, so I can scroll up and down. If I quickly drag and tap on the screen for a few seconds, I will get into the state where the scroll bar on the right stays permanently on the screen. Once this happens, if I drag the screen in any direction, the page no longer has any momentum and I can no longer flick the page. I.e., it stays in the exact same position once I take my finger off the screen.
I also find while it's in this state that I can drag the page further off the screen (to a point where it would usually bounce back), and it no longer bounces back. The screen capture I have included is an image of my white page after being dragged up, and the scroll bar being stuck on the screen.
The only way of getting out this locked scroll bar state is too zoom on the webpage with two fingers.
I have a button which also doesn't perform it's javascript function when in this state.
Unfortunately, I have not been able to consistently reproduce this state, so tapping and dragging in quick succession is the best reproduction I have.

A: I don't think your webviews should ever be inside a scrollable area because websites themselves need to scroll as well. I would suggest that you use autolayouts to attach the webview to whatever the size of the container it's contained is in and let it figure out if and how to scroll itself.
A webview is really an app in an app and should be treated a bit differently than the rest of your app.


text:
Q: ASN.1 / binary notes specific anotation? I am working with "binary notes" a ASN.1 environment in Java.
First I created a class of an asn.1 sequence by hand.
@ASN1String(name = "", isUCS = false, stringType = UniversalTag.PrintableString)
@ASN1Element(name = "firstName", isOptional = false, hasTag = false, hasDefaultValue = false)
private String firstName = null;

Now I am wondering what that "@" sign means? I tried to find hints in the source of binary notes, and found the following:
package org.bn.annotations;
import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ASN1String {
    String name();
    boolean isUCS();
    int stringType();
}

Can someone explain the notation to me?
Would be nice. Thanks in advance.
nyyrikki

A: In Java, "@Foo" is an annotation. It's intended for a part of your particular build environment to interpret it. Generally annotations get replaced with chunks of Java code.
More information on annotations: http://download.oracle.com/javase/1.5.0/docs/guide/language/annotations.html
My guess is that you need to look up documentation on ASN.1 to know what those specific annotations do.

A: I'm author this framework. This is Java annotation feature (meta information) for your fields/classes used to control some ASN.1 features.
For your sample it's a string field encoding to ASN.1 byte stream as ASCII string (not unicode string) without tag and it's not optional (required) for parent structure (ASN.1 sequence).
For details you can start read it http://en.wikipedia.org/wiki/ASN.1#Standards


text:
Q: Closest true value to zero in Python A long time ago I read about the closest true value to zero, like zero = 0.000000001, something like that. In the article they mentioned about this value in Python and how to achieve it. Does anyone knows about this? I have look up here in SO but all the answers are about the closest value to zero of an array and that's not my point.

A: The minimum positive denormalized value in Python3.9 and up is given by math.ulp(0.0) which returns 5e-324, or 4.940656e-324 when printed with format(math.ulp(0.0), '.7').


text:
Q: Where is ~/.bash_profile located in Windows Subsystem for Linux? When trying to access ~/.bash_profile from Ubuntu Xenial (16.04) in Windows Subsystem for Linux I get the following error:
-bash: /home/<username>/.bash_profile: No such file or directory

Where is it located and how do I edit it?
Thank you!

A: Bash subsystem
With the bash on windows the files are located at in the same location if you are running within the bash environment, ie /home/user_name/.bashrc .
Create the file , form bash, as suggested by Rinzwind if necessary.

Windows
However, if you are looking at the files from windows, outside the bash subsystem, they are located at
C:\Users\<username>\AppData\Local\Lxss\rootfs

so ...
C:\Users\<username>\AppData\Local\Lxss\rootfs\home\username

Note: The windows user name may or may not be the same as your bash username, depends on how you set bash up I suppose.
Warning - Dont edit or modify files in your bash environment from windows, see this link:
DO NOT, under ANY circumstances, create and/or modify Linux files using Windows apps, tools, scripts, consoles, etc.

A: From the man page for bash:

By  default, it first reads and executes commands from the file > /etc/profile, if that file exists.  After reading that file, it
  looks for  ~/.bash_profile,  ~/.bash_login,  and ~/.profile,  in that
  order, and reads and executes commands from the first one that exists
  and is readable.

So it exists in your home directory IF AND WHEN you create it and make it readable.


text:
Q: Итератор с методами класса У меня есть класс FileSystem, и я хочу хочу сделать, чтобы с итераторов можно было выполнять некоторые методы самого класса. Для этого в итератор добавил указатель на класс чтобы методы вызванные с итератора были примерно такими:
int FileSystem::iterator::make_dir(const std::string& name){
    return указатель_на_FileSystem->make_dir(name,указатель_на_Dir );
}

метод в классе FileSystem:
int FileSystem::make_dir(const std::string& name, Dir* & cur_dir);

Создавать итератор хотел так
iterator(this,указатель_на_Dir);

Проблема в том, что this - константный, соответственно в итераторе можно создавать можно только константные указатели на FileSystem и выполнять только константные методы.
Вопрос заключается в том, стоит ли делать
 const_cast<...>(this)

и насколько это плохо. Возможно стоит как-то пересмотреть архитектуру или использовать что-то другое?

A: this может иметь несколько разных типов:

*

*T * const при вызове функции-члена на константном объекте (т.е. нельзя изменять как сам this, так и то, на что он указывает);

*T * при вызове на изменяемом объекте (по прежнему нельзя изменять this, но можно изменять объект, на который он указывает);

*ещё пара вариантов с volatile (в данном случае, не рассматриваем).
Если создание вашего итератора происходит в константной функции, то и this имеет соответствующий тип. Таким образом, как минимум следует создавать итератор там, где объект, указываемый this может изменяться. Более того, не обязательно создавать итератор именно из функции-члена.
Преобразования const_cast, сбрасывающие константность у действительно константных объектов приводят к неопределённому поведению. Поэтому тут надо быть крайне осторожным.
В качестве возможного подхода предлагаю рассмотреть ситуацию с итераторами для стандартных контейнеров. Они имеют как const-версию, так и обычную. Т.е. существуют два отдельных класса итераторов. Надеюсь, такое объяснение позволит решить Вашу проблему.


text:
Q: Be $(u_n)$ and $(v_n)$ two sequences of real numbers converging to zero.
Be $(u_n)$ and $(v_n)$ two successions of real numbers converging to zero.  Let's suppose
that there is a number $M > 0$ such that: $\forall n \in \mathbb{N}, |v_{0}| + |v_1| + \ldots |v_n| \leq M$.

Show that: $\lim_{n -> \infty} u_{0}v_{n} + u_{1}v_{n-1}+ \ldots + u_{n}v_{0} = 0$

This is what I tried,
Prove:
We are gonna prove that $|u_{0}v_{n} + u_{1}v_{n-1}+ \ldots + u_{n}v_{0} - 0|< \epsilon $
so:
$|u_{0}v_{n} + u_{1}v_{n-1}+ \ldots + u_{n}v_{0}| \leq \sum_{k=0}^n|u_{k}v_{n-k}|$
but: $ \sum_{k=0}^n|u_{k}v_{n-k}| =  \sum_{k=0}^{n_{0}} |u_{k}||v_{n-k}| + \sum_{n_{0}+1}^n|u_{k}||v_{n-k}| $
then i can take:
$|v_{n}| + |v_{n-1}| + \ldots |v_{n-n_{0}}| + |v_{n-(n_{0}+1)}|+ \ldots + |v_{0}|\leq M$
therefore:
$|v_{n}| + |v_{n-1}| + \ldots |v_{n-n_{0}}| = \sum_{k=0}^{n_{0}}|v_{n-k}|\ \leq M $
on the other side, taking $n = n - (n_{0} +1)$:
$|v_{0}| + |v_1| + \ldots |v_{n -(n_{0}+1)}| = \sum_{k = n_{0}+1}^{n}|v_{n-k}| \leq M$
so, replacing:
$ \sum_{k=0}^n|u_{k}v_{n-k}| =  \sum_{k=0}^{n_{0}} |u_{k}||v_{n-k}| + \sum_{n_{0}+1}^n|u_{k}||v_{n-k}| \leq M( \sum_{k=0}^{n_{0}} |u_{k}| +  \sum_{n_{0}+1}^n|u_{k}|)$
and I'm stuck here; i thought, if the serie of $u_{k}$ were absl converged then i could put $\sum_{k=0}^{\infty}  |u_{k}|< \epsilon / 2M$. But i couldn't find the convergence.
Maybe this is not the way, can someone tell me a hint of what can i do to solve this problem pls.

A: Choose $N$ such that $|u_i| <\epsilon / M$ for $i \geq N$. $|\sum\limits_{i=0}^{n} u_iv_{n-i}|\leq |\sum\limits_{i=0}^{N} u_iv_{n-i}|+|\sum\limits_{i=N+1}^{n} u_iv_{n-i}|$ for $n >N$. Note that the second term does not exceed $\epsilon$ since $|u_i| <\epsilon / M$ for $n \geq N$. The forst term tends to $0$ as $ n \to \infty$. Hence $\lim \sup |\sum\limits_{i=0}^{n} u_iv_{n-i}| \leq 0+\epsilon =\epsilon$ whenever $n >N$.


text:
Q: Bootstrap divs don't line up when page is minimized This is what I have: http://codepen.io/auble220/pen/rOPBKP. I added media queries here: http://codepen.io/auble220/pen/avyZZE, which isn't too bad, but I know there has to be a better way. I tried using Bootstrap's clearfix class, but that doesn't change anything. This is the code for that section:
html:

    <button class="plusMinus" id="plus1">+</button>

05

    <button id="minus1" class="plusMinus">-</button>

break length

    <button id="plus2" class="plusMinus">+</button>

25

    <button id="minus2"class="plusMinus">-</button>

session length

css:
#brkSesDiv {
  margin: 30px 0 0 0;
  height: 100px;
  width: 350px;
  margin: auto;
}
#breakDiv {
  display: inline;
}
#breakLen {
  display: inline;
}
#sesDiv {
  float: left;
}
#sesLen {
  display: inline;
}

A: Here's an example of you how you can make this mobile first and may give you a base to adjust to your needs.
I would (personally) avoid mixing classes/IDs with structural elements like containers/rows/columns other then pure styling (ie color, text etc) as this can effect how the grid is designed to operate. You can however place your content inside these columns with much better results (generally speaking).
Have a fixed width for this isn't necessary, so I removed that as well as place everything inside of rows/columns instead of combining them:
#brkSesDiv {
  margin: 30px 0 0 0;
  height: 100px;
  width: 350px;
  margin: auto;
}

See working example Snippet.

var sec = 0;
var min;
var breakLenCount = 5;
var sesLenCount = 25;
var breakTimer;
var timerRunning = false;

$(document).ready(function() {
  $('#plus1').click(function() {
    if (breakLenCount < 9) {
      $('#breakLen').html('0' + (breakLenCount += 1));
    } else {
      $('#breakLen').html(breakLenCount += 1);
    }
  });
  $('#minus1').click(function() {
    if (breakLenCount < 9) {
      $('#breakLen').html('0' + (breakLenCount -= 1));
    } else {
      $('#breakLen').html(breakLenCount -= 1);
    }
  });
  $('#plus2').click(function() {
    if (sesLenCount < 10) {
      $('#sesLen').html('0' + (sesLenCount += 1));
      $('#min').html(sesLenCount);
    } else {
      $('#sesLen').html(sesLenCount += 1);
      $('#min').html(sesLenCount);
    }
  });
  $('#minus2').click(function() {
    if (sesLenCount < 11) {
      $('#sesLen').html('0' + (sesLenCount -= 1));
      $('#min').html(sesLenCount);
    } else {
      $('#sesLen').html(sesLenCount -= 1);
      $('#min').html(sesLenCount);
    }
  });

  min = sesLenCount;
  sec = 0;

  $('#timer').click(function() {
    if (timerRunning) {
      clearInterval(sesTimer);
      timerRunning = false;
      return;
    } else {
      sesTimer = setInterval(time, 1000);
    }
  });

  function time() {
    timerRunning = true;
    sec--;
    if (sec < 00) {
      sec = 59;
      min--;
    }
    if (sec < 10) {
      sec = '0' + sec;
    }
    if (min < 1 && sec < 1) {
      timerRunning = false;
      clearInterval(sesTimer);
      min = breakLenCount;
      $('#min').html(min);
      $('#sec').html(00);
      bTimer = setInterval(breakTimer, 1000);
    }
    $('#min').html(min);
    $('#sec').html(sec);
  }

  function breakTimer() {
    sec--;
    if (sec < 00) {
      sec = 59;
      min--;
    }
    if (sec < 10) {
      sec = '0' + sec;
    }
    if (min < 1 && sec < 1) {
      clearInterval(bTimer);
      min = sesLenCount;
      $('#min').html(min);
      $('#sec').html(00);
      setInterval(time, 1000);
    }
    $('#sec').html(sec);
    $('#min').html(min);
  }
});
body {
  font-family: Arial, sans-serif;
}
h1#pTimer {
  font-size: 5em;
}
h1.title {
  font-size: 4em;
  color: #444444;
  text-shadow: 3px 3px 5px;
}
#brkSesDiv {
  padding-top: 10px;
}
#breakDiv {
  display: inline;
}
#breakLen {
  display: inline;
}
#sesLen {
  display: inline;
}
.plusMinus {
  border-radius: 25%;
  border: 1px solid transparent;
  background-color: transparent;
  color: #444;
  font-size: 2.5em;
  font-weight: bold;
}
#timer {
  margin: 25px auto 0 auto;
  width: 300px;
  height: 300px;
  border: 3px solid #444;
  border-radius: 50%;
  box-shadow: 0px 0px 25px;
  background-color: #fff;
  cursor: pointer;
  display: table;
  vertical-align: middle;
}
#time {
  display: table-cell;
  vertical-align: middle;
}
@media (max-width: 480px) {
  h1#pTimer {
    font-size: 2.5em;
  }
  h1.title {
    font-size: 2em;
  }
  #timer {
    margin: 10px auto 0 auto;
    width: 175px;
    height: 175px;
  }
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />

Pomodoro Timer

          <button class="plusMinus" id="plus1">+</button>

05

          <button id="minus1" class="plusMinus">-</button>

break length

          <button id="plus2" class="plusMinus">+</button>

25

          <button id="minus2" class="plusMinus">-</button>

session length

Session

25:00


text:
Q: Git Hub Contribution - Fork or Branch I have created a repo on Github and added a contributor to
work with me on the project. I'm a little confused as to how
to instruct them to work on the project
Some docs are saying they should fork the project to their
own account and then clone locally
Other are saying create branches of the master
Im new to git and he is.. but i have working knowledge of
CVS and SVN im  confused as to instruct him the best way
to checkout my master and work on it
So should I tell him to fork and clone.. or If i tell him to
branch.. does he need to do an initial checkout of the master first?
Just trying to clear this up..
Oh.. also question for my own sanity.. I should be working off a branch
off my own master.. and how does that effect the local files when
I switch through branches

A: Whether to fork your repo or just clone and branch depends on your workflow. If you want to manage your project like a centralized system, then simply have him clone your repo locally on his machine using:
git clone https://github.com/username/your-project.git

Then he can make a branch and request that you pull from his clone. If you want to try the distributed method of source control management, then have him fork your repo. Then he can clone, make changes, push to his fork, and then send you a pull request right on github. I recommend forking because pulling from another machine seems a little more complicated and because github has some very nice features for displaying the changes that have been made. No matter which way you do it, I would recommend branching, making your changes and then merging back to master (you can see the reasoning in the answer to this question).

Oh.. also question for my own sanity.. I should be working off a
  branch off my own master.. and how does that effect the local files
  when I switch through branches

When you switch branches, git removes all your previous branch's commits and changes from files and then adds all commits and changes to files from your new branch. Also I recommend checking out the git documentation. It should be able to answer basic questions about how git works and how you can get started using it.


text:
Q: filter array of objects with dates I am trying to fetch the data and store into 2 separate arrays from given below array of objects which meet following two conditions

*

*From the current Array of objects, I want to only get the objects whose month is the current month.

*another array for past 7 days
How can I do soo?
can I get any tip to work with dates as I am not soo good with it?
{
    "status": "success",
    "results": 10,
    "orders": [
        {
            "orderID": 1,
            "orderStatus": 1,
            "purAmt": 1000,
            "orderDate": "2020-06-14T03:23:20.000Z",
            "fullName": "velocity",
            "email": "velocity@gmail.com",
            "phone": "999999",
            "flatNo": "b-863",
            "complex": "tara tra",
            "landmark": "kaskd",
            "street": "asdasd",
            "area": "rob city",
            "city": "asda",
            "products": [
                {
                    "productID": 1,
                    "name": "lassi",
                    "price": 62,
                    "image": "images\\rtoRAOwj4-conn.PNG",
                    "quantity": 5
                },
                {
                    "productID": 2,
                    "name": "curd",
                    "price": 55,
                    "image": "curd.png",
                    "quantity": 9
                }
            ]
        },
        {
            "orderID": 2,
            "orderStatus": 1,
            "purAmt": 1000,
            "orderDate": "2020-06-14T03:24:32.000Z",
            "fullName": "velocity",
            "email": "velocity@gmail.com",
            "phone": "999999",
            "flatNo": "b-863",
            "complex": "tara tra",
            "landmark": "kaskd",
            "street": "asdasd",
            "area": "rob city",
            "city": "asda",
            "products": [
                {
                    "productID": 6,
                    "name": "chicken chilly",
                    "price": 65,
                    "image": "images\\PIwc5RQ7s-conn2.PNG",
                    "quantity": 1
                },
                {
                    "productID": 7,
                    "name": "buteer flyyy",
                    "price": 70,
                    "image": "images\\GvIgYj-lO-conn2.PNG",
                    "quantity": 2
                }
            ]
        },
        {
            "orderID": 4,
            "orderStatus": 1,
            "purAmt": 250,
            "orderDate": "2020-06-15T09:04:45.000Z",
            "fullName": "velocity",
            "email": "velocity@gmail.com",
            "phone": "999999",
            "flatNo": "b-863",
            "complex": "tara tra",
            "landmark": "kaskd",
            "street": "asdasd",
            "area": "rob city",
            "city": "asda",
            "products": [
                {
                    "productID": 1,
                    "name": "lassi",
                    "price": 62,
                    "image": "images\\rtoRAOwj4-conn.PNG",
                    "quantity": 1
                },
                {
                    "productID": 2,
                    "name": "curd",
                    "price": 55,
                    "image": "curd.png",
                    "quantity": 1
                }
            ]
        },
        {
            "orderID": 5,
            "orderStatus": 2,
            "purAmt": 250,
            "orderDate": "2020-05-15T10:33:59.000Z",
            "fullName": "velocity",
            "email": "velocity@gmail.com",
            "phone": "999999",
            "flatNo": "b-863",
            "complex": "tara tra",
            "landmark": "kaskd",
            "street": "asdasd",
            "area": "rob city",
            "city": "asda",
            "products": [
                {
                    "productID": 2,
                    "name": "curd",
                    "price": 55,
                    "image": "curd.png",
                    "quantity": 1
                }
            ]
        },
        {
            "orderID": 6,
            "orderStatus": 2,
            "purAmt": 250,
            "orderDate": "2020-06-15T10:41:53.000Z",
            "fullName": "velocity",
            "email": "velocity@gmail.com",
            "phone": "999999",
            "flatNo": "b-863",
            "complex": "tara tra",
            "landmark": "kaskd",
            "street": "asdasd",
            "area": "rob city",
            "city": "asda",
            "products": [
                {
                    "productID": 2,
                    "name": "curd",
                    "price": 55,
                    "image": "curd.png",
                    "quantity": 1
                }
            ]
        },
        {
            "orderID": 7,
            "orderStatus": 2,
            "purAmt": 250,
            "orderDate": "2020-06-15T10:44:58.000Z",
            "fullName": "velocity",
            "email": "velocity@gmail.com",
            "phone": "999999",
            "flatNo": "b-863",
            "complex": "tara tra",
            "landmark": "kaskd",
            "street": "asdasd",
            "area": "rob city",
            "city": "asda",
            "products": [
                {
                    "productID": 2,
                    "name": "curd",
                    "price": 55,
                    "image": "curd.png",
                    "quantity": 1
                }
            ]
        },
        {
            "orderID": 8,
            "orderStatus": 2,
            "purAmt": 250,
            "orderDate": "2020-06-15T11:00:57.000Z",
            "fullName": "velocity",
            "email": "velocity@gmail.com",
            "phone": "999999",
            "flatNo": "b-863",
            "complex": "tara tra",
            "landmark": "kaskd",
            "street": "asdasd",
            "area": "rob city",
            "city": "asda",
            "products": [
                {
                    "productID": 2,
                    "name": "curd",
                    "price": 55,
                    "image": "curd.png",
                    "quantity": 1
                }
            ]
        },
        {
            "orderID": 9,
            "orderStatus": 1,
            "purAmt": 250,
            "orderDate": "2020-06-15T11:01:50.000Z",
            "fullName": "velocity",
            "email": "velocity@gmail.com",
            "phone": "999999",
            "flatNo": "b-863",
            "complex": "tara tra",
            "landmark": "kaskd",
            "street": "asdasd",
            "area": "rob city",
            "city": "asda",
            "products": [
                {
                    "productID": 2,
                    "name": "curd",
                    "price": 55,
                    "image": "curd.png",
                    "quantity": 1
                }
            ]
        }
    ]
}

A: The Date object here will help a lot. To get orders this month you could try something like:
orders.filter(order => {
  const orderDate = new Date(order.orderDate);
  const today = new Date();
  const isThisYear = orderDate.getFullYear() === today.getFullYear()
  const isThisMonth = orderDate.getMonth() === today.getMonth();

  return isThisYear && isThisMonth;
})

And to get in the last 7 days you could try something like:
orders.filter(order => {
  const orderDate = Date.parse(order.orderDate); // in milliseconds
  const today = Date.now(); // in milliseconds
  const millisecondsInAWeek = 604800000;

  return orderDate > today - millisecondsInAWeek;
})


text:
Q: iOS/Objective-C: UINavigationBar delegate not called Here are 3 controllers - ViewController subclass of viewController, SecViewController subclass of viewController, nvgc subclass of UINavigationController.
SecViewController is child controller of nvgc and pushes to viewController. In SecViewController, I use delegate method of UINavigationBar but it never gets called. I tried to use it in nvgc, but it didn't work either. Kindly help me locate the issue.
#import "nvgc.h"
@interface nvgc ()<UINavigationBarDelegate,UINavigationControllerDelegate>

@end

@implementation nvgc

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationBar.delegate=self;
    self.navigationController.navigationBar.delegate=self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPushItem:(UINavigationItem *)item{
    return YES;
}
-(BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item{
    return NO;
}
-(void)navigationBar:(UINavigationBar *)navigationBar didPopItem:(UINavigationItem *)item{
}
-(void)navigationBar:(UINavigationBar *)navigationBar didPushItem:(UINavigationItem *)item{
}
@end

A: I asked my friend.Then I knew from him that my scene structure is bad.I only use push method but not pop.Finally,I modify my scene structure.And I change to use code to push controller but not storyboard.Then UINavigationBar delegate is called.


text:
Q: How I can bind textblock with bolded and normal text I have a part of text which some of the words are formatted.
These text are listed in a ListBox. When user clicks ListBoxitem, I want to collect that selectedItem and take user to the other place. My problem is that I cant bind TextBlock with another instance of TextBlock. And that TextBlock has many inlines, which I want to show.
I have been trying this solution:
<ListBox Width="800" Name="foundedTextBlocksListBox" SelectionChanged="foundedTextBlocksListBox_SelectionChanged" Background="Transparent" ItemsSource="{Binding}" Grid.Row="2" Visibility="Visible" Height="Auto" HorizontalAlignment="Center">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel VerticalAlignment="Center" Orientation="Vertical">
                    <TextBlock x:Name="foundedTextBlocks" DataContext="{Binding Textblock}"></TextBlock>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

After Binding to DataContext like this:
            ObservableCollection<FoundedTextBlock> listOfFoundedTextBlockResults = new ObservableCollection<FoundedTextBlock>();
            TextBlock textblock = new TextBlock();
            while (blockString.IndexOf("<b>") != -1)
            {
                int startOfWord = blockString.IndexOf("<b>");
                int endOfWord = blockString.IndexOf("</b>");
                string text = blockString.Substring(0, startOfWord);
                textblock.Inlines.Add(text);
                string boldedWord = blockString.Substring(startOfWord + 3, endOfWord - startOfWord - 3);
                textblock.Inlines.Add(new Run() { Text = boldedWord, FontWeight = FontWeights.Bold });
                blockString = blockString.Substring(endOfWord + 4);
                textblock.Inlines.Add(blockString);
            }
            textblock.Tag = dbInfo;
            listOfFoundedTextBlockResults.Add(new FoundedTextBlock() { Textblock = textblock });
        }
        foundedTextBlocksListBox.DataContext = listOfFoundedTextBlockResults;

I can't see any ListBoxItems in ListBox. Is my Binding wrong or is this possible at all?
I managed before to get TextBlock.Text property to show but not the Inlines where are bolded text or any other Inlines after my first inline addition to TextBlock.
How I can solve this annoiyng problem? In short, I need to display many TextBlocks with formatted text...
FoundedTextBlock class has TextBlock textblock {get;set;} property
I'm saving to Tag property my class instance, so I could collect the information I need when SelectedValueChanged event occurs.

A: Maybe you should use a ContentPresenter instead of TextBlock in your XAML
Replace
 <TextBlock x:Name="foundedTextBlocks" DataContext="{Binding Textblock}"></TextBlock>

with
<ContentPresenter Content="{Binding Textblock}" />

Please try it out ... the rest of your code is missing to provide a better answer.


text:
Q: Can not find class org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory in Tomcat7/Ubuntu 12.10? (Possible bug) Tomcat7: 7.0.30-0ubuntu1.1
Tomcat 7 has the jar files commons-dbcp.jar and tomcat-dbcp.jar but in tomcat-dbcp.jar, it is the file org.apache.tomcat.dbcp.BasicDataSourceFactory class instead of org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory that is looking for.
root cause
javax.naming.NamingException: Could not create resource factory instance [Root exception is java.lang.ClassNotFoundException: org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory]
    org.apache.naming.factory.ResourceFactory.getObjectInstance(ResourceFactory.java:121)
    javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:321)
    org.apache.naming.NamingContext.lookup(NamingContext.java:843)
    org.apache.naming.NamingContext.lookup(NamingContext.java:154)
    org.apache.naming.NamingContext.lookup(NamingContext.java:831)
    org.apache.naming.NamingContext.lookup(NamingContext.java:168)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    java.lang.Thread.run(Thread.java:722)

A: A solution is given for this same problem on StackOverflow by modifying the resource tag in conf/context.xml to use factory="org.apache.commons.dbcp.BasicDataSourceFactory" instead of Tomcat 7 default factory. You can see there the cause of this problem.
The resource tag will look something like (taken from the referenced answer):
<Resource name="jdbc/myDataSource"
    auth="Container"
    type="javax.sql.DataSource"
    driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/myDatabase"
    username="username" password="password"
    validationQuery="SELECT COUNT(*) FROM MY_TABLE"
    factory="org.apache.commons.dbcp.BasicDataSourceFactory" />

A: The default DataSource factory in tomcat 7 is org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory. This is contained in a jar file which the Debian maintainers don't distribute.
Tomcat 7 now includes another connection pool implementation which can be used instead, but it isn't default.
org.apache.tomcat.jdbc.pool.DataSourceFactory

We could change the default factory to this that it is already included in the current distribution and so solve this problem.
Ubuntu version: 12.10
tomcat7: 7.0.30-0ubuntu1.1


text:
Q: SSIS Constraints We have containers(steps) which only run on Wednesdays.  I want SSIS/VS to wait until that has been evaluated before proceeding.
Please see this picture for an example:

In the example, Pass_3 only runs on Wednesdays.  I want Pass_Final to wait, until Pass_3 is evaluated and either runs with Success or doesn't run.  If either of those occur, go to Pass_Final.  But, if Pass_3 runs and fails, don't proceed to Pass_Final.  The way it is currently, if Pass_3 doesn't run, Pass_Final will not run.
Is this possible?
Visual Studio 2015/SSDT 2015

A: This would be easier to follow, I'm sure, if I provided an image, but right now I only have time to type.  Hopefully this will be clear enough.
What you need to do is to re-work the pass_3 path so that it returns true when it's not Wednesday.
One way to do that is to add a dummy script task that doesn't do anything between pass_3 and pass_final.   So you will have completion constraints going from pass_3 to dummy_task and also from dummy_task to pass_final.
THEN you add a constraint from pass_1 straight to dummy_task that checks to see if the day is NOT Wednesday.  And use an OR condition on the constraints going to dummy_task so that only one of them has to be true.
What this does is, on Wednesday, pass_3 will be used, and when completed, it will activate dummy_task which will pass through to pass_final, and every other day, pass_3 will be skipped, but dummy_task will still get activated and pass through to pass_final.
hope this is clear enough.


text:
Q: Best sorting algorithm for case where many objects have "do-not-care" relationships to each other I have an unusual sorting case that my googling has turned up little on.  Here are the parameters:

1) Random access container.  (C++ vector)
2) Generally small vector size (less than 32 objects)
3) Many objects have "do-not-care" relationships relative to each other, but they are not equal.  (i.e. They don't care about which of them appears first in the final sorted vector, but they may compare differently to other objects.)  To put it a third way (if it's still unclear), the comparison function for 2 objects can return 3 results: "order is correct," "order need to be fliped," or "do not care."
4) Equalities are possible, but will be very rare.  (But this would probably just be treated like any other "do-not-care."
5) Comparison operator is far more expensive than object movement.
6) There is no comparison speed difference for determining that objects care or don't care about each other.  (i.e. I don't know of a way to make a quicker comparison that simply says whether the 2 objects care about each other of not.)
7) Random starting order.

A: Whatever you're going to do, given your conditions I'd make sure you draw up a big pile of tests cases (eg get a few datasets and shuffle them a few thousand times) as I suspect it'd be easy to choose a sort that fails to meet your requirements.
The "do not care" is tricky as most sort algorithms depend on a strict ordering of the sort value - if A is 'less than or equal to' B, and B is 'less than or equal to' C, then it assumes that A is less than or equal to C -- in your case if A 'doesn't care' about B but does care about C, but B is less than C, then what do you return for the A-B comparison to ensure A will be compared to C?
For this reason, and it being small vectors, I'd recommend NOT using any of the built in methods as I think you'll get the wrong answers, instead I'd build a custom insertion sort.
Start with an empty target vector, insert first item, then for each subsequent item scan the array looking for the bounds of where it can be inserted (ie ignoring the 'do not cares', find the last item it must go after and the first it must go before) and insert it in the middle of that gap, moving everything else along the target vector (ie it grows by one entry each time).
[If the comparison operation is particularly expensive, you might do better to start in the middle and scan in one direction until you hit one bound, then choose whether the other bound is found moving from that bound, or the mid point... this would probably reduce the number of comparisons, but from reading what you say about your requirements you couldn't, say, use a binary search to find the right place to insert each entry]
Yes, this is basically O(n^2), but for a small array this shouldn't matter, and you can prove that the answers are right. You can then see if any other sorts do better, but unless you can return a proper ordering for any given pair then you'll get weird results...

A: You can't make the sorting with "don't care", it is likely to mess with the order of elemets. Example:
list = {A, B, C};
where:
A dont care B
B > C
A < C

So even with the don't care between A and B, B has to be greater than A, or one of those will be false: B > C or A < C. If it will never happen, then you need to treat them as equals instead of the don't care.

A: What you have there is a "partial order".
If you have an easy way to figure out the objects where the order is not "don't care" for a given objects, you can tackle this with basic topological sorting.
If you have a lot of "don't care"s (i.e. if you only have a sub-quadratic number of edges in your partial ordering graph), this will be a lot faster than ordinary sorting - however, if you don't the algorithm will be quadratic!

A: I believe a selection sort will work without modification, if you treat the "do-not-care" result as equal.  Of course, the performance leaves something to be desired.


text:
Q: Memory leak with Visual Studio running alongside web application I'm running a web application with models defined in C# and views being in HTML5, client-side business logic is JavaScript/jQuery. I've noticed something odd recently. Whenever both Visual Studio and my web application are running simultaneously, the browser memory usage starts to climb. It is worse in IE and Chrome, but likewise substantial in Firefox (all the latest versions of these browsers). Also, the memory usage of Visual Studio starts to climb. The CPU usage for the browser hovers in the teens, normally hovering around 0 otherwise.
Once I close down either the web application, or Visual Studio, the memory stops growing, and indeed, closing Visual Studio often allows the browser to run its garbage collection and clean up the mess. I suspect this has something to do with some sort of background debugging going on. I'm surprised that googling this hasn't turned up a similar issue for somebody somewhere in the world, and I suspect it's some kind of configuration setting in my IDE. Visual Studio 2013 Premium. I've reset my settings (Tools -> Import and Export Settings -> Reset all settings, with no effect. Building in Release mode likewise seems to have no effect. I'll keep hunting this one down, but has anyone here seen anything like this and resolved it?
edit: I have recently been debugging some dynamic code using the debugger keyword. I've commented that out, and am still seeing the same results. But I wonder if there isn't some lingering effect from using this in the first place?
edit: Updating Resharper from 8.2 to 9.2 didn't help either.
edit: Apparently this issue has been seen before and reported, if you just know what to google for.

A: Visual Studio has a browser link feature that causes the web app to poll Visual Studio in case you have changed a file.
In VS there is a small refresh icon in the debug menu with a drop down. In there you can disable this feature.

A: Did you trying running the application without debugging? (Ctrl+F5)
To enable VS debug the browser more info is needed specifically things like scripts and eval code are needed even after use. So, running the browser with debugging enabled will use more memory and cause memory to grow with time.


text:
Q: "Package directory does not exist" when running setup.py with sdist I've got a game.py in ex48\ex48\game.py and my setup.py in ex48\docs\setup.py, I have init.py in both ex48\ex48__init.py and ex48\tests__init__.py . Game.py contains the following code:
class lexicon(object):

def __init__(self):
    pass

def lexicon(self):
    pass

setup.py contains the following code:
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

config = {
    'description': 'ex48',
    'author': 'My Name',
    'url': 'URL to get it at.',
    'download_url': 'Where to download it.',
    'author_email': 'My email',
    'version': '0.1',
    'install_requires': ['nose'],
    'packages': ['ex48'],
    'scripts': [],
    'name': 'ex48'
}

setup(**config)

When I run python -m setup.py sdist I get the following message:
PS C:\python\projects\ex48\docs> python -m setup.py sdist
running sdist
running egg_info
writing requirements to ex48.egg-info\requires.txt
writing ex48.egg-info\PKG-INFO
writing top-level names to ex48.egg-info\top_level.txt
writing dependency_links to ex48.egg-info\dependency_links.txt
warning: manifest_maker: standard file '-c' not found

error: package directory 'ex48' does not exist

Here's a picture of my file structure:
Why am I getting this error?
===========================EDIT===============================
I put the setup file in the root folder instead of docs as suggested below. I then tried to install again, and got this:
PS C:\python\projects\ex48> python -m setup.py sdist
running sdist
running egg_info
writing requirements to ex48.egg-info\requires.txt
writing ex48.egg-info\PKG-INFO
writing top-level names to ex48.egg-info\top_level.txt
writing dependency_links to ex48.egg-info\dependency_links.txt
warning: manifest_maker: standard file '-c' not found

reading manifest file 'ex48.egg-info\SOURCES.txt'
writing manifest file 'ex48.egg-info\SOURCES.txt'
warning: sdist: standard file not found: should have one of README, README.rst, README.txt

running check
creating ex48-0.1
creating ex48-0.1\ex48
creating ex48-0.1\ex48.egg-info
copying files to ex48-0.1...
copying ex48\__init__.py -> ex48-0.1\ex48
copying ex48\game.py -> ex48-0.1\ex48
copying ex48.egg-info\PKG-INFO -> ex48-0.1\ex48.egg-info
copying ex48.egg-info\SOURCES.txt -> ex48-0.1\ex48.egg-info
copying ex48.egg-info\dependency_links.txt -> ex48-0.1\ex48.egg-info
copying ex48.egg-info\requires.txt -> ex48-0.1\ex48.egg-info
copying ex48.egg-info\top_level.txt -> ex48-0.1\ex48.egg-info
Writing ex48-0.1\setup.cfg
Creating tar archive
removing 'ex48-0.1' (and everything under it)
C:\Python27\python.exe: No module named setup.py

So I got two warnings about files not found, and when I try to import modules from my game file in another script, I get:
PS C:\python\projects\ex48> python tests\ex48_tests.py
Traceback (most recent call last):
    File "tests\ex48_tests.py", line 1, in <module>
        from ex48.game import lexicon
ImportError: No module named game

So something's not working, but I'm not sure what.


text:
Q: Regex multiple line breaks I want to substitute the value of HTML <br> tag with 2 newlines. i.e what i want to is
$string=~s/br>/\n\n/s;

but somehow it doesn't work. Whereas it works fine for a single new line.
i.e. if i do this:
$string=~s/br>/\n/s;

it works fine.  What am I doing wrong?

A: If you're talking about vim's substitute command then you probably want to use \r in the replacement string instead of \n.  In this context vim treats \n as NULL, not newline.
Relevant snippet from :help sub-replace-special:
<CR>    split line in two at this point
        (Type the <CR> as CTRL-V <Enter>)          *s<CR>*
\r      idem                                       *s/\r*
\<CR>   insert a carriage-return (CTRL-M)
        (Type the <CR> as CTRL-V <Enter>)          *s/\<CR>*
\n      insert a <NL> (<NUL> in the file)


text:
Q: Awk - How to cut a line, check if a column matches something, print another column? I have a laaaaaarge file like this:
VENDOR|QTY|ITEM|PRICE
2|3|Sugar|15
3|3|Coffee|35
4|244|Sugar2|55
33|2|Pizza|36
3|3|Pizza|55
5|5|Pizza2|33
6|6|Pizza3|44

How do I print VENDOR and PRICE IFF ITEM is Pizza?
I've tried grep but it's slow.
I could write a python code like so,
for line in file:
    fields = line.split('|')
    if fields[2] == 'Pizza':
        print fields[0], fields[-1]

but I want to do it in Awk from the shell itself. How do I do this?
Update
How do I check substrings as well?
I want to output VENDOR and PRICE if Pizza occurs in ITEM?
Output should be:
33|36
3|55
5|33
6|44

A: This makes it:
$ awk -F\| '$3=="Pizza" {print $1,$4}' file
33 36
3 55

Explanation

*

*-F\| set | as field delimiter.

*$3=="Pizza" check if the 3rd field is "Pizza".

*{print $1,$4} prints the 1st and 4th fields.

Update

I want to output VENDOR and PRICE if Pizza occurs in ITEM?

$ awk 'BEGIN{OFS=FS="|"} $3~/Pizza/ {print $1,$4}' file
33|36
3|55
5|33
6|44

Explanation

*

*$3~/Pizza/ checks "occurs", as well as $3=="Pizza checks exact matching.

*BEGIN{OFS=FS="|"} sets the (input & output) field separator to be |.


text:
Q: How to search for entirely bold paragraphs? I need to be able to find paragraphs that are wholly bold (such as a subheading), but I've been struggling to figure it out or find much help online. I've seen similar questions but the responses are too complicated for me to really know what I'm replicating, despite trying to use parts that seem relevant.
My end goal is to, after finding a wholly bold paragraph, delete the character immediately following it (usually an empty line).
So far, this is my code, using MsgBox as my quick easy test to see if the search works correctly:
Dim para As Paragraph

For Each para In ActiveDocument.Paragraphs
    If Selection.Font.Bond = True Then MsgBox "All Bold"
    Else: Next para

What this macro does is bring up a MsgBox saying "All Bold" for each paragraph in the document (as in, if there are 50 paragraphs it brings the MsgBox up 50 times), rather than check each paragraph then bring up a MsgBox IF it's entirely bold. Ideally, in my actual document of about 50 paragraphs, only the 3 headings would prompt the MsgBox to appear.

A: As your code doesn't select anything Selection.Font.Bold does not relate to anything in the loop. By simply changing Selection to para.Range you will find only those paragraphs you are looking for.
Dim para As Paragraph

For Each para In ActiveDocument.Paragraphs
    If para.Range.Font.Bold = True Then para.Next.Range.Delete
Next para

The paragraph following can be accessed simply by using the Next property.
If the headings have been formatted using a style you could find them simply by looking for all instances of that style.


text:
Q: bash call variable built in loop some variables are built but I don't know how to call them.
I tried:
echo "$r$z"
echo $($r$z)
echo "$($r$z)"

or
echo "$r$i"
echo $($r$i)
echo "$($r$i)"

here is the way I build the variables:
z=0;for i in {1..3};do y=$(( RANDOM % 10 ));r[z++]=$y;done

or
for i in {1..3};do eval "r$i=$(( RANDOM % 10 ))";done

the expected result should be:
r1r2r3

A: It might be better to store them in an array instead of creating r1, r2 and r3 variables. That's because, afaik, there's not really an way to create variables from other variables.
$ r=(0);
$ z=0;
$ for i in {1..3}; do
    (( y = RANDOM % 10 ));
    r+=($y);
done
$ for i in ${r[@]}; do echo $i; done

This produces an array with three integers, in my case:
8
1
9

A: The best is design to use arrays instead of handcooked variable names, hence Bayou's answer is what you're looking for.
Now, the way to expand variables the name of which is in another variable, exists in Bash (without using eval) and is called indirect expansion. You'll find some information about this in the Shell Parameter Expansion section of the reference manual.
In your case it will look like this:
for i in {1..3}; do
    # You need to create an auxiliary variable with the name of the variable to expand
    varname=r$i
    # Then use the indirect expansion (it's prefixed with an exclamation mark)
    echo "${!varname}"
done

This is considered poor practice and should be avoided whenever possible: the better design is to use arrays.

Just another comment about the way of creating variables without using eval is to use declare or printf. Here's how it goes with printf:
for i in {1..3}; do
    printf -v "r$i" "%d" "$((RANDOM % 10))"
done


text:
Q: Lost 2 weeks worth of progress by clicking 'Checkout' in Xcode source control, is there any way to recover it? I admit that I have very little experience with source control and git, however, in my past projects it has been useful to make commitments as backups. During this project, I decided to test out making a new branch. After working in it I decided to click 'checkout' master not knowing what it really did, now all my commits 2 weeks prior have been deleted, it's like I traveled back in time and all those commits I made never existed. All the files I had been working on are now gone and nowhere to be seen. I searched trash, I searched the project folder. They vanished. Did I screw up? Is there any way to recover this files? I searched all the branches without any luck. Thanks.

A: I don't know how Xcode's UI spells it, but the git command is git checkout @{1}.  Look up reflogs and revisions, @{1} is how git spells "what I had checked out just before I did whatever just changed it".

A:
Did I screw up?

Not necessarily! If you made commits on the new branch, everything is still there, on the new branch you created and worked on. So just checkout that branch again, and it will return!

now all my commits 2 weeks prior have been deleted

Ah, so you did make commits. In that case, be assured, nothing is lost.
But if you did not commit on the new branch — if you checked out master without committing your work from the new branch you were working on — then yes, you screwed up and it is all gone. The substance of git is commits, and whatever is not committed is not in the purview of git and is subject to unexpected loss. Loss due to checkout is a classic git trap; you would think it would warn you of the danger, but it doesn't always do that.


text:
Q: Show/Hide Button depending on stored procedure return value I'd like to get some help on an issue I'm having. I have a stored procedure that returns a dataset to fill a datagriview. One of the data grid's columns contains 2 manually set buttons, 'View' & 'Add'. These buttons open up a new popup window which displays extra information etc. I would like to be able to hide a 'View' button if 1 of the returned parameter's, POCount, count is equal to 0. i.e. there is nothing to view for that row. What is the best way to make this happen.
My stored procedure is
SELECT PM.ProjectCode,
       PM.ProjectDesc,
       PM.Active,
       PM.Chargeable,
       (SELECT COUNT(*) FROM POMaster PO WHERE PO.ProjectCode = PM.ProjectCode) AS POCount

FROM PROJECTMASTER PM

Front End Code
<asp:TemplateField HeaderText="P.O. Number" ItemStyle-Wrap="false" >
<ItemTemplate>
<asp:LinkButton ID="linkPONumber" runat="server" Text="View" CssClass="buttonStyle" OnClick="LinkPONumber_Click" CommandArgument='<%# Eval("ProjectCode") + ";" + Eval("ProjectDesc") %>' ></asp:LinkButton>
  <asp:LinkButton ID="linkAddPO" runat="server" Text="Add" CssClass="buttonStyle" OnClick="LinkAddPO_Click" CommandArgument='<%# Eval("ProjectCode") + ";" + Eval("ProjectDesc") %>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>

Code Behind
        private void BindGrid()
        {
            DSProjectDetails = objProjectMasterBL.GetProjectDetails();
            GvProject.DataSource = DSProjectDetails;
            GvProject.DataBind();
        }

        public DataSet GetProjectDetails()
        {
            try
            {
                SqlProcedureName = "USP_GetProjectListWithPO";
                SqlConnectionObject = DBConnection.InitializeConnection(SqlConnectionObject);

                dsrepeater = SqlHelper.ExecuteDataset(SqlConnectionObject, CommandType.StoredProcedure, SqlProcedureName);
                return dsrepeater;
            }
            catch (Exception ex)
            {
                log.Error("Exception in ProjectMasterBL.GetProjectDetails:", ex);
                throw ex;
            }
        }

Apologies if I've sent the wrong sections of code, still residing in the noob ranks

A: You can use the Visible property of Link Button:-
 <asp:LinkButton ID="linkAddPO" runat="server" Text="Add" CssClass="buttonStyle"
    OnClick="LinkAddPO_Click" Visible='<%# Convert.ToInt32(Eval("POCount")) == 0 %>'
   CommandArgument='<%# Eval("ProjectCode") + ";" + Eval("ProjectDesc") %>'>
 </asp:LinkButton>

Whenever your SP returns POCount as 0, you LinkButton will be hidden.


text:
Q: Is $S_3$ isomorphic to anything other than $D_3$? Problem: Is $S_3$ isomorphic to anything other than $D_3$?
I know that $S_3$ is isomorphic to $D_3$. Is it isomorphic also to some $\mathbb{Z}_n$ or $\mathbb{Z}_m \times \mathbb{Z}_n$?

A: There are only two non-isomorphic groups of order $6$: $Z_6$ and $S_3\cong D_3$. Therefore, $S_3\cong S_3/Z(S_3)$ cannot be isomorphic to any product of abelian groups.

A: When we talk about groups, there isn't really a good definition of "different" besides "non-isomorphic." For example, I can define the group $G_1$ generated by some element $x$ satisfying $x^{10}=1$, and I can also define the group $G_2$ generated by some element $y$ satisfying $y^{10}=1$. On one hand, these groups are clearly the same thing -- if you rename $x$ to $y$, you get $G_2$ from $G_1$, and vice versa; equivalently, they are both the cyclic group of order $10$. On the other hand, their elements aren't actually equal: $x$ does not equal $y$; there is no element of $G_2$ that "is" $x$. Our intuition about $G_1$ and $G_2$ being "the same" actually means that they are isomorphic.
There are, of course, other ways of defining groups that are isomorphic to the cyclic group of order $10$ that are less obviously "the same." We can, if we want, define a group $G_3$ generated by two elements $a$ and $b$ for which $a$ and $b$ commute, $a^2=1$, and $b^5=1$. There are $10$ elements of this group, and they look like
$$\{1,b,b^2,b^3,b^4,a,ab,ab^2,ab^3,ab^4\}.$$
It isn't that hard to check that $G_3$ is isomorphic to $G_1$ via $a\mapsto x^5$ and $b\mapsto x^2$. So, $G_3$ "is" the cyclic group of order $10$, which is to say that it is isomorphic to (any instance of) the cyclic group of order $10$.
So, for any group $G$, there are lots of different ways we can write groups that are isomorphic to $G$. For example, we can show that $S_3$ and $D_3$ are isomorphic, even though they do not "look the same." There are (probably) arbitrarily complex ways to write groups that are isomorphic to $S_3$, but in some sense, due to being isomorphic to $S_3$, they are actually $S_3$. One other example of a group that is "non-obviously" $S_3$ is $GL_2(\mathbb F_2)$, as noted by Qiaochu Yuan in the comments. In fact, because $|S_3|=6$ is a small number, it isn't too hard to show by hand that any group of order $6$ is either isomorphic to $\mathbb Z/6\mathbb Z$ or $S_3$ (we say that these are "the only groups of order $6$, up to isomorphism"). As a result, any group of order $6$ you can come up with will either be (isomorphic to) $\mathbb Z/6\mathbb Z$ or (isomorphic to) $S_3$.
One can, however, show that there are no groups in some particular classes of groups that are isomorphic to $S_3$. For example, the groups $\mathbb Z/m\mathbb Z$ and $\mathbb Z/m\mathbb Z\times \mathbb Z/n\mathbb Z$ are abelian groups. So, there is no way any of them are isomorphic to $S_3$.


text:
Q: how to print all the maven artifacts list which will be generated during the build? Is there a way to print all the maven build artficats which will be generated by a Maven project without running it ?
Tried something which is given here Create a list of artifacts that are build by a maven project
But it doesn't print all the artifacts. if project generates more than 1 artiafct then it lists only one artifact which is primary.

A: managed to achieve this in different way. by writing an extension which gives all the artiafcts info at the end of the build.
check it here https://stackoverflow.com/a/48575858/7315297


text:
Q: i can't switch between pages with react-router today i am writing my latest project.
but i have a problem with react router.
when i want to switch page from navbar
it can't.
here is the demo >> https://zedjf.csb.app/
if you can pls help me solve this problem, any suggestion will be very helpful to improve my project.
thnx.

github code: https://github.com/ennouri0maak/forslack

A: Add a separate component for home page instead of replace the router.
<Router>

    <Navbar />

       <Switch>
         <Route path="/about" component={About} />
         <Route path="/contact" component={Contact} />
         <Route path="/" component={Home}/>
       </Switch>

</Router>

It may resolve your issue.
Ref: Codebox Sample


text:
Q: c# WebClient catch Response Cookies and collect all of cookies for make a new successful requests I am trying to login a website then walk around for catch some infromation and do some stuff in it.
Everything is well when the request doesnt need any cookies, but some page need cookie which is created on first request. So I should collect all of cookies in WebClient object.
I am using this code but its not enough for me. Because still I am missing all of my cookies for next request.
public class CookieAwareWebClient : WebClient
{
    public CookieContainer CookieContainer { get; set; }
    public CookieCollection ResponseCookies { get; set; }
    //public CookieContainer ResponseCookieContainer { get; set; }

    public CookieAwareWebClient()
      : base()
    {
        CookieContainer = new CookieContainer();
        ResponseCookies = new CookieCollection();
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);

        HttpWebRequest webRequest = request as HttpWebRequest;
        if (webRequest != null)
        {
            webRequest.CookieContainer = CookieContainer;
        }

        return request;
    }

    protected override WebResponse GetWebResponse(WebRequest request)
    {
        var response = (HttpWebResponse)base.GetWebResponse(request);
        this.ResponseCookies = response.Cookies;

        return response;

    }

Here is my code for make request.
var loginLink ="https...."; // an Uri with username and password values as queryString

   CookieAwareWebClient client = new CookieAwareWebClient();
   var loginResult = client.DownloadString(loginLink);

I can see the result , yes I am in! login was success, but I am losting all of my cookies , and next request sending me to login page..
I should collect all of cookies in my webcilent cookieContainer. I should read Response Header for set "Set-Cookie" values to my container.
Think about this, I have 3 key in my cookies before request.
a = "123",
b = "asd",
c = "123"

and now I send a request to website and its returning me 2 cookies(one is new and one is old key with new value) back,(I can see in response Headers , in "Set-Cookie")
a = "123456",
d = "blabla"

so  I need to change key of "a"s value, and I need to add "d" key to my Cookie, because I dont want to go back to login page on my next request again...
Maybe I need a library, maybe a better WebClient Class whcih can collect all cokkies to help me to discover all pages.
I hope someone can help me.
Best Regards!


text:
Q: RuntimeError: shape '[-1, 784]' is invalid for input of size 614400 I'm practicing code that implements the "Auto-Encoding Variable Bayes (VAE)" paper.
However, the error "RuntimeError:shape [16, 1, 28, 28] is invalid for input of size 37632" has not been resolved. I don't know how to solve it. Please help me.
EPOCHS = 50
BATCH_SIZE = 16
# Transformer code
transformer = transforms.Compose([
            transforms.Resize((28, 28)),
            transforms.ToTensor()
])

# Transform data
train_set = torchvision.datasets.ImageFolder(root = "/home/seclab_dahae/dahye/VAE_data", transform = transformer)
train_set, test_set = train_test_split(train_set, test_size=0.2)
print("Train size is {}, test size is {} ".format(len(train_set), len(test_set)))

#test_set = torchvision.datasets.ImageFolder(root = "/home/seclab_dahae/dahye/VAE_data", transform = transformer)

# Loading trainloader, testloader
trainloader = torch.utils.data.DataLoader(train_set, batch_size = BATCH_SIZE, shuffle = True, num_workers = 2)
testloader = torch.utils.data.DataLoader(test_set, batch_size = BATCH_SIZE, shuffle = True, num_workers = 2)

This is the code that brings my data to pytorch.
# VAE model
class VAE(nn.Module):
    def __init__(self, image_size, hidden_size_1, hidden_size_2, latent_size): #28*28, 512, 256, 2
        super(VAE, self).__init__()

        self.fc1 = nn.Linear(image_size, hidden_size_1)
        self.fc2 = nn.Linear(hidden_size_1, hidden_size_2)
        self.fc31 = nn.Linear(hidden_size_2, latent_size)
        self.fc32 = nn.Linear(hidden_size_2, latent_size)

        self.fc4 = nn.Linear(latent_size, hidden_size_2)
        self.fc5 = nn.Linear(hidden_size_2, hidden_size_1)
        self.fc6 = nn.Linear(hidden_size_1, image_size)

    def encode(self, x):
        h1 = F.relu(self.fc1(x))
        h2 = F.relu(self.fc2(h1))
        return self.fc31(h2), self.fc32(h2)

    def reparameterize(self, mu, logvar):
        std = torch.exp(0.5 * logvar)
        eps = torch.randn_like(std)
        return mu + std * eps

    def decode(self, z):
        h3 = F.relu(self.fc4(z))
        h4 = F.relu(self.fc5(h3))
        return torch.sigmoid(self.fc6(h4))

    def forward(self, x):
        mu, logvar = self.encode(x.view(-1, 784))
        z = self.reparameterize(mu, logvar)
        return self.decode(z), mu, logvar

VAE_model = VAE(28*28, 512, 256, 2).to(DEVICE)
optimizer = optim.Adam(VAE_model.parameters(), lr = 1e-3)

This is the part that implements the VAE model.
def loss_function(recon_x, x, mu, logvar):
    BCE = F.binary_cross_entropy(recon_x, x.view(-1, 784), reduction = 'sum')
    KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
    return BCE, KLD

Here is a code that implements a loss function.
def train(epoch, model, train_loader, optimizer):
    model.train()
    train_loss = 0
    for batch_idx, (data, _) in enumerate(train_loader):
        data = data.to(DEVICE)
        optimizer.zero_grad()

        recon_batch, mu, logvar = model(data)

        BCE, KLD = loss_function(recon_batch, data, mu, logvar)

        loss = BCE + KLD

        loss.backward()

        train_loss += loss.item()

        optimizer.step()

        if batch_idx % 100 == 0:
            print('Train Epoch: {} [{}/{} ({:.0f}%)]\t Loss: {:.6f}'.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                100. * batch_idx / len(train_loader),
                loss.item() / len(data)))

    print("======> Epoch: {} Average loss: {:.4f}".format(
        epoch, train_loss / len(train_loader.dataset)
    ))

def test(epoch, model, test_loader):
    model.eval()
    test_loss = 0
    with torch.no_grad():
        for batch_idx, (data, _) in enumerate(test_loader):
            data = data.to(DEVICE)

            recon_batch, mu, logvar = model(data)
            BCE, KLD = loss_function(recon_batch, data, mu, logvar)

            loss = BCE + KLD
            test_loss += loss.item()

            if batch_idx == 0:
                n = min(data.size(0), 8)
                comparison = torch.cat([data[:n], recon_batch.view(BATCH_SIZE, 1, 28, 28)[:n]]) # (16, 1, 28, 28)
                grid = torchvision.utils.make_grid(comparison.cpu()) # (3, 62, 242)

This is the train code and test code.
Jupiter's error occurred in the "recon_batch.view(BATCH_SIZE, 1, 28, 28)[:n]" section of the test code.
for epoch in tqdm(range(0, EPOCHS)):
    train(epoch, VAE_model, trainloader, optimizer)
    test(epoch, VAE_model, testloader)
    print("\n")
    latent_to_image(epoch, VAE_model)

Finally, This code is a trigger to start learning.
How can I solve this error?

A: It seems like your test images are not 28 by 28 pixels. You are trying to reshape/view a tensor that is not 28 by 28 to a shape that is incompatible. Is it possible your test data is a batch of 600 images of size 32 by 32?
Note that when you reshape/view a tensor you only change the arrangement of elements, but you cannot change the number of elements in the tensor.

A: A similar error was solved by replacing
mu, logvar = self.encode(x.view(-1, 784))
by
mu, logvar = self.encode(x.view(x.size(0), 784))
I hope this helps.


text:
Q: Horseshoe lemma for Cartan-Eilenberg resolution Let
$$0 \to A^\bullet \to B^\bullet \to C^\bullet \to 0$$
be a short exact sequence of bounded complexes of objects in an abelian category with enough injectives. Does there exist Cartan-Eilenberg resolutions $A^\bullet \hookrightarrow I^{\bullet,\bullet}$, $B^\bullet \hookrightarrow J^{\bullet,\bullet}$, and $C^\bullet \hookrightarrow K^{\bullet,\bullet}$ such that
$$0 \to I^{\bullet,\bullet}\to J^{\bullet,\bullet} \to K^{\bullet,\bullet} \to 0$$
is exact extending the above short exact sequence?
This is probably well-known and I would like to know in which references we can cite this result.


text:
Q: yum gives multilib version error I have two different arch of same package. rpm -qa libvirt-client gives output as-
libvirt-client-3.9.0-14.el7_5.2.i686 and
libvirt-client-1.2.17-13.el7.x86_64. When I give yum install libvirt-client it gives me a error as-
Error:  Multilib version problems found.
Protected multilib versions: libvirt-client-3.9.0-14.el7_5.6.x86_64 != libvirt-client-3.9.0-14.el7_5.2.i686.
Is there a way to install both of these packages?.
And moreover package-cleanup --dupes does not return these packages.

A: yum has as option --setopt which helps in ignoring the multilib problem. As -
yum --setopt=protected_multilib=false install 'packageName'


text:
Q: Array conversion using scikit-image: from integer to float I am facing some kind of problem when converting an integer image to a float image using scikit-image.
This is an example (the image is a 2 pixel image):
from numpy import array,uint8;
import skimage;

rgb = array([array([[0,0,0],[0,0,5]])])
i1 = skimage.img_as_float(rgb)#rgb.dtype ->dtype('int32')
i2 = skimage.img_as_float(rgb.astype(uint8))
i3 = skimage.img_as_float(rgb.astype(float))

print i1[0,1,:]
print i2[0,1,:]
print i3[0,1,:]

I expected this:
[ 0.  0.  5.]
[ 0.  0.  5.]
[ 0.  0.  5.]

But I got this:
[  2.32830644e-10   2.32830644e-10   2.56113708e-09]
[ 0.          0.          0.01960784]
[ 0.  0.  5.]

It is normal to loss precision from float to int, but here I am losing the real information when passing from int to float using img_as_float. I didn't found anything when reading the code on GitHub...
Why is this possible?

A: img_as_float() is not just type conversion, it convert full unsigned integer range to [0, 1], full signed integer range to [-1, 1].

*

*i1, the dtype is int32, means convert [-2147483648, 2147483647] to [-1, 1]

*i2, the dtype is uint8, means convert [0, 255] to [0, 1]

*i3, because the dtype is already float, do nothing.


text:
Q: Message from application: cannot load such file -- bundler/setup (LoadError) What do I do about this?
App 1090 stdout:
App 1090 stderr: Ignoring executable-hooks-1.4.2 because its extensions are not built.  Try: gem pristine executable-hooks --version 1.4.2
App 1090 stderr: Ignoring gem-wrappers-1.3.2 because its extensions are not built.  Try: gem pristine gem-wrappers --version 1.3.2
App 1090 stderr: Ignoring taglib-ruby-0.7.1 because its extensions are not built.  Try: gem pristine taglib-ruby --version 0.7.1
App 1090 stdout:

Trace on PasteBin.


text:
Q: how i can take a screenshot of a flash video while its playing using selenium webdriver? To automate the testing of videos, we decided to capture the screenshots of the video while its playing and compare those screenshots in order to ensure the video getting played. But when i am trying to capture the screenshots of the video player while video is getting played, only the black screen is getting displayed.
We are using selenium web-driver and JAVA for developing the automation scripts. Is there any other way that we can ensure the videos are getting played or not. Is there any flash support needed for taking screenshots of a flash video getting played?
Please help us with this. Is the method we following the correct one for video testing?
Please find my below selenium web-driver code
CODE
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Screenshot {

public static void main(String[] args) throws InterruptedException, IOException
{
    FirefoxDriver driver = new FirefoxDriver();
    driver.manage().window().maximize();
    FlashObjectWebDriver flashapp=null;
    flashapp = new FlashObjectWebDriver(driver,"PlayerPlatformAPI");
    driver.get("Flash media player URL");
    Thread.sleep(1000L);
    WebElement streamurl = driver.findElement(By.name("Stream URL"));
    streamurl.clear();
    streamurl.sendKeys("video link");
    WebElement    tune=driver.findElement(By.xpath("//div[@id='outer']//input[@type='button']"));
    tune.click();
    Thread.sleep(1000L);
    driver.findElement(By.id("PlayerPlatformAPI"));
    screen.seekTo(50);
    flashapp.callFlashObject("SeekTo","50");
    int i;
    for(i=0;i<4;i++)
    {
    File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
    // Now you can do whatever you need to do with it, for example copy somewhere
    File file1 = new File("c:\\tmp\\"+i+"_scrnshot.jpeg");
    FileUtils.copyFile(scrFile,file1);
    Thread.sleep(10000);
    }
    driver.close();
}
}


text:
Q: express route handler context is global (node.js) The route handler context is global? This makes it nearly impossible to pass an instance method of a class, or am I wrong here?
For example:
App.all('/anyRoute', instanciatedClass.REST);

Where as .REST is a method on that instance.
If this route is called, i just wanted to call another method on that class instance, but it is not available as this within the function seems to be the global context of the node app.
Anyone any ideas?
Didn't find any apply/call in express where the function is invoked.

A: That's because you're just passing the function itself. Once you do that, the context is gone.
There's at least two solutions for this:

*

*Create a wrapper function:
App.all('/anyRoute', function(req, res, next) {
  instanciatedClass.REST(req, res, next);
});

*Use function.bind() to bind the desired context to the function:
App.all('/anyRoute', instanciatedClass.REST.bind(instanciatedClass));

On an unrelated note, you might consider doing App.use() instead of App.all(), since the latter will add a separate route handler for every supported HTTP method, whereas the former will add just one route handler that still catches everything.


text:
Q: Java Regex that finds YYYY-MM even in a chaotic string I need a regex to find the year and the month value from filenames that can get very chaotic. My example here is "SuSa_Q2Factory_2012-08.xls". My regexes get annoyed because of the single "2" in the companys name that people sometimes write into the filename, too.
Currently my regex is looking like this:
// Search for date of the Format 2012-02 / YYYY-MM
if (fileName.matches("[0-9]{4}[\\-\\_\\.\\,\\ ][0-9]{2}\\.(xls|xlsx)")) {
int year = Integer.parseInt(fileName.substring(0, 4));
int month = Integer.parseInt(fileName.substring(5, 7));
return new Month(year, month);
}

// Search for date of the Format 2012-2 / YYYY-M
if (fileName.matches("[0-9]{4}[\\-\\_\\.\\,\\ ][0-9]\\.(xls|xlsx)")) {
int year = Integer.parseInt(fileName.substring(0, 4));
int month = Integer.parseInt(fileName.substring(5, 6));
return new Month(year, month);
}

A: You can use the Pattern and the Matcher classes:
import java.util.regex.Pattern;
import java.util.regex.Matcher;

[...]

String fileName = "SuSa_Q2Factory_2012-08.xls";
Pattern p = Pattern.compile(".*([0-9]{4})[-_., ]([0-9]{1,2})\\.(xls|xlsx)");
Matcher m = p.matcher(fileName);
if (m.matches()) {
    int year = Integer.parseInt(m.group(1));
    int month = Integer.parseInt(m.group(2));
    System.out.printf("year = %d, month = %d\n", year, month);
}

This prints year = 2012, month = 8
Your code didn't work because a company name doesn't have a fixed length and hardcoded substring indexes won't do (You just don't know where month-year part of the string starts). You need to capture month and year in a regular expression group and extract them with the Matcher.group(int) method.


text:
Q: How to insert time of user's logout in database? I successfully made the code for logging in...when user logs in, the time of logging in is written in database.
session_start();
    $query = mysql_query("SELECT * FROM users");
    $result = mysql_fetch_array($query);

    if(!empty($_POST['username']) && !empty($_POST['password'])){
        $username = ($_POST['username']);
        $password = ($_POST['password']);
        $username = stripslashes($username);
        $password = stripslashes($password);
        $username = mysql_real_escape_string($username);
        $password = mysql_real_escape_string($password);
        $_SESSION['username'] = $username;
        $_SESSION['password'] = $password;

$result = mysql_query("SELECT * FROM users WHERE username = '$username' AND status = '1'");
 if(mysql_num_rows($result) == 1) {
                mysql_query("INSERT INTO entry(id, username_id, entry_time) VALUES ('', 'bkrpan', NOW()) ");
                header("Location: admin.php");
                exit; }

        $result = mysql_query("SELECT username FROM users WHERE username = '$username' AND password = '$password'");
            if(mysql_num_rows($result) == 1) {
                mysql_query("INSERT INTO entry(id, username_id, entry_time) VALUES ('', '$username', NOW()) ");
            $_SESSION['username'] = $username;
            $_SESSION['password'] = $password;
            header("Location: users.php");
            exit; }
            echo "Login failed! You will be redirected.";
            echo "<meta http-equiv=\"refresh\" content=\"2;URL=index.php\">";
            }

    else {
        echo "Login failed! You will be redirected.";
        echo "<meta http-equiv=\"refresh\" content=\"2;URL=index.php\">";
    }

     session_destroy();

but...now I don't know how to make the code for logout.
This is something that I made, but it's not working.
 <?php
 mysql_connect("localhost", "root", "") or die("cannot connect");
 mysql_select_db("zavrsni_rad") or die("cannot select DB");
 session_start();
 $username = $_SESSION['username'];
 $sql = "SELECT * FROM users WHERE username = ".$username." AND password = ".$password;
 $result = mysql_query($sql);
 if(mysql_num_rows($result) == 1) {
$sql_2 = "INSERT INTO entry(username_id, entry_time) VALUES (".$username.", NOW()        )";
mysql_query($sql_2);
 }
session_destroy();
 header("location: index.php");
 ?>

A: You forgot the single quotes in your queries and you're not getting the value of $password
$sql = "SELECT * FROM users WHERE username = '".$username."' AND password = '".$password."'";

$sql_2 = "INSERT INTO entry(username_id, entry_time) VALUES ('".$username."', NOW())";

updated for clarity
<?php
session_start();

// check that the session exists first
if(isset($_SESSION['username'])) {

    // you should put your db connection in a config.php file and use mysqli or PDO - what you're using is depreciated
    mysql_connect("localhost", "root", "") or die("cannot connect");
    mysql_select_db("zavrsni_rad") or die("cannot select DB");

    // don't think I'd store password in a session...
    // also, is username UNIQUE in your database?
    // also, also, ALWAYS escape (sanitize) your database input to prevent agains SQL injection

    $sql = "SELECT username, password
    FROM
        users
    WHERE
        username = '".mysql_real_escape_string($_SESSION['username'])."'
    AND
        password = '".mysql_real_escape_string($_SESSION['password'])."'";
    $result = mysql_query($sql) or die('sql: '.mysql_error());

    if(mysql_num_rows($result) > 0) {
        $sql_2 = "INSERT INTO entry(username_id, entry_time) VALUES ('".mysql_real_escape_string($_SESSION['username'])."', NOW())";
        mysql_query($sql_2) or die('sql2: '.mysql_error());

        session_destroy();
        header("location: index.php");
    } else {
        echo 'There was an error. You have not been logged out.';
    }
}


text:
Q: Finding out the cause of the Hard Fault in lpc1788 I have been developing a firmware that has a heavy GUI library ported on lpc1788. I am using a 32 MB SDRAM for processing the fonts and images and a NAND flash to store the binaries of the font and bmp's, along with the device configuration data.
I have disable the Usage Fault, MemManage fault and Bus Fault. So sometimes when something goes wrong with any GUI function, the execution goes in Hard Fault. Now, the library that I have used for GUI is emWin and I have no means to know what function caused the Hard Fault. If the NAND flash is corrupted and the library tries to fetch anything to display, say a background image, then it goes in hard fault. I can handle such a situation, because I know for sure (by means of some code implementation with flags) that my NAND flash is corrupted and I need to reprogram the binaries into it, because if I don't, whenever the device is booted up, it will go in hard fault.
But, if some other routine causes the Hard Fault, then I actually should not reprogram the entire flash allover again.
So, if I know what caused the Hard Fault, I would be able to modify the handler accordingly deciding on whether I need to reprogram it or simply modify some parameters and carry on with the last know configuration.
Is there a way to determine what function caused the Hard Fault, run-time? Even the address would be enough. Can this be done?

A: Implement a hard fault handler that reports the stacked registers.  The PC register will indicate the execution address at which the exception occurred.
An example can be found here, though the use of printf in the example is probably ill-advised; you'd want something that wrote unbuffered direct to the UART I'd suggest - the system is already broken - the less code needed to get the diagnostic out the better.  The similar solution here simply copies the values to variables and requires you to set a breakpoint in your debugger to inspect them.
To see the code at the reported PC address, either consult your compiler's map and or list output files, or enter the address directly into the PC register in your debugger.


text:
Q: Vim Search/replace: what do I need to escape? I'm trying to search and replace $data['user'] for $data['sessionUser'].
However, no matter what search string I use, I always get a "pattern not found" as the result of it.
So, what would be the correct search string? Do I need to escape any of these characters?
:%s/$data['user']/$data['sessionUser']/g

A: :%s/\$data\[\'user\'\]/$data['sessionUser']/g

I did not test this, but I guess it should work.

A: Here's a list of all special search characters you need to escape in Vim: `^$.*[~)+/

A: There's nothing wrong with with the answers given, but you can do this:
:%s/$data\['\zsuser\ze']/sessionUser/g

\zs and \ze can be used to delimit the part of the match that is affected by the replacement.
You don't need to escape the $ since it's the at the start of the pattern and can't match an EOL here. And you don't need to escape the ] since it doesn't have a matching starting [. However there's certainly no harm in escaping these characters if you can't remember all the rules. See :help pattern.txt for the full details, but don't try to digest it all in one go!
If you want to get fancy, you can do:
:%s/$data\['\zsuser\ze']/session\u&/g

& refers to the entire matched text (delimited by \zs and \ze if present), so it becomes 'user' in this case. The \u when used in a replacement string makes the next character upper-case. I hope this helps.

A: Search and replace in vim is almost identical to sed, so use the same escapes as you would with that:
:%s/\$data\['user'\]/$data['session']/g

Note that you only really need to escape special characters in the search part (the part between the first set of //s). The only character you need to escape in the replace part is the escape character \ itself (which you're not using here).

A: The [ char has a meaning in regex. It stands for character ranges. The $ char has a meaning too. It stands for end-line anchor. So you have to escape a lot of things. I suggest you to try a little plugin like this or this one and use a visual search.


text:
Q: python icalendar setting dtstart properly I'm setting up a script to format a bunch of hockey schedules into .ics files, using python and the python package iCalendar.
When I set:
event.add('dtstart', game_datetime[i])
event.add('dtend', game_datetime[i]+timedelta(hours=i))

I get the following in the resultant .ics file:
DTSTART;VALUE=DATE-TIME:20141019T140500
DTEND;VALUE=DATE-TIME:20141019T160500

Clearly not ideal; it appears to be passing over the object and not the value. So when I try and set it using strftime() as following:
#event.add('dtstart', game_datetime[i].strftime('%Y%m%dT%H%M%SZ'))
#event.add('dtend', (game_datetime[i]+timedelta(hours=i)).strftime('%Y%m%dT%H%M%SZ'))

I get the following error:
File "D:\schedule_format.py", line 72, in <module>
event.add('dtstart', game_datetime[i].strftime('%Y%m%dT%H%M%SZ'))
File "C:\Python27\lib\site-packages\icalendar-3.9.dev0-py2.7.egg\icalendar\cal.py", line 171, in add
value = self._encode(name, value, parameters, encode)
File "C:\Python27\lib\site-packages\icalendar-3.9.dev0-py2.7.egg\icalendar\cal.py", line 123, in _encode
obj = klass(value)
File "C:\Python27\lib\site-packages\icalendar-3.9.dev0-py2.7.egg\icalendar\prop.py", line 276, in __init__
raise ValueError('You must use datetime, date, timedelta or time')
ValueError: You must use datetime, date, timedelta or time

So clearly I'm supposed to be using a datetime object, but apparently I'm not using it correctly?

A: You can use vDatetime function of icalendar package on a python datetime object
from icalendar import Calendar, Event, vDatetime
event.add('dtstart', vDatetime(starttime))

A: i don't know what you have in game_datetime but i faced this problem like you and use like this for date type property and it's work:
from time import strftime,gmtime
from icalendar import Calendar,Parameters,Todo
import icalendar
from datetime import *

year = int(strftime("%Y", gmtime()))
month = int(strftime("%m", gmtime()))
day = int(strftime("%d", gmtime()))
hour = int(strftime("%H", gmtime()))
minute = int(strftime("%M", gmtime()))
second = int(strftime("%S", gmtime()))

temp = Todo()
temp.add('CREATED',datetime(year,month,day,hour,minute,second))

you should change 'CREATED' to date type you want

A: Not quite sure what you are seeing as a problem:
RFC5545 section 3.3.5 ([link][1]), states:

Value Name:  DATE-TIME

Purpose:  This value type is used to identify values that specify a
precise calendar date and time of day.

Format Definition:  This value type is defined by the following
notation:

  date-time  = date "T" time ;As specified in the DATE and TIME

                              ;value definitions

[...]
For example, the following represents January 18, 1998, at
11 PM:
19980118T230000

Which looks very similar (and quite normally) to what iCalendar generated.
If you have a specific issue, could you clarify the desired output?
[1]: https://www.rfc-editor.org/rfc/rfc5545#section-3.3.5


text:
Q: SAGE (Financial Software) data to Tableau I was googling a lot, but couldn't find a solution.
I need to pull SAGE (Financial Software) data to Tableau.
I have Sage Intacct Web Services Developer License Credentials ready (sender_id, sender_password, user_id, user_password, and company_id)
If anyone was able to do that, could You please share how you did it?


text:
Q: a very special function $ f:\Bbb R \to \Bbb R$ Let $ f: \Bbb R \to \Bbb R$ be $C^{\infty}$. Such that for each $x\in \Bbb R$ there exist a natural number $n=n_x $ such that $ f^{(n)}(x)=0$. Let's consider the set $$
J = \left\{ x:\exists \left( {a,b} \right) \ni  x\,;\,f|_{\left( {a,b} \right)} \text{is a polynomial} \right\}
$$
Prove that the complement $ F = J^c$ has no intervals $[a,b]$ or in other words, F has empty interior, or in other words, J is dense.
I think that I have to use Taylor expansion but I don't know how :S


text:
Q: C++ pointer runtime error I made a program using structure and pointer. But for some reason it is not working properly. The main problem is that, for-loop would no go as it would. It would be helpful if you could solve this problem
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

struct Book{
    string name;
    int release;
};

int main(){
    //local variable
    int i;
    string release_dte;
    int choice;
    //interface
    cout << "Welcome to Book Storage CPP" << endl;
    cout << "How many entries would you like to make: ";
    cin >> choice;
    Book* Issue = new Book[choice];
    //for handler
    for (i = 0; i < choice; i++){
        cout << "Book: ";
        getline(cin, Issue[i].name);
        cout << "Release Date: ";
        getline(cin, release_dte);
        Issue[i].release = atoi(release_dte.c_str());
    }
    cout << "These are your books" << endl;
    for ( i = 0; i < choice; i++){
        cout << "Book: " << Issue[i].name << " Release Date: " << Issue[i].release << endl;
    }
    system("pause");
    return 0;
}

A: You're not checking if the input succeeded, nor are you clearing the new line left after the extraction into choice:

if ((std::cout << "Book: "),
        std::getline(std::cin >> std::ws, Input[i].name) &&
    (std::cout << "Release Date: "),
        std::getline(std::cin >> std::ws, release_dte))
{
    Input[i].release = std::stoi(release_dte);
}

You should also be using std::stoi for C++ strings as shown above.

A: I could not exactly infer  what is the problem you are referring to. But my guess is getline() function inside the for loop is not working properly, I suggest the code before the for loop to be like the following\
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');

for (i = 0; i < choice; i++){
    cout << "Book: ";
    getline(cin, Issue[i].name);
    cout << "Release Date: ";
    getline(cin, release_dte);
    Issue[i].release = atoi(release_dte.c_str());
}

Your final code should be
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

struct Book{
  string name;
  int release;
};

int main(){
//local variable
int i;
string release_dte;
int choice;
//interface
cout << "Welcome to Book Storage CPP" << endl;
cout << "How many entries would you like to make: ";
cin >> choice;
Book* Issue = new Book[choice];

cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');

//for handler
for (i = 0; i < choice; i++){
    cout << "Book: ";
    getline(cin, Issue[i].name);
    cout << "Release Date: ";
    getline(cin, release_dte);
    Issue[i].release = atoi(release_dte.c_str());
}
cout << "These are your books" << endl;
for ( i = 0; i < choice; i++){
    cout << "Book: " << Issue[i].name << " Release Date: " << Issue[i].release << endl;
}
system("pause");
return 0;

}
This will work as you intended