text:
Q: How to display username of sender in chat app? I am using react-native-gifted-chat for my UI and for the backend, I am using AWSAppSync/GraphQL to store user data. I am not so sure how to go about displaying username of sender in my ChatApp and would need this feature for group chats. So far,  this is my code.
import React from 'react'
import { GiftedChat } from 'react-native-gifted-chat'

class ChatScreen extends React.Component {
  state = {
    messages: [],
    username: ''

  }

  componentWillMount() {
    this.setState({
      messages: [
        {
          _id: 1,
          text: 'Hello developer',
          createdAt: new Date(),
          user: {
            _id: 0,
            name: 'Default',
            avatar: 'https://placeimg.com/140/140/any',

          },

        },
      ],
    })
  }

  onSend(messages = []) {
    this.setState(previousState => ({
      messages: GiftedChat.append(previousState.messages, messages),
    }))
  }

  render() {
    return (
      <GiftedChat
        messages={this.state.messages}
        renderUsernameOnMessage={true}
        onSend={messages => this.onSend(messages)}
        user={this.username}

      />
    )
  }
}

export default ChatScreen;

A: Did you try this?
 <GiftedChat
        messages={this.state.messages}
        renderUsernameOnMessage={true}
        onSend={messages => this.onSend(messages)}
        user={this.state.username}
 />

A: In react native gifted chat user must be object containing the keys _id, name and avatar. _id will help it to separate sender and receiver. So yes, you have to set user with these properties. It not allowe only username.
So simple way to do this is that first fetch current user info from the server and store it into redux of asyncStorage. For example I am fetching current user from firebase as below :
export const getAccountInfo = () => {
  return async dispatch => {
    const cu = auth().currentUser;
    const user = await firestore().collection('users').doc(cu.uid).get();
    dispatch({
      type: Types.INFO_FETCHED,
      data: user.data()
    });
  };
};

Now, In my chat screen I set user as below :
<GiftedChat
  ...
  ...
  user={{
    _id: this.props.account?.user?.uid,
    name: this.props.account?.data?.fullName,
    avatar: this.props.account?.data?.avatar
  }}
/>


text:
Q: How to insert batch for multiple table using Spring NamedParameterJdbcTemplate? public int insertUser(User user) {
      String query = "insert into named_demo.user_details (f_name, l_name, email, password) values(:f_name, :l_name, :email, :password);
      +
     "insert into named_demo.media (user_id, media_type, media_url) values ((SELECT LAST_INSERT_ID()), :media_type, :media_url);";
    Map<String, Object> namedParameters = new HashMap<>();
    namedParameters.put("f_name", user.getFname());
    namedParameters.put("l_name", user.getLname());
    namedParameters.put("email", user.getEmailId());
    namedParameters.put("password", user.getPassword());
    namedParameters.put("media_type", 1);
    namedParameters.put("media_url", user.getMediaUrl());
    int[] value = jtemplate.batchUpdate(query, namedParameters);
}

Here I try to use batch processing in spring NamedParameterJdbcTemplate and insert data in multiple table.
. I try to insert data in user details table and i want to get table primary id using ((SELECT LAST_INSERT_ID())and insert into media table.
Can it possible by NamedParameterJdbcTemplate or we can use another approach. If anyone tried to before, please let me know.
Tnank you

A: It is possible to insert two tables at once using CTE query in postgresql:
with first_insert as (
    insert into address (address_description, address_type)
        values ('test', 0)
        returning id)
insert
into address_geometry(id, geom_text)
select id,'test2'
from first_insert;

You can wrap this query into another CTE to make 3 inserts, and so on.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where to post questions related to configuration management tools? I have questions related to configuration management tools.
Does Stack Exchange have an appropriate site for such questions, and if so which is it?
By configuration management tool, I'm thinking of Puppet, Ansible, SaltStack, Chef, and Cfengine.


text:
Q: How to backup Store Apps? I have been searching and I didn't find an optimal solution for my problem. I have some apps purchased from the Mac App Store (Pixelmator, GarageBand), and other ones installed (Xcode).
I want to know is there an efficient way to backup this apps, and reinstall them after I do a fresh install of my system.
P.S. I want to do this because Xcode's download size is too big, and my internet connection isn't the better around... Same with other apps.

A: The receipt data from the Mac App Store is stored inside the application bundles, so anything that backs up your Applications folder will do the trick. You don't need to worry about your proof-of-purchase being saved in some other location on your hard disk.
Time Machine is probably the simplest to set up, as it will back up your entire hard disk.


text:
Q: Custom advanced filtering I am using Wordpress to build a reasonably complex query builder and I am fairly close to completing it, I am essentially building up a large query based on the users options which looks something like the following:
(SELECT x_posts.* FROM x_posts LEFT JOIN x_term_relationships
ON (x_posts.ID = x_term_relationships.object_id) WHERE 1=1
AND (x_term_relationships.term_taxonomy_id IN (13) )
AND x_posts.post_type = 'articles' GROUP BY x_posts.ID ORDER BY x_posts.post_date DESC )
UNION
(SELECT * FROM x_posts where post_type = 'articles'
AND post_title LIKE '%he%' )

This gives me back a full response set that I intend on sorting through using PHP based on the users inputs. So far, the user has built up the result set but then further drill downs are required.
I cannot for the life of me work out how to join the Taxonomies / meta back into this thus allowing me to use php to filter the array returned form the DB.
Is there a way of appending / concatenating a join into the above query? Something like:
SELECT * FROM `wp_posts` wp
INNER JOIN `wp_postmeta` wm ON (wm.`post_id` = wp.`ID` AND
wm.`meta_key`='repeatable_fields')
INNER JOIN `wp_term_relationships` wtr ON (wp.`ID` = wtr.`object_id`)
INNER JOIN `wp_term_taxonomy` wtt ON (wtr.`term_taxonomy_id` =
wtt.`term_taxonomy_id`)
INNER JOIN `wp_terms` wt ON (wt.`term_id` = wtt.`term_id`)
AND wtt.taxonomy = 'location' AND wt.`slug`IN ('berlin','canada')
AND wp.post_status = 'publish' AND wm.meta_value LIKE '%July%'
ORDER BY wp.post_date DESC

The initial query can have multiple unions and be quite complicated. I am able to do all of the filtering via PHP.
Sorry if I am missing something, I haven't had to do this kinda crazy stuff with WordPress before.
Thank you,


text:
Q: How do I defend myself against the eagles? Every once in a while, an eagle will attack me from the sky while I'm outside, like how this video perfectly illustrates. How can I defend myself against them, besides shooting them before and after they attack me?
Is there a way to melee them when they are close, for instance? I don't recall there being a key prompt when they are attacking me though, like there are with other animals, like the crocodile.

A: There is no way to defend yourself against eagles once they attack you.
You can try to spot them before they swoop down and attack you, but you're going to look like a crazy person looking up every 5 seconds.

A: There's no way to shake or melee them, but shooting them before (or after if needed) is a good approach and isn't that hard.
1 - The Warning Cry
While it's true that eagles occasionally give a single, long call, before attacking they give a very distinctive cry: three high-pitched "skrees" in quick succession. Sometimes these are followed by the standard call.
The next time an eagle attacks you, just stand there for a while and let it come back for successive attacks, healing as needed, and learn to recognize the attack cry.
Over time that cry will probably start giving you an unpleasant jolt even if you're not specifically listening for it. (Thank you, Dr. Pavlov.)
2 - Initial Defense
When you hear the attack cry, either head for cover or look up quickly to counter-attack. From the start of the first "skree" you'll have 3-5 seconds until that unpleasant bird-bite cut scene.
With luck that'll give you time to look up and switch to an appropriate weapon. Shotguns or guns with a high fire rate (machine, SMG) are ideal.
3 - Payback
If you don't kill it the first time around, quickly switch to your camera and tag it, then wait. If you stay in the same area it should attack again fairly soon, and this time you'll be ready to eliminate the threat.

A: You can always run as fast as you can through vegetation. Usually a tree will get in the way and you'll be fine. Works for most predators and enemies as well, really.


text:
Q: Replace dot if behind or infront of a number I have loads of lines which looks like this:
"d6.der.ld"   "5.3355"    "0.4555"

I've done this in PowerShell which replaces the dot with a comma (,)
(Get-Content "data.tsv") | Foreach-Object {$_ -replace "\.", ","} | Set-Content "data.tsv"

Which works fine. But i would like it to only replace if a number 0-9 is both infront and behind the dot.
Thanks.

A: Use the below regex and then replace the matched dots with the string you want.
(?<=\d)\.(?=\d)

It matches all the dots only if it's preceded and followed by a digit character.

A: You can use this regex:
{$_ -replace "([0-9]<$1>)\.([0-9]<$2>)", "$1,$2"}

<$1> means you save the digit inside $1, allowing you to reuse it after


text:
Q: How to create a polygon on Google map using list of GPS location I have a list of customer (GPS coordinates) for each salesman in excel file. I want to create a polygon in Google map that shows area of each salesman in map.
Is there any tool that shows my salesman area in the Google map ?

A: For the first step it is easier to use Google Earth.
To display data you need a google kml file.
Create a placemark, and use the Polygon.
More, see https://developers.google.com/kml/documentation/kml_tut
To display a kml in google maps, the file has to be located on a server reachable by an url.
Ffor goggle earth a local file on your disk is sufficient.

A: For this problem, you may want to use a concave hull algorithm. You can read more in depth at https://gis.stackexchange.com/questions/39205/converting-point-sets-to-polygon-boundaries
In JavaScript, you can use https://www.npmjs.com/package/concaveman.


text:
Q: Connecting to multiple DB Instances from Code I was creating a console app that will execute a script in a DB and get some path location of several files and this tool will verify whether the file exist in that location or not.
currently I have a requirement that in the server the user has 2 sql instances.(eg., ABCD/test1, ABCD/test2)
So is it possible to connect to multiple instance from C# code and execute the script in each instance in a single run.
If possible how can I use the connection string?

A: If you're going to be doing low-level database access, this seems fine to me. Of course, if you only need one database connection open at any time, you could abstract most of the code into a method (that takes an SQL command/text as a parameter and returns the result), but this may not be the case in your situation.
You could also make things slightly neater by making use using of statements, as such:
using(var sqlConnectionA = new ...)
using(var sqlConnectionB = new ...)
{
    try
    {
        // Perform queries here.
    }
    catch (SqlException exSql)
    {
        // SQL error
    }
}


text:
Q: Setting a date variable in mysql Why does the following return a MEDIUMTEXT type?
set @entered_date = date "2015-01-01";
select @entered_date;

What would be the correct way to store a date in mysql and then later reference that?

A: You should probably be using single quotes for MySQL date literals:
set @entered_date = '2015-01-01';

Double quotes indicate database objects.  Note that you don't need the ANSI date keyword here.


text:
Q: have or has following "something and something" My work experience and education have provided me with an extensive background in business.
Do i use have/has here?

A: (both) My work experience and education have (both) provided me- with "both being implied in either part of the sentence.
However, this is not a strong opening sentence for a resume.  There is nothing to suggest that your work experience, or your education provided an "extensive background in business."
"I have an extensive background in business, beginning with my x years, at X school, majoring in x, followed by x years working in x areas of business."
My work experience and education have provided me with an extensive background in business.
Do i use have/has here?

A: It's ambiguous. You could be talking about two separate things or a single, combined thing.
More explicitly:

Both my work experience and education have provided me with an extensive background in business.

Or:

The combination of my work experience and education has provided me with an extensive background in business.

So, you can use either one. If you don't make your meaning explicit, it will be assumed by the verb form you choose. (Nobody will think that you got it wrong.)  If you use have, it will be interpreted as two things; if you use has, it will be interpreted as a single thing.


text:
Q: $f(x)=1/(1+x^2)$. Lagrange polynomials do not always converge. why? Let $f(x) = \frac{1}{1+x^2}$. Error of Interpolation with Lagrange polynomials for $n+1$ points is given by
$$
e(x)=f(x)-P_n(x)=\frac{f^{(n+1)}(\eta_x)}{(n+1)!}\prod_{i=0}^n (x-x_i)
$$
Carl Runge said that for this $f$, Lagrange polynomial $P_n$ do not converge uniformly. How can I show this?

A:
Any textbook answers this question by referring to Runge's work, which is dated, and not translated in English.

Not true. The textbook Numerical analysis by Kinkaid and Cheney refers to the article On the Runge example by James F. Epperson, published in: American Mathematical Monthly
Volume 94 Issue 4, April 1987; pages 329-341.
As the length of the article suggests, detailed treatment is a bit too long to reproduce here. Besides, the article is freely available from MAA website. (MAA publishes the journal, so I'm assuming this is a legitimate copy.)
As for the original question:

Carl Runge said that for this $f$, Lagrange polynomial $P_n$ do not converge uniformly.

This is rather vague. Lagrange polynomials do converge if the nodes are chosen well. Also, even with equidistant nodes they converge when the interval of interpolation is not too large. If you wanted to discuss a particular interval and a set of nodes, you should include it in the question. But read the aforementioned article first.

A: Here is an elementary proof that equispaced Lagrange polynomials on $[-a,a]$ do not converge at $b$ for $a=5$ and $b=4$ (and many other values). We assume an odd number of nodes $2n+1$, so the nodes are at $ak/n$ for $-n \leq k \leq n$; an even number of nodes is similar but notationally a little uglier. Let $p(x)$ be the Lagrange interpolating polynomial. Let $q(x) = \prod_{k=-n}^n (x-ak/n)$, the monic polynomial vanishing at the nodes.
So $p(x)(x^2+1)-1$ vanishes at the nodes, and we thus have
$$p(x) (x^2+1)-1 = q(x) r(x) \quad (\ast)$$
 for some polynomial $r(x)$. The polynomial $p$ has degree $\leq 2n$ and $q$ has degree $2n+1$, so $\deg r \leq 1$. Also, note that $p(x)$ is an even polynomial (obtained by interpolating an even function at symmetrically placed points) and $q(x)$ is an odd polynomial (a root at $0$, and all other roots mirror symmetric) so $r$ is odd. Thus, $r(x) = c x$ for some constant $c$.
We can compute $c$ by plugging in $x=i$. (If I were teaching this to students who fear complex numbers, I might first write $p(x) = f(x^2)$, $q(x) = x g(x^2)$, set $y=x^2$ and plug in $y=-1$. But here we will be fearless!)
$$p(i) \cdot 0 -1 = (c i) \prod_{k=-n}^n (i-ak/n) = (ci) \cdot i \cdot \prod_{k=1}^n (i^2 - a^2 k^2/n^2)$$
$$c =\frac{(-1)^n}{\prod_{k=1}^n (1+a^2 k^2/n^2)}.$$
Rearranging equation $(\ast)$ gives an exact formula for the error:
$$p(x) - \frac{1}{1+x^2} = \frac{c x q(x)}{1+x^2} = \frac{(-1)^n x^2 \prod_{k=1}^n (x^2-a^2 k^2/n^2)}{(1+x^2) \prod_{k=1}^n (1+a^2 k^2/n^2)}.$$
We see that the error goes to zero if and only if
$$\lim_{n \to \infty} \left( \sum_{k=1}^n \log {\Large |} x^2 - a^2 k^2/n^2 {\Large |} - \sum_{k=1}^n \log ( 1+a^2 k^2/n^2 ) \right) = - \infty.$$
The sums look like Riemann sums with spacing $a/n$, so the quantity in the limit is approximately
$$\frac{n}{a} \cdot \left( \int_{t=-a}^a \log| x^2 - t^2| dt - \int_{t=-a}^a \log( 1+ t^2) dt \right).$$
More precisely, we can justify turning sums into integrals as long as $x$ isn't too close to one of the nodes: For example, if we take a sequence of points $x_n$ approaching $x \in [-a,a]$, with $x_n$ always halfway between two nodes, this is valid.
So the limit will be $\pm \infty$ according to the sign of
$$\int_{t=-a}^a \log |x^2 - t^2| dt - \int_{t=-a}^a \log (1+t^2) dt.$$
The integrals can be done in closed form, but I'll close by just plotting the graph for $a=5$:

As you can see, the curve crosses the axis around $3.8$, which is exactly where the Lagrange polynomials stop converging.


text:
Q: Physical Database and Log File location How do I get the Physical Database and Log File location (file system path) of a DB in SQL Server 2005?
I used this to get the mdf file: {SELECT [Name], FileName FROM sysdatabases} but need to get the log file as well...
Cheers,
Conor

A: SELECT * FROM sys.database_files

A: Here is another way
select * from sys.sysaltfiles

A: You should be using sp_helpdb or sp_helpfile for this.
e.g:
sp_helpdb 'master'

A: try this T-SQL Statement provides the logical name and the physical location of the data/log files of all the databases available in the current SQL Server instance:
SELECT db_name(database_id) as DatabaseName,name,type_desc,physical_name FROM sys.master_files

If you are using SQL Server 2000, you could execute the following T-SQL Statement:
SELECT db_name(dbid) as DatabaseName,name,filename FROM master.dbo.sysaltfiles

A: I used the following script to retrieve the data/log file names and paths:
declare @DBName                 sysname
        , @LogicalDataFile      sysname
        , @LogicalLogFile       sysname
        , @PhysicalDataFile     nvarchar(260)
        , @PhysicalLogFile      nvarchar(260)

set @DBName = '<database-name>'

-- Data file
select  @LogicalDataFile = name
        , @PhysicalDataFile = physical_name
from    sys.master_files
where   database_id = db_id(@DBName)
        and type_desc = 'ROWS'

-- Log file
select  @LogicalLogFile = name
        , @PhysicalLogFile = physical_name
from    sys.master_files
where   database_id = db_id(@DBName)
        and type_desc = 'LOG'

select  @LogicalDataFile as [@LogicalDataFile]
        , @LogicalLogFile as [@LogicalLogFile]
        , @PhysicalDataFile as [@PhysicalDataFile]
        , @PhysicalLogFile as [@PhysicalLogFile]

Credit for the script goes to this blog entry:
http://sqlblogcasts.com/blogs/davidwimbush/archive/2009/07/28/how-to-get-the-logical-and-physical-file-names-for-a-database.aspx


text:
Q: Does Twisted Fate's Ult grant vision during Nocturne's Ult? If Twisted Fate ults, and then an enemy Nocturne ults, will Twisted Fate's team have vision of their opponent's champs? If not, does that mean Nocturne's ultimate effectively counters Twisted Fate's ult if used after?

A: Nocturne's ultimate takes priority.

A: If Nocturne uses his ultimate AFTER Twisted Fate, the map would be blacked out, because Nocturne's ultimate takes priority as it was cast after TF's. Because of this, Nocturne's ultimate does counter Twisted Fate's.


text:
Q: SQL various combination for group by I have a table with column names:
category1, category2, category3, Value
I want to get the following combinations from table:
---> category1,count(*)

---> category1, category2, count(*)

---> category2, category3, count(*)

Is there a way to do this in just one query or do I really need to write 3 separate queries? I am thinking of design like following:
Category1, Category2, Category3, CountNumber

Where the for case 1, category2 and category3 columns would be blank and for case 2 category 3 column would be blank, etc.
--------EXAMPLE---------------------------------------------------------
Cat1           Cat2          Cat3        Value
a              NULL           d1           13
b              e1             d1           13
a              e2             d1           13
c              NULL           d2           13
a              e1             d1           13
a              NULL           d1           13
--------DESIRED OUTPUT -------------------------------------------------
Cat1           Cat2           Cat3           CountNumber
a              NULL           NULL           4
b              NULL           NULL           1
c              NULL           NULL           1
a              e1             NULL           1
c              e1             NULL           0
NULL           e1             d1             2

and so on
Thanks

A: Try this
Select category1, null Category2, null category3, count(*)
from table
group by category1
UNION ALL
Select category1, category2, null category3, count(*)
from table
group by category1, category2
UNION ALL
Select null  category1,category2, category3, count(*)
from table
group by category2, category3

To insert rows in tmp table
SELECT * INTO TmpTable FROM (
Select category1, null Category2, null category3, count(*)
from table
group by category1
UNION ALL
Select category1, category2, null category3, count(*)
from table
group by category1, category2
UNION ALL
Select null  category1,category2, category3, count(*)
from table
group by category2, category3) x


text:
Q: Right-continuous for every decreasing sequence Let $f \colon I \to \overline{\mathbb{R}}$ a function. I want to show that $f(x_n) \to f(x)$ for every sequence $(x_n)$ with $x\leq x_n$ and $x_n \to x$ iff $f(x_n) \to f(x)$ for every strictly decreasing sequence $(x_n)$ with $x\leq x_n$ and $x_n \to x$. But I don't know how i can do this. Can I maybe use the sequence $a_k= \sup_{n \geq k} x_n$?

A: One direction ($\implies$) of the equivalence is trivial. For the other direction ($\impliedby$) assume that $(x_n)$ is a sequence with $x_n \ge x$, $x_n \to x$, but $f(x_n) \to f(x)$ does not hold. Then you can extract a subsequence $(x_{n_k})$ such that $(f(x_{n_k}))$ is convergent, with $f(x_{n_k}) \to c \ne f(x)$. Note that $x_{n_k} > x$ must hold for all but finitely many $k$. Finally extract a strictly decreasing subsequence $(x_{n_{k_j}})$ to get a contradiction.
This is an example of the following principle:

Let $(a_n)$ be a sequence with the property that every subsequence of $(a_n)$ has a subsequence that converges to $A$. Then $(a_n)$ converges to $A$.


text:
Q: How to download a pdf with python or curl? I want to download a PDF file using Python. I am aware that there are several SO Q&A about this issue. However, I was only able to find cases where the URL follows this format http://www.example.com/example.pdf.
The URL I use to download the file is the following: http://dof.gob.mx/nota_to_pdf.php?fecha=25/07/2018&edicion=MAT. If I open a browser and paste the URL in the search bar, I am taken to a blank page where I am prompted to save the file.
When I try to use the methods shown in several tutorial sites, or try to follow the advise I find in other SO questions, I am only able to download the HTML, the same thing happens when I try to do it using curl in the terminal.
Any help will be deeply appreciated.

A: Hi there and welcome to Stack Overflow!
If you want to use Python use the requests library to get the initial page to check out the content (you will need to install it first via pip or pipenv):
>>> import requests
>>> r = requests.get('http://dof.gob.mx/nota_to_pdf.php?fecha=25/07/2018&edicion=MAT')
>>> r.status_code
200
>>> r.headers['content-type']
'text/html; charset=UTF-8'
>>> r.encoding
'UTF-8'
>>> r.text
'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r\n\r\n\r\n<meta http-equiv="Content-
Type" content="text/html; charset=utf-8" />\r\n<title>Diario Oficial de la
Federación</title>\r\n\r\n\r\n\r\n\r\n\r\n\n\n<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">\n\t\n\n\n\n
<input type="hidden" value="25072018-MAT.pdf" id="pdf" name="pdf">\n\n

\n\n\n\n'

If you dig through that HTML, you will see that the page uses self.location to redirect to the PDF file when the page loads.
The actual URL for the PDF is:
http://dof.gob.mx/abrirPDF.php?archivo=25072018-MAT.pdf&anio=2018&repo=

So, if you do the same process again with the requests library, this time specifying the actual PDF file:
>>> import requests
>>> r = requests.get('http://dof.gob.mx/abrirPDF.php?archivo=25072018-MAT.pdf&anio=2018&repo=')
>>> r.status_code
200
>>> r.headers['content-type']
'application/pdf'

Now you have the PDF in the body of the request.
You can do the same with cURL -- you just need to ensure that you are grabbing the right thing (which admittedly is obfuscated by the webpage javascript function, probably by design).
I hope that helps!

A: A function doing the job with a progress bar:
from tqdm import tqdm
import requests

def download_file( url, filename):
    response = requests.get(url, stream=True)

    with open(filename, "wb") as handle:
        for data in tqdm(response.iter_content()):
            handle.write(data)


text:
Q: Add Flutter method channel to the IOS share extension I want to add the Flutter platform channel in an iOS share extension ( Is this even possible?
In the main app's AppDelegate I would simply use something like this:
let controller : FlutterViewController = window?.rootViewController as! FlutterViewController

let channel = FlutterMethodChannel(name: "<channelName>",
                                                binaryMessenger: controller.binaryMessenger)

In the FlutterMethodChannel initialization, a binaryMessenger of the type FlutterBinaryMessenger is required.
In the ShareViewController I tried to create a class of the type FlutterAppDelegate, and create there FlutterViewController
But turns out the controller is null.
   @objc class ExtDelegate: FlutterAppDelegate {
func invokeMethod(
    ) -> Bool {
  let controller = (window.rootViewController as! FlutterViewController)
  let methodChannel =
      FlutterMethodChannel(name: "task-identifier", binaryMessenger: controller.binaryMessenger)
        methodChannel.invokeMethod("fetchImage", arguments: "Arg-s")
      return true
    }
}

Any ideas on how to realize this?

A: Step 1:
Use this link
https://docs.flutter.dev/development/add-to-app/ios/add-flutter-screen?tab=engine-swift-tab
Step 2:
I prefer to use UIViewControllerRepresentable
As this
import Flutter
struct FlutterView: UIViewControllerRepresentable {
typealias UIViewControllerType = FlutterViewController

    var callbackPressBack: (() -> Void)?

func makeUIViewController(context: Context) -> FlutterViewController {

    let controller = FlutterViewController(project: nil, nibName: nil, bundle: nil)
    let mainChannel = FlutterMethodChannel(name: "com...... From flutter",
                                           binaryMessenger: controller.binaryMessenger)

    mainChannel.setMethodCallHandler({
        (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
        // This method is invoked on the UI thread.

        print("Method \(call.method)")

        if call.method == "back" {
            print("BACK")
            callbackPressBack?()
        }
    })
    return controller
}

func updateUIViewController(_ uiViewController: FlutterViewController, context: Context) {
    // Updates the state of the specified view controller with new information from SwiftUI.
}

}
Step 3: To use it using SwiftUI
struct FlutterSwiftUI : View {
var body: some View {
FlutterView ()
}
}


text:
Q: Kill jobs from the background I have two jobs running
me@me:~$ jobs
[1]-  Running                 emacs --daemon &
[2]+  Running                 emacs &

I want to kill the job 1 and get it done in a cumbersome way
fg 1
Ctrl + C

Is it possible to kill it on the background without put it to the forewords.

A: You may find this link helpful.
Basically, type jobs to see a job list, and type kill %{job #} to kill a specific one.
So in your example, kill %1 should do the trick.


text:
Q: Regular Expression Get US Zip Code How do I "extract" zip code (US) from the following string?
import re
address = "Moab, UT 84532"
postal_code = re.match('^\d{5}(-\d{4})?$', address)
print postal_code

A: Firstly, you are using match, which will match only from the beginning of the string: see http://docs.python.org/library/re.html#matching-vs-searching
Also, even if you were using search, you are not grabbing the group that includes the 5 digits that are guaranteed to be there.
Lastly, even if you were using search, starting your regex with a carat ^ will force it to search from the beginning, which obviously won't work in your case.
>>> postal_code = re.search(r'.*(\d{5}(\-\d{4})?)$', address)
>>> postal_code.groups()
('84532', None)

A: Assuming the zip code is always 5 digit (is that the case in the US is it not?)
re.match('\d{5}$', address)

will do.
Comment is right about match vs search and if I want to include the extra 4 chars:
re.search('\d{5}(-\d{4})?$', address)

should do it.

A: you can use :
postal_code = re.match('^.*?(\d+)$', address)
if postal_code is not None:
    print postal_code.group(1)

A: This one works perfectly for all these formats:
99999-9999
99999 9999
99999
address = '123 Main St, 12345-5678 USA'
re.search('(\d{5})([- ])?(\d{4})?', address).groups()

The result is: ('12345', '-', '5678')
To get the whole match, use:
re.search('(\d{5})([- ])?(\d{4})?', address).group(0)

And group(1) & group(3) contain both portions of the zip code. I use match instead since I am applying this to a field that contains a zip code only. I also added ^ $ at the beginning and end respectively for this case.
zip_code = '12345-6655'
re.match('^(\d{5})([- ])?(\d{4})?$', zip_code).group(0)


text:
Q: Remove items from listview on its ItemClickListener I am using a collection of ArrayList to fill my Listview. My ListView contains two separate rows types.

Header and Footer.

I am trying to achieve the ExpandableListView Functionality on my Listview from which I am trying to remove some items on click of header till next header.
I am using this function to loop through items and removing items
private void removeItems(int value)
{   Log.e(Constant.LOG, items.size()+"");
    for (int i = value;i < items.size(); i++) {
        if(!items.get(i).isSection())
            items.remove(i);
    }
    Log.e(Constant.LOG, items.size()+"");
    adapter = new EntryAdapter(this, items, this);
    mListView.setAdapter(adapter);
}

QUESTION IS : I am not able to remove all items from the list in one shot, some stays there !

I have tried looping through adapter.count(); but no luck
My List :
SECTION 1
ITEM 1
ITEM 2
Item N
Section 2
But when I click on Section 1 not all ITEMS get deleted in one shot WHY!
I am not able to use Expandable Listview at this stage because activity contains many more complex functionality on List. Please help me where I am going wrong!

A: Create a new ArrayList<Collection> , Then add your item in it and then use removeAll(collection).
TRY THIS:
  private void removeItems(int value)
  {   Log.e(Constant.LOG, items.size()+"");
   ArrayList<Collection> deleteItems= new ArrayList<Collection>();

  for (int i = value;i < items.size(); i++) {
    if(!items.get(i).isSection())
       deleteItems.add(items.get(i));
}
 items.removeAll(deleteItems);
 Log.e(Constant.LOG, items.size()+"");
 adapter = new EntryAdapter(this, items, this);
 mListView.setAdapter(adapter);
 }

EDIT
Every time you are deleting an item, you are changing the index of the elements inside .
e.g :  let suppose you are deleting list1 , then list[2] becomes list1 and hence your code will skip list1 next time because now your counter would be moved to 2.
Here are other ways by which you can achieve this also,
Removing item while iterating it

A: So what exactly I did now. Instead of looping through items again I did like this :
I created another list and parallely populate it with the main array.
items.add(user);
// after populating items did this
newItems.addAll(items);  // same collection ArrayList

and finally I can play with the main array by using removeAll and addAll methods.
items.removeAll(newItems);  // remove items
items.addAll(afterPosition,newItems); // add items after position


text:
Q: Bottom Up reference in Ms Excel I'm doing seating arrangement for an exam.
Sheet1 - A1:A5 (Contains Roll numbers)
1
2
3
4
5

I want this in Sheet2 Bottom up reference from another sheet
Sheet2 - A1:15
5
4
3
2
1

I did This
1. In Sheet2 A5 =Sheet1:A1
2. In Sheet2 A4 =Sheet1:A2
3. Dragged up after selecting these two cells.
This is not working.

A: Put following formula to Sheet2 A1 cell then drag and down
=LARGE(Sheet1!$A$1:$A$5,ROW(1:1))


text:
Q: c# json force patch Let's say there an empty is JSON object:
String obj1 = "{}";

Is there a way to patch update it and force creation of missing path using C#?
So after patch like this:
{ "op": "add", "path": "/a/b", "value": "foo" },

the result will be: { a: { b: "foo" } }

A: not sure what is your problem exactly, if I'm wrong my bad, you can create those custom json objects in C# using System.Dynamic.ExpandoObject or using IDictionary, or both as in my example (case I'm lazy),
as in the comments being said this is more like a parse, not a transform:
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;

namespace ExpandoObject
{
    class Program
    {
        static void Main(string[] args)
        {
            string stringObj;
            stringObj = "{\"op\": \"add\", \"path\": \"/a/b\", \"value\": \"foo\"}";
            Console.WriteLine(JsonConvert.SerializeObject(GetObjectPatchResult(stringObj)));
            stringObj = "{\"op\": \"add\", \"path\": \"/a/b/c/d/e/f/g/h/i/j\", \"value\": \"foo\"}";
            Console.WriteLine(JsonConvert.SerializeObject(GetObjectPatchResult(stringObj)));
        }

        private static object GetObjectPatchResult(string param)
        {
            dynamic expando = new System.Dynamic.ExpandoObject();
            var result = (IDictionary<string, object>)expando;
            var parchObject = JsonConvert.DeserializeObject<PatchObject>(param);
            var level = result;
            int i = 0;
            foreach (var path in parchObject.Path.Split('/'))
            {
                i++;
                if (string.IsNullOrEmpty(path)) continue;
                dynamic pathExpando = new System.Dynamic.ExpandoObject();
                level[path] = (IDictionary<string, object>)pathExpando;
                if (i < parchObject.Path.Split('/').Count())
                {
                    level = (IDictionary<string, object>)level[path];
                }
                else
                {
                    level[path] = parchObject.Value;
                }
            }
            return result;
        }
    }

    public class PatchObject
    {
        public string Op { get; set; }
        public string Path { get; set; }
        public string Value { get; set; }
    }
}

result:

{"a":{"b":"foo"}}
{"a":{"b":{"c":{"d":{"e":{"f":{"g":{"h":{"i":{"j":"foo"}}}}}}}}}}
Press any key to continue . . .


text:
Q: Keep history of deleted characters in Notepad I am monitoring Notepad activities.  I want the character that gets deleted when we press backspace or delete.
In addition, I don't want to modify the existing clipboard contents.

A: The only way I can think of where it might be possible to do something like this is to inject a DLL into notepad which would let you automate it but I'm not sure if it could pick up this.
An article about how to do this can be found at:
http://www.codeproject.com/KB/COM/automatingwindowsapps.aspx
However, I'd think that it might actually be easier to write your own notepad replacement that could do this for you. Possibly you could just download the source for NotePad++ or similar and amend it.

A: It may not be the best solution, but you can do almost anything like this with a little creativity and AutoHotKey.
Here's a sample AHK script I wrote.  It executes custom code whenever a user presses backspace or delete in a notepad window.  Pressing Ctrl+Shift+z will give you a message box with the delete history.  It does make use of the clipboard, but it restores it back to the original value.
This was a 5 minute hack, so I'm sure there are issues with it.  Use at your own risk :)
#NoEnv
#SingleInstance
SendMode Input

_removalHistory =
_backupClipboard =

#IfWinActive, ahk_classNotepad
{
    Backspace::Delete("left")
    Delete::Delete("right")
    ^+z::MsgBox %_removalHistory%
}

Delete(direction) {
    global

    BackupAndClearClipboard()

    length := GetSelectedLength()
    if length = 0 SelectOneCharacter(direction)

    Copy()
    _removalHistory = %_removalHistory%%clipboard%
    Send {Delete}

    RestoreClipboard()
}

GetSelectedLength() {
    local length = 0
    Copy()
    StringLen, length, clipboard
    return length
}

SelectOneCharacter(direction) {
    if (direction = "left") {
       Send +{Left}
    }
    else if (direction = "right") {
       Send +{Right}
    }
}

Copy() {
    Send ^c
    ClipWait 0.01
}

BackupAndClearClipboard() {
    global
    _backupClipboard := ClipboardAll
    clipboard =
}

RestoreClipboard() {
    global
    clipboard := _backupClipboard
    _backupClipboard =              ;free memory
}


text:
Q: Inserting different strings read from file in a linked list I'm writing a programm in c that reads words from a file, and adds the different from them in a linked list. However, i don't get the right result.I have problem finding if a word exists in the list. Any help could be appreciated.Thanks.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

struct list_el {
   char val[30];
   struct list_el * next;
};

typedef struct list_el item, item2;

void main() {

    item * curr, * head, * curr2, * head2;
    FILE *fp;
    char words[30];
    int i;

    head = NULL;
    head2 = NULL;
    if ((fp=fopen("file.txt","r"))==NULL)
        printf("cannot open file\n");
    i=0;
    while (fscanf(fp,"%s",&words)!=EOF) {
        if (i!=0)
            while(curr2) {
                if  (!strcmp(words,curr2->val)){
                    break;
                }
                curr2 = curr2->next ;
            }
        if (curr2==0 || i==0){
            curr = (item *)malloc(sizeof(item));
            curr2 = (item2 *)malloc(sizeof(item2));
            strcpy(curr->val,words);
            strcpy(curr2->val,words);
            curr->next  = head;
            curr2->next = head2;
            head = curr;
            head2 = curr2;
        }
        i++;
    }
    while(curr) {
      printf("%s\n", curr->val);
      curr = curr->next ;
    }
    fclose(fp);
}

A: int main(void) {//void main() is invalid.
    item *curr, *head = NULL;
    FILE *fp;
    char words[30];

    if ((fp=fopen("file.txt","r"))==NULL){
        printf("cannot open file\n");
        return EXIT_FAILURE;//can't continue
    }
    while (fscanf(fp,"%29s", words) != EOF) {//remove &
        curr = head;
        while(curr) {//Search the current list
            if  (!strcmp(words, curr->val)){
                break;
            }
            curr = curr->next;
        }
        if (curr == NULL){//not find words
            item *node = malloc(sizeof(*node));
            strcpy(node->val, words);
            node->next  = head;
            head = node;
        }
    }
    fclose(fp);

    curr = head;
    while(curr) {
      printf("%s\n", curr->val);
      curr = curr->next ;
    }
}


text:
Q: Vue-strap Carousel: How to select specific slide I have managed to create a carousel (slider) using Vue-strap carousel component with the following code:
<carousel>
        <slider  v-for="(photo,index) in photos"  :key="photo.sequenceID" >

        </slider>
</carousel>

Carousel is working. I also display thumbnails of images on the page. I want to select a specific slide when I click a thumbnail.
How can I display a specific slide in the carousle? Is there a function in Vue-strap carousle or slider that can displays specific slide if I pass the slide number?

A: The following code will display the slide fo the pictureID. It uses the indicatorClick() method of the carousel component. Here vm is the Vue object name.
vm.$children[0].indicatorClick(pictureID);

A: Late reply:
You can use the navigateTo prop as follows:
template.vue > tamplate/transition
<carousel
  :perPage="1"
  :navigateTo="carouselPosition"
  :navigationEnabled="true"
  :paginationEnabled="false">
  <slide>
    ...
  </slide>
</carousel>

carouselPosition should be stored as a prop:
template.vue > export default {}
data () {
  return {
    carouselPosition: null // OR 1
  }
}

Include the following on your thumbnail element:
template.vue > component thumbnail
v-on:click=";(carouselPosition = index)"

In this case the index value would be generated in a loop:
template.vue > component loop
v-for="(thumbnail, index) in yourData"

NOTE: Nuxtjs used in this example but it should easy to modify these examples to your needs.

A: Using v-model
See Carousel documentation;

Programmatically control which slide is showing via v-model (which binds to the value prop). Note, that slides are indexed starting at 0

Inside my slide I use a img for every thumbnail. Upon click currentSlide is changed to the index of the thumbnail.

store currentSlide in data:
data() {
  return {
    currentSlide: 0
  }
}

method for changing currentSlide
showImage (index) {
  this.currentSlide = index;
}

Vue will update the value prop of the slider if the v-model reference is changed.

A: use v-bind:data-slide-to="index"


text:
Q: center text in undersized div I'm trying to get text centered inside a fixed with div, which will allow overflow, but I can't seem to get it to center inside the div.
I've made a jsfiddle to show you what i mean: http://jsfiddle.net/mdHKZ/3/
The problem is that once the text begins to overflow the div, it will no longer be centered. However, I can't expand the div, because that would defeat the purpose of me having a fixed width div. Is there any way to achieve what I'm trying to do?

A: I don't think it's possible to do this dynamically with straight css, but if you know the width of your text ahead of time you could specify a negative margin-left on the contents: jsFiddle
If you wanted to do this dynamically (i.e. to have the text centered in a small div for any width of text) I think you'd have to use javascript.
Edit: Here's an updated jsFiddle with the margin set using jQuery: jsFiddle
HTML:

    Sample Text Sample Text Sample Text

jQuery:
var $hack = $('#hack');
var innerWidth = $hack.width();
var outerWidth = $hack.parent().width();
if(innerWidth > outerWidth) {
    var marginLeft = -1 * (innerWidth - outerWidth)/2;
    $hack.css('margin-left', marginLeft);
}

CSS:
.contents {
  margin-left: 150px;
  text-align: center;
  width: 100px;
  white-space: nowrap;
  border: 1px solid;
  margin-bottom: 20px;
}

A: change overflow to "auto" instead of "visible"

A: Do you know what the width of the div inside is going to be?  I'm not sure if you'll be able to get to do it automatically based on a variable width.  I was able to get to center with a static width:

Sample Text Sample Text SamText Sampl eple

I had to set the width to 200px and then substract half of it with margin-left.  I couldn't get it to work with something more generic like "margin-left: 50%", because it will only shift left -75px (half of 150px) from the outter div


text:
Q: Can this conditional be shortened? Is it possible to just use .get() function from dictionary for this? Is this the best we can do to shorten this piece of code?
n_dict is a Dict type (uppercase D) and NES is just a list of str
eted_info = {}
for key in n_dict:
    if key in NES:
        eted_info[key] = n_dict[key]

I'm just curious if there is a better / more pythonic way to retrieve a value, like C# has with TryGetValue.

A: I think a dictionary comprehension and using n_dict.items() is the cleanest way of doing this
n_dict = {'a': 1, 'b': 2, 'c': 3}

NES = ['a', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

eted_info = {key:value for key,value in n_dict.items() if key in NES}

print(eted_info)

RESULT
{'a': 1, 'c': 3}

A: You can do something with dictionary comprehension like this:
eted_info = {key: n_dict[key] for key in n_dict if key in NES}

A: If you want to avoid the O(n^2) operation of iterating through each item in NES for each item in n_dict, you can build a list of keys as a set intersection and iterate through that:
eted_info = {k: n_dict[k] for k in set(n_dict) & set(NES)}

A: Iterate over keys in NES; use n_dict.get.get with a default of None; conditionally add to eted_info.
for key in NES:
    v = n_dict.get(key,None)
    if v: eted_info[key] = v

*

*This will only iterate over the list once regardless of the length of n_dict.

*Assumes all values in n_dict are truthy. Other placeholders could be used for the default value.


text:
Q: How to find path to a field in a graphql query I am very new to graphql. I have a following graphql query for an example:
query pets {
  breed(some arguments)
  {
    name
    items
    {
      owner(some arguments)
      {
        items
        {
          ID
          ownerSnumber
          country
          address
          school
          nationality
          gender
          activity
        }
      }
      name
      phoneNumber
      sin
    }
  }
}

Is it possible to parse a gql query and get the path of a field in the query?
For example I would like to get the path of 'ID'. For example from the above query, is it possible to get the path where the ID is: owner.items.ID

A: With https://graphql.org/graphql-js/ it exposes a fourth argument called resolve info. This field contains more information about the field.
Have a look at GraphQLObjectType config parameter type definition:

A: With a good start from the earlier answer, relying on the ResolveInfo you could do something like a recursive check going from child to parent:
export const getFieldPath = (path: Path): string => {
  if (!path.prev) return `${path.key}`

  return `${getFieldPath(path.prev)}.${path.key}`
}

And later in your resolver you could use it like:
const myFieldResolver = (parent, args, ctx, info) => {
  const pathOfThisResolversField = getFieldPath(info.path)

  // use your pathOfThisResolversField

  return yourFieldResolvedData
};

Worth noting though, the solution above will include every node all the way to the query root, rather than just the ones you mentioned owner.items.ID


text:
Q: How to combine the results of two queries into a single dataset (one above the other) and still display the titles of the table below This is the query I tried (it's simplified and doesn't include joins). It lets me display one table below the other but it doesn't show the column titles for the one below.
SELECT column1, column2
FROM Table1
UNION
SELECT column2, column3
FROM Table2
I'm getting the following output
column1 | column2
  val1      val2
  val3      val4

The output I need for my project is:
column1 | column2
  val1      val2

column3 | column4
  val3      val4

It would be extremely helpful if anyone knew how to display it in this way! :)

A: One query can only return a specified set of columns.  If you want all four columns, then you need four columns in the result set:
SELECT column1, column2, NULL as column3, NULL as column4
FROM Table1
UNION ALL
SELECT NULL, NULL, column3, column4
FROM Table2;


text:
Q: Building Mobile Apps out of HTML5, with motion tracking? This is an open question and I was really hoping for advice...
I am planning on creating a mobile app which will track your steps and distance (based on GPS), while sitting in your pocket.
I was planning to make the app out of html5 as I know you can calcualte the motion of the device using this
So, I am really asking if people think this is possible on HTML5?
Thanks

A: Assuming you know JavaScript, you should be able to accomplish this with PhoneGap's Geolocation object.
Appcelerator has Titanium.Geolocation as well.

A: If you plan to do it with HTML5 and PhoneGap is probably your best option. But you'll still need to program a background service* in order to handle tracking the location while the app isn't actively in use.
It sounds like the real work will need to be done in Java either way so I think you should just make a regular Android application. But as I said PhoneGap is still an option for the interface if that's what you really want.
* The background service will still need to be done with Android API's. Which would then need to be hooked into PhoneGap. It might just be simpler to make a native app.


text:
Q: TypeScript dynamic property type on class There is a way to declare the type of dynamic class property if it's accessed by [] operator, like on the following example:
class Foo {
  [key: string]: number;
}

let a = new Foo();
let b = a['bar']; //Here, the compiler knows that b is a number

But is there a way to declare the same thing, without [] operator?
A way to write this:
let a = new Foo();
let b = a.someProperty;

And letting TypeScript knows that someProperty is of type number, because we say to it: All unknown properties on Foo are of type number.

A: I do not think its is possible. When you define class you define 'static' information about its properties and methods. If you specify indexer - it means just that - that the objects of the class will have indexer, not any properties. Thats what classes are for after all - to define structure of your business entities.
The only way I am aware of doing something similar to what you want is by using object literals. For example this will work:
let x: { PropA: number, [x: string]: number };
x = { PropA: 1, PropX: 2, PropY: 3, PropZ: 4 };

Hope this helps.


text:
Q: $L^2$ convergence from convergence in distribution and uniform integrability Is it true that if $X_n \to X$ in distribution and $\{X_n^2\}$ are uniformly integrable then $X_n \to X$ in $L^2$

A: No: let $X$ be a random variable such that $\mathbb P\{X=1\}=\mathbb P\{X=-1\}=1/2$ and $X_n=X$ for $n$ even, $X_n=-X$ for $n$ odd. Since $X$ is symmetric, the sequence $\left(X_n\right)_{n\geqslant 1}$ converges in distribution to $X$. Since $X_n^2$ equals $1$ almost surely, the sequence $\left(X_n^2\right)_{n\geqslant 1}$ is uniformly integrable. But
$X_{2n+1}-X=-2X$, which does not converge to $0$ in $\mathbb L^2$.


text:
Q: How to include Google Analytics in preact Please let me know how to include google analytics in preact? I found someone did in react as follow
  componentDidMount() {
    window.ga = window.ga || function() { (ga.q = ga.q || []).push(arguments)  }; ga.l = +new Date;
    const account = this.props.account;
    // const scriptProtocol = ("https:" === document.location.protocol ? "https://ssl" : "http://www");
    const scriptSrc = `//google-analytics.com/analytics.js`;
    jQuery.getScript(scriptSrc, () => {
      // Track Route changes
      ga("create", account, "auto");
      if(this.props.history) {
        this.props.history.listen((newLocation) => {
          ga("send", "pageview", newLocation.pathname);
        });
      }
    });
  }

But problem is this person used jQuery in the above code which goes undefined. Please let me know how to solve it.

A: You can use the react-ga dependency to achieve this.
As mentioned in that project's documentation: add it as a dependency with npm install react-ga --save  (if you're using npm, for example), then simply add this code to your main component:
import ReactGA from 'react-ga';
ReactGA.initialize('UA-000000-01');
ReactGA.pageview(window.location.pathname + window.location.search);

react-ga also has function calls to do the same you would do with your jQuery approach, like sending pageviews and other data to Google Analytics.

A: For working with jquery follow this
try installing npm install jquery
then import jquery as following
import jQuery from 'jquery';

Other method for adding google analytics is add the following code which dose't require jquery
 (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', '***YOUR ID HERE****', 'auto');
  ga('send', 'pageview');


text:
Q: Read JSON Multipart request in php Android is sending data to server in JSON format. It includes image files in request. Request type is multi-part.
I tried below. but no luck.
function  readInputStream() {
    $return_array = array();
    $body = @file_get_contents('php://input');
    if(get_magic_quotes_gpc())
    {
        $body = stripslashes($body);
    }
    // check if body is compressed or not
    if (strlen($body) < 18 || strcmp(substr($body,0,2),"\x1f\x8b"))
    {
        $body = $body;
    }
    else
    {
        $tbody = $this->gzdecode($body);
        $body = $tbody;
    }
    if(!empty($body))
    {
        $return_array = json_decode($body, true);
    }

    return $return_array;

}

I tried this with $_POST method , It works with that but want to know what wrong in above code.

A: The code you have is for parsing a JSON request body.
You have a Multipart request body.
Multipart can contain JSON but it isn't JSON itself.


text:
Q: Button is not fired normally and fired when UseSubmitBehavior="false" but textbox values are coming null I am using ASP button its working properly at client side but on server side its not firing.

            LoginName
            <asp:TextBox ID="txt_LoginName" runat="server"></asp:TextBox>

             Password
             <asp:TextBox ID="txt_Password" TextMode="Password" runat="server"></asp:TextBox>

        <asp:Button ID="btn_SignIn" OnClientClick="LogInUser()" UseSubmitBehavior="false" runat="server" Text="Login`enter code here`" />
        <asp:Label ID="lbl_InValidError" runat="server"></asp:Label>

Client Side Code:
    function LogInUser()
    {
        var LoginName = document.getElementById("<%=txt_LoginName.ClientId %>").value;
        var Password = document.getElementById("<%=txt_Password.ClientId%>").value;

        if(LoginName == '')
        {
            alert("Please Enter UserName.");
            return false;
        }
        else
        {
            if(Password == '')
            {
                alert("Please Enter Password.");
                return false;
            }
            else
            {
                alert("You are logged in");
            }
        }
        return true;
    }

Server Side Code
Protected Sub btn_SignIn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_SignIn.Click
 If Trim(Me.txt_LoginName.Text) = "" Then
            lbl_InValidError.Text = "Please Enter Login Name."
            Return
        End If
        If txt_Password.Text = "" Then
            lbl_InValidError.Text = "Please Enter Password."
            Return
        End If
End Sub

when I am not using UseSubmitBehavior=false event is not fire at server side.

A: Change your OnClientClick to:
OnClientClick="if (LogInUser() == false) return;"

This way, if the user is not validated, it blocks the postback, but if valid, it allows it to continue.


text:
Q: Struggling with $push with Mongoose So I feel like my code is honestly not that complex, so it's driving me absolutely wild trying to figure out why I can't get a simple array with no nesting in my Mongo collection to update! This is what I'm currently working with:
console.log("documentID: ", documentId); //string defined elsewhere
console.log("userId ", userId); //string defined elsewhere

const targetUser = await Users.findByIdAndUpdate(
          userId,
          {$push: { documents: documentId }},
          { new: true }
 );

 console.log("targetUser:", targetUser);

The output comes out as:
documentID:  6077c0d308ba09c77206b81b
userId  6072623145acaf65f7390e11

targetUser: {
    createdAt: 2021-04-15T04:13:45.226Z,
    _id: 6072623145acaf65f7390e11,
    documents: [ '6073db2c6bbd3d64bd694307' ],
}

I removed most of the irrelevant and sensitive fields, but basically the problem comes down to this: I'm trying to push a new documentID into the documents array of a specific user saved in my User collection, but when I try, what happens is that the targetUser object is returned completely unchanged (the id in there was already there before). Even running the program multiple times, displays the exact same result, so I know it's not an issue of a lag in what's being logged otherwise I would see the updated array the following times I run it. The fact that it's successfully logging the desired targetUser object tells me that it's neither a database connection issue or an issue with how the _id field/query is formatted. I feel like that only leaves $push as the potential problem, but based on what I've read here and elsewhere, I don't think I'm using it incorrectly?
Some other things I tried:
Using updateOne({"_id": userId}, [similar args]). Had the same exact issue.
I also tried using
const targetUser = findOne({"_id": userId});
targetUser.documents.push(documentId);

This one gave me an error to the tune of "can't find "push" for undefined, and when I logged targetUser.documents I did indeed get undefined, even though logging just targetUser gave me the same expected result as above. I then tried logging the result of Object.keys(targetUser); and got some funky results, but I guess according to this answer, it's because "Mongoose always return an instance mongoose object, which is immutable by default." What I was seeing was pretty much the same as what the OP of that post was seeing.
I also tried importing ObjectId from the mongodb npm package and casting my userId variable to ObjectId before re-trying the updateOne() and findByIdAndUpdate() methods. I tried it with both ObjectId(userId) and new ObjectId(userId) though that unsurprisingly didn't change anything, since the correct user object containing the specified ID is showing up and isn't really the problem.
I suspect that the documents field is read-only or immutable for some reason, though I don't have a clue why that would be. Would appreciate a helping hand :)
--
Edit: Also tried adding the argument to the findOne() and findByIdAndUpdate() methods to try to log the results and errors, but there isn't an error firing, so it didn't tell me much. I also tried some of the other variations of the "find" functions.
--
Edit: Solved! I didn't include a "documents" key and corresponding array in the schema ♀


text: Q: iPhone SDK: Delete cookies of a specific webview I would like to know if there is a way to delete the cookies but only of a specific webview. For example, I have two webviews in which they both load facebook.com. When I log on to facebook in one webview the other logs in as well. I don't want this. I want each webview to have their own instance of facebook. So when I log on to facebook in one webview, the other webview stays at the log in screen. I've researched and found out that I can delete cookies to clear the data, however when I do this both webviews automatically log off of facebook instead of just one. So, I was wondering if there was a way to specifically delete the cookies of a certain webview. Thanks.


text:
Q: How to send emails back via moneris upon successful purchase? The company I work for has a method for processing credit cards. The only thing is... there seems to be ZERO api incorporated within the webpages. We use Moneris. All I see is this:
<?php
$monerisURL = ($debug) ? "https://esqa.moneris.com/HPPDP/index.php" : "https://www3.moneris.com/HPPDP/index.php";

?>
<form name="mail" action="<?php echo $monerisURL; ?>" method="post">
<?php

That's fine as it seems to work (I don't understand why but it does). Furthermore, the person who was here before me was actually a graphic artist (and NOT a programmer, so the way he programmed a lot of shit is confusing like crazy to me). In any case, I have never set up any moneris or other credit card payment solution methods.
I've been searching online to understand how it works, and the closest thing I found was this link:
https://github.com/ironkeith/Moneris-eSELECTplus-API/blob/master/examples/purchase.php
But, it is extremely extremely far from what the graphic artist did. So different.
In any case, the problem I am having is simply adding an email address (for the client and for us). Since the email acts in this case as a proof of purchase, it cannot come before the client makes a purchase. The email which is sent must come AFTER a successful transaction.
There is another place where I had to modify the coding (since his coding wasn't working), and so now I can properly send emails (the same as mentioned before) to clients who are making purchases via ANOTHER method. So now, all I need to figure out is how to send an email in conjunction to moneris. I've looked through the files, and found nothing resembling an api of any sort. Nor any file itself that would be exclusively reserved for the purpose of using Moneris.

A: In this case, there seemed to be a login (which I was completely unaware of until this morning). Since I couldn't find anything, I suspected it would have been something of the genre.


text:
Q: Emergence of the discrete from the continuum An almost eternal theme in Mathematics is the approximation of the Continuum by the Discrete. This core idea goes back at least to Archimedes, and remains active to these very days (and quite likely for the next thousand years) .
You have a continuous structure, say a sphere, and you approximate it as the limit of a series of discrete objects, say polyhedra.
I do not need to provide more examples, I am sure you all have plenty.
But, there is also, though by no means so prominent, a reverse direction.
I am not able to date  precisely when it made its debut in the history of mathematics, but it most certainly appears in the revolutionary work of Fourier: take a discrete function, say the Heaviside step function, and approximate it via series of trigonometric functions:

So, here a discrete object is realized as a limit of continuous ones (in this case smooth functions).
I am especially intrigued by this possibility, which, pushed to the extreme, will depict a mathematical world where the Discrete is an emergent phenomenon, out of a  Continuum
Thus I ask to everybody:

can you list active research in the way of approximating discrete structures via smooth ones?

For instance, a polyhedron via a series of smooth manifolds, or examples in analytic number theory, or patterns in finite combinatorics out of .....(fill the dots)  .
Any thoughtful and possibly well documented answer will get my vote, regardless  the domain chosen (in fact, the more examples I will harvest from heterogeneous disciplines, the happier I shall be).
On the other hand, to get the GREEN the stakes are higher: rather than single examples, a sketch of a general perspective on the Discrete as emerging from the Continuum
ADDENDUM: As pointed out by Andreas Blass, I have implicitly conflated two themes here:

*

*discrete as limit of the continuum

*emergence of the discrete from some background
Point 2) does not seem to necessarily imply point 1) and probably the same applies the other way around. Which one I am interested in? Easy: BOTH OF THEM.
But now that Andreas has already marked this point, the GREEN ANSWER would be, perhaps, a clarification on the relationship between  1 and 2 (inter alia)

A: Mirco, regarding your second question (emergence from the continuum):
My view would be that the FUNDAMENTAL GROUP of topological objects is an example. It captures discrete properties of a continuous object, e.g. a sphere. Or seen as the deck transformation group, it expresses the discrete structure of the universal cover of a continuous object like torus, sphere, and so on.

A: The emergence of particles as excited states (quanta) of underlying continuous fields in quantum field theory might fit the bill. See The Unquantum Quantum by David Tong, in the section titled Emergent Integers:

Erwin Schrödinger developed an alternative approach to quantum theory
based on the idea of waves in 1925. The equation that he formulated to
describe how these waves evolve contains only continuous
quantities--no integers. Yet when you solve the Schrödinger equation
for a specific system, a little bit of mathematical magic happens.
Take the hydrogen atom: the electron orbits the proton at very
specific distances. These fixed orbits translate into the spectrum of
the atom. The atom is analogous to an organ pipe, which produces a
discrete series of notes even though the air movement is continuous.
At least as far as the atom is concerned, the lesson is clear: God did
not make the integers. He made continuous numbers, and the rest is the
work of the Schrödinger equation.
In other words, integers are not inputs of the theory, as Bohr
thought. They are outputs. The integers are an example of what
physicists call an emergent quantity. In this view, the term "quantum
mechanics" is a misnomer. Deep down, the theory is not quantum. In
systems such as the hydrogen atom, the processes described by the
theory mold discreteness from underlying continuity.
Perhaps more surprisingly, the existence of atoms, or indeed of any
elementary particle, is also not an input of our theories. Physicists
routinely teach that the building blocks of nature are discrete
particles such as the electron or quark. That is a lie. The building
blocks of our theories are not particles but fields: continuous,
fluidlike objects spread throughout space. The electric and magnetic
fields are familiar examples, but there are also an electron field, a
quark field, a Higgs field, and several more. The objects that we call
fundamental particles are not fundamental. Instead they are ripples of
continuous fields.

See Reason for the discreteness arising in quantum mechanics? for more information along these lines. In particular, note that compact operators (or more generally, operators with compact resolvents) have discrete spectra (see here and here). As this answer says:

There are several forms of discreteness in quantum theory. The
simplest one is the discreteness of eigenvalues and the associated
countable eigenstates. Those arise similarly to the discrete standing
waves on a guitar string. The boundary conditions only allow certain
standing waves that nicely fit into the enforced region in space. Even
though the string is a continuous object, its spectrum becomes
discontinuous and is naturally labeled with natural numbers.
Another reason for discreteness comes in with multi-particle systems.
Quantum theory requires that a system that is realized in space-time
contains a unitary representation of the symmetry group of space-time,
the Lorentz group. In fact, you can define a particle in quantum
theory as a subsystem that contains such a group representation. And
because you can't have any non integer fraction of a unitary group
representation, you need to have an integer number of them in your
total system. So the number of particles is also an (expected)
discrete feature, and it plays a role when you talk about single
photons for example, that are either absorbed completely or not at
all.

A: Bill Lawvere has, for a long time now, promoted the idea that the discrete emerges as a limiting case by abstracting from the continuous. At the most general level, this manifests in the distinction between cohesive and constant (i.e. abstract) toposes of sets:
Quantifiers and Sheaves, Continuously Variable Sets, Variable Quantities and Variable Structures in Topoi, Toward the Description in a Smooth Topos of the Dynamically Possible Motions and Deformations of a Continuous Body, Cohesive Toposes and Cantor's 'lauter Einsen', etc...
This line of thought is worked out more precisely with the concept of Axiomatic Cohesion wherein, roughly speaking, a topos $\mathscr{E}$ is exhibited as cohesive relative to a base topos $\mathscr{S}$ via a string of adjoints between them describing how the discrete spaces $X \in \mathscr{S}$ sit inside the larger topos $\mathscr{E}$ of more general (cohesive, combinatorial, etc...) spaces. Lawvere gave some lectures on this topic in Como in 2008 and there are accompanying lecture notes. The nLab page for cohesive toposes is also quite helpful.
To bring things back down to earth a little bit, in Left and Right Adjoint Operations on Spaces and Data Types, he descirbes, in the last section, the following situation.
Suppose we have, in a cartesian closed category $\mathscr{C}$, a commutative ring object $R$ which we regard as the 'one-dimensional continuum'. We can form the correspinding 'complex numbers' ring $C = R[i]$ by defining complex multiplication on $R^2$ in the usual way. Inside of $C$ sits the multiplicative subgroup $S^1$ corresponding to the 'circle'. Finally, since we are in a cartesian closed category, we can extract from the map space $(S^1)^{(S^1)}$ the subspace $Z$ of those endomorphisms of $S^1$ which are group homomorphisms. This $Z$ can therefore be regarded as the 'integers' although it is important to note that it will not necessarily be the usual integers object $N[-1]$ derived from a natural numbers object $N$ in $\mathscr{C}$.

A: (Answer related to the one of Dustin Mixon.)
This appears as relaxation is discrete optimization: if you have an optimization problem $\min f(x)$ with a vector $x$ and the constraint that $x_i\in\{0,1\}$ for all entries $x_i$ of the vector $x$, this often becomes very hard. A common approach is to relax the constraint to $x_i\in [0,1]$. This is a continuous problem which is often easier to solve. There are several instances of the phenomenon of exact relaxation where you can prove that the relaxed problem happens to have a solution which is binary "by accident/magic".

A: In combinatorics, there is no shortage of functions that are hard to compute. Here are two famous examples whose input is a simple graph $G=(V,E)$:

*

*$\alpha(G):=$ size of the largest independent set $I\subseteq V$

*$\operatorname{MaxCut}(G):=$ size of the largest cut-set $C\subseteq E$
Both of these discrete functions are $\mathsf{NP}$-hard to compute. However, there are polynomial time–computable functions $\{\alpha'_k\}_{k=1}^\infty$ and $\{\operatorname{MaxCut}'_k\}_{k=1}^\infty$ that map simple graphs to real numbers (i.e., continuous quantities) in a way that monotonically decreases and converges pointwise to the desired functions.
Warning: While the runtime of the $k$th function is polynomial for a fixed precision (at least under certain models), the exponent increases with $k$. See this thread for more details on runtime considerations for semidefinite programs.
To be explicit, $\alpha'_1$ denotes Schrijver's strengthening of Lovász's semidefinite relaxation of the independence number, $\operatorname{MaxCut}'_1$ denotes the Goemans–Williamson semidefinite relaxation of maximum cut, and the sequences arise from sum-of-squares hierarchies that strengthen these relaxations. The claimed pointwise convergence is a consequence of the identities
$$\alpha'_{\alpha(G)}(G)=\alpha(G),\qquad \operatorname{MaxCut}'_{\lceil |V|/2\rceil}(G)=\operatorname{MaxCut}(G),$$
which follow from results in [Lasserre 2002] and [Fawzi-Saunderson-Parrilo 2016], respectively.


text:
Q: Random and negative numbers I have to generate numbers in range [-100; +2000] in c++. How can I do this with rand if there is only positive numbers available? Are there any fast ways?

A: You can use the C++ TR1 random functions to generate numbers in the desired distribution.
std::random_device rseed;
std::mt19937 rng(rseed());
std::uniform_int_distribution<int> dist(-100,2100);

std::cout << dist(rng) << '\n';

A: Generate a random number between 0 and 2100, and subtract 100.

A: generate a random number between 0 and 2100 then subtract 100.
A quick google search turned up a decent looking article on using Rand().  It includes code examples for working with a specific range at the end of the article.

A: Here is the code.
#include <cstdlib>
#include <ctime>

int main()
{
    srand((unsigned)time(0));
    int min = 999, max = -1;
    for( size_t i = 0; i < 100000; ++i )
    {
        int val = (rand()%2101)-100;
        if( val < min ) min = val;
        if( val > max ) max = val;
    }

}

A: Can you generate a number from 0-2100 and subtract 100?

A: In C++0x they will enhance this to provide better support for it with a standard library.
http://www2.research.att.com/~bs/C++0xFAQ.html#std-random

A: Currently my C++ syntax is a little rusty, but you should write a function that takes two parameters: size and offset.
So you generate numbers with the given size as maximum value and afterwards add the (negative) offset to it.
The function would look like:
int GetRandom(int size, int offset = 0);

and would be called in your case with:
int myValue = GetRandom(2100, -100);


text:
Q: Using a bash script to execute python script with arguments I have been searching for an answer to no avail.  I have a python script that I would like to run that has quite a few arguments.  It works just fine when I run the command from the terminal, but as soon as I try to put it in a bash script it no longer works.
script.py --arg1 --arg2 --arg3 --arg4 --arg5

This works.
#!/bin/bash
script.py --arg1 --arg2 --arg3 --arg4 --arg5

This does not.  I get no error message or output.

A: Try this
#!/bin/bash
python script.py --arg1 --arg2 --arg3 --arg4 --arg5

The above assumes python executable is present in your path. If it is not you could also use the full path to python as follows
#!/bin/bash
/usr/bin/python script.py --arg1 --arg2 --arg3 --arg4 --arg5


text:
Q: Get List View Fields Is there a way to get API Names of fields through Apex, which are displayed in the list view? I tried using Metadata API, Rest API, User Interface API, LDS.

A: List views are part of the CustomObject metadata type since they're associated with specific object configurations. The list view columns will have the API names of the fields displayed. Here's an example of a list view on a Lead.object metadata file:
<listViews>
    <fullName>AllLeads</fullName>
    <columns>FULL_NAME</columns>
    <columns>LEAD_SCORE</columns>
    <columns>LEAD.TITLE</columns>
    <columns>LEAD.COMPANY</columns>
    <columns>LEAD.EMAIL</columns>
    <columns>LEAD.PHONE</columns>
    <columns>Lead_Quality__c</columns>
    <columns>Source__c</columns>
    <columns>CORE.USERS.ALIAS</columns>
    <filterScope>Everything</filterScope>
    <label>All Leads</label>
</listViews>

Unfortunately, the built-in Apex Metadata class can only reference custom metadata types and does not have an interface for standard metadata.
Additionally, you can access list view information through the User Interface API List View endpoints to get results given the API name of a list view and the associated object:
https://[MY_DOMAIN].my.salesforce.com/services/data/v49.0/ui-api/list-info/Account/List_API_Name


text:
Q: The jQuery looks great. Now how do I get the PHP email to send? I am using jQuery to swap out the image here after the submit button on an email from is submitted. This part works very well, however, I also need to generate the email from the form contents.
Here is the form:
            <form action="estimate.php" action="post">
                <fieldset>
                <input type="text" name="name" value="FULL NAME" onfocus="if (this.value=='FULL NAME') this.value='';"/>
                <input type="text" name="phone" value="PHONE NUMBER" onfocus="if (this.value=='PHONE NUMBER') this.value='';"/>
                <input type="text" name="email" value="EMAIL" onfocus="if (this.value=='EMAIL') this.value='';"/>
                <input type="text" name="date" value="MOVE DATE" onfocus="if (this.value=='MOVE DATE') this.value='';"/>
                <input type="text" name="origin" value="ORIGINATING ADDRESS" onfocus="if (this.value=='ORIGINATING ADDRESS') this.value='';"/>
                <input type="text" name="destination" value="DESTINATION ADDRESS" onfocus="if (this.value=='DESTINATION ADDRESS') this.value='';"/>
                <select name="move-type">
                    <option value="" selected="selected">TYPE OF MOVE</option>
                    <option value="Private">Private</option>
                    <option value="Commercial">Commercial</option>
                </select>
                <input id="quoteSubmit"
                    type="image" src="_images/btn_submit.png" alt=""
                    onmouseover="javascript:this.src='_images/btn_submit-over.png'"
                    onmouseout="javascript:this.src='_images/btn_submit.png'"/>
                </fieldset>
            </form>

Here is the jQuery:
        // free quote form
    $('#freeQuote form').submit(function(e){

    //Set the data ready for ajax post
    var formdata = $(this).serialize();

    $.post("estimate.php",formdata,function(data){
        if(data.error)
        {
           alert('Error: ' + data.error);
           return;
        }
    });

    //The Image
    var Image = $('').attr({src:'_images/free-quote-confirm.png', width:231, height:267, alt:"Success"});

    //Remove the form
    $('#freeQuote form').remove()

    //Add the image inside the div
    $('#freeQuote').append(Image);

    //Return false so the form does not send as normal. you can also use e.PreventDefault():
    return false;
});

Here is the PHP:
<?php # sends contents of  Free Estimate form

if (isset($_POST['submitted'])) {
$errors = array();

// Check for empty fields

if (empty($_POST['name'])) {
    $errors[] = 'Please enter your name.';
}

if (empty($_POST['email'])) {
    $errors[] = 'Please enter your email address.';
}

if (empty($_POST['date'])) {
    $errors[] = 'Please enter the date of your move.';
}

if (empty($_POST['origin'])) {
    $errors[] = 'Please enter the origin of your move.';
}

if (empty($_POST['destination'])) {
    $errors[] = 'Please enter the destination.';
}

if (empty($errors)) { // everything is okay

$body = "The following Free Estimate Request has been submitted:\n

    Submitted by: {$_POST['name']}\r
    E-mail: {$_POST['email']}\r
    Phone: {$_POST['phone']}\r
    Move date {$_POST['date']}\r
    Moving from: {$_POST['origin']}\r
    Moving to: {$_POST['destination']}\r
    Move type: {$_POST['move-type']}\r;

    mail ('forrest@rouviere.com', 'Free Estimate Request', $body, 'From: admin@movingsimplified.com');

    // end email

} else {
    echo '
Error!

The following error(s) occurred:
';
    foreach ($errors as $msg) {
        echo " - $msg
\n";
    }
    echo '

Please go back and try again.

';
}
};

?>

The basic problem is, I can click the submit button without anything entered in the fields, and I don't get an email.
Any help would be appreciated.
Thanks.

A: Unless your code snipper is in correct you have the following issue..
$body = " // there is no closing "

You also state in your question:

The basic problem is, I can click the submit button without anything entered in the fields, and I don't get an email.

Your example would suggest (if no syntax errors) that you don't want an email sent if there are errors.
New corrected request.php
<?php # sends contents of  Free Estimate form

if (isset($_POST['submitted'])) {
    $errors = array();

    // Check for empty fields

    $checkArray = array('name', 'email', 'date', 'origin', 'destination');
    foreach($checkArray as $check) {
        if (empty($_POST[$check])) {
            $errors[] = 'Please enter your '.$check;
        }
    }

    if (empty($errors)) { // everything is okay

        $body = "The following Free Estimate Request has been submitted:\n

            Submitted by: {$_POST['name']}\r
            E-mail: {$_POST['email']}\r
            Phone: {$_POST['phone']}\r
            Move date {$_POST['date']}\r
            Moving from: {$_POST['origin']}\r
            Moving to: {$_POST['destination']}\r
            Move type: {$_POST['move-type']}\r;

        ";

        mail ($to, 'Free Estimate Request', $body, 'From:  '.$from);

        // end email

    } else {
        // If error then NO Email sent
        echo '
Error!

The following error(s) occurred:
';
        foreach ($errors as $msg) {
            echo " - $msg
\n";
        }
        echo '

Please go back and try again.

';
    }
};

?>


text:
Q: Recorded video as live using php I need to broadcast means
Everyone will view the video as it played, not at the beginning of the video once they visited the web page.
I saw some code like this for embedding video,
<object width="425px" height="360px" >
    <param name="allowFullScreen" value="true"/>
    <param name="wmode" value="transparent"/>
    <param name="movie" value="http://mediaservices.myspace.com/services/media/embed.aspx/m=5385825,t=1,mt=video,searchID=,primarycolor=,secondarycolor="/>
    <embed src="http://mediaservices.myspace.com/services/media/embed.aspx/m=5385825,t=1,mt=video,searchID=,primarycolor=,secondarycolor=" width="425" height="360" allowFullScreen="true" type="application/x-shockwave-flash" wmode="transparent"/>
</object>

i need to know is it possible with PHP , Search several times in web, but did nnt get a proper solution yet.

A: This is not about the clientside code. You should configure a single stream in your video hosting platform. That's where the challenge is being fixed, not in the client side code.
To be more specific:

I need to broadcast

As far as I see from some server, I don't see anything about a client side cam.

means Everyone will view the video as it played

So it is a stream send to all visitors of the page, not personal chat stream just like a TV broadcasting.

, not at the beginning of the video once they visited the web page.

So you start it centrally and you can hook in. So if the stream is at 35 minutes and you start watching you miss it. Just like TV.
If that is all correct then you should configure that at the server. So don't stream separately for every viewer but just use a general stream.


text:
Q: ssh virtualbox to guest os from different network using public ip I run win10 as Host os and Ubuntu as guest os at the virtualbox. What I want to do is ssh from a different pc to ubuntu ! The guest os network is attached to NAT adapter. How I think it is that I will ssh from a different pc(in a different network) using the public IP like that "ssh [username]@[public ip] -p 2222" on let's say port 2222. I have already port forwarded the port 2222 on my router settings so that it will redirect the data to my HOST MACHINE'S local ip , because I use NAT and guest os does't have specific ip. Also I have port forward virtual box to enable connection between host and guest os. So I have put these settings at the vbox using the GUI -> NAME:"something" , PROTOCOL:TCP , Host IP: 127.0.0.1 , HOST PORT:2222 , GUEST IP:10.0.2.15 , GUEST PORT:2222. So when I try to ssh from a different network it won't even say something. Just hit the command and do nothing..... Any Ideas please???

A: You can try to configure the virtual machine in bridge mode and through a DDNS connect from the outside to your MV.
What you would be doing would be that the MV was like another PC on the network, and through router routing you could reach the MV. This system is what I have set up to enter the raspberry configuration panel that makes me a VPN server.
I hope it helps.

A: I fixed it,it was a problem from my isp when i tried to port forward my router.
Thanks a lot for the answers


text:
Q: LEFT() is not working in Postgres I have a date in the format of 2012-08-10. I want the first four digits of the date.
Using extract(year from date) works, but it will make a problem in CakePHP.
So i try to use LEFT() or RIGHT():
select LEFT(date,4) from table

But it is not working.

A: If you want to get the four digit year from a date as a string then to_char is what you want:
select to_char(some_date, 'YYYY') from table;

Actually, pretty much any date or time formatting inside the database should be done with to_char so you might want to read the fine manual.
LEFT won't work because LEFT wants a string argument but you're giving it a date.

A: you can use substring if you dont want to use extract like
select substring('2012-4-03',1,4);

or use select to_char(some_date, 'YYYY') from table;
you can also write a function calling left for the same.but there is no inbuilt function in postgresql.

A: Use EXTRACT() if you want to extract the year from a DATE:
SELECT EXTRACT(YEAR FROM fieldname) FROM tablename;

Or TO_CHAR(), as mentioned by others.


text:
Q: How to assemble a project with software products and your own code Let's say you have a specific project on hand, it can be divided to parts, and you are not completely sure about all the difficulties that will arise.
Time is of the essence.

*

*How do you decide whether a part should use software product or your own code? (considering, that some tools are awesome, but will require much time to learn)

*How do you choose the right software product?

*How much time (as a percentage) should this stage of choosing the right product, if any, take, and how much time to evaluate a single product?

*Is there a way-back, is it o.k to change your mind, after putting efforts in a product, and finding it not suitable?

I would love to hear any rules of thumb about those.

A: Changing your decisions is like changing your blueprint for a house while it's already being built.
It will entirely depend on what you have spent in time and money to that point.
Some considerations:
0) Understand the problem in clear and simple terms before beginning.  Know what's critical to it's success and then use that list to see if any software, language, or tool will aid it, and at what cost, and if the cost outweighs the benefit.
1) Use a crammer's schedule. Build it in the order of what you would build if you only had 1 day or 1 week and no more to work on it.  It's amazing how much doesn't matter anymore when you have to do 50% of the features at 100% of the quality. Focus on value, value, value.    Read something like 37 Signal's book Getting Real for more on this.
2) Do not re-invent the wheel.  It's always easier it seems to build something from scratch.  Unless you are doing a fraction of the implementation and it's truly simpler, meaning you can avoid abstraction until you forget what you were building, consider it.  If you can build it faster, better, cheaper and in the same amount of time, do it.
3) Know the features of your tools, and the benefits any tools need to give your solution. You should be familiar with or at least aware of many of the tools out there that you may or may not integrate.
4) Pick a language that is used to solve a lot of problems.  Chances are you will find many great libraries and tools to build your software that will save your time.  If you need something that delivers, can run, and you can lean on the smarts of others, use something established, or a language that can access .NET or Java easily if need be.

A: For each part of your software you recognize as a software component/package:

*

*How do you decide whether a part should use software product or your own code?
(considering, that some tools are awesome, but will require much time to learn)

*

*Ask yourself whether the component you are considering is a part of your product's main business core.

*

*If not then it is usually better to use an existing solution and not send too much time on it.

*If it is then make sure there is no existing product that is better than what you are planning. - It there is, consider purchasing licenses to it instead of developing your product.

*Search online for similar components (commercial, open source and even articles/demo-source-code).

*

*Do any of them implement all of your requirements from the components?

*How much do they cost, would it cost you more to develop and maintain a similar component?

*What are the license conditions? - Are they OK for your product?

*If component includes a user-interface, is it plesent to look at and easy to use?

*If you answered yes to all the above then do not develop the component yourself.

*If not:

*Is the component open source or published in an article / demo-code? - If so, it robust, could you take the code an improve it or use it as an example to help you write code that is more suitable for your requirements? - If so write your own code, use code as part of your own component that is not developed from scratch.

*If your answer to the above is no, then you'll have to develop your own (or you're searching in the wrong places).

*How do you choose the right software product?

*

*See answers to 1.

*How much time (as a percentage) should this stage of choosing the right product, if any, take, and how much time to evaluate a single product?

*

*Clear an entire day, search for existing components, read about them (features, prices, reviews) and download + install up to 5 of them.

*Clear another day evaluate 2-3 products, compare demos/examples, look at code, write 2 small examples of using each (same example different product).

*If you choose more than 3, clear another day and test the others.

*Is there a way-back, is it o.k to change your mind, after putting efforts in a product, and finding it not suitable?

*

*Always design your software so that every component is replaceable.

*

*This guarantees that there is always "a way back".
(Use interfaces & adapter design pattern, divide to many assemblies, connect all components as loosely as possible (using events, binding, as etc.) - loose coupling.

*Even if you implement something yourself make sure there is a way back - sometime you may use the wrong technology/design and have to replace a component with a new one you develop/purchase.

*Other rules of thumb:
Consider which application-wide technologies to use before considering each component.

*

*Writing in assembly would take the longest, in C less, in C++ even less, in more modern languages such as C#, Java, Delphi even less.

*Which has more of the self components that are relevant to you? What does your team have experience in.

*If you are using .NET (C#), then WPF could help you lower the coupling between GUI and business logic and make a better looking GUI, however it take time to learn how to use it (a 5 day minimum course is very much recommended).

A: As in any art the difficulty is composing a good solution based on a very large possible solutions space. There as many ways to go about this as there are developers.
I'd normally spend some time understanding the problem and stating it clearly and succinctly as possible, preferably in a written form. The problem description should be completely abstracted away from any possible solutions. Next I'd normally list available constraints that will need to be applied to the solution (time, budget, legal, political, performance, usability, skill availability within team and so on).
Then the theory goes that you need to look on the market for something that solves the problem and meets the constraints at the same time. In practise, the process is not that straight-forward: you try to identify market categories that are likely to be useful, then research them, see what is available and continuously try to reduce the gap between the constraints and capabilities as much as possible, often by going back and revisiting and re-negotiating the constraints.
A few generic tips:

*

*During the research keep coming back to the original problem.

*There is always more than one solution, try to extend breadth (concentrating on very different ways of solving the problem) of the search space before going deeper.

*Be clear on a number of options it's worth researching, and amount of time worth spending on each of them before making a decision whether to investigate further.

*It's seldom worth finding an optimal solution, especially then technological landscape keeps changing very rapidly. Look for a solution that is good enough: "The Paradox of Choice - Why More is Less".

*It's rarely worth turning to users for help (unless they are software experts) on choosing between several options. If you've got a number of options all looking equally attractive that means you need to go back and understand the original problem better, it's likely you've missed a requirement or two.

*Some further notes on using third-party components (refers to GUI components, but easy to apply to other software areas as well).

*And even more notes on scoping, composing and researching for a project.

A: *

*How do you decide whether a part should use software product or your own code? (considering, that some tools are awesome, but will require much time to learn)

Ask your self two questions.
1) Is it a mature product. If yes, then
2) How long it would take to create the functionality it provides on your own. If that value times your hourly rate is greater than the cost of the product, then use that product.

*

*How do you choose the right software product?

Consult your network of other developers. Have they used it, did they run into problems. Consult the interweb. Create a prototype using the product. Does it work well? Any major bugs?

*

*How much time (as a percentage) should this stage of choosing the right product, if any, take, and how much time to evaluate a single product?

It depends on the size of the project, and the criticality of the product to the success. Most of the time, you are going to be able to get a high level view of the product in a very short amount of time.
It may be just a few minutes using it before you say, nope - not ready for prime time. If it makes past that, a day or two of experimentation may tell you that it passes muster for your project.
If it's a huge project with many developers, then you probably want to spend more time doing a prototype application with it to be sure it's worth investing all that time in.

*

*Is there a way-back, is it o.k to change your mind, after putting efforts in a product, and finding it not suitable?

If you find it's not working out, there's nothing wrong with going back. In fact you probably have to. Ideally you will find this out early. Not at the 11th hour. Again, this is the purpose of prototyping.

A: There are already some really good answers here, so I won't repeat it, however there is one point you should definitely consider, and though I would have thought its obvious I havent seen it mentioned here yet:
The personnel you have available to implement the solution, their core competency, and their general level of competence.
Who you have to implement this (assuming it's a team, and not just yourself - but relevant even if its just you, too...) can have a HUGE effect on the outcome. If you don't have experienced programmers to help you develop this, you're better off looking for some OTS product to do the work for you... Or, even if you have programmers who are not likely to succeed, you still might want to find a solution with lower overall project risk.