text:
Q: httpd -k restart : print some info like " service httpd restart " restarting apache via service command :
service httpd restart

Stopping httpd: [ OK ]
Starting httpd: [ OK ]

I want to be able to get the same output without using the "service" command.
the following command works but does not print anything.
/usr/sbin/httpd -k restart

A: The "service" command runs the /etc/init.d/httpd script, this script restarts httpd and prints the info.
With /usr/sbin/httpd -k restart, you are restarting httpd without printing anything.

I want to be able to get the same output without using the "service" command.

Option 1
Run the httpd init script:
/etc/init.d/httpd restart

Option 2
You could create a script like the following:
#!/bin/bash
echo "Restarting httpd..."
/usr/sbin/httpd -k restart

Name it 'restart_httpd.sh', for example, and make it executable:
chmod +x restart_httpd.sh

Run it:
./restart_httpd.sh


text:
Q: iTunes Match music gone missing I have been an iTunes Match for several years, since shortly after they introduced the service.  Recently I noticed that entire albums were missing off my phone, or weirder still, that some albums would have two or three tracks present and the rest missing.
After checking that I did not have "Only Offline Music" selected, I did the obvious: I logged out of my Apple ID account and logged back in. A lot more music disappeared. Now roughly 90% of my music is missing.
Some artists are entirely present, some have taken huge hits, and a lot have exactly one song each.
I have also deauthorized my main computer (which has all my music) and reauthorized it in the hopes that would force a resync, but no such luck.
I should also mention that I never signed up for Apple Music, not even the free trial. I know there were some problems there, but that's not the cause of my woes.
So what is going on here?

A: Finally figured it out: in the Settings app, under Music, "iCloud Music Library" was somehow disabled. Problem solved!

redpajama_set_name: RedPajamaStackExchange


text:
Q: HA Proxy fails to recognize Tomcat:8080 running on a mac Can someone help be understand why haproxy fails to detect my tomcat instance running on port 8080?  I can reach the server just fine when browsing to 127.0.0.1:8080
On start up haproxy spits out the following error:
WARNING] 141/163609 (23336) : Server cim/cim is DOWN, reason: Layer7 wrong status, code: 404, info: "Not Found", check duration: 1ms. 0 active and 0 backup servers left. 0 sessions active, 0 requeued, 0 remaining in queue.
[ALERT] 141/163609 (23336) : backend 'cim' has no server available!

Here's the haproxy config.
global
    maxconn                   128
    chroot                    /var/lib/haproxy
    pidfile                   /var/run/haproxy.pid
    tune.ssl.default-dh-param 2048

defaults
    mode                      http
    log                       global
    log                       127.0.0.1 local0
    log                       127.0.0.1 local1 notice
    option                    httplog
    option                    forwardfor
    option                    httpclose
    option                    redispatch
    option httpchk            HEAD / HTTP/1.0
    retries                   3
    timeout http-request      10s
    timeout queue             1m
    timeout connect           10s
    timeout client            1m
    timeout server            1m
    timeout http-keep-alive   20s
    timeout check             10s

frontend in-http
    bind *:80
    acl restricted_urls       path_beg /trm/ws/v2
    use_backend cim           if restricted_urls

backend cim
    balance      roundrobin
    server       cim 127.0.0.1:8080 check

Tomcat is definitely up and running, and I can telnet to 127.0.0.1 8080 and receive an http response.


text:
Q: Order of query execution I have a query of the basic structure
with cte1 as (Select *query on tbl1*)
,cte2 as (select *query on tbl1*
      Exception join cte1 )

Select * from cte1
union all
Select * from cte2

And I really have no idea whether I can be confident this will behave as expected - each of ctes produce similar rows, but would have different logic - I want cte1 to pass through the table with its logic, then cte2 to review the same table again, after cte1 has picked all the records that apply to it - will this work?
Edit: Ok, I have created some data and outlined where I am concerned. I am not sure how to interpret philipxy's response with the above - I can understand from his response what to expect from cte1, but I do not fully understand what cte2 would be - does cte1 get "declared" before cte2, so that their values are locked in once the query begins?

A: You seem to be confused about the interpretation of SQL queries. Maybe all queries, or maybe just CTE queries, or maybe just recursive CTE queries.
The value of a relational query is based on names representing values (that are tables) and on the value of an expression being calculated from those values to give other values.
An update then causes the new current value of a base table, ie the value associated with a base table name, to be the value calculated by the query. SQL queries describe how updated rows in terms of input rows, but all rows are updated at once.
A base table name stands for its value before the query is executed. A recursively defined CTE name is one that is used in its own definition. That describes a loop which when executed gives a new value for the CTE name in every iteration. (You didn't do that here.) Otherwise a CTE name stands for the value given to it when it was introduced.
Since this CTE query isn't recursive, you can just take the base table names and CTE names as standing for their values. So your CTE names only ever have one value, and when you SELECT from a named (base or CTE) table it doesn't affect its value.


text:
Q: Synchronize video viewing between computers with matching local files? Let's say I have a video file that I'd like to watch with some friends of mine in different states. FTP makes it easy enough for all of us to get a local copy of the file.
Sure we could call each other up, load the video paused at the beginning, and call out "3... 2... 1... NOW" to all have us play the video at the roughly the same time. For short videos that might work. For longer videos this becomes an issue as soon as somebody wants to pause the video for whatever reason.
Is there any easy way to set up synchronized viewing across multiple PCs on different networks that all have the file loaded locally? It doesn't need to be frame perfect sync, just close enough for a social viewing over the internet. It'd be awesome if it kept play, pause, and seek commands synced up across all machines. For my friends and I we might only need to sync up 2 or 3 machines total.

A: Syncplay does what you're looking for. It's free open-source software that synchronizes playback by controlling the media players over a network. The media files and players are local to each computer.
https://syncplay.pl/

A: Not aware of any video player with synchronized controls, so suggest use of the National Institute of Standards and Technology atomic clock as your kickoff signal. Have everyone select the file to play in VLC or your other video player of choice,  connect to the website, and at the appointed time, click PLAY.
If you want a slightly more sophisticated system, use a remote control app running in multiple windows, one for each Child PC. The Parent PC uses a remote control app to click PLAY on the player loaded up on each Child PC.


text:
Q: JsfUnit without JBoss in spring web app - maven dependency setup I can't find an easy JSFUnit setup for my pom anywhere. What repository do I use and which dependencies? We have a running web app with JSF and Spring. Can't be that hard to get JSFUnit into the mix..?!
Also we want to run the tests from Eclipse (I think I found something there) and via Maven when building the artifacts on jenkins.
Can anyone please post their dependency setup (as well as maven build cycle integration)?
Thanks!


text:
Q: My recursive function is too fast, to animate paths I'm visualising voyages on a map with D3.js' path. My data is in a JSON file like the following format:
[{"begin_date":1519,"trips":[[-13.821772,14.294839],[-9.517688,-7.958521],[0.598434,-34.704567],[18.374673,-86.850335]]},
{"begin_date":1549,"trips":[[12.821772,-16.294839],[5.517688,-20.958521],[13.598434,-54.704567],[18.374673,-86.850335]]},
{"begin_date":1549,"trips":[[12.821772,-16.294839],[5.517688,-20.958521],[13.598434,-54.704567],[18.374673,-86.850335]]}]

As can be seen, sometimes there are multiple voyages for a year. The following recursive function works:
d3.json("data/output.json", function(error, trips) {
            if (error) throw error

            var nest = d3.nest()
            .key(function(d){
                return d.begin_date;
            })
            .entries(trips)

            var trip = svg.selectAll(".voyage");

            // Add the year label; the value is set on transition.
            var label = svg.append("text")
                .attr("class", "year label")
                .attr("text-anchor", "end")
                .attr("y", height - 400)
                .attr("x", width+150)
                .text(function(d) {return d});

            var pnt = 0;

            doTransition();
            function doTransition() {
                trip.data(nest[pnt].values).enter()
                    .append("path")
                        .attr("class", "voyage")
                        .style("stroke", colorTrips)
                        .attr('d', function(d) {label.text(d.begin_date); return lineGen(d.trips.map(reversed).map(projection))})
                        .call(function transition(path) {
                            path.transition()
                                .duration(500)
                                .attrTween("stroke-dasharray", tweenDash)
                                .each("end", function(d) {
                                    d3.selectAll(".voyage")
                                        .remove()
                                        pnt++;
                                        if (pnt >= nest.length){return;}
                                        doTransition();
                                        })
                                    })
                                }

Some voyages plot as they should

However some of them, are never plotted (I can see in the log) and it jumps from year 1545-1569 despite there being data points in between. I suspect it is due to the recursive function calling itself before the transition is finished. But I am also not sure, in the slightest.
Hope it is sufficient, I am new to D3.js, and suddenly found myself out of depth.


text:
Q: Site.Master Changes I started out with a basic site.master.  After I laid out several pages, I have found that I need to make changes to the site.master.  The changes show up while I am working in Visual Studio, but when I run the application, they don't take effect.  What do I need to do to have them show up?

A: When you make changes to CSS or javascript (or any other static content, for that matter), you need to clear out the browser cache to ensure the latest version is loaded from your server.
You can force a reload from the server by using Ctrl + F5 on most browsers.


text:
Q: how to run python manage.py migrate inside a docker container that runs Django with apache2 I'm running Django app inside Docker container with apache2, I need to add the command python manage.py migrate inside the Dockerfile or docker-compose but am unable to run it .
Dockerfile
FROM ubuntu

RUN apt-get update

# Avoid tzdata infinite waiting bug
ARG DEBIAN_FRONTEND=noninteractive
ENV TZ=Africa/Cairo

RUN apt-get install -y apt-utils vim curl apache2 apache2-utils
RUN apt-get -y install python3 libapache2-mod-wsgi-py3
RUN ln /usr/bin/python3 /usr/bin/python
RUN apt-get -y install python3-pip
#Add sf to avoid ln: failed to create hard link '/usr/bin/pip': File exists
RUN ln -sf /usr/bin/pip3 /usr/bin/pip
RUN pip install --upgrade pip
RUN pip install django ptvsd
COPY www/demo_app/water_maps/requirements.txt requirements.txt
RUN pip install -r requirements.txt
ADD ./demo_site.conf /etc/apache2/sites-available/000-default.conf
EXPOSE 80
WORKDIR /var/www/html/demo_app
CMD ["apache2ctl", "-D", "FOREGROUND"]
CMD ["python", "manage.py", "migrate", "--no-input"]

docker-compose
version: "2"

services:

  db:
    image: postgres
    volumes:
      - ./data/db:/var/lib/postgresql/data
    environment:
      - POSTGRES_DB=database_innvoentiq
      - POSTGRES_USER=database_user_innvoentiq
      - POSTGRES_PASSWORD=mypasswordhere
      - PGDATA=/tmp
  django-apache2:
    build: .
    container_name: water_maps
    environment:
      - POSTGRES_DB=database_innvoentiq
      - POSTGRES_USER=database_user_innvoentiq
      - POSTGRES_PASSWORD=mypasswordhere
      - PGDATA=/tmp
    ports:
      - '80:80'
    volumes:
      - ./www/:/var/www/html
    depends_on:
      - db

what happens here is that the container exists after running the last CMD in the Dockerfile

A: Do this:
django-apache2:
    build: .
    container_name: water_maps
    environment:
      - POSTGRES_DB=database_innvoentiq
      - POSTGRES_USER=database_user_innvoentiq
      - POSTGRES_PASSWORD=mypasswordhere
      - PGDATA=/tmp
    ports:
      - '80:80'
    volumes:
      - ./www/:/var/www/html
    command: >
       sh -c 'python manage.py migrate &&
              python manage.py runserver 0.0.0.0:8000'
    depends_on:
      - db

or run docker-compose using below command:
docker-compose run --rm projectname sh -c "python manage.py filename"


text:
Q: Autostart permission programmatically I am working on an app where I need to ask user for the autostart permission and for that I am opening the Autostart permissions settings page for the user to turn on the permission for our app using following code for few Manufacturers:
Intent autostartIntent = new Intent();
    if ("xiaomi".equalsIgnoreCase(android.os.Build.MANUFACTURER)) {
       autostartIntent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
       startActivity(autostartIntent);
    } else if ("oppo".equalsIgnoreCase(android.os.Build.MANUFACTURER)) {
       autostartIntent.setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity"));
       startActivity(autostartIntent);
    } else if ("vivo".equalsIgnoreCase(android.os.Build.MANUFACTURER)) {
       autostartIntent.setComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.BgStartUpManagerActivity"));
       startActivity(autostartIntent);
    } else if ("huawei".equalsIgnoreCase(android.os.Build.MANUFACTURER)) {
       autostartIntent.setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity"));
       startActivity(autostartIntent);
}

Moreover, when I am trying to redirect user to the following devices, I am facing following difficulties:

*

*On RealMe 2 Pro, for which the manufacturer is Oppo, the system is unable to start the AutoStart Permissions Activity.

*On Moto and Nokia devices, I am not able to get the path of AutoStart Activity, so that I can redirect user to that page directly.

A: Found the solution to this question, i am opening the Battery Optimization page for the user to turn off Battery Optimization for my app.
Here is the code i am using:
AlertDialog.Builder builder = new AlertDialog.Builder(PermissionsActivity.this);
    builder.setTitle("Turn off Battery Optimization");
    builder.setMessage("Find XYZ in the list of applications and choose 'Don't optimize'.");
    builder.setPositiveButton("Allow",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    if (Build.VERSION.SDK_INT >= 23) {
                        Intent intent = new Intent();
                        intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
                        startActivity(intent);
                    }
                }
            });

    builder.setNegativeButton("Deny", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            finish();
        }
    });
    builder.show();


text:
Q: How to bulk share / invite a site collection to multiple external customers using Powershell? I have a number of users who are on an O365 SharePoint site that we manage that need access to another O365 SharePoint site. Both are separate Tenants.
Rather than email them individually I want to bulk send them an invite, how can I do this?
At the same time I want to catch those invites (which can be done using a mail flow rule to send the invitation email to another email address) but need to also accept them automatically in bulk.
How best can I do this with PowerShell?
Thank you in advance.


text:
Q: How to add files to an input file tag? I wanted to add files to <input type="file" multiple> using js/jQuery.
Here is where am having trouble, I am using cropperjs, so I want the cropped image to be appended to data of a form and sent on submit.


text:
Q: Is there any disadvantage to declare a variable global? In C++ language is there any disadvantage to declare a variable global?
void foo()
{
  int a;
  a=10;
}

int a;
void foo()
{
  a=10;
}

Any differences between them?

A: Why Global Variables Should Be Avoided When Unnecessary

*

*Non-locality -- Source code is easiest to understand when the scope of its individual elements are limited. Global variables can be read
  or modified by any part of the program, making it difficult to
  remember or reason about every possible use.

*No Access Control or Constraint Checking -- A global variable can be get or set by any part of the program, and any rules regarding its use
  can be easily broken or forgotten. (In other words, get/set accessors
  are generally preferable over direct data access, and this is even
  more so for global data.) By extension, the lack of access control
  greatly hinders achieving security in situations where you may wish to
  run untrusted code (such as working with 3rd party plugins).

*Implicit coupling -- A program with many global variables often has tight couplings between some of those variables, and couplings between
  variables and functions. Grouping coupled items into cohesive units
  usually leads to better programs.

*Concurrency issues -- if globals can be accessed by multiple threads of execution, synchronization is necessary (and too-often neglected).
  When dynamically linking modules with globals, the composed system
  might not be thread-safe even if the two independent modules tested in
  dozens of different contexts were safe.

*Namespace pollution -- Global names are available everywhere. You may unknowingly end up using a global when you think you are using a
  local (by misspelling or forgetting to declare the local) or vice
  versa. Also, if you ever have to link together modules that have the
  same global variable names, if you are lucky, you will get linking
  errors. If you are unlucky, the linker will simply treat all uses of
  the same name as the same object.

*Memory allocation issues -- Some environments have memory allocation schemes that make allocation of globals tricky. This is especially
  true in languages where "constructors" have side-effects other than
  allocation (because, in that case, you can express unsafe situations
  where two globals mutually depend on one another). Also, when
  dynamically linking modules, it can be unclear whether different
  libraries have their own instances of globals or whether the globals
  are shared.

*Testing and Confinement - source that utilizes globals is somewhat more difficult to test because one cannot readily set up a 'clean'
  environment between runs. More generally, source that utilizes global
  services of any sort (e.g. reading and writing files or databases)
  that aren't explicitly provided to that source is difficult to test
  for the same reason. For communicating systems, the ability to test
  system invariants may require running more than one 'copy' of a system
  simultaneously, which is greatly hindered by any use of shared
  services - including global memory - that are not provided for sharing
  as part of the test.

A: Global variable's memory is not automatically freed. While scope variable's memory is freed as soon as the completion of block.
void foo()
{
  int a;
  a=10;
}

This int a will be freed after the completion of foo
int a;
void foo()
{
  a=10;
}

This int a will be freed depending upon its scope outside foo()

A: Memory usage. In first case memory will be freed, in second will not.
And ofc this is very bad to declare variable with name like ''A'' as global variable. This will be source of great number of errors.

A: In the first, the variable lives on the stack and is only valid until the function exits, and it is visible only from inside the function. In the second, it is both valid and accessible from outside.
As a general rule, you should always declare a variable as local as possible, so only use global variables when it is really necessary.
There is a third variant. If you do this:
void foo()
{
static int a;
a=10;
}

Then your variable remains valid after the function exits, but it is only visible from inside (although you can give out pointers or references if you want). This is the recommended usage if you need a variable that needs to retain its value between function calls but is only used from within the function.

A: This has been discussed before on StackOverflow. See for example this:
https://stackoverflow.com/a/485020/980195
The main disadvantages of putting variables in global scope is precisely that they become globally accessible. Any other piece of code could decide to read or write to them. Whereas with a local variable, you only need to look to the local scope in order to know everything which is going to be able to change or even access the value.
Apart from that, putting it in the global namespace means it can give rise to name clashes, ambiguity or even users accidentally referring to the wrong variable through a simple typo. This is especially bad if you call your variable something as simple as in your case.
There are more reasons as well, for example look at the answer @naren provided.


text:
Q: What does this php code means Hello I am new to PHP and I don't know exactaly what does this code means
$de = array('Ä'=>'ae','ä'=>'ae','Ü'=>'ue','ü'=>'ue', 'Ö'=>'oe', 'ö'=>'oe', 'ß'=>'ss');
 strtr($str, ${$de});

The only thing that I need to know is what does ${$de} mean?

A: It's a variable variable, one of the most intriguing part of the php implementation.
Sometimes usefull, always confusing:
$Bar = "a";
$Foo = "Bar";
$World = "Foo";
$Hello = "World";
$a = "Hello";

$a; //Returns Hello
$$a; //Returns World
$$$a; //Returns Foo
$$$$a; //Returns Bar
$$$$$a; //Returns a
$$$$$$a; //Returns Hello
$$$$$$$a; //Returns World
....

A: That's a variable variable.
http://php.net/manual/en/language.variables.variable.php

A: Known as Variables Variable
http://php.net/manual/en/language.variables.variable.php


text:
Q: React how to get index in search I have an application to divide between available and non-available coupon, when user clicked available coupon the coupon will go to non-available section (vice versa), everything works fine. But, if I searched the coupon in the search box, the bug happens, turns out I can't get the initial index of the searched coupon (it will always change to index 0)
For instance, Coupon B should have index 1, but when i type Coupon B in the search box the index will change to 0, which break my changedHandler logic. How can i solve this?
You can see my application in Action through this link https://go-coupon-d0fe4.firebaseapp.com/
MainContainer.Jsx
state = {
    availableCoupon: ['Coupon A', 'Coupon B', 'Coupon C', 'Coupon D'],
    nonAvalailable: ['filter0', 'filter1', 'filter2', 'filter3'],
    text: ''
  };

  searchHandler = text => {
    this.setState({ text });
  };

  changedHandler = i => {
    console.log(i);
    const r = window.confirm('Use Coupon?');
    if (r) {
      let newItems = [...this.state.nonAvalailable];
      let updatedItems = this.state.availableCoupon.splice(i, 1);
      newItems.push(...updatedItems);
      this.setState({
        nonAvalailable: newItems
      });
      console.log('THIS IS NEW ITEMS ' + updatedItems);
    }
    return false;
  };
  render(){
     return(
      <SearchBox
        searchTerm={this.state.text}
        filteredList={this.state.availableCoupon}
        searchHandler={this.searchHandler}
      />
      <FilteredItem
        changed={this.changedHandler}
        searchTerm={this.state.text}
        availableCoupon={this.state.availableCoupon}
      />
    )
 }

SearchBox.jsx
<Input
   onChange={e => this.props.searchHandler(e.target.value)}
   value={this.props.text}
   type="text"
   name="coupone"
   id="exampleCoupon"
   placeholder="Coupon Goes Here"
/>

filteredItem.jsx
{this.props.availableCoupon
   .filter(
      item =>
         `${item}`
         .toUpperCase()
         .indexOf(this.props.searchTerm.toUpperCase()) >= 0
   )
   .map((item, index) => {
      return (
          <Col key={index} className="mt-3" md="2" lg="2" sm="3" xs="4">
             <Card onClick={() => this.props.changed(index)}>
                <CardBody>
                   <CardTitle>{item}</CardTitle>
                </CardBody>
              </Card>
           </Col>
       );
   })}

A: As you can see, using the index of the array as a key for each item is unreliable, since the item's key will change whenever its position in the array changes, therefore making the key pretty much useless.
What you should do instead is make it so that your items are objects with unique IDs associated with each one, so that the ID of each item will always match with the item you're working with. Wherever you're using index, use item.id instead.
availableCoupon: [
  {name: 'Coupon A', id: 0},
  {name: 'Coupon B', id: 1},
  {name: 'Coupon C', id: 2},
  {name: 'Coupon D', id: 3},
],
nonAvalailable: [
  {name: 'filter0', id: 4},
  {name: 'filter1', id: 5},
  {name: 'filter2', id: 6},
  {name: 'filter3', id: 7},
],

Make sure to update the rest of your code accordingly, e.g. by doing <Col key={item.id}>, filtering  by item.name instead of item, and so on.

A: So, the reason it is not working is because the key attribute that you rely on changes every time you actually search. So you have 2 options:
1 - use objects instead of strings, which is kind of more real-world like. Objects have properties that are unique, and not supposed to change, like id for example, or might be something else. For example [{name: 'ABCDE', id: 1}, {name: 'PQRST', id: 2}]. And so you build filtering, deleting etc on them.
2 - Stay with using strings for a while, but rather rely on the index of  each element of the initial array.
Here is what I mean:
{this.props.availableCoupon
 .filter(
    item =>
       `${item}`
       .toUpperCase()
       .indexOf(this.props.searchTerm.toUpperCase()) >= 0
 )
 .map((item, index) => {
    return (
        let ind = this.props.availableCoupon.indexOf(item);
        <Col key={index} className="mt-3" md="2" lg="2" sm="3" xs="4">
           <Card onClick={() => this.props.changed(ind)}>
              <CardBody>
                 <CardTitle>{item}</CardTitle>
              </CardBody>
            </Card>
         </Col>
     );
 })}

The second one is a realy quick fix but in real world you usually do not  do that. And you probably won't need that as long as in real world we have  stable id of each object and with it.


text:
Q: Pagination can not back to prev number I have pagination, and my pagination is working fine if I click next number.
View :

1 2 >

if I am clicking on 2 it goes on second page and shows proper result.but if I want to come back on 1 than its not redirect to page 1. here is my controller code:
public function index($date_start = 'all', $date_end = 'all', $title = 'all', $cid = 0, $skpd = 'all', $offset = NULL)
{
    if($_POST)
    {
        $filter = array(
            ($this->input->post('filter_date_start') == '') ? 'all' : $this->input->post('filter_date_start'),
            ($this->input->post('filter_date_end') == '') ? 'all' : $this->input->post('filter_date_end'),
            ($this->input->post('filter_title') == '') ? 'all' : $this->input->post('filter_title'),
            ($this->input->post('filter_kategori') == 0) ? 0 : $this->input->post('filter_kategori'),
            ($this->input->post('filter_skpd') == '') ? 'all' : $this->input->post('filter_skpd')
        );
        $url = implode('/', $filter);
        redirect('document/index'.$url);
    }
    //echo urldecode($title);
    $this->load->model('News_model');
    $this->load->library('pagination');
    $data['title'] = 'Informasi Publik';
    $param_document = array('status' => 1);
    if(!empty($tid)) $param_document['tid'] = $tid;
    if($date_start != 'all') $param_document['date_start'] = $date_start;
    if($date_end != 'all') $param_document['date_end'] = $date_end;
    if(!empty($cid)) $param_document['cid'] = $cid;
    if($title != 'all') $param_document['title'] = urldecode($title);
    if($skpd != 'all') $param_document['skpd'] = $skpd;
    $params_total = $param_document;
    $param_document_berkala = $param_document;
    $param_document_serta_merta = $param_document;
    $param_document_setiap_saat = $param_document;
    $param_document_dikecualikan = $param_document;
    $param_document['limit'] = 10;
    $param_document['offset'] = $offset;
    $data['document'] = $this->Document_model->get($param_document);

    //dimodif cara urang
    $data['bijilkategori'] = $this->Document_model->tampil();

    // get document download count
    foreach($data['document'] as $i => $row)
    {
        $document_transaction = $this->Document_model->get_transaction(array('did' => $row['document_id']));
        $data['document'][$i]['download_count'] = empty($document_transaction) ? 0 : $document_transaction[0]['count'];
    }
    /*
    $config['base_url'] = site_url('document/index/'.
        (empty($tid) ? 0 : $tid).'/'.$date_start.'/'.$date_end.'/'.
        $title.'/'.(empty($cid) ? 0 : $cid).'/'.$skpd
    );
    */

    $config['base_url'] = site_url('document/index/'.
        $date_start.'/'.$date_end.'/'.
        $title.'/'.(empty($cid) ? 0 : $cid).'/'.$skpd
    );

    $config['total_rows'] = count($this->Document_model->get($params_total));
    $config['uri_segment'] = 9;
    $this->pagination->initialize($config);
    $data['main'] = 'document/document_indeks';
    $data['kategori'] = $this->get_category();
    $data['type'] = $this->get_type(TRUE);
    $data['filter_kategori'] = $cid;
    //dihidden ku urang
    //$data['filter_type'] = $tid;
    $data['filter_date_start'] = ($date_start == 'all') ? '' : $date_start;
    $data['filter_date_end'] = ($date_end == 'all') ? '' : $date_end;
    $data['filter_title'] = ($title == 'all') ? '' : $title;
    $data['filter_author'] = ($skpd == 'all') ? '' : $skpd;
    $param_document_berkala['tid'] = 1;
    $param_document_serta_merta['tid'] = 2;
    $param_document_setiap_saat['tid'] = 3;
    $param_document_dikecualikan['tid'] = 4;
    $data['total_record'] = count($this->Document_model->get($params_total));
    $data['total_record_berkala'] = count($this->Document_model->get($param_document_berkala));
    $data['total_record_serta_merta'] = count($this->Document_model->get($param_document_serta_merta));
    $data['total_record_setiap_saat'] = count($this->Document_model->get($param_document_setiap_saat));
    $data['total_record_dikecualikan'] = count($this->Document_model->get($param_document_dikecualikan));
    $this->load->view('layout', $data);
}

Model:
public function get($params = array())
{
    if(isset($params['fields']))
    {
        $this->db->select($params['fields']);
    }
    else
    {
        $this->db->select('*');
    }

    if(isset($params['id']))
    {
        $this->db->where('document.document_id', $params['id']);
    }
    elseif(isset($params['code']))
    {
        $this->db->where('document_code', $params['code']);
    }
    elseif(isset($params['date_start']) AND isset($params['date_end']))
    {
        $this->db->where('document_date >=', $params['date_start'].' 00:00:00');
        $this->db->where('document_date <=', $params['date_end'].' 23:59:59');
    }
    elseif(isset($params['tid']))
    {
        $this->db->where('type_id', $params['tid']);
    }
    elseif(isset($params['cid']))
    {
        $this->db->where('document.category_id', $params['cid']);
    }
    elseif(isset($params['uid']))
    {
        $this->db->where('user_id', $params['uid']);
    }
    elseif(isset($params['sid']))
    {
        $this->db->where('document.skpd_id', $params['sid']);
    }
    if(isset($params['title']))
    {
        $this->db->like('document_title', $params['title']);
    }
    if(isset($params['author']))
    {
        $this->db->like('document_author', $params['author']);
    }
    elseif(isset($params['date']))
    {
        $this->db->where('document_date', $params['date']);
    }

    if(isset($params['dsid']))
    {
        $this->db->where('document_skpd_id', $params['dsid']);
    }

    if(isset($params['status']))
    {
        $this->db->where('document_is_published', $params['status']);
    }
    if(isset($params['document_sync']))
    {
        $this->db->where('document_sync', $params['document_sync']);
    }
    if(isset($params['sync']))
    {
        $this->db->reset_query();
        $this->db->select('document.*');
        $this->db->where('document_sync', $params['sync']);
    }

    if(isset($params['limit']))
    {
        if(!isset($params['offset']))
        {
            $params['offset'] = NULL;
        }

        $this->db->limit($params['limit'], $params['offset']);
    }

    if(isset($params['order_by']))
    {
        $this->db->order_by($params['order_by'], 'desc');
    }
    else
    {
        $this->db->order_by('document_date', 'desc');
    }

    $this->db->select('document.document_id');
    $this->db->join('user_desktop', 'user_desktop.user_desktop_id = document.operator_id');
    $this->db->join('(SELECT document_id, MAX(document_file_id) AS document_file_max_id FROM document_file GROUP BY document_id) AS document_file_max', 'document.document_id = document_file_max.document_id', 'left', FALSE);
    $this->db->join('document_file', 'document_file.document_file_id = document_file_max.document_file_max_id', 'left');
    $this->db->join('document_type', 'document_type.document_type_id = document.type_id');
    $this->db->join('document_form', 'document_form.document_form_id = document.form_id');
    $this->db->join('document_category', 'document_category.category_id = document.category_id');
    $this->db->join('skpd', 'skpd.skpd_id = document.skpd_id');
    $res = $this->db->get('document');

    if(isset($params['id']))
    {
        return $res->row_array();
    }
    else
    {
        return $res->result_array();
    }
}

Please master how to fix it ? whst is problem on my pagination

A: Please try this :
 $config['base_url'] = site_url('document/index/'.
        $date_start.'/'.$date_end.'/'.
        $title.'/'.(empty($cid) ? 0 : $cid).'/'.$skpd.'/'
    );
$config['uri_segment'] = 8;

in your base_url you missed out / at the end and codeigniter places offset for pagination. Hence, uri_segment would be 8.


text:
Q: HTML Broken Links For some reason a couple of hours ago I was working on our website and all of a sudden the links stopped working. We were updating the back end too. These html files aren't even working locally on my computer. The links in the source are the correct ones. What could be wrong?

Home

How It Works

Sign Up

Donate

Twitter

facebook

Does it have to do with my doctype?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

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


text:
Q: Python.net is not receiving correct encoded string from .net I am using .net 4.7.1 console program talking to python.net that VS2017 is reporting as version 2.5.1.0 (runtime version v4.0.30319) Python code is in 3.6
python:
def ping(input):
    if (input == 'ping'):
        return 'pong'
    return 'invalid'

def headervalid(header):
    if (header == '@\n\u001e\rANSI '):
        return True
    return False

if __name__ == '__main__':
    input = '@\n\u001e\rANSI '
    print(headervalid(input))
    input = 'ping'
    print(ping(input))

dot net :
using (Py.GIL())
            {
                dynamic np = Py.Import("numpy");
                Console.WriteLine(np.cos(np.pi * 2));

                dynamic sin = np.sin;
                Console.WriteLine(sin(5));

                double c = np.cos(5) + sin(5);
                Console.WriteLine(c);

                dynamic a = np.array(new List<float> { 1, 2, 3 });
                Console.WriteLine(a.dtype);

                dynamic b = np.array(new List<float> { 6, 5, 4 }, dtype: np.int32);
                Console.WriteLine(b.dtype);

                Console.WriteLine(a * b);

                dynamic parsers = Py.Import("newworld_parsers.bridgetest");

                string input = "ping";
                var result = parsers.ping(input);
                Console.WriteLine(result);
                input = @"@\n\u001e\rANSI ";
                result = parsers.headervalid(input);
                Console.WriteLine(result);

                Console.WriteLine("=======");
                Console.ReadLine();
            }

The python stand alone run reports:
True
pong
Press any key to continue . . .

Dot net run reports:
1.0
-0.9589242746631385
-0.675262089199912
float64
int32
[ 6. 10. 12.]
pong
False
=== Press any key to continue ====

Notice the True in python vs the False when calling from C#
The special characters in headervalid() from dot net don't seem to be going over correctly. What should I do to fix this? Any ideas greatly appreciated!

A: Putting '@' character in front of C# string turns it into a raw string, meaning no escape sequences inside will work.
You can see that by adding Console.WriteLine(input); to your code.


text:
Q: How to adjust size of matplotlib plot to fit into pyqt frame I am trying to add a plot into qt window, but i can't fit that into the window it is overflowing how to properly place the plot into qt window?
i created a frame with width 650 and height 600 and i want to add plot into this frame

        self.XYFrame = QtWidgets.QFrame(self.top)
        self.XYFrame.setMinimumSize(QtCore.QSize(650, 600))
        self.XYFrame.setMaximumSize(QtCore.QSize(650, 600))
        self.XYFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.XYFrame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.XYFrame.setObjectName("XYFrame")
        self.horizontalLayout_9 = QtWidgets.QHBoxLayout(self.XYFrame)
        self.horizontalLayout_9.setObjectName("horizontalLayout_9")

        xy_plot = self.plot.plotXY()
        self.plotWidget = FigureCanvas(xy_plot)
        self.horizontalLayout_9.addWidget(self.plotWidget)
        self.horizontalLayout_7.addWidget(self.XYFrame)

Here is my plotXY()
        def plotXY(self):
        height, parameter = self.connection.XYPlotData()
        fig, ax = plt.subplots()
        ax.set(xlabel = "Relative humidity", ylabel = "Height")
        ax.plot(height, parameter)
        return fig

this how the plot looks now i wanted fit the plot completely into window with weigh background without overflowing

i tried fig.tight_layout() and fig.subplots_adjust(0.2, 0.2, 0.8, 0.8) in plotXY() but it's not working
code for testing
main.py

    import sys
    from PyQt5.QtWidgets import QApplication,QMainWindow

    from ui import *
    # from mainWindowUI import *

    class MainWindow(QMainWindow):
        def __init__(self, parent=None):
            QMainWindow.__init__(self)
            self.ui = Ui_MainWindow()
            self.ui.setupUi(self)

    if __name__ == '__main__':
        app = QApplication(sys.argv)
        mainWindow = MainWindow()
        mainWindow.setWindowState(QtCore.Qt.WindowMaximized)
        mainWindow.show()
        sys.exit(app.exec_())

ui.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file '.\ui\mainWInLay.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.

from PyQt5 import QtCore, QtGui, QtWidgets
# from PyQt5.QtWebEngineWidgets import QWebEngineView
from matplotlib.backends.backend_qt5agg import FigureCanvas
import matplotlib.pyplot as plt

x = [100, 125, 150, 175, 200, 225, 250, 300, 350, 400, 450, 500, 550, 600, 650,700, 750, 775, 800, 825, 850, 875, 900, 925,950,975,1000]
y = [104.355,89.6661,86.6984,78.7212,104.783,103.04,53.765,21.0933,21.8741,24.0535,28.5814,46.6883,61.0047,79.1699,87.5734,89.2936,88.4784,86.8854,84.4816,82.6208,82.166,82.0942,83.798,82.3396,77.1371,82.0763,76.2785]

def plotXY():
    height, parameter = x, y
    fig, ax = plt.subplots()
    ax.set(xlabel = "Relative humidity", ylabel = "Height")
    ax.plot(height, parameter)
    return fig

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1389, 600)
        MainWindow.setStyleSheet("")

        # self.plot = Plot()

        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setStyleSheet("background-color: rgb(43, 54, 72);")
        self.centralwidget.setObjectName("centralwidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.mainFrame = QtWidgets.QFrame(self.centralwidget)
        self.mainFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.mainFrame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.mainFrame.setObjectName("mainFrame")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.mainFrame)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.top = QtWidgets.QFrame(self.mainFrame)
        self.top.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.top.setFrameShadow(QtWidgets.QFrame.Raised)
        self.top.setObjectName("top")
        self.horizontalLayout_7 = QtWidgets.QHBoxLayout(self.top)
        self.horizontalLayout_7.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_7.setObjectName("horizontalLayout_7")
        self.contourFrame = QtWidgets.QFrame(self.top)
        self.contourFrame.setMinimumSize(QtCore.QSize(650, 600))
        self.contourFrame.setMaximumSize(QtCore.QSize(650, 600))
        self.contourFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.contourFrame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.contourFrame.setObjectName("contourFrame")
        self.horizontalLayout_8 = QtWidgets.QHBoxLayout(self.contourFrame)
        self.horizontalLayout_8.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_8.setSpacing(0)
        self.horizontalLayout_8.setObjectName("horizontalLayout_8")

        # self.url = QtCore.QUrl.fromLocalFile(r"data.html")
        # self.webview = QWebEngineView(self.contourFrame)
        # self.webview.load(self.url)
        # # self.widget = QtWidgets.QWidget(self.contourFrame)
        # # self.widget.setStyleSheet("")
        # # self.widget.setObjectName("widget")
        # self.horizontalLayout_8.addWidget(self.webview)

#----------------------------------------------------------------------------------------
# HERE IS THE FRAME THAT I WANT TO INSRET MY PLOT

        self.horizontalLayout_7.addWidget(self.contourFrame)
        self.XYFrame = QtWidgets.QFrame(self.top)
        self.XYFrame.setMinimumSize(QtCore.QSize(650, 600))
        self.XYFrame.setMaximumSize(QtCore.QSize(650, 600))
        self.XYFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.XYFrame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.XYFrame.setObjectName("XYFrame")
        self.horizontalLayout_9 = QtWidgets.QHBoxLayout(self.XYFrame)
        self.horizontalLayout_9.setObjectName("horizontalLayout_9")

        xy_plot = plotXY()
        self.plotWidget = FigureCanvas(xy_plot)
        self.horizontalLayout_9.addWidget(self.plotWidget)

#----------------------------------------------------------------------------------------
        self.horizontalLayout_7.addWidget(self.XYFrame)

        self.verticalLayout.addWidget(self.top)
        self.bottom = QtWidgets.QFrame(self.mainFrame)
        self.bottom.setMinimumSize(QtCore.QSize(0, 250))
        self.bottom.setMaximumSize(QtCore.QSize(16777215, 250))
        self.bottom.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.bottom.setFrameShadow(QtWidgets.QFrame.Raised)
        self.bottom.setObjectName("bottom")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.bottom)
        self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_2.setSpacing(10)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.selectionFrame = QtWidgets.QFrame(self.bottom)
        self.selectionFrame.setMinimumSize(QtCore.QSize(500, 250))
        self.selectionFrame.setMaximumSize(QtCore.QSize(500, 250))
        self.selectionFrame.setStyleSheet("background-color: rgb(0, 0, 0);")
        self.selectionFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.selectionFrame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.selectionFrame.setObjectName("selectionFrame")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.selectionFrame)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.dayMonFrame = QtWidgets.QFrame(self.selectionFrame)
        self.dayMonFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.dayMonFrame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.dayMonFrame.setObjectName("dayMonFrame")
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.dayMonFrame)
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.dayLabel = QtWidgets.QLabel(self.dayMonFrame)
        self.dayLabel.setMinimumSize(QtCore.QSize(100, 25))
        self.dayLabel.setMaximumSize(QtCore.QSize(100, 25))
        self.dayLabel.setStyleSheet("color: rgb(86, 101, 127);\n"
"font-size:18px;")
        self.dayLabel.setObjectName("dayLabel")
        self.horizontalLayout_3.addWidget(self.dayLabel)
        self.daySpinBox = QtWidgets.QSpinBox(self.dayMonFrame)
        self.daySpinBox.setMinimumSize(QtCore.QSize(100, 25))
        self.daySpinBox.setMaximumSize(QtCore.QSize(100, 25))
        self.daySpinBox.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.daySpinBox.setObjectName("daySpinBox")
        self.horizontalLayout_3.addWidget(self.daySpinBox)
        self.monLabel = QtWidgets.QLabel(self.dayMonFrame)
        self.monLabel.setMinimumSize(QtCore.QSize(100, 25))
        self.monLabel.setMaximumSize(QtCore.QSize(100, 25))
        self.monLabel.setStyleSheet("color: rgb(86, 101, 127);\n"
"font-size:18px;")
        self.monLabel.setObjectName("monLabel")
        self.horizontalLayout_3.addWidget(self.monLabel)
        self.monSpinBox = QtWidgets.QSpinBox(self.dayMonFrame)
        self.monSpinBox.setMinimumSize(QtCore.QSize(100, 25))
        self.monSpinBox.setMaximumSize(QtCore.QSize(100, 25))
        self.monSpinBox.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.monSpinBox.setObjectName("monSpinBox")
        self.horizontalLayout_3.addWidget(self.monSpinBox)
        self.verticalLayout_2.addWidget(self.dayMonFrame)
        self.paramprsFrame = QtWidgets.QFrame(self.selectionFrame)
        self.paramprsFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.paramprsFrame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.paramprsFrame.setObjectName("paramprsFrame")
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.paramprsFrame)
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.label = QtWidgets.QLabel(self.paramprsFrame)
        self.label.setMinimumSize(QtCore.QSize(100, 25))
        self.label.setMaximumSize(QtCore.QSize(100, 25))
        self.label.setStyleSheet("color: rgb(86, 101, 127);\n"
"font-size:18px;")
        self.label.setObjectName("label")
        self.horizontalLayout_4.addWidget(self.label)
        self.comboBox = QtWidgets.QComboBox(self.paramprsFrame)
        self.comboBox.setMinimumSize(QtCore.QSize(100, 25))
        self.comboBox.setMaximumSize(QtCore.QSize(100, 25))
        self.comboBox.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.comboBox.setObjectName("comboBox")
        self.horizontalLayout_4.addWidget(self.comboBox)
        self.label_2 = QtWidgets.QLabel(self.paramprsFrame)
        self.label_2.setMinimumSize(QtCore.QSize(100, 25))
        self.label_2.setMaximumSize(QtCore.QSize(100, 25))
        self.label_2.setStyleSheet("color: rgb(86, 101, 127);\n"
"font-size:18px;")
        self.label_2.setObjectName("label_2")
        self.horizontalLayout_4.addWidget(self.label_2)
        self.comboBox_2 = QtWidgets.QComboBox(self.paramprsFrame)
        self.comboBox_2.setMinimumSize(QtCore.QSize(100, 25))
        self.comboBox_2.setMaximumSize(QtCore.QSize(100, 25))
        self.comboBox_2.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.comboBox_2.setObjectName("comboBox_2")
        self.horizontalLayout_4.addWidget(self.comboBox_2)
        self.verticalLayout_2.addWidget(self.paramprsFrame)
        self.latLonFrame = QtWidgets.QFrame(self.selectionFrame)
        self.latLonFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.latLonFrame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.latLonFrame.setObjectName("latLonFrame")
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout(self.latLonFrame)
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.label_3 = QtWidgets.QLabel(self.latLonFrame)
        self.label_3.setMinimumSize(QtCore.QSize(100, 25))
        self.label_3.setMaximumSize(QtCore.QSize(100, 25))
        self.label_3.setStyleSheet("color: rgb(86, 101, 127);\n"
"font-size:18px;")
        self.label_3.setObjectName("label_3")
        self.horizontalLayout_5.addWidget(self.label_3)
        self.comboBox_3 = QtWidgets.QComboBox(self.latLonFrame)
        self.comboBox_3.setMinimumSize(QtCore.QSize(100, 25))
        self.comboBox_3.setMaximumSize(QtCore.QSize(100, 25))
        self.comboBox_3.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.comboBox_3.setObjectName("comboBox_3")
        self.horizontalLayout_5.addWidget(self.comboBox_3)
        self.label_4 = QtWidgets.QLabel(self.latLonFrame)
        self.label_4.setMinimumSize(QtCore.QSize(100, 25))
        self.label_4.setMaximumSize(QtCore.QSize(100, 25))
        self.label_4.setStyleSheet("color: rgb(86, 101, 127);\n"
"font-size:18px;")
        self.label_4.setObjectName("label_4")
        self.horizontalLayout_5.addWidget(self.label_4)
        self.comboBox_4 = QtWidgets.QComboBox(self.latLonFrame)
        self.comboBox_4.setMinimumSize(QtCore.QSize(100, 25))
        self.comboBox_4.setMaximumSize(QtCore.QSize(100, 25))
        self.comboBox_4.setStyleSheet("background-color: rgb(255, 255, 255);")
        self.comboBox_4.setObjectName("comboBox_4")
        self.horizontalLayout_5.addWidget(self.comboBox_4)
        self.verticalLayout_2.addWidget(self.latLonFrame)
        self.btnFrame = QtWidgets.QFrame(self.selectionFrame)
        self.btnFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.btnFrame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.btnFrame.setObjectName("btnFrame")
        self.pushButton = QtWidgets.QPushButton(self.btnFrame)
        self.pushButton.setGeometry(QtCore.QRect(190, 10, 125, 35))
        self.pushButton.setMinimumSize(QtCore.QSize(125, 35))
        self.pushButton.setMaximumSize(QtCore.QSize(125, 35))
        self.pushButton.setStyleSheet("background-color: rgb(255, 255, 255);\n"
"border:1px solid black;\n"
"border-radius:15px;")
        self.pushButton.setObjectName("pushButton")
        self.verticalLayout_2.addWidget(self.btnFrame)
        self.horizontalLayout_2.addWidget(self.selectionFrame)
        self.timeFrame = QtWidgets.QFrame(self.bottom)
        self.timeFrame.setMinimumSize(QtCore.QSize(825, 250))
        self.timeFrame.setMaximumSize(QtCore.QSize(825, 250))
        self.timeFrame.setStyleSheet("background-color: rgb(0, 0, 0);")
        self.timeFrame.setFrameShape(QtWidgets.QFrame.StyledPanel)
        self.timeFrame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.timeFrame.setObjectName("timeFrame")
        self.horizontalLayout_6 = QtWidgets.QHBoxLayout(self.timeFrame)
        self.horizontalLayout_6.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_6.setSpacing(0)
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")

        # self.timeWidget = QtWidgets.QWidget(self.timeFrame)
        # self.timeWidget.setObjectName("timeWidget")
        # self.time_plot = self.plot.plotTime(13, 1)
        # self.timePlotWindow  = FigureCanvas(self.time_plot)
        # self.horizontalLayout_6.addWidget(self.timePlotWindow)

        self.horizontalLayout_2.addWidget(self.timeFrame)
        self.verticalLayout.addWidget(self.bottom)
        self.horizontalLayout.addWidget(self.mainFrame)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1389, 21))
        self.menubar.setObjectName("menubar")

        MainWindow.setMenuBar(self.menubar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.dayLabel.setText(_translate("MainWindow", "Day"))
        self.monLabel.setText(_translate("MainWindow", "Month"))
        self.label.setText(_translate("MainWindow", "Parameters"))
        self.label_2.setText(_translate("MainWindow", "Pressure"))
        self.label_3.setText(_translate("MainWindow", "Latitude"))
        self.label_4.setText(_translate("MainWindow", "Longitude"))
        self.pushButton.setText(_translate("MainWindow", "PushButton"))


text:
Q: Host Youtube API data on a database to avoid quota limitation We are developing an android application which showcases the videos published by our channel on the application.
We are simply using the DATA API to fetch the videos present in our playlist and display them in the App.
Since there is a limit on API quota of 10,000 units, I would like to host the data on a database which I can scale up to 200,000 calls per day,
as we are targeting an audience of around 250,000 users.
Is this process legal?
I have raised the quota extension request using the form https://support.google.com/youtube/contact/yt_api_form?hl=en, but there is no significant progress.
Please guide me if I am missing something here or is there better way to approach the problem.


text:
Q: MVC3 Webgrid sorting problem with 2nd+ columns in this sample the sorting of the grid works well with the first column. Every other column can only be sorted ascending, the "sortdir" never switches to "DESC". (Ajax caching is also disabled)
Does anybody knows a solution or had the same problem? What im doing wrong?
Controller:
[OutputCache(Location = OutputCacheLocation.None)]
public ActionResult Index_Result_Org(string sort, string sortdir)
{
   this.setRep();
   this.rep.LoadOV();
   return View("Index_OV", rep.GetOV(sort != null ? sort : "Kennung", sortdir != null ? sortdir == "ASC" : true));
}

View:
@model List<Models.OV_View>
@{
    Layout = null;
    var grid_BA = Html.Grid<OV_View>(Model, ajaxUpdateContainerId: "BAS_OV", canPage: false, defaultSort: "Kennung");
}
<div id="BAS_OV">
    @grid_BA.GetHtml(
    htmlAttributes: new { @id = "webgrid_BA" },
    alternatingRowStyle: "alt",
    tableStyle: "BAS",
    columns: grid_BA.Columns(
                         grid_BA.Column("Kennung", header: "Verbandskennung", format: @<text>@Html.Label(@item.Data.Kennung)</text>, canSort: true),
                         grid_BA.Column("Name", header: "Verbandsname", format: @<text>@item.Data.Name</text>, canSort: true),
                         grid_BA.Column("Anzahl", header: "Anzahl", format: @<text>@item.Data.Anzahl</text>, canSort: true, style: "counter_column"),
                         grid_BA.Column("Select", header: "X", canSort: false, format: @<text><input id="Select" name="Select" type="checkbox" onclick="Select(this)" value="@item.Select" @(item.Select == true ? "Checked" : null) /></text>, style: "checkbox_column"),
                         grid_BA.Column("ID", "", format: @<text>@item.Data.ID</text>, canSort: false, style: "invisible_column")
                            )
                      )
</div>

A: Got it.
Only the defaulSort: Column can be sorted descending.
So i added the following line to the controller:
this.ViewBag.Sort = sort;

And andded and changed the following lines in the view:
var grid_BA = Html.Grid<ErgoBAS_OV_View>(Model, ajaxUpdateContainerId: "BAS_OV", canPage: false, defaultSort: "Kennung");

to:
string temp = this.ViewBag.Sort != null ? this.ViewBag.Sort : "Kennung";
var grid_BA = Html.Grid<ErgoBAS_OV_View>(Model, ajaxUpdateContainerId: "BAS_OV", canPage: false, defaultSort: temp);

This is the dirty solution, think to be clean the defaultSort has to be added to the View Model, thats what i will do now.


text:
Q: Duplicate a document on elasticsearch I need to clone the content of a document in my elasticsearch index (in the same index) by using the kibana console. I need exactly the same fields in the _source of the document (of course, the copy will have another id). I tryed to:

*

*GET the document

*Create a new empty instance of document

*Update the new document by
manually copying the properties of the result on (1):

POST /blog/post/VAv2FWoBKgnBpki61WiD/_update {    "doc" : {
  "content" : "..." ...

But the problem is the field contain veeeery long properties. And sometimes I got an error since the strings seem not to be scaped when I manually copy them from the Kibana interface.
I searched in the documentation but I can not find a query to duplicate a document, and it is a quite common think to do I think...
Any clue?

A: Make use of Reindex API. Here is what you can do.
Summary of steps:

*

*Create a destination_index (dummy). Make sure the mapping is exact to that of source_index

*Using Reindex API, reindex that particular document from source_index to desitnation_index. During this operation, update the _id (I've mentioned the script)

*Reindex this document back from desitnation_index to source_index
Reindex Query
Step 1: Copy document from source_index to destination_index. (With the script)
POST _reindex
{
  "source": {
    "index": "source_index",
    "query": {
      "match": {
        "_id": "1"
      }
    }
  },
  "dest": {
    "index": "destination_index"
  },
  "script": {
    "inline": "ctx._id=2",
    "lang": "painless"
  }
}

Note how I've added a script in the above query that would change the _id (_id is set as 2) of the document. Your destination_index would have all the fields with exact same values as that of source except for the _id field.
Step 2: Copy that document from destination_index to source_index
POST _reindex
{
  "source": {
    "index": "destination_index",
    "query": {
      "match": {
        "_id": "2"
      }
    }
  },
  "dest": {
    "index": "source_index"
  }
}

Now search the source_index, it would have two documents with different _ids (_id=1 and _id=2) having exact same content.
Hope this helps!


text:
Q: How do I create this semi-enclosed arrow symbol? I would like to create a symbol for \implies and \impliedby where they are enclosed in a rotated lidless box as shown in the picture. Can anybody tell me how I could achieve this?

A: Welcome! You do not need any packages for that.
\documentclass{article}
\newcommand{\RightArrowInBox}{\begingroup
\renewcommand{\arraystretch}{0.6}\begin{array}{@{}c@{}|}\hline
\raisebox{-0.2ex}{$\Rightarrow$}\\ \hline\end{array}\endgroup}
\newcommand{\LeftArrowInBox}{\begingroup
\renewcommand{\arraystretch}{0.6}\begin{array}{@{}c@{}|}\hline
\raisebox{-0.2ex}{$\Leftarrow$}\\ \hline\end{array}\endgroup}
\begin{document}
$\RightArrowInBox~\LeftArrowInBox$
\end{document}

Of course you can modify the padding etc.
A version without cutting corners with major input by barbara beeton.
\documentclass{article}
\newcommand{\RightArrowInBox}{\begingroup
\renewcommand{\arraystretch}{0.6}\begin{array}{@{}c@{\rule[-3pt]{0.4pt}{0.85em}}}\hline
\raisebox{-0.28ex}{$\Rightarrow$}\\ \hline\end{array}\endgroup}
\newcommand{\LeftArrowInBox}{\begingroup
\renewcommand{\arraystretch}{0.6}\begin{array}{@{}c@{\rule[-3pt]{0.4pt}{0.85em}}}\hline
\raisebox{-0.28ex}{$\Leftarrow$}\\ \hline\end{array}\endgroup}
\begin{document}
$\RightArrowInBox~\LeftArrowInBox$
\end{document}

Or with trimclip.
\documentclass{article}
\usepackage{trimclip}
\newcommand{\RightArrowInBox}{\begingroup
\clipbox{0.5ex 0em 0em 0em}{\fbox{$\Rightarrow\!$}}\endgroup}
\newcommand{\LeftArrowInBox}{\begingroup
\clipbox{0.5ex 0em 0em 0em}{\fbox{$\Rightarrow\!$}}\endgroup}

\begin{document}
$\RightArrowInBox~\LeftArrowInBox$
\end{document}

A: Here's a solution which places \implies and \impliedby into a modified version of \fbox.

\documentclass{article}
\usepackage{amsmath}
\makeatletter
\def\@rframeb@x#1{%
  \@tempdima\fboxrule
  %\advance\@tempdima\fboxsep
  \advance\@tempdima\dp\@tempboxa
  \hbox{%
    \lower\@tempdima\hbox{%
      \vbox{%
        \hrule\@height\fboxrule
        \hbox{%
          %\vrule\@width\fboxrule
          #1%
          \vbox{%
            \vskip.7\fboxsep
            \box\@tempboxa
            \vskip.3\fboxsep}%
          #1%
          \vrule\@width\fboxrule}%
        \hrule\@height\fboxrule}%
                          }%
        }%
}
\DeclareRobustCommand\rfbox[1]{%
  \leavevmode
  \setbox\@tempboxa\hbox{%
    \color@begingroup
      \kern.2\fboxsep{#1}\kern.2\fboxsep
    \color@endgroup}%
  \@rframeb@x\relax}
\makeatother
\newcommand{\boximplies}{%
    \mathrel{\:\rfbox{$\Longrightarrow$}\:}%
}
\newcommand{\boximpliedby}{%
    \mathrel{\:\rfbox{$\Longleftarrow$}\:}%
}
\begin{document}
\( A \implies B \)

\( A \boximplies B \)

\( A \impliedby B \)

\( A \boximpliedby B \)
\end{document}

A: Only array (that's a required package in every distribution):
\documentclass{article}
\usepackage{array}

\newcommand{\bimplies}{\mathrel{\bimpl{c|}{\Rightarrow}}}
\newcommand{\bimpliedby}{\mathrel{\bimpl{|c}{\Leftarrow}}}
\newcommand{\bimpl}[2]{%
  \begingroup
  \setlength{\arraycolsep}{0pt}%
  \renewcommand{\arraystretch}{0}%
  \begin{array}{#1}\hline{#2}\vphantom{+}\\\hline\end{array}%
  \endgroup
}

\begin{document}

$A\bimplies B\bimpliedby C$

\end{document}

A: Try this overlay of two symbols. Too bad there is no big square left/right, so it requires rotation.
\usepackage{graphicx}
\usepackage{amssymb}

\newcommand\RightArrowInBox{%
 \rotatebox[origin=c]{90}{\ooalign{%
  \hfil$\Downarrow$\hfil\cr\noalign{\kern0.4pt}%
  \hfil$\bigsqcup$\hfil\cr}}}
\newcommand\LeftArrowInBox{%
 \rotatebox[origin=c]{-90}{\ooalign{%
  \hfil$\Downarrow$\hfil\cr\noalign{\kern0.4pt}%
  \hfil$\bigsqcup$\hfil\cr}}}

Other symbol collections like basic LaTeX or stmaryrd work better when inserting \displaystyle with the square or \scriptstyle with the arrow because the \bigsqcup is smaller than the version from amssymb.


text:
Q: Microsoft Word VSTO AddIn not able to write a file to the file system - access denied I am working on a Microsoft Word Add In using VSTO, and the Add In works properly on my development system. But when I install it on another system, it is not able to create a file on the file system and throws the following error:
Access to the path XYZ is denied.
This exception is thrown when the following line of code is executed:
File.WriteAllBytes(Constants.temporaryTemplateFile, schemaEntity.TemplateFile);

The Microsoft Word is running as a User which is Administrator. In the task manager, the WINWORD.EXE shows the user as xyz which is an Administrator.
Any suggestions how to resolve this?

A: go to folder than want create file in. then in right click properties options on security tab add everyone type user, give all access to everyone.

after do this test your add-ins again, if result is ok you know that problem in accessing and you can find way for this problem...


text:
Q: how to stop email of order programmatically in custom payment method? use Magento\Quote\Model\QuoteManagement;
...

// Create order from quote

$order = $this->quoteManagement->submit($quote);

// This code send mail automatically

//also used **$order->setCanSendNewEmailFlag(false);**

// But this not working in magento 2.3.0

A: Overwrite/pluginize following class which is responsible for sending order mail.
vendor/magento/module-quote/Observer/SubmitObserver.php
You can try the following using plugin:

app/code/SR/MagentoCommunity/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Quote\Observer\SubmitObserver">
        <plugin name="SR_MagentoCommunity::stop_sending_order_email_for_custom_payment"
                type="SR\MagentoCommunity\Plugin\Quote\Observer\SubmitObserver" sortOrder="1"/>
    </type>
</config>

app/code/SR/MagentoCommunity/Plugin/Quote/Observer/SubmitObserver.php

<?php
namespace SR\MagentoCommunity\Plugin\Quote\Observer;

class SubmitObserver
{
    public function beforeExecute(
        \Magento\Quote\Observer\SubmitObserver $subject,
        \Magento\Framework\Event\Observer $observer
    ) {
        /** @var  \Magento\Sales\Model\Order $order */
        $order = $observer->getEvent()->getOrder();

        // Add your custom logic here
        $order->setCanSendNewEmailFlag(false);
        return [$observer];
    }
}


text:
Q: Android Image centered in design but not in application I have problem. I am using android studio 2.2.3

That traffic light
And when I run app

it is not centred as in design, why is this happening ?
my java and xml code
package com.example.filip.traficcontrol;

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ImageView imageView =  (ImageView)findViewById(R.id.ivImage);
        ImageButton imageButton2 = (ImageButton)findViewById(R.id.imageButton2);
        ImageButton imageButton3 = (ImageButton)findViewById(R.id.imageButton3);
        ImageButton imageButton4 = (ImageButton)findViewById(R.id.imageButton4);

        imageButton2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageView.setImageResource(R.drawable.cetl);
            }
        });

        imageButton3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageView.setImageResource(R.drawable.zetl);
                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        imageView.setImageResource(R.drawable.cetl);
                    }
                }, 3000);

            }
        });

        imageButton4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imageView.setImageResource(R.drawable.zltl);
            }
        });

    }
}

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.filip.traficcontrol.MainActivity"
    android:background="@drawable/code"
    android:scaleType="fitStart"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    >

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/photo"
        android:id="@+id/imageButton4"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignTop="@+id/imageButton3" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/photo"
        android:id="@+id/imageButton2"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="10dp"
        android:layout_marginStart="10dp" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/photo"
        android:id="@+id/imageButton3"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        app:srcCompat="@drawable/cetl"
        android:id="@+id/ivImage"
        android:adjustViewBounds="false"
        android:cropToPadding="false"
        android:focusable="false"
        android:keepScreenOn="false"
        android:layout_centerInParent="false"
        tools:layout_width="match_parent"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/imageButton4"
        android:scaleType="center"
        android:layout_gravity="center"
        />

</RelativeLayout>

I just want the picture of traffic light centered can someone help ?
Its just ff aplication not hacking application if someone thought.

A: I figured it out this way
I was cutting those traffic lights from image where were 3 of them. So I reworked graphics to make every trafficlight in middle of picture. Works for me fine


text:
Q: Synchronizing clock time in host and guest under KVM I have a relatively simple requirement: I want the clock on the CentOS guests that I create under KVM to be synchronized with their CentOS host from the very first boot of the VMs.
It's easy enough to synchronize them with NTP after they are up and running. However, if the host's clock and the VM's clock are widely different when NTP starts, it can cause a large jump in the VM's time. Many of our applications running under the VMs do not handle this time jump well, so we want to prevent this from happening.
So my question is how can I configure my VMs to start with the same time as their host? In the test I just ran, my host's time was 14:00 PDT. A VM I created under that host came up with an initial time of 21:00 PDT. This was adjusted by NTP to 14:00 PDT shortly after it started to 14:00 PDT, matching the host's time, and subsequent reboots of the VM always had the correct time. The problem only occurs on the first boot. I want the VM to come up with 14:00 PDT one the very first boot to avoid the NTP time jump.

A: Okay, I've answered my own question. The combination of settings that I used to give me the results I need are:

*

*Set the hwclock on the host and to use UTC time. This is done with the --utc option of the hwclock command. I run the following command on my host OS:
hwclock --utc --set --date="time-string"

*Tell CentOS that the hwclock is using UTC via the file /etc/adjtime. For example, you could initialize this file using
echo -e "0.0 0 0.0\n0\n\nUTC" >/etc/adjtime
Create this file on both the host and your guest VMs. I create the file on my guests before I boot them for the first time by directly accessing the guest file system from the host.

*Set the time zone you want for your system time. Again, do this on both your host and your guests:
ln -sf /usr/share/zoneinfo/time-zone /etc/localtime
echo "ZONE=time-zone" >/etc/sysconfig/clock
export TZ=time-zone
where time-zone is a standard CentOS time zone string, for example "US/Pacific".

*Set the system time on your host based on the hwclock. The --utc option is needed to tell CentOS that the hwclock is in UTC time. It will take the UTC time and set your system time based on the TZ environment variable:
hwclock --utc --hctosys

*The steps above are all done once, when you are configuring your host and guests. To keep time synced on all your servers after they are up and running you'll want to configure NTP on your host and guests.


text:
Q: How many times a different word appear in a string - python For example I have GolDeNSanDyWateRyBeaChSand and I need to find how many times the word sand appears.
text = input()
text = text.lower()
count = 0

if "sand" in text:
    count += 1

print(count)

But the problem is that there is 2 sand in this string and when it found the first one it stops. Im a beginner in the programming.

A: You can simply use the str.count() method to count how many times a string appears in another string.
text = input()
text = text.lower()
count = text.count("sand")

A: To find every occurrence of a string pattern inside another string s, even nested occurrences, do the following:
s = "sandsandssands"  # your string here
pattern = "sands"     # your pattern here

pos = -1
end_of_string = False

while not end_of_string:
    pos = s.find(pattern, pos+1)
    print(pos)
    end_of_string = (pos == -1)

Output
0
4
9
-1

A: Extending the solution offered by the OP.
The idea is to use find and move to towards the end of the string.
It is clear that count can be used here and the solution below is for educational purpose.
text = 'GolDeNSanDyWateRyBeaChSand'
word = 'sand'
ltext = text.lower()
offset = 0
counter = 0
while True:
    idx = ltext.find(word, offset)
    if idx == -1:
        break
    else:
        counter += 1
        offset = idx + len(word)
print(f'The word {word} was found {counter} times')

output
The word sand was found 2 times


text:
Q: Using google maps with Lightbox2 Does anyone know how to show google maps using lightbox2 by Lokesh Dhakar (http://lokeshdhakar.com/projects/lightbox2/)  I can see lots of examples of showing images, but none on showing maps.  I was using lightbox, but it is problematic with later versions of jquery.
This is how to show an image

I tried doing something like this, but it doesn't seem to work:

    location

A: Straight answer
Lightbox2 does not support anything other than images.
Alternative
Heres an example of how to roll your own lightbox for Google Maps using some simple css and jQuery.
Basically the only real challenge is to resize the canvas on the first show of the overlay.
Other lightbox alternatives

*

*Easybox

*Fancybox

*Colorbox


text:
Q: Actionscript 2.0 variable and button issue I'm new here, and I already need help. Typical newb thing, you know?
I'm testing the waters in Actionscript 2.0, since it looked easier to get into than 3.0. I know 3.0 is more powerful and stuff, but babysteps.
Anyway, I'm testing using variables and buttons, but can't get it to work. My code is this:
var val = 100;

tstBtn.onRelease = function()
{
    val++;
}

Simple enough, right?
On stage I have a dynamic text that tracks the value.
So when I test it and press the button, it works the first time I press it, outputs val=101.
But if I press it again, it goes val=10 and stays there, no matter how many times I press the button again.
Anyone who can tell me what I'm doing wrong here?

A: Wow, so turns out it's the font and not the script that's messing up. Gee, guess I'm an idiot then. Thanks akmozo! Got it to work.
Tried the trace() and the value is correct. Fixed the font and now it displays correctly.


text:
Q: Fatal error in wchar_t* to char* conversion Here is a C code that converts a wchar_t* string into a char* string :
wchar_t *myXML = L"<test/>";
size_t length;
char *charString;
size_t i;
length = wcslen(myXML);
charString = (char *)malloc(length);
wcstombs_s(&i, charString, length, myXML, length);

The code compiles but at exectution it detects a fatal error at the last line and stops running.
Now, if I replace the last line with this one :
wcstombs_s(&i, charString, length+1, myXML, length);

I just added +1 to the third argument. Then it works perfectly...
Why is there a need to add this trick ? Or is there a flaw elsewhere in my code ?

A: You need one extra byte for the '\0' terminator character. wcslen does not include this in the length it returns!
To do this properly, you don't just need to pass length+1 to wcstombs_s but also to malloc:
charString = (char *)malloc(length+1);
wcstombs_s(&i, charString, length+1, myXML, length);

And even then, I suspect it will not work correctly. Not all wide characters can be mapped to a single char, so for non-ASCII characters you will need extra space in the multi-byte string.

A: DESCRIPTION
       The wcslen() function is the wide-character
       equivalent of the strlen(3) function.  It determines
       the length of the wide-character string pointed to by
       s, not including the terminating L'\0' character.

The trick is that you should always look for code of the form:
string = malloc(len);

very suspiciously, because both wcslen(3) and strlen(3) return the string length without the nul byte, and malloc(3) must allocate the space with that byte. C kinda sucks sometimes.
So every time you see string = malloc(len); rather than string = malloc(len+1);, be very careful to read how len gets assigned.

char String = (char *)malloc(length + 1);

Ought to do the trick. :)
EDIT:
Better would be to ask wcstombs() for the size to allocate in the first place:
size_t len = wcstombs(NULL,src,0) + 1;
char *dest = malloc(len);
len = wcstombs(dest, src, len);
if (len == -1) /* handle error */ ...

The +1 allocates for the ascii nul, and wcstombs() will report how much memory is required to do the conversion. It'll do the conversion twice, once to keep track of the memory required, and then once to store the result, but it will be MUCH simpler to maintain. The second time, when it stores the result, it will write at most len bytes including the ascii nul.


text:
Q: How do I use object object1 = new object on my program? I have an assignment where my program outputs a simple String using if conditions of another String, but I keep running into a problem where I cannot create a new instance(i think that is what it is called)
anyway, here is my code
 import java.util.Scanner;

public class EP54
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Do you want to continue? ");
        **yesNoChecker check1 = new yesNoChecker();**
        System.out.print(EP54.yesNoChecker);
    }

   public String yesNoChecker()
   {
       if(in.equalsIgnoreCase("y") ||
         in.equalsIgnoreCase("yes") ||
         in.equalsIgnoreCase("Sure") ||
         in.equalsIgnoreCase("why not"))
         System.out.println("OK");
       else if(in.equalsIgnoreCase("y") ||
         in.equalsIgnoreCase("yes") ||
         in.equalsIgnoreCase("Sure") ||
         in.equalsIgnoreCase("why not"))
         System.out.println("Terminating.");
       else
         System.out.println("Bad Input");
   }
}

Please help me! (bolded part is where I get error)
Can anybody give me a working version of the code so I can compare it with mine?

A: import java.util.Scanner;

public class EP54
{
   public static void main(String[] args)
   {
       Scanner in = new Scanner(System.in);
       System.out.print("Do you want to continue? ");
       String answer = in.next();
       yesNoChecker(answer);
   }

   public static void yesNoChecker(String in)
   {
       if(in.equalsIgnoreCase("y") ||
         in.equalsIgnoreCase("yes") ||
         in.equalsIgnoreCase("Sure") ||
         in.equalsIgnoreCase("why not"))
         System.out.println("OK");
       else if(in.equalsIgnoreCase("n") ||
         in.equalsIgnoreCase("no") ||
         in.equalsIgnoreCase("nope") ||
         in.equalsIgnoreCase("quit"))
         System.out.println("Terminating.");
       else
         System.out.println("Bad Input");;
   }
}

Got it

A: yesNoChecker() is a function, not an object.  In this case you will want to invoke yesNoChecker() (also known as "calling the method"), rather than instantiate yesNoChecker (also known as "creating an object").  Instead, your code should look something like:
import java.util.Scanner;

public class EP54
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Do you want to continue? ");
        yesNoChecker();
        System.out.print(EP54.yesNoChecker);
    }

   public String yesNoChecker()
   {
       // (omitted for brevity)
   }
}

You instantiate new objects of a class type.  For example, Scanner is a class that you've used here that Java provides you with.  When you say new Scanner(), you are creating a new instance of the Scanner class.

A: yesNoChecker is a method, not a class-you cannot instantiate it.
You can call it:
yesNoChecker();

However, it is defined to return a String, which it currently does not do. You may want to return the string you are now printing instead.

A: You need to get the actual input from the user/Scanner class also.
Something like:
String s = in.nextLine();

Then you compare the String s to whatever you need ("Y", "yes" etc...)
Hope this helps!
p.s. Your function does that, but consider if someone enters a digit rather than a letter or a work. It is always a good idea to validate input before using it.


text:
Q: Error: spawn ng build --watch --output-path while running gulp I'm new to Angular, when I try running gulp in the angular folder, I get the following error:
[08:24:14] Using gulpfile .../angular/gulpfile.js
[08:24:14] Starting 'styles'...
[08:24:14] Starting 'angular'...
[08:24:14] Finished 'angular' after 6.44 ms
[08:24:14] Starting 'server'...
[08:24:14] Finished 'server' after 19 ms
[08:24:14] Starting 'watch'...
[08:24:14] Finished 'watch' after 53 ms
events.js:141
      throw er; // Unhandled 'error' event
      ^

Error: spawn ng build --watch --output-path ../../public/angular/dist ENOENT
    at exports._errnoException (util.js:870:11)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:178:32)
    at onErrorNT (internal/child_process.js:344:16)
    at doNTCallback2 (node.js:441:9)
    at process._tickCallback (node.js:355:17)
    at Function.Module.runMain (module.js:469:11)
    at startup (node.js:136:18)
    at node.js:963:3

I have already followed a similar post and tried:
rm -rf node_modules && npm cache clean && npm install

But, still get the same error.

A: Given your error message, it looks like your gulp task is calling:
spawn("ng build --watch --output-path ../../public/angular/dist")
Spawn requires arguments to be passed separately from the initial command, so you should use
spawn("ng", ["build", "--watch", "--output-path", "../../public/angular/dist"])
instead.
https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options

A: I have faced the similar problem with NPM angular script on windows, there are couple of thing you can check.
Step 1. Add below code to the top, so that you know which command has problem
  /** add below childProcess logic to troubleshoot what's wrong if error happens. */
  var childProcess = require("child_process");
  var oldSpawn = childProcess.spawn;
  function mySpawn() {
      console.log('spawn called');
      console.log(arguments);
      var result = oldSpawn.apply(this, arguments);
      return result;
  }
  childProcess.spawn = mySpawn;
  spawn = childProcess.spawn;

Step 2. If you run your application on windows, you may need to use ng.cmd; otherwise, for other os, please use ng.sh
  const isWindows = /^win/.test(process.platform);
  const commandFileExtension = isWindows ? 'cmd' : 'sh';
  let child = spawn(`ng.${commandFileExtension}`, ['build']);


text:
Q: API xStation xtb log in troubles Someone knows how to log in to xtb API ? http://developers.xstore.pro/documentation/
Python request:
import requests, json

parameters = {
    "command" : "login",
    "arguments" : {
        "userId" : "10576375",
        "password": "PASSWORD"
    }
}

response = requests.get("https://xapia.x-station.eu:5124", params=parameters)
data = response.json()
print(data)

Response :
ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))

Did I do something wrong ?

A: It requires an SSL connection. Try the following (works for me):
import socket
import ssl
import json

host = 'xapia.x-station.eu'
port = 5124
USERID = 123456
PASSWORD = 'YOURPASSWORD'

host = socket.getaddrinfo(host, port)[0][4][0]

s = socket.socket()
s.connect((host, port))
s = ssl.wrap_socket(s)

parameters = {
    "command" : "login",
    "arguments" : {
        "userId": USERID,
        "password": PASSWORD
    }
}
packet = json.dumps(parameters, indent=4)
s.send(packet.encode("UTF-8"))

END = b'\n\n'
response = s.recv(8192)
if END in response:
    print('Print login: {}'.format(response[:response.find(END)]))

parameters = {
    "command" : "logout"
}
packet = json.dumps(parameters, indent=4)
s.send(packet.encode("UTF-8"))

response = s.recv(8192)
if END in response:
    print('Print logout: {}'.format(response[:response.find(END)]))


text:
Q: Query issue (row values to columns) in PostgreSQL I've been looking around this, but I can not go forward and is stopping a project that I'm into.
My issue (I think) is very simple, but because I'm not familiar with postgresql I'm stuck in page 1.
I've this table:
"id";"date";"name";"seller";"order";"result"
"1";"2013-12-10 11:09:28.76";"adam";"mu";1;"5"
"1";"2013-12-10 11:09:28.76";"adam";"mu";2;"3"
"1";"2013-12-10 11:09:28.76";"adam";"mu";3;"1"
"2";"2013-12-10 11:10:26.059";"eve";"wa";1;"3"
"2";"2013-12-10 11:10:26.059";"eve";"wa";2;"9"
"2";"2013-12-10 11:10:26.059";"eve";"wa";3;"5"
"3";"2013-12-10 11:11:34.746";"joshua";"mu";1;"2"
"3";"2013-12-10 11:11:34.746";"joshua";"mu";2;"2"
"3";"2013-12-10 11:11:34.746";"joshua";"mu";3;"9"

Creation script:
CREATE TABLE myTable
(
  id character varying(50) NOT NULL,
  date timestamp without time zone NOT NULL,
  name character varying(64) NOT NULL,
  seller character varying(64) NOT NULL,
  order integer NOT NULL,
  result character varying(64)
)
WITH (OIDS=FALSE);
ALTER TABLE myTable OWNER TO postgres;

(Note: I can not modify the structure of that table)
And I want to get a result like this for use the copy function and write it to file:
"id";"date";"name";"seller";"result_1";"result_2";"result_3"
"1";"2013-12-10 11:09:28.76";"adam";"mu";"5";"3";"1"
"2";"2013-12-10 11:10:26.059";"eve";"wa";"3";"9";"5"
"3";"2013-12-10 11:11:34.746";"joshua";"mu";"2";"2";"9"

I've looked into the "crosstab" function, but I can not get that work within my environment and also I want to lose the column order in my output.
I'm not a query expert so I'm very over my head here :(
Any help will be appreciated. Thanks in advance!

A: CASE statements are the poor man's surrogate for a proper crosstab() function:
SELECT a.id
      ,max(CASE WHEN myorder = 1 THEN result END) AS result_1
      ,max(CASE WHEN myorder = 2 THEN result END) AS result_2
      ,max(CASE WHEN myorder = 3 THEN result END) AS result_3
FROM   mytab
GROUP  BY id
ORDER  BY id;

Only requires a single table scan and is therefore much faster than multiple joins.
BTW, never use reserved words like order as identifiers.
Details for this as well as a proper crosstab() query under this related question:
PostgreSQL Crosstab Query

A: This is not exactly what you want but it creates an array for results field for each id. Similar to group_concat in MySQL
 SELECT id, array_agg(result)
 FROM table
 GROUP BY id

A: If you can't use crosstab (tablefunc module isn't installled?)
How about something like this:
SELECT a.id,  b.myresult as one, c.myresult as two, d.myresult as three
FROM (SELECT id
      FROM mytab
      GROUP BY id) a
JOIN mytab b ON a.id = b.id AND b.myorder = 1
JOIN mytab c ON a.id = c.id AND c.myorder = 2
JOIN mytab d ON a.id = d.id AND d.myorder = 3

http://www.sqlfiddle.com/#!15/a3780/6


text:
Q: Does openvpn Access Server use RPC bind or other port mapping services ? We are running an access server which has a port mapping service running on 111. Does OpenVPN require port mapping services. We currently use two way connectivity (i.e) Machines on the server side subnet should be able to connect to the VPN users.

A: No, openvpn does not use rpcbind.


text:
Q: how do i make a nested dictionary in python? I'm trying to make an API that fetches memes from Reddit and I am stuck at creating JSON data with nested dictionaries. I have the following dictionaries and I want to merge them together. How do I go about it?
{
  "author": "Mizanur1214",
  "nsfw": false,
  "subreddit": "dankmemes",
  "title": "They do be like that",
  "upvotes": 33302,
  "url": "https://i.imgur.com/xZpJFQU.jpg"
}

and the other one as follows
{
  "author": "Kristis1",
  "nsfw": false,
  "subreddit": "me_irl",
  "title": "me irl",
  "upvotes": 1941,
  "url": "https://i.redd.it/u2qesppixhh61.jpg"
}

I want to make something like the following in python
{
{
  "author": "Mizanur1214",
  "nsfw": false,
  "subreddit": "dankmemes",
  "title": "They do be like that",
  "upvotes": 33302,
  "url": "https://i.imgur.com/xZpJFQU.jpg"
},
{
  "author": "Kristis1",
  "nsfw": false,
  "subreddit": "me_irl",
  "title": "me irl",
  "upvotes": 1941,
  "url": "https://i.redd.it/u2qesppixhh61.jpg"
}
}

A: As others pointed out the result is not a valid json or dict.
You need a key for the dict object:
a = {
  "author": "Mizanur1214",
  "nsfw": false,
  "subreddit": "dankmemes",
  "title": "They do be like that",
  "upvotes": 33302,
  "url": "https://i.imgur.com/xZpJFQU.jpg"
}

b = {
  "author": "Kristis1",
  "nsfw": false,
  "subreddit": "me_irl",
  "title": "me irl",
  "upvotes": 1941,
  "url": "https://i.redd.it/u2qesppixhh61.jpg"
}

res = {"items": [a, b]}

print(res)

Output:
{'items': [{'author': 'Mizanur1214', 'nsfw': None, 'subreddit': 'dankmemes', 'title': 'They do be like that', 'upvotes': 33302, 'url': 'https://i.imgur.com/xZpJFQU.jpg'}, {'author': 'Kristis1', 'nsfw': None, 'subreddit': 'me_irl', 'title': 'me irl', 'upvotes': 1941, 'url': 'https://i.redd.it/u2qesppixhh61.jpg'}]}


text:
Q: How do I Validate a Key in ARGV? I am so stuck. Been trying for days. I need to validate that each char input into argv[1] is a number but I have tried isdigit, isalpha, char, atoi conversion without any success. I'm still new at coding. I got frustrated and deleted everything to start over again but here's where I'm at now.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

int main(int argc, string argv[])
{
    if (argc == 2)
    {
        for (int k = 0; k <strlen(argv[1]); k++)
        {
            printf("Success!\n");
            printf("%s\n", argv[1]);
        }
    }
    else
    {
        printf("Usage: ./caesar key\n");
    }
}

Here is where I was at before. I kept getting a sanitization error everytime I tried to run this:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
include <ctype.h>
#include <stdlib.h>

int main(int argc, string argv[])
{
    if (isdigit(argv[1]))
    {
        if(atoi(argv[1]))
        {
            if (argc == 2)
            {
                for (int x = 0; x < strlen(argv[1]); x++)
                {
                    printf("Success!\n");
                    printf("%s", argv[1]);
                }
            }
        }
    }
    else
    {
        printf("Usage: /caesar key\n");
    }
}

Any help would be appreciated!

A: A quick and dirty example on onlinegdb:
Didn't test a lot...
#include <stdio.h>
#include <string.h>

int main(int argc, char * argv[])
{
    if (argc == 2)
    {
        int n = strlen(argv[1]);
        for (int k = 0; k < n; k++)
        {
            if ( isdigit(argv[1][k]) )
            {
                printf("%c is a digit\n", argv[1][k]);
            }
            else
            {
                printf("%c is not a digit\n", argv[1][k]);
            }
        }
    }
    else
    {
         printf("Error\n");
    }
}

Remember that argv[1] is a string, ie. an array of characters (with a null chracter at the end).
So you have to travel all the characters of this array.
EDIT: good comment from chmike in the other answer.

A: You had a good start with for (int x = 0; x < strlen(argv[1]); x++), unfortunately it is not appropriate for C.
In C a string is terminated by the special character '\0'. The function strlen counts the characters from the start of the string to this special character. So when you write for (int x = 0; x < strlen(argv[1]); x++) is executes strlen() at each test of x.
Here is one way to avoid this:
 for (int x = 0, n = strlen(argv[1]); x < n; x++)

This declares i initialized with 0, and n initialized with the length of argv[1]. The test compares x with n which is fast.
Another way to test if the end of the string is reached is to test if we reached that special character '\0'.
 for (int x = 0; argv[1][x] != '\0'; x++)

They are both equivalent. Make your pick.
Now, for each character you want to test if its a digit. You could use the function isdigit() that does the job for you. Or you could write the test yourself which is not that difficult.
for (int x = 0, n = strlen(argv[1]); x < n; x++)
    if (!isdigit(argv[1][x])) {
        printf("failure: argv[1] is not all digits\n");
        return;
    }
printf("success: argv[1] is all digits\n")

The alternative test implemented ourselves is this
for (int x = 0, n = strlen(argv[1]); x < n; x++)
    if (argv[1][x] < '0' || argv[1][x] > '9') {
        printf("failure: argv[1] is not all digits\n");
        return;
    }
printf("success: argv[1] is all digits\n")

Note that argv[1][x] contains the ASCII code of the character and that '0' is the ASCII code of 0. Note also that the ASCII code of digits is in the range '0' to '9' and this range contains only digits. This is why the test above test if argv[1][x] is not a digit.

A: You could use some helper functions to check whether a string consists of all digits.
/* Return pointer to first non-digit character in a string. */
const char *findnondigit(const char *input)
{
    while (*input >= '0' && *input <= '9')
    {
        input++;
    }
    return input;
}

/* Return 1 if string is all digits, or 0 if it contains a non-digit. */
int checkalldigits(const char *input)
{
    /* Find first non-digit character in input. */
    input = findnondigit(input);
    /* Return whether first non-digit character is the string's null terminator. */
    return *input == '\0';
}

For example:
int main(int argc, char *argv[])
{
    if (argc > 1)
    {
        if (checkalldigits(argv[1]))
        {
            printf("%s is all digits\n", argv[1]);
        }
    }
}


text:
Q: what does the word "off" exactly mean? There are two "off" in the below sentence, are they both adverb? does "off+of" mean "from"? I am trying to find its meaning in longman dictionary, but failed, which explanation can the word "OFF" match?
This is all plastic picked up off of beaches, every single bit of it," said Pozzi, "So we have processed about 18 tons of garbage off of a small area of beach in the last six years. And it could be anywhere in the world. This is a worldwide problem, the plastic pollution issue.
Remark:
This sentence comes from :http://www.51voa.com/VOA_Standard_English/animal-sculptures-national-zoo-plastic-ocean-pollution-70348.html

A: off (variant off of) is used in contexts where something is removed or taken from a place or a surface, or (figuratively) from an intangible place.

I can't get this gunk off of my new shirt.
Where did you get this picture of an eagle attacking a wolf?
  -- I got it off the internet.
Some news just came in off the wire.
They picked trash off of the beach.
She took the book off the shelf.

A: Yes. In both of those cases, off of does mean from. You can replace off of with from.
Adverbs describe how a verb is done, and almost always they end in -ly; think slowly, quickly etc. "Off of" is used as a preposition. This is a word that shows the relationship between a noun and a pronoun. This shows where I/you/he/she is in relation to the noun - think above, below, behind etc.