Q: How convert 2 string columns (date and time) to one timestamp i have table with two columns (both string):
| Dates    | Times          |

| -------- | -------------- |

|20210401  | 121012         |

|20210401  | 121024         |

And I would like to combine these columns into one in timestamp format:
YYYY-MM-DD HH:MM:SS

I tried this, but it is wrong:
CONVERT(datetime, CONVERT(CHAR(8), DATES, 112) + ' ' + CONVERT(CHAR(6), TIMES, 108))

A: SQL Server allows you to add datetime values, so that is a convenient data type for this purpose.
It is easy to convert the date to a datetime -- it is in a standard format.
The time column is tricker, but you can add in ':' for the conversion:
select v.*,
       convert(datetime, v.date) + convert(datetime, stuff(stuff(time, 5, 0, ':'), 3, 0, ':'))
from (values ('20210401',  '121012')) v(date, time);

A: convert(datetime, DATES + ' ' + substring(TIMES, 1, 2) + ':' + substring(TIMES, 3, 2) + ':' + substring(TIMES, 5, 2) , 121)


Q: How can I give my Flask Apache WSGI App permission to write/append to a file? I am writing a small Flask web-application hosted on an Apache Server running Ubuntu 14. There is a feedback section on the website where one can visit and submit a feedback message which will then be sent to the server, and appended to a text file. Here is the new_feedback method:
def new_feedback(name, message):
    file = open('feedback.txt', "a")
    file.write(name + '  wrote:  ' + message + '\n'+'***********************************'+'\n\n')
    file.close()

However, when the method is called, the Apache server gives the following error in the error.log file.
File "/var/www/FlaskApp/FlaskApp/feedback.py", line 2, in new_feedback
[Sat Dec 05 13:15:02.825594 2015] [:error] file = open('feedback.txt', "a")
[Sat Dec 05 13:15:02.825601 2015] [:error] IOError: [Errno 13] Permission denied: 'feedback.txt'

One way I have attempted to debug this, is to run it locally, which has absolutely no issues on my Windows computer. In other words, the logic seems to be alright. Thanks!


Q: Wordpress - create a page with custom URL I have a Wordpress page /users and it displays a list of all users created. Each user has a link to its profile page. What I need to do is create that page. I want it to go like this /users/{user_id}-{first_name}-{last_name}, for example - /users/1-john-doe. I have a template for /users and also for profile pages. Question - how do I properly make a page with that profile template so that it would have the url described above? The page does not need to select the user automatically, it needs to pass the user slug so I can read it in that page and query for that user (as a variable or something).
Thanks.

A: What you are looking for is the WordPress Rewrite API.
This allows you to define a new "endpoint" for your URL's, and allows you to pick up the variable from the URL via built-in WordPress functionality.
A great article on it can be found here: Custom Endpoints


Q: Pass javascript variable to php with ajax , Nothing result? MY js page :
$m = 77;
var xhr = new XMLHttpRequest();
xhr.open("POST", "try.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("m=" + escape(m));

php page :
$var = $_POST['m'];
echo $var;

When I call php page nothing happens! can you help me?

A: Just you need to change variable m to get expected output
    m = 77; // here what i have changed from $m to m

    var xhr = new XMLHttpRequest();

    xhr.open("POST", "try.php", true);

    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhr.send("m=" + escape(m));

A: You have two problems.
Variable names
At the top of your code you create a variable called $m but later you try to read m.
This will throw a ReferenceError which you would have spotted if you had looked at the Console in your browser's Developer Tools
You never look at the response
Once you fix that error, your code will make the request … but you don't do anything with the response.
You should add a load event listener for that.
function alert_response() {
    alert(this.responseText);
}

xhr.addEventListener("load", alert_response);

Asides

*

*escape is deprecated because it doesn't work properly. Use encodeURIComponent instead.

*PHP sticks a text/html content-type on the response by default, by echoing out user input without modification or filtering, you are vulnerable to XSS attacks. Take steps to defend yourself.


Q: Can't close frame in java? Hi guys I am writing a little program in java and it's my first try at anything with an interface/picture.
It makes the frame for me but when I click the close button X, it doesn't close it just treats it like nothing happened...any ideas?
class Graph extends Canvas{

    public Graph(){
        setSize(200, 200);
        setBackground(Color.white);
    }

    public static void main(String[] args){

        Graph gr = new Graph();

        Frame aFrame = new Frame();
        aFrame.setSize(300, 300);
        aFrame.add(gr);
        aFrame.setVisible(true);

    }

A: Is that java.awt.Frame? I think you need to explicitly add the handler for so:
frame.addWindowListener(new WindowAdapter(){
  public void windowClosing(WindowEvent we){
    System.exit(0);
  }
}

I used this source for so.
If it were swing it would be something like jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

A: add aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

A: class Graph extends Canvas{

public Graph(){
    setSize(200, 200);
    setBackground(Color.white);
    addWindowListener(
              new java.awt.event.WindowAdapter() {
                public void windowClosing( java.awt.event.WindowEvent e ) {
                  System.out.println( "Closing window!" );
                  dispose() ;
                  System.exit( 0 );
                }
                }
            );
}

public static void main(String[] args){

    Graph gr = new Graph();

    Frame aFrame = new Frame();
    aFrame.setSize(300, 300);
    aFrame.add(gr);
    aFrame.setVisible(true);

}


Q: Using Angular 1.2 and Animate.css for loading animation? I'm trying to get a page to animate in on load using Angular 1.2 and Animate.css.
Here's the Plunker: http://plnkr.co/edit/oDiDfRCO2Msc0StNrtqH
I'd like the background to crossfade in and the yellow menu on the right side to slide in from the right.
In main.html:

    <my-Background></my-Background>

      <my-Menu id="menu"></my-Menu>

In main.css:
.menu-container.ng-enter {
    animation:3s fadeInRightBig;
}

.background-container.ng-enter {
    animation:3s fadeInDown;
}

The animations defined in main.css don't seem to get fired. I'm pretty sure its due to the order and/or timing of css being loaded although I might be dealing with more than one issue.
What's the "right" way to ensure everything, from an animation standpoint, is loaded and ready in order to make the animations work on load?

A: Have you looked at something like an HTML5 loader to load your initial assets when the DOM is loaded.  There is a jQuery plugin, I know it is not Angular and another library, but it may help your order of operation.
http://gianlucaguarini.github.io/jquery.html5loader/

A: You can try nganimate , an easy documentation for you to refer
https://docs.angularjs.org/api/ngAnimate


Q: Python Code for Hypothesis Testing I was going through some programming assignment for detection and estimation theory.
But I do not know how to proceed.The question is as follows:
Consider the location testing with Gaussian errors binary hypothesis testing problem with $µ_{0} = 0$
and $µ_{1} = 1$. For each possible value of SNR $ d ∈ \{0, 0.1, 0.2, . . . , 1.9, 2\} (recall: d := (µ1 − µ0 )/σ)$, and
each possible value of prior $π_{0} ∈ \{0.1, 0.2, 0.3, 0.4\}$,you need to find the following
(a) Generate $10^5$ independent samples of the observation Y , according to the Bayes prior $π_{0}$ and
$1 − π_{0}$ on the two hypotheses.
I will be thankful if anyone give me some idea.


Q: setState doesnt render extra one time? Code A:
componentDidMount(){
  this.dateString = this.props.navigation.getParam('dateString', moment());
}

Code B:
state = { dateString: moment() }

componentDidMount(){
  const dateString = this.props.navigation.getParam('dateString', moment());

  this.setState({ dateString })
}

dateString is a parameter passed from previous screen. I've console.log in render() and found that they appeared to be exactly the same number of times? I was expecting Code B to render one extra time since it uses setState?
Which way of above is a better approach?

A: Not sure if this is the case in this your specific case, but: React may batch multiple setState calls together. So even if you have multiple async setState calls, there might only one (re-)render. So you shouldn’t rely on the number of calls to render

A: Check the value of this.props.navigation.getParam('dateString', moment()) in render and componentDidmount().
If both values are same it wont trigger a re-render as react re-render the components only if state change there if you made it PureComponent.
In this jsfiddle you can try running the code by changing Pure and normal component and can see the difference.

A: Try to put in the Code B the state inside constructor() method like this:
constructor(){
    super();
    this.state = { dateString: moment() }
}

I don't usually use to put state floating in the class, I always put him in the constructor.


Q: Add color to rows when a value is in a cell I am trying to figure out how to make numerous cells change color (red) when one cell has a value in it. Basically it is when money is owed I want the whole row to turn red so it stands out to me. I have it set right now that the cell with the money value turns red, but I want that whole row to do it. Any help is appreciated.
Thank you

A: here is an example where only the cells in question get highlighted:

And here is one where the row gets highlighted:

Look at the difference in the Applies to columns, one reads =$E$1:$E$14 and the other =$A$1:$E$14


Q: Найти точки на расстоянии от маршрута Всем доброго времени суток.
Есть задача вывести точки на N - расстоянии от заданного маршрута.
Изначально имеем выгрузку с каким-то числом точек, они могут находится по всему миру, нужно сделать выборку по этим точкам исходя построенного из маршрута.
Пример
Вопрос: что использовать для поиска нужных точек?

A: На данный момент подобных методов в API Яндекс.Карт не реализовано. Проверить можно только попадание точек в полигон. И на это в документации Яндекса есть готовый пример.
Однако преобразование линии в полигон для Яндекс.Карт само по себе является непростой задачей. Необходимо учесть огрубление окружностей на углах-поворотах, конечных точках маршрута, возможные пересечения линий и т.п. Проводить расчет на плоскости также будет неверным решением, поскольку геодезические линии между точками, а значит и углы в начальной и конечной точке участка маршрута могут сильно отличаться от результатов таких вычислений при значительных расстояниях.


Q: Scroll issue in mootools (In Firefox it's okay but Chrome giving some issue) I have set following code to create a floating navigation menu. It works fine in Firefox but Chrome has some issue. It keep resetting when I manually scroll the bar to it's threshold.
    var nav = $$('#navigationBar');
var navCord = nav.getCoordinates();
var navHomeY = navCord[0].top;
var isFixed = false;
var $w = $(window);

$w.addEvent('scroll', function(){

    var scrollTop = $w.getScroll().y;
    console.log(scrollTop + ' and ' + navHomeY);
    var shouldBeFixed = scrollTop > navHomeY;
    if (shouldBeFixed && !isFixed){
        console.log("fix it now");
        nav.setStyles({
            position: 'fixed',
            top: 0,
            left: navCord[0].left,
            width: navCord[0].width
        });
        isFixed = true;
    }
    else if (!shouldBeFixed && isFixed)
    {
        nav.setStyles({
            position: null,
            top: null,
            left: null,
            width: null
        });
        isFixed = false;
    }
});

});

Here is the console.log output from Chrome.
0 and 25 index.php:532
10 and 25 index.php:532
20 and 25 index.php:532
41 and 25 index.php:532
fix it now index.php:537
0 and 25 index.php:532 (PROBLEM: scrollTop reset happen)

Here is the console.log output from Firefox.
9 and 25
17 and 25
26 and 25
fix it now
33 and 25

In short, in Firefox scrollTop behave nicely and doesn't reset to 0 where as in Chrome it does.


Q: EJB - How to use CRUD code with multiple Persistence Units I would like to equip my EJBs with CRUD methods.
I have many entities and multiple persistence units.
I want to implement my CRUD methods once and invoke them on different persistence units.
I tried to achieve this using inheritance, but it isn't working.
The CRUD class is:
public class FormEBean<T> {

    protected EntityManager em;

    public EntityManager getEm() {
        return em;
    }

    public void setEm(EntityManager em) {
        this.em = em;
    }

    public String create(T entity) {
        try {
            em.persist(entity);
            em.flush();
            return null;
        } catch (Exception ex) {
            return ex.getLocalizedMessage();
        }
    }

    public void create(List<T> entityList) {
        for (T entity : entityList) {
            em.persist(entity);
        }
    }

    public void edit(T entity) {
        em.merge(entity);
    }

    public void edit(Set<T> entitySet) {
        Iterator<T> it = entitySet.iterator();
        while (it.hasNext()) {
            T entity = it.next();
            em.merge(entity);
        }
    }

    public void remove(T entity) {
        em.remove(em.merge(entity));
    }

    public void remove(T[] listaDaRimuovere) {
        for (T entity : listaDaRimuovere) {
            em.remove(em.merge(entity));
        }
    }

    public void remove(List<T> listaDaRimuovere) {
        for (T entity : listaDaRimuovere) {
            em.remove(em.merge(entity));
        }
    }
}

So I tryed in this way:
@Stateless
@Remote(MyEBeanRemote.class)
public class MyEBean extends FormEBean<MyEntityClass> implements MyEBeanRemote {

    @PersistenceContext(unitName = "siat-ejbPU")
    private EntityManager em;

    // code here
}

Even if I haven't got any error, the CRUD functions have no effect on my DataBase.
Instead if I insert them directly into MyEBean it behaves as expected.
I don't want to use @PersistenceContext(unitName = "siat-ejbPU") in the FormEBean, because EJBs could use different persistence units.
Is there a way to solve this problem?
Is there a pattern I can use to reuse my code?
Edit:
The aim of this question is finding a solution that maximizes CRUD code reuse in EJBs belonging to different EJB modules and having different persistence units.
Using generic methods in a stateless session bean seems like a good solution, but only for reusing CRUD code for EJBs in the same persistence unit.
What solution could be persistence unit independent (if it exists)?

A: Hi you can use setter method:
@Stateless
@Remote(MyEBean.class)
public class MyEBean extends FormEBean implements MyEBeanRemote {

    final Logger logger = LoggerFactory.getLogger(MyEBean.class);

    @PersistenceContext(unitName = "siat-ejbPU")
    @Override
    public void setEmCrud(EntityManager em) {
        super.setEmCrud(em)
    }

Worked for me.

A: You need to make your CRUD methods generic (create/edit/remove).
The class named FormEBean should NOT be generic.
If you make the methods generic in stead of the class, you can implement them once and use them with any entity class.  Generic crud methods might look something like this:
public <T> T create(T someEntity) {
    em.persist(someEntity);
    return someEntity;
}

public <T> void create(Collection<T> entities) {
    for (T entity : entities) {
        em.persist(entity);
    }
}

public <T> void edit(T entity) {
    em.merge(entity);
}

public <T> void edit(Collection<T> entities) {
    for (T currentEntity : entities) {
        em.merge(currentEntity);
    }
}

Put those in your session bean and use them anywhere to operate on any entity.
/**
 *  Example managed bean that uses our
 *  stateless session bean's generic CRUD
 *  methods.
 *
 */

class ExampleManagedBean {

    @EJB
    MyCrudBeanLocal crudBean;

    public void createStuff() {
        // create two test objects
        Customer cust   =  createRandomCustomer();
        FunkyItem item  =  createRandomItem();
        // use generic method to persist them
        crudBean.create(cust);
        crudBean.create(item);
    }
}

This answer does exactly what I describe and provides example code:

*

*EJB 3 Session Bean Design for Simple CRUD
Another example:

*

*EJB with Generic Methods

A: I found a solution that solves the problem.
It's based on jahroy's answer, but uses inheritance to deal with multiple persitence units.
The common code is a base class (not generic but with generic methods):
    public class FormEBean {

        final Logger logger = LoggerFactory.getLogger(FormEBean.class);

        protected EntityManager emCrud;

        public EntityManager getEmCrud() {
            return emCrud;
        }

        public void setEmCrud(EntityManager em) {
            emCrud = em;
        }

        public <T> String create(T entity) {
            String exception = null;
            try {
                emCrud.persist(entity);
                emCrud.flush();
            } catch (Exception ex) {
                //ex.printStackTrace();
                exception = ex.getLocalizedMessage();
            }
            return exception;
        }

        public <T> void create(List<T> entityList) {
            for (T entity : entityList) {
                emCrud.persist(entity);
            }
        }

        public <T> void edit(T entity) {
            emCrud.merge(entity);
        }

        public <T> void edit(Set<T> entitySet) {
            Iterator<T> it = entitySet.iterator();
            while (it.hasNext()) {
                T entity = it.next();
                emCrud.merge(entity);
                emCrud.flush();
            }
        }

        public <T> void remove(T entity) {
            emCrud.remove(emCrud.merge(entity));
        }

        public <T> void remove(T[] listaDaRimuovere) {
            for (T entity : listaDaRimuovere) {
                emCrud.remove(emCrud.merge(entity));
            }
        }

        public <T> void remove(List<T> listaDaRimuovere) {
            for (T entity : listaDaRimuovere) {
                emCrud.remove(emCrud.merge(entity));
            }
        }
     }

... and this is the interface:
public interface FormEBeanRemote {
    public void setEmCrud(EntityManager em);
    public <T> String create(T entity);
    public <T> void create(List<T> entityList);
    public <T> void edit(T entity);
    public <T> void edit(Set<T> entitySet);
    public <T> void remove(T entity);
    public <T> void remove(T[] listaDaRimuovere);
    public <T> void remove(List<T> listaDaRimuovere);
}

The EJB (stateless session bean) looks like this:
@Stateless
@Remote(MyEBean.class)
public class MyEBean extends FormEBean implements MyEBeanRemote {

    final Logger logger = LoggerFactory.getLogger(MyEBean.class);

    @PersistenceContext(unitName = "siat-ejbPU")
    private EntityManager em;

    public EntityManager getEm() {
        return em;
    }

    public void setEm(EntityManager em) {
        this.em = em;
    }

    @PostConstruct
    public void postConstruct() {
        this.setEmCrud(em);
    }

...where
@Remote
public interface MyEBeanRemote extends FormEBeanRemote {
......
}

Note that the EJB uses the postConstruct method to set the entityManager, which is delegated to perform CRUD operations on a specific persistence unit.
It's working like a charm so far.
If someone finds any pitfalls please let me know.


Q: What is a safe way to use pointers as keys for an NSMutableDictionary? In a project, I have data objects XXData and objects which represent these objects visually XXDataVisual. There can be up to 10'0000 objects which need to be loosely coupled. Only the XXDataVisual knows the represented XXData.
@interface XXDataVisual
@property (strong) XXData *data;
@end

The XXData must not know it's visual representation:
@interface XXData
// Elements
@end

To manage the visual representations, I need an efficient lookup which visual representation exists for a given data element.
Can I use the pointer of the XXData instances as a key to safely identify the the data elements?
Which is the best approach using modern Objective-C and Cocoa?

A: To have an NSDictionary-type collection where your keys are pointers, you might be needing an NSMapTable class.
From this link:

NSMapTable (as the name implies) is more suited to mapping in a
  general sense. Depending on how it is constructed, NSMapTable can
  handle the "key-to-object" style mapping of an NSDictionary but it can
  also handle "object-to-object" mappings — also known as an
  "associative array" or simply a "map".

A: Using NSMutableDictionary is bad idea. It copies keys, so your memory usage will increase dramatically. Use NSMapTable. You can configure it to use non-copyable keys and storing weak references to values, for example:
NSMapTable *mapTable = [NSMapTable mapTableWithKeyOptions:NSMapTableStrongMemory
                                             valueOptions:NSMapTableWeakMemory];


Q: Example for two sequences bounded I am struggling with finding $2$ examples of sequences $a_n,n\geq1$ $b_n,n\geq 1$ that are bounded such that
 $a_n<b_n$ for all $n$, but $\sup(a_n)\geq \sup(b_n)$.
I have been thinking for more than three days, this question I got it from Analysis I, written by Terence Tao. I will appreciate any help

A: Guide:
Pick your sequence of $b_n$.
Let $a_n = b_n - c_n$ where $c_n$ is a positive sequence that converges to $0$.

A: Take any bounded increasing sequence $b_n$ with limit $L$ and let $a_n=3b_n-2L.$

A: You can take $a_n=-\frac{1}{n}$ and $b_n=0$
And $a_n=\frac{n}{n+1}$ and $b_n=1$


Q: Labeling coordinates on an image using Python I have an input image and a dataframe with 1000 rows and 3 columns, an X coordinate, Y coordinate, and a Label (0-5).
I want to read in my image, find each of the coordinates on the image from the dataframe and label them by to color depending on the label column and display the image.
My DataFrame is something like this.
   data = {'X': [200, 246, 387, 86, 100], 'Y': [100, 200, 34, 98, 234], 'Texture': [0,1,2,3,4]}

 df = pd.DataFrame(data)

I can plot a single point (200, 200)
import matplotlib.pyplot as plt
img = plt.imread('../data/textures/test/test_image.jpg')

fig, ax = plt.subplots()
ax.imshow(img, extent=[0, 400, 0, 300])
ax.plot(200, 200, 'x', color='firebrick')

A: As far as I understood you want to mark certain pixels based on a label and you have the pixel/label as a data frame. You only need to define markers and colors and iterate over your data frame. The following will do this
import pandas as pd
import matplotlib.pyplot as plt

data = {'X': [200, 246, 387, 86, 100], 'Y': [100, 200, 34, 98, 234], 'Texture': [0,1,2,3,4]}
data = pd.DataFrame(data)
img = plt.imread("img.jpg")
# Define symbols and colors as you want.
# Item at ith index corresponds to that label in 'Texture'.
color = ['y', 'r', 'b', 'g', 'm']
marker = ['o', 'v', '1', 's', 'p']

#
fig, ax = plt.subplots()
ax.imshow(img, extent=[0, 400, 0, 300])
#
for _, row in data.iterrows():
    ax.plot(row['X'], row['Y'], marker[row['Texture']],color=color[row['Texture']])
plt.show()

If you have your data as python dictionary, you can Zip the dictionary values and iterate over them. The following will do it,
import matplotlib.pyplot as plt

data = {'X': [200, 246, 387, 86, 100], 'Y': [100, 200, 34, 98, 234], 'Texture': [0,1,2,3,4]}
img = plt.imread("img.jpg")
# Define symbols and colors as you want.
# Item at ith index corresponds to that label in 'Texture'.
color = ['y', 'r', 'b', 'g', 'm']
marker = ['o', 'v', '1', 's', 'p']
# Zip the data, returns a generator of paired (x_i, y_i, texture_i)
data_zipped = zip(*(data[col] for col in data))
#
fig, ax = plt.subplots()
ax.imshow(img, extent=[0, 400, 0, 300])
#
for x,y, texture in data_zipped:
    ax.plot(x, y, marker[texture],color=color[texture])
plt.show()


Q: Create http query in Flask Python I am trying to work with querys in Flask. I have a page choose.html where you can click buttons. these should be sent in a query then to page 2. So page 2 should be rendered by Flask with the query e.g.
127.0.0.1/login?username=test&color=3

I have tried the following so far (hard coded):
<button class="continue" id="submit" name="submit">Continue</button>

@app.route('/login', methods=['post', 'get'])
def login():
    message = request.args.get('username')

That was the response:
werkzeug.routing.BuildError: Could not build url for endpoint 'login?username=test'. Did you mean 'login' instead?

A: Found out the answer:
{{ url_for('login', user='foo', name='test') }}

This will create a query like this:
http://127.0.0.1:10000/login?user=foo&name=test


Q: Erlang install on Freebsd 10 on Amazon ec2 I'm trying to install erlang on amazon ec2 - on freebsd 10:
fetch http://www.erlang.org/download/otp_src_17.0.tar.gz
gunzip -c otp_src_17.0.tar.gz | tar xf -
cd otp_src_17.0
./configure --disable-hipe
gmake
gmake install

and I get the following error:

configure: error: Perl is required to generate v2 to v1 mib converter script
  configure: error: /bin/sh '/usr/home/ec2-user/otp_src_17.0/lib/snmp/./configure' failed for snmp/.
  configure: error: /bin/sh '/usr/home/ec2-user/otp_src_17.0/lib/configure' failed for lib

How do I avoid this error and install erlang on freebsd 10?

A: Use either packages ("pkg install erlang"), or ports (cd /usr/ports/lang/erlang && make install).  Software often requires patches to make it run correctly, and ports/packages take care of that.  They also automatically take care of dependencies, and that seems to be the root cause of your problem: you don't have perl installed.

A: So, I think you can install package
I have FreeBSD storage 10.1-RELEASE-p16 FreeBSD 10.1-RELEASE-p16 #0
And simple way is pkg install erlang

A: There's kerl which is an excellent project for building and maintaining all Erlang/OTP versions


Q: Checking if an input is formatted correctly in Python 3 so I've been assigned an assignment (obviously) to check if an input that a user has entered is formatted correctly, in the way AA99AAA (where A is a letter and 9 is a number from 0 to 9). So for the first character in the input, it would have to be a letter or python would return some sort of error and so on, you get the idea. I've got no clue where to start with this, I've tried looking around and haven't found anything - I guess I just don't know what it is I'm looking for. Any pointers would be greatly appreciated, thanks!

A: To do this, you could split the string into 3 parts (the first group of letters, the numbers, and then the second group of letters). Then you can use s.isalpha() and s.isnumeric().
For example:
while True:
    c=input('Password: ')
    if len(c)==7 and c[:2].isalpha() and c[2:4].isnumeric() and c[4:].isalpha():
        break
    else:
        print('Invalid input')
print('Valid input')

A: Could you provide more information regarding the question, is the example you have provided the format you are attempting to match? AA99AAA, so 2-alpha, 2-numeric, 3-alpha?
There are two approaches off the top of my head you could take here, one would be to utilize regular expressions to match on something like [\w]{2}[\d]{2}[\w]{3}, alternatively you could iterate through the string (recall that strings are character arrays).
For this approach you would have to generate substrings to isolate parts you are interested in. So..
for c in user_input[0:2]:
    if c.isdigit:
        print('Invalid Input')
for c in user_input[3:5]:
...
...

There are definitely more pythonic ways to approach this but this should be enough information to help you formalize a solution.

A: I finally did it! After about an hour...
So I used [] formatting and .isdigit/.isalpha to check each part of the code, like recommended above, however I did it in a slightly different way:
while True:
regNo = input("Registration number:")
if len(regNo) != 7:
    print("Invalid Registration Number! Please try again")
elif regNo[:2].isdigit():
    print("Invalid Registration Number! Please try again!")
elif regNo[2:4].isalpha():
    print("Invalid Registration Number! Please try again!")
elif regNo[4:].isdigit():
    print("Invalid Registration Number! Please try again!")
else:
    break

Hopefully this helps anyone else who stumbles across this problem!


Q: How to access ASP.NET Core web server from another device I created a project using C# and ASP.NET Core empty and it worked on localhost - how can I access it from another device using the IP of the computer running the project?

A: You need to configure kestrel to bind requests from 0.0.0.0 instead of localhost to accept requests from everywhere.
You can achieve this with different methods.
1- Run application with urls argument
dotnet app.dll --urls "http://0.0.0.0:5000;https://0.0.0.0:5001"
2- Add kestrel config to appsettings.json (Or any other way that you can inject value to IConfiguration)
{
 ...
  "Kestrel": {
    "Endpoints": {
      "Http": {
        "Url": "http://0.0.0.0:5000"
      },
      "Https": {
        "Url": "https://0.0.0.0:5001"
      }
    }
  }
  ...
}

3- Hard-code your binding in the program.cs file.
and the result should look like this

For complete details, please visit
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel/endpoints


Q: Syntax Error in Java print statement System.out.println("if(line.contains(\"<string key=\"concept:name\" value=\"LCSP\"/>\"\))");

I am getting an error. I want to print above statement as a string.
Can someone help me.

A: Remove the last backslash \ there is no need to escape )
System.out.println("if(line.contains(\"<string key=\"concept:name\" value=\"LCSP\"/>\"))");

DEMO1
Solution to the problem given in comment
String v11 = "John";
System.out.println("if(line.contains(\"<string key=\\\"concept:name\\\" value=\\\""+v11+"\\\"/>\"))");

OUTPUT
if(line.contains("<string key=\"concept:name\" value=\"John\"/>"))

DEMO2

A: no need to escape ')' at end of the line.
the changed statement is:
System.out.println("if(line.contains(\"<string key=\"concept:name\" value=\"LCSP\"/>\"))");

A: Original
System.out.println("if(line.contains(\"<string key=\"concept:name\" value=\"LCSP\"/>\"**\**))");

**** is not required I have removed from Original
Changed:
System.out.println("if(line.contains(\"<string key=\"concept:name\" value=\"LCSP\"/>\"))");

A: String v11 = "John1";
System.out.println("if(line.contains(\"<string key=\\\"concept:name\\\" value=\\\""+v11+"\\\"/>\"))");

remove the last backlash and update the "LCSP" to v11 variable.
output:
if(line.contains("<string key=\"concept:name\" value=\"John1\"/>"))


Q: Getting data for a video fails Using the following call:
https://www.googleapis.com/youtube/v3/videos?part=snippet&id=whatever&key=whatever
We get the following response:
{
"error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "accessNotConfigured",
    "message": "Access Not Configured. YouTube Data API has not been used in project 755558787820 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/youtube.googleapis.com/overview?project=755558787820 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.",
    "extendedHelp": "https://console.developers.google.com/apis/api/youtube.googleapis.com/overview?project=755558787820"
   }
  ],
  "code": 403,
  "message": "Access Not Configured. YouTube Data API has not been used in project 755558787820 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/youtube.googleapis.com/overview?project=755558787820 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry."
}
}

We checked the project (truthorange), and the Youtube Data API has been enabled (since 2017 or so). Everything was actually fine until 5/11, but starting with 5/12, this started failing for some reason.
Any ideas oh how to fix?


Q: How do I perform a threaded sparse matrix - vector multiplication using MKL? I need to perform a matrix vector multiplication, where the matrix is complex, symmetric and has four off-diagonal non-zero bands. So far I am using the sparse BLAS routine mkl_zdiasymv to perform the multiplication and it works fine on one core. I would like to try if I can gain a performance boost by using multi-threading (e.g. openMP). As far as I have understood some (many?) of the MKL routines are threaded. However if I use
    mkl_set_num_threads(4)
my program still runs on one single thread.
To give a specific example here is a little test program which I compile (using icc 14.01) with:
icc mkl_test_mp.cpp -mkl -std=c++0x -openmp

mkl_test_mp.cpp:
#include <complex>
#include <vector>
#include <iostream>
#include <chrono>

typedef std::complex<double> complex;
using std::vector;
using namespace std::chrono;

#define MKL_Complex16 std::complex<double>
#include "mkl.h"

int vector_dimension = 10000000;
int number_of_multiplications = 100;

vector<complex> initialize_matrix() {

    complex value_main_diagonal          = complex(1, 2);
    complex value_sub_and_super_diagonal = complex(3, 4);
    complex value_far_off_diagonal       = complex(5, 6);

    std::vector<complex> matrix;
    matrix.resize(1 * vector_dimension, value_main_diagonal);
    matrix.resize(2 * vector_dimension, value_sub_and_super_diagonal);
    matrix.resize(3 * vector_dimension, value_far_off_diagonal);

    return matrix;
}

vector<complex> perform_matrix_vector_calculation(vector<complex>& matrix, const vector<complex>& x) {

    mkl_set_num_threads(4);

    vector<complex> result(vector_dimension);

    char uplo = 'L';   // since the matrix is symmetric we only need to declare one triangular part of the matrix (here the lower one)
    int number_of_nonzero_diagonals = 3;
    vector<int> matrix_diagonal_offsets = {0, -1, -int(sqrt(vector_dimension))};

    complex *x_data = const_cast<complex* >(x.data()); // I do not like this, but mkl expects non const pointer (??)

    mkl_zdiasymv (
            &uplo,
            &vector_dimension,
        matrix.data(),
        &vector_dimension,
        matrix_diagonal_offsets.data(),
        &number_of_nonzero_diagonals,
        x_data,
        result.data()
    );
    return result;
}

void print(vector<complex>& x) {
  for(complex z : x)
    std::cerr << z;
  std::cerr << std::endl;
}

void run() {
  vector<complex> matrix = initialize_matrix();
  vector<complex> current_vector(vector_dimension, 1);

  for(int i = 0; i < number_of_multiplications; ++i) {
      current_vector = perform_matrix_vector_calculation(matrix, current_vector);
  }
  std::cerr << current_vector[0] << std::endl;
}

int main() {

  auto start = steady_clock::now();

  run();

  auto end = steady_clock::now();
  std::cerr << "runtime = " << duration<double, std::milli> (end - start).count() << " ms" << std::endl;
  std::cerr << "runtime per multiplication = " << duration<double, std::milli> (end -     start).count()/number_of_multiplications << " ms" << std::endl;
  }

Is it even possible to parallelize this way ? What am I doing wrong ? Are there other suggestions to speed up the multiplication ?

A: Since you are not showing how you compile the code, could you check that you are linking against the multi threaded Intel MKL libs and e.g. pthreads?
For example (this is for an older version of MKL):
THREADING_LIB="$(MKL_PATH)/libmkl_$(IFACE_THREADING_PART)_thread.$(EXT)"
OMP_LIB = -L"$(CMPLR_PATH)" -liomp5

There should be an examples directory in your MKL distribution e.g. intel/composer_xe_2011_sp1.10.319/mkl/examples. In there you can check the contents of spblasc/makefile to see how to correctly link against the multithreaded libs for you particular version of MKL.
Another suggestion that should speed things up is adding compiler optimisation flags e.g.
OPT_FLAGS = -xHost -O3
to allow icc to generate optimised code for your architecture so your line would end up as:
icc mkl_test_mp.cpp -mkl -std=c++0x -openmp -xHost -O3


Q: Get sequence of characters from words I wanted to generate a, unique code based on the input given.
Input = "ABC DEF GHI"

The code generated will be like,
"ADG" (first letter of each word) and if this exists then "ABDG" (first two letters of first word and first letter of rest of the words) this exists too then "ABCDG" next is "ABCDEG" and like wise if goes on till a unique code is generated. The validation is made thorough an API.
Types of input can be:
"ABC" (or)
"ABC DEF" (or)
"ABC DEF GHI" (or)
"ABC DEF GHI JKL"
I have tried like,
let count = 1;

    let val = this.userForm.get("name").value;
    let textArr = val.split(" ");

    let res;

      for(let i = 0; i< textArr.length; i++){

         res += textArr[i].substring(0,count)

      }

      let char1 = "", char2 = "", char3 = "";

       let ss:any = val.split(" ", 3);

       if(ss[0].length > 1)
         char1 = ss[0].substring(0,2)

       if(ss[1] && ss[1].length > 0)
         char2 = ss[1].substring(0,1)

       if(ss[2] && ss[2].length > 0)
         char3 = ss[2].substring(0,1)

    let result = char1 + char2 + char3;

   this.restApi.validateCode(result).subscribe((data: any) => {
     console.log(data) // returns boolean
    });

Couldn't get the logic what I want. Any help?

A: You can use this code to generate your desire sequence in order.

function generateCandidates(input)
{
  let candidates = [];
  //associate pointers for each word
  let words = input.split(" ").map(str => {return {str, ptr:1}});

  //First candidate
  let candidate = words.map(({str,ptr}) => str.substr(0,ptr)).join("");
  candidates.push(candidate);

  //find the first pointer that is still less than the length of the word
  let word;
  while( word = words.find(({str,ptr}) => ptr < str.length ) )
  {
    word.ptr++; //increment the pointer
    candidate = words.map(({str,ptr}) => str.substr(0,ptr)).join("");
    candidates.push(candidate);
  }

  return candidates;
}

console.log(generateCandidates("ABC"));
console.log(generateCandidates("ABC DEF"));
console.log(generateCandidates("ABC DEF GHI"));
console.log(generateCandidates("ABC DEF GHI JKL"));


Q: How to pass String and File data with Volley POST method in Android? I am using Volley to make server requests but i came to know that volley is not passing params from getParams() method in POST request, so now i am passing these data by concatenating all param/values with the url like bellow.
String url = "http://myweb/api/work?"+param1+"="+value;

Now the problem is it works fine with text data only, i can make request successfully and all params are passing to server but now i have to upload some image file also using same api.
How can i pass a file and string data using Volley POST method?
Following are the solutions i tried but got no success.
https://gist.github.com/anggadarkprince/a7c536da091f4b26bb4abf2f92926594#file-volleymultipartrequest-java
https://www.simplifiedcoding.net/android-volley-tutorial-to-upload-image-to-server/
Edit
Following is my current request code:
StringRequest request = new StringRequest(Request.Method.POST, uri + param, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            dismissProgressDialog();
            printResponse(response);

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dismissProgressDialog();
            error.printStackTrace();

        }
    }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<>();
            headers.put("key", key);
            headers.put("tkey", tkey);
            headers.put("Content-Type", "application/multipart");
            return headers;
        }
    };

A: Use Following code
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
    @Override
    public void onResponse(NetworkResponse response) {
        String resultResponse = new String(response.data);
        // parse success output
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        error.printStackTrace();
    }
}) {
    @Override
    protected Map<String, String> getParams() {
        Map<String, String> params = new HashMap<>();
        params.put("name", "Sam");
        params.put("location", "India");
        params.put("about", "UI/UX Designer");
        params.put("contact", "xyz@email.com");
        return params;
    }

    @Override
    protected Map<String, DataPart> getByteData() {
        Map<String, DataPart> params = new HashMap<>();
        // file name could found file base or direct access from real path
        // for now just get bitmap data from ImageView
        params.put("avatar", new DataPart("file_avatar.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mAvatarImage.getDrawable()), "image/jpeg"));
        params.put("cover", new DataPart("file_cover.jpg", AppHelper.getFileDataFromDrawable(getBaseContext(), mCoverImage.getDrawable()), "image/jpeg"));

        return params;
    }
};

VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);

A: VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(com.android.volley.Request.Method.POST, url, new Response.Listener<NetworkResponse>() {

        @Override
        public void onResponse(NetworkResponse response) {
        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
        }
    })
    {
        //pass String parameters here
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("category", "image");
            params.put("p_name", "myImage");
            return params;
        }

        //pass header
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<String, String>();

            headers.put("key", key);
            headers.put("tkey", tkey);
            headers.put("Content-Type", "application/multipart");

            return headers;
        }

        //pass file here (*/* - means you can pass any kind of file)
        @Override
        protected Map<String, VolleyMultipartRequest.DataPart> getByteData() {
            Map<String, DataPart> up_params = new HashMap<>();
            up_params.put("params", new DataPart(file_path, file_name, "*/*"));

            return up_params;
        }
    };
 VolleySingleton.getInstance(getBaseContext()).addToRequestQueue(multipartRequest);


Q: Problems with Programatically selecting checkbox nodes I have a checkbox group Listed in a tree structure.The tree is connected with a vector, which stores the state of checkboxes in the tree. I have buttons to select all checkboxes, and other buttons to select the corresponding checkbox. From the below diagram you can picturize UI.

for (CheckBoxNode Node : CheckBoxNodeTree.checkBoxRows) {
if(Node.isSelected()){
Node.setSelected(!Node.isSelected());
        }

For Select All the code used is :
TreeModel model = TREE.getModel();
        TreeNode  rootofTree = (TreeNode) model.getRoot();

        Enumeration<TreeNode> enumeratorForTree =                ((DefaultMutableTreeNode)rootofTree).breadthFirstEnumeration();
        while (enumeratorForTree.hasMoreElements()) {
         TreeNode child = enumeratorForTree.nextElement();
         Object currentNode = ((DefaultMutableTreeNode) child).getUserObject();
         if(currentNode instanceof CheckBoxNode) {

                ((CheckBoxNode) currentNode).setSelected(true);
         }
        }
        for (CheckBoxNode Node: CheckBoxNodeTree.checkBoxRows)
        {
        Node.setSelected(true);
        }

The issue i am facing now is that on clicking the respective buttons the checkbox state changes, but after clicking "Select All" button i am able to see that the nodes get checked ,but after this , if i try to select the induvidual nodes using the corresponding button , i cannot see the result on the tree .
Can anyone Help me with your suggestions. Thanks to the replier in advance.

A: Looks like a notification issue - you are changing node state without the model knowing of it. Assuming your model is a DefaultTreeModel, invoke a model.nodeChanged after changing the selection:
currentNode.setSelected(newState);
model.nodeChanged(currentNode);

A: Where is the code for your buttons used to select individual nodes?  Are you trying to make a button that toggles but yours only checks the box right now?  Maybe try this:
 buttonPushed() {
     //get your node for this button
    node.setSelected(!node.isSelected());
 }


Q: ChromeHeadless not starting: timing out when running ng test I am working on an Angular 7 (7.2.13) app and am having trouble running npm run test, which maps to ng test --watch=false --browsers=ChromeHeadless.
I am running Ubuntu under Windows 10 and all of my app-relating command line stuff is done on Ubuntu. This is a requirement of the project, but I've only been here a few weeks and haven't yet found out why!
I have installed ChromeHeadless by following these instructions. I set CHROME_BIN=/usr/bin/chromium-browser after doing this. However, it looks like ChromeHeadless is having trouble starting:

27 05 2019 11:26:40.497:INFO [karma-server]: Karma v4.0.1 server started at http://0.0.0.0:9876/
27 05 2019 11:26:40.500:INFO [launcher]: Launching browsers ChromeHeadless with concurrency unlimited
  #
27 05 2019 11:26:40.506:INFO [launcher]: Starting browser ChromeHeadless              27 05 2019 11:27:40.507:WARN [launcher]: ChromeHeadless have not captured in 60000 ms, killing.
27 05 2019 11:27:40.724:INFO [launcher]: Trying to start ChromeHeadless again (1/2).

It tries again a few times, but just times out. I have seen a few posts about turning on verbose logging, but modifying the captureTimeout has only the effect of making the process slower!
Can anyone help?

A: I solved an issue with this same message caused by a proxy-blocker of the client. I had to set --proxy-server flag in my customLauncher in karma.conf.js, so the karma server could get the ChromeHeadless and execute the tests perfectly.
karma.conf.js

browsers: ['MyChromeHeadless'],
    customLaunchers: {
    MyChromeHeadless: {
        base: 'ChromeHeadless',
        flags: [
          '--no-sandbox',
          '--proxy-bypass-list=*',
          '--proxy-server=http://proxy.your.company'
        ]
      }
    }


Q: Broadcast Receivers can not get new values from new intent and show the previous values I have alarm manager . when user click on add button , user select time , date and fill title and other ... and after this . I save this into database and show this values into recycle view .
I get values and save them into database like this :
        saveAlarm.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            final String mTitle = title.getText().toString();
            final String mDate = date;
            final String mTime = time;
            final String mRepeat = getrepeat.getText().toString();
            final String mReport = single_choice_selected_report_as;

            if (isAnyStringNullOrEmpty(mTitle, mDate, mTime, mRepeat, mReport)) {
                Snackbar snackbar = Snackbar.make(mainLayout, "", Snackbar.LENGTH_LONG);
                Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) snackbar.getView();
                TextView textView = (TextView) layout.findViewById(com.google.android.material.R.id.snackbar_text);
                textView.setVisibility(View.INVISIBLE);
                View snackView = LayoutInflater.from(SetAlarmActivity.this).inflate(R.layout.custom_toast, null, false);
                TextView txtNoticToExit = (TextView) snackView.findViewById(R.id.txtCustomToast);
                txtNoticToExit.setText(getResources().getString(R.string.fill_field));
                txtNoticToExit.setTypeface(Apps.font);
                layout.setPadding(0, 0, 0, 0);
                layout.addView(snackView, 0);
                snackbar.show();
            } else {
                if (editMode) {

                    Alarm alarm = new Alarm(id, mTitle, mDate, mTime, mRepeat, mReport, active);
                    mDatabase.updateAlarm(alarm);

                } else {
                    Alarm alarm = new Alarm(mTitle, mDate, mTime, mRepeat, mReport, 0);
                    mDatabase.addAlarm(alarm);

                }

                Intent intent = new Intent(SetAlarmActivity.this, AlarmActivity.class);
                startActivity(intent);
                SetAlarmActivity.this.finish();
            }

        }

In row of my recycle view I have a button to active this item to alarm base on the time .
          holder.toggleButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int test = alarm.getActive();
            state = !state;
            if (test == 0) {

                holder.toggleButton.setBackgroundResource(R.drawable.on);
                holder.row.setBackgroundResource(R.drawable.purple_row);
                holder.reminderCalenderRow.setTextColor(context.getResources().getColor(R.color.white));
                holder.reminderTitleRow.setTextColor(context.getResources().getColor(R.color.white));
                holder.showCalenderRow.setTextColor(context.getResources().getColor(R.color.white));
                holder.showTimeRow.setTextColor(context.getResources().getColor(R.color.white));
                holder.reminderCalenderRow.setTextColor(context.getResources().getColor(R.color.white));
                holder.reminderTimeRow.setTextColor(context.getResources().getColor(R.color.white));
                Drawable myDrawable = context.getResources().getDrawable(R.drawable.menu_icon);
                holder.popUp_menu.setBackground(myDrawable);
                alarm.setActive(1);

                String strTime = alarm.getTime();
                String[] timeRemoveSpace = strTime.split(" ");
                String[] splitTime = timeRemoveSpace[0].split(":");
                hour = getHour(strTime);
                mintue = Integer.parseInt(splitTime[1]);

                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(System.currentTimeMillis());
                calendar.set(Calendar.HOUR_OF_DAY, hour);
                calendar.set(Calendar.MINUTE, mintue);
                calendar.set(Calendar.SECOND, 00);

                Long date = calendar.getTimeInMillis();
                StartAlarm(alarm.getId(), alarm, date);

            } else {
                holder.row.setBackgroundResource(R.drawable.white_row);
                holder.reminderTitleRow.setTextColor(context.getResources().getColor(R.color.colorBlack));
                holder.showCalenderRow.setTextColor(context.getResources().getColor(R.color.colorBlack));
                holder.showTimeRow.setTextColor(context.getResources().getColor(R.color.colorBlack));
                holder.reminderCalenderRow.setTextColor(context.getResources().getColor(R.color.colorBlack));
                holder.reminderTimeRow.setTextColor(context.getResources().getColor(R.color.colorBlack));
                Drawable myDrawable = context.getResources().getDrawable(R.drawable.menu_icon_black);
                holder.popUp_menu.setBackground(myDrawable);
                alarm.setActive(0);
            }
            mDatabase.updateActive(state, alarm.getId());
            notifyDataSetChanged();

        }
    });

and send intent into broatcast :
    public void StartAlarm(int id, Alarm alarm, Long time) {
    Intent intent = new Intent(context, MyReceiver.class);
    intent.setAction("com.nooshindroid.yastashir");
    Bundle bundle = new Bundle();
    bundle.putString(EXTRA_TITLE, alarm.getTitle());
    bundle.putString(EXTRA_ALARM_DATE, alarm.getDate());
    bundle.putString(EXTRA_REPORT, alarm.getReport());
    bundle.putString(EXTRA_REPEAT, alarm.getRepeat());
    intent.putExtras(bundle);
    pendingIntent = PendingIntent.getBroadcast(context, id, intent, 0);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
    if ("بدون تکرار".equals(alarm.getRepeat())) {
        Log.i("ShowMeTime", "111111");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent);

            Toast.makeText(context, "Alarm>kitkat", Toast.LENGTH_SHORT).show();
        }

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);

            Toast.makeText(context, "Alarm<kitkat", Toast.LENGTH_SHORT).show();
        }
    } else {
        Log.i("ShowMeTime", "222222");
        switch (alarm.getRepeat()) {
            case "هر ساعت":
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_HOUR, pendingIntent);
                break;
            case "هر روز":
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_DAY, pendingIntent);
                break;
            case "هر هفته":
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_DAY * 7, pendingIntent);
                break;
            case "هر ماه":
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_DAY * 30, pendingIntent);
                break;
        }
    }

}

all thins is ok until I want to edit , Once I edit my values and all these repeat , broad cast show the old values .
this my Receiver :
    public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    //and doing something
    if (intent.getAction().equals("com.nooshindroid.yastashir")) {
        String title = intent.getExtras().getString(EXTRA_TITLE);
        Toast.makeText(context, "Its time!!!", Toast.LENGTH_SHORT).show();
        Log.i("khhhhhhhhhhhhhhh", "Started >>>>>>>"+title);
    }
}

}
Why this happen ? any help?


Q: Relation among Chern classes Let $E\rightarrow\mathbb{P}^2$ be a rank $r$ vector bundle over $\mathbb{P}^2$ with Chern classes $c_i = c_i(E)$.
Is there any relation among $c_1$ and $c_2$ or are they in general completely unrelated?
Thank you.

A: One may consider $(c_1,c_2)$ as a pair of integers by choosing generators of $H^{2}$ and $H^4$ (both isomorphic to $\mathbb{Z}$).
Then it was proved by  Schwarzenberger that any pair $(c_1,c_2) \in \mathbb{Z}^2$ is realsed by some rank 2 vector bundle on $\mathbb{CP}^2$. See http://www.numdam.org/article/SB_1978-1979__21__80_0.pdf page 81.
Then taking products with trivial bundles shows that any pair can appear for higher ranks also.
For rank 1 i.e. line bundles then $c_2=0$, but any $c_1$ can occur (as $\mathcal{O}(k)$ shows).
For $\mathbb{CP}^k$ for $k>2$ there are some relations in the Chern classes of suitably high rank vector bundles, see the above reference paper (also page 81).


Q: How to pass data from useSelector (redux) to useSate hook in react? Hi i am trying to work on a app, which has some predefined code of redux, and react.
I am trying to get the players data which is formated json file and pass it to useSate hook.
The data which I get using
 const players = useSelector(getPlayers); // redux

looks perfect when I do console log, however when I pass this to useState
const [playerData, setPlayerData] = useState(players); //react

there is no data on the console.
I do not know if this is the right way to do, if not what would be the best solution to this? as I am more into react hooks and not redux.
any help is appreciated . Thanks

A: you can set it in useEffect like that but my suggestion is to use the directly redux players variable.
useEffect(() => {
  setPlayerData(players);
}, [players])


Q: NSData dataWithContentsOfURL: returning nil NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"CRN_JSON"
                                                     ofType:@"json"];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    data = [NSData dataWithContentsOfURL:
                    [NSURL URLWithString:@"http://properfrattire.com/Classifi/CRN_JSON.json"]];
    [self performSelectorOnMainThread:@selector(fetchedData:)
                           withObject:data waitUntilDone:YES];

});

My data variable is nil after running this code. If you follow the link you'll see that it is a JSON file. I've run the function with this exact same file locally but it is not able to obtain the data at the given URL without error.

A: Not sure why you're nesting calls to URLWithString:
[NSURL URLWithString:[NSURL URLWithString:@"http://properfrattire.com/Classifi/CRN_JSON.json"]]];

Once will do:
[NSURL URLWithString:@"http://properfrattire.com/Classifi/CRN_JSON.json"];

Also, you should use dataWithContentsOfURL:options:error: so you can see any error.


Q: How to call Rust async method from Python? I want to use a Rust async method in Python.
I'm trying to use PyO3 or rust-cpython.
For example, for sync Rust functions, I can use,
#[pyfunction]
fn myfunc(a: String) -> PyResult<String> {
   let mut contents = String::new();
   contents = a.to_string() + " appended";
   Ok((contents))
}

#[pymodule]
fn MyModule(py: Python, m: &PyModule) -> PyResult<()> {
    m.add_wrapped(wrap_pyfunction!(urlshot))?;
    Ok(())
}

For async methods, how can I do it? For example, I want to call the following method in Python,
async fn hello_world() {
    println!("hello, world!");
}

A: Since there was no easy way of solving this issue (at least, I hadn't found), I converted my async method to sync one. And called it on Python side as,
async fn my_method(s: &str) -> Result<String, Error> {
    // do something
}

#[pyfunction]
fn my_sync_method(s: String) -> PyResult<String> {
    let mut rt = tokio::runtime::Runtime::new().unwrap();
    let mut contents = String::new();
    rt.block_on(async {
        result = format!("{}", my_sync_method(&s).await.unwrap()).to_string();
    });
   Ok((result))
}

#[pymodule]
fn MyModule(py: Python, m: &PyModule) -> PyResult<()> {
    m.add_wrapped(wrap_pyfunction!(my_sync_method))?;
    Ok(())
}

Edited
In the Cargo.toml file, I added the following dependencies,

[dependencies.pyo3]
git = "https://github.com/PyO3/pyo3"
features = ["extension-module"]

After running cargo build --release, target/release/libMyModule.so binary file is generated. Rename it as MyModule.so and it now can be imported from Python.
import MyModule
result = MyModule.my_sync_method("hello")

Using setuptools-rust, I could bundle it as an ordinary Python package.
All of the above code and commands are tested on newly-released Linux Mint 20. On MacOS, the binary file will be libMyModule.dylib.

A: If you want to use Python to control Rust's async function, I don't think it will work (Or at least it is very complicated, as you need to connect two different future mechanism). For async functions, Rust compiler will maintain a state machine to manage the coroutines run correctly under await's control. This is an internal state of Rust applications and Python cannot touch it. Similarly Python interpreter also has a state machine that cannot be touched by Rust.
I do found this topic about how to export an async function using FFI. The main idea is to wrap the async in a BoxFuture and let C control the timing of returning it to Rust. However, you cannot use BoxFuture in PyO3 since its pyfunction macro cannot convert a function returns BoxFuture to a Python callback. You may try to create a library using FFI and use python's cffi module to load it.


Q: How to keep decimal places with two zeros? Using the lib Decimal i can set the quantize to get the 2 decimal places with zero:
from decimal import Decimal
value = Decimal('1000.0').quantize(Decimal('1.00'))
print(value) # Decimal('1000.00')

But if i need to change it to float the last zero disappear:
value = float(value)
print(value) # 1000.0

How can i set two zeros at decimal place and still use as float?
the print method was an e example to show the final result, i need to use the value as float and not string.
the value will be used in a json request:
{
    "value": 1000.00
}


Q: Cómo obtener los 3 valores mas altos en columnas? Hola amigos pregunto si es posible obtener 3 valores mayores de un conjunto y mostrarlos en columnas es decir que la tabla estaría de la siguiente forma: ValorMayor1, ValorMayor2, ValorMayor4.  Es posible obtener así los resultados. Mi consulta hasta ahora:
Mi problema es que me muestra los resultados de esta manera.

    SELECT id_alumno, resultado, id_perfil FROM puntajes WHERE
resultado >= IFNULL((SELECT resultado FROM puntajes AS p2 WHERE
p2.id_alumno = puntajes.id_alumno ORDER BY resultado DESC
LIMIT 1 OFFSET 2), 0) ORDER BY puntajes.id_alumno, resultado DESC

Y los quiero tener los tres resultados en columnas cómo hago eso? resultado1, resultado2 y resultado3.
Ejemplo:

Tabla a la que le realizo la consulta:

A: Ahora que has explicado con claridad lo que quieres:

... solo quería que cada id_alumno le mostrara sus 3 resultados mas
  altos. Ejemplo alumno 1 tiene 9,8,7,6,5 entonces le muestro 9,8 y 7 y
  así sucesivamente con los demás alumnos, alumno 2, alumno 3 etc

Propongo esta solución simple que consiste en una combinación de SUBSTRING_INDEX y GROUP_CONCAT.
Lo que hace la consulta es agrupar la columna resultado por cada id_alumno, en el GROUP_CONCAT ordenamos por resultado y nos valemos de SUBSTRING_INDEX para obtener solamente tres resultados (que serían los mayores)  por cada grupo.
Lo único es que no te mostrará los tres valores en tres columnas como querías. Pero si los datos van a ser manejados en un lenguaje de programación cualquiera, se podría explotar el separador , para obtener cada valor como un dato individual.
Si esta solución no te sirve, entonces habría que simular algo parecido a la función ROW_NUMBER() de otros manejadores de bases de datos, la cual no existe en MySQL.
Entonces, la consulta sería esto sencillamente.
SELECT
    id_alumno,
    SUBSTRING_INDEX(GROUP_CONCAT(resultado ORDER BY resultado DESC SEPARATOR ',' ), ',', 3) as resultados
FROM puntaje
GROUP BY id_alumno;

Y los resultados vendría así, tres valores separados por coma que serían los resultados más altos por cada alumno:
id_alumno       resultados
---------------------------
1               53,52,51
3               56,52,48
4               12,10,10

Otra ventaja que esto tendría es que si un alumno tiene menos de tres resultados la consulta no va a fallar, te presentará solamente los valores que tenga, aunque sean menos de tres.

Código de prueba
Puedes ver aquí una DEMOSTRACIÓN de los datos de prueba que fueron usados para reproducir la situación.
Espero te sea de utilidad.

A: Creo que te refieres a una estructura pivot. El problema es que de todo lo que he buscado en todos los ejemplos hay 3 campos necesarios para ejecutar esto, en tu deberían ser caso serian:

*

*id_alumno

*numResultado ( el que te falta);

*resultado

Para ejecutar esta forma de estructuracion necesitarias una estructura tal que asi
+------------+--------------+-----------+
| id_alumno  | numResultado | resultado |
+------------+--------------+-----------+
|     1      |      1       |    20     |
|     1      |      2       |    10     |
|     1      |      3       |    18     |
|     2      |      1       |    42     |
|     2      |      2       |    35     |
|     2      |      3       |    18     |
|     3      |      1       |    11     |
|     3      |      2       |    45     |
+------------+--------------+-----------+

Siendo numResultado el indice de cada nota:

*

*Nota 1 del alumno 1 = 20

*Nota 2 del alumno 1 = 10

*Nota 3 del alumno 3 = 18

*...

*Nota 2 del alumno 3 = 45

Para llegar a este resultado puedes reestructurar tu tabla o hacer un Select que te lo deje de esta forma

Esto es necesario ya que de momento todos los ejemplo encontrados hacen uso de una estructura similar.

Teniendo esto ya puedes ejecutar la Select utilizando la metodologia pivot:

Hay bases de datos como SQLServer por ejemplo que lo tienen implementado como funciones sin emabrgo en otros como MySQL solo se llama de esta forma a la forma de estructurarlo

SELECT
 id_alumno,
 SUM(numResultado=1) AS "Nota1",
 SUM(numResultado=2) AS "Nota2",
 SUM(numResultado=3) AS "Nota3"
FROM table -- SI es una select en vez de tabla seria [FROM (SELECT...) AS reestructuracion]
GROUP BY id_alumno

Esta consulta te dará el siguiente resultado:
+-----------+-------+-------+-------+
| id_alumno | Nota1 | Nota2 | Nota3 |
+-----------+-------+-------+-------+
|     1     |   20  |   10  |  18   |
|     2     |   42  |   35  |  18   |
|     3     |   11  |   45  |   0   |
+-----------+-------+-------+-------+

Con poner MySQL Pivot en google encontraras muchos mas ejemplos aunque esto es de lo mas simple y claro que he encontrado.

A: AMIGOS HE ENCONTRADO UNA MANERA DE TENER LOS 3 valores mas altos de cada grupo en mi caso id_alumno cada uno sus tres resultados mayores:  Investigando llegue a esto, no es mucho pero a alguien le puede servir, gracias a todos por ayudar:
Esta es eficiente en los duplicados ya que si tenemos 10,11,11,12,11,12  Lo que mostrara será:  12,12,11 y la que publique la de arriba me muestra los duplicados o sea: 12,12,11,11,11. Esta es mejor:
      SELECT id_puntaje, id_alumno, resultado FROM ( SELECT id_puntaje, id_alumno, resultado,
     @rn := IF(@prev = id_alumno, @rn + 1, 1) AS rn, @prev := id_alumno
        FROM puntajes JOIN (SELECT @prev := NULL, @rn := 0)
AS vars ORDER BY id_alumno, resultado DESC, id_puntaje ) AS T1 WHERE rn <= 3;

Muestra:


Q: Retrofit2 How to get redirect url @HEAD("/") I have a minified URL and I want to have the final URL
With Retrofit 1.9 I used to do this :
@HEAD("/XXXXXXXXX")
void fetchFinalUrl(Callback<String> cb);

public void getUrl() {
   mMinifyService.fetchFinalUrl(new Callback<String>() {
                @Override
                public void success(String s, Response response) {
                    response.getUrl();
                }
                [...]
}

But now with Retrofit 2 .getUrl() not exist any ideas how to do this?
Thanks in advance.
EDIT
Finally got it!
public class ApiProvider<T> {

    private Retrofit retrofit;
    private static final String END_POINT_MINIFY = "XXXXXXX";

    public ApiProvider() {
        initAdapter();
    }

    public T getService(Class<T> service) {
        return retrofit.create(service);
    }

    private void initAdapter() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .followRedirects(false)
                .build();

        retrofit = new Retrofit.Builder()
                .baseUrl(END_POINT_MINIFY)
                .addConverterFactory(new ToStringConverterFactory())
                .client(client)
                .build();
    }

}

public interface IMinifyService {
    @HEAD("/XXXXXXXXX")
    Call<Void> fetchFinalUrl(Callback<String> cb);
}

public class MinifyServiceImpl {

    private ApiProvider<IMinifyService> mApiProvider = new ApiProvider<>();
    private IMinifyService mMinifyService = mApiProvider.getService(IMinifyService.class);

    public Promiser<String, Integer> fetchMinifyUrl() {
        return new Promiser<>((resolve, reject) -> mMinifyService.fetchMinifyUrl().enqueue(new Callback<Void>() {
            @Override
            public void onResponse(Call<Void> call, Response<Void> response) {
                if (response.code() >= 300 && response.code() < 400){
                    resole.run(response.headers().get("Location"));
                } else {
                    reject.run(response.code());
                }
            }

            @Override
            public void onFailure(Call<Void> call, Throwable t) {
                reject.run(t.hashCode());
            }
        }));
    }

}

if you want to use Promizer --> Click here

A: response.raw().request().url()


Q: how fix cors error on react app and coinbase connect api I can't get authorization URL to coinbase connect OAuth2 api.
fetch("https://www.coinbase.com/oauth/authorize?response_type=code&client_id=cc460ce71913c49e4face4ac0e072c38564fabea867ebcd7ab9905970d8f3021&redirect_uri=http://localhost:3000/callback&state=SECURE_RANDOM&scope=wallet:accounts:read")
      .then(res => res.json())
      .then(
        (result) => {
          console.log(result)
        },
        (error) => {
          console.log(error)
        }
      )

give me this error
enter image description here

A: You can disable cors like that :
fetch('https://www.coinbase.com/oauth/authorize?response_type=code&client_id=cc460ce71913c49e4face4ac0e072c38564fabea867ebcd7ab9905970d8f3021&redirect_uri=http://localhost:3000/callback&state=SECURE_RANDOM&scope=wallet:accounts:read', {
mode: 'no-cors',
method:'GET'
}).then(res => res.json())
  .then(
    (result) => {
      console.log(result)
    },
    (error) => {
      console.log(error)
    }
  )


Q: Visualforce - Clickable DataTable Cells - How to get Column and Row information I'd like to create a datatable where each cell is clickable.  I'm assuming that I can probably fill each cell with apex:outputlink and that takes care of the clickable part as well as calling my controller for each click.  The big question I need an answer for is how do I pass information to my apex controller about which cell (i.e.: which row and which column) was actually clicked.
Any help for this is highly appreciated.

A: Its easy. Just define an action function to catch the values from the dataTable:
1) First defining three vars tht we will pass to controller: raw-id, cell-value, cell-type
public String clickedRowId { get; set; }
public String clickedCellValue { get; set; }
public String clickedCellType { get; set; }

public PageReference readCellMethod(){
    System.debug('#### clickedRowId: ' + clickedRowId);
    System.debug('#### clickedCellValue: ' + clickedCellValue);
    System.debug('#### clickedCellType: ' + clickedCellType);
    return null;
}

2) Second we create an action function, that calls our apex method an pass three vars to it:
<apex:actionFunction name="readCell" action="{!readCellMethod}">
    <apex:param name="P1" value="" assignTo="{!clickedRowId}"/>
    <apex:param name="P2" value="" assignTo="{!clickedCellValue}"/>
    <apex:param name="P3" value="" assignTo="{!clickedCellType}"/>
</apex:actionFunction>

3) And third we create our dataTable, where each cell has onClick listener:
<apex:pageBlockTable value="{!someArray}" var="item">

    <apex:column value="{!item.name}" onclick="readCell('{!item.id}','{!item.name}','name')" />
    <apex:column value="{!item.CustomField1__c}" onclick="readCell('{!item.id}','{!item.CustomField1__c}','custom1')" />
    <apex:column value="{!item.CustomField2__c}" onclick="readCell('{!item.id}','{!item.CustomField2__c}','custom2')" />

</apex:pageBlockTable>

We can access our actionFunction like any other JavaScript function. If user clicks on the cell - three vars will be send to the actionFunction and then to controller.


Q: webm to mp4 without loosing audio video sync Iam trying to covert webm to mp4 using ffmpeg so that the output file is playable in all browsers.
Iam using this ffmpeg command in ubuntu
ffmpeg -i inpput.webm -f mp4 -copyts -vcodec libx264 -strict -2 -vf scale="380:-2" -pix_fmt yuv420p -profile:v baseline -level 3 output.mp4

It is converting the file to mp4 but that file is out of sync in Mac safari browser and chrome browser. Means the audio and video is not syncing and sometimes the video gets stopped in between and audio goes on.
If I play the input.web media file directly in chrome it is playing perfectly fine, the same input.webm is also playing good with firefox. But the converted mp4 is out of sync in safari on mac and all chrome browsers.
However if the output.mp4 is played on ipad safari it is playing fine.
The Mac safari version I tried is 11.03
iPad safari version is 11.3
Firefox and chrome are all latest.
firefox : 59.0.2(64 bit),
chrome : 65.0.3325.181 (Official Build) (64-bit)
Please help me out with what Iam doing wrong.
Thanks in advance.


Q: How to check if string is a proper subset of another string I want to check if a string is a strictly a subset of another string.
For this end I used boost::contains and I compare the size of strings as follows:
#include <boost/algorithm/string.hpp>
#include <iostream>

using namespace std;
using namespace boost::algorithm;

int main()
{
  string str1 = "abc news";
  string str2 = "abc";
  //strim strings using boost
  trim(str1);
  trim(str2);
  //if str2 is a subset of str1 and its size is less than the size of str1 then it is strictly contained in str1
  if(contains(str1,str2) && (str2.size() < str1.size()))
  {
    cout <<"contains" << end;
  }
  return 0;
}

Is there a better way to solve this problem? Instead of also comparing the size of strings?

Example

*

*ABC is a proper subset of ABC NEWS

*ABC is not a proper subset of ABC

A: I would use the following:
bool is_substr_of(const std::string& sub, const std::string& s) {
  return sub.size() < s.size() && s.find(sub) != s.npos;
}

This uses the standard library only, and does the size check first which is cheaper than s.find(sub) != s.npos.

A: You can just use == or != to compare the strings:
if(contains(str1, str2) && (str1 != str2))
    ...

If string contains a string and both are not equal, you have a real subset.
If this is better than your method is for you to decide. It is less typing and very clear (IMO), but probably a little bit slower if both strings are long and equal or both start with the same, long sequence.
Note: If you really care about performance, you might want to try the Boyer-Moore search and the Boyer-Moore-Horspool search. They are way faster than any trivial string search (as apparently used in the string search in stdlibc++, see here), I do not know if boost::contains uses them.

A: About Comparaison operations
TL;DR : Be sure about the format of what you're comparing.
Be wary of how you define strictly.
For example, you did not pointed out thoses issue is your question, but if i submit let's say :
 "ABC       " //IE whitespaces
 "ABC\n"

What is your take on it ? Do you accept it or not ? If you don't, you'll have to either trim or to clean your output before comparing - just a general note on comparaison operations -
Anyway, as Baum pointed out, you can either check equality of your strings using == or you can compare length (which is more efficient given that you first checked for substring) with either size() or length();

A: another approach, using only the standard library:
#include <algorithm>
#include <string>
#include <iostream>

using namespace std;

int main()
{
  string str1 = "abc news";
  string str2 = "abc";
  if (str2 != str1
    && search(begin(str1), end(str1),
              begin(str2), end(str2)) != end(str1))
  {
    cout <<"contains" << endl;
  }
  return 0;
}


Q: What happens to the Apache process when a PHP session expires? My understanding is that when a request is received, the Apache server will fork a new process and invoke the appropriate php script/file.
What happens when the session started by the php script, in this new process forked by Apache, has expired or the user has ended it by closing their browser ? There is an exit(); call after errors or logout redirects that I use but I am unsure of what it does at the Server/OS level.
Does Apache kill the process ? How does the communication between apache and php work ?

A:
My understanding is that when a request is received, the Apache server will fork a new process and invoke the appropriate php script/file.

This is only the case for PHP-CGI configurations, which are not typical. Most deployments use the mod_php SAPI, which runs PHP scripts within the Apache process.

What happens when the session started by the php script, in this new process forked by Apache, has expired or the user has ended it by closing their browser ?

Nothing.
In PHP-CGI configurations, the process exits as soon as your script finishes generating a response. In mod_php configurations, the Apache process returns to listening for new requests when your script finishes.
The lifetime of sessions is not tied to any specific process. Keep in mind that sessions are stored as files in your system's temporary directory -- PHP periodically checks this directory for sessions which have expired and removes them as appropriate.
Closing your browser does not remove the session from the server's temporary directory. It may cause your browser to discard the cookies related to the session, causing the session to stop being used, but the server is not notified of this.


Q: load an OCX dynamically and get the handle of loaded module in C# I am going to load an OCX in runtime and pass the handle of loaded ocx to another function which is a patch ,
I have the delphi code and it works fine , I want to convert it to c# but I don't know how
Type
  TDLLFunc = procedure(param1: dword);
VAR
  DLLFunc      : TDLLFunc;
  OcxDllHndle  : LongInt;
  DllHandle    : LongInt;

begin
  OcxDllHndle := LoadLibrary('SampleOcx.Dll');
  DllHandle   := LoadLibrary('Patch.dll');
  @DLLFunc    := GetProcAddress(DllHandle, 'DoPatch');
  DLLFunc(OcxDllHndle);
end;

here is the c# code but it doesnt work (I made AxInterop version of OCX ) :
AppDomain Domain = AppDomain.CreateDomain("TestApp", null, null);
var assemblyName = AssemblyName.GetAssemblyName(@".\AxInterop.SampleOcx.dll");
Assembly Ocx = Assembly.Load(assemblyName);
IntPtr DLLHandle = LoadLibrary(Application.StartupPath + @"\Patch.dll");
IntPtr funcaddr = GetProcAddress(DLLHandle, "DoPatch");

[UnmanagedFunctionPointer(CallingConvention.StdCall)]
delegate void MyFunc(int Handle);

MyFunc DLLFunc = Marshal.GetDelegateForFunctionPointer(funcaddr, typeof(MyFunc)) as    MyFunc;
IntPtr OCXHandle = Marshal.GetHINSTANCE(Ocx.GetType().Module);
DLLFunc(OCXHandle.ToInt32());

Please help

A: The function that is exported from that Delphi DLL cannot be called from C#. The Delphi DLL exports the function using the register calling convention which is a non-standard Delphi only calling convention. You will need to modify the DLL to export using, for instance, stdcall.
Assuming you made the change the C# code would look like this:
[DllImport("patch.dll")]
static extern void DoPatch(IntPtr moduleHandle);
....
IntPtr OcxHandle = LoadLibrary("SampleOcx.dll");
if (OcxHandle == IntPtr.Zero)
    .... handle error
DoPatch(OcxHandle);

Note that the parameter is not really a DWORD. It is an HMODULE. That's a 64 bit type under 64 bit process. Which leads me to point out that your program must target x86 to work with your 32 bit Delphi DLL. And the OCX is presumably 32 bits too.


Q: Error in config.preparations.append(modelName.self) Use of unresolved identifier 'modelName' I have already gone through the proper way of the fluent provider to build a relation for my model (Swift) using vapor (server side) and PostgreSQL provider (database), I follow the general method of fluent,  but I don't know where I am doing mistake, in extension for modelName preparation,
below the code of my modelName.swift and main.swift.
 import Foundation
 import Vapor
import FluentProvider
import PostgreSQLProvider

final class modelName: Model {

    let storage = Storage()
    var id: Node?
    var name:String
    var displayName:String
       public var content: String

    init(content: String, displayName:String, name:String) {

        self.content = content
        self.displayName = displayName
        self.name = name
    }

    func forDataBase() {

        let array:[berichtDataPoint] = [intDataPoint(), boolDataPoint(), doubleDataPoint()]

        let _ = array[0] as! intDataPoint
        let _ = array[1] as! doubleDataPoint

        for point in array {

            switch point {
            case is  intDataPoint:
                print("int")
            case is doubleDataPoint:
                print("double")
            case is boolDataPoint:
                print("bool")
            default:
                print("error")
            }
        }

    }

  func makeRow() throws -> Row {
        var row = Row()
        try row.set("id", idKey)
        try row.set("displayName", displayName)
        try row.set("name", name)
        return row
    }

    init(row: Row) throws {
        content = try row.get("content")
        displayName = try row.get("displayName")
        name = try row.get("name")
    }

    func makeNode(context: Context) throws -> Node {
        return try Node(node: [
            "id": id,
            "content": content,
            "displayName": displayName,
            "name": name
            ])
    }
}

extension modelName: Preparation {
    static func prepare(_ database: Database) throws {
        try database.create(self) { modelName in
            modelName.id()
            modelName.string("displayName")
            modelName.string("name")

        }
    }

    static func revert(_ database: Database) throws {
        try database.delete(self)
    }
}

main.swift
import App
import Vapor
import FluentProvider
import PostgreSQLProvider

/// We have isolated all of our App's logic into
/// the App module because it makes our app
/// more testable.
///
/// In general, the executable portion of our App
/// shouldn't include much more code than is presented
/// here.
///
/// We simply initialize our Droplet, optionally
/// passing in values if necessary
/// Then, we pass it to our App's setup function
/// this should setup all the routes and special
/// features of our app
///
/// .run() runs the Droplet's commands,
/// if no command is given, it will default to "serve"
let config = try Config()
config.preparations.append(modelName.self) \\error is here '(Use of
unresolved identifier 'modelName')

let drop = try Droplet(config)
try drop.setup()

try drop.run()

A: I think the root cause is that modules are separated.
If you created vapor project as vapor new, main.swift is in Run module, modelName.swift is in App module.
// Package.swift

let package = Package(
    name: "hello",
    targets: [
        Target(name: "App"),
        Target(name: "Run", dependencies: ["App"]),
    ],

When access to other module class, target class's access level is must use open or public.
// modelName.swift

public class moduleName: Model {
...

Please note that you must also modify other method declarations according to this change.
Thanks.

A: move modelName.swift to run folder


Q: How to run android instrumental test using `androidx` and `navgation architecture`? I'm trying to write tests for an android app. Which has one Activity and two fragments (i.e FragmentOne and FragmentTwo) by clicking a button on FragmentOne it goes to the FragmentTwo. And I wrote the test for the same and I'm using androidx and navigation architecture. I have read this link and this link but didn't succeed.
Here is my current code-
ExampleInstrumentedTest
@RunWith(JUnit4::class)
class ExampleInstrumentedTest {

    @Test
    fun checkSecondFrag() {
        // Create a mock NavController
        val mockNavController = mock(NavController::class.java)

        // Create a graphical FragmentScenario for the OneFragment
        val oneFragmentScenario = launchFragmentInContainer<OneFragment>()

        // Set the NavController property on the fragment
        oneFragmentScenario.onFragment { fragment ->
            Navigation.setViewNavController(fragment.requireView(), mockNavController)
        }

        // Verify that performing a click prompts the correct Navigation action
        onView(ViewMatchers.withId(R.id.nextFragment)).perform(ViewActions.click())
        verify(mockNavController).navigate(R.id.action_oneFragment_to_twoFragment)
    }
}

Gradle(App)
apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.varun.navtesting"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'

    // Core library
    androidTestImplementation 'androidx.test:core:1.2.0'

    // AndroidJUnitRunner and JUnit Rules
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test:rules:1.2.0'

    // Assertions
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.ext:truth:1.2.0'
    androidTestImplementation 'com.google.truth:truth:0.42'

    // Espresso dependencies
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-intents:3.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-accessibility:3.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-web:3.2.0'
    androidTestImplementation 'androidx.test.espresso.idling:idling-concurrent:3.2.0'

    testImplementation 'junit:junit:4.12'

    implementation 'androidx.navigation:navigation-fragment-ktx:2.0.0'
    implementation 'androidx.navigation:navigation-ui-ktx:2.0.0'

    // required if you want to use Mockito for unit tests
    testImplementation 'org.mockito:mockito-core:2.25.0'
    // required if you want to use Mockito for Android tests
    androidTestImplementation 'org.mockito:mockito-android:2.19.0'

    // Fragment test
    implementation 'androidx.fragment:fragment:1.2.0-alpha01'
    androidTestImplementation 'androidx.fragment:fragment-testing:1.2.0-alpha01'

    implementation 'com.android.support:support-annotations:28.0.0'
}

Mainfiest
<?xml version="1.0" encoding="utf-8"?>
<manifest
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        package="com.varun.navtesting">

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme" tools:ignore="GoogleAppIndexingWarning">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <uses-library android:name="android.test.runner"
                      android:required="false"/>

        <uses-library android:name="android.test.base"
                      android:required="false"/>
        <uses-library android:name="android.test.mock"
                      android:required="false"/>
    </application>
    <instrumentation android:targetPackage="com.varun.navtesting"
                     android:name="android.test.ExampleInstrumentedTest"/>
</manifest>

This line
<instrumentation
          android:targetPackage="com.varun.navtesting"
          android:name="android.test.ExampleInstrumentedTest"/>

is showing in red color in android studio.
Here is the
Logcat
2019-07-30 22:00:16.967 6821-6837/com.varun.navtesting E/TestRunner: failed: checkSecondFrag(com.varun.navtesting.ExampleInstrumentedTest)
2019-07-30 22:00:16.967 6821-6837/com.varun.navtesting E/TestRunner: ----- begin exception -----
2019-07-30 22:00:16.968 6821-6837/com.varun.navtesting E/TestRunner: java.lang.RuntimeException: Unable to resolve activity for: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.varun.navtesting/androidx.fragment.app.testing.FragmentScenario$EmptyFragmentActivity (has extras) }
        at androidx.test.core.app.InstrumentationActivityInvoker.startActivity(InstrumentationActivityInvoker.java:344)
        at androidx.test.core.app.ActivityScenario.launchInternal(ActivityScenario.java:231)
        at androidx.test.core.app.ActivityScenario.launch(ActivityScenario.java:209)
        at androidx.fragment.app.testing.FragmentScenario.internalLaunch(FragmentScenario.java:299)
        at androidx.fragment.app.testing.FragmentScenario.launchInContainer(FragmentScenario.java:282)
        at com.varun.navtesting.ExampleInstrumentedTest.checkSecondFrag(ExampleInstrumentedTest.kt:39)
        at java.lang.reflect.Method.invoke(Native Method)
        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.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
        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.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.junit.runners.Suite.runChild(Suite.java:128)
        at org.junit.runners.Suite.runChild(Suite.java:27)
        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.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
        at androidx.test.internal.runner.TestExecutor.execute(TestExecutor.java:56)
        at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:392)
        at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2145)
2019-07-30 22:00:16.968 6821-6837/com.varun.navtesting E/TestRunner: ----- end exception -----

Any help will be appriciated.

A: As per the Fragment testing page, you must use debugImplementation for the fragment-testing artifact:
debugImplementation 'androidx.fragment:fragment-testing:1.2.0-alpha01'


Q: Day of week last year Im trying to calculate the date of the equivalent current day last year same week in standard SQL BigQuery.
For instance if the current date 2019-07-01 is a monday of week 27. I want to know the date of monday of week 27 last year (2018).
Current week would be select extract(isoweek from current_date())
but I don't know how to use this to calculate a date.
Expected output is 2018-07-02 if current date is 2019-07-01
The reason for this is that I want to compare current sales with same week and day of week as last year.
Any suggestions are appreciated.

A: Something like this should get you going...
with dates as (select * from unnest(generate_date_array('2018-01-01','2019-12-31', interval 1 day)) as cal_date),
       cal as (select cal_date, cast(format_date('%Y', cal_date) as int64) as year, cast(format_date('%V', cal_date) as int64) as week_num, format_date('%A', cal_date) as weekday_name from dates)
select c1.cal_date, c1.week_num, c1.weekday_name, c2.cal_date as previous_year_same_weekday
from cal c1
inner join cal c2
  on c1.year = c2.year+1 and c1.week_num = c2.week_num and c1.weekday_name = c2.weekday_name

The above query uses a week starting on a Monday, you may need to play around with the format_date() arguments as seen here to modify it for your needs.

A: This query returns no results, implying that SHIFT works. The function returns NULL if a year does not have the same number of weeks as its predecessor.
CREATE TEMP FUNCTION P_YEAR(y INT64) AS (
  MOD(CAST(y + FLOOR(y / 4.0) - FLOOR(y / 100.0) + FLOOR(y / 400.0) AS INT64), 7)
);

CREATE TEMP FUNCTION WEEKS_YEAR(y INT64) AS (
  52 + IF(P_YEAR(y) = 4 OR P_YEAR(y - 1) = 3, 1, 0)
);

CREATE TEMP FUNCTION SHIFT(d DATE) RETURNS DATE AS (
  CASE
    WHEN WEEKS_YEAR(EXTRACT(ISOYEAR FROM d)) != WEEKS_YEAR(EXTRACT(ISOYEAR FROM d) - 1)
      THEN null
    WHEN WEEKS_YEAR(EXTRACT(ISOYEAR FROM d)) = 52
      THEN DATE_SUB(d, INTERVAL 52 WEEK)
    ELSE d
  END
);

WITH dates AS (
SELECT d
FROM UNNEST(GENERATE_DATE_ARRAY('2000-12-31', '2020-12-31', INTERVAL 1 DAY)) AS d
)
SELECT
 d,
 EXTRACT(ISOWEEK FROM d) AS orig_iso_week,
 EXTRACT(ISOWEEK FROM SHIFT(d)) AS new_iso_week,
 SHIFT(d) AS new_d
FROM dates
WHERE EXTRACT(ISOWEEK FROM d) != EXTRACT(ISOWEEK FROM SHIFT(d))
  AND SHIFT(d) IS NOT NULL


Q: NSTextView Chinese/Unicode Characters I have a piece of text drawn in my cocoa app but I also need to draw it in a NSTextField and a NSTextView and look exactly the same, they all usually draw fine but if there are unicode or Chinese characters in the text then the NSTextView has large line spaces between the lines, it works perfectly in the nstextfield and when drawing normally.
I have tried every setting that I can find but none affect this issue, has anyone run into this issue before and know of a fix?
You can see the issue in a screenshot at http://cl.ly/3e0U1T2U2G2z341j3O3T

Here is my test code to show the issue
NSTextField *textField = [[NSTextField alloc] initWithFrame:NSMakeRect(5, 50, 100, 100)];
[textField setStringValue:@"え？移転！？ TESTTestTer 友達の旦那の店 THIS IS A TEST THIS IS A TEST"];
[textField setBordered:NO];
[textField setBezeled:NO];
[textField setAllowsEditingTextAttributes:YES];
[textField setDelegate:self];
[textField setFont:[NSFont fontWithName:@"LucidaGrande" size:12.0]];
[textField setTextColor:[NSColor colorWithDeviceRed:(74.0/255.0) green:(74.0/255.0) blue:(74.0/255.0) alpha:1.0]];
[[window contentView] addSubview: textField];

NSTextView *textView = [[NSTextView alloc] initWithFrame:NSMakeRect(200, 50, 100, 100)];
[textView setString:@"え？移転！？ TEST TestTer 友達の旦那の店 THIS IS A TEST THIS IS A TEST"];
[textView setDelegate:self];
[textView setFont:[NSFont fontWithName:@"LucidaGrande" size:12.0]];
[textView setTextColor:[NSColor colorWithDeviceRed:(74.0/255.0) green:(74.0/255.0) blue:(74.0/255.0) alpha:1.0]];
[[textView layoutManager] setTypesetterBehavior:NSTypesetterBehavior_10_2_WithCompatibility];
[[textView textContainer] setLineFragmentPadding:0.0];
[[window contentView] addSubview: textView];