text:
Q: cv::Mat , get value at row column without knowing the type of the matrix so I am trying to get the value of a matrix, which type I do not know, using row and column value. I basically want to implement the following:
bool someFunction(cv::Mat m){
   return m(1,0) != 0;
}

I know this will error out since I need to specify the type like so m.at< Type >(1,0)
but I would not know the type.
I tried doing the following:  m.at< m.type() >(1,0) but that, of course, errors out.
I am wondering what could potentially work here. Thanks!

A: A not so elegant solution. Use depth and a switch case.
#include<cv.h>
#include<stdint.h>

using namespace cv;
using namespace std;

bool someFunction(Mat m) {
    switch (m.depth()){
        case CV_8U:
            return m.at<uint8_t>(1,0) != 0;
        case CV_8S:
            return m.at<int>(1,0) != 0;
        case CV_16U:
            return m.at<uint16_t>(1,0) != 0;
        case CV_16S:
            return m.at<int16_t>(1,0) != 0;
        case CV_32S:
            return m.at<int32_t>(1,0) != 0;
        case CV_32F:
            return m.at<float>(1,0) != 0;
        case CV_64F:
            return m.at<double>(1,0) != 0;
    }
}

int main() {
    Mat m(2,2, CV_8UC1);
    cout << someFunction(m) << endl;
}

A: I am assuming that you are doing this for single channel images, but you will get an idea even for > 1 channel images.
You can change your function to
template<class T>
bool someFunction(cv::Mat_<T> m) {
   return m(1,0) != 0;
};

And you can call the function like -
someFunction<uchar>(gray);

Here, I am assuming that you know the type, from the function you are calling.
In place of uchar, you can use any data type your Mat object is of.
If you want to automate this task also, check here.


text:
Q: Cannot create a SVN repository in XCode I created a project in XCode and tried to add it to SVN. I went to File -> Source Control -> Repository. In the Add a Repository dialog box, I enter the URL as below:
Name: test
Location: http://xxx.xxx.x.xxx:8080
Type: Subversion
After I clicked Add, the IDE seemed to be executing something and kept showing me the progress bar. And I didn't get any error message.
Anyone knows how to solve the problem?
Thanks,

redpajama_set_name: RedPajamaStackExchange


text:
Q: WDS Auto Logging in after Install I have setup WDS to push out images to our machines completely hands of. It all works fine, accept at the end of the process, when the machine is sat at the crl+alt+del login prompt. If you hit crl_alt+del instead of asking for a username/pass, is is automaticly logging on as the local admin account.
Anyone any ideas how to stop it auto logging on, we are going to be deploying to remote unmanned sites, and dont really want a user to be able to use the machine logged in as the local admin
Cheers
Luke

A: WDS doesn't really have anything to do with the resulting OS that ends up on your machines.  It is just the delivery mechanism.  You have to look at the customizations you've made to the OS deployment you're pushing out.  What tool(s) did you use to create your deployment?

A: I would suggest that you look at your sysprep inf file.  There may be a setting in there that will allow for autologging in the first time.


text:
Q: How To remove all Index values from an array other then given in swift 3 suppose i have a string array in swift 3 with values
var Names:[String] = ["john","Obama","Trump"]

in my other number array i have values
var index int[]  = [0,2]

i want to delete all the values from Names array except index 0 and 2 thats listed in my second numeric array list
so my result sould like
["john","Trump"]
i am working in swift 3

A: var names = [String]()
var indexes = [Int]()

Create newNames
var newNames = [String]()

Populate newNames
for idx in indexes {
   newNames.append(names[idx])
}

A: to remove all elements exepts the elements contained in the list indexs:
var names = [String]()
names.append("john")
names.append("Obama")
names.append("Trump")

var indexs = [Int]()
indexs.append(0)
indexs.append(2)

var names_res = [String]()

for index in indexs {
       names_res.append(names[index])
}


text:
Q: mybatis is not working while put AUTO_INCREMENT in INSERT statement just like the code below, it's work fine in Navicate, but I put this in mybatis, it's not working, seems cannot get the value.
    INSERT INTO `table_user`(
        `account`,
        `createtime`,
        `path`
    )
    VALUES
    (
    'test',
    now(),
    CONCAT(
        'test-',
        (
            SELECT
                AUTO_INCREMENT
            FROM
                information_schema. TABLES
            WHERE
                TABLE_SCHEMA = DATABASE ()
            AND TABLE_NAME = 'user_info'
        )
    )
)

mybatis:

    INSERT INTO

        (
        account, createtime, path
        ) VALUES (
        #{account}, now(), CONCAT('test-',(SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='user_info'))
        )

I got exceptions:

### Error updating database.  Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'path' cannot be null
### The error may involve bestyyt.dao.UserInfoDao.save-Inline
### The error occurred while setting parameters
### SQL: INSERT INTO                table_user               (         account, createtime, path         ) VALUES (         ?, now(), CONCAT('test-',(SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='table_user'))         )
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'path' cannot be null
; SQL []; Column 'path' cannot be null; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'path' cannot be null

    at org.springframework.jdbc.support.SQLExceptionSubclassTranslator.doTranslate(SQLExceptionSubclassTranslator.java:85)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
    at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:75)
    at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:447)
    at com.sun.proxy.$Proxy26.insert(Unknown Source)
    at org.mybatis.spring.SqlSessionTemplate.insert(SqlSessionTemplate.java:279)
    at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:56)
    at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:53)
    at com.sun.proxy.$Proxy27.save(Unknown Source)
    at bestyyt.dao.UserInfoDaoTest.save(UserInfoDaoTest.java:28)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'path' cannot be null
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
    at com.mysql.jdbc.Util.getInstance(Util.java:387)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:934)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3966)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3902)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2526)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2673)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2549)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1861)
    at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1192)
    at org.apache.commons.dbcp2.DelegatingPreparedStatement.execute(DelegatingPreparedStatement.java:198)
    at org.apache.commons.dbcp2.DelegatingPreparedStatement.execute(DelegatingPreparedStatement.java:198)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.ibatis.logging.jdbc.PreparedStatementLogger.invoke(PreparedStatementLogger.java:59)
    at com.sun.proxy.$Proxy29.execute(Unknown Source)
    at org.apache.ibatis.executor.statement.PreparedStatementHandler.update(PreparedStatementHandler.java:46)
    at org.apache.ibatis.executor.statement.RoutingStatementHandler.update(RoutingStatementHandler.java:74)
    at org.apache.ibatis.executor.SimpleExecutor.doUpdate(SimpleExecutor.java:50)
    at org.apache.ibatis.executor.BaseExecutor.update(BaseExecutor.java:117)
    at org.apache.ibatis.executor.CachingExecutor.update(CachingExecutor.java:76)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:198)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.insert(DefaultSqlSession.java:185)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:434)
    ... 34 more

A: The short answer here is to hardcode your database name in the query rather than use DATABASE(). The longer version ...
As has been identified in the comments the immediate cause of your problem is the NULL returned by the query. The CONCAT() function will return NULL if any part of it is NULL which you could solve by using
CONCAT_WS('','test-',(SELECT the rest of your query))
That would always guarantee that path contained the string 'test-' so you'd not fail the NOT NULL constraint on the column (but you'd have nonsense data).
Since you have confirmed the existence of the user_info table, the failure of the query is likely down to
TABLE_SCHEMA=DATABASE()

which attempts to select the default (current) database. If there isn't a default then it returns NULL (hence CONCAT fails). To get DATABASE() to return a value you need to set it explicitly with a USE statement (or your client does this). I tried this in workbench but it would probably work in navicat e.g.
-- make sure you have no database selected
CREATE DATABASE foo;
USE foo;
DROP DATABASE foo;

-- create the test table
CREATE DATABASE test IF NOT EXISTS;
DROP TABLE IF EXISTS test.auto_inc;
CREATE TABLE test.auto_inc (
  `id` INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
  `path` varchar(20) NOT NULL );

-- without a default using database()
SELECT 'With DB()',`AUTO_INCREMENT`
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'auto_inc';
Empty set (0.00 sec)

USE test;

-- with explicit USE statement
SELECT 'DB()',`AUTO_INCREMENT`
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'auto_inc';
+------+----------------+
| DB() | AUTO_INCREMENT |
+------+----------------+
| DB() |              1 |
+------+----------------+
1 row in set (0.02 sec)

I can't see anything in your sample where you explicitly set the database. Presumably, you specify a database in your connection string but that doesn't appear to be sufficient. You could test that from your application with a simple
SELECT DATABASE();

If you hardcode the database name, as you do the table name, it will work without the need for a USE statement .
Finally, since this table has an AUTO_INCREMENT column and the record you create would have that value, why are you trying to get it separately to write into the record?


text:
Q: when download application from url (.plist) multi time I download an application from url, but this multi time between Calls to Url and see the app begin to download,
How can I to abbreviate the time, and see immediately that the application began to download,
example code:
NSURL* url = [NSURL URLWithString:@"itms-services://?action=download-manifest&url=https://.....plist"] ;
 [[UIApplication sharedApplication] openURL:url];

The problem began ios 10


text:
Q: Amazon simple DB select query with order by clause I am trying to execute select query with order by in date field.
SELECT * FROM <domain> WHERE
LastModifiedDate is not null and
FileName LIKE 'a%'
order by lastmodifiedDate desc.

Query results client error
Client error : Invalid sort expression. The sort attribute must be present in at least one of the predicates, and the predicate cannot contain the is null operator.
How to add order by clause in amazon simple db.

A: SELECT * FROM <domain> WHERE
FileName LIKE 'a%'
order by lastmodifiedDate desc.

is not null counts as the is null operator
you may be able to test for something else?


text:
Q: generate an ordered zig-zag set of points (path) given bounds, direction, and starting point say we want to generate a zig-zag set of points as a numpy array like the following image such that the array elements' order is similar to moving on the path:
we are given:

*

*The bounds where this path should be in (e.g., the above image has
x=[-2500:2500], y=[-200, 200])

*the starting point that defines the
order of points in such path (e.g., in the blow image it is (2500,
200)

*teeth direction (e.g., the below image is in y)
direction, that is why the starting point starts going down in the
beginning)

*the step size between each point (e.g., 10)

*the width of each teeth

What is the simplest way to generate such numpy array? I tried scipy square wave but aside from other required features it only generates the teeth edge points but not all the path in a way that can be shown with scatter plot

A: Apologies in advance for ignoring your starting point and teeth direction. I started without considering them and when I was finished and only had to add them I thought that you can very likely do that yourself. I also think there could be a more pretty solution to your x pixel point distance request than just getting a lot of points and filtering them so that is satisfied. Let me know if that's important to you. That aside I think this is a nice solution.
def zig_zag(x_interval,y_interval,tooth_width,step_size):
    #finding the teeth edge points
    x_vals = np.arange(*x_interval,tooth_width)
    idx = np.arange(x_vals.shape[0]*2-1)%4
    mask = ((idx == 0) | (idx == 1))

    x = np.empty(mask.shape, dtype='int')
    y = np.empty(mask.shape, dtype='int')

    x[mask] = x_vals
    x[~mask] = x_vals[1:]
    y[mask] = y_interval[1]
    y[~mask] = y_interval[0]

    #interpolating between the teeth edge points and get way to many points
    tck, u = interpolate.splprep([x,y],s=0,k=1)
    x, y = interpolate.splev(np.linspace(0, 1, 10**6), tck)

    #pick the perfect points
    arr = np.array(tuple(filter_points(x,y,step_size)))
    x = arr[:,0]
    y = arr[:,1]

    #plot it
    ax = plt.gca()
    ax.scatter(x, y)
    ax.set_aspect('equal')
    plt.savefig("teeth.png")

def filter_points(x,y,step_size):
    found = x[0],y[0]
    step_size **= 2
    yield found
    for x,y in zip(x,y):
        if (found[0]-x)**2+(found[1]-y)**2 >= step_size:
            found = x,y
            yield found

zig_zag((0,700),(0, 200),100,5)

A: I have so far the following answer:
from copy import copy
import numpy as np

class ZigZagTraj(object):
    def __init__(self, xs, ys, xe, ye, tooth_direction='x', tooth_width=0.2, step=0.05):
        self.xs, self.ys, self.xe, self.ye = xs, ys, xe, ye
        self.tooth_direction = tooth_direction
        self.tooth_width = tooth_width
        self.step = step

        self.bounds = {'x': {'lb':None, 'ub':None },
                      'y': {'lb':None, 'ub':None }}
        if xe - xs > 0:
            self.bounds['x']['ub'] = self.xe
            self.bounds['x']['lb'] = self.xs
        else:
            self.bounds['x']['ub'] = self.xs
            self.bounds['x']['lb'] = self.xe
        if ye - ys > 0:
            self.bounds['y']['ub'] = self.ye
            self.bounds['y']['lb'] = self.ys
        else:
            self.bounds['y']['ub'] = self.ys
            self.bounds['y']['lb'] = self.ye

        self.x_increment_sign =  np.sign(self.xe - self.xs)
        self.y_increment_sign =  np.sign(self.ye - self.ys)

        self.curr_direction = tooth_direction
        self.curr_tooth_width = 0

        self.traj = []
        self.traj.append([xs, ys])

    def change_curr_direction(self):
        if self.curr_direction == 'x':
            self.curr_direction = 'y'
        elif self.curr_direction == 'y':
            self.curr_direction = 'x'
        return self.curr_direction

    def in_bound(self,new_point):
        return self.in_x_bound(new_point) and self.in_y_bound(new_point)

    def in_x_bound(self,new_point):
        return self.bounds['x']['lb'] <= new_point[0] <= self.bounds['x']['ub']

    def in_y_bound(self, new_point):
        return self.bounds['y']['lb'] <= new_point[1] <= self.bounds['y']['ub']

    def generate_trajectory(self):
        self.tooth_direction = self.tooth_direction
        curr_tooth_width = 0
        traj = []
        traj.append([self.xs, self.ys])
        #print('self.x_increment_sign',self.x_increment_sign, 'self.x_increment_sign',self.x_increment_sign)
        while True:
            #print(traj[-1], 'for direction', self.curr_direction)
            new_point = copy(traj[-1])
            if self.curr_direction == 'x':
                new_point[0] += self.step * self.x_increment_sign
            elif self.curr_direction == 'y':
                new_point[1] += self.step * self.y_increment_sign

            if self.curr_direction != self.tooth_direction:  # we're on a tooth
                curr_tooth_width += self.step
                #print('checking if tooth width is reached', curr_tooth_width, tooth_width)
                if curr_tooth_width >= self.tooth_width:
                    if self.tooth_direction == 'x':  # along the tooth direction we should now run backwards
                        self.x_increment_sign *= -1
                    else:
                        self.y_increment_sign *= -1
                    curr_tooth_width = 0
                    self.change_curr_direction()
                    #print('not append(tooth width). moving to direction: ', self.curr_direction)
                    continue
            elif not self.in_bound(new_point): # we're on tooth length ( out of bound for lenght direction)
                self.change_curr_direction()
                #print('not append(tooth length)')
                continue

            #print('checking if we should append')
            #print('new point', new_point)
            #print(self.in_x_bound(new_point), self.in_y_bound(new_point))
            if not self.in_x_bound(new_point) or not self.in_y_bound(new_point):
                #print('not append(break)')
                break
            new_point[0] = round(new_point[0], 3)
            new_point[1] = round(new_point[1], 3)
            traj.append(new_point)
        return np.array(traj)

with the following result:
[![zig = ZigZagTraj( 1.2, 1.2, 0, 0, tooth_direction='x', tooth_width=0.2, step=0.05)
traj = zig.generate_trajectory()
fig, ax = plt.subplots()
ax.scatter(traj\[:, 0\], traj\[:, 1\])
plt.show()


text:
Q: If ${ X_n }$ is a sequence of real numbers and E = set of all numbers z s.t. $\exists$ a subsequence ${ X_{n_k} }$ convergent to z, then E is closed. I have to show that, if ${ X_n }$ is a sequence of real numbers and $E$ denotes the set of all numbers $z$ that have the property that there exists a subsequence ${ X_{n_k} }$ convergent to $z$, then $E$ is closed.
So I have to show that any accumulation point of $E$, say $x$, is in the set $E$. By the definition of accumulation points of $E$ we have that  for every $c>0$ the intersection
$$(x-c,x+c) \cap E$$
contains infinitely many points. So there exists a subsequence ${ X_{n_k} }$ convergent to some $z$ arbitrary close to $x$.  If ${ X_{n_k} }$ converges to $z$ then for all $\epsilon >0 $ there is an integer $N$ so that
$$ \lvert { X_{n_k} } - z \rvert < \epsilon$$
whenever $n\geq N$. Choose $z$ such that $z>x>0$, then it follows that $$ \lvert { X_{n_k} } - x \rvert < \lvert { X_{n_k} } - z \rvert < \epsilon$$
whenever $n\geq N$. Thus $x$ converges to $x_{n_k}$ as well, so $x\in E$.
QED
Does my idea make sense? Is it rigorous? Any pointers/hints would be greatly appreciated.


text:
Q: Requesting yours to access GooglePlayServices In my android application I wish to ask users permission to use the google playservices. Is there any way to do that?
Like for reading contacts, we use:
// Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPermission(getActivity(),
                android.Manifest.permission.)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    android.Manifest.permission.READ_CONTACTS)) {

                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

            } else {

                // No explanation needed, we can request the permission.

                ActivityCompat.requestPermissions(getActivity(),
                        new String[]{android.Manifest.permission.READ_CONTACTS},
                        MY_PERMISSIONS_REQUEST_READ_CONTACTS);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }

P.S :  My gradle.build file has:
compile 'com.google.android.gms:play-services:9.0.2'
    compile 'com.google.android.gms:play-services-location:8.1.0'

A: Google play service are library. You never need to ask for permission to use them. Bt depends on feature you wanna use u need permission.
Like to use map you need to ask location permission


text:
Q: My GameScene is returning nil when I try to use it in GameViewController I'm creating a basic spaceship game using Swift, and everything was working well until I tried to add a feature where the spaceship moves up every time the user swipes up. I added a UISwipeGestureRecognizer and connected it with an IBAction in my GameViewController, from which I then intended to call a method in my GameScene to make the spaceship move up.
import UIKit
import SpriteKit

extension SKNode {
    class func unarchiveFromFile(file : NSString) -> SKNode? {
        if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
            var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)!
            var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)

            archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
            let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene
            archiver.finishDecoding()
            return scene
        } else {
            return nil
        }
    }
}
class GameViewController: UIViewController {

    let scene: GameScene!

    @IBAction func swipeUp(sender: UISwipeGestureRecognizer){
        scene.movePlaneUp()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
            let skView = self.view as SKView
            skView.ignoresSiblingOrder = true
            scene.scaleMode = .AspectFill

            skView.presentScene(scene)
        }
    }

    override func shouldAutorotate() -> Bool {
        return false
    }

    override func supportedInterfaceOrientations() -> Int {
        if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
            return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
        } else {
            return Int(UIInterfaceOrientationMask.All.rawValue)
        }
    }

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

    override func prefersStatusBarHidden() -> Bool {
        return true
    }
}

Everything compiles and the app runs, however, whenever I try to swipe up, I get a fatal error: unexpectedly found nil while unwrapping an Optional value on the line
scene.movePlaneUp()

I understand that the error occurs because scene's value was nil, but how do I make it so that scene actually has a value of GameScene?
Here is my code for GameScene:
import SpriteKit

class GameScene: SKScene {
    override func didMoveToView(view: SKView) {
        let bg = SKSpriteNode(imageNamed: "Background")
        bg.size = self.frame.size
        bg.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame))
        self.addChild(bg)
        let sprite = SKSpriteNode(imageNamed: "Spaceship")
        sprite.xScale = 0.6
        sprite.yScale = 0.5
        sprite.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMinY(self.frame)+CGRectGetMaxY(sprite.frame))
        sprite.name = "spaceship"
        self.addChild(sprite)
    }
    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        var t = touches.allObjects[0]
        let location = t.locationInNode(self)
        let action = SKAction.moveToX(location.x, duration:0.1)
        let n = self.childNodeWithName("spaceship")
        n?.runAction(action)
        let bullet = SKSpriteNode(imageNamed: "Spaceship")
        bullet.xScale = 0.05
        bullet.yScale = 0.05
        bullet.position = CGPoint(x: location.x, y: 200+bullet.position.y)
        bullet.runAction(SKAction.moveToY(1000, duration: 0.75))
        self.addChild(bullet)
    }
    func movePlaneUp(){
        let n = childNodeWithName("spaceship")
        n?.removeAllActions()
        let action = SKAction.moveBy(CGVector(dx: 0, dy: 100), duration: 1)
        n?.runAction(action)
    }
}

A: I realized the reason I had the error was because I never assigned anything to scene. I solved my problem by changing
let scene: GameScene!

to
let myScene: GameScene!

then I changed my viewDidLoad to
override func viewDidLoad() {
    super.viewDidLoad()
    if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
        let skView = self.view as SKView
        skView.ignoresSiblingOrder = true
        scene.scaleMode = .AspectFill
        skView.presentScene(scene)
        myScene = scene
    }
}

which then actually assigned a value to myScene

A: I know this is a bit late... if you used self.scene = scene it would have worked as well. It's due to the scene var, created with if let scene, overriding any other variable with the same name within the if let scope.  You probably already know this now (as it's been two years since this was created) :) However, I hope it's useful to newcomers to the language.


text:
Q: Count entries that belong to specific type Lets say I have a database called people:
That has id and type
How can i count the people that belong to specific types.
I dont want to have a query like this one, i want to automate this:
SELECT
         COUNT(CASE WHEN type = 'single' THEN 1 END) as single,
         COUNT(CASE WHEN type = 'married' THEN 1 END) as marrried,
         COUNT(CASE WHEN type = 'kids' THEN 1 END) as kids
         ......
FROM people;

How can I do that? THANKS

A: Use group by
SELECT COUNT(id), type FROM people GROUP BY  type

A: The closest technique to yours that gives the right result would be:
  SELECT
   SUM(CASE WHEN type = 'single' THEN 1 ELSE 0 END) as single,
   SUM(CASE WHEN type = 'married' THEN 1 ELSE 0 END) as marrried,
  ...


text:
Q: Excel column heads on row 2 of export from ColdFusion I want the table exported from ColdFusion to Excel with the headers below to show column headers on Row 2 of the spreadsheet, with filtering turned on when first viewed.
<cfheader name="Content-Type" value="application/msexcel">

How do I set styles and XML specs to obtain this result?

A: The easiest approach is to just create a simple spreadsheet with the feature you want in Excel. Then save it as HTML and view the source to see how what code is used.
This is a basic example I created by doing exactly that. The main properties that control filtering are autofilter and autofilterrange:

<cfset someQuery = queryNew("")>
<cfset queryAddColumn(someQuery, "ID", listToArray("10,22,14,51,62"))>
<cfset queryAddColumn(someQuery, "Title", listToArray("AAA,BBB,CCC,DDD,EEE"))>

<cfheader name="Content-Type" value="application/msexcel">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

ID
    Title

<cfoutput query="someQuery">

#ID#
        #Title#

</cfoutput>


text:
Q: Json schema not validating as expected I am working on a Json schema for validation but it does not seem to be working.
Apart from the if then condition, the rest works fine but even though i am following the example provided in jsonschema - Applying Subschemas Conditionally, it does not work.
This is the schema
'''
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "definitions": {
    "identifierKey": {
      "type": "string",
      "pattern": "^[a-z][a-z0-9]*(_[a-z0-9]+)*$",
      "minLength": 2
    },
    "uuid": {
      "type": "string",
      "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
      "minLength": 36,
      "maxLength": 36
    },
    "mail_identifierKey": {
      "pattern": "^(?:(?!.*?[.]{2})[a-zA-Z0-9](?:[a-zA-Z0-9.+!%-]{1,64}|)|\"[a-zA-Z0-9.+!% -]{1,64}\")@[a-zA-Z0-9][a-zA-Z0-9.-]+(.[a-z]{2,}|.[0-9]{1,})$"
    },
    "question_type": {
      "enum": [
        "barcode",
        "name",
        "nps",
        "single_choice",
        "text",
        "date",
        "number",
        "id",
        "mail_address",
        "multiple_choice",
        "phone_number",
        "zip_code",
        "rating"
      ]
    },
    "question": {
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "key": {
          "$ref": "#/definitions/identifierKey"
        },
        "type": {
          "$ref": "#/definitions/question_type"
        }
      },
      "required": ["key", "type"]
    },
    "answers": {
      "type":"array",
      "items": {
        "type": "object",
        "properties": {
          "question": {
            "$ref": "#/definitions/question"
          },
          "status": {
            "type": "string"
          }
        },
        "allOf": [
          {"if": {
            "properties": { "question": { "const": "rating" } } },
          "then": {
            "properties": { "value": { "type": "number", "minimum": 1, "maximum": 5 } } }
          },
          {"if": {
            "properties": { "question": { "const": "zip_code" } } },
           "then": {
            "properties": { "value": { "type": "string", "$ref": "#/definitions/identifierKey","minLength": 4, "maxLength": 10 } } }
          },
          {"if": {
            "properties": { "question": { "const": "phone_number" } } },
          "then": {
            "properties": { "value": { "type": "string", "minLength": 8, "maxLength": 15 } } }
          },
          {"if": {
            "properties": { "question": { "const": "multiple_choice" } } },
           "then": {
            "properties": { "value": { "type": "array", "minItems": 1, "uniqueItems": true,
                "contains": { "type": "string" } }
              }
            }
          },
          {"if": {
            "properties": { "question": { "const": "single_choice" } } },
           "then": {
            "properties": { "value": {"type": "string","$ref": "#/definitions/identifierKey"} } }
          },
          {"if": {
            "properties": { "question": { "const": "mail_address" } } },
           "then": {
            "properties": { "value": {"type": "string","$ref": "#/definitions/mail_identifierKey"} } }
          },
          {"if": {
            "properties": { "question": { "const": "id" } } },
           "then": {
            "properties": { "value": {"type": "string","$ref": "#/definitions/uuid"} } }
          },
          {"if": {
            "properties": { "question": { "const": "number" } } },
           "then": {
            "properties": { "value": {"type": "number"} } }
          },
          {"if": {
            "properties": { "question": { "const": "text" } } },
           "then": {
            "properties": { "value": {"type": "string"} } }
          },
          {"if": {
            "properties": { "question": { "const": "date" } } },
           "then": {
            "properties": { "value": {"type": "string", "format": "date"} } }
          },
          {"if": {
            "properties": { "question": { "const": "nps" } } },
           "then": {
            "properties": { "value": {"type": "number", "minimum": 1, "maximum":10 } } }
          },
          {"if": {
            "properties": { "question": { "const": "name" } } },
           "then": {
            "properties": { "value": {"type": "string" } } }
          },
          {"if": {
            "properties": { "question": { "const": "barcode" } } },
           "then": {
            "properties": { "value": {"type": "number" } } }
          }
        ]
      }
    }
  },
  "properties": {
    "answers": {
      "$ref": "#/definitions/answers"
    }
  }
}

'''
and this is what i am trying to validate
''' {
    "$schema": "./blank.json",
    "answers":[ {
        "status": "hello1",
        "question": {
            "key": "hello",
            "type": "rating"
        },
        "value": 1234
    }]
} '''

i am following the example below but not able to figure out what i am missing

*

*https://json-schema.org/understanding-json-schema/reference/conditionals.html

A: Okay... I see the problem.
Here's the if subschema that you expect to trigger for your data
{
  "properties": {
    "question": { "const": "rating" }
  }
}

However, in your data, question has a type property.
"question": {
  "key": "hello",
  "type": "rating"
}

This means that the if subschema isn't passing because {"key": "hello", "type": "rating" } != "rating".
You'll need to update your if subschema to account for this property hierarchy.
{
  "properties": {
    "question": {
      "properties": {
        "type": { "const": "rating" }
      }
    }
  }
}

You'll need to do this for all of the if subschemas.
Making just this change gives this error on my validator:
{
  "valid": false,
  "keywordLocation": "#/properties/answers/$ref/items/allOf/0/then/properties/value/maximum",
  "absoluteKeywordLocation": "https://json-everything/base#/definitions/question_type/items/allOf/0/then/properties/value/maximum",
  "instanceLocation": "#/answers/0/value",
  "error": "1234 is greater than or equal to 5"
}


text:
Q: jQuery Datatables - Showing 1 of X entries all the time I've hit an issue where jQuery data tables is showing in the info bar at the bottom:
Showing 1 of X entries
This happens upon scrolling down and doesn't update the counter. The total number of records are correct, just not the position within the dataset.
Example: https://jsfiddle.net/jubq03oL/3/
Seems to also be doing this on the Scroll Y example on their site:
https://datatables.net/examples/basic_init/scroll_y.html

A: It appears you need the Scroller extension in order for this functionality to work.
Then changing the JavaScript call to DT enables the functionality:
$('#datatable').DataTable({
    order:    [[0, 'desc']],
    scrollY:  350,
    deferRender: true,
    scroller: true
});

See the following JSFiddle:
https://jsfiddle.net/jubq03oL/6/

A: That number isn't suppose to change unless you have multiple pages.
See my fiddle update. I changed the following:
$('#datatable').DataTable({
    order: [
        [0, 'desc']
    ],
    scrollY: 350,
    pageLength: 10, // Added to show how the numbering works on multiple pages, not scrolling
    paging: true,
    searching: true });


text:
Q: Extract Alberta (Canada) postal code through regular expressions in python I want to extract postal codes of Alberta (Canada) region from an address string.
For example:
 addr = '12345-67 Ave, Edmonton, AB T1A 2B3, Canada'

Should extract T1A 2B3.
The regular expression to match the postal code is [T]\d[A-Z] *\d[A-Z]\d. However, I do not know that given an entire address, how can I extract only the postal code? I guess it has to do something with backreferences () but I cannot figure it out.
How can I achieve this in Python?

A: Extracting just the substring that matched the regexp is easy enough:
test = re.compile(r'[T]\d[A-Z] *\d[A-Z]\d')
addr = '12345-67 Ave, Edmonton, AB T1A 2B3, Canada'
test.search(addr).group()

test.search will return a match object, which has all kinds of stuff you can extract.

A: Building on @Peter's Answer here is how you can do it for some more postal codes:
US:
addr= 'Statue of liberty, New York, NY 10004, USA'
test = re.compile(r'\d{5}')
test.search(addr).group()

UK:
addr= 'Olympic Park, Montfichet Rd, London E20 1EJ, United Kingdom'
test = re.compile(r'[A-Z]\d\d\s\d[A-Z]\d')

Canada:
addr= 'Toronto City Hall, 100 Queen St W, Toronto, ON M5H 2N2'
test = re.compile(r'[A-Z]\d[A-Z]\s\d[A-Z]\d')

[A-Z] Matches any uppercase letter in range A-Z
[a-zA-Z] Matches any uppercase letter in range A-Z (case insensitive)
\d matches any digit
\d{n} matches any occurrence of n digits
\s matches any whitespace character
You can also use Regex101, which is a very helpful tool for testing Regexes.


text:
Q: Compile SASS directory into multiple files Q. How do I / is it possible to split my /SCSS directory into multiple output .css files?
I have a part of the application /admin that I don't want to serve to the standard user for performances reasons. Also, there are some standalone landing pages that are not part of the 'main' site, so could do with their own bundle.
Example SCSS structure:
/scss
  - partials
  - modules

Compile into:
main.css
admin.css
landing.css

Note: I'm using webpack


text:
Q: add image to FileField in Django I'm using Django building a website and I'm trying to let the user upload an image to be used, here is my files :
settings.py
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home2/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media')

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = '/media/'

models.py
class test1(models.Model):
    dress_name = models.CharField(max_length=250, default='dress')
    dress_size = models.CharField(max_length=50, default='5')
    docfile = models.FileField(upload_to='documents/%Y/%m/%d',default ='upload')

views.py
def home(request):
    all_dress = test1.objects.all()
    context = {
        'all_dress': all_dress,
    }
    return render(request, 'fostania/home.html', context)

and here is how I used it in my template
HTML
    {% for item in all_dress %}

{{ item.dress_name }}

{{ item.dress_size }}

    Go somewhere

      {% endfor %}

URLS.py
from django.contrib import admin
from django.template.context_processors import static
from django.urls import path
from django.contrib.auth import views as auth_views
from dress import settings
from fostania import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('login/', auth_views.login, name='login'),
    path('home/',views.home, name='home'),
    path('add/',views.add, name="add"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

finally, the image never shows .. it is always an error in the link !!
Please note that image goes there in the static/media file after uploading, So i think it is some kind of URL error!
ERROR
The error is that the image always shows a broken link, and when I open the link (Open images link ) it gives me this error
Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/media/documents/2018/05/18/test_dress3.jpg

A: You need to add MEDIA_URL to the project's urlpattern list:
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Check related part of the doc.

A: SOLVED
it was a wrong import reference, I used from django.conf.urls.static import static instead of  from django.template.context_processors import static and it worked.


text:
Q: Determine what 'sub' element is selected I have a p element and users can select sections of this text with their mouse. I need to determine what element is selected (in the below example either p or span).

$(document).ready(function() {

$('button').click(function(e) {
  console.log('sel', window.getSelection());
  console.log('h', window.getSelection().getRangeAt(0));

  // How can I determine if a span is selected or a text section of the p?

  // If a span is selected I do nothing except make the span italic
  // If a text section of the p is selected I need to add a span and then make the span italic

  if (window.getSelection().getRangeAt(0).commonAncestorContainer.nodeType != 'span') {
    var selection = window.getSelection().getRangeAt(0);
    var selectedText = selection.extractContents();
    var span = document.createElement("span");
    span.appendChild(selectedText);
    selection.insertNode(span);
  }
});
});

Foo bar span

<button>Italicise</button>


text:
Q: Can i use Activex with silverlight4? I need to use a ActiveX control in my silverlight application. After some research i found out a few ways in which a silverlight app can use ActiveX control
Use ActiveX control in a webpage along with silverlight plugin and use javascript for interaction between silverlight and activex.
Use a webbrowser control in silverlight 4 and load the webpage containing activex in webbrowser control.
Is there any other way that can utilized to embed activex control in silverlight app. I read somewhere that silverlight 4 has support for COM components. Can silverlight4 provide support for embedding activex control in a silverlight app.
Any help on this is highly appreciated and if some samples/documentation link is there that would be great.
Thanks in advance.

A: Silverlight does have support for COM automation servers like those used with Microsoft Office. It doesn't have general support for COM though and even if it did, ActiveX controls have very specific hosting requirements.
The idea of using the browser control is a possibility, but it will introduce some significant limitations. For one, you cant use the WebBrowser control in Silverlight unless you're running in out-of-browser mode which means your users would have to take steps to install the Silverlight application.
Additionally, the WebBrowser control (including any ActiveX controls it contains) will always render above your Silverlight content and won't be able to participate in transforms, animations, styling, etc. In other words it will stick out like a sore thumb.
What kind of control is it? Perhaps there is an alternative?


text:
Q: Optimize jQuery code? I just want me to know how is it possible to optimize this code snippet?
$('#datedebut').change(function() {
    if (Date.parse($('#datefin').val()) - Date.parse($(this).val()) <= 0) {
        alert('Impossible');
    }
});

$('#datefin').change(function() {
    if (Date.parse($(this).val()) - Date.parse($('#datedebut').val()) <= 0) {
        alert('Impossible');
    }
});

I think it is repeating the same thing, but I do not know how to find something that is optimized and of course simple.
Thank you in advance for your proposal.

A: If you don't mind looking up the elements again, you could simply do
$('#datedebut, #datefin').change(function() {
    if (Date.parse($('#datefin').val()) - Date.parse($('#datedebut').val()) <= 0) {
        alert('Impossible');
    }
});

Of course you can also select the elements once and keep references to them...
However, it is not optimization in terms of performance.

A: You can try this one:
<input type="text" id="datefin" onchange="validateChange()" />
<input type="text" id="datedebut" onchange="validateChange()" />

<script type="text/javascript">
    function validateChange(){
        if (Date.parse($('#datefin').val()) - Date.parse($('#datedebut').val()) <= 0) {
            alert('Impossible');
        }
    });
</script>


text:
Q: Array,pointer getting error [warning]Braces around scalar initializer here is my code:
int main(int argc, const char * argv[])
{

    int *A[3] = {{1,1,1,1},{1,1,1,1},{1,1,1,1}};
    int *B[4] = {{2,2,2},{2,22,2},{3,3,3},{3,3,3}};
    int *C[3];
    multiply(A, 1, 2, B, 3, 4, C);
    printf("A matrix:\n");
    printMatrix(A,3,4);
    printf("B matrix:\n");
    printMatrix(B,4,3);
    printf("C matrix:\n");
    printMatrix(C,3,3);
    printf("Hello, World!\n");
    return 0;
}

Its just int main part!
I'm getting the error

[warning]Braces around scalar initializer

in line:
int *A[3] = {{1,1,1,1},{1,1,1,1},{1,1,1,1}};

Why? Is it because of my mistake or compiler version difference?

A: A is an array of int *, not a 2D array.  Therefore, the initializers should be scalar values which are an int *.
If you have C99 or C11, you can rescue the code like this:
#include <stdio.h>

extern void printMatrix(int *x[], int y, int z);
extern void multiply(int *A[], int n1, int n2, int *B[], int n3, int n4, int *C[3]);

int main(void)
{
    int *A[3] = {(int []){1,1,1,1}, (int []){1,1,1,1}, (int []){1,1,1,1}};
    int *B[4] = {(int []){2,2,2}, (int []){2,22,2}, (int []){3,3,3}, (int []){3,3,3}};
    int *C[3];
    multiply(A, 1, 2, B, 3, 4, C);
    printf("A matrix:\n");
    printMatrix(A, 3, 4);
    printf("B matrix:\n");
    printMatrix(B, 4, 3);
    printf("C matrix:\n");
    printMatrix(C, 3, 3);
    printf("Hello, World!\n");
    return 0;
}

This uses C99 compound literals in the initializers.
However, you will need to be careful to allocate the right amount of space inside multiply() to store the data for each row in C.  You'll also have to know how to release the allocated space.


text:
Q: Не получается сделать выравнивание в header Я учу html и css, пока что сильно путаюсь в блоках. Пытаюсь сделать header сайта: с логотипом и панелью навигации. Всё получилось, кроме выравнивания.

*, *:after, *:before {
    box-sizing: border-box;
}

h1,
h2,
h3,
h4,
h5,
h6 {
    margin: 0;
}

p {
    margin: 0 0 10px;
}

body {
    margin: 0;

    /* Настройки шрифта */
    font-family: 'Nunito', sans-serif;
    font-size: 22px;
    font-weight: 400;
    color: #81858e;

    background-color: #fff;
}

/* Container
================== */
.container {
    width: 100%;
    min-width: 1600px;
    /* Выравнивание элемента по центру */
    margin: 0 auto;
}

/* Header
================== */
.header {
    width: 100%;
    padding: 0 160px;

    position: absolute;
    top: 0;
    left: 0;
    z-index: 1000;

}

.header__inner {
    display: flex;
    justify-content: space-between;
    padding: 35px 0;
    align-items: center;
}

/* Navigation
================== */
.nav {
    font-size: 22px;
    font-weight: 600;
    text-transform: uppercase;
    display: flex;
}

.nav__link {
    color: #bab8b8;
    margin-left: 70px;
    text-decoration: none;
    transition: color .2s linear;
}

.nav__link:hover {
    color: #3984f3;
}

.nav__sign-in {
    color: #3984f3;
    margin-left: 60px;
    text-decoration: none;
    border: 3px solid #3984f3 ;
    padding: 13px 16px;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="css/styles.css">
    <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;800&display=swap" rel="stylesheet">

                    Home
                    Video
                    Destinations
                    Booking
                    Sing In

A: Возможно не полностью понимаю вопрос,но если проблема в том,что кнопка sing in не ровно, то вот это добавь:
.header__inner nav{
  display:flex;
  align-items:center;
}


text:
Q: Modifying Hive script in SQL on AWS I need assistance with modifying a Hive script in SQL with the log file stored in AWS S3. We are given access to the web server log and Hive script. The code to return 'OS Version' is mentioned below:
-- Summary: This sample shows you how to analyze CloudFront logs stored in S3 using Hive
-- Create table using sample data in S3.  Note: you can replace this S3 path with your own.
CREATE EXTERNAL TABLE IF NOT EXISTS cloudfront_logs (
  DateLog DATE,
  Time STRING,
  Location STRING,
  Bytes INT,
  RequestIP STRING,
  Method STRING,
  Host STRING,
  Uri STRING,
  Status INT,
  Referrer STRING,
  OS STRING,
  Browser STRING,
  BrowserVersion STRING
)
ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.RegexSerDe'
WITH SERDEPROPERTIES (
  "input.regex" = "^(?!#)([^ ]+)\\s+([^ ]+)\\s+([^ ]+)\\s+([^ ]+)\\s+([^ ]+)\\s+([^ ]+)\\s+([^ ]+)\\s+([^ ]+)\\s+([^ ]+)\\s+([^ ]+)\\s+[^\(]+[\(]([^\;]+).*\%20([^\/]+)[\/](.*)$"
) LOCATION '${INPUT}/cloudfront/data';

-- Total requests per operating system for a given time frame
INSERT OVERWRITE DIRECTORY '${OUTPUT}/os_requests/' SELECT OS, COUNT(*) FROM cloudfront_logs WHERE DateLog BETWEEN '2014-07-05' AND '2014-08-05' GROUP BY OS;

The key script here that needs modification is the last two lines above:
'${OUTPUT}/os_requests/' SELECT OS, COUNT(*) FROM cloudfront_logs WHERE DateLog BETWEEN '2014-07-05' AND '2014-08-05' GROUP BY OS;

Now, we need to modify this script to return other queries, such as Location, Host, Method, BrowserVersion, or even combining two columns together, etc.
Any thoughts or ideas on how to do this? I just need assistance with the last two lines of the code above, I will do the working in AWS S3 myself. I understand some words need to be changed and specific functions need to be modified, but since I'm a total beginner at SQL, I am having a hard time with this!!
Thanks a lot for your help!
Details provided in the previous section


text:
Q: Finding General solution to pde $u_x^2+u_y^2=0$ $$u_x^2+u_y^2=0$$
I'm having trouble trying to find a general solution to the pde
What I did so far was I rewrote it as $(d_x + d_y)u^2$. So I need to find when $d_x =-d_y$ Im just really stuck on where to go. I found a general solution by trial and error to be $Ae^{k(x-y)}$ where $k$ is an element of the reals.

A: Seems that you misunderstood the ambiguous notation $u_x^2$ which meaning is usually $(u_x)^2$, not $(u^2)_x$. The sum of two positive reals is zero if and only if both are zero themselves. Therefore, for real $u$, the equation $u_x^2 + u_y^2 = 0$ implies that both partial derivatives vanish:
$$
u_x = 0 \qquad\text{and}\qquad u_y = 0 .
$$
Therefore, $u(x,y) = c_1$ is constant.

A: This is just a piece of cake.
$u_x^2+u_y^2=0$
$u_y^2=-u_x^2$
$u_y=\pm iu_x$
$u_y\mp iu_x=0$
Follow the method in http://en.wikipedia.org/wiki/Method_of_characteristics#Example:
$\dfrac{dy}{dt}=1$ , letting $y(0)=0$ , we have $y=t$
$\dfrac{dx}{dt}=\mp i$ , letting $x(0)=x_0$ , we have $x=\mp it+x_0=\mp iy+x_0$
$\dfrac{du}{dt}=0$ , letting $u(0)=f(x_0)$ , we have $u(x,y)=f(x_0)=f(x\pm iy)$


text:
Q: Folium (Maps with different data sources) I am starting to use Folium to generate interactive maps, of which I need to generate a map with markers from different data sources, that is, I have this:
#Data Sources

data1 = pd.read_excel('./data/Relevancia.xls')
data2 = pd.read_excel('./data/Zona.xls')

Data1 (Relevance) has the following structure (There are more than 500 data):
   lat         lon         event

--------------------------------------
-99.1483     19.2419      Bad
-99.2411     19.0561      Good
-99.5083     18.3361      Good
-99.2078     19.7153      Good
-99.9289     20.2961      Bad

Data2 (Zone) has the following structure (There are 100 data):
   x          y         locate

--------------------------------------
-99.1483     19.2419      CDMX
-99.2411     19.0561      Jalisco
-99.5083     18.3361      Edo Mexico
-99.2078     19.7153      Jalisco
-99.9289     20.2961      CDMX

What I require is to generate a map containing the two data sources. I have done this but with no expected results:
#Map
center = [20.5223, -99.8883]
map = folium.Map(location=center, zoom_start=8)
#Show Map
map

I generate the markers for data1:
Latitudes = data1['lat'].to_list()
Longitudes = data1['lon'].to_list()
Popups = data1['event'].to_list()

marker1 = []
for lat, long, pop in list(zip(Latitudes, Longitudes, Popups)):
    fLat = float(lat)
    fLon = float(long)
    if pop == "Malo":
        folium.Marker(
        location=[fLat,fLon],
        popup= pop,
        icon = folium.Icon(color = 'red', icon="remove-sign"))
    elif pop == "Bueno":
        folium.Marker(
        location=[fLat,fLon],
        popup= pop,
        icon = folium.Icon(color = 'green', icon="ok-sign"))

marker1.append([lat, long, pop])

I generate the markers for data2:
Latitudes1 = data2['x'].to_list()
Longitudes1 = data2['y'].to_list()
Popups1 = data2['locate'].to_list()

marker2 = []

for lat1, long1, pop1 in zip(Latitudes1, Longitudes1, Popups1):
    fLat1 = float(lat1)
    fLon1 = float(long1)
    folium.Marker(
        location=[fLat1,fLon1],
        popup= pop1,
        icon = folium.Icon(color = 'red', icon='home'))

marker2.append([lat1, long1, pop1])

I proceed to add attributes and markers to the map:
# Creamos dos grupos para los marcadores
feat1 = folium.FeatureGroup(name='Event')
feat2 = folium.FeatureGroup(name='Zone')

map.add_child(feat1)
map.add_child(feat2)

# I add the markers to the group they belong to, not to the map

marker1.add_to(feat1)
marker2.add_to(feat2)

# Now if I add the groups to the map

feat1.add_to(map)
feat2.add_to(map)

# In addition, layer control is added

folium.LayerControl().add_to(map)

#Show Map
map

The result is error:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-25-48f67a4d9c56> in <module>
      7
      8 # I add the markers to the group they belong to, not to the map
----> 9 marker1.add_to(feat1)
     10 marker2.add_to(feat2)

AttributeError: 'list' object has no attribute 'add_to'

Pass the markers to a list but maybe I am not understanding the concept well, any suggestions?

A: I could already solve. It was for issues of updating or reloading the map, where by rerunning the code, you can now see the markers separated by layers.


text:
Q: Jquery- Bainding Ctr+t is not working in Chrome? I was trying to bind Ctrl+t with some event.. the code is...
$(document).keydown(function(event) {
 if (event.ctrlKey && (event.which == 84)) {
 console.log('Ctrl+t was pressed');
    window.location.href ="www.example.com";
     return false;
}
  return true;//Pass the event on

});
it is working fine with Mozilla but, not in Crome . I am using current version of crome.

A: In Chrome4 the browser executes the default action (i.e. open new window,
open new tab and close tab/window) and does not execute the JavaScript
intercept (at all).
In IE7, IE8, FF3, FF3.5 and Chrome3 the intercept works fine.
http://code.google.com/p/chromium/issues/detail?id=33056


text:
Q: Which is the most professional way to combine functions I am taking a Java course and have a question about professionalism and efficiency.  I have read that it is best not to create temporary variables.
I have answered one of the quiz questions correctly as follows:
public void removeLowest(){

    remove(find(lowScore())); //doesn't really read very easily
}

The answer broke down each step like this:
public void removeLowest(){

    double low = lowScore();
    int lowScoreIndex = find(low);
    remove(lowScoreIndex);
}

Both versions accomplish the same task, but which is better?
Thanks.

A: In terms of speed efficiency both are the same. However the first one saves some memory instead of allocating memory to store the returned values in the stack. In general one doesn't worry on using stack memory in such cases for two reasons. First, the stack is flexible and can store huge amount of temp data. Second, for later review of the code, giving the returned value of functions a name, makes the code more readable for the author and for other people modifying the code.

A: It's a difficult question to answer, as there is some opinion for both arguments. However, if we look at the byte code for each:
Remove Lowest no intermediates
  public void removeLowest();
    Code:
       0: aload_0
       1: aload_0
       2: aload_0
       3: invokespecial #2                  // Method lowScore:()D
       6: invokespecial #3                  // Method find:(D)I
       9: invokespecial #4                  // Method remove:(I)V
      12: return

Lowest with Intermediates
  public void removeLowest2();
Code:
   0: aload_0
   1: invokespecial #2                  // Method lowScore:()D
   4: dstore_1
   5: aload_0
   6: dload_1
   7: invokespecial #3                  // Method find:(D)I
  10: istore_3
  11: aload_0
  12: iload_3
  13: invokespecial #4                  // Method remove:(I)V
  16: return

So you can see here that the intermediates do require more operations and storage. However, remember that the JVM is smart - so at runtime it will likely perform optimisations to this bytecode. Chances are if you call this a certain number of times it would inline the methods all into the same block anyway and remove the local storage.
In terms of your question, I'd go for readability over trying to write your code more compact at the cost of legibility. This is purely because that from your code -> byte code -> hotspot so much will happen to optimize this code that your main concern is writing the most maintainable code possible. As others have mentioned a few intermediate storage values that represent meaning cost very little in the bigger picture.

A: You are right - they both do the same thing!
However, the only difference is that by creating a variable, you also create a LocalVariableReference owned by the Thread running the method. This referenced to the returned Value returned by the inner method (such as the getLow() ). This means that naming the returned Values by declaring a variable for them takes more memory.
Nonetheless, it makes the code easier to read, and honestly, the space taken is very very minimal that it can be neglected!
(It's only a reference to a Value -- very small data taken)
Bottom line: Do what is more comfortable for you to read and debug.

A: For a small set of statements where variable names are intuitive even your first code example is perfectly fine. In second case the code is more verbose and easy to understand. (not saying verbosity == understanding).
Efficiency: you don't need to worry much about it at least in this particular case. correctly pointed out by Jim, JVM is more smarter than what we assume and may optimize where ever required. Also don't worry much about the space as long as you have put your variables/objects in correct scope. (method,class,instance). Remember when we say java program we are talking about managed code, So if you are favoring 1st for more efficiency I would say will not impact much.
Professionalism: here the second example is favored (as a practice demonstrator), There is one more aspect, maintainability. where similar usage may shine. (*maintainability doesn't only depend on this)
There are languages which are less verbose and still work well for large code bases.


text:
Q: Sqlite minutes conversion If I have a table with a column representing minutes, how can I convert those to hours and minutes?
For example, if I have in a cell "70" to be shown in the select "1h 10min", "60" to be shown "1h", etc.

A: I would suggest returning two derived fields in one query, the first one to get hours (through division), the second one to get minutes (through modulo operator). Try this:
select
    minutes / 60 as h,
    minutes % 60 as m

from
    minutes

And here's a SQLFiddle.
EDIT
The following shows how the result could be formatted, too. I also updated the fiddle:
select
    minutes / 60 as h,
    minutes % 60 as m,
    cast(minutes / 60 as text) || 'h ' || cast(minutes % 60 as text) || 'min' as formatted

from
    minutes

Maybe you want to add some conditions to only show hours or minutes greater 0.


text:
Q: Linear transformation defined on vector space of twice differentiable functions to $R^2$.How to determine whether it is one to one or onto Given that T is a linear transformation from V to $R^2$ where V be the vector space of all twice differentiable functions with the condition that $f''(0)-2f'(0)+f(0)=0$ and $T(f)=(f'(0),f(0))$
Then how to determine whether it is one one or onto
I was trying to find out the dimension of the vector space V
But I am unable to find an basis of V
How to proceed with this please help

A: It is not injective, consider a función whose Taylor series around zero has a not zero term of degree  3. But it is surjective, you can take any pair of numbers and construct the corresponding polynomial.

A: $T$ is not one-one because if $f$ is any polynomial of the form $x^2a(x)$, where $a(x)$ is some polynomial, then $f \in V$ and and $f'(x)=x^2a'(x)+2xa(x)$. Thus
$$T(f)=(0,0) \qquad \text{for all such } f(x).$$
$T$ is onto because if we take any $(a,b) \in \Bbb{R}^2$, then we can have $f(x)=\left(\frac{2a-b}{2}\right)x^2+ax+b \in V$ such that $T(f(x))=(a,b)$ because $f(0)=b$ and $f'(0)=a$.
For the dimension of $V$, note that $\{x^3,x^4, \ldots\} \subset V$ as all $f(x)=x^n$ (with $n \geq 3$) satisfy the given condition $f''(0)-2f'(0)+f(0)=0$. Furthermore the set is linearly independent. Thus $V$ is not finite dimensional.


text:
Q: Slow computer processing I run a 1.66 Ghz Duo Core with 512 RAM. I had rebuilt my OS about a month ago, started it as Windows XP SP2. then I updated it to Windows XP SP3 and installed all the latest updates about 90 of them. Since then my computer is processing slow, taking more time than usual to load on boot up, slower gaming applications etc.
I've been defragmenting on weekly basis, cleaning up temporary files etc. I guess if it is because of the updates that I've installed then how does it make your computer run slow than normal?

A: Simply put, you do not have enough memory to really run Windows XP well. Your are probably doing a lot of memory swapping to the hard drive, causing you slowness. New service packs, and a lot of (necessary security) updates can often make it worse.
I consider 1GB the minimum to run XP well, and 2GB to run Vista/Windows 7 well. I have had many people, who I know and have helped personally, change their minds about buying a new computer after simply upgrading the RAM (and cleaning the viruses out, in some cases).

A: Viruses and malware are usually the culprit.. follow these easy steps.. no need to upgrade your pc and spend money. it helped me alot too.. its not just cleaning files but also doing some tweaking in the performance configuration of the windows. You need to delete the bloatware, change the settings of notification, removing unwanted apps and disabling startup apps.
https://step-diychannel.tumblr.com/post/660627460767006720/speed-up-your-windows-for-free-and-very-easy-steps


text:
Q: vb user profile access restrictions I need help with creating a vb login app that has control access restrictions depending on the user profile. I'm already done with my login form
Public Class main
    Private Sql As New Control
    Private AuthUser As String
    Public form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    End Sub

    Private Sub main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Button1.Visible = False
    End Sub

    Public Function btn() As Boolean
        If form1.txtusername.text = "" Then
            Return False
        Else

        End If
        Return True
    End Function

End Class

A: The best and latest way to create and manage user profiles and to impose restrictions in .Net is using Membership Provider and role based authorization. Membership is used to provide authentication to the user and Role based authorization is used to authorize and restrict users to certain pages based on roles. Here is an MSDN reference for Membership.
Membership for VB.Net. That page also has description and implementation of Role based authorization.


text:
Q: Adding new value to nested observable array created with knockout.mapping plugin and knockoutjs So close to getting this to work as expected. I am getting data from a JSON request and then using the mapping plugin to map it. I want to add new values to a nested array on a click binding.
Right now in my code I am getting an error that addPoint is not defined.
View:

<button data-bind="click: saveChanges">Save Changes</button>

View Model
var viewModel = {};

$.getJSON('data-forecast-accuracy.json', function(result) {

    function mappedData(data) {
        this.val = data;
    }

    //override toJSON to turn it back into a single val
    mappedData.prototype.toJSON = function() {
       return parseInt(ko.utils.unwrapObservable(this.val), 10);  //parseInt if you want or not
    };

    var mapping = {
        'data': {
            create: function(options) {
            return new mappedData(options.data)
            }
        }
    }

    viewModel.stats = ko.mapping.fromJS(result, mapping);

    viewModel.addPoint = function() {
    this.stats.data.push(new mappedData(0));
    }

    viewModel.saveChanges = function() {

        var unmapped = ko.mapping.toJSON(viewModel.stats);
        //console.log(unmapped);
        $.post('save-changes.php', {data: unmapped})
        .success(function(results) { console.log("success")})
        .error(function() {  console.log("error"); })
        .complete(function() {  console.log("complete"); });
    }

    ko.applyBindings(viewModel);
});

The JSON:
[{"type":"spline","marker":{"symbol":"diamond"},"name":"Cumulative","data":[10,17,18,18,16,17,18,19]},{"type":"spline","marker":{"symbol":"circle"},"name":"Monthly","data":[10,22,20,19,8,20,25,23]}]
I was able to adjust this jsfiddle from an earlier response to add points to the single array. I need to find a way to implement this across the generated mapping.
http://jsfiddle.net/vv2Wx/1/

A: The reason you're getting "addPoint is not defined" error is because you're inside a template for a child property of the view model. Inside the template, the binding context is a stat object, not your view model.
Bottom line: Knockout is looking for a stat.addPoint function, which doesn't exist, so you get the error.
What you probably want to do is reference the parent binding context, your view model. In KO 1.3 beta, you can access parent binding contexts like this:
<button data-bind="click: $.parent.addPoint">Add Point</button>

If you're stuck on an old version of Knockout that doesn't provide access to the parent binding context, let me know, there are some additional options, such as making your view model globally accessible, then just binding to that fully qualified name.

A: Where you are binding against addPoint the context is an item in stats rather than your view model.
If viewModel has global scope, then you can do: click: viewModel.addPoint.  You will want to make sure that this is set correctly in your addPoint method.  Easiest way is to bind the method to your viewModel variable like:
viewModel.addPoint = function() {
    this.stats.data.push(new mappedData(0));
}.bind(viewModel);

If viewModel does not have global scope, then you can pass it in via templateOptions.  This would be like:

Then, call it like: <button data-bind="click: $item.add">Add Point</button>
Finally, if you are using KO 1.3 beta, then you can do: <button data-bind="click: $root.addPoint">Add Point</button>


text:
Q: Sage One API Error I am using the SageOne API PHP Library. It works fine, but I get an error if I try to use get or post.
The error is,

Only variables should be passed by reference sage.api.php on line 130

My get request code is
$client = new SageOne(SAGE_CLIENT_ID, SAGE_CLIENT_SECRET);
$client->setAccessToken("c7c7547xxxxxxxxxxxx8efa4f5df08f750df");
$data = array( );
$result = "";
$client = $client->get('/products', $data);

I don't know what's wrong.
Full Code
require 'sage.api.php';
define('SAGE_CLIENT_ID', "fa1e8c1b114347a356d2");
define('SAGE_CLIENT_SECRET', "faaa7b353521f823ba13e3a20e72dd057c3a5fd1");

$client = new SageOne(SAGE_CLIENT_ID, SAGE_CLIENT_SECRET);
$callbackURL = 'xxxxx/addonmodules.php?module=sageone';
// We need to build the authorise url and redirect user to authorise our app
if(!$_GET['code']){

    $authoriseURL = $client->getAuthoriseURL($callbackURL);

    // redirect user
    header("Location: ".$authoriseURL);

    exit;

// We now have the authorisation code to retrieve the access token
} else {

$accessToken = $client->getAccessToken($_GET['code'], $callbackURL);

$token= $accessToken['access_token'];
$end = 'public';
$data ='';
$result = $client->get($end, $data);
echo '<pre>';
print_r($result);

Code Snippets from sage.api.php
    class SageOne { ...

...
public function get($endpoint, $data=false){
        return $this->call($endpoint, 'get', $data);
    }
...

// error line 130 from this code

    private function buildSignature($method, $url, $params, $nonce){

        // uc method and append &
        $signature = strtoupper($method).'&';

        // percent encode bit of url before ? and append &
        $signature .= rawurlencode(array_shift(explode('?', $url))).'&';

        // percent encode any params and append &
        if (is_array($params)){

            // sort params alphabetically
            $this->ksortRecursive($params);

            // build query string from params, encode it and append &
            $signature .= str_replace(
                array('%2B'),
                array('%2520'),
                rawurlencode(http_build_query($params, '', '&'))
            ).'&';

        // params can be string
        } else {

            // build query string from params, encode it and append &
            $signature .= rawurlencode($params).'&';
        }

        // add 'nonce' - just use an md5
        $signature .= $nonce;

        // now generate signing key
        $signingKey = rawurlencode($this->signingSecret).'&'.rawurlencode($this->accessToken);

        // encode using sha 1, then base64 encode
        $finalSignature = base64_encode(hash_hmac('sha1', $signature, $signingKey, true));

        return $finalSignature;

    }

This is the shortest i can make to see all important code

A: This is due to trying to return the result of a function or method directly to another function or method... the result doesn't have a reference.
So, for example:
$obj->method(doSomething(), 'asdf', 'qwerty');

The error means you should assign the value of doSomething() before passing it.
$result = doSomething();
$obj->method($result, 'asdf', 'qwerty');

Also see: Only variables should be passed by reference

A: A function (in this case, $client->get()) can be defined to receive its parameters by reference. This means that it can modify those parameters directly. So if you call $client->get($a, $b), the function may alter the values of $a and $b.
Clearly, it can only alter the values of variables, so when a function receives a parameter by reference, you must pass it a variable, not a string, an integer, or a direct call to another function.
So if the function $client->get() receives its first parameter by reference, none of the following can work:
$client->get('string', $data);
$client->get(15, $data); // int
$client->get(other_function_call(), $data);
$client->get(12.5, $data); // float
$client->get(array(), $data);

You have to do this:
$a = 'string';
$client->get($a, $data);

Or $a = whatever, be it a string, an int, a function call. The point is (and this is stated quite clearly in the error message) that you must pass a variable. So save whatever you want to pass as a variable, then pass that.


text:
Q: Google Apps Script (Google Docs) - trigger on comment add or change? I am searching thorugh Google Apps Script documentation and I don't find how to make a trigger if comment is added or changed in a google document.
Under ElementType section (https://developers.google.com/apps-script/reference/document/element-type) I can see a property COMMENT_SECTION but also there is CommentSection element crossed in the description of the property. Does this mean that CommentSection class doesn't exist anymore?

A: To get the comments of a document you need to use the Advanced Drive Service (which you should enable in the Script Editor by selecting Resources > Advanced Google services... and then enable it in the Google Developers Console. Official Documentation)
Once enabled, you can retrieve the comments with the Drive.Comments.list. The list of properties of the comments can are documented here.
Here's an example:
function retrieveComments() {
  var comments;
    comments = Drive.Comments.list('docId');
    if (comments.items && comments.items.length > 0) {
      for (var i = 0; i < comments.items.length; i++) {
        var comment = comments.items[i];
        Logger.log('%s on %s by %s', comment.content, comment.createdDate, comment.author.displayName);
      }
    } else {
      Logger.log('No comments found.');
    }
}

Depending on your use case, you can store the commentId, createdDate and modifiedDate to evaluate if the have changed


text:
Q: how to number of rows affected by delete in sybase There is requirement that I want rows affected by delete operation in sybase any one if know please do let me know.
There is not sufficient documentation for sybase as I see.

A: According to : https://archive.sap.com/discussions/thread/3732742 did you checked this?

master.monProcessStatement.RowsAffected


text:
Q: How to click in the menu with google script I added a button in my google sheet and I assigned a script to it.
I want that if I click the button, my script automatically click one submenu in the default menu (in Add-ons).
How can I do it? I only see tutorial on how to to add a custom menu but not this.
Sorry if it's a silly question, this is my first script ever.
Thanks!


text:
Q: Check Box does'nt behaves back again ideally after behaving like radio button Below is the code where there are two conditions:

*

*On selection of Carrier "AT&T", only four checkbox willbe displayed,
Ear Piece, Leather Case, Car Charger and Label Only. Also, along
with this, the checkbox associated behaves as radio button, (This is
working fine).

*On selection of Carrier "Sprint", all the checkbox will be displayed
with normal behaviour of Checkbox.(This doesn't work with below
code), rather the output is, once anyof the checkbox is clicked to
mark check, it doesn't get unchecked on re-clicking it.

HTML

                  * Carrier Name
                    <select name="carriername" id="carriername">
                        <option value="">Please Select</option>
                        <option value="att">AT&T</option>
                        <option value="sprint">Sprint</option>
                    </select>

<fieldset id="accessories_block">
              <legend>Accessories</legend>

 Were there any accessories affected
                by the incident?

                  <input class="battery_ele hide_att" type="checkbox" name="accbattery" value="accbattery" />
                  Battery
                  <input type="checkbox" name="acchomecharger" value="acchomecharger"  class="homecharger_ele hide_att" />
                  Home Charger
                  <input type="checkbox" name="accearpiece" value="accearpiece" />
                  Ear Piece
                  <input type="checkbox" name="accsim" value="accsim" class="simcard simcard_ele hide_att"  />
                  SIM Card
                  <input type="checkbox" name="acclabel" value="acclabel"  />
                  Label Only

                <input type="checkbox" name="accbeltclip" value="accbeltclip" class="hide_att" />
                Belt Clip
                <input type="checkbox" name="acccase" value="acccase"  />
                Leather Case

                <input type="checkbox" name="accmemory" value="accmemory"  class="hide_att"/>
                Memory Card
                <input type="checkbox" name="acccharger" value="acccharger"  />
                Car Charger

            </fieldset>

Javascript

 $('document').ready(function(){
    var epaper = {
        carrier : 'nocarrier',
        carrier_name : $("#carriername"),
        hideATT :$('.hide_att'),
        OnCarrierChange: function(){
            epaper.carrier_name.change(function() {
                epaper.setAccessoryChosen();
            });
        },
        getSelCarr : function (){ return (epaper.carrier_name.val() != '') ? epaper.carrier_name.val() : epaper.carrier; },
            acc_blk_inp_chk : $('#accessories_block input[type=checkbox]'),
    convertCheckboxToRadio : function(){
        /*epaper.acc_blk_inp_chk.not($('#accessories_block input[type=checkbox]')).not(".simcard").removeAttr("checked");   */
        $('#accessories_block input[type=checkbox]').not($(this)).not(".simcard").removeAttr("checked");
    },
    setRadioBehave : function (){
        $('#accessories_block input[type=checkbox]').click(function(){
            epaper.convertCheckboxToRadio();
            $(this).attr('checked','checked');
        });
    },
    unsetRadioBehave : function (){
        $('#accessories_block input[type=checkbox]').click(function(){
            $(this).attr('checked','checked');
        });
    },
    setAccessoryChosen : function(){

        var carrier = '';
        var carrier = epaper.getSelCarr();
        $('#accessories_block input[type=checkbox]').unbind('click');
        epaper.acc_blk_inp_chk.attr("checked",false);
        if(carrier == "att"){
            epaper.hideATT.hide();
            epaper.setRadioBehave();

        } else {
            epaper.unsetRadioBehave();
            epaper.hideATT.show();
        }
    }
    };
epaper.OnCarrierChange();
});

Could someone help me with Point 2 resolution

A: It looks to me like your unsetRadioBehave function is always checking the box when it is clicked rather than toggling.
unsetRadioBehave : function (){
    $('#accessories_block input[type=checkbox]').click(function(){
        $(this).attr('checked','checked'); // <---- always checking the box
    });
},

You could unbind the original setRadioBehave behaviour to have the checkbox revert to it's natural state.
See the answer here: https://stackoverflow.com/a/210345/61470 for information on removing the event handler.

A: This worked for me:
setAccessoryChosen : function(){

        var carrier = '';
        var carrier = epaper.getSelCarr();
        $('#accessories_block input[type=checkbox]').unbind('click');
        epaper.acc_blk_inp_chk.attr("checked",false);
        if(carrier == "att"){
            epaper.hideATT.hide();
            epaper.setRadioBehave();

        } else {
            $(this).unbind('click');
            //epaper.unsetRadioBehave();
            epaper.hideATT.show();
        }
    }


text:
Q: Python - Create a join condition from lists I have two lists for two tables with their key columns
keycol1 = [col1,col2]
keycol2 = [col3,col4]

I want to frame a sql query with these two colums as join condition
for column1,column2 in zip(keycol1,keycol2):
    join = "table1."+ column1 + " = " + "table2." + column2 and
qry = "select * from table1 join table2 on " + join

But this gives me an extra and at the end. How to avoid it?
Expected query:
select * from table1 join table2 on table1.col1 = table2.col3 and  table1.col2 = table2.col4

A: Here is one way.
keycol1 = ['col1', 'col2']
keycol2 = ['col3', 'col4']

join = ' and '.join(['table1.{0} = table2.{1}'.format(c1, c2) \
                     for c1, c2 in zip(keycol1, keycol2)])

qry = "select * from table1 join table2 on " + join

# 'select * from table1 join table2 on table1.col1 = table2.col3 and table1.col2 = table2.col4'

Explanation

*

*Use a list comprehension with str.format to form each condition.

*Combine your conditions using ' and '.join().

A: You can also do it using the map function along with join:
keycol1 = ['col1', 'col2']
keycol2 = ['col3', 'col4']

for column1,column2 in zip(keycol1,keycol2):
    joined = " and ".join(map(lambda c: "table1."+ c[0] + " = " + "table2." + c[1], zip(keycol1, keycol2)))

qry = "select * from table1 join table2 on " + joined

print(qry)

Output:
select * from table1 join table2 on table1.col1 = table2.col3 and table1.col2 = table2.col4


text:
Q: iTunes COM interface - Cannot add song to library I'm trying to add a simple .mp3 file to the iTunes library but my program keeps crashing when I call AddFile(). However, when I call get_Tracks() it returns a valid pointer, so I suppose the pointer to IITLibraryPlaylist is valid. What am I doing wrong?
IiTunes* p_iTunes;
IITLibraryPlaylist* p_Library;
IITOperationStatus* status;
IITTrackCollection* iTrackCollection;

CoInitialize(0);
if (FAILED(CoCreateInstance(CLSID_iTunesApp, NULL, CLSCTX_LOCAL_SERVER, IID_IiTunes, (PVOID *)&p_iTunes))){
    p_iTunes->Release();
    CoUninitialize();
}
else{
    p_iTunes->get_LibraryPlaylist(&p_Library);

    p_Library->get_Tracks(&iTrackCollection); // This works, so I suppose p_Library is valid..
    long trackCount = 0;
    iTrackCollection->get_Count(&trackCount);

    p_Library->AddFile(L"C:\\asd\asd.mp3",&status); // crashes here
}

A: The problem is you pass WCHAR* instead of properly allocated BSTR and that leads to undefined behavior.
You should first allocate a BSTR using SysAllocString() (don't forget to release the string later) or better yet use a wrapper class like ATL::CComBSTR or _bstr_t for managing BSTR lifetime.


text:
Q: Spark: Optimal use of executors I am running a Spark application with 5 executors with 5 cores per executor.
However, I have noticed that only a single executor does most of the work (i.e most of the tasks are done there). The jobs that I am running are highly parallel (20 partitions or greater). How do you explain this behavior?
Even if I decrease the number of cores per executor, results to just running less tasks on that single executor at the same time.
Should I limit the memory per executor so that more executors are used (just in case the whole data fits on a single executor)?

A: Just to add my two cents, for people facing this issue in future. This kind of issue usually arises as a result of skewed partition size of the RDD/Dataframe. To debug the problem, you can check the partition sizes of the RDD, to find out if there is any outlier there. And if there is one, you can see the elements in that big partition to get a sense of what's going on.
A similar issue is addressed in detail in this stackoverflow question.


text:
Q: Blazor Server NavManager NavigateTo cshtml I have just started on my first site using Blazor (server side).
Under normal circumstances my site navigates ok. I use a button click event to call an injected NavManager.NavigateTo while navigating between Blazor (.razor) pages.
e.g. _NavManager.NavigateTo("/mypage");   - Navigation is OK
When I try to navigate to the default login pages (cshtml)
_NavManager.NavigateTo("Identity/Account/Login");

or
_NavManager.NavigateTo("/Identity/Account/Login");
I get a message 'Sorry, there's nothing at this address.' . The browser address bar is filled in correctly. If I hit enter on the address bar then the correct page loads.
Using a <a hyperlink navigates OK.
To fix this I tried
_NavManager.NavigateTo("Identity/Account/Login",true);

this works and opens the page OK. Unfortunately if I then hit the back button it loads my original page but at the bottom of the page I get
'An error has occurred. This application may no longer respond until reloaded. Reload'
when I investigate the page I get
blazor.server.js:19 [2021-03-03T14:01:43.181Z] Error: The list of component records is not valid.
e.log @ blazor.server.js:19
blazor.server.js:1 Uncaught (in promise) Error: Invocation canceled due to the underlying connection being closed.
at e.connectionClosed (blazor.server.js:1)
at e.connection.onclose (blazor.server.js:1)
at e.stopConnection (blazor.server.js:1)
at e.transport.onclose (blazor.server.js:1)
at e.close (blazor.server.js:1)
at e.stop (blazor.server.js:1)
at e.<anonymous> (blazor.server.js:1)
at blazor.server.js:1
at Object.next (blazor.server.js:1)
at a (blazor.server.js:1)

I'm just wondering if anyone can point me in the right direction
Interestingly if I hit refresh, it all works Ok so I'm guessing its something (like it suggests) to do with the client dropping a connection?
Thanks


text:
Q: Solving a system of linear ODEs using variables I am trying to solve the following system of linear ODEs.
$\dfrac{dx}{dt} = x-4y$
$\dfrac{dy}{dt} = 4y$.
The initial conditions are $x(0) = -1$ and $y(0) = -3$.
I have tried letting:
$u_1 = x \implies u_1' = u_2$
$u_2 = x' \implies u_2 = u_1 - u_3$
$u_3 = y \implies u_3' = u_4$
$u_4 = y' \implies u_4 = 4u_3$
I also know that $y' = x - x'$ however I am unsure how to tie all of this information together. Any help is appreciated. Thanks in advance.

A: $$ \frac{dy}{dt} = 4y \rightarrow y = C_1e^{4t} $$
So then we can substitute into earlier where we have
$$ \frac{dx}{dt} = x - 4y \rightarrow \frac{dx}{dt} = x - 4C_1e^{4t} $$
Now the equation
$$ \frac{dx}{dt} = x - 4C_1e^{4t}$$
Is a standard first order linear ODE which can be written as
$$ \frac{dx}{dt} - x = - 4C_1e^{4t} $$
By choosing the integration factor $e^{-t}$ It can be seen that
$$ xe^{-t} = -4C_1 \int e^{-t}e^{4t} dt $$
Yielding
$$ x = C_2e^{t} - 4C_1 e^{t} \int e^{3t} dt $$
Thus the final solution is:
$$ x = C_2e^{t} - \frac{4C_1}{3} e^{4t} $$
$$ y = C_1e^{4t} $$

A: We have
$$ y' = 4y \implies y(t) = C e^{4t} \quad \text{where} \quad C \in \mathbb{R}$$
This implies
$$ x' = x -4y = x - 4 C e^{4t} $$
which is a first order linear equation. Now you just have to solve
$$ x' -x = 4 C e^{4t} $$
which you've most likely seen.

A: Here is another way, let $A=\begin{bmatrix} 1 & -4 \\ 0 & 4\end{bmatrix}$ and
note that $A (1,0)^T = (1,0)^T$ and $A(4,-3)^T = 4 (4,-3)^T$.
Hence starting from an initial condition $(1,0)^T$, the solution will be
$t \mapsto e^t (1,0)^T$ and starting from $(4,-3)^T$ the solution will be
$t \mapsto e^{4t} (4,-3)^T$.
Now write $(-1,-3)^T$ as a linear combination of $(1,0)^T$, $(4,-3)^T$.


text:
Q: Display both Markers and Polygon (javascript api v3) I am trying to show markers that fall within a state boundary.  I am working with the code provided below (which is working great for the markers) but am having trouble getting it to work when I add to it an array of polygon coordinates for the state boundary polygon.  Any help on how to add an array of coordinates for a single polygon would be greatly appreciated.  Thank You.

<title>Web Map of Offices</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

 `enter code here`

A: *

*you don't want to create a new map for the FusionTablesLayer, you want to add it to your existing map.

*you can't have extraneous white space (the extra space at the end of the table id).

Inside your initialize function (at the end, or at least after you have created the "map", add (to display "West Virginia" only, with the styling in the FusionTables UI):
    var layer = new google.maps.FusionTablesLayer({
        query: {
            select: 'geometry',
            from: '18_J2uuiZRLon48Lc6bclZ0ckHanbKZB9qg319KV3',
            where: "STATE_NAME CONTAINS IGNORING CASE 'West Virginia'"
        },
        options: {
            styleId: 2,
            templateId: 2
        }
    });
    layer.setMap(map);

Working snippet:

function initialize() {
    var myLatlng = new google.maps.LatLng(38.895308, -80.304565);
    var myOptions = {
        zoom: 7,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    lats = new Array(38.3213861, 38.4579809, 38.8014155, 38.9875643, 38.8022869, 39.2844968, 39.4850848, 39.6078332, 39.0194418, 38.9399985, 40.065598, 39.2648469, 40.4019707, 39.5641071, 37.7924745, 37.3602823, 37.8212103, 38.304694, 38.401603, 37.848631, 37.5848663, 39.4964831, 39.401424, 39.3356127, 37.4360439, 38.0121122, 39.0713631);
    longs = new Array(-81.5816714, -81.931094, -81.3513514, -81.9755644, -81.7392611, -80.2709958, -80.1425781, -79.9180457, -80.4194388, -79.8539348, -80.722355, -81.5595981, -80.5868196, -80.9960285, -81.1929363, -81.0978385, -80.4235672, -80.830412, -82.492229, -81.993392, -81.3812904, -77.9541342, -79.0133107, -78.7457004, -81.6041864, -81.1274056, -78.9388241);
    hovertitle = new Array("Charleston WVDRS", "Teays Valley WVDRS", "Spencer WVDRS", "Point Pleasant WVDRS", "Ripley WVDRS", "Clarksburg WVDRS", "Fairmont WVDRS", "Morgantown WVDRS", "Weston WVDRS", "Elkins WVDRS", "Wheeling WVDRS", "Parkersburg WVDRS", "Weirton WVDRS", "Sistersville WVDRS", "Beckley WVDRS", "Princeton WVDRS", "Lewisburg WVDRS", "Summersville WVDRS", "Huntington WVDRS", "Logan WVDRS", "Mullens WVDRS", "Martinsburg WVDRS", "Keyser WVDRS", "Romney WVDRS", "Welch WVDRS", "Oak Hill WVDRS", "Moorefield WVDRS");
    htmlAll = new Array("
Charleston WVDRS

4701 MacCorkle Avenue SE
Charleston, WV 25304
304-356-
304-926-(Fax)

Get Directions
",
        "
Teays Valley WVDRS

115 Liberty Square
Hurricane, WV 25526
304-760-(Phone)
304-759-(Fax)

Get Directions
",
        "
Spencer WVDRS

321 Market Street
Spencer, WV 25276
304-927-(Phone)
304-927-(Fax)

Get Directions
",
        "
Point Pleasant WVDRS

209 5th Street
Point Pleasant, WV 25550
304-675-(Phone)
304-675-(Fax)

Get Directions",
        "
Ripley WVDRS

206 Stone Drive
Ripley, WV 25271
304-373-(Phone)
304-373-(Fax)

Get Directions",
        "
Clarksburg WVDRS

107 Cambridge Place
Bridgeport, WV 26330
304-842-(Phone)
304-842-(Fax)

Get Directions",
        "
Fairmont WVDRS

Veterans Square
320 Adams Street, Suite 106
Fairmont, WV 26554
304-367-(Phone)
304-367-(Fax)

Get Directions",
        "
Morgantown WVDRS

1415 Earl Core Road
Morgantown, WV 26505
304-285-(Phone)
304-285-(Fax)

Get Directions",
        "
Weston WVDRS

306 Market Place Mall
Weston, WV 26451
304-269-0547(Phone)
304-269-0427(Fax)

Get Directions",
        "
Elkins WVDRS

1025 North Randolph Avenue
Elkins, WV 26241
304-637-0205(Phone)
304-637-0209(Fax)

Get Directions",
        "
Wheeling WVDRS

Central Union Building
40 14th Street, Suite 103
Wheeling, WV 26003
304-238-1093(Phone)
304-238-1096(Fax)

Get Directions",
        "
Parkersburg WVDRS

State Office Building
400 5th Street
Parkersburg, WV 26101
304-420-4580(Phone)
304-420-4583(Fax)

Get Directions",
        "
Weirton WVDRS

100 Municipal Plaza, Suite 200
Weirton, WV 26062
304-723-5311(Phone)
304-723-5318(Fax)

Get Directions",
        "
Sistersville WVDRS

714 Wells Street
Sistersville, WV 26175
304-652-2354(Phone)
304-652-2359(Fax)

Get Directions",
        "
Beckley WVDRS

800 New River Town Center
Beckley, WV 25801
304-256-6900(Phone)
304-256-6903(Fax)

Get Directions",
        "
Princeton WVDRS

195 Davis Street
Princeton, WV 24739
304-425-1256(Phone)
304-487-2631(Fax)

Get Directions",
        "
Lewisburg WVDRS

777 North Jefferson Street, Suite 105
Lewisburg, WV 24901
304-647-7515(Phone)
304-647-7518(Fax)

Get Directions",
        "
Summersville WVDRS

830 Northside Drive, Suite 113
Summersville, WV 26651
304-872-0813(Phone)
304-872-0518(Fax)

Get Directions",
        "
Huntington WVDRS

2699 Park Avenue, Suite 200
Huntington, WV 25704
304-528-5585(Phone)
304-528-5591(Fax)

Get Directions",
        "
Logan WVDRS

216 Dingess Street
Logan, WV 25601
304-792-7060(Phone)
304-792-7062(Fax)

Get Directions",
        "
Mullens WVDRS

316 Howard Avenue
Mullens,WV 25882
304-294-5653(Phone)
304-294-5655(Fax)

Get Directions",
        "
Martinsburg WVDRS

489 Mid Atlantic Parkway, Suite 2
Martinsburg, WV 25404
304-267-0005(Phone)
304-267-0007(Fax)

Get Directions",
        "
Keyser WVDRS

67 North Tornado Way
Keyser, WV 26726
304-788-2313(Phone)
304-788-6389(Fax)

Get Directions",
        "
Romney WVDRS

24948 Northwestern Pike
Romney, WV 26757
304-822-3957
304-822-7417

Get Directions",
        "
Welch WVDRS

110 Park Avenue
Welch, WV 24801
304-436-3175(Phone)
304-436-3176(Fax)

Get Directions",
        "
Oak Hill WVDRS

549 Mall Road
Oak Hill, WV 25901
304-465-3025(Phone)
304-465-3069(Fax)

Get Directions",
        "
Moorefield WVDRS

151 Robert C. Byrd
Industrial Park Road, Suite 3
Moorefield, WV 26836
304-538-2701(Phone)
304-538-2718(Fax)

Get Directions");

    markers = new Array();
    for (var i = 0; i < 30; i++) {
        myLatlng = new google.maps.LatLng(lats[i], longs[i]);

        var contentString = htmlAll[i];
        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        var marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            html: htmlAll[i],
            title: hovertitle[i]
        });

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.setContent(this.html);
            infowindow.open(map, this);

        });
    }
    var layer = new google.maps.FusionTablesLayer({
        query: {
            select: 'geometry',
            from: '18_J2uuiZRLon48Lc6bclZ0ckHanbKZB9qg319KV3',
            where: "STATE_NAME CONTAINS IGNORING CASE 'West Virginia'"
        },
        options: {
            styleId: 2,
            templateId: 2
        }
    });
    layer.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
html {
    height: 100%
}
body {
    height: 100%;
    margin: 0px;
    padding: 0px
}
#map_canvas {
    height: 100%
}


text:
Q: python iteration through list of list I have list a with below elements :
[[('433318', 0.7064461851335214), ('433363', 0.6709502341952089)],
 [('433395', 0.6988424611161282), ('433400', 0.6794787567547861)],
 [('433395', 0.6871546406771576), ('433363', 0.653218445986381)]]

Now I wanted retrieve the elements into a new list b which will have
['433318','433363','433395','433400','433395','433363']
a[0][0][0] gives '433318'
a[0][1][0] gives '433363'

But I am looking for a generic way (may be in a loop which iterates through the entire list) and gives me the desired result ?

A: Use a list comprehension:
l = [[('433318', 0.7064461851335214), ('433363', 0.6709502341952089)],
[('433395', 0.6988424611161282), ('433400', 0.6794787567547861)],
[('433395', 0.6871546406771576), ('433363', 0.653218445986381)]]

[y[0] for x in l for y in x]

A: Using a list comprehension is best, but it may be helpful to see how a regular loop version would look like:
my_list = [[('433318', 0.7064461851335214), ('433363', 0.6709502341952089)],
[('433395', 0.6988424611161282), ('433400', 0.6794787567547861)],
[('433395', 0.6871546406771576), ('433363', 0.653218445986381)]]

result = []
for inner_list in my_list:
    for inner_tuple in inner_list:
        result.append(inner_tuple[0])