text:
Q: Convert milliseconds into date in different timezones How to convert milliseconds in mm/dd/yyyy in different timezones.
I have a datepicker, when I press save, it saves the date in millisecond.
The saved millisecond should display date according to timezone date.
My Code:
var millisecond=1378792800000;
var date=new Date(millisecond);
var date_month = date.getMonth() + 1;
display_date = date_month + "/" + date.getDate() + "/" + date.getFullYear();

The date is differ in different timezones
When my timezone is India GMT then it is 09/10/2013
and when I change my timezone to US Mountain it change to 09/09/2013.
So how can I handle different timezone in javascript.

A: I would suggest using a third party script such as moment.js to make your life easier
Here is an example: http://jsfiddle.net/cyxgJ/
var ms = 1378792800000;
var date = new moment(ms);

// see <http://momentjs.com/docs/#/manipulating/timezone-offset/>
date = date.zone(120);

document.body.innerHTML = date;


text:
Q: Number check and using pattern? The point is, that during the jquery.validation.js $.validator.addMethod("pattern"... pattern for general are modified to:
"^(?:" + myPattern + ")$" on line 612 in the jquery.validation.js source and as this result the pattern check is invalid. Equal if I key in 10 10.0 or 10,0.

text:   "ok",
id:     "btn_ok",
name:   "btn_ok",
click: function() {
  $("#dataset").validate({
  debug: true,
  rules: {
    myNumInput: {
  pattern: "((/^\d+)|(/^\d+\,\d*?))$"
    }
  },

  showErrors: function(errorMap, errorList) {
    var jsMsg = "";
      if (errorList.length > 0) {
          jsMsg = "

Error: Value must be " + errorList[0].element.name.toUpperCase()  + " " +
          errorList[0].message.toLowerCase() + "

";
    $(".isReturn").html("" + jsMsg + "");
          errorList[0].element.style.border = "solid red 1px";
          errorList[0].element.focus();
      }
  }
});

Any idea?

A: solved!
the point is, how key in patterns...
instead of using this syntax:
pattern: "((/^\d+)|(/^\d+\,\d*?))$"
this one works...:
pattern: /((^\d+)|(^\d+\,\d*?))$/
the important part is the "-sign. dont use it. should be a part of the documentation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ruby gems path issue (system vs brew) I'm having an issue with homebrew looking to the system gems when the system gems aren't in the $PATH.
Here is my gem env to show that my gems are installed in my .rvm/gems directory:
    RubyGems Environment:
  - RUBYGEMS VERSION: 2.4.5
  - RUBY VERSION: 2.2.2 (2015-04-13 patchlevel 95) [x86_64-darwin14]
  - INSTALLATION DIRECTORY: /Users/scott/.rvm/gems/ruby-2.2.2
  - RUBY EXECUTABLE: /usr/local/opt/ruby/bin/ruby
  - EXECUTABLE DIRECTORY: /Users/scott/.rvm/gems/ruby-2.2.2/bin
  - SPEC CACHE DIRECTORY: /Users/scott/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: /usr/local/Cellar/ruby/2.2.2/etc
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-darwin-14
  - GEM PATHS:
     - /Users/scott/.rvm/gems/ruby-2.2.2
     - /Users/scott/.rvm/gems/ruby-2.2.2@global
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
     - :sources => ["http://gems.rubyforge.org/", "http://gems.github.com"]
     - :benchmark => false
     - "gem" => "--no-ri --no-rdoc"
  - REMOTE SOURCES:
     - http://gems.rubyforge.org/
     - http://gems.github.com
  - SHELL PATH:
     - /Users/scott/.rvm/gems/ruby-2.2.2/bin
     - /Users/scott/.rvm/gems/ruby-2.2.2@global/bin
     - /Users/scott/.rvm/rubies/ruby-2.2.2/bin
     - /usr/local/bin
     - /usr/bin
     - /bin
     - /usr/sbin
     - /sbin
     - /opt/X11/bin
     - /Users/scott/.rvm/bin
     - /Users/scott/.composer/vendor/bin
     - /usr/local/sbin

Now here is the error message I keep getting on various commands (this in particular was from brew services start httpd22):
Error: ERROR: Failed to build gem native extension.

    /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby extconf.rb
Extracting libxml2-2.8.0.tar.gz into tmp/x86_64-apple-darwin14.3.0/ports/libxml2/2.8.0... OK
Running 'compile' for libxml2 2.8.0... ERROR, review 'tmp/x86_64-apple-darwin14.3.0/ports/libxml2/2.8.0/compile.log' to see what happened.
/Library/Ruby/Gems/2.0.0/gems/mini_portile-0.5.2/lib/mini_portile.rb:265:in `block in execute': Failed to complete compile task (RuntimeError)
    from /Library/Ruby/Gems/2.0.0/gems/mini_portile-0.5.2/lib/mini_portile.rb:257:in `chdir'
    from /Library/Ruby/Gems/2.0.0/gems/mini_portile-0.5.2/lib/mini_portile.rb:257:in `execute'
    from /Library/Ruby/Gems/2.0.0/gems/mini_portile-0.5.2/lib/mini_portile.rb:69:in `compile'
    from /Library/Ruby/Gems/2.0.0/gems/mini_portile-0.5.2/lib/mini_portile.rb:109:in `cook'
    from extconf.rb:101:in `block in <main>'
    from extconf.rb:119:in `call'
    from extconf.rb:119:in `block in <main>'
    from extconf.rb:109:in `tap'
    from extconf.rb:109:in `<main>'

extconf failed, exit code 1

Gem files will remain installed in /Library/Ruby/Gems/2.0.0/gems/nokogiri-1.6.1 for inspection.
Results logged to /Library/Ruby/Gems/2.0.0/extensions/universal-darwin-14/2.0.0/nokogiri-1.6.1/gem_make.out

See how it's looking to the system version of Ruby & Gems? I have XCode installed and up to date.
brew doctor yields no results and brew update is ready to brew.
I'm using OS 10.10.3. Anything I've left out, just ask.
EDIT
Here is my .zshrc $PATH export:
export PATH="$PATH:$HOME/.composer/vendor/bin"
export PATH="$PATH:/usr/local/sbin"
export PATH="$PATH:$HOME/.rvm/bin"

EDIT 2
$GEM_HOME
/Users/scott/.rvm/gems/ruby-2.2.2

$GEM_PATH
/Users/scott/.rvm/gems/ruby-2.2.2:/Users/scott/.rvm/gems/ruby-2.2.2@global

Thoughts?

A: looking at brew:
https://github.com/Homebrew/homebrew/blob/master/bin/brew
https://github.com/Homebrew/homebrew/blob/master/bin/brew#L22
so brew is upsetting the GEM_PATH and doing its own thing.

A: Found the answer, the system rubygems.rb was referencing the wrong version of Ruby. More details here: https://github.com/Homebrew/homebrew/issues/31220


text:
Q: count characters in a word in text file python and write those characters into a csv file i have a text file test.txt with words as apple,ant,dog,cat,son etc. I want python to calculate the total number of characters for all words in text file
Eg:
Word Letters
Ant   3
Apple 5
Dog   3
Cat   3
Son   3

This is what I have tried:
string = open('file.txt').read()

for word in string.split():
    print len(word)

A: If you have on word per line you can use this :
def main():
string = open('Newfile.txt').read()
for word in string.split():
    print ("{} {}".format(word, len(word)))
main()

Try it here

A: To add to Reda Maachi's answer, if you have the same word occurring multiple times in the text document, you can convert the split string to a set. Iv also included a line that converts all words to lowercase in the event that you have mixed cases.
string = string.split()
string = [x.lower() for x in string]
string = set(string)

A: You can use Collections
from collections import Counter
file=open('file.txt','r')
words = Counter(file.read().split())
for item in words.items():
    print("{}\t{}".format(*item))


text:
Q: How to position text under image column? How do I make it so that where the text is, it is just white space and the text instead goes under the picture? Heres an image of what the code is doing on the site: https://i.stack.imgur.com/PAwLN.jpg
Heres my current CSS for the image grid setup: `
.column{ float: left; width: 33.3%; padding:5px;} .column img{height: 370px; width:300px}

A: you can make your code like this,

.img-container{
  display: flex;
  justify-content: space-evenly;
}

.img-card img{
  border: solid black 1px;
  margin: 10px;
  width: 200px;
}

.img-card p{
  text-align: center;
  margin-top: -10px;
}

Message

Message

Message

A: I'm trying to understand what you mean, but if it's about layouts you better learn about css grid
https://www.w3schools.com/css/css_grid.asp
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout

.container{
  display: grid;
  grid-template-columns: auto auto auto;
}

.image > img{
  width: 200px;
  height: 150px;
}

Lorem ipsum dolor sit amet consectetur adipisicing elit. Earum molestiae quasi incidunt esse quisquam reiciendis error cum ea quos doloremque.


text:
Q: How to navigate from Mainviewcontroller to another view controller using SlideMenuViewcontroller I'm trying to navigate from MainViewController to other ViewController when clicked on the rightHeaderButtonClicked method. But, it doesn't navigate. I have shared the code below.
Appdelegate.swift
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    fileprivate func createMenuView() {
        // create viewController code...
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let mainViewController = storyboard.instantiateViewController(withIdentifier: "MainViewController") as! MainViewController
        let menuViewController = storyboard.instantiateViewController(withIdentifier: "MenuViewController") as! MenuViewController
        let nvc: UINavigationController = UINavigationController(rootViewController: mainViewController)
        menuViewController.mainViewController = nvc

        let slideMenuController = ExSlideMenuController(mainViewController:mainViewController, leftMenuViewController: menuViewController)
        slideMenuController.automaticallyAdjustsScrollViewInsets = true
        slideMenuController.delegate = mainViewController
        slideMenuController.removeRightGestures()

        self.window?.backgroundColor = UIColor(red: 236.0, green: 238.0, blue: 241.0, alpha: 1.0)
        self.window?.rootViewController = slideMenuController
        self.window?.makeKeyAndVisible()
    }

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        createMenuView()
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
}

MainViewController.swift
class MainViewController: UIViewController,SlideMenuControllerDelegate {

    @IBOutlet weak var chitsTableView: UITableView!

    var mainVc: UIViewController!

    override func viewDidLoad() {
        super.viewDidLoad()

        chitsTableView.register(UINib(nibName: "ChitTableViewCell", bundle: nil), forCellReuseIdentifier: "ChitTableViewCell")
    }

    override func viewWillAppear(_ animated: Bool) {
        self.slideMenuController()?.changeMainViewController(self.allbiddersViewController, close: true)
        self.navigationController?.isNavigationBarHidden = true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func viewDidAppear(_ animated: Bool) {
        self.slideMenuController()?.addLeftGestures()
    }

    @IBAction func leftHeaderButtonClicked(_ sender: UIBarButtonItem) {
        self.slideMenuController()?.openLeft()
    }

    @IBAction func rightHeaderButtonClicked(_ sender: UIBarButtonItem) {
        let chitdetailVc = self.storyboard?.instantiateViewController(withIdentifier: "ChitDetailViewController") as! ChitDetailViewController
        self.slideMenuController()?.navigationController?.pushViewController(chitdetailVc, animated: true)
    }
}

I am unable to understand the hierarchy of SlideMenuViewController and the viewcontroller stack prints nil always.

A: I assume that you are using https://github.com/dekatotoro/SlideMenuControllerSwift.
However, I don't think that's your issue here.
I think the problem is with your setup of the UINavigationController.
Instead of setting the mainViewContoller as a property of the ExSlideViewController, you should use the navigation controller that contains it:
let slideMenuController = ExSlideMenuController(mainViewController: nvc, leftMenuViewController: menuViewController)

Then, you can push directly in the MainViewController, instead of having to call the parent slideMenuController:
@IBAction func rightHeaderButtonClicked(_ sender: UIBarButtonItem) {
    let chitdetailVc = self.storyboard?.instantiateViewController(withIdentifier: "ChitDetailViewController") as! ChitDetailViewController
    self.navigationController?.pushViewController(chitdetailVc, animated: true)
 }


text:
Q: How to know a downloaded database file is secure? maybe it's two questions but maybe someone has already faced with my issue exactly, and just knows ONE precise answer during this conversion target described below. I have downloaded an empty .mdb access file from this site, which apparently must be blank to do my .sql to .mdb conversion using sql server import&export wizard; I found no threat using HitmanPro from the downloaded .mdb file, but it is 3.5Mg !! and it's still suspicious for me how a blank database file could be 3mg?! (I tried to use copy a trusted .mdb file existing in my laptop, I deleted the tables inside in order to make it blank but apparently there must be other configurations to make it a convertible .mdb file into .sql or vice versa; I faced with these errors during the export of SQL Server:

Error 0xc02020a1 , Error 0xc020902a, Error 0xc0202092, Error 0xc0047038

Although I can insist and follows those errors in this forum and stackoverflow, but I just want faster way, because that website mentioned above demonstrates conversion using SQL Server export wizard, and has put that .mdb file as a requirement in this discription

A: You have a basic misunderstanding of what a blank database file is. In our parlance, that just means that there's no user data in the file. It doesn't mean that the file is zero bytes in size.
If you create a new empty database using Microsoft Access today, you'll find that it is a certain size, even though there's nothing in it. No tables, queries, etc.
However, under the covers, the file itself contains information to make it understood by Microsoft Access. This is called the file format. No file formats for complex applications start off at zero bytes. You'll find exactly the same case with a Word or Excel document.
What I suspect is that your downloaded file contains empty database structures. This is the same as a "blank" Excel file containing, say, ten worksheets that are formatted with headers, but no data. It will also be a suspicious size if you're unfamiliar with the file format.
Don't delete what's in the file you downloaded. See if it works.
I hope that helps your understanding better.


text:
Q: Multiple commands with Maven Exec plugin I am struggeling a bit with the Maven Exec plugin. I want to execute two seperate mvn commands using the plugin so I only need to execute mvn exec:exec in order to execute all commands.
The following two commands work well seperately:
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.6.0</version>
    <configuration>
        <executable>mvn</executable>
        <arguments>
            <argument>clean</argument>
        </arguments>
    </configuration>
</plugin>

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.6.0</version>
    <configuration>
        <executable>mvn</executable>
        <arguments>
            <argument>package</argument>
        </arguments>
    </configuration>
</plugin>

And this is my attempt to combine both in order to execute them with one command:
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.6.0</version>

    <executions>
        <execution>
            <id>id1</id>
            <phase>package</phase>
            <goals>
                <goal>exec</goal>
            </goals>
            <configuration>
                <executable>mvn</executable>
                <arguments>
                    <argument>clean</argument>
                </arguments>
            </configuration>
        </execution>

        <execution>
            <id>id2</id>
            <phase>package</phase>
            <goals>
                <goal>exec</goal>
            </goals>
            <configuration>
                <executable>mvn</executable>
                <arguments>
                    <argument>package</argument>
                </arguments>
            </configuration>
        </execution>
    </executions>

</plugin>

Unfortunately, when I now execute mvn exec:exec I receive the following error message:
[INFO] Scanning for projects...
[INFO]
[INFO] Using the builder org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder with a thread count of 1
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building MyProjet 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- exec-maven-plugin:1.6.0:exec (default-cli) @ MyProject ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.787 s
[INFO] Finished at: 2017-09-26T09:56:57+01:00
[INFO] Final Memory: 6M/15M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.6.0:exec (default-cli) on project MyProject: The parameter 'executable' is missing or invalid -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

A: When you run mvn exec:exec on the command-line, it runs an <execution> with an <id> of default-cli. This explains the error message, as there is no execution with <id>default-cli</id> that has an <executable> configured in your POM.
To solve your problem, have a look at the Guide to Configuring Plug-ins. It explains how to execute a goal from the command-line with an <id> other than default-cli:
mvn exec:exec@id1 exec:exec@id2


text:
Q: If $a$, $b$, $c$ are the roots of $x^3-6x^2+3x+1=0$, find all possible values of $a^2b+b^2c+c^2a$
Let $a$, $b$, $c$ be the roots of
$$x^3 - 6x^2 + 3x + 1 = 0$$ Find all possible values of $a^2 b + b^2 c + c^2 a$. Express all the possible values, in commas.

I've already tried to bash out all the roots, Vieta's Formula, and try to manipulate the equation to become easier to work with. However, Vieta's didn't get me anywhere, and I couldn't find a way to make the equation simpler or anything. Any hints to start this problem?

A: Hint : Let $A=a^2 b + b^2 c + c^2 a$ and $B=a^2 c + b^2 a + c^2 b$. Now calculate $A+B$ and $AB$.

 Now consider the quadratic whose roots are $A$ and $B$.

A: Let $p = a + b + c$, $q = ab + bc + ca$ and $r = abc$.
As pointed out by @Donald Splutterwit, we may let $A = a^2b + b^2c + c^2a$ and $B = ab^2 + bc^2 + ca^2$,
then $A + B$ and $AB$ are both symmetric which can both be expressed in terms of polynomials of $p, q, r$.
Indeed, we have
\begin{align}
A + B &= a^2b + b^2c + c^2a + ab^2 + bc^2 + ca^2\\
&= a^2(b+c) + b^2(c+a) + c^2(a+b)\\
&= (a^2+b^2+c^2)(a+b+c) - (a^3 + b^3 + c^3)\\
&= (p^2 - 2q)p - [3r + p(p^2 - 2q - q)]\\
&= pq - 3r
\end{align}
where we have used the known identity
$$a^3 + b^3 + c^3 - 3abc = (a+b+c)(a^2+b^2+c^2 - ab - bc - ca).$$
Also, we have
\begin{align}
AB &= (a^3+b^3+c^3)abc + (a^3b^3 + b^3c^3 + c^3a^3) + 3(abc)^2\\
&= [3r + p(p^2 - 2q - q)]r + [q^3 - 6r^2 - 3r(pq - 3r)] + 3r^2\\
&= p^3r-6pqr+q^3+9r^2
\end{align}
where we have used
\begin{align}
(ab+bc+ca)^3 &= a^3b^3 + b^3c^3 + c^3a^3 + 6(abc)^2\\
&\quad + 3abc(a^2b + b^2c + c^2a + ab^2 + bc^2 + ca^2).
\end{align}
Now, by Vieta's formula, we have $p = 6, q = 3, r = -1$.
Thus, $A + B = 21$ and $AB = -72$ which results in $A = 24, B = -3$ or $A = -3, B = 24$.
Thus, all the possible values of $A$ are $24, -3$.


text:
Q: Reducing run time with pandas accessors I have the following call:
def compute_using_AA(self):

    k=0

    while k<self.nobs:
        L = 0
        self.BB.ix[k]=0.0
        while L<self.nobs:
            self.BB.ix[k] = self.BB.ix[k]+self.AA[k,L]*self.detrend.ix[L]
            L+=1
        k+=1

And in profiling I see:
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
8    1.510    0.189   59.611    7.451   Data.py:47(compute_using_AA)

Where:
type(AA)=<type 'numpy.ndarray'>
type(BB) =<class 'pandas.core.series.Series'>

and
type(detrend)=<class 'pandas.core.series.Series'>
Are there any low hanging fruit recommendations that may help me to speed things up?

A: The most obvious thing I see is that you should use numpy array operations. The computation going on inside the inner loop does not depend on the values of BB, it is just an accumulator. So you can perform point-by-point multiplication on AA an detrend, sum everything, and store in BB. It actually looks like you're just performing a linear product of two vectors, where the second is always the same, and the first is stored in a matrix. This could be performed with:
def compute_using_AA(self):
    self.BB.ix = np.dot(self.AA, self.detrend.ix)

This will result in an array with the same size as BB.ix with its elements being the sum of the products of each row in AA by detrend.


text:
Q: Apollo writing to cache fails Im writing tests with vitest using react-testing-library to a React component using Apollo Mock Provider.
I have a mutation in my code, which I'm mocking (works just fine).
The mutation has an update function(that fails).
The update function reads data from the cache, deep clones it, changes a specific field and writes it back to the cache.
Im doing the read/write to cache since my mutation should trigger a refetchQueries request that takes long time, I'm trying to avoid it by updating the cache manually, since the response contains enough data and I would like to display the user the update instantly and not wait for the refetchQueries .
Im trying to debug my code, I'm getting the following error:
TypeError: Cannot read properties of undefined (reading 'toString')

I narrowed my problem right after the writeCache function, after it is executed I get the error.
update(cache, { data: payTotalOutstandingResult }) {
      const isPendingPayment = !!payTotalOutstandingResult?.payTotalOutstanding
        ?.pending;
      if (!isPendingPayment) {
        const getCurrentData = cache.readQuery<GetPaymentAccountQuery>({
          query: GetPaymentAccountDocument,
        });

        const clonedCache = _.cloneDeep(getCurrentData);
        if (clonedCache?.getCurrent?.paymentAccount?.totalOutstanding) {
          clonedCache.getCurrent.paymentAccount.totalOutstanding = 0;
          console.log('cloned1', clonedCache);

          cache.writeQuery<GetPaymentAccountQuery>({
            query: GetPaymentAccountDocument,
            data: clonedCache,
          });
          console.log('cloned2', clonedCache);
        }
      }
    },`

cloned1 prints just fine, cloned2 fails with the mentioned error.
What am I doing wrong?


text:
Q: dynamically set the propeties in c# i have the following code in c#
class1
{
 public string Body
        {
 set
            {
                byte[] bytesToEncode = Encoding.UTF8.GetBytes(value);
                string encodedText = Convert.ToBase64String(bytesToEncode);
                this._body = HttpUtility.UrlEncode(encodedText);
            }
        }
}

now inside some another class i have to provide the string values to Body like
class my class
{
class1 c = null;
c.body = ???
}

Please help me out how to give the values dynamically to Body . I don't want to hard code the string literal.
regards
priya

A: Are you perhaps trying to initialize an instance of class1, like this?
class myClass
{
    private class1 c = new class1 { Body = "foo" };
}

Or, maybe you want to create it in the myClass constructor:
public class myClass
{
    private class1 c;

    public myClass(string body)
    {
        c = new class1 { Body = body };
    }
}

And then you create an instance of myClass by calling:
myClass mine = new myClass("foo");

If that's not what you're trying to do, then you need to provide a better second example, and some description.


text:
Q: Caffe: Check failed: Network should have exactly one output I'm using the Caffe android lib (based on the C++ api). I'm trying it with a GoogleNet model.
Unfortunatly it's giving me this error:

Check failed: net_->num_outputs() == 1 Network should have exactly one output

I'm having the feeling I'm missing something stupid. Any thoughts?

A: What implementation of GoogLeNet are you using?
Depending on the implementation, you might indeed get more than a single output.
The original GoogLeNet (published in CVPR 2015) had three "output" losses for training, so you might be using a similat prototxt resulting with several output layers.
Considering this deploy.prototxt - it has only one output "prob". However, the corresponding train_val.prototxt has three outputs: "loss1/loss1", "loss2/loss1" and "loss3/loss3".


text:
Q: Confusion about SSD, HDD, SATA and motherboards From example lets take this computer where in the spec it says

Hard Disk Drive Specifications:
  SATA 3.0Gb/s

When looking at harddrives under RPM 7200 they say either 6.0Gb/s or nothing at all.
Only when I go down to 5400/5900 does it say 3.0Gb/s. Does this mean my computer wont benefit from a fast harddrive? Does this mean SSD would be useless except for fast seek times?

A: Not sure I understand what you are asking.
As a general rule a faster hard drive with more throughput is better. You will get information quicker and things will load faster.
HDDs - reliable (within reason), good speed, cheap, plenty of space, but contain moving parts and consume more power.
SSDs - newer tech, more expensive, less capacity available, faster (generally speaking), lower power usage.
So it comes down to 3 things, how much storage do you need? how fast do you need it to be? and how much money are you willing to throw at it?

A: Unfortunately you will find that specification sheets are often mangled, usually in an attempt to simplify the specs to your average person.
However in this case, on the link you provide, the full line what you are refering to is actually this:
Interface   SATA 3.0Gb/s

So that means the interface is rated to support a speed up to 3.0Gbits/sec - this would be a SATA-II interface.
No spinning hard drive will approach 3.0Gbits/sec except when it is transferring data from its buffer - buffers on hard drives are pretty small compared to the storage on the drive so it's usually not something that would be a dealbreaker.  The speed benefit between 3.0Gbits/sec and 6.0Gbits/sec (SATA-III) is minimal for spinning hard drive.
Some solid state drives will break the 3.0Gbits/sec barrier and those can benefit.
An SSD that can transfer at 6.0Gbits/sec rate will still be much faster than a spinning drive on a 3.0Gbits/sec interface.
You have to read the specifications on the hard drive and see what its maximum transfer rate (for both read and write) is to determine whether it can take advantage of 3.0Gbit/sec or higher.

A: Let define few things:
RPM:  rotation per minute, higher is better. So 7200 is better than 5400. But the rotation speed doesn't indicate the transfer speed. The seek time is affect by the rpm
Sata 6.0Gb/s or 3.0Gb/s:   6.0Gb/s is in theory better, but hard drive can't reach those speed yet, so for now 3.0 or 6.0 are kind of equals
A HDD can offer a speed of about maximun 450Mb/s (depend on HDD and the tests, etc), but HDD have a latency while moving the head. SDD don't have a moving part, so it's can be quicker (fast seek time).
SDD are usually better than HDD, HDD are cheaper than SDD.  You can forget the 3.0Gb/s or 6.0Gb/s for now except if you buy a high-end computer with SDD / RAID. But if it's the same price, and you will keep your computer for a long time, go with the 6.0Gb/s


text:
Q: Numpy: Select row multiple times using different indices array Suppose I have the following array.
l = np.asarray([1,3,5,7])

Out[552]: array([1, 3, 5, 7])

I can select the row twice using a index array np.asarray([[0,1],[1,2]]):
l[np.asarray([[0,1],[1,2]])]
Out[553]:
array([[1, 3],
       [3, 5]])

It doesn't work if the index array have different length on each row:
l[np.asarray([[1,3],[1,2,3]])]

Traceback (most recent call last):

  File "<ipython-input-555-3ec2ab141cd4>", line 1, in <module>
    l[np.asarray([[1,3],[1,2,3]])]
IndexError: arrays used as indices must be of integer (or boolean) type

My desired output for this example would be:
array([[3, 7],
       [3, 5, 7]])

Can someone please help?

A: I think this is the closest I can get.
import numpy as np
l = np.asarray([1, 3, 5, 7])
idx = [[1,3],[1,2,3]]
output = np.array([np.array(l[i]) for i in idx])
print output

Result:
[array([3, 7]) array([3, 5, 7])]

A: You can get the result you are after if you build the lists seperately.
Code:
l = np.asarray([1, 3, 5, 7])

# Build a sample array
print(np.array([[3, 7], [3, 5, 7]]))

# do the lookups into the original array
print(np.array([list(l[[1, 3]]), list(l[[1, 2, 3]])]))

Results:
[[3, 7] [3, 5, 7]]
[[3, 7] [3, 5, 7]]


text:
Q: Select only specific fields in Magento I'm trying to use the MAX function of MySQL to retrieve the latest dates from my table.
$_updates = Mage::getModel('ticket/updates')->getCollection();
$_updates->getSelect()->columns('MAX(created) as max_created')->group(array('status_id'));

This is the resulting query:
SELECT `main_table`.*, MAX(created) AS `max_created` FROM `em_ticket_updates` AS `main_table` GROUP BY `status_id`

The problem with this is that if all the fields are included (main_table.*)  it does not function correctly.
Is there a way to remove main_table.* from the query and only use specific fields?
Thanks.

A: Magento provide addFieldToSelect() fumctionality. Use below code to get specific field.
$Collection = Mage::getModel('showdown/votes')->getCollection();
$Collection->addFieldToSelect('id');

A: I recognise this is an old post but I thought I'd post an alternative solution.
I had a similar problem myself, I eventually searched through the source until I reached Zend_Db_Select After consulting the Zend Documentation (Example 8).
$select = $db->select()
    ->from(array('p' => 'products'),
           array('product_id', 'product_name'));

A: A Zend trick can be used here.
$_updates->getSelect()
    ->reset(Zend_Db_Select::COLUMNS)
    ->columns('MAX(created) as max_created')
    ->group(array('status_id'));

NOTE:
For EAV collection you must re-add the entity_id or you will have an error when the collection is loaded.
    $collection = Mage::getModel('catalog/product')
        ->getCollection();
    $collection->getSelect()
        ->reset(Zend_Db_Select::COLUMNS)
        ->columns(array('entity_id'));

    $collection
        ->addAttributeToSelect(array('image','small_image','thumbnail'))
        ->addFieldToFilter('entity_id', array('in' => $simple_ids));

A: Just need to use "getColumnValues"
$_updates = Mage::getModel('ticket/updates')->getCollection();
$columnValues = $_updates->getColumnValues('Your Column Name');


text:
Q: Trying to perform ajax request in Cakephp but will redirect to the link specified in the form I am trying to perform ajax request when a link is click passing id value. And try to alert the data if successful. Please tell me what is wrong.
    $('a.view-btn').on('click', function(e){
            var view = $(this);
            var id = view.data('id');
        $.ajax({
            url: '/bootstrap_exercise/contacts/view/',
            type: 'POST',
            data: {product_id: id},
            success: function(data) {
                alert(data);
                $('div#view-contact').load('/bootstrap_exercise/contacts/view .view-contact');
            }
        });
        console.log(id);
    });

this is my edit method in controller
public function view($id) {
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->set('contact', $this->request->data('product_id'));
            echo "AJAX SUCCESS";
        } else {
            $this->set('contact', $this->Contact->findById($id));
        }
    }

A: Do return false at the end of the statement.
$('form#add_form').on('submit', function(e){
        var thisForm = $(this);
        $.ajax({
            url: thisForm.attr('action'),
            type: 'POST',
            data: thisForm.serialize(count),
            success: function() {
                console.log(count);
            }
        });
        e.preventDefault();
        return false;
    });

A: //use preventDefault()
$('form#add_form').on('submit', function(e){
            e.preventDefault();
            var thisForm = $(this);
            $.ajax({
                url: thisForm.attr('action'),
                type: 'POST',
                data: thisForm.serialize(count),
                success: function() {
                    console.log(count);
                }
            });
            e.preventDefault();
        });


text:
Q: MediaCodec: Convert image to video I want to be able to write a bitmap to a video using MediaCodec. I want the video to be e.g. 3 seconds long and 30 fps. I am targeting Android API 21.
I have a class that does the drawing:
public class ImageRenderer {
    private static final String NO_FILTER_VERTEX_SHADER = "" +
            "attribute vec4 position;\n" +
            "attribute vec4 inputTextureCoordinate;\n" +
            " \n" +
            "varying vec2 textureCoordinate;\n" +
            " \n" +
            "void main()\n" +
            "{\n" +
            "    gl_Position = position;\n" +
            "    textureCoordinate = inputTextureCoordinate.xy;\n" +
            "}";
    private static final String NO_FILTER_FRAGMENT_SHADER = "" +
            "varying highp vec2 textureCoordinate;\n" +
            " \n" +
            "uniform sampler2D inputImageTexture;\n" +
            " \n" +
            "void main()\n" +
            "{\n" +
            "     gl_FragColor = texture2D(inputImageTexture, textureCoordinate);\n" +
            "}";

    private int mGLProgId;
    private int mGLAttribPosition;
    private int mGLUniformTexture;
    private int mGLAttribTextureCoordinate;

    private static final int NO_IMAGE = -1;
    private static final float CUBE[] = {
            -1.0f, -1.0f,
            1.0f, -1.0f,
            -1.0f, 1.0f,
            1.0f, 1.0f,
    };

    private int mGLTextureId = NO_IMAGE;
    private final FloatBuffer mGLCubeBuffer;
    private final FloatBuffer mGLTextureBuffer;

    private Bitmap bitmap;

    private static final float TEXTURE_NO_ROTATION[] = {
            0.0f, 1.0f,
            1.0f, 1.0f,
            0.0f, 0.0f,
            1.0f, 0.0f,
    };

    public ImageRenderer(Bitmap bitmap) {
        this.bitmap = bitmap;

        mGLCubeBuffer = ByteBuffer.allocateDirect(CUBE.length * 4)
                .order(ByteOrder.nativeOrder())
                .asFloatBuffer();
        mGLCubeBuffer.put(CUBE).position(0);

        mGLTextureBuffer = ByteBuffer.allocateDirect(TEXTURE_NO_ROTATION.length * 4)
                .order(ByteOrder.nativeOrder())
                .asFloatBuffer();
        mGLTextureBuffer.put(TEXTURE_NO_ROTATION).position(0);

        GLES20.glClearColor(0, 0, 0, 1);
        GLES20.glDisable(GLES20.GL_DEPTH_TEST);

        mGLProgId = OpenGlUtils.loadProgram(NO_FILTER_VERTEX_SHADER, NO_FILTER_FRAGMENT_SHADER);
        mGLAttribPosition = GLES20.glGetAttribLocation(mGLProgId, "position");
        mGLUniformTexture = GLES20.glGetUniformLocation(mGLProgId, "inputImageTexture");
        mGLAttribTextureCoordinate = GLES20.glGetAttribLocation(mGLProgId,
                "inputTextureCoordinate");

        GLES20.glViewport(0, 0, bitmap.getWidth(), bitmap.getHeight());
        GLES20.glUseProgram(mGLProgId);
    }

    public void drawFrame() {
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);

        // Draw bitmap
        mGLTextureId = OpenGlUtils.loadTexture(bitmap, mGLTextureId, false);

        GLES20.glUseProgram(mGLProgId);

        mGLCubeBuffer.position(0);
        GLES20.glVertexAttribPointer(mGLAttribPosition, 2, GLES20.GL_FLOAT, false, 0, mGLCubeBuffer);
        GLES20.glEnableVertexAttribArray(mGLAttribPosition);
        mGLTextureBuffer.position(0);
        GLES20.glVertexAttribPointer(mGLAttribTextureCoordinate, 2, GLES20.GL_FLOAT, false, 0,
                mGLTextureBuffer);
        GLES20.glEnableVertexAttribArray(mGLAttribTextureCoordinate);
        if (mGLTextureId != OpenGlUtils.NO_TEXTURE) {
            GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
            GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mGLTextureId);
            GLES20.glUniform1i(mGLUniformTexture, 0);
        }
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
        GLES20.glDisableVertexAttribArray(mGLAttribPosition);
        GLES20.glDisableVertexAttribArray(mGLAttribTextureCoordinate);
        GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
    }
}

I also have an InputSurface hooked up to my video encoder and muxer.
At the start of the processing, and then every time I successfully mux a frame thereafter, I call:
inputSurface.makeCurrent();
imageRenderer.drawFrame();
inputSurface.setPresentationTime(presentationTimeNs);
inputSurface.swapBuffers();
inputSurface.releaseEGLContext();

where inputSurface and imageRenderer are instances of the above classes, and presentationTimeNs I calculate based on the required frame rate.
This generally does work, but feels pretty inefficient. I feel like I am unnecessarily redrawing the bitmap over and over, even though I know it hasn't changed. I tried calling drawFrame() just once or twice at the beginning, but then the outputted video flickers to black on all my Samsung test devices.
Is there a more efficient way I can draw the same bitmap over and over to my encoder input surface?

A: Efficiency wise, this drawing of the input frame probably is as efficient as it will get. Each time you submit a frame to the encoder, you can't really assume anything about the input surface buffer content (I think), so you need to copy the content to be encoded into it somehow, and this does pretty much it.
If you skip drawing, you need to keep in mind that the surface you're drawing into isn't just a single buffer, but a set of a number of buffers (usually 4-10 buffers or so). When using the direct buffer access mode of the encoder, the encoder will tell you exactly which one of the buffers out of the pool it gave you to fill, and in such cases, you might have better luck with skipping drawing in the case if you've already filled the buffer before (and hoping that the encoder hasn't invalidated the contents).
With surface input, you don't get to know which buffer you got to write into. In that case, you could e.g. try just doing the drawing the first N times. I don't think you can get the actual number of buffers though - you could try calling the deprecated getInputBuffers() method, but I don't think it's possible to use it in combination with surface input.
However, about performance, the absolutely biggest issue and reason for your (lack of) performance is that you're doing everything synchronously. You said

At the start of the processing, and then every time I successfully mux a frame thereafter, I call

Hardware encoders generally have a bit of latency, and the time it takes to encode a single frame from start to finish is longer than the average time per frame, if you start encoding more than one at a time.
Assuming you're using MediaCodec in async mode, I would suggest to just serially do the encoding of all the 90 frames in one thread, and write output packets to the muxer when you get them in the callback. That should keep the encoder pipeline busy. (Once the input buffers to the encoder are exhausted, the inputSurface methods will block until the encoder has completed a frame and freed up another one of the input buffers.) You might also want to buffer the output packets in a queue and write them asynchronously to the muxer (I remember reading about cases where MediaMuxer occasionally can block longer than you'd like).


text:
Q: InvalidArgumentError after step 6 during my training on TPU at Kaggle I am getting an error when I train my model with TPU on kaggle. I already looked around the internet but can get any solution. Note that it is working if I use GPU but I run OOM error.
Here is the parameter:
batch_size = 8 * strategy.num_replicas_in_sync
tensorflow v 2.4.1
TPU v3-8

Here is my code
try: # detect TPUs
    tpu = tf.distribute.cluster_resolver.TPUClusterResolver.connect() # TPU detection
    strategy = tf.distribute.TPUStrategy(tpu)
except ValueError: # detect GPUs
    strategy = tf.distribute.MirroredStrategy() # for GPU or multi-GPU machinesof multi-GPU machines

image_shape =(224, 224,3)
batch_size = 8 * strategy.num_replicas_in_sync
N_epoch = 200 # number of epoches

# I created the model using the strategy
with strategy.scope():
    model = ... # I create the model here

def train_step(in_one, in_two):
    loss_ = model.train_on_batch([in_one,], [in_two,])
    return loss_

for epoch in range(N_epoch):
    for step, (in_one, in_two) in enumerate(zip(data_one, data_two)):
        loss_ = train_step(in_one, in_two)
        if step % 1 == 0:
            print("epoch> %d | step> %d | loss>%.2f" % (epoch+1,step, loss_))

The training process is working fine till it's reach the step 6.
Here is the output of my training with the error
epoch> 1 | step> 0 | loss>0.09
epoch> 1 | step> 1 | loss>0.08
epoch> 1 | step> 2 | loss>0.07
epoch> 1 | step> 3 | loss>0.07
epoch> 1 | step> 4 | loss>0.07
epoch> 1 | step> 5 | loss>0.08
epoch> 1 | step> 6 | loss>0.07
2022-12-16 06:28:40.938812: W tensorflow/core/distributed_runtime/eager/remote_tensor_handle_data.cc:76] Unable to destroy remote tensor handles. If you are running a tf.function, it usually indicates some op in the graph gets an error: 9 root error(s) found.
  (0) Invalid argument: {{function_node __inference_train_function_69334}} Compilation failure: Reshape's input dynamic dimension is decomposed into multiple output dynamic dimensions, but the constraint is ambiguous and XLA can't infer the output dimension %reshape.7586 = f32[3920,16,384]{2,1,0} reshape(f32[62720,384]{1,0} %transpose.7577), metadata={op_type="Reshape" op_name="model/swin_transformer_block_1/window_attention_1/name1/attn/qkv/Tensordot"}.
    TPU compilation failed
     [[{{node tpu_compile_succeeded_assert/_358545883293887456/_5}}]]
     [[tpu_compile_succeeded_assert/_358545883293887456/_5/_63]]
  (1) Invalid argument: {{function_node __inference_train_function_69334}} Compilation failure: Reshape's input dynamic dimension is decomposed into multiple output dynamic dimensions, but the constraint is ambiguous and XLA can't infer the output dimension %reshape.7586 = f32[3920,16,384]{2,1,0} reshape(f32[62720,384]{1,0} %transpose.7577), metadata={op_type="Reshape" op_name="model/swin_transformer_block_1/window_attention_1/name1/attn/qkv/Tensordot"}.
    TPU compilation failed
     [[{{node tpu_compile_succeeded_assert/_358545883293887456/_5}}]]
     [[tpu_compile_succeeded_assert/_358545883293887456/_5/_95]]
  (2) Invalid argument: {{function_node __inference_train_function_69334}} Compilation failure: Reshape's input dynamic dimension is decomposed into multiple output dynamic dimensions, but the constraint is ambiguous and XLA can't infer the output dimension %reshape.7586 = f32[3920,16,384]{2,1,0} reshape(f32[62720,384]{1,0} %transpose.7577), metadata={op_type="Reshape" op_name="model/swin_transformer_block_1/window_attention_1/name1/attn/qkv/Tensordot"}.
    TPU compilation failed
     [[{{node tpu_compile_succeeded_assert/_358545883293887456/_5}}]]
     [[tpu_compile_succeeded_assert/_358545883293887456/_5/_111]]
  (3) Invalid argument: {{function_node __inference_train_function_69334}} Compilation failure: Reshape's input dynamic dimension is decomposed into multiple output dynamic dimensions, but the constraint is ambiguous and XLA can't infer the output dimension %reshape.7586 = f32[3920,16,384]{2,1,0} reshape(f32[62720,384]{1,0} %transpose.7577), metadata={op_type="Reshape" op_name="model/swin_transformer_block_1/window_attention_1/name1/attn/qkv/Tensordot"}.
    TPU compilation failed
     [[{{node tpu_compile_succeeded_assert/_358545883293887456/_5}}]]
     [[tpu_compile_succeeded_assert/_358545883293887456/_5/_47]]
  (4) Invalid argument: {{function_node __inference_train_function_69334}} Compilation failure: Reshape's input dynamic dimension is decomposed into multiple output dynamic dimensions, but the constraint is ambiguous and XLA can't infer the output dimension %reshape.7586 = f32[3920,16,384]{2,1,0} reshape(f32[62720,384]{1,0} %transpose.7577), metadata={op_type="Reshape" op_name="model/swin_transformer_block_1/window_attention_1/name1/attn/qkv/Tensordot"}.
    TPU compilation failed
     [[{{node tpu_compile_succeeded_assert/_358545883293887456/_5}}]]
     [[tpu_compile_succeeded_assert/_35854588329 ... [truncated]
2022-12-16 06:28:40.940134: W ./tensorflow/core/distributed_runtime/eager/destroy_tensor_handle_node.h:57] Ignoring an error encountered when deleting remote tensors handles: Invalid argument: Unable to find the relevant tensor remote_handle: Op ID: 17806, Output num: 0
Additional GRPC error information from remote target /job:worker/replica:0/task:0:
:{"created":"@1671172120.940038755","description":"Error received from peer ipv4:10.0.0.2:8470","file":"external/com_github_grpc_grpc/src/core/lib/surface/call.cc","file_line":1056,"grpc_message":"Unable to find the relevant tensor remote_handle: Op ID: 17806, Output num: 0","grpc_status":3}
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
/tmp/ipykernel_20/2809624530.py in <module>
     11     # Train the discriminator & generator on one batch of real images.
     12     for step, (low, high) in enumerate(zip(dataL_all, dataH_all)):
---> 13         loss_ = train_step(low, high)
     14         historic.append(loss_)
     15

/tmp/ipykernel_20/2809624530.py in train_step(low, high)
      1 def train_step(low, high):
----> 2     loss_ = model.train_on_batch([low,], [high,])
      3 #     tensorboard.on_epoch_end(epoch, named_logs(model, loss_))
      4     return loss_
      5

/opt/conda/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py in train_on_batch(self, x, y, sample_weight, class_weight, reset_metrics, return_dict)
   1729     if reset_metrics:
   1730       self.reset_metrics()
-> 1731     logs = tf_utils.to_numpy_or_python_type(logs)
   1732     if return_dict:
   1733       return logs

/opt/conda/lib/python3.7/site-packages/tensorflow/python/keras/utils/tf_utils.py in to_numpy_or_python_type(tensors)
    512     return t  # Don't turn ragged or sparse tensors to NumPy.
    513
--> 514   return nest.map_structure(_to_single_numpy_or_python_type, tensors)
    515
    516

/opt/conda/lib/python3.7/site-packages/tensorflow/python/util/nest.py in map_structure(func, *structure, **kwargs)
    657
    658   return pack_sequence_as(
--> 659       structure[0], [func(*x) for x in entries],
    660       expand_composites=expand_composites)
    661

/opt/conda/lib/python3.7/site-packages/tensorflow/python/util/nest.py in <listcomp>(.0)
    657
    658   return pack_sequence_as(
--> 659       structure[0], [func(*x) for x in entries],
    660       expand_composites=expand_composites)
    661

/opt/conda/lib/python3.7/site-packages/tensorflow/python/keras/utils/tf_utils.py in _to_single_numpy_or_python_type(t)
    508   def _to_single_numpy_or_python_type(t):
    509     if isinstance(t, ops.Tensor):
--> 510       x = t.numpy()
    511       return x.item() if np.ndim(x) == 0 else x
    512     return t  # Don't turn ragged or sparse tensors to NumPy.

/opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/ops.py in numpy(self)
   1069     """
   1070     # TODO(slebedev): Consider avoiding a copy for non-CPU or remote tensors.
-> 1071     maybe_arr = self._numpy()  # pylint: disable=protected-access
   1072     return maybe_arr.copy() if isinstance(maybe_arr, np.ndarray) else maybe_arr
   1073

/opt/conda/lib/python3.7/site-packages/tensorflow/python/framework/ops.py in _numpy(self)
   1037       return self._numpy_internal()
   1038     except core._NotOkStatusException as e:  # pylint: disable=protected-access
-> 1039       six.raise_from(core._status_to_exception(e.code, e.message), None)  # pylint: disable=protected-access
   1040
   1041   @property

/opt/conda/lib/python3.7/site-packages/six.py in raise_from(value, from_value)

InvalidArgumentError: 9 root error(s) found.
  (0) Invalid argument: {{function_node __inference_train_function_69334}} Compilation failure: Reshape's input dynamic dimension is decomposed into multiple output dynamic dimensions, but the constraint is ambiguous and XLA can't infer the output dimension %reshape.7586 = f32[3920,16,384]{2,1,0} reshape(f32[62720,384]{1,0} %transpose.7577), metadata={op_type="Reshape" op_name="model/swin_transformer_block_1/window_attention_1/name1/attn/qkv/Tensordot"}.
    TPU compilation failed
     [[{{node tpu_compile_succeeded_assert/_358545883293887456/_5}}]]
     [[tpu_compile_succeeded_assert/_358545883293887456/_5/_63]]
  (1) Invalid argument: {{function_node __inference_train_function_69334}} Compilation failure: Reshape's input dynamic dimension is decomposed into multiple output dynamic dimensions, but the constraint is ambiguous and XLA can't infer the output dimension %reshape.7586 = f32[3920,16,384]{2,1,0} reshape(f32[62720,384]{1,0} %transpose.7577), metadata={op_type="Reshape" op_name="model/swin_transformer_block_1/window_attention_1/name1/attn/qkv/Tensordot"}.
    TPU compilation failed
     [[{{node tpu_compile_succeeded_assert/_358545883293887456/_5}}]]
     [[tpu_compile_succeeded_assert/_358545883293887456/_5/_95]]
  (2) Invalid argument: {{function_node __inference_train_function_69334}} Compilation failure: Reshape's input dynamic dimension is decomposed into multiple output dynamic dimensions, but the constraint is ambiguous and XLA can't infer the output dimension %reshape.7586 = f32[3920,16,384]{2,1,0} reshape(f32[62720,384]{1,0} %transpose.7577), metadata={op_type="Reshape" op_name="model/swin_transformer_block_1/window_attention_1/name1/attn/qkv/Tensordot"}.
    TPU compilation failed
     [[{{node tpu_compile_succeeded_assert/_358545883293887456/_5}}]]
     [[tpu_compile_succeeded_assert/_358545883293887456/_5/_111]]
  (3) Invalid argument: {{function_node __inference_train_function_69334}} Compilation failure: Reshape's input dynamic dimension is decomposed into multiple output dynamic dimensions, but the constraint is ambiguous and XLA can't infer the output dimension %reshape.7586 = f32[3920,16,384]{2,1,0} reshape(f32[62720,384]{1,0} %transpose.7577), metadata={op_type="Reshape" op_name="model/swin_transformer_block_1/window_attention_1/name1/attn/qkv/Tensordot"}.
    TPU compilation failed
     [[{{node tpu_compile_succeeded_assert/_358545883293887456/_5}}]]
     [[tpu_compile_succeeded_assert/_358545883293887456/_5/_47]]
  (4) Invalid argument: {{function_node __inference_train_function_69334}} Compilation failure: Reshape's input dynamic dimension is decomposed into multiple output dynamic dimensions, but the constraint is ambiguous and XLA can't infer the output dimension %reshape.7586 = f32[3920,16,384]{2,1,0} reshape(f32[62720,384]{1,0} %transpose.7577), metadata={op_type="Reshape" op_name="model/swin_transformer_block_1/window_attention_1/name1/attn/qkv/Tensordot"}.
    TPU compilation failed
     [[{{node tpu_compile_succeeded_assert/_358545883293887456/_5}}]]
     [[tpu_compile_succeeded_assert/_35854588329 ... [truncated]


text:
Q: Loop through points with a step size, inclusive of end point I have a start and end point, I'd like to loop through them using a specific step size, but I need to ensure that the end point is included. Is the following the best way to accomplish this, or is there a better way?
Double start = 2.1;
Double end = 5.3;
Double step = 0.6;
for(Double i = start; i <= end; i += step) {
    // do stuff

    if(i != end && (i + step) > end) {
        i = end;
    }
}

A: You can use an instruction outside the loop , to do the end part.
Don't use double in iterations. Because of the way floating point numbers are stored, you may 2.1 +0.6 as 2.7 but as 2.69999999999999999999 for example. In this case, multiply by 10 to achieve what you want.
Your solution is wrong. You make i=end, but it is then added by step, so you dont iterate. You could use:
 if(i != end && (i + step) > end) {
        i = end-step;
    }

A: Generally you should prefer integers for your loop variables, especially when the interval divides in the whole number of steps. In case this is not possible you could use double values, but you need to be careful to avoid precision pitfalls of double computations.
Comparing doubles for equality is not a good idea. A better approach is to use Math.min to cap i at the value of end:
for(double i = start; i < end+step; i += step) {
    double pt = Math.min(end, i);
    ... // use pt here
}

A: You can calculate the number of integer steps required and use these to control the loop. When you reach the final step you use the end value.
public static void main(String[] args)
{
    Double start = 2.1;
    Double end = 5.3;
    Double step = 0.6;

    int steps = (int)Math.round((end-start)/step);
    if(start + steps*step < end) steps++;

    double pos = start;
    for(int s=0; s<=steps; )
    {
        System.out.println(pos);
        s += 1;
        pos = (s==steps) ? end : start + step*s;
    }
}

Output:
2.1
2.7
3.3
3.9
4.5
5.1
5.3

Note that for the intermediate steps we calculate the position using a multiplication rather than repeated addition. I can't find a reference at the moment but my understanding is that this incurs less floating point "drift". This seems to be borne out. If we use:
pos = (s==steps) ? end : pos+step;

to calculate the next pos then we get as output:
2.1
2.7
3.3000000000000003
3.9000000000000004
4.5
5.1
5.3


text:
Q: How to count how many types in array[Any] I am new to Swift so im just trying to solve basic problems, but can't figure out this one.
I am trying to count how many times a String, Int, Double or another class appears. And output the data. Right now i am only outputting the type. This is the code so far:
var myArr = [Any]()

myArr.append("hello")
myArr.append("goodbye")
myArr.append(1)
myArr.append(1.0)
myArr.append(Student())

for item in myArr {
    switch item {
    case let stringy as String :
        print(stringy, type(of: stringy))
    case let inty as Int :
        print(type(of: inty))
    case let doubly as Double :
        print(type(of: doubly))
    case let student as Student :
        print(type(of: student))
    default:
        print("unknown object")
    }
}

A: A simple solution is to group the array to a dictionary by the type description
var myArr = [Any]()

myArr.append("hello")
myArr.append("goodbye")
myArr.append(1)
myArr.append(1.0)
myArr.append(Student())

let typeData = Dictionary(grouping: myArr, by: {String(describing:type(of: $0))})

// -> ["Student": [__lldb_expr_9.Student()], "Double": [1.0], "Int": [1], "String": ["hello", "goodbye"]]

and print the result, the key and the number of items in value
for (key, value) in typeData {
    print("\(key): \(value.count)" )
}

A: For your question, you can make a value storeCount to store value each team it match in each switch case
But the thing is that is not the good way to do that. You can split the array into subarray which each array match a type then you can easily to deal with value later.
Using filter to filter from beginning array each value  which match with condition ( here is type given). If right type than get value.
let stringArr = myArr.filter {
    $0 as? String != nil
}
let intArr = myArr.filter {
    $0 as? Int != nil
}
let doubleArr = myArr.filter {
    $0 as? Double != nil
}
let studentArr = myArr.filter {
    $0 as? Student != nil
}

Usage
print("value string: ", stringArr, "; count: ", stringArr.count) // value string:  ["hello", "goodbye"] ; count:  2
print("value int: ", intArr, "; count: ", intArr.count) // value int:  [1] ; count:  1
print("value double: ", doubleArr, "; count: ", doubleArr.count) // value double:  [1.0] ; count:  1
print("value student: ", studentArr, "; count: ", studentArr.count) // value student:  [SelectText.Student] ; count:  1


text:
Q: Laravel Eloquent where between two dates are null I'm trying to get values between two dates. I have some data between dates but it returns empty.
$oneMonthAgo = date('Y-m-01 00:00:00', strtotime('-1 month'));
$thisMonth = date('Y-m-01 00:00:00', strtotime('0 month'));
$nextMonth = date('Y-m-01 00:00:00', strtotime('+1 month'));

$cezalar = DB::table('cezalar')
    ->where('ceza_tarih', '>=', $oneMonthAgo)
    ->where('ceza_tarih', '<', $thisMonth)
    ->get();

return $cezalar;

A: You may try something like this:
$thisMonth = \Carbon\Carbon::now()->startOfMonth();

$oneMonthAgo = \Carbon\Carbon::now()->subMonth()->startOfMonth();

$dateRange = [$oneMonthAgo, $thisMonth];

$cezalar = DB::table('cezalar')->whereBetween('ceza_tarih', $dateRange)->get();

Check Carbon, which is available out of the box, in Laravel.

A: first note : you are using "query builder" not eloquent,
and if you want to get one month ago date you should use something like this :

$oneMonthAgo = date('Y-m-d 00:00:00', strtotime('-1 month'));

I have checked it in my own app, and it is working...


text:
Q: Handle missing data in titanic dataset There is a titanic dataset. It has an 'Age' independent feature with 177 missing values. I am looking at a solution in github but can't understand one line. Can you guys explain me please.
THe line is:
data['Age'].dropna().sample(data['Age'].isnull().sum(), random_state=0)

A: First it drop the null value  with dropna
data['Age'].dropna()

then use above output , it sample the not null column with the same length of not null value
sample(data['Age'].isnull().sum(), random_state=0)


text:
Q: Filling a region between two straight lines I want to fill the region between two straight lines without displaying the region boundaries. How can it be done?

ContourPlot[{x == 2, x == 4}, {x, -2, 8}, {y, -2, 6}]

A: Use BoundaryStyle -> None as shown in the documentation of RegionPlot:
RegionPlot[2 <= x <= 4, {x, -2, 8}, {y, -2, 6}, BoundaryStyle -> None]

A: is this what you mean?
p1 = ContourPlot[{x == 2, x == 4}, {x, -2, 8}, {y, -2, 6}];
r = ImplicitRegion[2 < x < 4 && -2 < y < 6, {x, y}];
p2 = RegionPlot[r];
Show[p1, p2]

Update
In this case, just plot the region directly. No need for ContourPlot at all to be there.
r = ImplicitRegion[2 < x < 4 && -2 < y < 6, {x, y}];
RegionPlot[r, BoundaryStyle -> None,
 PlotRange -> {{-2, 8}, Automatic}]

A: c := RandomInteger[{-100, 100}];

RegionPlot[RegionIntersection[
  HalfPlane[{{2, c}, {2, c}}, {1, 0}]
  , HalfPlane[{{4, c}, {4, c}}, {-1, 0}]
  ]
 , Frame -> True
 , BoundaryStyle -> None
 , PlotRange -> { {-2, 8}, {-2, 6}}
 ]


text:
Q: lein - how to use a downloaded library Let's say I find a cool clojure library like https://github.com/clojurewerkz/buffy
Now I want to use it. And it only lives on github.
How do I do this? I would love a full start to finish hello world example.
I've read about compiling it as a jar and using that, or using :dependencies in my project.clj but so far no examples have been complete, and I'm new.
For example in python I'd git clone the repo into the root of my working tree and any file could just say import buffy

A: I just learned this five minutes ago. I wanted to use the clojure-csv library, here's what I did using Leiningen

*

*Make a new leiningen project
lein new app csvtest

*Now I have a folder called csvtest/. In the csvtest/project.clj file, edit the dependencies section to add the clojure-csv github path and a version. I'm not quite sure how the versioning works to be honest:
:dependencies [[org.clojure/clojure "1.5.1"]
               [clojure-csv/clojure-csv "2.0.1"]]

*Now run lein deps to automagically download any unresolved dependencies for your project
$ lein deps
...
Retrieving clojure-csv/clojure-csv/2.0.1/clojure-csv-2.0.1.pom from clojars
...

*Now edit csvtest/src/csvtest/core.clj. Make it look like this:
Edit: (Based on sveri's comment I changed :use closjure-csv.core to the :require line)
(ns csvtest.core
  (:gen-class)
  (:require [clojure-csv.core :refer [parse-csv]]))

(defn -main
  "I don't do a whole lot ... yet."
  [& args]
  (println (parse-csv "1,2,3,hello,world")))

You have to add the (:require [clojure-csv.core :refer [parse-csv]]) line to your ns, and in main it calls parse-csv, one of the functions provided by the library. From reading, it looks like :use is depreciated in favor of :require.
Note: For anyone coming from python (like me), it looks like doing :use clojure-csv.core is akin to from closure_csv import *, which is bad practice in python as well. And (:require [clojure-csv.core :refer [parse-csv]]) is like from clojure_csv import parse_csv

*Run the project with lein run. My output was
$ lein run
([1 2 3 hello world])

I hope that helps!

A: You can download/use it from Clojars.
Clojars link:
https://clojars.org/clojurewerkz/buffy
To use it with Leiningen, add this to your dependencies(on project.clj file):
[clojurewerkz/buffy "1.0.0-beta4"]
After that, you can run lein deps from your project root folder in order to download dependencies.
To use dependencies directly from Github repos, you can check out this: https://github.com/tobyhede/lein-git-deps

A: Using lein (which is Clojure's build tool) you have a project.clj file. if you do lein new project-name you get a new project named "project-name", with a project.clj file in it. look at that file, you will see a :dependencies entry in it as in this example:
:dependencies [[org.clojure/clojure "1.5.1"]]
all you must do to include buffy, is look at their github site, and find out which version to use, then you add it to the :dependecies list:
:dependencies [[org.clojure/clojure "1.5.1"]
                [clojurewerkz/buffy "1.0.0-beta3"]]
now you can simply do lein deps which will download the dependencies and once you written your code lein run to actually run it.
read a little about lein and check out its sample project.clj file to get a better understanding of how you should use clojure.


text:
Q: Two identical code snippets, one of them does not work. How come? I am trying to rewrite some of my code into functions instead, but a problem has occurred, that does not make any sense for me. I will now show the two code snippets:
Code 1:
def get_isPrivateAccount(page_source):
    try:
        match = re.search(r'"isPrivateAccount":(.+?)', page_source)
        if match:
            isPrivateAccount = match.group(1)

    except Exception as e:
        print('Could not find the isPrivateAccount of the user. The following exception was raised:\n', e)

    return isPrivateAccount

Code 2:
page_source = driver.page_source
match = re.search(r'"isPrivateAccount":(.+?)', page_source)

if match:
    is_private = match.group(1)
else:
    print('Match not found')

The first code gets the page_source = driver.page_source from another function that returns it, exactly the same way written.
How come the second code snippet works perfect and can find '"isPrivateAccount":false' and return 'f' without any problem as a string, but the first code snippet cannot and says that it is 'None'? Error code from first code snippet:
cannot access local variable 'isPrivateAccount' where it is not associated with a value

A: As the error traceback suggests if an exception occurs then the code execution jump to the exception block and then continue till the return were isPrivateAccount.. but it is only defined if no exception occur.
def get_isPrivateAccount(page_source):
    try:
        match = re.search(r'"isPrivateAccount":(.+?)', page_source)
        if match:
            return match.group(1)

    except Exception as e:
        print('Could not find the isPrivateAccount of the user. The following exception was raised:\n', e)

Notice that the try/except is a bit meaningless, use instead raise and/or a custom excpetion.
def get_isPrivateAccount(page_source):
    match = re.search(r'"isPrivateAccount":(.+?)', 'bjkasfdjadas')
    if match:
        return match.group(1)

    print(Exception('Could not find the isPrivateAccount of the user. The following exception was raised:'))
    #raise Excpetion(...)

A: You are declaring and initializing isPrivateAccount inside the if statement. If there is no match, the variable will never be defined and the return statement throws an error as you cannot access a variable which does not exist.
You have to define the variable at the top of your function:
isPrivateAccount = None


text:
Q: .prop("checked", false) makes checkbox true I have some <input value=name type=checkbox> whose values must be persistent. So I stored in Cookies the value of every of them, and I wrote a function which must restore the values when the page is ready.
The function which save the cookies is:
function setAllCookies() {
    var checkboxs = $("#divwheretheinputsare input");
    for (i in checkboxs)
        Cookies.set(checkboxs[i].value,checkboxs[i].checked);
}

And the function to restore them is:
function readAllCookies() {
    var checkboxs = $("#divwheretheinputsare input");
    for (i in checkboxs) {
        var nom = checkboxs[i].value;
        var value = Cookies.get(nom);
        $("##divwheretheinputsare input[value='" + nom + "']").prop("checked", value);
    //Also tried $("##divwheretheinputsare input[value='" + nom + "']")[0].checked = value;
    }
}

I can confirm the Cookies are stored with the correct name and the two functions are completly executed. With debugging, I detect this: When the line $("##divwheretheinputsare input[value='" + nom + "']").prop("checked", value) is executed, the checkbox always turn checked, no matter if value is false. If I execute that exact line in console, the checkbox change correctly...
Also, the alternative codeline, is correctly executed in the console but in the function it drops: "TypeError: $(...)[0] is undefined".

A: As charlieftl mentioned your value is coming in as a string ("true" or "false") not (true or false) and any value in the prop("checked",value) field will be taken as true.
Try:
var value = (Cookies.get(nom) == 'true');
That will set your value to a boolean rather than a string.


text:
Q: Building f2py module with numpy.distutils To build a project managed with poetry I need to build an f2py extension first. I am trying to achieve it with a separate build.py file inspired by this answer. For now my setup.py is:
# In case of numpy, build_ext is a module containing class build_ext
from numpy.distutils.core import Extension, build_ext

ext = Extension(
    'ext_name',
    sources=[<list_of_fortran_sources>],
)

def build(setup_kwargs):
    setup_kwargs.update(
        {"ext_modules": [ext], "cmdclass": {"build_ext": build_ext.build_ext}}
    )

But trying to build it I am getting an error:
>>> poetry build

A setup.py file already exists. Using it.
running build
running build_py
running build_ext
Traceback (most recent call last):
  File "/home/lap1dem/dev-python/iricore/setup.py", line 37, in <module>
    setup(**setup_kwargs)
  File "/home/lap1dem/.cache/pypoetry/virtualenvs/iricore-iDxR-q1V-py3.8/lib/python3.8/site-packages/setuptools/__init__.py", line 87, in setup
    return distutils.core.setup(**attrs)
  File "/home/lap1dem/.cache/pypoetry/virtualenvs/iricore-iDxR-q1V-py3.8/lib/python3.8/site-packages/setuptools/_distutils/core.py", line 148, in setup
    return run_commands(dist)
  File "/home/lap1dem/.cache/pypoetry/virtualenvs/iricore-iDxR-q1V-py3.8/lib/python3.8/site-packages/setuptools/_distutils/core.py", line 163, in run_commands
    dist.run_commands()
  File "/home/lap1dem/.cache/pypoetry/virtualenvs/iricore-iDxR-q1V-py3.8/lib/python3.8/site-packages/setuptools/_distutils/dist.py", line 967, in run_commands
    self.run_command(cmd)
  File "/home/lap1dem/.cache/pypoetry/virtualenvs/iricore-iDxR-q1V-py3.8/lib/python3.8/site-packages/setuptools/dist.py", line 1214, in run_command
    super().run_command(command)
  File "/home/lap1dem/.cache/pypoetry/virtualenvs/iricore-iDxR-q1V-py3.8/lib/python3.8/site-packages/setuptools/_distutils/dist.py", line 986, in run_command
    cmd_obj.run()
  File "/home/lap1dem/.cache/pypoetry/virtualenvs/iricore-iDxR-q1V-py3.8/lib/python3.8/site-packages/setuptools/_distutils/command/build.py", line 136, in run
    self.run_command(cmd_name)
  File "/home/lap1dem/.cache/pypoetry/virtualenvs/iricore-iDxR-q1V-py3.8/lib/python3.8/site-packages/setuptools/_distutils/cmd.py", line 313, in run_command
    self.distribution.run_command(command)
  File "/home/lap1dem/.cache/pypoetry/virtualenvs/iricore-iDxR-q1V-py3.8/lib/python3.8/site-packages/setuptools/dist.py", line 1214, in run_command
    super().run_command(command)
  File "/home/lap1dem/.cache/pypoetry/virtualenvs/iricore-iDxR-q1V-py3.8/lib/python3.8/site-packages/setuptools/_distutils/dist.py", line 985, in run_command
    cmd_obj.ensure_finalized()
  File "/home/lap1dem/.cache/pypoetry/virtualenvs/iricore-iDxR-q1V-py3.8/lib/python3.8/site-packages/setuptools/_distutils/cmd.py", line 107, in ensure_finalized
    self.finalize_options()
  File "/home/lap1dem/.cache/pypoetry/virtualenvs/iricore-iDxR-q1V-py3.8/lib/python3.8/site-packages/numpy/distutils/command/build_ext.py", line 86, in finalize_options
    self.set_undefined_options('build',
  File "/home/lap1dem/.cache/pypoetry/virtualenvs/iricore-iDxR-q1V-py3.8/lib/python3.8/site-packages/setuptools/_distutils/cmd.py", line 290, in set_undefined_options
    setattr(self, dst_option, getattr(src_cmd_obj, src_option))
  File "/home/lap1dem/.cache/pypoetry/virtualenvs/iricore-iDxR-q1V-py3.8/lib/python3.8/site-packages/setuptools/_distutils/cmd.py", line 103, in __getattr__
    raise AttributeError(attr)
AttributeError: warn_error

I have looked into build_ext.py source file, seems like this class is trying to set undefined options, like warn_error, cpu_baseline, cpu_dispatch, etc. in addition to built-in ditutils.command.build_ext. Those additional options should be initialized with the build_ext.initialize_options(), but build_ext.set_undefined_options() fails to find them. It is not clear to me how I can fix it. Am I even on the right track to build the f2py extension?


text:
Q: where is chat history of Skype for Business is stored in Windows 7 For Skype application, the chat logs are stored into the main.db file of skype user folder.
Now I want to backup my chat logs from Skype for business application. I am trying to find out the chat logs file like main.db but it does not exist for business application.
Where is the Skype for Business stores users chat log in Windows 7?

A: Either in the cloud or in your main.db - it depends on your own settings. If you can't see them in main.db you may need to change your settings. More here: https://support.skype.com/en/faq/FA392/where-can-i-find-my-conversation-history-in-skype-for-windows-desktop-and-what-can-i-do-with-it


text:
Q: how to programmatically determine, within the module, if javascript module was loaded via script src (not imported) Suppose I have a module:
// module.js
export default function greet() { console.info( 'hello' ); }

If the module is loaded via:
<script type=module>
import greet from './module.js';
...
</script>

then I want the calling code to be able to invoke greet() on its own, without it being called automatically (the normal scenario).
However, if the module is loaded via:
<script type=module src="./module.js"></script>

then I want the module to invoke greet() immediately (as a side-effect of being loaded).
How can I accomplish this?

A: Unfortunately, this question has a similar answer to your previous one: it isn't possible.
Modules may export things, but they aren't responsible for how (and which) do the importers use (of) them.
Modules are created to be separate and reusable, even on the same page, without re-evaluation:
The module's code evaluated once, then its exports are passed to every place that imports it.
That design is good, but essentially makes impossible for a module to determine anything about its importers.

On the other hand, the <script type="module"> syntax also wasn't designed for that: it's the way to signal the browser through HTML the main (aka. "top-level") module,  that loads its dependecies (sub-modules) on its own.

Partial solution:
Make a single top-level module, that imports everything else and operates the page by "side effects", and avoid importing other modules by script tags. Moreover, I recommend you to avoid side effects in the non-top-level modules, and focus on exports instead.
And if someone really wants to import your module from their HTML, they can still do this instead:
<script type="module">
  import greet from './module.js';
  greet();
</script>


text:
Q: Pyspark - after groupByKey and count distinct value according to the key? I would like to find how many distinct values according to the key, for example, suppose I have
x = sc.parallelize([("a", 1), ("b", 1), ("a", 1),  ("b", 2), ("a", 2)])

And I have done using groupByKey
sorted(x.groupByKey().map(lambda x : (x[0], list(x[1]))).collect())
x.groupByKey().mapValues(len).collect()

the output will by like,
[('a', [1, 1, 2]), ('b', [1, 2])]
[('a', 3), ('b', 2)]

However,  I want to find distinct values in the list, the output should be like,
[('a', [1, 2]), ('b', [1, 2])]
[('a', 2), ('b', 2)]

I am very new to spark and try to apply the distinct() function somewhere, but all failed :-(
Thanks a lot in advance!

A: you can use set instead of list -
sorted(x.groupByKey().map(lambda x : (x[0], set(x[1]))).collect())

A: You can try number of approaches for same. I solved it using below approach:-
from operator import add
x = sc.parallelize([("a", 1), ("b", 1), ("a", 1),  ("b", 2), ("a", 2)])
x = x.map(lambda n:((n[0],n[1]), 1))
x.groupByKey().map(lambda n:(n[0][0],1)).reduceByKey(add).collect()

OutPut:-
[('b', 2), ('a', 2)]

Hope This will help you.


text:
Q: Moving a square in SDL2 using C I'm unable to move the rectangle I made in the program. There is no error message in the compiler when I run the program. Can you please tell me what I missed out in the keyboard event. Other event that I assigned to the window works fine. Thanks (an example will also be helpful).
#include <SDL.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
    SDL_Window *o;
    SDL_Renderer *r;
    SDL_Event e;
    int i = 1;

    SDL_Rect q;

    SDL_Init(SDL_INIT_VIDEO);

    o = SDL_CreateWindow("Game test",
                            SDL_WINDOWPOS_UNDEFINED,
                            SDL_WINDOWPOS_UNDEFINED,
                            1024,
                            800,
                            SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);

    r = SDL_CreateRenderer(o, -1,SDL_RENDERER_ACCELERATED);
    SDL_SetRenderDrawColor(r,0,0,255,255);
    SDL_RenderClear(r);
    //Creating a box
    q.x=475;
    q.y=700;
    q.h=50;
    q.w=50;
    SDL_SetRenderDrawColor(r,0,0,0,255);
    SDL_RenderFillRect(r,&q);
    //SDL_Delay(10);

    SDL_RenderPresent(r);

    while(i)
    {
        while(SDL_PollEvent(&e) !=0)
        {
            if(e.type == SDL_QUIT)
                i=0;
            else if(e.type == SDL_KEYDOWN)
            {
                switch(e.key.keysym.sym)
                {
                case SDLK_ESCAPE:
                case SDLK_q:
                    i=0;
                break;
                case SDLK_UP:
                    q.y -=10;
                    SDL_Delay(11);
                break;
                case SDLK_DOWN:
                    q.y +=10;
                    SDL_Delay(11);
                break;
                case SDLK_RIGHT:
                    q.x +=10;
                    SDL_Delay(11);
                break;
                case SDLK_LEFT:
                    q.x -=10;
                    SDL_Delay(11);
                break;
                default:
                break;
                }
            }
        }
    }

    SDL_DestroyWindow(o);
    SDL_DestroyRenderer(r);
    SDL_Quit();

    return 0;
}

A: You are only rendering the contents of the window before you enter your event loop. Since you never redraw the contents in the event loop, it's not very strange that no changes happen.

A: In SDL, you need to constantly redraw the window to see any changes you make. Since you only call the redraw function once, you only see what's happening in the very first moment of the window's creation. You simply need to add a redraw call inside of the loop, and it'll show you moving the rectangle as expected.


text:
Q: Openshift-django-mysql : No tables created to database via syncdb My settings.py
if ON_OPENSHIFT:
     DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'django',
            'USER': 'USER',
            'PASSWORD': 'PASS',
            'HOST': '127.2.202.129',
            'PORT': '3306',
        }
    }

and my action_hooks/deploy
source $OPENSHIFT_APP_DIR/virtenv/bin/activate
export PYTHON_EGG_CACHE=$OPENSHIFT_APP_DIR/virtenv/lib/python-2.6

echo "Executing 'python $OPENSHIFT_REPO_DIR/wsgi/my/manage.py syncdb --noinput'"
python $OPENSHIFT_REPO_DIR/wsgi/my/manage.py syncdb --noinput

echo "Executing 'python $OPENSHIFT_REPO_DIR/wsgi/my/manage.py collectstatic --noinput'"
python $OPENSHIFT_REPO_DIR/wsgi/my/manage.py collectstatic --noinput

and whenever i do,
git add .
git commit -a -m "project"
git push

my database shows no tables...why??
THANKS iin advance

A: Read this and you will understand a lot more about Django on OpenShift
http://appsembler.com/blog/django-deployment-using-openshift/


text:
Q: SQL Server Where clause with Case Checking null value So basically performing a name search on first and last name. The first name search parameter is not required, so I need a case statement in the where clause. However, the field first name in the table I'm searching can also be null.
And the problem is in SQL Server to check for a null you must use is null or is not null and I can't seem to use that with a case. The regex % doesn't cover null values.
Is this possible in one query or will this need to be two separate queries?
Here is essentially what it looks like:
select *
from table
where first_name like case
                       when @pFirstName is not null then @pFirstName
                       when @pFirstName is null then '%' end
and last_name = @pLastName

A: You can use Boolean logic :
WHERE ( (@pFirstName IS NOT NULL AND first_name = @pFirstName) OR
        (@pFirstName IS NULL)
      ) AND (last_name = @pLastName);

However, the first logic you can evaluate also :
(@pFirstName IS NULL OR first_name = @pFirstName)

By using that your query would be SARGable.

A: You could use a ISNULL() in order to handle passing of one argument or not.
I don't really recommend using this in a query, but you can do something like:
select *
from table
where first_name = ISNULL(@pFirstName, first_name)
    and last_name = @pLastName;

However, a better version would be:
select         /* do you really need all (*) the columns? */
    column_1
    , column_2
    , column_3
from table
where first_name = ISNULL(@pFirstName, first_name)
    and last_name = @pLastName
OPTION (RECOMPILE);

I'm adding OPTION (RECOMPILE) so that your query performs optimally (as far as it can in this form), by recalculating row estimates in case the @pFirstName parameter is not provided.
Ideally you would treat passing a parameter with a IF:
IF @pFirstName IS NOT NULL
    BEGIN
        select
            column_1
            , column_2
            , column_3
        from table
        where first_name = @pFirstName
            and last_name = @pLastName;
    END
ELSE
    BEGIN
        select
            column_1
            , column_2
            , column_3
        from table
        where last_name = @pLastName;
     END

A: Try this:
select *
from table
where (@pFirstName is null or first_name = @pFirstName)
  and last_name = @pLastName;

If @pFirstName is null, then (@pFirstName is null or first_name = @pFirstName) evaluates to true. If @pFirstName is not null, then the whole expression will be true whenever first_name = @pFirstName is true.

A: Something like this can do it
select *
from   table
where  (first_name is null or first_name = @pFirstName)
and    last_name = @pLastName

if you need a like it will look more like this
select *
from   table
where  (first_name is null or first_name like '%' + @pFirstName + '%')
and    last_name like '%' + @pLastName + '%'

A: I think you need this one:
select * from table where last_name = @pLastName and
    (@pFirstName is null or first_name = @pFirstName)

A: ...WHERE  (first_name like @pFirstName OR @pFirstName IS NULL)
            AND last_name = @pLastName


text:
Q: First occurrence of a tractor beam? Popular Mechanics has an article out today which claims that:

scientists [have] created the first tractor beam strong enough to manipulate macroscopic objects

Neato!
While setting the stage for this announcement, PM says:

Tractor beams have long been a staple of sci-fi

So, what's the first occurrence of a tractor beam in fiction?
For my purposes, a tractor beam is a piece of technology that can pull arbitrary macro-scale objects toward itself without touching those objects.
Some things that are not tractor beams:

*

*magnets

*telekinesis

*magic

*ghosts

EDIT: Just to make it clear, it does not matter whether the thing is actually named a "tractor beam," so long as it fits the functional definition. That's why I provided it.

A: It's not precisely "tractor beam" but "The Metal Horde" (Astounding, April 1930) by John W. Campbell Jr. has an "attractor beam."

Great liners of space were requisitioned and fitted with Dis rays, and with mighty attractor beam apparatus that would grip and hold anything short of another liner. Each of the ten-man-cruisers had a smaller attractor beam by which they could grip an adversary and hold to his tail with the tenacious grip of a bulldog and yet not weary the pilot with violent movement.

A: E.E. Smith, no later than 1931 (as a modern form)

A tractor-beam is a device with the ability to attract one object to another from a distance.[1] The concept originates in fiction: The term was coined by E. E. 'Doc' Smith (an update of his earlier "attractor-beam") in his novel Spacehounds of IPC (1931)

Ref: https://en.wikipedia.org/wiki/Tractor_beam
I looked this up because I have recently listened to the beginning of Smith's "Lensman" series as was pretty sure I remembered hearing it. As well as the 'space-time continuum' which I thought was pretty cool this early into Sci-Fi.

A: Jules Verne's The Chase of the Golden Meteor was not published in his lifetime, but in 1908 his son Michel published a revised version with several added chapters that he wrote himself, one of which introduced the character of the brilliant but absent-minded French scientist and inventor Zephyrin Xirdal. He invents a device, based on fictitious principles (see the explanation starting on p. 120 of the English translation on archive.org which @fez linked to in a comment), which emits a beam that can draw distant objects towards it, planning to deflect the golden asteroid from its orbit and guide it to crash at a spot of his choosing.
Edit - Thanks to Ray Butterworth for finding the exact source material. On p. 426 we read:

La seule chose un peu délicate, reprit Zéphyrin Xirdal, c'est de régler la longueur d'onde du courant neutre hélicoïdal. S'il atteint l'objet que l'on désire influencer, il le repousse, au lieu de l'attirer. Il faut donc qu'il expire à une certaine distance de cet objet, mais le plus près possible, de telle sorte que l'énergie libérée rayonne dans son voisinage immédiat.

which roughly translates to

The tricky part is to adjust the length of helical neutral current waveform, said Zéphyrin Xirdal. If it reaches the object that one wishes to influence, it will be pushed away instead of being attracted. It must therefore expire at a certain distance from this object, the closest possible, so that the released energy shines in its immediate vicinity.

A: According to the Technovelgy.com website the first use of the term "tractor beam" was in E.E. Smith's Spacehounds of IPC, 1931.

Tractor Beam
A force field used to pull objects.
Read an early example of this specialized kind of force field. This is the first instance of the term "tractor beam."
"We'll carry off the pieces of that ship, too, Quince—we may be able to get a lot of pointers from it," and Brandon swung mighty tractor beams upon the severed halves of the Jovian vessel, then extended a couple of smaller rays to meet the two little figures racing across the smooth green meadow toward the Sirius.
From Spacehounds of IPC, by E.E. 'Doc' Smith.
Published by Amazing Stories in 1931
The same device is used in Triplanetary

Although Smith certainly won the naming convention, Edmond Hamilton wrote about essentially the same thing three years earlier in Crashing Suns - the attractive ray.>

http://technovelgy.com/ct/content.asp?Bnum=695
https://www.isfdb.org/cgi-bin/title.cgi?11454

This is a very early reference to what sci-fi fans have come to refer to as the "tractor beam." The term tractor beam occurs first in E.E "Doc" Smith's Spacehounds of IPC three years later.

A spark of intense white light had suddenly broken into being on the platform beneath us, a beam of blinding light that stabbed straight up toward us, bathing the cruiser in its unearthly glow. And suddenly our ship was falling!
Sarto Sen sprang to the controls wrenched around the power-lever. "That ray!" he cried. "It's attractive! - it's pulling us down!" Our ship was vibrating now to the full force of its generators, but still we were falling...
From Crashing Suns, by Edmond Hamilton.

http://technovelgy.com/ct/content.asp?Bnum=974
https://www.isfdb.org/cgi-bin/title.cgi?78109
So other answerers will have to find use of the term "tractor beam" before 1931, or use of the device under a different name before 1928.

A: The Skylark of Space (written between 1915 and 1920) by E.E. "Doc" Smith
A predecessor of the Tractor Beam concept used in his later books.
Smith describes an "Attractor", paired with "Repellors" which operate as a kind of forcefield shield.
The Attractor fits the description of a Tractor Beam pretty solidly I think.
Here's a quote where the ship is hunting a Karlon, a massive winged predator on an alien world. The creature dives into a mudpit to hide and they use the Attractor to drag it out again and hold it in front of the ship.

Seaton brought the Skylark to a halt and stabbed downward with the full power of the attractor. The first stab brought up nothing but a pillar of muck; the second, one wing and one arm; the third, the whole animal - fighting as savagely as ever

The story was written around 1915-1920, but first serialized in Amazing Stories in 1928, and published in book form in 1946


text:
Q: AutoMapper Mapping navigation property issue I'm following this answer AutoMapper mapping int[] or List<int> from ViewModel to a List<Type> in Domain Model and have got it binding with my CategoryId to SelectedCategoryIds on UploadSongViewModel, however I want to also get it to bind SongId to Id on UploadSongViewModel.
namespace App
{
    public static class AutoMapper
    {
        public static MapperConfiguration Config;

        public static void Initialize()
        {
            //It works with CategoryId, but throws an error when I include SondId.
            Config = new MapperConfiguration(x =>
            {
                x.CreateMap<int, SongCategory>()
                    .IgnoreAllNonExisting()
                    .ForMember(dest => dest.CategoryId, opt => opt.MapFrom(src => src))
                    .ForMember(dest => dest.SongId, opt => opt.MapFrom(src => src)); //Code that's throwing exception

                x.CreateMap<UploadSongViewModel, Song>()
                    .IgnoreAllNonExisting()
                    .ForMember(dest => dest.AudioName, opt => opt.MapFrom(src => src.SongName))
                    .ForMember(dest => dest.AudioPath, opt => opt.MapFrom(src => src.SongPath))
                    .ForMember(dest => dest.SongCategories, opt => opt.MapFrom(src => src.SelectedCategoryIds))
                    .ForMember(dest => dest.SongCategories, opt => opt.MapFrom(src => src.Id)); //Code that's throwing exception
            });

            //Throws exception here because it can't bind SongId property
            Config.AssertConfigurationIsValid();
        }
    }
}

public abstract class Entity
{
    public int Id { get; set; }
}

public class SongCategory : Entity
{
    public int SongId { get; set; }
    public int CategoryId { get; set; }
}

public class Song : Audio
{
    public string AlbumName { get; set; }
    public string ArtistName { get; set; }

    public List<SongCategory> SongCategories { get; set;}
}

public class UploadSongViewModel
{
    public int Id { get; set; }
    public string ArtistName { get; set; }
    public string AlbumName { get; set; }
    public int[] SelectedCategoryIds { get; set; }

    public MultiSelectList CategoriesSelectList { get; set; }
}

I don't really understand what the auto mapper code is doing from Darin Dimitrov answer so it's hard to debug. If someone could explain how this mapping works for categoryId and why it is not working for SongId that would be great.
The exception I get is:

The following property on System.Collections.Generic.List1[[SoundVast.Models.SongCategory, SoundVast, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] cannot be mapped:
      SongCategories
  Add a custom mapping expression, ignore, add a custom resolver, or modify the destination type System.Collections.Generic.List1[[SoundVast.Models.SongCategory, SoundVast, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].
  Context:
      Mapping to property SongCategories from System.Int32 to System.Collections.Generic.List`1[[SoundVast.Models.SongCategory, SoundVast, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
      Mapping from type SoundVast.Areas.Upload.Models.UploadSongViewModel to SoundVast.Models.Song
  Exception of type 'AutoMapper.AutoMapperConfigurationException' was thrown.

A: This can be easily achieved with some custom mapping once the basic rules have been applied:
x.CreateMap<int, SongCategory>()
    .IgnoreAllNonExisting()
    .ForMember(dest => dest.CategoryId, opt => opt.MapFrom(src => src));

x.CreateMap<UploadSongViewModel, Song>()
    .IgnoreAllNonExisting()
    .ForMember(dest => dest.AudioName, opt => opt.MapFrom(src => src.SongName))
    .ForMember(dest => dest.AudioPath, opt => opt.MapFrom(src => src.SongPath))
    .ForMember(dest => dest.SongCategories, opt => opt.MapFrom(src => src.SelectedCategoryIds))
    .AfterMap((viewModel, model) =>
    {
        foreach (var item in model.SongCategories)
        {
            item.Id = viewModel.Id;
        }
    });


text:
Q: With a negative translateY on child, how to adjust parent height accordingly? I have a website with a header that I slide up on first scroll using translateY(-590px). The problem I get is that all the way on the bottom of my page, I get an extra bit of white space on some browsers.
A demo of the problem in this fiddle
Here's the example code:
HTML

block 1

block 2

block 3

block 4

CSS
.content{
    background-color: grey;
}
.content div{
    height: 100px;
    color: white;
    background-color: #2f2f2f;
    transition: transform 0.6s ease;
}
.content.scrolled div:last-child{
    height: 100px;
    transform: translateY(-100%);
}

JS (jQuery)
$(function(){
    setTimeout(function(){
        $(".content").addClass("scrolled");
    }, 700);
});

How can I make it so that the parent automatically adjusts its height.
ps
I use translateY because I have an animation on the sliding and using margin-top would be slow on Safari (because redrawing everything constantly). This is why I have to use translate instead of margin.

A: If the height of the resulting header is fixed, then you can just add a height value to .content.scrolled like so:
http://jsfiddle.net/1shxwmv8/8/
.content.scrolled {
    height: 300px;
}

Hope I understood your question and helped.


text:
Q: What does $\sum_{(a_1,a_2,...,a_n)\in\{1,x\}^n} a_1a_2\cdot\cdot\cdot a_n$ mean? In my textbook, I have this summation, but I can't understand what it means:
$$\sum_{(a_1,a_2,...,a_n)\in\{1,x\}^n} a_1a_2\cdot\cdot\cdot a_n$$
For example, if $n = 3$, what would this summation expand as?
Thanks

A: It just means each $a_i \in \{1,x\}$.  With $n=3$ the sum is $$(1\cdot 1 \cdot 1) + (1\cdot 1 \cdot x) + (1\cdot x \cdot 1) + (1\cdot x \cdot x) + (x\cdot 1 \cdot 1) + (x\cdot 1 \cdot x) + (x\cdot x \cdot 1) + (x\cdot x \cdot x)$$ $$= 1 + 3x + 3x^2 + x^3.$$

A: Note that if $A$ and $B$ are sets then
$$A\times B=\{(a,b):a\in A,b\in B\}$$
so
$$A^2=A\times A=\{(a,b):a,b\in A\}$$
And $$A^{n}=A\times A^{n-1}$$
So $$A^3=\{(a,b,c):a,b,c\in A\}$$
Hence if $A=\{1,x\}$ then
$$\{1,x\}^3=\{(a,b,c):a,b,c\in\{1,x\}\}$$
$$\begin{align}
=\{&(1,x,x),(x,1,x),(x,x,1)\\
&(1,1,x),(1,x,1),(x,1,1)\\
&(1,1,1),(x,x,x)\}
\end{align}$$
And in general, $\{1,x\}^n$ is going to have $2^n$ points. The sum in question is a sum over all those points:
$$S_n=\sum_{(a_1,...,a_n)\in\{1,x\}^n}a_1\cdots a_n$$
Which will be a sum of $2^n$ terms.
Let $P^{(n)}_j$ be the set of all points $(a_1,a_2,...,a_n)$ such that there are $j$ entries $a_k$ that are $x$, and there are $n-j$ entries $a_i$ that are $1$. We see that there is ${n\choose 0}=1$ point in $P^{(n)}_0$ and ${n\choose n}=1$ point in $P^{(n)}_n$. Then we see that there are ${n\choose 1}=n$ points in $P_1^{(n)}$ and ${n\choose n-1}=n$ points in $P_{n-1}^{(n)}$. So in general $$\left|P_{j}^{(n)}\right|={n\choose j}=\frac{n!}{j!(n-j)!}$$
Then we define the function $$q(a_1,a_2,...,a_n)=a_1a_2\cdots a_n$$
And see that, since points in $P^{(n)}_j$ by definition have $j$ entries equal to $x$,
$$\mathbf{a}\in P_{j}^{(n)}\Rightarrow q(\mathbf{a})=x^j$$
So of course
$$S_n=\sum_{j=0}^{n}\left|P_{j}^{(n)}\right|q\left(\mathbf{a}\in P_{j}^{(n)}\right)\\
=\sum_{j=0}^{n}{n\choose j}x^j=(1+x)^n$$
The final step coming from the Binomial theorem:
$$(x+y)^n=\sum_{j=0}^{n}{n\choose j}x^jy^{n-j}$$

A: Every $a_i$ is either $1$ or $x$, and you're taking the sum over all possibilities. For example, for $n=3$ you have $2^3$ terms (in order?): $$\begin{align}&1\cdot 1 \cdot 1+ 1\cdot x \cdot 1 + 1\cdot 1\cdot x + 1\cdot x\cdot x \\ &+x\cdot 1 \cdot 1+ x\cdot x \cdot 1 + x\cdot 1\cdot x + x\cdot x\cdot x. \end{align}$$

A: $\{1,x\}^n$ is the Cartesian self product of the set to the $n$-th degree.  $$\begin{align}\{1,x\}^n &= \overbrace{\{1,x\}\times\{1,x\}\times\cdots\times\{1,x\}}^{\text{$n$ factors}}\\[2ex]&=\{\underbrace{(1,1,\ldots,1, 1)}_{\text{$n$ terms}},(1,1,\ldots, 1,x),\ldots,(x,x,\ldots, x,1),(x,x,\ldots,x,x)\}\end{align}$$
So...

$$\sum\limits_{(a_1,\ldots,a_n)\in\{1,x\}^n} a_1a_2\cdots a_n$$
This is the sum, for all possible selections, of the product of $n$ factors each selected independently from the set $\{1,x\}$.
It is clearly equal to $(1+x)^n$
$$\begin{align}\sum\limits_{(a_1,\ldots,a_n)\in\{1,x\}^n} a_1a_2\cdots a_n&=(1+x)\sum_{(a_1,\ldots,a_{n-1})\in\{1,x\}^{n-1}}a_1a_2\cdots a_{n-1}
\\[2ex]&=(1+x)^n\end{align}$$