text:
Q: Devise 1.5 + Omniauth 1.0 + Facebook: undefined method `extra` I'm trying to get my Cucumber test to work with Devise 1.5 and Omniauth 1.0, with Facebook authentication. Funny thing is, it works on development mode, but when run the Cukes test, it fails with this message:
undefined method `extra' for #<Hash:0x007f95f0d26260> (NoMethodError)
./app/models/user.rb:13:in `find_for_facebook_oauth'
./app/controllers/users/omniauth_callbacks_controller.rb:4:in `facebook'
(eval):2:in `click_link'
./features/step_definitions/web_steps.rb:58:in `/^(?:|I )follow "([^"]*)"$/'
features/facebook_auth.feature:11:in `When I follow "Sign in with Facebook"'

Here is the corresponding method:
def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)

    data = access_token.extra.raw_info
    if user = User.where(:email => data.email).first
        user
    else
        User.create!(:email => data.email, :password => Devise.friendly_token[0,20])
    end
end

To get the Cukes test to be all green, I had to do this workaround, which then breaks the Development mode code. So for now, I'm doing this:
    case Rails.env
    when "test"
        data = access_token['extra']['user_hash']
        if user = User.find_by_email(data["email"])
            user
        else
            User.create!(:email => data["email"], :password => Devise.friendly_token[0,20])
        end
    else
        data = access_token.extra.raw_info
        if user = User.where(:email => data.email).first
            user
        else
            User.create!(:email => data.email, :password => Devise.friendly_token[0,20])
        end
    end

Seems like the offending line is data = access_token.extra.raw_info.
The way I'm mocking the Facebook hash is:
OmniAuth.config.add_mock(:facebook, {
    :uid => '12345',
    :nickname => 'zapnap',
    :extra => {
      :user_hash => {
        'email' => 'someone@webs.com'
      }
    }
  })

And I have turned on OmniAuth.config.test_mode = true by appending it at the last line of test.rb.
Any ideas would be greatly appreciated!

A: You can place settings in the spec_helper.rb, as alternative to stub_env_for_omniauth method.

  OmniAuth.config.test_mode = true
  OmniAuth.config.full_host = 'http://example.com'

  omni_hash = {
    'uid' => '12345',
    'provider' => 'facebook',
    "info" => {
      "email" => Faker::Internet.email,
      "image" => "http://example.com/pic.img"
     },
    "extra" => {
      "raw_info" => {
        "first_name" => Faker::Name.first_name,
        "last_name" => Faker::Name.last_name,
        "name" => Faker::Internet.user_name,
        "gender" => "male",
        "locale" => "en"
      }
    }
  }
  OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new(omni_hash)

A: I got exactly the same error and could somehow get it to be all green.
Although I use stub instead of mock
as is written here, hope it can be a help.
As it is discussed here, this occurs because OmniAuth1.0 uses Hashie::Mash for the part we got error.
So, we figured out to use a Hashie::Mash object to return instead of a Hash.
In order to do so,
I added this to spec_helper..
require "omniauth"

and modified stub method like this..
def stub_env_for_omniauth
  request.env["devise.mapping"] = Devise.mappings[:user]
  pre = { "omniauth.auth" => { "provider" => "facebook", "uid" => "1234", "credentials" => {"token" => "abcdefg"}, "extra"=>{"raw_info" => {"id" => "1234567", "email" => "ghost@nobody.com", "name" => "Mark", "gender" => "male" }}}}
  env = OmniAuth::AuthHash.new(pre)
  @controller.stub!(:env).and_return(env)
end

This works for me.

A: For Cucumber tests an additional mock object seems to work:
Given /^a new facebook user "([^"]*)"$/ do |name|
  OmniAuth.config.test_mode = true
  OmniAuth.config.mock_auth[:facebook] = {
    :provider => 'facebook',
    :uid => '123545',
    :name => name}

  m = mock("mock_extra",
    :raw_info =>
      mock("mock_raw_info",
        :email => 'someone@webs.com',
        :first_name => name,
        :last_name => "xyz"))

  OmniAuth.config.mock_auth[:facebook].stub(:extra).and_return(m)
end


text:
Q: Fit XAML path into view I have the following path. The data is from some data file:
<Path StrokeThickness="5" Stroke="Black" Fill="Yellow" Data="M 30330.8847248349,-37724.909002528 L 28556.3829935257,-37596.5557453925 28031.7660050946,-38008.0608378072 27746.4689258268,-38895.6687979239 27655.7148993139,-39397.1764657993 27718.5888966473,-39755.4955438608 27628.0246979519,-40621.440862981 28514.7500540091,-41208.8847446069 29093.8320242864,-40459.5872073251 29768.3831435369,-40107.7166927063 30092.4525793664,-39483.6045857995 30784.2658266352,-38627.7070622611 30811.846313938,-38537.1499823241 30358.6906348136,-37734.2759127391 30330.8847248349,-37724.909002528" />

I like to know what this looks like, so I want to render it in Kaxaml or XamlPad. Is there an easy way to resize this path so it will render nicely centered on the screen?

A: Just set the path's stretch attribute to Uniform to maitain the apsect ratio and you should be able to see it in KaXaml
    <Path Stretch="Uniform" StrokeThickness="5" Stroke="Black" Fill="Yellow" Data="M 30330.8847248349,-37724.909002528 L 28556.3829935257,-37596.5557453925 28031.7660050946,-38008.0608378072 27746.4689258268,-38895.6687979239 27655.7148993139,-39397.1764657993 27718.5888966473,-39755.4955438608 27628.0246979519,-40621.440862981 28514.7500540091,-41208.8847446069 29093.8320242864,-40459.5872073251 29768.3831435369,-40107.7166927063 30092.4525793664,-39483.6045857995 30784.2658266352,-38627.7070622611 30811.846313938,-38537.1499823241 30358.6906348136,-37734.2759127391 30330.8847248349,-37724.909002528" />

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create a trunk after merge from multiple developer branches in SVN (Tortoise SVN) My team is new to SVN, and I think we made a mistake of each developer creating their own branch and started adding code to their own branches.  Now, I need to merge all the branches into a trunk.  is there a safe way to do this?  I've been working on it, but I keep getting the "tree conflict" error when there's a file in a branch, that is not in the trunk.  Most of the files would be added, except for a few that would generate the error.
The trunk is initially empty, and I'm trying to merge one branch at a time.
We're using Tortoise SVN 1.7.9.
this is our current structure.
projectFoo

    - branches
        - dev1
            - proj1

        - dev2
            - proj1

        - dev3
            etc...

    - trunk
        - <empty>

A: You're going to have a fun time since everyone is working in their own branch, and the branches have nothing to do with each other. This isn't a merge in the programming sense. A true merge means that you split Branch "A" from Branch "B", so the two branches have a common ancestor revision, and you're now merging from "A" to "B" or "B" to "A".
There is no easy way to do what you need to do. If you are lucky, all of the developers are working on separate code, so merging simply means merging the branches together, and you'll have no real conflicts. If developers are working on the same file, but in different branches, you're in trouble.
You will need to use the --ignore-ancestors parameter when merging since there is no ancestor. That's the only thing I can say. However, once you get over this pain, you can resolve to use a more standard way of handling branching and merging. There are two paradigms
that are actually good to use. (There are several others, but they're basically toxic):

*

*Unstable Trunk: My personal favorite. Everyone works off of trunk. It's the way God designed Subversion to work. Branching is only done when necessary. The definition of when necessary is a bit nebulous. Basically, you branch when you need to because you don't want developers idle.

*Stream Development: In Stream Development, you have an integration stream (usually trunk) and developers create _development streams (aka branches) to do their work. A development stream might be a developer's personal workspace, an Agile task, a Jira issue, a feature. You basically create a branch off of trunk, do the work, rebase (aka merge from trunk to the development branch stream), and _deliver (aka merging from the development stream back to trunk).
As you can see, in the Unstable trunk, everything is very simple because there is very little branching going on. And since everyone works off of trunk, they communicate a bit better with everyone, and they take smaller development bites. It works great when combined with Continuous Integration.
When do you branch in the Unstable Trunk? Usually when you start finishing up one revision, and developers start working on the current revision and then next. Let's say everyone is working on release 1.2. Everyone works on the trunk. When you get to the point where some of the developers finish work on 1.2 and want to work on release 1.3, and there is still some cleanup work on release 1.2 to do, you branch a 1.2 release branch off of trunk.
Developers working on release 1.3 continue working on trunk. Developers firming up release 1.2 work on the 1.2 branch. When 1.2 i ready to be released, the 1.2 release is done off the 1.2 branch and tagged on the 1.2 branch. If a patch/hotfix release 1.2.1 is needed, it's also done on the 1.2 branch.
If an issue is found on the 1.2 branch and it also is an issue on the 1.3 release on trunk, you can easily merge that particular change on 1.2 back to trunk since the 1.2 branch came from trunk.
The Stream Development is favored by the Agile crowd because it allows you to pick and chose what to include in the integration branch (aka trunk). Many times, software isn't delivered into trunk until the sprint is almost complete. People who like this method like it because it offers flexibility, but I don't like it because continuous integration doesn't work too well with this method. Plus, you usually don't have a decent build until a few days before a release.


text:
Q: Programmatically using smartcard to login onto Active Directory (C#) Here is my scenario:
I have a client application running outside the domain, on a computer outside the domain.
My application needs to prompt the user to login with smart-card, and use the x.509 certificate on the card to authenticate against active directory.
While I did find some libraries that give access to the smartcard, I can't seem to find the right API to extract the certificate from the smart card (or from the store), and validate it against the AD.
Also, I am kind of lost on the many differnet libraries and framework: WCF, WSE (kerberos, x.509?), cryptoAPI etc.
To make my question focuesd: what would be the best direction in order to allow a user to login to a domain from my client application?
Thanks!


text:
Q: Партиционирование MySQL таблицы, как временное решение? В проекте есть пара таблиц, в которые по предположению, будет вестись активная запись. По моим расчетам она будет разбухать от 1-го до 4-х гигабайт в месяц. Чтение будет производиться крайне редко и в основном за текущий месяц.
Правильным ли будет применить партиции?
Планирую разбить помесячно, а идея с мерджем что-то совсем не нравиться. Или посоветуйте свой вариант. Благодарю.
P.S. Архивировать планирую, все старше полугода.

A: InnoDB убрать - оно заточено под связи между таблицами и обеспечение ссылочной целостности. Если данные льются в базу и практически не читаются, то лучше MyISAM, еще лучше - Archive. Индексы тут ни к чему. Партиции тоже - они нужны для таблиц, данные из которых постоянно читаются.
Здесь же: подумайте над возможностью фиксировать изменения при помощи триггеров в дополнительных таблицах, которые уже можно будет заточить под чтение. Вообще повод посмотреть в сторону связки OLTP+OLAP.
Второе. Подумать все-таки над вариантом создавать через некоторый промежуток времени новую таблицу. Например, раз в три-шесть месяцев. 4 гигабайта не очень много. Так что не привязывайтесь к месяцу.
Третье. Посмотрите в сторону MongoDB.


text:
Q: If I select a row I am going to do my best to explain this, though admittedly I have not attempted much in months so I'm not only rusty, I wasn't good to being with.
I am using visual web developers and asp, vb is the code behind with a sql db.
If I select a columns from a table, for example:
sqlCmd.CommandText = "SELECT Username, W1, W2, W3, W4 FROM tablename"

Say there are multiple rows in this table with data in these columns.
When I do a datareader, or how I have been shown, I declare dr like:
Dim dr As Data.SqlClient.SqlDataReader

I can work with the selected items such as:
dr.item(0)
dr.item(1)

etc.
But the only items I can work with are the first row of items selected.  How do I select all of the rows in the table.  Or how can I work with the data from multiple rows using dr.item or by somehow telling it to move onto the next row so that dr.item(0) becomes the username for the second row in the table.
I hope that made sense and I'm sorry if this is a stupid question.  I appreciate the time and help in advance.  Thanks guys.

A: SqlDataReader.Read advances the reader to the next record and returns true when there is at least one other row:
Using conn = New SqlClient.SqlConnection(connString)
    Using cmd = New SqlClient.SqlCommand("SELECT Username, W1, W2, W3, W4 FROM tablename", conn)
        conn.Open()
        Using dr = cmd.ExecuteReader()
            While dr.Read()
                Dim UserName As String = dr.GetString(0)
                ' ... '
            End While
        End Using
    End Using
End Using

Use Using to dispose anything that implements IDisposable as soon as possible. It will also close connections implicitely.
Edit: using a DataTable

How do I select all of the rows in the table

The DataReader approach above works well, but if you want to select all rows anyway and it's ok to load all into memory, you can use a DataTable instead. Then you could also access each row via indexer like an array or list:
Dim tblUsers = New DataTable()
Using conn = New SqlClient.SqlConnection(connString)
    Using da = New SqlClient.SqlDataAdapter("SELECT Username, W1, W2, W3, W4 FROM tablename", conn)
        da.Fill(tblUsers)
    End Using
End Using
' access a row via index: '
Dim row10 As DataRow = tblUsers.Rows(9)
Dim user10 = row10.Field(Of String)("Username")
' of course you can also iterate all rows: '
For Each row As DataRow In tblUsers.Rows
    Dim userName = row.Field(Of String)("Username")
Next

A: To iterate through the rows of Data Table you need to use the following method:
while dr.read()
 Dim col1=dr.item(0)
 Dim col2=dr.item(1)
End while

So that You can each Attribute of ALL Rows.


text:
Q: Unable to activate Lizard analyzer [vscode] Installing the C/C++ Advanced Lint extension in vscode offers supported Static Analyzers. lizard is amongst the list. I have lizard installed successfully via pip install lizard. But I still get the following error

The options in settings related to lizard are to either enable or override the feature

Not sure how I can get this to work. CppCheck worked fine after installing it via scoop install cppcheck


text:
Q: Python: Created custom package; error: name 'requests' is not defined (Although imported) I tried to create my own python package (basically as described in the first 2 chapters of https://learn.datacamp.com/courses/developing-python-packages).
The folder structure of the package is like this:
mainfolder contains
a)setup.py
b)subfolder with the same name as mainfolder
subfolder contains
a)init.py (plus the 2 underscores in front and after init; somehow that is not shown here)
b) module1.py
c) module2.py
d) module3.py
e) module4.py
the only content of init.py is the import statement of all 4 modules.
I installed this package with "pip install -e setup.py".
I can successfully import either the whole package or single modules.
Sadly I have one problem I can't solve:
One of the module contains code for a function that uses requests.get() and .json() to extract data from an online API and extracts the json.
When i try to use this function in another code file (after importing the function of course) i get an error: name 'requests' is not defined.
And that is although I imported requests at the start of the code. I also can use requests normally without errors there. Only when using my custom function this error is raised.
I was only able to fix the error by rating the import requests statement INSIDE the custom function module, but that is not nice.
Somehow other packages like pandas or json work inside my custom package without importing it there.
Any ideas?
Sorry for my confusing trains of thoughts ;-)


text: Q: Users Activity Data We have started tracking users activity in Sharepoint 2007, and while it doesn't matter that much, I know I am going to be asked - what does the data represent? Our highest users Value is 14.7. Is that vists in 30 days? Why the fraction?


text:
Q: It is possible to select table from database of remote server2 even you are in the remote server1, Not in local server? I have Remote_Server1 and Remote_Server2. From Remote_Server1 i want to select tables in the database of Remote_Server2
It is possible? If yes, How?
I try to use federated engine but it only in local server. I did not use local i want to use the remote server in my program.
If the solution is to enable federated engine in Remote server, How can I enabled it in my desktop?
I am new at Mysql.


text:
Q: Angular unidirectional data flow in nested forms I'm working on an angular app with nested forms. The main page contains the submit button for the entire page and each of the child components (which contain forms) needs to register itself with the parent form in order for validation of the entire page to work properly.
In order to do this I first tried having a FormArray in the page component and passing that to the children which then call formArray.push(this.formGroup). This worked properly except for the ExpressionChangedAfterItHasBeenCheckedError that I got.
Reading about the error I realized that this might be violating the principle of unidirectional data flow since the child updates the parent formArray.
I updated the logic instead to have the children emit events containing their own form groups and the page listens to these events and adds the child formGroups to the FormArray.
Unfortunately this still seems to sometimes cause the ExpressionChangedAfterItHasBeenCheckedError, even though to my understanding the unidirectional data flow is not being violated? It seems now that when the child component is initialized via *ngFor it works properly but directly putting the child component the template (without ngI or ngFor) causes the exception.
Any ideas on why this might be happening or general approaches to validating all nested forms on a page?


text:
Q: Using parameter as '#'( document.getElementById) for ajax (on javascript) gives me an error From a.html

   <form id='a' action='' method='POST'>
      ....
   </form>

And on script

   <form id='a' action='' method='POST'>
      <input type="submit"  value="submit"/>
   </form>

A: I hope this will helpful

    <form id='a' action='' method='POST'>
        ....
    </form>


text:
Q: How to turn Table auto-expand feature off? I want to copy some ranges, in the Helper Worksheet.
Indeed I want reformat that copied ranges and set them into Format as Table.
Each ranges contains a Title wanted be non Table format.
I tried code below:
ActiveSheet.ListObjects.Add(xlSrcRange, Range(Cells(UpLeft,1).Address ":" & Cells(DownRight, 20).Address), , xlYes).Name = "Table" & i

Everything is good when I perform first range to copy, but when I do copy next ranges, Previous 'Table format` have automatically expand and disturb Titles and Headers of the current range.
I had set end of each copied range size to entire print area Height using
(IIf(WS.PageSetup.Orientation = xlLandscape, 591, 852) - WS.PageSetup.TopMargin - WS.PageSetup.BottomMargin) * _ (100 / WS.PageSetup.Zoom) - 1

And add end of each copied range a Page brake with
WS.HPageBreaks.Add Before:=Rows(sh + 1).

And I need each range have start from top of page, so I cant leaving gaps between pastings
How can I prevent Table auto expand in a specific Worksheet?

A: Turn autoexpand off:
Application.AutoCorrect.AutoExpandListRange = False


text:
Q: How do I get a file system path from an OPEN_DOCUMENT intent? I'm building an android app in which I have to read a file from the Downloads folder of my Motorola G 2015 phone running Android Marshmallow (API v23).
To achieve this I'd like to choose the file via an OPEN_DOCUMENT or GET_CONTENT intent to leverage existing file-browsers on the user's phone, rather than implementing my own.
My manifest declares :
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

I have tried to receive the result from the intent like this:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case action_choose_file:
            Intent chooseFile;
            Intent intent;
            chooseFile = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            chooseFile.setType("application/epub+zip");
            intent = Intent.createChooser(chooseFile, "Choose a file");
            startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
            return true;
        .....
    }
}

To process the result I do this:
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case ACTIVITY_CHOOSE_FILE: {
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                String filePath = uri.getPath();
                final InputStream in = new FileInputStream(filePath);
            }
            break;
    ....
    }
}

However new FileInputStream fails with a ENOENT- file does not exist exception, and logging filePath reveals that it's value is something like /documents/2055 rather than the real filepath.
I suspect that I need something like querying DocumentProvider, but I could not find a case similar to mine.
It's worth mentioning that a couple of years ago my code used to work pretty much like this so I suspect something changed about the way android handles file access.
How do I access a file from the Downloads location of my android phone?

A:
How do I get a file system path from an OPEN_DOCUMENT intent?

You don't. There is no requirement that there be a file for that Uri, let alone one that you can access.

However new FileInputStream fails with a ENOENT- file does not exist exception, and logging filePath reveals that it's value is something like /documents/2055 rather than the real filepath.

Use a ContentResolver and openInputStream() and/or openOutputStream() to get a stream on the data represented by that Uri.

How do I access a file from the Downloads location of my android phone?

Either use an existing file-browsing library, or write your own file-browsing UI. The Storage Access Framework (ACTION_OPEN_DOCUMENT and kin) is for allowing the user to choose the content from where the user has chosen to store it, whether that be in a Downloads/ directory, or Google Drive, or Dropbox, or anywhere else.


text:
Q: Syntax of They're memories made
Nothing comparesNo worries or cares Regrets and mistakes They are memories made. Who would have known how bittersweet this would taste?

These are some lines from the lyrics of "Someone Like You" by Adele.
At first, I must tell you my question isn't about some deep interpretation, but it's about the syntax it holds. I had a disagreement with my English teacher discussing the syntax of the fourth line.
Some days before, she brought the class the song in question and interpreted the whole syntax and translated the meaning in our language. She said that the line I've got problem with means, to put it back to English, "They're what memories made.";that regrets and mistakes are what memories made. After which, I asked the teacher, "Isn't it 'They're memories which have been made'?" She replied no. Should I interpret the line as "They're what memories made" or "They're memories which have been made"?
Thanks.

A: "Memories made" does indeed refer to (the) memories (that have been) made, in this case from the "regrets and mistakes" that the singer is refusing to forget. Adele uses the same phrase on her website, which talks of her "soul-tinged songs of love's lost [sic] and memories made."
The other interpretation that "memories made" means "made by memories" doesn't quite work, as one would naturally use the singular form "memory made" instead.


text:
Q: "No matching function for call to" Templates C++ Help I don't understand why i can not run this snippet of code it is for a homework assignment and xCode seems to disagree with me when it says I havent defined the function. see bellow in main for the error
template <class Comparable>
Comparable maxSubsequenceSum1( const vector<Comparable> & a, int & seqStart, int & seqEnd){
        int n = a.size( );
        Comparable maxSum = 0;

        for( int i = 0; i < n; i++ )
            for( int j = i; j < n; j++ )
            {
                Comparable thisSum = 0;
                for( int k = i; k <= j; k++ )
                    thisSum += a[ k ];

                if( thisSum > maxSum )
                {
                    maxSum = thisSum;
                    seqStart = i;
                    seqEnd = j;
                }
            }

        return maxSum;

}

int main(){

        vector<int> vectorofints;
        vectorofints.resize(128);
        for (int i=0; i<vectorofints.size(); i++){
            vectorofints[i] = (rand() % 2001) - 1000;
        }
        maxSubsequenceSum1(vectorofints, 0, 127) //**---->the error i get in xcode is "No matching function for call to maxSubsequenceSum1"

        return 0;
}

A: Change the signature from
Comparable maxSubsequenceSum1( const vector<Comparable> & a,
                               int & seqStart, int & seqEnd)

to
Comparable maxSubsequenceSum1( const vector<Comparable> & a,
                                 int seqStart, int seqEnd)

The same problem happens if you would do int & i = 0;. You cannot initialize a non-const reference from an rvalue. 0 and 127 are temporary objects that expire at the end of the expression, temporaries cannot bind to non-const references.

A: The compiler is correct.  You are calling maxSubsequenceSum1(std::vector<int>&, int, int), you defined maxSubsequenceSum1(std::vector<int>&, int &, int &)
There are 2 quick solutions:
1)  Redefine your function to not take a reference.
2)  Move your constants to variables and pass them along that way.
Note: there is another problem with your code.  You invoke the function maxSubsequenceSum1, but you do not tell it what template parameter to use.
I have been corrected, and the correction is correct.  The note is not valid.

A: You have declared a function that expects two integer references but the one you are calling takes two integers by value.
It should be like this
vector<int> vectorofints;
        vectorofints.resize(128);
        for (int i=0; i<vectorofints.size(); i++){
            vectorofints[i] = (rand() % 2001) - 1000;
        }
        int k = 0;
        int j = 127;
        maxSubsequenceSum1(vectorofints, k, j)

        return 0;


text:
Q: WPF Trigger a storyboard in a usercontrol When click on button I am trying to develop a menu that looks like windows media center menu. So I made a usercontrol as a container which will contain menuitems (each menuitems is a usercontrol).I want to hide or display the container  after a click on a button.So  in click event of the button, i set  to true a dependencyproperty "DisappearProperty" (located in the container). But this method doesn't work.
to disappear the container, i trigger a storyboard based on "DisappearProperty" DependencyProperty. here the code :
//The container
<UserControl x:Class="MyUserControls.WMCBorder"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         mc:Ignorable="d"
         Name="UC"
         d:DesignHeight="300" d:DesignWidth="300">

 <UserControl.Resources>
    <ControlTemplate x:Key="ctContainer">
        <ControlTemplate.Resources>
    <Storyboard x:Key="SBDisappear">

        <DoubleAnimation Storyboard.TargetName="borderZooming"
                                         Storyboard.TargetProperty="ScaleX"
                                         From="1" To="4.0"
                                         Duration="0:0:0.1"/>
        <DoubleAnimation Storyboard.TargetName="borderZooming"
                                         Storyboard.TargetProperty="ScaleY"
                                         From="1" To="4.0"
                                         Duration="0:0:0.1"/>

                <DoubleAnimation Storyboard.TargetName="container"
                                         Storyboard.TargetProperty="Opacity"
                                         From="1"
                                         To="0"
                                         Duration="0:0:0.1"/>

    </Storyboard>

    <Storyboard x:Key="SBDisplay">

        <DoubleAnimation Storyboard.TargetName="borderZooming"
                                         Storyboard.TargetProperty="ScaleX"
                                         From="4" To="1.0"
                                         Duration="0:0:0.1"/>
        <DoubleAnimation Storyboard.TargetName="borderZooming"
                                         Storyboard.TargetProperty="ScaleY"
                                         From="4" To="1.0"
                                         Duration="0:0:0.1"/>

                <DoubleAnimation Storyboard.TargetName="container"
                                         Storyboard.TargetProperty="Opacity"
                                         From="0"
                                         To="1"
                                         Duration="0:0:0.1"/>

    </Storyboard>

        </ControlTemplate.Resources>
        <Border x:Name="container">
            <Border.RenderTransform>
                <ScaleTransform x:Name="borderZooming" ScaleX="0.1" ScaleY="0.1"/>
                </Border.RenderTransform>
                <Grid>
        <ContentPresenter />

            </Grid>
        </Border>

            <ControlTemplate.Triggers>
        <DataTrigger Binding="{Binding Path=DisappearProperty}" Value="true">
            <DataTrigger.EnterActions>
                <BeginStoryboard Storyboard="{StaticResource SBDisappear}"/>
            </DataTrigger.EnterActions>
        </DataTrigger>

        <DataTrigger Binding="{Binding Path=DisplayProperty}" Value="True">
            <DataTrigger.EnterActions>
                <BeginStoryboard Storyboard="{StaticResource SBDisplay}"/>
            </DataTrigger.EnterActions>
        </DataTrigger>
    </ControlTemplate.Triggers>

</ControlTemplate>
</UserControl.Resources>
<Grid>

</Grid>

//Code behind of the container
 public partial class WMCBorder : UserControl
{
    public WMCBorder()
    {
        InitializeComponent();
    }

    public bool Disappear
    {
        get { return (bool)GetValue(DisappearProperty); }
        set { SetValue(DisappearProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Disappear.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DisappearProperty =
        DependencyProperty.Register("Disappear", typeof(bool), typeof(WMCBorder), new PropertyMetadata(false));

    public bool Display
    {
        get { return (bool)GetValue(DisplayProperty); }
        set { SetValue(DisplayProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Disappear.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty DisplayProperty =
        DependencyProperty.Register("Display", typeof(bool), typeof(WMCBorder), new PropertyMetadata(false));

}

//The click event of the Hide button
  private void Button_Click(object sender, RoutedEventArgs e)
    {
        wmcb.Disappear = true;

     }

 //The click event of the Hide button
  private void Button2_Click(object sender, RoutedEventArgs e)
    {
        wmcb.Display= true;

     }

Thanks in advance.
As I received no response so far, so I simplified the question on this post


text:
Q: In Minecraft what's the best way to harvest wheat and wood underground? In my city we only have a small place for our house but we can build under it as much as we want so I want to build a place to grow wheat and trees. What's the best layout in terms of light (torches preferred) and water for growing them quickly?

A: This is what my underground tree farms usually look like.  I'm sure there are more efficient ways, but this is pretty good as far as the area/volume you need to excavate to the amount of trees that will grow.
It's just started to sprout, but if you leave it long enough you'll have solid walls of wood.

A: You need a light level of 9 or higher for wheat to grow. Saplings will need a light level of about 10 specifically above them, so one torch (which provides 14 light) nearby will suffice. There is a small disagreement on the wiki for what light level trees need, but 10 is the safe number. Beyond that light does not affect the rate at which they grow.
For wheat to grow quickly, however, you need to place it on hydrated farmland blocks, which meet the following constraints (from the Minecraft wiki):

*

*Water at the same level, or one block above the farmland block. Water one block below will not work.

*Water up to four blocks away, including diagonals.

*The blocks between the farmland block and the water make no difference.

Farmland blocks are made by tilling a dirt block with a hoe.
Other constraints are that wheat will only grow on farmland blocks and trees will only grow on dirt/grass blocks. Also, trees need at least 5 blocks of open air above them to grow at all, but leaving 14 blocks will allow almost all large trees to grow (source). Space around the sapling is not required but will result in more leaves and possibly wood, so I recommend leaving an open 5x5 area that is also 14 blocks tall and centered on the sapling in order to maximize each tree's potential wood output.
Here is a good example of an underground tree farm.

A: I've used the 80% efficiency tree farm from the wiki and it works very well. . Mine is above ground but the same results should work below ground.
I did place a canopy above the farm leaving an 8 block high space. This allows me to chop all the wood from ground level. After a couple minecraft days almost all the saplings have grown to full tress and produce a couple stacks of wood.


text:
Q: Need to extract. latest N records from MongoRepository My project requires that I extract latest N records from the MongoDB Collection. I have written my repository as follows:
public interface ActivityRepository extends MongoRepository<Activity, String> {

}
where Activity is defined as
@Document(collection = "Activity")
public class Activity {

    @Id
    private String id;
    private LocalDateTime createdOn;
    //other attributes
    //getters and setters
}

Within the ActivityRepository above, how can I extract the most recent N activities based on field createdOn?
Thanks
Singham


text:
Q: What were Darth Vader's day-to-day tasks/duties? Vader's role in the Empire/Imperial Forces was already discussed multiple times (here for example).
I understand that he has a special role, not comparable to any position in real world military and he primarily executed special tasks given by the emperor, like finding the rebel base, capturing Luke and so on.
But I asked myself what his day-to-day tasks were. Are there any canon sources (Legends would be fine for me, too) what he did on a day to day basis? Did he have administrative tasks or something of the like? I find it hard to believe all he did was meditating or standing on the bridge of a ship being bad-ass, when there weren't any urgent tasks (things we see him do in the movies)
Trying to be more specific:

*

*What did he do after he arrived on the Death Star 2 until the Emperor and later the Rebels showed up?

*What did he do during the time after the first Death Star was destroyed (his primary task seemed to be finding the rebel base, but again, I can hardly imagining him always standing on a bridge and giving orders like "Ok, go there, fly this way")

Are there any information on this topic?

A: Vader didn't have daily routine
In Canon, life of Vader is now described in two comics series : Star Wars:Darth Vader and Star Wars: Darth Vader: Dark Lord of the Sith. Without mentioning details, Vader was task-oriented. Those tasks would (of course) mostly came from his master Palpatine. Sometimes he had to work alone, sometimes in small groups, sometimes he commanded fleets and armies ...
Palpatine often tested him by pitting him against other Imperials, Vader  tried to clandestinely work for his own interests, but Palpatine mostly foresaw this. Vader acted according to Palpatine's plans even if he didn't know that (this is one of the reasons Vader feared and respected Palpatine). Vader did have some time for himself (for example to build his castle on Mustafar), and this is he used to better understand Dark Side of the Force.
Overall, Vader was not tied to specific unit, system or Galactic Sector, so he didn't regularly attend boring administrative meetings if they didn't concern his current mission.

A: Shadows of the Empire, Legends canon-imo best canon. Has Vader doing his daily activities of running the Empire. He practiced with battle droids of various levels of ability and speed, even upgrading to 2 at once, but mentioning Luke was the only real fun he had. He also practiced healing his scarred tissue, keeping time outside of a stasis unit as long as he could hold it. This story takes place after empire and before jedi.
He had various meetings with Imperials as well as Criminal organizations, discussing troop movements or shipping orders. He was also tasked with specific missions deemed more important by the Emperor, such as the destruction of a rebel shipyard, leading the attack and even going into his own ship for some dogfights for the fun of it...then gets bored.
Part of the fun of the book was reading about the various activities and thoughts of both Vader(such as how he hated spies) and Xizor(who loved spies), the real antagonist of the book.

A: As a high force in the Empire, he most likely had many boring day to day tasks that Lucasfilm does not bother showing us. One of these scenes is on the Death Star, when he is attending the board room meeting and terrorizing the poor workers. He just attends meetings, and reports his progress to the Emperor, as shown throughout the movies. He reports down to exterminate Rebel Forces spread out and about the galaxy, as on Cloud City. His day to day life is not very exciting, as most people's life's are.


text:
Q: SQL Help Inner JOIN LEFT JOIN My query is:
SELECT Pics.ID, Pics.ProfileID, Pics.Position, Rate.ID as RateID, Rate.Rating, Rate.ProfileID, Gender
FROM Pics
    INNER JOIN Profiles ON Pics.ProfileID = Profiles.ID
    LEFT JOIN Rate ON Pics.ID = Rate.PicID
WHERE Gender = 'female'
ORDER BY Pics.ID

And results are:
ID ProfileID Position RateID Rating ProfileID Gender
23 24        1        59     9      42        female
24 24        2        33     8      32        female
23 24        1        53     3      40        female
26 24        4        31     8      32        female
30 25        4        30     8      32        female
24 24        2        58     4      42        female

Now I want to do another query which would be:
If Rate.ProfileID = 32, remove any rows that contain that same Pics.ID
so left with:
ID ProfileID Position RateID Rating ProfileID Gender
23 24        1        59     9      42        female
23 24        1        53     3      40        female

and also remove any duplicate Pics.ID so just one of the above as they are both = 23 so left with :
23 24 1 59 9 42 female or 23 24 1 53 3 40 female

A: You should probably get rid of "magical numbers", like 32. That said, I think that this will give you what you need.
SELECT
    P.ID,
    P.ProfileID,
    P.Position,
    R.ID as RateID,
    R.Rating,
    R.ProfileID,
    PR.Gender
FROM
    Pics P
INNER JOIN Profiles PR ON PR.ID = P.ProfileID
LEFT JOIN Rate R ON R.PicID = P.ID
WHERE
    PR.Gender = 'female' AND
    NOT EXISTS (
        SELECT *
        FROM Pics P2
        INNER JOIN Profiles PR2 ON PR2.ID = P2.ProfileID
        INNER JOIN Rate R2 ON R2.PicID = P2.ID AND R2.ProfileID = 32
        WHERE
            P2.ID = P.ID
    )
ORDER BY
    P.ID

A:
@Shadow Because the 2nd row contains the Rate.ProfileID = 32, and that
  Pic.ID = 24, therefore it must remove ALL Pic.ID = 24, which removes
  the bottom row also.

SELECT Pics.ID, Pics.ProfileID, Pics.Position, Rate.ID as RateID, Rate.Rating, Rate.ProfileID, Gender
FROM Pics
INNER JOIN Profiles ON Pics.ProfileID = Profiles.ID
LEFT JOIN Rate ON Pics.ID = Rate.PicID
WHERE Gender = 'female' AND Pics.ID NOT IN (
    SELECT Pics.ID
    FROM Pics
    INNER JOIN Profiles ON Pics.ProfileID = Profiles.ID
    LEFT JOIN Rate ON Pics.ID = Rate.PicID
    WHERE Gender = 'female' AND Rate.ProfileID = 32)

ORDER BY Pics.ID

A: Try this:
SELECT Pics.ID, Pics.ProfileID, Pics.Position, Rate.ID as RateID,
       Rate.Rating, Rate.ProfileID, Gender
FROM Pics
INNER JOIN Profiles ON Pics.ProfileID = Profiles.ID
LEFT JOIN Rate ON Pics.ID = Rate.PicID
LEFT JOIN Rate AS r
   ON Rate.ProfileID = r.ProfileID AND Rate.ID > r.ID
WHERE Gender = 'female' AND (Pics.ProfileID <> 32) AND (r.ID IS NULL)
ORDER BY Pics.ID

The last LEFT JOIN operation helps identify duplicates using this predicate in the ON clause:
Rate.ProfileID = r.ProfileID

If such duplicates exist, as is the case with Rate.ProfileID = 42, then only the one having the maximum Rate.ID is returned due to the following conditions:
Rate.ID > r.ID (`ON` clause)

and
(r.ID IS NULL) (`WHERE` clause)


text:
Q: How to prove $f(x,y)=\sqrt {xy}$ is concave? How can I prove (preferably elegantly) that $f(x,y)=\sqrt {xy}$ where $x≥0$ and $y≥0$ is concave in both $x$ and $y$?

A: Take $ (x_0, y_0)$ and $ (x_1,y_1)$ and then you need to show
$ f( t( x_0 , y_0) + (1-t) (x_1 , y_1) ) \geq t f(( x_0 , y_0)) +(1-t) f((x_1 , y_1) )$
which by squaring it becomes
$$ (t x_0 +(1-t)x_1)( t y_0 +(1-t)y_1) \geq ( t \sqrt{ x_0 y_0} + (1-t) \sqrt{x_1 y_1 })^2$$
which hold trivially by Cauchy-Schwarz.


text:
Q: Extracting specific rows from a multi-indexed Pandas Dataframe to form new DataFrame I have a data set that I am loading onto a Pandas dataframe that is a Jagged 3-D array called: Waveform. The dataframe is multi-indexed by three levels: Events (Entry), Photons (Subentry) generated by each event, data points (subsubentry) per photon.
The number of data points and Photons varies randomly per each event, hence why it's jagged. I want to extract the Photons (subentries) for each Event (entry) that contain at minimum an "2*n" number of data points, take the average of the first n data points of the selected photons and save them in a new dataframe that contains their respective event and photon index.
I can't put my actual data here because it's too large and jagged so I will create an example that is the same, just scaled down in terms of data.
import awkward as ak
import pandas as pd

#I'm gonna generate an example awkward array that I want to convert to a Pandas DF
wf = ak.to_pandas(ak.Array([ [[1,2,5,6,8,3,21,3],[5986.472,0,6,1,2,3],[0]],[[1]],[[0.1,23,534,21,53,12],[0]],[[1],[2],[0],[12,12,12,12,125,34]],[[76],[23,23,43],],[[0],[12,12,12,12]] ]))

print(wf)
                              values
entry subentry subsubentry
0     0        0               1.000
               1               2.000
               2               5.000
               3               6.000
               4               8.000
               5               3.000
               6              21.000
               7               3.000
      1        0            5986.472
               1               0.000
               2               6.000
               3               1.000
               4               2.000
               5               3.000
      2        0               0.000
1     0        0               1.000
2     0        0               0.100
               1              23.000
               2             534.000
               3              21.000
               4              53.000
               5              12.000
      1        0               0.000
3     0        0               1.000
      1        0               2.000
      2        0               0.000
      3        0              12.000
               1              12.000
               2              12.000
               3              12.000
               4             125.000
               5              34.000
4     0        0              76.000
      1        0              23.000
               1              23.000
               2              43.000
5     0        0               0.000
      1        0              12.000
               1              12.000
               2              12.000
               3              12.000

#This is what I want the filter/Extraction to produce

wf_pF = ak.to_pandas(ak.Array([[[1,2,5,6,8,3,21,3],[5986.472,0,6,1,2,3,5]],[[0.1,23,534,21,53,12]],[[12,12,12,12,125,34]] ]))

print(wf_pF)
                              values
entry subentry subsubentry
0     0        0               1.000
               1               2.000
               2               5.000
               3               6.000
               4               8.000
               5               3.000
               6              21.000
               7               3.000
      1        0            5986.472
               1               0.000
               2               6.000
               3               1.000
               4               2.000
               5               3.000
               6               5.000
1     0        0               0.100
               1              23.000
               2             534.000
               3              21.000
               4              53.000
               5              12.000
2     0        0              12.000
               1              12.000
               2              12.000
               3              12.000
               4             125.000
               5              34.000

#I then want to take the average of the first n datapoints and place them into a new dataframe as such

averages = ak.to_pandas(ak.Array([[2.666,1997.333],[185.7],[12]]))
print(averages)
                  values
entry subentry
0     0            2.666
      1         1997.333
1     0          185.700
2     0           12.000

I used query to look for the 2n -1 datapoint first (in this case I used n = 3 so "5")  in the level subsubentry Wf_n = wf.query('subsubentry == 5'). I took the index of this new dataframe Wf_n and converted the indices of the Entry and Subentry into their respective NumPy arrays
nQuery  = wf.query('subsubentry == 5')
indices = nQuery.index.to_frame()["entry"]
indices2 = nQuery.index.to_frame()["subentry"]
ind = pd.Series.to_numpy(indices)
ind2 = pd.Series.to_numpy(indices2)

Then I used query to extract the Entries with their respective subentries with the following:
wf_AF = wf.query("entry in @ind and subentry in @ind2")
print(wf_AF)

which results in this dataframe wf_AF
                              values
entry subentry subsubentry
0     0        0               1.000
               1               2.000
               2               5.000
               3               6.000
               4               8.000
               5               3.000
               6              21.000
               7               3.000
      1        0            5986.472
               1               0.000
               2               6.000
               3               1.000
               4               2.000
               5               3.000
2     0        0               0.100
               1              23.000
               2             534.000
               3              21.000
               4              53.000
               5              12.000
      1        0               0.000
3     0        0               1.000
      1        0               2.000
      3        0              12.000
               1              12.000
               2              12.000
               3              12.000
               4             125.000
               5              34.000

It's still keeping subentries (Photons) that contain less than the desired subsubentries (datapoints) number threshold, 2*n. What am I doing wrong? Is there something I am not understanding? What can I do to achieve this specific method of filtering and can it be implemented in CuDF? Because there's so much data it would be ideal if I could replicate this as well in CuDF.

A: UPDATE: I deserve a dang medal...
Reading through the documentation of awkward, particularly check out help(ak.Array.__getitem__) as it's very informative. Also see help(ak.num), help(ak.mean) etc.
These use awkwards' own methods to filter, slice, and perform calculations on the array... which I'm sure is significantly faster than pandas. Pandas are only used here for visualization.
array = ak.Array([ [[1,2,5,6,8,3,21,3],[5986.472,0,6,1,2,3],[0]],[[1]],[[0.1,23,534,21,53,12],[0]],[[1],[2],[0],[12,12,12,12,125,34]],[[76],[23,23,43],],[[0],[12,12,12,12]] ])
filtered = array[ak.num(array, -1)>5]
df = ak.to_pandas(filtered)
print(df)

Output:
                              values
entry subentry subsubentry
0     0        0               1.000
               1               2.000
               2               5.000
               3               6.000
               4               8.000
               5               3.000
               6              21.000
               7               3.000
      1        0            5986.472
               1               0.000
               2               6.000
               3               1.000
               4               2.000
               5               3.000
2     0        0               0.100
               1              23.000
               2             534.000
               3              21.000
               4              53.000
               5              12.000
3     0        0              12.000
               1              12.000
               2              12.000
               3              12.000
               4             125.000
               5              34.000

Say we only want the first three values from each of those...
first_three = filtered[:,:,:3]
df2 = ak.to_pandas(first_three)
print(df2)

Output:
                              values
entry subentry subsubentry
0     0        0               1.000
               1               2.000
               2               5.000
      1        0            5986.472
               1               0.000
               2               6.000
2     0        0               0.100
               1              23.000
               2             534.000
3     0        0              12.000
               1              12.000
               2              12.000

Now say we want the average of those...
averages = ak.mean(first_three, axis=2)
df3 = ak.to_pandas(averages)
print(df3)

Output:
                     values
entry subentry
0     0            2.666667
      1         1997.490667
2     0          185.700000
3     0           12.000000

All in one step:
ak.to_pandas(ak.mean(array[ak.num(array, -1)>5,:3], axis=2))

Pandas Only:
n = 3
wf_AF = wf.reset_index(-1).groupby(level=[-2, -1]).filter(lambda x: x.subsubentry.max() >= 2*n-1).set_index('subsubentry', append=True)
# OR
wf_AF = wf.groupby(level=[-3, -2]).filter(lambda x: x.index.to_series().str[2].max() >= 2*n-1)
print(wf_AF)

Output:
                              values
entry subentry subsubentry
0     0        0               1.000
               1               2.000
               2               5.000
               3               6.000
               4               8.000
               5               3.000
               6              21.000
               7               3.000
      1        0            5986.472
               1               0.000
               2               6.000
               3               1.000
               4               2.000
               5               3.000
2     0        0               0.100
               1              23.000
               2             534.000
               3              21.000
               4              53.000
               5              12.000
3     3        0              12.000
               1              12.000
               2              12.000
               3              12.000
               4             125.000
               5              34.000

averages = wf_AF.groupby(level=[-3, -2]).agg(lambda x: x.head(n).mean())
print(averages)

Output:
                     values
entry subentry
0     0            2.666667
      1         1997.490667
2     0          185.700000
3     3           12.000000


text:
Q: LINQ: Problem using DB with relations I don't know how can I return posts to my view where their tags are equal to those who are passed to controller action.
I think there is some clever and easy way of doing this but I am very new to LINQ and SQL.

Code
// id = tag name, not it's id
public ActionResult Tag(string id)
{
    // I get all the PostTags where PostTags.Tag.Name = id
    var postTags = _db.PostTags.Where(x => x.Tag.Name == id);

    // And what I do now?
}

A: Using joins in relational data is easier to grasp as a novice using query syntax instead of extension methods. The following is possible with extension methods (like .Join(...), etc), but this is closer to the SQL you might already be used to.
var postTags = from t in _db.Tags
               join pt in _db.PostTags on t.ID equals pt.TagID
               join p in _db.Posts on pt.PostID equals p.ID
               where t.Name == id
               select p;

A: Well to select them you could do something similar to..
var posts = _db.Posts.Where(post => post.PostTags.Any(postTag => postTag.Tag.Name == id));

This will just select all Posts where any of the related PostTags has a Tag with the name passed.


text:
Q: 'Interaction failed.' Discord slash commands It worked the first few times I did. It's random. It sometimes works or fails and says 'The Interaction failed'. Mostly failing. Please help.
from discord_slash import SlashCommand
client = commands.Bot(command_prefix='!', intents=intents)

slash = SlashCommand(client, sync_commands=True)
@slash.slash(description='Ping.')
async def ping(ctx):
    await ctx.send(f'Current speed - {round(client.latency * 1000)}')

A: To avoid the error message "This Interaction failed." the library provides a simple solution.
Simply put await ctx.defer() at the top of your code, in your case:
@slash.slash(description='Ping.')
async def ping(ctx):
    await ctx.defer()
    await ctx.send(f'Current speed - {round(client.latency * 1000)}')

If the bot needs more than 3 seconds to give out an answer, the API will return this kind of error. With ctx.defer() this is bypassed, and the bot gives out a message.
Please note that global slash commands take about an hour for any changes to be visible/noticeable. To work around this, you can add guild_ids=[YourGuildID] to your code and test it.


text:
Q: If $\,\lim_{p\to\infty} \sum_{j=1}^n a_j\cos(p\pi \theta_j) \to 0,\,$ then $\,a_1 = \dots = a_n = 0$. The exercise
Let $n \geq 1$, $0 < \theta_1 < \dots < \theta_n < 1$ and $a_1, \dots, a_n \in \mathbb{R}^n$. Assume $ \sum_{j=1}^n a_j\cos(\pi p \theta_j) \underset{p \to +\infty}{\longrightarrow} 0$ ($p \in \mathbb{N}$). Show $a_1 = \dots = a_n = 0$.
My try
I tried to prove this by induction over $n$. I succeeded for $n = 1$, but I have no clue to show how the property can be used for $n \geq 2$.

A: $\left(\cos(\pi p\vartheta_1)\right)_{p\geqslant 0}$ is bounded, thus there exists $\sigma_1:\mathbb{N}\rightarrow\mathbb{N}$ and $\ell_1\in[-1,1]$ such that $\lim\limits_{p\rightarrow +\infty}\cos\left(\pi\sigma_1(p)\vartheta_1\right)=\ell_1$. By the same argument, since $\left(\cos\left(\pi\sigma_1(p)\vartheta_2\right)\right)_{p\geqslant 1}$ is bounded, there exists $\sigma_2:\mathbb{N}\rightarrow\mathbb{N}$ and $\ell_2\in[-1,1]$ such that $\lim\limits_{p\rightarrow +\infty}\cos\left(\pi(\sigma_1\circ\sigma_2)(p)\vartheta_2\right)=\ell_2$, and we also have $\lim\limits_{p\rightarrow +\infty}\cos\left(\pi(\sigma_1\circ\sigma_2)(p)\vartheta_1\right)=\ell_1$. We do the same for $\ell_3,\ldots,\ell_n$. Let $\sigma=\sigma_1\circ\ldots\circ\sigma_n$, then $\lim\limits_{p\rightarrow +\infty}\cos\left(\pi\sigma(p)\vartheta_j\right)=\ell_j$ for all $j$ and, we can suppose without loss of generality that $(\sigma(p+1)-\sigma(p))_{p\geqslant 0}$ is a nondecreasing sequence. Since $\sin\left(\pi\sigma(p)\vartheta_j\right)=\pm\sqrt{1-\cos^2\left(\pi\sigma(p)\vartheta_j\right)}\underset{p\rightarrow+\infty}{\longrightarrow}\pm\sqrt{1-\ell_j^2}$ we have
$$ \cos\left(\pi\left(\sigma(p+1)-\sigma(p)\right)\vartheta_j\right)=\cos\left(\pi\sigma(p+1)\vartheta_j\right)\cos\left(\pi\sigma(p)\vartheta_j\right)+\sin\left(\pi\sigma(p+1)\vartheta_j\right)\sin\left(\pi\sigma(p)\vartheta_j\right)\underset{p\rightarrow +\infty}{\longrightarrow}\ell_j^2+\left(\pm\sqrt{1-\ell_j^2}\right)^2=1 $$
thus we finally get
$$ \lim\limits_{p\rightarrow +\infty}\sum_{j=1}^n a_j\cos\left(\pi\left(\sigma(p+1)-\sigma(p)\right)\vartheta_j\right)={\rm Card}\{j\in[\![1,n]\!],a_j\neq 0 \} $$
But since $\displaystyle\lim\limits_{p\rightarrow +\infty}\sum_{j=1}^n a_j\cos(\pi p\vartheta_j)=0$, we have $a_j=0$ for all $j$.

A: We shall prove something slightly more general:
If $\,0<\theta_1<\cdots<\theta_n<1$ and
$$
\lim_{p\to\infty}\sum_{j=1}^n \big(a_j\cos(p\pi \theta_j)+b_j\sin(p\pi \theta_j)\big)=0,
$$
then $a_1=b_1=a_2=b_2\cdots=a_n=b_n=0$.
Clearly
$$
\sum_{j=1}^n \big(a_j\cos(p\pi \theta_j)+b_j\sin(p\pi \theta_j)\big)
=\sum_{j=1}^n c_j\mathrm{e}^{ip\pi\theta_j}+
\sum_{j=1}^n \overline{c}_j\mathrm{e}^{-ip\pi\theta_j},
$$
where
$c_j=\frac{a_j-ib_j}{2}$, and hence it suffices to show that $c_1=\cdots=c_n=0$.
Note that the $2n$ complex numbers
$$
\mathrm{e}^{i\pi\theta_j},\mathrm{e}^{-i\pi\theta_j},\quad j=1,\ldots,n,
$$
and distinct. Each of them of absolute value 1.
Hence it suffices to show the following:
If $w_j\in\mathbb C$, $j=1,\ldots,m$, are distinct complex numbers, with $|w_j|=1$, $j=1,\ldots,m$, and
$$
\lim_{p\to\infty}\sum_{j=1}^m d_jw_j^p=0,
$$
then $d_1=\cdots=d_m=0$.
This can be shown inductively on $m$. For $m=1$ it is obvious. Assume that it is true for $m=k-1$ and we have that $\,\lim_{p\to\infty}\sum_{j=1}^k d_jw_j^p=0$. Then
$$
0=w_k\lim_{p\to\infty}\sum_{j=1}^k d_jw_j^p-\lim_{p\to\infty}\sum_{j=1}^k d_jw_j^{p+1}=
\lim_{p\to\infty}\left(w_k\sum_{j=1}^k d_jw_j^p-\sum_{j=1}^k d_jw_j^{p+1}\right) \\
=\lim_{p\to\infty} \sum_{j=1}^{m-1} d_j(w_k-w_j)w_j^p.
$$
Using the induction hypothesis, we obtain that
$$
d_j(w_k-w_j)=0, \quad j=1,\ldots,k-1
$$
and hence $d_j=0$, $j=1,\ldots,k-1$, which implies also that $d_k=0$.


text:
Q: Rails Wiselinks & Angular : How can I make the angular code load after the page loads? When I use the data-push the Angular code shows up as this {{user.name }} How can I make the page request so the Angular code gets triggered ?
Turbolinks is a bad mix with Angular and jQuery on Rails, I took it out, because it caused so much trouble, I decided not to go there and use Wiselinks instead.
This is what I'm doing:
I have the @users being passed to $resource to the data to Angular side:
App.factory('User', [
  '$resource', function($resource) {
    return $resource('/users/:id.json', {
      id: '@id'
    });
  }
]);

and I have the template working when I enter the Page localhost:3000/users as address however when I click the link with data-push enabled:
<a href="<%= users_path %>" data-push="true">Users

It only loads to the console and the empty Angular template shows up in the view
 {{user.name}}

from the ng-repeat
Again I know this is a bad mixture, but this is the only way I know to make this Web app like style work and I feel like I'm hitting bottleneck and I missing something, I guess the page Have to be LOADED without push, wiselinks and turbolinks one way or another.
Is that true ? please say no.
Code Update:
app.js
window.App = angular.module('UsersApp', ['ngResource'])
user_ctrl.js
`
App.controller('UserCtrl', [
  '$scope', 'User','$compile', function($scope, User,$compile) {
    $scope.users = User.query();

  }
]);

user.js
App.factory('User', [
  '$resource', function($resource) {
    return $resource('/users/:id.json', {
      id: '@id'
    });
  }
]);

Now in the view I have this inside users/index.html.erb

                        {{ user.full_name }}

`
In the actuall code, ng-cloak ng-app="UsersApp" is defined on the body


text:
Q: Containers and syscall.CLONE_NEWNS I'm running the golang code on this repo https://github.com/lizrice/containers-from-scratch/blob/master/main.go and I'm having a problem with the mount namespace. What the code should do is creating a process within its own mount namespace. So if I run the code with sudo go run main.go run /bin/bash and I create a file inside the directory mytemp, I should be able to see that file from within the new started process, but if I try to view that file moving to the rootfs directory on the host, I shouldn't be able to see that file thanks to the mount namespace.
Unfortunately I still see this file, so it seems that the process I run is not mount namespaced.
To run the code, I used this https://github.com/ericchiang/containers-from-scratch/releases/download/v0.1.0/rootfs.tar.gz as a rootfs and moved it under /home/me. Then I created a mytemp directory to use as the tmpfs mount target.
Do you have any ideas about the reasons why the process doesn't get mount namespaced?
Thanks!

A: This issue could be solved by configuring the host machine mount to be private which does not receive or forward any propagation events to other mounts, vide  RedHat - Sharing Mounts.
This command should be executed on your host machine before your create the container:
$ mount --make-rprivate /


text:
Q: Click on button first time show alert, click second time execute code I want to show users, when they click on a button for the first time, an alert when in a date field a value is chosen which lies before the current date. When they insist to this choice for good reasons, I want them to give a second chance to click on the same button, and then the value has to be submitted.
The click event is defined in a function:
$("#edit_date_btn").click(function(){
 // do something and save
}

In an other function the comparing is handled. The basic code is:
function edit_date_compare() {
....
if(usersDate < today)
 { //show alert
  return false; // needed for the first click so the input is not submitted
 }

I've tried several options e.g. with a count on the click function (on a second click 'return true;' instead of 'return false;') but it seems difficult to handle this situation. Any ideas how to make this successful? It could be with Javascript or jQuery.

A: You have the right idea with the count on the click function. I suspect you might have difficulty implementing it. You need a separate variable that tracks the number of clicks. Here's a working fiddle: http://jsfiddle.net/zwmquxaL/
$(document).ready(function () {
    var clickCount = 0;

  $("#btnSave").click(function () {
    if (clickCount > 0) {
      AlertSave();
    } else {
        AlertFirst();
      clickCount++;
    }
  });
});

function AlertSave() {
  alert("Some code has been executed!");
}

function AlertFirst() {
  alert("Are you sure you want to perform this operation?");
}


text:
Q: HTML  tag styling - NVD3 I am using NVD3 library to plot the PIE chart using angular. This is the output :

svg tag is of width: 320px and height: 200px. <g> element of html is not taking full width, I did not find width property on <g> element, i tried stroke-width: 100% but did not worked. I am trying to make <g> take full available width.
Chart config :
                 chart: {
                            type: 'pieChart',
                            height: height,
                            width: width,
                            x: function(d){return d.key;},
                            y: function(d){return d.y;},
                            showLabels: false,
                            duration: 500,
                            labelThreshold: 0.01,
                            labelSunbeamLayout: true,
                            legend: {
                                margin: {
                                    top: 5,
                                    right: 35,
                                    bottom: 5,
                                    left: 0
                                }
                            },
                            margin:{
                                left: 20
                            },
                           useInteractiveGuideline: true,
                           interactive: true
                        }


text:
Q: Kendo DatePicker in UK with US format We are in the UK but have a US client. We want the date of a Kendo DatePicker to display in US format MM-dd-yyy but, testing here, it won't accept any selection of a date value, stating that it must be a valid date.
I have applied .Format("MM-dd-yyyy") to display the value, which works. I have attempted a couple of things to get it to accept a date selection, as you can see here:
@(Html
        .Kendo()
        .DatePickerFor(model => model.Date)
        .Name("Date")
        //.Format("MM-dd-yyyy")
        //.ParseFormats(new[] { "dd/MM/yyyy", "dd-MM-yyyy", "MM-dd-yyyy" })
        .Culture("en-US")
        .HtmlAttributes(new { style = "width:150px" })
)

How can I get this to work?

A: Finally got this to work.
In JavaScript we can specify
kendo.culture("en-US");

but the key piece of code I used to get it to work was:
function OnSave(e) {
    e.model.Date = (e.model.Date).toUTCString();
}

Even though e.model.Date was already a valid (UK) date, toUTCString enables an automatic conversion that Kendo/C# can convert to an acceptable date in the model.


text:
Q: How to inherit javascript from core OpenERP 6.1 I made some changes in my core module to hide some buttons using javascript.
I put this code below in my view_list_editable.js
openerp.web.ListView.include({
  start: function() {
    var self = this;
    var ret = this._super.apply(this, arguments);
    var res_model = this.dataset.model;
    if ($.inArray(res_model, ['inno.open.lab.report']) != -1) {
      self.options.addable = false; /* create button */
      self.options.deletable = false; /* delete button */
    };
    return ret;
  },
});

and it works.
But when I try to inherit it, by put it doesn't work at all
I did it like this

*

*I make a new javascript file that contain this code below:
instance.web.ListView = instance.web.ListView.extend({
    start: function() {
        var self = this;
        var ret = this._super.apply(this, arguments);
        var res_model = this.dataset.model;
        if ($.inArray(res_model, ['inno.open.lab.report']) != -1) {
            self.options.addable = false; /* create button /
            self.options.deletable = false; / delete button */
        };
        return ret;
    },
});

*I put it my_module/static/src/js

*I also add javascript in terp like this:
'js' : ['static/src/js/view_list_editable.js',],

A: I believe you have to have 'web' in the dependencies section of terp as well:
'depends': [
         'web',
         ],

A: Yes, you are doing write put there is still one more step to do.
Add this below code in your views/xml file at top.
<?xml version="1.0" encoding="utf-8"?>
<openerp>
    <data>
        <template id="assets_backend" name="your-module-name" inherit_id="web.assets_backend">
            <xpath expr="." position="inside">
                <script type="text/javascript" src="/module-ame/static/src/js/view_list_editable.js"></script>
            </xpath>
        </template>
    </data>
</openerp>

Try this one.!


text:
Q: gEdit External Tools Output I'm new to these forums, so I'm sorry if I've not put this in the correct place or followed forum rules.
I am writing a gEdit External Tools shell script.
In the 'Manage External Tools' dialogue box there is a drop down menu to choose the output.
These options are:

*

*Nothing

*Display in bottom pane

*Create new document

*Append to current document

*Replace current document

*Replace current selection

*Insert at cursor position

So the script can only use one of these.
I want to be able to choose the output from the script. Is there an output variable that can be set in the script? Is what I want even possible?
I've scoured the web for a solution, but to no avail, so I've come here for help.
Thank-you in advance.

A: It depends on exactly what you want to do, but you definitely have some options:
Inside your script, you can use > /dev/stderr to redirect output to stderr -- that will make it appear in the "Shell Output" pane. In one script of mine that is set to "replace current document" I also write to the Shell Output pane with echo "Something something" > /dev/stderr
You can overwrite the current document the same way: echo "Something something" > $GEDIT_CURRENT_DOCUMENT_NAME will replace the current document with "Something something"
And you can append to current document with >> eg. echo "Something something" >> $GEDIT_CURRENT_DOCUMENT_NAME will add "Something something" to the end of the current document.


text:
Q: onOptionsItemSelected called twice Running Android 5.0 on Nexus 5. My app uses v4 Support Library 21.0.0. minSdkVersion is 11 and targetSdkVersion is 21.
I have an activity deriving from android.support.v4.app.FragmentActivity. I have a number of menu items on the action bar. Now, if I quickly double-tap one of the action bar's menu items, onOptionsItemSelected is called twice resulting in two instances of my menu-triggered child ctivity! And yes, my menu handlers do return true.
I have googled this, but couldn't find anything. Am I facing a bug, or have I missed something? I've implemented this in the past, and never encountered this weird behavior. Ideas?

A: Not sure why it happens in the latest support lib, but in the past, for any views, I've used this solution -
private long mLastClickTime = 0;

protected boolean isNotAFastClick() {
     boolean result = true;
     if (SystemClock.elapsedRealtime() - mLastClickTime < FAST_CLICK_THRESHOLD) {
          result = false;
     }
     mLastClickTime = SystemClock.elapsedRealtime();
     return result;
}

Before handling any click events, I just call the method to check if it was fast click.


text:
Q: Question about the characteristic subgroup. Let G be a group. A subgroup  H is called characteristic if $f(H)\subset H$ for all auto morphism $f$ of G.Pick out true statements.
(a) Every characteristic subgroup is normal.
(b) Every normal subgroup is characteristic.
(c) if $N$ is normal subgroup of a group G and M be a characteristic subgroup of N then M is normal subgroup of G.

A: Hint on a):
A subgroup $H$ is normal if $f(H)\subset H$ is true for each inner automorphism.

A: For the last one:
Consider the automorphism $$\phi: N\to N,~~x\mapsto g^{-1}xg$$ Since $M~\text{char}~ N$ so $M^{\phi}=M$ and so...

A: a) True.  For $g \in G$, we use $f:G \rightarrow G$ defined by $x\mapsto gxg^{-1}.$
b) Wrong.  Example $G=\mathbb{Z}_2 \oplus \mathbb{Z}_2$. Choose $H = \mathbb{Z}_2 \oplus 0$
and $f(x,y)=(y,x)$
c) True. For $g \in G$, we can choose $f:N \rightarrow N$ defined by $x\mapsto gxg^{-1} $ because $N$ is normal of $G.$
Let $m \in M$. Then $gmg^{-1}=f(m) \in M.$


text:
Q: Add a new column in df1 based on match between df1 and df2 in r I have two data sets df1 and df2, which have one column "ID" in common:
df1 <- data.frame(ID=c(1:20), Country=c("US"))
df2 <- data.frame(ID=c(1:10), Gender=c("Female","Male"))

How can I add another column "Respondents"=="Yes" in df1 if the same ID exists in df2 and is "Female"?

A: We can do a join with the second dataset and create the 'Respondents' column by checking if the 'Gender' is 'Female' then label as "Yes" with case_when
library(dplyr)
df1 <- df1 %>%
  left_join(df2) %>%
    mutate(Respondents = case_when(Gender == 'Female' ~ "Yes" )) %>%
    select(-Gender)


text:
Q: Access private stash repo during npm install on Jenkins I've created a node package that I'd like to use in my company's primary application. Both my package and the application are stored in private git repositories. Here is an the relevant portion of my package.json file:
"dependencies": {
    "qc-event-logger": "git+ssh://git@git-ssh.XXXXXXXXX.com/qc-event-logger.git#v1.0.0"
},

I'm able to run and build it locally, and everything works fine. The problem is when I try to deploy from our Jenkins build server. The npm install build task hangs. It doesn't fail or throw an exception, it just sits on that step until I kill the build agent.
I can't be sure, but I think it's failing because it isn't providing an ssh key for the node package. I tried adding an SSH key credential:

But that appears to only be related to pulling the whole project down, and I can't find any way to attach the credentials to a build task. I tried switching the credentials for the main application's git repo to SSH, but it's not set up that way.
Is there a way to either:
a) attach an SSH key to a Jenkins build task, or
b) specify the SSH key at the command line, either before calling npm install or as a parameter?

A: I solved this problem generating a ssh key from jenkins user.
First I connect via ssh on jenkins host.
Then I generate a ssh private and public key using a jenkins user, not current or root user.
I will give a bitbucket example:
su - jenkins
ssh-keygen -f ~/.ssh/bitbucket -C "bitbucket"

Then you should create a config file to use this ssh key on every bitbuket request.
touch ~/.ssh/config
chmod 755 ~/.ssh/config

echo "# Bitbucket configuration" > ~/.ssh/config
echo "Host bitbucket.org" >> ~/.ssh/config
echo "   HostName bitbucket.org">> ~/.ssh/config
echo "   IdentityFile ~/.ssh/bitbucket">> ~/.ssh/config

Lastly update ssh configs adding bitbucket private key:
ssh-add ~/.ssh/bitbucket

You can check if everythig is OK, checking by following command ssh-add -l and a line with private key configurations should be returned.

A: It's been two years since this question was asked, but it pretty accurately described the situation I was in as well, so I'll explain how I managed to resolve this in case someone else also finds themselves in the same situation.
Basically, you don't need to add the credentials to the build in jenkins in this situation. If id_rsa is present in that location and has the right permissions, git will actually pick it up automatically.
However, the reason it was hanging (for me anyway) was that it was asking whether to add the ssh fingerprint to the known_hosts file. For some reason, jenkins does not show this question and as the server is waiting for input, it just seems to be hanging.
The way to solve this is to create (/add the server to) ~/.ssh/known_hosts yourself. The easiest way to do is to run ssh <my git server> from the jenkins server by hand. It will then ask about the fingerprint and this time you can say yes. Once this is done, it won't ask again and the build should no longer hang.


text:
Q: Docusign Request the Authorization Code related query I have checked Docusign Request the Authorization Code related documentation and set all the settings on Docusign Admin. But when I run the below url in the browser it wants login details and accept screen. My query is how can I skip this login and accept steps. Here is the request url
https://account-d.docusign.com/oauth/auth?response_type=code&scope=YOUR_REQUESTED_SCOPES&client_id=YOUR_INTEGRATION_KEY
&state=YOUR_CUSTOM_STATE&redirect_uri=YOUR_REDIRECT_URI

A: You cannot skip this login page if you are using the authorization grant flow as this is part of the oauth protocol security. To get a token, you need to authenticate (or your customer/user would need to). This token is typically valid for 8 hours and a cookie is stored on the device which means you won't be asked again to login for the next 8 hours, but you do need to do this initially.


text:
Q: Create an IObservable and return the result of a cached async operation immediately I'm using reactive extensions to call a async method and I want to cache the result and return this for subsequent calls to the method.
How can I create an Observable instance, return it and provided the data (cacheResult) the subscribe requires?
public IObservable<Bar> GetBars(int pageIndex, int pageSize)
{
   var @params = new object[] { pageIndex, pageSize };
   var cachedResult = _cache.Get(@params);
   if (cachedResult != null)
   {
 // How do I create a Observable instance and return the 'cacheResult'...
 return ...
   }

   var observable = new BaseObservable<Bar>();
   _components.WithSsoToken(_configuration.SsoToken)
      .Get(@params)
      .Select(Map)
      .Subscribe(c =>
                     {
                          _cache.Add(@params, c);
                          observable.Publish(c);
                          observable.Completed();
                     }, exception =>
                     {
                        observable.Failed(exception);
                        observable.Completed();
                     });

       return observable;
}

A: I believe you are looking for Observable.Return:
return Observable.Return((Bar)cachedResult);

On an unrelated note:

*

*There's no need to return a BaseObservable<T>. You should return a Subject<T> as it does what your implementation is doing but is thread safe (you should also call .AsObservable() on the return value to it can't be cast back).

*You use Do to add the value to the cache:

var observable = new Subject<Bar>();
_components.WithSsoToken(_configuration.SsoToken)
    .Get(@params)
    .Select(Map)
    .Subscribe(c =>
    {
        _cache.Add(@params, c);
        observable.OnNext(c);
        observable.OnCompleted();
    }, exception =>
    {
        observable.OnError(exception);
    });

return observable.AsObservable();

A: Conveniently, I've written a class that does this pattern for you, check it out:
https://github.com/xpaulbettsx/ReactiveXaml/blob/master/ReactiveXaml/ObservableAsyncMRUCache.cs
var cache = new ObservableAsyncMRUCache<int, int>(
    x => Observable.Return(x*10).Delay(1000) /* Return an IObservable here */,
    100 /*items to cache*/,
    5 /* max in-flight, important for web calls */
    );

IObservable<int> futureResult = cache.AsyncGet(10);

futureResult.Subscribe(Console.WriteLine);
>>> 100

Some tricky things that it handles correctly:

*

*It caches the last n items and throws away items that aren't being used

*It ensures that no more than n items are running at the same time - if you don't do this, you can easily spawn out thousands of web calls if the cache is empty

*If you ask for the same item twice in a row, the first request will initiate a request, and the second call will wait on the first one instead of spawning an identical request, so you won't end up querying data redundantly.


text:
Q: Build _msearch query in javascript I tried to write the _msearch elasticsearch query in Nodejs. But I'm getting the following error
{"module":"Search","type":"Success","response":{"error":{"root_cause":[{"type":"illegal_argument_exception","reason":"The msearch request must be terminated by a newline [\n]"}],"type":"illegal_argument_exception","reason":"The msearch request must be terminated by a newline [\n]"},"status":400}}

I have created the search template in elasticsearch using kibana. It's working in kibana. I have tried to add \n at end of the string, still getting the same error. Here is my full code.
    let doc=`{"index":"my_index"}
{  "id": "count", "params": {  "domain":"'+domain+'", "condition":"attributes.sent", "value":"0" }  }
{"index":"my_index"}
{  "id": "count", "params": {  "domain":"'+domain+'", "condition":"attributes.status", "value":"open" }  }
{"index":"my_index"}
{  "id": "count", "params": {  "domain":"'+domain+'", "condition":"attributes.status", "value":"click" }  }
{"index":"my_index"}
{  "id": "count", "params": {  "domain":"'+domain+'", "condition":"attributes.status", "value":"bounce" }  }
`;
            let reqObj = {
                uri: API_URL+INDEX+'_msearch/template',
                method: 'GET',
                headers: { "content-type": "application/json" },
                body: doc,
                json: true
            };
            return new Promise((resolve,reject)=>{
                request(reqObj, (err, res, body) => {
                    if(err) return reject(this.Response("Search","error",err));
                    return resolve(this.Response("Search","Success",body));
                });
            });

I tried to remove extra spaces still same result
let doc=`{"index":"my_index"}{  "id": "count", "params": {  "domain":"'+domain+'", "condition":"attributes.sent", "value":"0" }  }{"index":"my_index"}{  "id": "count", "params": {  "domain":"'+domain+'", "condition":"attributes.status", "value":"open" }  }{"index":"my_index"}{  "id": "count", "params": {  "domain":"'+domain+'", "condition":"attributes.status", "value":"click" }  }{"index":"my_index"}{  "id": "count", "params": {  "domain":"'+domain+'", "condition":"attributes.status", "value":"bounce" }  }`;

A: You need to make sure to remove all leading spaces before the opening curly braces and also ensure that you have a newline character after the last line.
Moreover, you probably need to remove the json: true and change the application/json content-type to application/x-ndjson.


text:
Q: No nic with thid ID () is registered with this ConnectionManager, return empty GateList I use Veins-4a2 and I have changed the car.ned and its nicType by specifying
string nicType = default("Nic802154_TI_CC2420");
When I run the simulation, I get this window with the following message "Module RSUExampleScenario.node[0].nic.phy: No nic with thid ID (9) is registered with this ConnectionManager, return empty GateList.":
[
What this message means and how can I adjust it please?

A: The simulation module you are using was not written to support creation of new modules during runtime. Veins is creating a new module whenever a new car starts driving. This is different to most other network simulations where all nodes are already present at the start of the simulation.
As the simulation module you are using (Nic802154_TI_CC2420) is not part of Veins, I cannot say how you can change the module to support creation during runtime.


text:
Q: Python Numpy add an array at array index I'm struggling with something that may be very simple or not possible.
I want to add an numpy array to another numpy array at a specific index.
a = np.zeros(shape=(17, 1, 2))

for i in range(10):
  b = [i]
  c = [1,2,3,4]
  b.append(c)

  # Here I want to add b in a at specific index but it's not working
  # np.append(a[i][0][0], b)

At the end I want something like that :
a = [[[[0, [1,2,3,4]], ....]]]

Thank you

A: Your example is not very clear and you do not say what actually is going wrong. You are not doing anything with a in the loop for example. Also you are trying to mix lists and arrays.
Still, I think I know what you mean/need.
You can use insert and append for lists, as illustrated in the example below:
a = []
for i in range(10):
  b = [i]
  c = [1,2,3,4]
  b.insert(1,c)
  a.append( b )
print a

Update
Use list.insert(index, obj) to insert an object at a specific index.

A: If the following is not near to what you'd like, you'll really have to be more specific, dear OP.
I acknowledge numpy to be a powerful library, but you ask it to initialize zeros, which are int then want to add in list. You cannot expect the constructor to know at creation time that it needs to allocate space for object type data. What you want is to help the numpy ndarray constructor with type inference.
a = np.zeros(shape=(17, 1, 2), dtype=object)
for i in range(10):
  b = [i]
  c = [1,2,3,4]
  b.append(c)
  a[i] = b
a
#array([[[0, [1, 2, 3, 4]]],
#
#  [[1, [1, 2, 3, 4]]],
#
#  [[2, [1, 2, 3, 4]]],
#
#  [[3, [1, 2, 3, 4]]],
#
#  [[4, [1, 2, 3, 4]]],

#  [[5, [1, 2, 3, 4]]],

#  [[6, [1, 2, 3, 4]]],

#  [[7, [1, 2, 3, 4]]],

#  [[8, [1, 2, 3, 4]]],

#  [[9, [1, 2, 3, 4]]],

#  [[0, 0]],

#  [[0, 0]],

#  [[0, 0]],

#  [[0, 0]],

#  [[0, 0]],

#  [[0, 0]],

#  [[0, 0]]], dtype=object)


text:
Q: Login dentro do javascript alert Tem como fazer um login com usuario e senha unicos dentro de um alert?

Queria que fosse um codigo tipo esse, só nao sei colocar 2 prompt no msm popup

A: Dentro de um alert não, mas você pode pegar informações do usuário através de um prompt.
https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt
O problema é que esta não é uma forma muito "amigável" de se obter dados. Dê uma olhada se uma janela modal dentro da própria página atenderia aos seus requisitos:
http://getbootstrap.com/javascript/#modals

A:
Isso não é exatamente "um login no alert", mas um login via HTTP Basic Authentication;

Especificamente esta captura de tela parece ser de uma autenticação de HTTP Basic Authentication, inclusive pode fazer o login diretamente no URL como http://nome:senha@site.com.
Você pode ler mais sobre isso aqui.
Se realmente deseja usar este tipo de autenticação e de quebra exibir dois formulários num único "alert" essa é a única solução, até onde saiba.
Vale ressaltar que a exibição de tal "alert" pode mudar de acordo com o navegador, não necessariamente será mostrado desta forma.

Acredito que solução do @lfarroco, usando modal, é melhor e não exige mudanças no código em PHP, ou são mudanças menores do que migrar para outro tipo de autenticação.


text:
Q: RedirectTo, AmpScript and website-generated parameters I have a URL that is created with some Ampscript that needs to have click-tracking.  However, there are parameters that our 3rd party's website adds and I believe that is breaking the link.
Here's the AmpScript I'm using to create the URL:
%%[
    var @Store_Id, @Store_Link, @RSTR_PLRS_First_Name, @SN_TMS_Name
    SET @Store_Id = SL_Store_Id
    SET @Store_Link = Concat('https://teamlocker.squadlocker.com/#/lockers/', @Store_Id)
]%%

Link

So, when I go to test the link - this is what it's generating:
https://teamlocker.squadlocker.com/#/lockers/49753?cm_ven=ExactTarget&cm_cat=SE_SquadLockerTeamStore_Parent_Email1_jordan&cm_pla=All+Subscribers&cm_ite=STATIC+TEXT+HERE&cm_lm=nick.burggraf@sportsengine.com&cm_ainfo=&&&&%%__AdditionalEmailAttribute4%%&%%__AdditionalEmailAttribute5%%&_k=h94gl3
The final parameter &_k=h94gl3 is generated from the webpage.
The webpage should render like this:   https://teamlocker.squadlocker.com/#/lockers/49753?_k=h94gl3

A: If the &%%_AdditionalEmailAttributeX%% breaks your links, you could raise a support case via the Help & Training Portal to enable all available additional email attributes. Then you can set them in the properties of your emails. For every unset parameter just an ampersand is added to the url which shouldn't break the link. The other automatically added parameters like cm_ven, cm_cat, etc. shouldn't break your link either. You could also add an alias to your link, so this is set as cm_ite value.


text:
Q: password protection - bcrypt vs. forced delay on login? I have been doing a lot of research on safely storing passwords in a database, and bcrypt seems to be coming up all over the place as one of the most safe hashing algorithms, so I am probably going to use it for storing my website's passwords (written in PHP).  One of it's major selling points seems to be that it is extremely slow and therefore helps to slow brute force / dictionary attacks.  Literally every article I read mentions how bcrypt is great because it's slow and therefore prevents brute force attacks.
So, my question is: Can't I just manually make my code pause for a second or two after a failed login using PHP's sleep()?  Why is it so important that bcrypt is slow?  I am under the impression that I could use any encryption algorithm (let's assume that it's encrypted just as well as bcrypt), add a PHP sleep() on a failed login, and have just as good a defense against brute force / dictionary attacks as bcrypt.

A: bcrypt and forced delay on login protect against two different attacks.
A forced delay on login adds protection against an online attack, where the attacker uses your login page to try different passwords.
bcrypt adds protection against offline attacks, where the attacker has gained access to your password hashes and can try hashes without using the login page.


text:
Q: Strategy for breaking up a vector product Given is the equality
$$\vec{A}\times\vec{B}=\vec{C}$$ What is the strategy for breaking up the vector product and expressing $\vec{B}$? Given this equality, what does $\vec{B}$ alone equal to?
I know one strategy, say $\vec{A}$ is a constant vector and $\vec{B}$ is the position vector $\vec{x}$:$$\vec{A}\times\vec{x}=\vec{C}$$ Take curl of both sides: $$\nabla\times(\vec{A}\times\vec{x})=\nabla \times \vec{C},$$ then $$2\vec{A}=\nabla \times \vec{C}, $$ or
$$\vec{A}=\frac{1}{2}\left( \nabla \times \vec{C} \right)$$
Do you have a strategy for expressing either A or B when both $\vec{A}$ and $\vec{B}$ are not constant? How do we eliminate $\vec{A}$ form the LHS to express $\vec{B}$.

A: Attempted answer:
If $$\vec{A}\times\vec{B}=\vec{C},$$ then $$\vec{B}=-\frac{\vec{A}\times\vec{C}}{|A|^2}+\lambda\vec{A},$$ where $\lambda$ is an arbitrary constant.
Check if true:
$$\vec{A}\times\vec{B}=$$
$$=-\frac{1}{|A|^2}\vec{A}\times(\vec{A}\times\vec{C})+\lambda(\vec{A}\times\vec{A})$$
$$=-\frac{1}{|A|^2}\vec{A}\times(\vec{A}\times\vec{C})$$
$$=-\frac{1}{|A|^2}\left[(\vec{A}\cdot\vec{C})\vec{A}-(\vec{A}\cdot\vec{A})\vec{C} \right]$$
since $\vec{A}\times\vec{B}=\vec{C},$ the vectors A and C are orthogonal, $(\vec{A}\cdot\vec{C})=0$ and we are getting
$$=\vec{C}$$

A: Short answer to

How do we eliminate $A$   form the LHS to express $B$?

is that you can't.
Geometrically, the cross product $A \times B$ is a vector perpendicular to both $A$ and $B$ whose length is the area of the parallelogram determined by $A$ and $B$. Then it's clear that there are many vectors $X$ for which $A \times B = A \times X$.


text:
Q: Regex match word that may or may not have prefix and suffix These are the inputs I have:
ab_something#123
something else#15
zy_s0meth1ng third
nothing

The output I need is:
something
something else
s0meth1ng third
nothing

The closest I got was this (?:.._|^)(.*)(?:#[0-9]*|$) but this still captures the suffix.

A: Try this: ^(?:.*_)*(.*?)(?:#[0-9]*)*$
Based on a regex tester I used, this pattern captures the desired string in group 1 for your four examples.
Things I changed:

*

*Moved the start and end anchors outside the non-capturing groups to
ensure they are always matched.

*Used * on both prefix/suffix
patterns in case there are multiple prefix/suffixes in a string.

*Used the lazy quantifier (*?) on the middle pattern to ensure that
it won't grab suffixes before the suffix group can get them.

A: /^(.{2}_)?([^#]+)(.\d+)*$/
A friend of mine ended up helping me.
Basically:
(.{2}_)? matches prefix which appears 0 or 1 times
([^#]+) matches the middle part until #
(.\d+)*$ matches # and all the numbers after it

A: Try this :

var str = ["ab_something#123",
  "something else#15",
  "zy_s0meth1ng third",
  "nothing"
];

for (var i = 0; i < str.length; i++) {
  str[i] = str[i].replace(/(^[a-zA-Z]+_|#[0-9]+$)/g, '');
}
console.log(str);


text:
Q: Can Jest testing framework test the code written in java as TS calls a java function My project is on Java-JS/TS, I am currently writing test cases for JS/TS in jest. One module is calling Java function and returns a value to Js based on which test will pass or fail. My question is will jest run this test as it involves Java code? If no then How can I test the module?
Pls advise.


text:
Q: Use file system watcher to monitor files being copied? i am doing an application that uses file system watcher and the main aim is to monitor files that are being copied , so i looked at the file system watcher method i found 4 events i can sue , they are change , delete , rename and create , i didn't find the copy event , umm and i'd like to watch specific files and when a user tries to copy the files i prevent him from doing so using the file system watcher method , so in file system watcher is there any method for copying files monitoring that i can use ? , sorry my question may look stupid but this is the first time i use file system watcher and i read about it a lot and almost all people agree about the 4 events that can be used in that class .

A: There is no operation called copying a file.
Rather, copying is a combination of reading one file and writing another one.
You cannot reliably do this.

A: You cannot do this with FileSystemWatcher
May be monitor Clipboard and if you find list of files, check location of it

A: I think you can at least have a notification of who copied the file by using WMI notification. Another option is restricting user access to the folders.
Try this link.
http://technet.microsoft.com/en-us/library/ee176985.aspx#EHAA

A: Why don't you check that the executable is launched from the usb key at the beginning of your software ? this way the user who copied the file won't be able to launch it even if he copied the exe.


text:
Q: How to extract specific line in text file I am text mining a large document. I want to extract a specific line.
CONTINUED ON NEXT PAGE   CONTINUATION SHEET REFERENCE NO. OF DOCUMENT BEING CONTINUED: PAGE 4 OF 16 PAGES

SPE2DH-20-T-0133   SECTION B

PR: 0081939954   NSN/MATERIAL: 6530015627381

ITEM DESCRIPTION

BOTTLE, SAFETY CAP

BOTTLE, SAFETY CAP   RPOO1: DLA PACKAGING REQUIREMENTS FOR PROCUREMENT

RAQO1: THIS DOCUMENT INCORPORATES TECHNICAL AND/OR QUALITY REQUIREMENTS (IDENTIFIED BY AN 'R' OR AN 'I' NUMBER) SET FORTH IN FULL TEXT IN THE DLA MASTER LIST OF TECHNICAL AND QUALITY REQUIREMENTS FOUND ON THE WEB AT:

I want to extract the description immediately under ITEM DESCRIPTION.
I have tried many unsuccessful attempts.
My latest attempt was:
for line in text:
    if 'ITEM' and 'DESCRIPTION'in line:
        print ('Possibe Descript:\n', line)

But it did not find the text.
Is there a way to find ITEM DESCRIPTION and get the line after it or something similar?

A: The following function finds the description on the line below some given pattern, e.g. "ITEM DESCRIPTION", and also ignores any blank lines that may be present in between. However, beware that the function does not handle the special case when the pattern exists, but the description does not.
txt = '''
CONTINUED ON NEXT PAGE CONTINUATION SHEET REFERENCE NO. OF DOCUMENT BEING CONTINUED:    PAGE 4 OF 16 PAGES

SPE2DH-20-T-0133 SECTION B

PR: 0081939954 NSN/MATERIAL: 6530015627381

ITEM DESCRIPTION

BOTTLE, SAFETY CAP

BOTTLE, SAFETY CAP RPOO1: DLA PACKAGING REQUIREMENTS FOR PROCUREMENT

RAQO1: THIS DOCUMENT INCORPORATES TECHNICAL AND/OR QUALITY REQUIREMENTS (IDENTIFIED BY AN 'R' OR AN 'I' NUMBER) SET FORTH IN FULL TEXT IN THE DLA MASTER LIST OF TECHNICAL AND QUALITY REQUIREMENTS FOUND ON THE WEB AT:
'''

I've assumed you got your text as a text string, and thus the function below will split it into a list of lines ..
pattern = "ITEM DESCRIPTION" # to search for

def find_pattern_in_txt(txt, pattern):
    lines = [line for line in txt.split("\n") if line] # remove empty lines
    if pattern in lines: return lines[lines.index(pattern)+1]
    return None

print(find_pattern_in_txt(txt, pattern)) # prints: "BOTTLE, SAFETY CAP"

A: Test like this :
description = False
for line in text:
    if 'ITEM DESCRIPTION' in line:
        description = True
    if description:
        print(line)

Know this will work but you need something to stop reading the description, maybe another title like this
description = False
for line in text:
    if 'ITEM DESCRIPTION' in line:
        description = True
    if description:
        print(line)
    if "END OF SOMETHING":
        description = False

A: Use the string function 'find' as in the following, 'find' will return the index of the string you are looking for, so a positive number shows that you have found it.
code:

txt = "Hello, welcome to my world."
x = txt.find("welcome")
if x > 0:
    print(x)

***
output:
***
7

A: f=open("aa.txt","r")

a=[]

for i in f:

  a.append(i.split())

t1=0

for j in range(len(a)):

   for i in range(len(a[j])):

       if(a[j][i]=="ITEM" and a[j][i+1]=="DESCRIPTION"):

           t1=j

for i in range(t1+1,len(a)):

    for j in range(len(a[i])):

        print(a[i][j]),

A: Use regex
import re
pattern = re.compile("(ITEM DESCRIPTION)\n.*") #if the information is directly
below without white space
pattern = re.compile("(ITEM DESCRIPTION)\n\n.*") #if there is a white space
before the information

for i, line in enumerate(open('file.txt')):
    for match in re.finditer(pattern, line):
        print 'Found on line %s: %s' % (i+1, match.group())