text:
Q: Check if entry exists in previous mysql query results I'm using MySQLdb with python.  I execute a SELECT query and store the results in a dictionary, D.  The actual query is quite complicated so it's not clear how to do it in a single query, which is why I'm splitting it into two.
Then I run a second query and would like to add the condition that rows from columnB in the second query exist IN D.values(). ie, I'd like to do something like:
import MySQLdb
db = MySQLdb.connect()
cursor = db.cursor(MySQLdb.cursors.DictCursor)

cursor.execute("SELECT a, b FROM t1;")
results1 = cursor.fetchall()

I'd like to do the following, somehow passing an array from a previous query's results into to SELECT command:
cursor.execute("SELECT c, d FROM t2 WHERE d IN results1.b.values();")

Thank you,

A: It sounds like you can do what you want with a single query, and a join statement:
cursor.execute("SELECT t1.a, t1.b, t2.c, t2.d FROM t1 JOIN t2 ON t1.b = t2.d;")

A: You can set a set of values in an IN statement, but it is not advisable for the following reasons:

*

*Slow: An IN statement becomes an OR a OR b OR etc statement, which is just slow in execution

*An IN statement is limited in number of values you can place in there.

A better solution is to use a subquery:
SELECT c, d FROM t2 WHERE d IN (SELECT b FROM t1);

Or even better (faster) is the JOIN:
SELECT c, d FROM t2
INNER JOIN t1 ON t2.d=t1.b;


text:
Q: Rails has_many relation to all enum types I have 2 models: Department and Station. Station has 3 different enum types. User should have a possibility to select 1, 2 or 3 stations of different type using checkboxes. If a station is selected, a record in Station should be created.
Any idea how to do so?
Another words, it should be something like this:
class Department < ApplicationRecord
  has_many :stations, dependent: :destroy

class Station < ApplicationRecord
  enum type: { type1: 0, type2: 1, type3: 2 }
  belongs_to :department

_form.rb should be something like this:
  = f.association :stations, :as => :check_boxes, :collection => Station.types.keys

but of course it should be different.

A: Since a Department can have at most one Station of each type, each type of station should have its own select input. These inputs should use names different from stations (maybe station_type_1 etc.). Then you can create a hidden stations input and sync the selections.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Warning: Each child in a list should have a unique "key" prop I am getting this error when I upload the files in cloudinary.
  const [images, setImages] = useState([]);

 function showWidget(){
    const widget= window.cloudinary.createUploadWidget(
      {
        cloudName:'djguiefro',
        uploadPreset:'fz1sjhdc',
      },
      (error, result)=>{
        if(!error && result.event ==='success'){
          setImages((prev)=>[...prev,{url:result.info.url, public_id:result.info.public_id}])
        }
        else{
          console.log(error)
        }
      }
    );
    widget.open();
  }`

<Form.Group className='mb-3'>
                  <Button type='button' onClick={showWidget}>Upload Images</Button>

                    {/* 2:11:34 */}
                    {images.map((image)=>(

                        {/*add items for removing  {(imgToRemove != image.public_id) this will remove the cross icon once clicked }*/}
                        {imgToRemove !== image.public_id && handleRemoveImg(image)}>}

                    ))}

                </Form.Group>`

I tried to fix the error but stuck


text:
Q: Accessing data from Database View from Rails Console I have created a view according to this blog:
http://viget.com/extend/rails-nested-has-many-through-with-sql-views
The migration was successful. My view name is the same as the blog (groupby_entries).
I can see that view was successfully created and data is accessible from it when I do a select * on it from my DB UI.
I would like to use this as a table from now on only to retrieve the data (group by queries).
But, when I try to access the data from my rails console it throws an error:
1.9.3p194 :002 > GroupbyEntry.find(:all)
NameError: uninitialized constant GroupbyEntry
Am I missing on adding something somewhere? Kindly let me know.. I tried Groupby_entry.find(:all) as well.. But it gives out the same error.
Thanks,


text:
Q: Why am I not able to print the value outside th e for loop I am trying to print the value of max but not able to print. But once I put the Print statement inside the for loop then I can print it. Can anyone please help me out
class Codechef {
     public static void main(String[] args) throws java.lang.Exception {
        // your code goes here
        try {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            int a[] = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = sc.nextInt();

            }
            int max = a[0];

            for (int i = 0; i < n; i++) {
                int sum = a[i];
                while (a[i + 1] > a[i] && i + 1 < n) {

                    sum = sum + a[i + 1];
                    i++;
                }
                if (sum > max) {
                    max = sum;

                }

            }
            System.out.println(max);

        } catch (Exception e) {
            return;
        }
    }
}

A: As pointed out in comments, you should add e.printStackTrace() to check what exception is being thrown.
        } catch (Exception e) {
            e.printStackTrace();
        }

When I added it in your catch block, I was able to see underlying problem:
5
1 2 3 4 5
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
    at in.rohaan.PrintMaxValue.main(PrintMaxValue.java:19)

Problem seemed to be inside inner while loop where you were accessing array element first before checking whether index is valid or not. You were doing this:
while(a[i+1] > a[i] && i+1<n){ // Would fail for i=n-1

It should actually be :
while (i + 1 < n && a[i + 1] > a[i]) { // ((n-1) + 1 < n) returns false, statement is not executed

When I updated while's condition, I was able to see max being printed:
5
1 2 3 4 5
15


text:
Q: Is there a way to Reflect JavaScript properties and method from a "class" or function, not from an object? It's very easy to get reflection from a JavaScript object, just as following code.
var getAllMembers = function (obj) {
    var members = {};
    members.properties = [];
    members.methods = [];

    for (var prop in obj) {
        if (typeof obj[prop] != 'function')
            members.properties.push(prop);
        else members.methods.push(prop);
    }
    return members;
}

function demo_class(na, nb) {
    this.a = na;
    this.b = nb;

    this.funca = function () {
        console.log(this.a);
    }
    this.funcb = function () {
        console.log(this.b);
    }
}

var x = new demo_class(1234, 4321);

var members = getAllMembers(x);

console.log(members.properties);  // [ 'a', 'b' ]
console.log(members.methods);     // [ 'funca', 'funcb' ]

My question is: Is there a way to get properties and methods from a class or function, instead of from an object? For example, like this:
var members = getAllMembers(demo_class); // Only can get '[] []'

A: In Javascript everything is an object. It doesn't exists the class concept. So each time you use the new operator (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new) it returns you an object using the function as a constructor.
You can get an approximation to this using the Prototype concept. Where you define your methods in the prototype instead of the constructor function itself.
function Person(name, family) {
    this.name = name;
    this.family = family;
}

Person.prototype.getFull = function() {
    return this.name + " " + this.family;
};

Here is a post explaining it https://www.thecodeship.com/web-development/methods-within-constructor-vs-prototype-in-javascript/

A: In javascript there is no real concept of class, because it is a prototypal language. A function is an object.
What you can do is test if your object has a named function constructor, to test if it is an object contructed with a function or not. If not, you can create an instance to get the properties like you already did:
NOTES: this will work only if you use class constructors defined with the keyword function (not constructed via another named function). Your function will also get all the inherited properties from the prototype chain, if you don't use the hasOwnProperty() function.
var getAllMembers = function (obj) {
    var members = {}, toTest;
    members.properties = [];
    members.methods = [];

    //construct object if argument is a constructor
    toTest = (obj.constructor === Function) ? new obj() : obj;

    for (var prop in toTest) {
        if (typeof toTest[prop] != 'function')
            members.properties.push(prop);
        else members.methods.push(prop);
    }
    return members;
}

function demo_class(na, nb) {
    this.a = na;
    this.b = nb;

    this.funca = function () {
        console.log(this.a);
    }
    this.funcb = function () {
        console.log(this.b);
    }
}

var x = new demo_class(1234, 4321);

var members = getAllMembers(x);

console.log(members.properties);  // [ 'a', 'b' ]
console.log(members.methods);     // [ 'funca', 'funcb' ]

var members = getAllMembers(demo_class);


text:
Q: Failed to Attach Database? I created a database using SQL Server 2008 and detached it.
When I try to re-attach on another server, I get this message:

TITLE: Microsoft SQL Server Management Studio
Attach database failed for Server ' x-PC'.  (Microsoft.SqlServer.Smo)
ADDITIONAL INFORMATION:
An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)
The database 'manage' cannot be opened because it is version 661. This server supports version 655 and earlier. A downgrade path is not supported.
  Could not open new database 'manage_test'. CREATE DATABASE is aborted.
  (Microsoft SQL Server, Error: 948)

A: You cannot attach/detach or backup/restore a database from a newer version of SQL Server down to an older version - the internal file structures are just too different to support backwards compatibility.
In your case, you have a SQL Server 2008 R2 database (version 661), and you're trying to attach it to a SQL Server 2008 server (version 655). This will not work since SQL Server 2008 and 2008 R2 are two different versions - they are not compatible when going from 2008 R2 "down" to 2008.
You can either get around this problem by

*

*using the same version of SQL Server on all your machines - then you can easily backup/restore databases between instances

*otherwise you can create the database scripts for both structure (tables, view, stored procedures etc.) and for contents (the actual data contained in the tables) either in SQL Server Management Studio (Tasks > Generate Scripts) or using a third-party tool

*or you can use a third-party tool like Red-Gate's SQL Compare and SQL Data Compare to do "diffing" between your source and target, generate update scripts from those differences, and then execute those scripts on the target platform; this works across different SQL Server versions.


text:
Q: Conditional if statement I would like to add a list of categories to my conditional statement, how should I add multiple categories id ?
Using like 123,124,125 or 123 || 124
I have a big list of categories so I am looking for the cleanest way to achieve that
thanks
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');
$categories = $product->getCategoryIds(); /*will return category ids array*/
foreach($categories as $category){
    $cat = $objectManager->create('Magento\Catalog\Model\Category')->load($category);
    echo $cat->getId();
    }

?>

  <?php if($cat->getId()==123): ?>
    <?php echo $block->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('myblockid')->toHtml();?>
    <?php endif; ?>

A: Use in_array PHP function:
<?php if(in_array($cat->getId(), [123, 124, 125])): ?>

A: The best solution is to use in_array function
<?php
   if(in_array($cat->getId(), $your_array){
      $block->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('myblockid')->toHtml();
   }
?>

A: Use in_array() : This Checks if a value exists in an array or not.Return true if exist.
<?php
    if(in_array($cat->getId(), $categories ):
        echo $block->getLayout()->createBlock('Magento\Cms\Block\Block')->setBlockId('myblockid')->toHtml();
    endif;
?>


text:
Q: Multiple stitching I used the code from Automatic Image Stitching with Accord.net
i changed the code to stitch multiple images
My code after selecting multiple files was
img1 = new Bitmap(imgName[0]);

I change the code for btnBlend
Blend blend = new Blend(homography, img1);
pictureBox.Image = blend.Apply(img2);
img1 = new Bitmap(blend.Apply(img2));`

I added the part img1 = new Bitmap(blend.Apply(img2)); so i can keep the first stitch image as my copy and this is were to sticth the other image.
Then at the btnDoItAll
for (int x = 1; x < NumOfFiles; x++)
{
  img2 = new Bitmap(imgName[x]);
  btnHarris();
  btnCorrelation();
  btnRansac();
  btnBlend();
}

After running it, there's no error at all but when it goes to the looping part at the btnBlend c# hangs and displays vshost.exe has stop working
any help to correct this?

A: The problem is that the resulting image of the first stitching is not flat and must be transform to flat image before sewing a new image


text:
Q: how can I monitor a folder for changes or activities? I want to delete my macport folder but I'm not sure if there is something important in it. So my idea was to observe the folder a time. Is this possible?

A: Use Folder Actions.
Alternatively, you can try starting a script using launchd with a WatchPaths. I'm pretty sure this answer can easily be adapted, by removing StartOnMount and specifying WatchPaths.
You can notify e.g. using the program say (audio notifications), or, if you use it, Growl from command line using growlnotify. If you want the latter to be really fancy, this answer might help with that.


text:
Q: Can I call function outside viewmodel on knockout? Let's say I want to call my plain javascript function on one of my data-binding. Is it possible to do so?
I have tried:-
hi

hi</span?

Obviously, my attempt was unsuccessful.
http://jsfiddle.net/RcxVj/
Edit:- Adding jsfiddle on the tag as this seems to be an issue with jsfiddle.

A: Yes it is possible to call plain javascript function in data-binding. Try it in your project, it's working. There may be some problem in the jsfiddle script.

A: Yes, you can.
Please note the official Knockout documentation for the click binding:

You can reference any JavaScript function - it doesn't have to be a function on your view model. You can reference a function on any object by writing click: someObject.someFunction.

Working example:
https://jsbin.com/ciwofayegi/1/edit?html,css,js,output
HTML

Javascript
var outsideFn = function () {
    alert("outside function");
};

var vm = {
    "txt": ko.observable("some text")
};

ko.applyBindings(vm);


text:
Q: code performance of my code             import java.util.Scanner;
            class same
          {static void anagram(String s1,String s2)
{int p=0;
    char[] c1=s1.toCharArray();
    char[] c2=s2.toCharArray();
    if(s1.length()!=s2.length())
    {
        System.out.println("not anagram");
        System.exit(0);
    }
    for(int i=0;i<s1.length();i++)
    {
        for(int j=0;j<s1.length();j++)
        {
            if(c1[i]==c2[j])
                c2[j]='\\';
        }
    }

        while
        ( p<s2.length()&&c2[p]=='\\')
        {
            p=p+1;

        }

        if(p==s2.length())
            System.out.println("anagram");
        else

    System.out.println("non anagram");

}
public static void main(String[] args)
{Scanner input=new Scanner(System.in);
System.out.println("enter the two strings");

String s1=input.next();
String s2=input.next();

    anagram(s1,s2);
}}

This code checks whether the two strings are anagram or not.
Can you tell me the performance of this code? Is it lengthy(time complexity) or not?
Or should I improve quality of my code?
And thanx for previous suggestion.It is my first post and i am new to java.

A: Since you don't iterate over any dynamic length but all iterations are with a limit of 4, the complexity of the code is ... O(1).

A: I've tried two ways, A is sorting the characters of both strings alphabetically and comparing the results, B is counting every character in both strings and comparing the counts. I'd prefer A over B regarding readability.
public boolean isAnagramA(String a, String b) {
    if (a.length() != b.length()) {
        return false;
    }
    char[] aAsArray = a.toUpperCase().toCharArray();
    char[] bAsArray = b.toUpperCase().toCharArray();
    Arrays.sort(aAsArray);
    Arrays.sort(bAsArray);
    return Arrays.equals(aAsArray, bAsArray);
}

public int numberOf(char needle, char[] haystack) {
    int count = 0;
    for (int i = 0; i < haystack.length; i++) {
        if (haystack[i] == needle) {
            count++;
        }
    }
    return count;
}

public boolean isAnagramB(String a, String b) {
    if (a.length() != b.length()) {
        return false;
    }
    char[] aAsArray = a.toUpperCase().toCharArray();
    char[] bAsArray = b.toUpperCase().toCharArray();
    for (int i = 0; i < aAsArray.length; i++) {
        if (numberOf(aAsArray[i], aAsArray) != numberOf(aAsArray[i], bAsArray)) {
            return false;
        }
    }
    return true;
}

public void run() {
    {
        long start = System.nanoTime();
        System.out.println(isAnagramA("OTTO", "TOT"));
        System.out.println(isAnagramA("OTTO", "TOTO"));
        System.out.println(isAnagramA("LOTTO", "TOLLO"));
        System.out.println(isAnagramA("yarm", "army"));
        System.out.println(isAnagramA("Yarm", "Army"));
        System.out.println(isAnagramA("SMAISMRMILMEPOETALEVMIBVNENVGTTAVIRAS",
                "AltissimvmPlanetamTergeminvmObservavi"));
        System.out.println((System.nanoTime() - start) + " ns for 6 x A");
    }
    {
        long start = System.nanoTime();
        System.out.println(isAnagramB("OTTO", "TOT"));
        System.out.println(isAnagramB("OTTO", "TOTO"));
        System.out.println(isAnagramB("LOTTO", "TOLLO"));
        System.out.println(isAnagramB("yarm", "army"));
        System.out.println(isAnagramB("Yarm", "Army"));
        System.out.println(isAnagramB("SMAISMRMILMEPOETALEVMIBVNENVGTTAVIRAS",
                "AltissimvmPlanetamTergeminvmObservavi"));
        System.out.println((System.nanoTime() - start) + " ns for 6 x B");
    }
    {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            isAnagramA("SMAISMRMILMEPOETALEVMIBVNENVGTTAVIRAS", "AltissimvmPlanetamTergeminvmObservavi");
        }
        System.out.println((System.currentTimeMillis() - start) + " ms for 1000000 x A");
    }
    {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            isAnagramB("SMAISMRMILMEPOETALEVMIBVNENVGTTAVIRAS", "AltissimvmPlanetamTergeminvmObservavi");
        }
        System.out.println((System.currentTimeMillis() - start) + " ms for 1000000 x B");
    }
}

Method run() is used to test whether it works (not JUnit, just output) and which ways is faster, this is the output:
false
true
false
true
true
true
579384 ns for 6 x A
false
true
false
true
true
true
252453 ns for 6 x B
1310 ms for 1000000 x A
1333 ms for 1000000 x B

At first A seems to be two  times slower but looping 1000000 times over checking Galileo Galilei's anagram shows almost no difference in performance (hopefully it's not due to compiler optimization).
I do agree with other commenters about caring for correctness and readability first and research optimizations only if and where there is a real need for it.


text:
Q: How to update npm nested (vulnerable) dependency? Github has flagged a dependency in my app lock file as vulnerable.
To fix it I should updated that package to a newer version.
How do I do that if I don't have any control on the vulnerable package, because is nested in the dependencies tree?
Apologies if this is a very basic question but I don't seem to find anything useful regarding this.

A: As explained here: https://stackoverflow.com/a/17423915, you can use npm shrinkwrap to explicitly tell npm to get the nested dependency version that you want.

A: I think there is a way to (potentially) achieve this with the depth flag.
caveat 1: The official npm update documentation advices to use a depth of 9999 to recursively inspect all dependencies. But on my setup that either results in an error or npm freezing. So I use a realistic depth of 1 or 2. (0 is the default, meaning only direct dependencies)
UPDATE: See mike's comment below. The depth option is no longer supported; npm update <name> will now update all instances of name in the tree, except those in a bundled or shrinkwrapped tree.
So this should still work:
npm update vulnerable_package

caveat: This only works if there is an updated version available of the nested package (with a fix for the vulnerability) that still fits the version range of your dependency. So if this is your dependency tree:
Your Package -> Dependency@^1.0.0 -> Vulnerable_package@^2.1.0

And the vulnerability fix is in Vulnerable_package version 3.0.0, then it won't work, since npm update will only update to the highest version that still fits the version range of your dependency. (in this case the highest 2.x.x release)

A: You're correct - as the vulnerable package lies within one of your dependencies, like so:
Your Package -> Dependency -> Vulnerable package

You will be unable to update the dependencies' dependency in a way that would survive a future npm install or yarn.
However, you could take the following approaches:

*

*Bug the maintainer: Get them to update their dependencies and bump versions. This will fix the issue for you and your peers who are depending on this package.

*Are there alternative packages? Maybe you can use a different package instead of the vulnerable one. This will involve some updates to your code, but might be the best approach in the long run, especially if the original maintainer is unresponsive.

*Fix it yourself: Fork the repository and update the dependency in this copy. You can then refer to the package in your package.json.

See this answer for more information on installing directly from Github repos.
This approach will fix the problem short term, but it is not advised as you won't benefit from any bug fixes the maintainer makes, and besides, by the time you've done this the dependency might have been updated anyway!

A: NPM 8 introduced "overrides" to help workaround these type of issues. You can now override specific transitive dependencies of your direct dependency to the version you need. In your case, you would declare something like below to fix the vulnerable dependency.
{
  "overrides": {
    "your-direct-dependency": {
      "vulnerable-package": "fixed_version"
    }
  }
}

More details @ https://docs.npmjs.com/cli/v8/configuring-npm/package-json#overrides

A: First Update command
npm install -g npm
then, to remove vulnerable
npm audit fix --force


text:
Q: How do I re-route network traffic using Python? Small apps like Freedom and Anti-social have created quite a stir lately. They cut you off from the internet either entirely or just block social networking sites in order to discourage procrastination and help you exert self control when you really want to get some work done.
I looked at the available options and also at some Google Chrome extensions and decided that none of them is exactly doing what I want, so I'm planning to write my own little Python tool to do that. My first impulse was to simply modify /etc/hosts to re-route requests to certain servers back to localhost. However, this can only block entire domains. I'd need to block addresses based on regular expressions or simple string matching to block something like google.com/reader (yes, this one in particular), but not the entire google.com domain.
Which Python framework can I use to monitor my network traffic and block blacklisted addresses and what is the basic design to achieve what I want to do? Do I use the socket library? I'm very comfortable with Python, but I'm very new to network programming.

A: Since you're comfortable with python, I'd directly recommend twisted. It is slightly harder than some other libraries, but it is well-tested, has great performance and many features. You would just implement a small HTTP proxy and do your regexp filtering on the URLs.


text:
Q: putBytes() vs putFile() for uploading images I want to upload images from app to firebase storage and there is fragment in app where I want to
show images on server in recycler view. Should I use putBytes() or putFile()? such that when I display images using recylerview in OnBind() function images load faster.

A: putFile() is just a convenience method for automatically reading the file and using putBytes() to upload it.  Either way, the speed of the upload is limited by the speed of the device's connection to Cloud Storage.


text:
Q: Why doesn't RFO after retirement break memory ordering? I thought that I understood how L1D write miss is handled, but thinking carefully about it made me confused.
Here is an assembly language fragment:
;rdi contains some valid 64-bytes aligned pointer
;rsi contains some data
mov [rdi], rsi
mov [rdi + 0x40], rsi
mov [rdi + 0x20], rsi

Assume that [rdi] and [rdi + 0x40] lines are not in the Exclusive or Modified state in l1d. Then I can imagine the following sequence of actions:

*

*mov [rdi], rsi retires.

*mov [rdi], rsi tries to write data into l1d. RFO is initiated, data is placed into WC buffer.

*mov [rdi + 0x40], rsi retires (mov [rdi], rsi already retired, so it's possible)

*mov [rdi + 0x40], rsi initiates RFO for the consecutive cache line, data is placed into WC buffer.

*mov [rdi + 0x20], rsi retires (mov [rdi + 0x40], rsi already retired so it is possible)

*mov [rdi + 0x20], rsi notices that there is RFO for [rdi] in progress. The data is placed into WC buffer.

*BOOM! [rdi] RFO is happened to finish before [rdi + 0x40] RFO so the data of mov [rdi], rsi and mov [rdi + 0x20], rsi can now be commited to the cache. It breaks memory ordering.
How is such case handled to maintain correct memory ordering?

A: Starting an RFO can be separate from placing the store data into an LFB; e.g. starting RFOs early for entries that aren't yet at the head of the store buffer can allow memory-level parallelism for stores.  What you've proved is that for that to happen, store data can't always move into an LFB (Line Fill Buffer, also used for NT / WC stores).
If an RFO could only happen by moving store data from the store buffer (SB) into an LFB, then yes, you could only RFO for the head of the SB, not in parallel for any graduated entry.  (A "graduated" store is one whose uops have retired from the ROB, i.e. become non-speculative).  But if you don't have that requirement, you could RFO even earlier, even speculatively, but you probably wouldn't want to.1
(Given @BeeOnRope's findings about how multiple cache-miss stores to the same line can commit into an LFB, and then another LFB for another line, this might be the mechanism for having multiple RFOs in flight, not just the SB head.  We'd have to check if an ABA store pattern limited memory-level parallelism.  If that's the case, then maybe starting an RFO is the same as moving the data from the SB to an LFB, freeing that SB entry.
 But note that the new head of the SB still couldn't commit until those pending RFOs complete and commit the stores from the LFBs.)

A simple mental model that's pretty close to reality
On a store miss, the store buffer entry holds the store data until the RFO is complete, and commits straight into L1d (flipping the line from Exclusive to Modified state).  Strong ordering is ensured by in-order commit from the head of the store buffer2.
As @HadiBrais wrote in answer to Where is the Write-Combining Buffer located? x86

My understanding is that for cacheable stores, only the RFO request is
  held in the LFB, but the data to be store waits in the store buffer
  until the target line is fetched into the LFB entry allocated for it.
  This is supported by the following statement from Section 2.4.5.2 of
  the Intel optimization manual:

The L1 DCache can maintain up to 64 load micro-ops from allocation
    until retirement. It can maintain up to 36 store operations from
    allocation until the store value is committed to the cache, or written
    to the line fill buffers (LFB) in the case of non-temporal stores.

This is pretty much fine for thinking about performance tuning, but probably not MDS vulnerabilities that can speculatively use stale data that faulting loads read from an LFB or whatever.
Any store coalescing or other tricks must necessarily respect the memory model.

But is it that simple?  No
We know CPUs can't violate their memory model, and that speculation + roll back isn't an option for commit to globally-visible state like L1d, or for graduated stores in general because the uops are gone from the ROB. They've already happened as far as local OoO exec is concerned, it's just a matter of when they'll become visible to other cores.  Also we know that LFBs themselves are not globally visible.  (There's some indication that LFBs are snooped by loads from this core, like the store buffer, but as far as MESI states they're more like an extension of the store buffer.)
@BeeOnRope has done some more experiments, finding some evidence that a series of stores like AAABBCCCC can drain into three LFBs, for lines A, B, C.  RWT thread with an experiment that demonstrates a 4x perf difference predicted by this theory.
This implies that the CPU can track order between LFBs, although still not within a single LFB of course.  A sequence like AAABBCCCCA (or ABA) would not be able to commit past the final A store because the "current head" LFB is for line C, and there's already an LFB waiting for line A to arrive.  A 4th line (D) would be ok, opening a new LFB, but adding to an already-open LFB waiting for an RFO that isn't the head is not ok.  See @Bee's summary in comments.
All of this is only tested for Intel CPUs, AFAIK.

Previous to this, we thought there was no store coalescing on Intel/AMD, but have long been puzzled by hints in Intel manuals about LFBs acting as WC buffers for stores to normal (strongly ordered) WB memory
(This section not updated in light of @BeeOnRope's new discovery).
There's also no solid evidence of any kind of store merging / coalescing in the store
buffer on modern Intel or AMD CPUs, or of using a WC buffer (LFB on Intel) to hold store data while waiting for a cache line to arrive.  See discussion in comments under Are two store buffer entries needed for split line/page stores on recent Intel?.  We can't rule out some minor form of it near the commit end of the store buffer.
We know that some weakly-ordered RISCs microarchitectures definitely do merge stores before they commit, especially to create a full 4-byte or 8-byte write of a cache ECC granule to avoid an RMW cycle.  But Intel CPUs don't have any penalty for narrow or unaligned stores within a cache line.
For a while @BeeOnRope and I thought there was some evidence of store coalescing, but we've changed our minds.  Size of store buffers on Intel hardware? What exactly is a store buffer? has some more details (and links to older discussions).
(Update: and now there is finally evidence of store coalescing, and an explanation of a mechanism that makes sense.)

Footnote 1:  An RFO costs shared bandwidth and steals the line from other cores, slowing them down.  And you might lose the line again before you get to actually commit into it if you RFO too early.  LFBs are also needed for loads, which you don't want to starve (because execution stalls when waiting for load results).  Loads are fundamentally different from stores, and generally prioritized.
So waiting at least for the store to graduate is a good plan, and maybe only initiating RFOs for the last few store-buffer entries before the head.  (You need to check if L1d already owns the line before starting an RFO, and that takes a cache read port for at least the tags, although not data.  I might guess that the store buffer checks 1 entry at a time and marks an entry as likely not needing an RFO.)  Also note that 1 SB entry could be a misaligned cache-split store and touch 2 cache lines,  requiring up to 2 RFOs...
Footnote 2:
Store buffer entries are allocated in program order (at the tail of the buffer), as instructions / uops are issued into the out-of-order back end and have back-end resources allocated for them.  (e.g. a physical register for uops that write a register, a branch-order-buffer entry for conditional branch uops that might mispredict.)  See also Size of store buffers on Intel hardware? What exactly is a store buffer?.  In-order alloc and commit guarantee program-order visibility of stores.  The store buffer insulates globally-visible commit from out-of-order speculative execution of store-address and store-data uops (which write store-buffer entries), and decouples execution in general from waiting for cache-miss stores, until the store buffer fills up.
PS Intel calls the store buffer + load buffers collectively the memory order buffer (MOB), because they need to know about each other to track speculative early loads.  This isn't relevant to your question, only for the case of speculative early loads and detecting memory-order mis-speculation and nuking the pipeline.
For retired store instructions (more specifically their "graduated" store buffer entries), it is just the store buffer that has to commit to L1d in program order.


text:
Q: Is there a way to use different Sublime Text themes for different file sources? I would like to set up two separate themes in ST3. One theme would be for local files, while the second would be for any file opened via my FTP app (Transmit). Is this possible?
The simplest solution may be to override any file coming from the FTP's cache folders. But I have no idea if this is possible.

A: Yes, this is possible with a fairly simple plugin. Open a new Python file in Sublime, and add the following to it:
import sublime
import sublime_plugin

class TransmitColorSchemeCommand(sublime_plugin.TextCommand):

    def run(self, edit):
        if "/path/to/transmit/tempfiles" in self.view.file_name():
            self.view.settings().set("color_scheme", "Packages/Color Scheme - Default/Monokai.tmTheme")

class TransmitEventListener(sublime_plugin.EventListener):

    def on_load_async(self, view):
        view.run_command("transmit_color_scheme")

Make sure you adjust "/path/to/transmit/tempfiles" to the actual path you want, and change the "color_scheme" setting to the color scheme you want to use for Transmit files. Save the file as Packages/User/transmit_color_scheme.py where Packages is the folder opened when selecting the Preferences -> Browse Packages... menu option. On OS X, it's ~/Library/Application Support/Sublime Text 3/Packages.
Once saved, the event listener will start up immediately, and any file you open that contains the specified path will have the color scheme set to whatever you indicate. All other files from other paths will use your default color scheme.
Have fun!

Please note that this plugin will only work in ST3. To make it work in ST2, change def on_load_async to def on_load.


text:
Q: How to set the name argument while using ctypes.pythonapi.PyCapsule_New How do I pass in the name of a capsule into the second argument of PyCapsule_New via ctypes?
I've tried the following, but it seems that something is off:
capsule = ctypes.pythonapi.PyCapsule_New(b'data', b'abcdef.ghijkl', None)
capsule = ctypes.pythonapi.PyCapsule_New(b'data', ctypes.create_string_buffer(b"abcdef.ghijkl"), None)
capsule = ctypes.pythonapi.PyCapsule_New(b'data', ctypes.c_chap_p(b"abcdef.ghijkl"), None)

For example, the name of the capsule is not being set correctly:
>>> import ctypes
>>> ctypes.pythonapi.PyCapsule_New.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_void_p]
>>> ctypes.pythonapi.PyCapsule_New.restype = ctypes.py_object
>>>
>>> capsule = ctypes.pythonapi.PyCapsule_New(b'data', b'abcdef.ghijkl', None)
>>>
>>> capsule
<capsule object "" at 0xf7102f98>
>>> capsule
<capsule object "e" at 0xf7102f98>
>>> capsule
<capsule object "���capsule
<capsule object "" at 0xf7102f98>
>>> capsule
<capsule object "e" at 0xf7102f98>
>>> capsule
<capsule object "e" at 0xf7102f98>
>>> capsule
<capsule object "���

If I use ctypes.create_string_buffer(b"abcdef.ghijkl"):
>>> capsule = ctypes.pythonapi.PyCapsule_New(b'data', ctypes.create_string_buffer(b"abcdef.ghijkl"), None)
>>> capsule
<capsule object "abcdef.ghijkl" at 0xf7102fb0>
>>> capsule
<capsule object "" at 0xf7102fb0>
>>> capsule
<capsule object "" at 0xf7102fb0>
>>> capsule
<capsule object "" at 0xf7102fb0>
>>> capsule
<capsule object "" at 0xf7102fb0>

The strange thing here is that if I make a C Extension that returns a capsule, I can extract it's name using ctypes, and it works:
>>> capsule_from_c_ext = mycext.capsule()
>>> ctypes.pythonapi.PyCapsule_GetName.restype = ctypes.c_char_p
>>> ctypes.pythonapi.PyCapsule_GetName.argtypes = [ctypes.py_object]
>>> name = ctypes.pythonapi.PyCapsule_GetName(capsule_from_c_ext)
>>> name
b"abcdef.ghijkl"
>>> type(name)
<class 'bytes'>
>>> assert name == b"abcdef.ghijkl"
>>>
>>> capsule = ctypes.pythonapi.PyCapsule_New(b'data', name, None)
>>> capsule
<capsule object "abcdef.ghijkl" at 0xf6f23c20>
>>> capsule
<capsule object "abcdef.ghijkl" at 0xf6f23c20>
>>> capsule
<capsule object "abcdef.ghijkl" at 0xf6f23c20>
>>>
>>> capsule
<capsule object "abcdef.ghijkl" at 0xf6f23c20>
>>> capsule
<capsule object "abcdef.ghijkl" at 0xf6f23c20>

Additionally, if you use a shorter name, like b'name', it appears to work correctly.

A: I got a hint from the docs:

The name string may either be NULL or a pointer to a valid C string. If non-NULL, this string must outlive the capsule. (Though it is permitted to free it inside the destructor.)

Creating a variable with the name first, and then calling it, seems to work:
>>> import ctypes
>>> ctypes.pythonapi.PyCapsule_New.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_void_p]
>>> ctypes.pythonapi.PyCapsule_New.restype = ctypes.py_object
>>> name = b'abcdef.ghijkl'
>>> capsule = ctypes.pythonapi.PyCapsule_New(b'data', name, None)
>>>
>>> capsule
<capsule object "abcdef.ghijkl" at 0xf6f23bd8>
>>> capsule
<capsule object "abcdef.ghijkl" at 0xf6f23bd8>
>>> capsule
<capsule object "abcdef.ghijkl" at 0xf6f23bd8>
>>> capsule
<capsule object "abcdef.ghijkl" at 0xf6f23bd8>

And you can prove that you need the name variable to not be deallocated:
del name
>>> capsule
<capsule object "" at 0xf7102fb0>
>>> capsule
<capsule object "" at 0xf7102fb0>
>>> capsule
<capsule object "" at 0xf7102fb0>
>>> capsule
<capsule object "" at 0xf7102fb0>


text:
Q: How to dynamically create subdomains I want to dynamically create new sub domains on my website. i mean if you have example.com then you dynamically create sub.example.com .
i looked on google and there was nothing really good. i downloaded some scripts but they were all not working. my website is based on php so please if there is anyway i can do it in php tell me, and also if it can be possible with python then that is awesome!.

A: You need to setup a wildcard subdomain. Basically, anything.mysite.com will resolve to mysite.com. At that point it's up to your code to kick in and serve up the proper content depending on what subdomain the user is looking at.
http://www.google.lk/search?q=wildcard+subdomain

A: You can't do this unless you have permission to alter the DNS server for your domain.


text:
Q: VUE and Pagination : pag.component loose values after pager is changed/clicked I am implementing a pager in my VUE app, and at first load, everything works fine.. The parameters needed for the pager-component is sat correctly, and the pager displays as it should..
Problem is.. when i navigate (use/click) the pager, all props are sat to Undefined and presents me one evil :
[Vue warn]: Invalid prop: type check failed for prop "currentPage". Expected Number, got Undefined.

When i use the VUE debugger in Chrome i notice :

My thoughts :

*

*Must be something wrong with passing prop values to the pager

*Pager is instancified before the values are sat ?

Snippet for Home.VUE component :

import * as types from '../store/mutationtypes'
import { mapGetters, mapActions } from 'vuex'
import Pagination from './Pagination.vue'
import Modal from './Modal.vue'

var moment = require('moment')

export default {
    name: 'Home',
    data() {
        return {
            FiltersVisible: false,
            orderList: {
                currentPage: 1,
                totalPages: this.$store.state.ordersCount / 10,
                // totalPages:5,
                itemsPerPage: 10
            },
            showModal: false,
            searchString: ''
        }
    },
    computed: {
        ...mapGetters(['orders', 'ordersCount']),
        totalPages() {
            return this.ordersCount / 10
        }
        // ...mapGetters(['orders'])
    },

    methods: {
        ...mapActions(['getOrders']),
        init() {
            var queryParams = null;
            this.getOrders(queryParams)
        },
        doSearch: function() {
            var queryParams = {
                searchString: this.searchString
            }
            this.getOrders(queryParams)
        },
        viewOrder: function(order) {
            this.$router.push('/vieworder/' + order._source.orderid)
        },
        viewAppInfo: function(order) {
            this.$router.push('/viewappinfo/' + order._source.mobileinstanceid)
        },
        humanDate: function(dateToFormat) {
            return moment(dateToFormat).format("DD.MM.YYYY [kl: ] hh:mm")
        },
        orderListChanged(pageNum) {
            this.orderList.currentPage = pageNum;
            var queryParams = {
                skip: (pageNum * this.orderList.itemsPerPage) - this.orderList.itemsPerPage,
                take: this.orderList.itemsPerPage
            };
            this.orderList = this.getOrders(queryParams)
        },
        toggleModal: function(actionName, orderItem) {
            var modalParams = {
                modalComponent: actionName,
                selectedOrderItem: orderItem,
                userProfileId: null
            }
            this.$store.dispatch('switchModalComponent', {
                modalParams: modalParams
            })
            this.showModal = true;
        },
    },
    watch: {
        'ordersCount': function(val) {
            if (val) {
                this.orderList.totalPages = val / 10
            }
        },
        route: function() {
            this.init()
            console.log("Orderscount er = " + ordersCount)
            console.log(this)
        }
    },
    created() {
        this.init()
    },
    components: {
        'modal': Modal,
        'Pagination': Pagination
    }
}
<template>

      .....Order data looped through and presented here....

This is page {{ orderList.currentPage }}

    <pagination :current-page="orderList.currentPage" :total- pages="orderList.totalPages" :items-per-page="orderList.itemsPerPage" @page-changed="orderListChanged">
    </pagination>

</template>

Snippet for Pagination.VUE

import Util from './services/Util'

export default {
  props: {
    currentPage: {
      type: Number,
      required: true
    },
    totalPages: Number,
    itemsPerPage: Number,
    totalItems: Number,
    visiblePages: {
      type: Number,
      default: 5,
      coerce: (val) => parseInt(val)
    }
  },

  methods: {
    activePage(pageNum) {
      return this.currentPage === pageNum ? 'active' : ''
    },
    pageChanged(pageNum) {
      this.$emit('page-changed', pageNum)
    }
  },

  computed: {
    lastPage() {
      if (this.totalPages) {
        return this.totalPages
      } else {
        return this.totalItems % this.itemsPerPage === 0 ?
          this.totalItems / this.itemsPerPage :
          Math.floor(this.totalItems / this.itemsPerPage) + 1
      }
    },
    paginationRange() {
      let start = this.currentPage - this.visiblePages / 2 <= 0 ?
        1 : this.currentPage + this.visiblePages / 2 > this.lastPage ?
        Util.lowerBound(this.lastPage - this.visiblePages + 1, 1) :
        Math.ceil(this.currentPage - this.visiblePages / 2)
      let range = []
      for (let i = 0; i < this.visiblePages && i < this.lastPage; i++) {
        range.push(start + i)
      }
      return range
    }
  }

}

Util.JS

lowerBound (num, limit) {
      return num >= limit ? num : limit
    }
<template>

                «

            {{ n }}

                »

</template>

Updated 05.10 - Order before paging :

Updated 05.10 - Order after paging

A: The problem is definitely in the getOrders action. without seeing it, I cannot pinpoint what it is, but based on the screenshot I feel like I can take a good guess. I'm assuming you're using an async call to an api every time you hit next page, if not, it's a whole lot easier.
getOrders returns a promise. that is most likely because it is an asynchronous function using axios/fetch or some other lib to do remote call. The way vuex works is that the actions are asynchronous and mutations are synchronous. If you call
this.orderList = this.getOrders(queryParams)

you are are assigning the asynch function as the value, which is guaranteed to return a promise.
what you need to do is split the functionality into a getter and an actions
you call the action to get new data from remote server (assuming that's what you're using)
as part of the callback/promise response, you mutate the data into the store
you also make a getter (orderList) available that you can access from your component, and use that instead of defining orderList in the component
when a user hits prev/next or any page, you...

*

*call action - updateList(queryParams)

*

*clear the orderList in the store (store.orders = []) as part of the action

*make an api call

*on success, update data

*update view to display a loading data animation

*once the data is updated, reactivity will kick in and the orderList will repopulate

*

*using a watch or a orderList > 0, remove the loading animation


text:
Q: Adding new Column to the Existing Table on ui5 I am trying to add a new column to myTable under some conditions but I couldn't manage to do it so far.  (I'm using JS views)
I have a variable called data.
Here is mycode
Table ;
var vergleichTable1 = new sap.m.Table(this.createId("vergleichTable1"), {
        columns: [
            new sap.m.Column({
                header: new sap.m.Label({
                    text: data[0].KURZNAME
                })
            }),
            new sap.m.Column({
                header: new sap.m.Label({
                    text: data[1].KURZNAME
                })
            }),
        ]
    }).addStyleClass("vergleichTable1");

And If my data.length === 3 I want to add another column to my table
What I tried and did not work is ;
       if(data.length === 3){
            this.byId("vergleichTable1").addColumn({
                header: new sap.m.Label({
                        text: data[2].KURZNAME
                })
            });
        }

could someone maybe help & show me the mistake I am doing ? This .addColumn() is not really working here
I am doing these both in my View but using .addColumn() in the Controller did not help either

A: You should use like below in controller.
this.getView().byId("vergleichTable1").addColumn( new sap.m.Column({
                                  header: new sap.m.Label({
                                      text:"hi" //data[0].KURZNAME
                                  })
                              }));

What you are doing wrong is you are not passing sap.m.Column object inside addColumn method.


text:
Q: sql : combining 2 query to give 1 resultset In a case where I have to perform 2 queries, I wanted to replace it by simply one single line of query. Example:
select col1, col2 from tableA where col3 = 'a';

This will return (consider) 2 rows:
col1    col2

abc     abc.bcd
xyz     xyz.pqr

Now, in a second table we made a different query for each rows from query 1:
   select col1 from tableB where col2 = 'abc';
   (AND)
   select col1 from tableB where col2 = 'xyz';

This will give a result set like:
 TableB
 col1
 1111
 2222

If the question is unclear kindly mention I shall try to elaborate with better example.
(although database vendor is not issue, I am comfortable with oracle or mysql. Thanks).

A: You basically just need a join between the two tables like this:
SELECT b.col1, a.col1
FROM tablea a
INNER JOIN tableb b ON a.col1 = b.col2
WHERE a.col3 = 'a'

A: You can make a single query like :
select col1 from tableB where col2 = 'abc' or col2 = 'xyz';

And if you have large number of strings to check for then you can use :
select col1 from tableB where col2 in ('abc','xyz','mno');

Update: you can use nested queries like :
select col1 from tableB where col2 in (select col1 from tableA where col3='a');

But make sure that data type of col1 inside that nested query and data type of col2 after where match.

A: Try this:
select col1
from tableB
where col2 in (select col1
               from tableA
               where col3='a')

A: You can use the single query as,
select col1, col2 from tableB where col2 = 'abc' or col2='xyz'

A: It' s not completely clear to me, but I think you are looking for a usual Join expression?
SELECT B.Col1, A.Col1 FROM TableA A inner join TableB B on A.Col1 = B.Col2
Please refer to the Join expression.  This example is for SQL Server and newer versions of Oracle.


text:
Q: How does angular determine whether jQuery is present? Because I'm getting the weird situation that angular objects like element in the link function of a controller ends up being a jQLite object although jQuery is definitely present as in being loaded in memory and successfully used elsewhere on the same page.
The Angular FAQ is rather vague on that question:

Yes, Angular can use jQuery if it's present in your app when the application is being bootstrapped. If jQuery is not present in your script path, Angular falls back to its own implementation of the subset of jQuery that we call jQLite.

So what exactly does 'present' mean?

A: Angular.js will use jQuery if it's included first, otherwise it will use it's own jqLite. If you load jQuery after AngularJS, AngularJS attaches itself to jqLite but you can still access jQuery through $.
See below the code used by angular.js to determine if jquery is loaded:
  // bind to jQuery if present;
  jQuery = window.jQuery;
  // Use jQuery if it exists with proper functionality, otherwise default to us.
  // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  // versions. It will not work for sure with jQuery <1.7, though.
  if (jQuery && jQuery.fn.on) {
    jqLite = jQuery;
    extend(jQuery.fn, {
      scope: JQLitePrototype.scope,
      isolateScope: JQLitePrototype.isolateScope,
      controller: JQLitePrototype.controller,
      injector: JQLitePrototype.injector,
      inheritedData: JQLitePrototype.inheritedData
    });

Changing the order of script tags may not happen very often, but it could occur if you start modularising the codebase. In particular, this issue has happened while using some module loaders like RequireJS.


text:
Q: R Data transformation: dataframe to matrix filled with 0 and 1 I am looking to transform a long dataformat to a wide one, but the values of the "signatories" column are not exactly the same as the new column names should be.
I have a dataframe with bill numbers and the names of their signatories (senators). If a senator has signed a bill, their is a row in the dataframe with the bill number and the name of the senator in questions. All the senators whose names are not listed next to the bill number have not signed the bill.
I want to construct a matrix with rows as bill numbers and columns as senator names, filled with 1s and 0s only. 1 indicates that a given senator has signed a bill, 0 indicates they have not.
ex <- data.frame(billno = c(715851, 715851, 715851,715852, 715852, 715852, 715852, 715852, 715852), signatories = c("Ben", "Lisa", "Roger", "Louise", "Macy", "John", "Jake", "James", "Ben"))

Senatornames <- c("Ben", "Lisa", "Roger", "Louise", "Macy", "John", "Jake", "James", "Julian", "Ayn")

#current output is this
#  billno signatories
#1 715851         Ben
#2 715851        Lisa
#3 715851       Roger
#4 715852      Louise
#5 715852        Macy
#6 715852        John
#7 715852        Jake
#8 715852       James
#9 715852         Ben

#I want something like this. How do I arrive at this result?
#  billno Ben   Lisa    Roger   Louise   Macy   John   Jake   James    Ayn
#1 715851  1      1       1       0        0      0       0      0      0
#2 715852  1      0       0       1        1      1       1      1      0

Thanks so much!!

A: You could just do:
table(ex)
#>        signatories
#> billno   Ben Jake James John Lisa Louise Macy Roger
#>   715851   1    0     0    0    1      0    0     1
#>   715852   1    1     1    1    0      1    1     0

Or if you want to do it in tidyverse style and be left with a data frame, the whole thing can be done with:
tidyr::pivot_wider(as.data.frame(table(ex)),
                   names_from  = "signatories",
                   values_from = "Freq")
#> # A tibble: 2 x 9
#>   billno   Ben  Jake James  John  Lisa Louise  Macy Roger
#>   <fct>  <int> <int> <int> <int> <int>  <int> <int> <int>
#> 1 715851     1     0     0     0     1      0     0     1
#> 2 715852     1     1     1     1     0      1     1     0

A: Next code can bring you close to what you want. I have used the vector you provided in order to create a full_join() so that all values can appear. Here the code:
library(tidyverse)
#Dataframe
df <- data.frame(signatories=Senatornames,stringsAsFactors = F)
#Code
ex1 <- ex %>% mutate(Value=1) %>%
  full_join(df) %>%
  fill(billno) %>%
  pivot_wider(names_from = signatories,values_from=Value) %>%
  replace(is.na(.),0)

Output:
# A tibble: 2 x 11
  billno   Ben  Lisa Roger Louise  Macy  John  Jake James Julian   Ayn
   <dbl> <dbl> <dbl> <dbl>  <dbl> <dbl> <dbl> <dbl> <dbl>  <dbl> <dbl>
1 715851     1     1     1      0     0     0     0     0      0     0
2 715852     1     0     0      1     1     1     1     1      0     0


text:
Q: Prove that any unbounded sequence has a subsequence that diverges to $∞$. To prove that any unbounded sequence has a subsequence that diverges to ∞, is it enough to say that you can take a subsequence $(a_{m(k)})$ where $m(k)=k$, as you know that this diverges to infinity, you are done?

A: Here is an example of an unbounded sequence that does not diverge to infinity:
$$1, 0, 2, 0, 3, 0, 4, 0, 5, \dots.$$
Do you see the problem in your thinking? Remember, diverging to infinity means for all $M > 0$ there is an $N$ such that $n \geq N$ implies $a_n \geq M$.
Here's a hint on how do this correctly. Given a term $a_{n_k}$ there must be an $m > n_k$ such that $a_{n_k} + 1< a_{m}$ otherwise $a_n$ would be bounded. Then choose $n_{k+1} = m$.


text:
Q: Loop through records and create .txt files from batches I have below code where I would like to create .txt files only instead of excel files. Below will take records from Sheet1 separate them by 47k rows, paste it into template and will create .txt file (format without commas, print method, not overwriting existing txt files in the folder, each filename to be "Part"& "sequence number", for ex. "Part 1" ) and then repeat until all records from Sheet1 gone into txt files. I need help with creating a loop which will create txt file & paste the records into txt files
     Sub FillTemplate(c As Long)
        Dim Lrow1A, c, start, finish as Long
        Dim TV As Variant

        ' this part divides all records by 47k and rounds up
        Lrow1A = Worksheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Row

        TV = Lrow1A / 47000
        TV = Application.WorksheetFunction.RoundUp(TV, 0)

        ' this part copies records (divided by batches of 47k) into template
        start = ((c - 1) * 47000) + 2
        finish = (c * 47000) + 1

        Worksheets("Sheet1").Range(Cells(start, 1), Cells(finish, 1)).Copy
        Worksheets("Template").Cells(1, 9).PasteSpecial Paste:=xlPasteValues
        End Sub

        Sub new_template(c As Long)

' Need help here: How to make macro create new text files?
'at the moment it overwrites existing text files in a folder

        Dim wb As Workbook
        Dim WBname, WBname1 As String

        Workbooks.Add
        Set wb = ActiveWorkbook

        WBname = wb.FullName 'create new workbook to rename previous one

        WBname1 = ActiveWorkbook.Name

        Workbooks("Sum.xlsm").Activate
        Worksheets("Template").Select
        Range("A:R").Select
        Selection.Copy
        Workbooks(WBname1).Activate
        Columns(1).Select
        ActiveSheet.Paste

        ActiveWorkbook.SaveAs "\\D\folder\Part " & c & ".txt", FileFormat:=xlTextWindows

        ActiveWorkbook.Close
        End Sub

        Sub Finalcode()

        Dim c As Long
        For c = 1 To TV

    Call FillTemplate(c)
    Call new_template(c)

    Next c

    End Sub

A: Set fs = CreateObject("scripting.filesystemobject")
file1 = ThisWorkbook.Name

file1 = Replace(file1, ".xlsm", "")
Debug.Print file1

filepath = "C:\Billing3\"    '<<< change me
j1 = 1
file2 = filepath & file1 & j1 & ".txt"
Set outfile = fs.OpenTextFile(file2, 8)
lrow = 250000
Sheets(1).Select

For i1 = 1 To lrow
    text1 = Cells(i1, 1)
    outfile.WriteLine text1

    If Int(i1 / 47000) = i1 / 47000 Then
        outfile.Close
        j1 = j1 + 1
        file2 = filepath & file1 & j1 & ".txt"
        Set outfile = fs.CreateTextFile(file2, 8)
    End If

Next
outfile.Close`

Filesystemobject can be used to deal with text and csv files
The above code will copy column A from 1st sheet in batches of 47000 up to a maximum of lrow (set at 250000 which can be changed)

A: Sub new_template(c As Long)

Set fs = CreateObject("scripting.filesystemobject")
file2 = "\\D\folder\Part " & c & ".txt"
Set Outfile = fs.OpenTextFile(file2, 8)

Worksheets("Template").Select
For r1 = 1 to 47000
    Text1 = cells(r1, 1)   'cell in row r1, column 1   (or A)
    For c1 = 2 to 18   'run from columns 2 to 18  (B to R)
        Text1 = Text1 & vbtab & cells(r1, c1)   'vbtab is the tab delimiter
    Next
        'Text1=left(Text1, Len(Text1)-1) 'remove last tab which is not be used
    Outfile.writeline Text1
Next
Outfile.close

End sub


text:
Q: Maximum Likelihood & Least Squares Method with and without given errors In our lecture we used ML and LS to estimate the parameter(s) of a given distribution. In both examples we had we were given three measurements $y_i$. For the LS method we also had an error $\sigma_i$ for each measurement. Now I think the LS method we used is also called weighted least squares as the function we sought to minimize was given by:
$S(a) = \sum_{i=1}^{N} \frac{(y_i-f(x_i,a))^2}{\sigma_i^2}$
For the error on the parameter estimate we varied $S(a)$ so that the difference between $S(a_{min})$ and the new $S(a)$ is $n^2$ to get the $n \sigma$ standard deviation for $a$.  Now I got this but here is my first question: What do I do if no errors for my measurements are given?
Secondly we had a very similar example for the Maximum Likelihood method, again with three measurements. But in this case no errors were given. So I know how to compute the parameter estimate but if errors were given I had no idea how to incorporate them in my likelihood function $L$. For the error of the parameter estimate we varied $L$ again (as in LS) so the difference would be $\pm 0.5/2/3.4$ for $1/2/3\sigma$. I would assume there is a reasonable way to include errors somehow. But how?

A: At least the first case you have two probabilities:
First you assume a fixed error that is the same for each point. A reasonable pick would have to be justified from the particular case.
Second you assume that the measurement itself was exact. This can also be justified, e.g. when the error is very small and you have lots of data points or when the measurement outcomes are discrete or just because you do have no better possibility. Then you simply set $\sigma=1$
Does this answer your first question?


text:
Q: SIngle word does'nt wrap for a japaneese word in table I have a table where table width can be anything depending upon number of columns.
In a particular column, there will be contact name in any language.
In all other languages, the single word appears for full width.
But in Japanese language, the single word breaks, by auto wrapping it.
I want to know the exact reason behind it.
Please find my workout here

    Normal English Language

            heading1
            Heading2
            Heading3

            accoutrements
            accoutrements
            accoutrements

    Japaneese Language

            Heading1
            Heading2
            Heading3

            わかりません
            わかりません
            の着用

A: It has nothing to do with the japanese characters, it  is just that the text doesn't fit in the cell (it uses the first row to determine the size) , splitting only occurs on words (separated by space).  In japanese this is more complicated since one character can be one word.
http://jsfiddle.net/s6s6fzbp/
use   tags for the header is advised. and use nowrap to prevent it from going to a new line.

                わかりません
                わかりません
                の着用

A: you could do as mentioned and add nowrap to the td's or th's individualy or you could use css on all td's and th's so that they will all not wrap like so:
td, th {
    white-space: nowrap;
}


text:
Q: How to open mat date picker in a modal? i have an angular 4 project requirement of opening a mat-date picker in a modal.I ve tried lot of ways of doing it and searched on web,but failed.
Is there any appropriate way to do it ?or any other nice date-picker which opens in a modal or pop up something ?
<mat-form-field>
     <input matInput [matDatepicker]="picker" placeholder="Choose a date">
     <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
     <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

A: You can use the touchUi input of MatDatepicker for a touch UI which is meant for mobile users. (You can treat it as a modal though)
<mat-form-field>
    <input matInput [matDatepicker]="picker" placeholder="Choose a date">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker touchUi></mat-datepicker>
</mat-form-field>


text:
Q: SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse () I have added reCaptcha to my firebase project. Using send button I am sending form data as well as the response from captcha using grecaptcha.getResponse() to my server.
here is client.js code:

$('.sendUrl').on('click', function(e){
      e.preventDefault() ;

      $('#nonauthForm').validate({
         rules: {
            url_nauth: {
               required: true,
               url: true
            }
         }
      }) ;

      if( $('#nonauthForm').valid()){
         var captcha_val = grecaptcha.getResponse(widget1) ;

         $.post('/nonauth_url',{
            URL: $('#url').val(),
            CAPTCHA: captcha_val
         },function(data, status){
            if(status === 'success'){
               if(data.val === 1){
                  $('#newurl').html(`${window.location.origin+ '/'+ data.code}`) ;
                  $('#url').val('') ;
                  grecaptcha.reset(widget1) ;
               }
               else if( data.val === 0 ){
                  alert('Please select the captcha to continue !!') ;
               }
               else if( data.val === -1){
                  alert('Failed to verify captcha !!') ;
                  grecaptcha.reset(widget1) ;
               }
            }
         }).fail(function(res){
            errorAlert('Error occurred', 'An error happend while connecting to the server !') ;
         }) ;
      }
      else{
         $('label.error').addClass('text-danger d-block mt-2');
      }

   }) ;

here is my node server code (index.js):

const express = require('express') ;
const urlId = require('shortid') ;
const string = require('randomstring') ;
const app = express() ;
require('dotenv').config() ;
const secretkey = process.env.SECRETKEY ;

app.post('/nonauth_url', (req, res) => {
   let captchaRes = req.body.CAPTCHA ;
   if(captchaRes === undefined || captchaRes === '' || captchaRes === null) {
      return res.send({
         val: 0 ,
         code: null
      }) ;
   }
   let verification_url = `https://www.google.com/recaptcha/api/siteverify?secret=${secretkey}&response=${captchaRes}&remoteip=${req.connection.remoteAddress}` ;

   request(verification_url, function(err,response,body){
      let data = JSON.parse(body) ;
      if( data.success !== undefined && !data.success){
         return res.send({
            val: -1,
            code: null
         }) ;
      }

      let codeGenerated = 'n' + urlId.generate() ; // n for non-authenticated users

      let docname = 'doc-' + string.generate(4) ;

      let schema = {
         code: codeGenerated,
         url: req.body.URL,
         expiredAt: Date.now()+600000  // in milisceonds for 10min
      }

      let docRef = db.collection('nonauth_url').doc(docname).set(schema).then(() => {
         res.send({
            val: 1,
            code: schema.code
         }) ;
      }).catch(err => {
         console.log(err) ;
      }) ;
   }) ;
}) ;

exports.routeFunc = functions.https.onRequest(app) ;

So, with this if user doesn't check the captcha its will return code 0, code 1 for success & code -1 for failure in verification. This code is working perfectly on localhost. But on my hosting url **.firebaseapp.com if I'm not checking the captcha it's responding back for requirement of the captcha. But when I'm checking the recaptcha and sending the request to the server it's giving an error code of 500.
This is console for my functions in my main project console:

EDIT: Now I've used axios instead of request
New code:

axios.get(verification_url).then( res => {
      return res.data ;
   }).then( object => {
      if(object.success){
         let codeGenerated = 'n' + urlId.generate() ; // n for non-authenticated users

         let docname = 'doc-' + string.generate(4) ;

         let schema = {
            code: codeGenerated,
            url: req.body.URL,
            expiredAt: Date.now()+600000  // in milisceonds for 10min
         }

         let docRef = db.collection('nonauth_url').doc(docname).set(schema).then(() => {
            res.send({
               val: 1,
               code: schema.code
            }) ;
         }).catch(err => {
            console.log(err) ;
         }) ;
      }
      else{
         res.send({
            val: -1,
            code: null
         }) ;
      }
   }).catch(err => {
      console.log("Error occurred in axios",err) ;
   }) ;
}) ;

Now its giving following error:

Error occurred in axios
{ Error: getaddrinfo EAI_AGAIN www.google.com:443
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:67:26)
  errno: 'EAI_AGAIN',
  code: 'EAI_AGAIN',
  syscall: 'getaddrinfo',
  hostname: 'www.google.com',
  host: 'www.google.com',
  port: 443
  .
  .
  .
  .
}

A: So, I was able to solve this issue by changing the verfication url i.e
www.google.com/recaptcha/api/siteverify which is not meant for firebase project only for node.js on checking reCaptcha for firebase link here

Also changing my previous answer to this one:

const rp = require('request-promise') ;
rp({
      uri: 'https://recaptcha.google.com/recaptcha/api/siteverify',
      method: 'POST',
      formData: {
         secret: secretkey,
         response: captchaRes
      },
      json: true
   }).then(result => {
      console.log("recaptcha result", result)
      if (result.success) {
         // for human detection
      }
      else {
         // for bot detection
      }
   }).catch(reason => {
      // error handling
}) ;

and deploying it on the firebase it finally worked. I think firebase was not allowing to make call to the older recaptcha verfication address for which I needed a paid plan but on searching for firebase with recaptcha solved my issue.


text:
Q: Unexpected jQuery ajax json response I am having some strange issues with jQuery (1.7.2) ajax and asp.net.
When using the code below locally this all appears to work fine.  The ajax fires fine, the modal pops up as expected, the div slides down, and I'm very happy with the result.
However, on our development server, we run into some strange issues.  We start hitting the error function.  In the error function, the return text isn't our JSON'd time stamp, but rather the HTML from a different page in our page flow.  We've tried playing with the params to .ajax, we've tried fiddling with the modal, we've tried just returning the timestamp in our code behind method, we tried changing our dataType to text.  That allowed it to fire the modal, however, Inf.innerHTML just ended up displaying the rendering of that other page in our page flow.
We've spent a bunch of time trying to debug this, but we're still stuck.  Any ideas would be much appreciated.
jQuery:
$("#<%= Btn.ClientID %>").click(function() {
            $.ajax({
                async: true,
                type: "POST",
                url: "Page.aspx/Method",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data) {
                    $("#Modal").modal({
                        closeClass: "Modal-Close",
                        escClose: false,
                        opacity: 35,
                        overlayCss: { backgroundColor: "#000" }
                    }); //end Modal
                    //timeStamp = data.d; //Timestamp elsewhere in the js
                }, //end success
                error: function(xhr, status, error) { alert("xhr: " + xhr.responseText + "\n\nstatus: " + status + "\n\nerror: " + error); }
            }); //end ajax
            return false;
        }); //end Btn.click

$(".Modal-Close").click(function() {
       ModalClose();
});

var timeStamp;

    function ModalClose() {
        var img = document.getElementById("imgP");
        var Inf = document.getElementById("Info");
        var Name = document.getElementById("<%=divName.ClientID %>").value;
        img.src = "difImg.png";
        Inf.innerHTML = "Sometext" + Name + ", MoreText.<br />" + timeStamp;
        var divO = document.getElementById("<%=divOut.ClientID %>");
        $(divO).slideDown();
    }

C# Page Code-behind
[WebMethod(EnableSession = true)]
public static string Method()
{
    // Various magic
    return "{\"d\":\"" + DateTime.Now.ToString("MMMM dd, yyyy h:mm tt") + "\"}";
}


text:
Q: Add and commiting a file into SVN using SVN-Kit jar Actually i want to commit source into svn. I need to add and commit new files into svn repository and am using the below code. Code works properly but not able to commit into SVN
    String urls = "http://192.168.0.19/svn/cadgraf/Branch/Jobs";
    final String url = urls+File.separator+l_users.getSelectedValue().toString()+File.separator+"Active";
    System.out.println("svn url------>"+url);
    final String destPath = "/home/dev702/Desktop/Jobs-test/Tempfiles";
    SVNRepository repository = null;
    setupLibrary();
    try {
        //initiate the reporitory from the url
        repository = SVNRepositoryFactory.create(SVNURL.parseURIDecoded(url));
        //create authentication data
        ISVNAuthenticationManager authManager =
                SVNWCUtil.createDefaultAuthenticationManager("xxxxxx", "xxxxxx");
        repository.setAuthenticationManager(authManager);
        //output some data to verify connection
        System.out.println("Repository Root: " + repository.getRepositoryRoot(true));
        System.out.println("Repository UUID: " + repository.getRepositoryUUID(true));
        //need to identify latest revision
        long latestRevision = repository.getLatestRevision();
        System.out.println("Repository Latest Revision: " + latestRevision);

        //create client manager and set authentication
        SVNClientManager ourClientManager = SVNClientManager.newInstance();
        ourClientManager.setAuthenticationManager(authManager);
        //use SVNUpdateClient to do the export
        SVNCommitClient commitClient = ourClientManager.getCommitClient();
        commitClient.setIgnoreExternals(false);
    commitClient.doCommit(new File[]{new File(destPath)}, false, "Commit message", null, null, false, false, SVNDepth.INFINITY);
        SVNCommitClient client = new SVNCommitClient(authManager, null);
         SVNCommitInfo info;
         info = client.doCommit( new File[]{new File(destPath)}, false, "Commit message", null, null, false, false, SVNDepth.INFINITY);
    } catch (SVNException e) {
        e.printStackTrace();
    } finally {
        System.out.println("Done");
    }

code works fine but its not commiting files into SVN.


text:
Q: How to find difference in two not distinct arrays in javascript? I used underscore but I am open to vanilla JS If I have two arrays like
array1 = [{id: 'id1'}, {id:'id2'}, {id:'id3'}, {id:'id3'}]
array2 = [{id: 'id1'}, {id:'id2'}, {id:'id3'}]

The expected result should be [{id:'id3'}]
My method works perfectly for distinct arrays.
idsFrom1 = _.pluck(array1, 'id');
idsFrom2 = _.pluck(array2, 'id');
var diff = _.difference(_.union(idsFrom1, idsFrom2), _.intersection(idsFrom1, idsFrom2))

A: I think your issue is that you have to use some mechanism to count the deleted elements, such as _.countBy:

var first = [{
  id: 'id1'
}, {
  id: 'id2'
}, {
  id: 'id3'
}, {
  id: 'id3'
}]
var second = [{
  id: 'id1'
}, {
  id: 'id2'
}, {
  id: 'id3'
}]

function unwrap (o) {
  return o[this]
}

function wrap (k) {
  return _.object([k], [String(this)])
}

function counted(array) {
  return _.countBy(array, unwrap, 'id')
}

function constant() {
  return String(this)
}

function difference(first, second) {
  return _.flatten(_.values(_.mapObject(counted(first), function(v, k) {
    return _.range(0, v - this[k]).map(constant, k)
  }, counted(second)))).map(wrap, 'id')
}

console.log(difference(first, second))
<script src="http://underscorejs.org/underscore-min.js"></script>

A: This approach steps through one of the arrays and removes elements from both arrays that match as it moves through the array. That way anything without a partner in both arrays will remain at the end:

var array1 = [{id: 'id1'}, {id:'id2'}, {id:'id3'}, {id:'id3'}]
var array2 = [{id: 'id1'}, {id:'id2'}, {id:'id3'}]

idsFrom1 = _.pluck(array1, 'id');
idsFrom2 = _.pluck(array2, 'id');

for(var i=0;i<idsFrom1.length;) {
  var index = idsFrom2.indexOf(idsFrom1[i]);
  if(index > -1) {
    idsFrom1.splice(i,1);
    idsFrom2.splice(index,1);
  }
  else i++;
}

diff = [].concat(idsFrom1,idsFrom2);
objarr = [];
for(var i=0;i<diff.length;i++) objarr.push({"id":diff[i]});
console.log(objarr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

A: Try this. If you don't want to modify your original arrays, then you can create copies and use them for the modification

var array1 = [{
    id: 'id1'
  }, {
    id: 'id2'
  }, {
    id: 'id3'
  }, {
    id: 'id3'
  }],
  array2 = [{
    id: 'id1'
  }, {
    id: 'id2'
  }, {
    id: 'id3'
  }];

_.each(array1, function(obj1, i) {
  _.each(array2, function(obj2, j) {
    // Make sure the objects are not cleared off by a previous comparison
    var isEqual = array1[i] && array2[j] && _.isEqual(obj1, obj2);
    if (isEqual) {
      array1[i] = array2[j] = null;
    }
  });
});

console.log([].concat(_.compact(array1), _.compact(array2)));
<script src="http://underscorejs.org/underscore-min.js"></script>

A: This one doesn't use splice() and instead it "marks" each array member that should be removed by setting it to null and then uses compact() to take them all out at once. The speed of the indexOf() actually improves as idsFrom2 gets smaller with splice, so the faster approach depends on the number of matches and sizes of arrays.

array1 = [{id: 'id1'}, {id:'id2'}, {id:'id3'}, {id:'id3'}]
array2 = [{id: 'id1'}, {id:'id2'}, {id:'id3'}]

idsFrom1 = _.pluck(array1, 'id');
idsFrom2 = _.pluck(array2, 'id');

for(var i=0;i<idsFrom1.length;i++) {
  var index = idsFrom2.indexOf(idsFrom1[i]);
  if(index > -1) {
    idsFrom1[i] = null;
    idsFrom2[index] = null;
  }
}
diff = [].concat(_.compact(idsFrom1),_.compact(idsFrom2));
objarr = [];
for(var i=0;i<diff.length;i++) objarr.push({"id":diff[i]});
console.log(objarr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

A: Ok, this one appears to be the fastest in all of my tests. Use the splice() on the idsFrom2 array to get it to shrink as you move through idsFrom1, and set null on the idsFrom1 array matches and use compact() afterwards.

var array1 = [{id: 'id1'}, {id:'id2'}, {id:'id3'}, {id:'id3'}];
var array2 = [{id: 'id1'}, {id:'id2'}, {id:'id3'}];

idsFrom1 = _.pluck(array1, 'id');
idsFrom2 = _.pluck(array2, 'id');

for(var i=0;i<idsFrom1.length;i++) {
  var index = idsFrom2.indexOf(idsFrom1[i]);
  if(index > -1) {
    idsFrom1[i] = null;
    idsFrom2.splice(index,1);
  }
}
diff = [].concat(_.compact(idsFrom1),idsFrom2);
objarr = [];
for(var i=0;i<diff.length;i++) objarr.push({"id":diff[i]});
console.log(objarr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>


text:
Q: How can we move linux process to different memory area than one it is created Here is a requirement for one of my project.
I need to move the entire linux process into different memory location after the process creation.
Quite confused from where to start either at the end of dofork in fork.c or somewhere else.
And some where i am thinking will the process still work the same way if it is moved to other memory location.
Expecting some help to do this task.
Thanks


text:
Q: how can i get the record in account object dynamically? I have created controller and vf page.In my controller having three buttons such as modify,save and cancel.when i click the modify button(read only) it display the same page with save and cancel button.when i select the picklist value it will be updated in account object.when i click the save button i am getting this error ;

System.QueryException: List has no rows for assignment to SObject
  Error is in expression '{!Submit}' in component
  in page rfleet_paymetcondition: Class.Rfleet_PaymentConditions.Submit:
  line 38, column 1.

How can i resolve this issue. please find below attached images controller and vf page

Vf Page:
 <apex:page standardController="account" extensions="Rfleet_PaymentConditions" showHeader="false" sidebar="false">
    <apex:form >

        <apex:pageBlock >
            <apex:pageBlockButtons location="bottom" >
                    <apex:commandbutton value="Modify" action="{!save}" rendered="{!showSave}"  />
                    <apex:commandbutton value="Save" action="{!Submit}" rendered="{!showSubmit}"/>
                    <apex:commandbutton value="Cancel" action="{!Back}" rendered="{!showback}"/>
            </apex:pageBlockButtons>

    <apex:panelGrid columns="2" width="100%" html-readonly="true">

   <apex:pageblock title="Period 1" id="blockA" >
    <apex:outputPanel id="otpn">
    <apex:outputLabel >Upper Date           </apex:outputLabel>
 <apex:inputField value="{!acc.Rfleet_UpperDate_Period1__c}" html-disabled="{!bool}" id="acctype"/>

        <apex:inputField value="{!account.Rfleet_UpperMonth_Period1__c}" html-disabled="{!bool}" id="acctype1"/>

    <apex:outputLabel >Lower Date           </apex:outputLabel>
        <apex:inputField value="{!account.Rfleet_LowerDate_Period1__c}" html-disabled="{!bool}" id="acctype2"/>

        <apex:inputField value="{!account.Rfleet_LowerMonth_Period1__c}" html-disabled="{!bool}" id="acctype3"/>

   <apex:outputLabel >Due Date               </apex:outputLabel>
         <apex:inputField value="{!account.Rfleet_DueDate_Period1__c}" html-disabled="{!bool}" id="acctype4"/>

         <apex:inputField value="{!account.Rfleet_DueMonth_Period1__c}" html-disabled="{!bool}" id="acctype5"/>

   </apex:outputPanel>
   </apex:pageBlock>

  <apex:pageblock title="Period 2" id="blockB">
  <apex:outputPanel id="otpn1">
    <apex:outputLabel > Upper Date           </apex:outputLabel>
         <apex:inputField value="{!account.Rfleet_UpperDate_Period2__c}" html-disabled="{!bool}" id="acctype6"/>

         <apex:inputField value="{!account.Rfleet_UpperMonth_Period2__c}" html-disabled="{!bool}" id="acctype7"/>

   <apex:outputLabel >Lower Date           </apex:outputLabel>
         <apex:inputField value="{!account.Rfleet_LowerDate_Period2__c}" html-disabled="{!bool}" id="acctype8"/>

         <apex:inputField value="{!account.Rfleet_LowerMonth_Period2__c}" html-disabled="{!bool}" id="acctype9"/>

   <apex:outputLabel >Due Date               </apex:outputLabel>
         <apex:inputField value="{!account.Rfleet_DueDate_Period2__c}" html-disabled="{!bool}" id="acctype10"/>

         <apex:inputField value="{!account.Rfleet_DueMonth_Period2__c}" html-disabled="{!bool}" id="acctype11"/>

   </apex:outputPanel>
   </apex:pageBlock>

     </apex:panelGrid>

    </apex:pageBlock>

   </apex:form>
</apex:page>

Controller:
public class Rfleet_PaymentConditions {

 public Boolean bool {get;set;} public Boolean showSave{get;set;}
 public Boolean showSubmit{get;set;} public Boolean showback{get;set;}
 public string id; public account acc{get;set;}

     public Rfleet_PaymentConditions(ApexPages.StandardController controller) {
         bool = true;
        showSave = true;
          id=ApexPages.currentPage().getParameters().get('id');
     }
       public void save() {

     bool =false;
     showSave=false;
     showSubmit=true;
     showback=true;

     }  public PageReference back() {    // PageReference newocp = new PageReference('/apex/RFLEET_PaymetCondition');    //
 newocp.setredirect(true);
     PageReference pageRef = new PageReference('/' + ApexPages.currentPage().getParameters().get('id')+'?inline=0');
     return pageRef;
    //return newocp;  }

  public void Submit() {
bool=false;
acc=[SELECT
 Rfleet_DueDate_Period1__c,Rfleet_DueDate_Period2__c,Rfleet_DueMonth_Period1__c,Rfleet_DueMonth_Period2__c,Rfleet_LowerDate_Period1__c,Rfleet_LowerDate_Period2__c,Rfleet_LowerMonth_Period1__c,Rfleet_LowerMonth_Period2__c,Rfleet_UpperDate_Period1__c,Rfleet_UpperDate_Period2__c,Rfleet_UpperMonth_Period1__c,Rfleet_UpperMonth_Period2__c
 FROM Account where id=:id];   insert acc;
}
}

A: The Submit method in controller doesnt look logical. Checkout these two contradicting lines -
    acc=[SELECT Rfleet_DueDate_Period1__c, Rfleet_DueDate_Period2__c, Rfleet_DueMonth_Period1__c,
Rfleet_DueMonth_Period2__c,Rfleet_LowerDate_Period1__c,Rfleet_LowerDate_Period2__c,
Rfleet_LowerMonth_Period1__c,Rfleet_LowerMonth_Period2__c,Rfleet_UpperDate_Period1__c,
Rfleet_UpperDate_Period2__c,Rfleet_UpperMonth_Period1__c,Rfleet_UpperMonth_Period2__c
 FROM Account where id=:id];

AND
  insert acc;

Now the 1st line, you are querying account object, which essentially means that you are expecting the Account to be present in the database. In the second line you are trying to insert the same account into the database which is already present.
Currently the error comes because this query (1st line) is not returning any row back from database due to missing ID parameter in the URL. Checkout this line where you get ID from the URL.
id=ApexPages.currentPage().getParameters().get('id');

But be ensured, even if you fix this error, you might get an error in the next line. i.e. insert acc;
So its important to revisit on what functionality is expected and accordingly align both these lines.You might also want to look at this answer : How do I start to debug my own Apex code?


text:
Q: How to dismiss input fields without first responder I am on a viewController having textField being first responder, then a view gets instantiated on some call back method, but the keyboard still gets open on the instantiated viewController, I have tried to dismiss the keyboard by [self.view endEditing:YES] but it wont work.

A: try adding the [self.view endEditing:YES] in viewDidDisappear

A: Use default overide function of viewcontroller
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    view.endEditing(true)
}

A: hi go to mainStoryBoard and just check the checkMark on auto enable returnkey if it is same as you mainStoryBoard so then return back to your code
/// the method where  view is getting instantialte before view get Instantite use this here is sample.

  [self resignKeyBoard];

// goto your code here is uiButton with close icon

 - (IBAction)closeKeyboardPressed:(id)sender {

 cellTypeButton*btn=(cellTypeButton*)sender;

if(btn.selected){
    btn.selected=false;
    [self resignKeyBoard];
}else{
    btn.selected=true;
    [self resignKeyBoard];
}

}

-(void)resignKeyBoard{

closeKeyBoardBtn.hidden=true;

[PhoneNumTxt resignFirstResponder];
[codeTxt1 resignFirstResponder];
[usernameField resignFirstResponder];
[fullnameField resignFirstResponder];
[statusField resignFirstResponder];
[Utilities animateDownTextField:PhoneNumTxt inView:self.view];
[Utilities animateDownTextField:codeTxt1 inView:self.view];
[Utilities animateDownTextField:usernameField inView:self.view];
[Utilities animateDownTextField:fullnameField inView:self.view];
[Utilities animateDownTextField:statusField inView:self.view];

[self.view endEditing:YES];
}

 //// have a good day :D


text:
Q: Need Help Regarding Percentage Calculator Project Guys I'm New In Android App Development, I'm Trying To Build A Percentage Calculator which shows required percentages when user enters input & Click Calculate Button
For Example : Input = 80
 Output (0.15%) = 80.12 [Formula i want to use (80*0.15%)+80 ]

 Output (0.25%) = 80.20 [Formula i want to use (80*0.25%)+80 ]

 Output (0.50%) = 80.40 [Formula i want to use (80*0.50%)+80 ]

 Output (0.75%) = 80.60 [Formula i want to use (80*0.75%)+80 ]

 Output (1.00%) = 80.80 [Formula i want to use (80*1.00%)+80 ]

How To Do That In Mainactivity.java

A: you can do it like this
    EditText input = (EditText) findViewById(R.id.ip);
    Button button = (Button) findViewById(R.id.calcbutton);
    TextView textView = findViewById(R.id.tv15);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

           int num = Integer.parseInt(input.getText().toString());
          // for 0.15%
          float fifteen_percent = (float) ((num * 0.15) + num);
          textView.setText(String.valueOf(fifteen_percent));
        }
    });

You can do the same for remaining textviews..


text:
Q: How to distinguish Windows Phone 8.1 from Windows 8.1 in WinRT-apps (Javascript, C#)? How to distinguish Windows Phone 8.1 from Windows 8.1 in WinRT-apps using Javascript or C#? I need to know the operating system at runtime. Can anybody help?

A: if in code please try using pragma preprocessor.
for example
#if WINDOWS_PHONE
  windows phone code here
#else if WINDOWS
 windows 8 code here
#endif


text:
Q: Django Tutorial Part 1 'Poll' object doesn't change I'm new to Django with its tutorial -part 1 : Write your first app. when I want to see my Poll objects in python shell with this command Poll.objects.all(), I see [<Poll: Poll object>], however I've changed my models.py and added
class Poll(models.Model):
    def __unicode__(self):
        return self.question

class Choice(models.Model):
    def __unicode__(self):
        return self.choice

but I should see this:
[<Poll: What's up?>]

What's the problem?

A: I have been struggling with this same problem, and have tried everything to fix it.
I restarted the shell, reloaded the sycdb, I even started over with a brand new project, but still got same problem.
I finally figured it out! its stupid and easy...
__unicode__ needs two underscores on each side!! so '_'_'unicode'_'_'
I had def _unicode_(self), when it should be def __unicode__(self).
I am new to django and python, so maybe this is known to people, but it was not indicated anywhere in the tutorial and it is not obvious that there are two underscores!
Hope that helps anybody who has tried everything.

A: Had the same problem working with Windows 7, Python 3.3 and Django 1.5.1. I solved it by replacing unicode by str
For some reason my configuration does not seem to understand unicode
The code is then:
def __str__(self):
    return self.question

and it works...

A: Exit from shell and re-open it.

A: Use this:
# Create your models here.
from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __unicode__(self):
        return self.question

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField()
    def __unicode__(self):
        return self.choice_text

A: finally I found my answer:
according to the tutorial, I added this code to my models.py :
def was_published_today(self):
    return self.pub_date.date() == datetime.date.today()
but when I remove these two lines, I can see "what's up?" and not [<Poll: Poll object>] !! I don't know why this happen exactly? but it just worked!
I'm new to django and python but i think this caused for not defining was_published_today under Poll class?! they probably just missed it...

A: You need to restart the Django project before changes will show up. If you have already restarted it, then check for stale .pyc files and remove them.

A: You are referencing fields that don't exist on the model.
Once you've defined the question field, try saving one.
p = Poll(question="what's up?")
p.save()

now run the query again :-)

A: I don't know about Django specifically, but the Python shell calls __repr__ on objects to display their value. Try implementing that method in your class and see what that results in.
>>> class A:
...     def __str__(self):
...         return 'str'
...     def __repr__(self):
...         return 'repr'
...
>>> A()
repr
>>> print A()
str


text: Q: Error-Logging Decorator with separate/isolated exception handling inside a function Is there a way to write a generic logging-decorator, which logs all exceptions occurring inside a function or method (both the handled and unhandled exceptions), but doesn't affect the exception handling inside the function itself ? This could be useful to log the exceptions within a generic decorator, but to keep the function-specific exception handling part.


text:
Q: simple tool for compiling Clojure .clj into .class / .jar I've found two ways of compiling Clojure *.clj files into *.class files, and while they both work, I have some gripes with both of them.
The first one uses a REPL and so cannot be automated (or can it?)
The second one uses lein. To be frank I don't see why I should use a dependency management tool for something that should be part of the core tool-chain of the language. But in any case, using lein soon forces you to use a local Maven repository if your Clojure code needs to access local jars (which is highly likely).
Is there a better way to generate *.class or *.jar files from Clojure code that involves only core Clojure tools and that can be employed in a scripted, non-interactive way?

A: Clojure provides clojure.core.Compile, which can be used to compile Clojure code from the command-line.
java -Dclojure.compile.path=<targetdir> -cp <targetdir>;clojure.jar <list of namespaces>
For an example of how to use this from ant, look at the compile-clojure task in Clojure's own build.xml file.

A: clojure.core/compile can be automated via Clojure


text:
Q: I am trying to access "C" directory using cmd (Windows 10), but it's not working? I am using cmd to access C directory in windows 10. But it always go to C:\Users\LENOVO>. Actually I have to go to xampp folder in C drive. I have tried a few options but could not reach to xampp.
Some of them are:

C:\Users\LENOVO>C:

This results to C:\Users\LENOVO>.
Another one,

C:\Users\LENOVO>C: cd xampp

This also results the same: C:\Users\LENOVO>.
So please help me to access xampp folder which is in C drive as the cmd is always on

C:\Users\LENOVO>

However writing D: to cmd go to
D:\>.

A: This is not a valid command.
C: cd xampp

Use this instead.
CD C:\xampp

or
CD /D C:\xampp

The /D switch is explained in the help information using CD /?. It will also change the current drive letter. If you are currently on a D: directory, just using CD C:\Users\me will change the current directory on C:, but it will not change the current working drive away from D:.

A: Try cd / or maybe cd ../..
Both of these options will take you to base directory.

A: Open your command prompt. Write on it cd xampp then you reach on this folder.


text:
Q: Python asyncio aiohttp request data encoding I'm using python's aiohttp basic request module to make requests. My request is base64 encoded string and request body looks like:
body = {'request': 'eyJhYmMiOiJ4eXoifQ=='}

Here is the code for sending request:
response = yield from request(method='POST', url=url, allow_redirects=False, headers=headers, data=body)

The problem here is, this is getting received at the other end as:
{'request': 'eyJhYmMiOiJ4eXoifQ%3D%3D'}

which I believe is the url-encoded version of my request body.
How can I avoid this and send request as it is?

A: Use json parameter. An example from documentation:
async with aiohttp.ClientSession() as session:
    async with session.post(url, json={'test': 'object'})

A: remove content type from header if you are sending


text:
Q: PHP Regex after HTML  Shop Selling Price:

N/A

I want to match all the entire first line and then grab the N/A off the second line.
This is my preg_match statement:
preg_match("/Shop Selling Price\:<\/b>
(.*?)<\/td>/si", $content, $shop);

If the N/A is on the same line it works fine but not when it's on the next line.  I've tried \r and \n and nothing.

A: This code works fine:
<?php
$content = "Shop Selling Price:

N/A	";
preg_match("/Shop Selling Price\:<\/b>
(.*?)<\/td>/si", $content, $shop);
var_dump($shop);
?>

I would suggest checking $content to see if it matches the string above.
P.S. You don't need \: just : is fine.


text:
Q: Replace value from text in python I've the following line in my file test.sdl:
PHASE 1: [Walk_Towards] [-, 1 to 3, -3 to -5][Ego:-4 to -2, FSL]

I want to replace the 1 to 3 with new random numbers (x,y) like 4 to 11. This two numbers are not fixed and generated by a random method and changing for every iteration.
Note the 1 to 3 also not fixed and it is varied for every file
all the files have the same structure Like
PHASE 1: [] [, to ,  to ][Ego: to , FSL]

So I would like to change only the numbers in between the first 'to'
My ultimate goal is to do an iteration lets say of 6. For every iterate the numbers will change
for example  :
The current line is : PHASE 1: [Walk_Towards] [-, 1 to 3, -3 to -5][Ego:-4 to -2, FSL]
Second iteration will be based on a pre-defined variables (x,y) that changes every time randomly. So the result will be
`PHASE 1: [Walk_Towards] [-, x2 to y3, -3 to -5][Ego:-4 to -2, FSL]`

Third : PHASE 1: [Walk_Towards] [-, x2 to y3, -3 to -5][Ego:-4 to -2, FSL]
And so
This is the only numbers that i need to replace in the file. The format of the PHASE 1 is standard the only values change are numbers
I used:
for line in lines:
        if 'PHASE 1:' in line:
            print(line)
            print(line.split('[')[2].split(','))

I could manage to get the following data:
['-', ' 1 to 3', ' -3 to -5]']
But I could not go beyond that How can take these values and replace them with my own and change the file for that. Any help would be appreciated

A: This is where a regular expression might come in handy. Using re.sub, you could do
re.sub(r'(?P<start>\[.+?,\s*)\d+\s+to\s+\d+\s*,', f'\g<start>{n1} to {n2},', line)

with n1 and n2 the randomly generated substitution values.
To explain that a bit more, here's a fuller code sample, with the verbose flag turned on and comments to explain the regular expression a bit:
import re

line = "PHASE 1: [Walk_Towards] [-, 1 to 3, -3 to -5][Ego:-4 to -2, FSL]"
n1, n2 = 4, 11

print(re.sub(r'(?P<start>\[.+?,\s*)\d+\s+to\s+\d+\s*,', f'\g<start>{n1} to {n2},', line))

newline = re.sub(
    r'(?P<start>'     # Capture opening pattern
    '\[.+?,\s*'       # match: opening bracket + any characters up to a comma + the comma itself + any whitespace
    ')'               # Close capturing group
    '\d+\s+to\s+\d+'  # match digit(s) + whitespace + 'to' + whitespace + digit(s)
    '\s*,',           # match any optional whitespace + the comma

    f'\g<start>{n1} to {n2},',  # replacement: opening pattern + "n1 to n2," using an f-string
    line,
    flags=re.VERBOSE
)
print(newline)

which prints
PHASE 1: [Walk_Towards] [-, 4 to 11, -3 to -5][Ego:-4 to -2, FSL]

If the opening pattern is always [-, , it can probably be a bit simpler. But the above also allows for input like ...Towards] [7 to 11, 1 to 3, -3 to -5][... and it will still only replace the middle 1 to 3 only.