text:
Q: Create UIImageView with circle border iOS I am trying to create a border around my UIIMageView which is a perfect circle using cornerRadius.  Everything i've looked at says my code is correct, but it returns more of a diamond shape. (i've imported quartzCore, not sure I needed to)
image.layer.cornerRadius = (image.bounds.size.width/2);
image.layer.borderWidth = 5;
image.layer.borderColor = [UIColor whiteColor].CGColor;

Any ideas?

A: image.layer.cornerRadius = image.frame.size.width /2;
image.layer.masksToBounds = YES;
image.layer.borderWidth = 5;
image.layer.borderColor = [UIColor whiteColor].CGColor;

The height and width of your imageview must be equal

A: Have you tried to add:
image.layer.masksToBounds = YES;

Another thing: is the width of your image equal to its height?

A: More simple no codign go on your Storyboard select your UIImageView and check under Identity Inspector to the colum right then ad under User Defined Runtime Attribute a Number and Key Path: layer.cornerRaius Neber 150 or what ever, then use your code to implementing, look a screen:

now your code and:

If you want use your code you cane use the same think:
//your code:

image.layer.cornerRadius = (image.bounds.size.width/2);
image.layer.borderWidth = 5;
image.layer.borderColor = [UIColor whiteColor].CGColor;

//improve with:

    CGFloat radius = 150.0f;
    self.image.layer.cornerRadius = radius;

you can add a function for universal app like to this example:
- (void)viewDidLoad {
    [super viewDidLoad];

    self.image.layer.masksToBounds = YES;
    self.image.layer.borderWidth = 5;
    self.image.layer.borderColor = [UIColor whiteColor].CGColor;

    if (isIpnoe4 || isIphone5) {

    CGFloat radius = 150.0f;

    } else if (isIphone6) {

        CGFloat radius = 200.0f;

    } else if (isIphone6Plus) {

        CGFloat radius = 250.0f;

    } else {

        //here is ipad/ipadmini

        CGFloat radius = 250.0f;
    }
    self.image.layer.cornerRadius = radius;
}

you can define the different display or in a Prefix.pch or in a header with this method:
#define   IsIphone6Plus     ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )1104 ) < DBL_EPSILON )
#define   IsIphone6     ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )667 ) < DBL_EPSILON )
#define   IsIphone5     ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )
#define   IsIphone4     ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )480 ) < DBL_EPSILON )

Hope this help you

A: Step (1)
As others have said, you need to make sure your width and height are the exact same value.  If you are absolutely sure this is the case, then go to Step 2.
Step (2)
Even when you think you are absolutely sure of Step 1, this is not usually the case.  I say this from my own personal experience trying to do the same thing before.  You would  be surprised some of the crazy thing AutoLayout does to your dimensions at runtime.  Even when you think your values are correct, they changed slightly.  Let me guess, are you using Storyboard to create your ImageView?  If your answer is yes, go to Step 3.
Step (3)
In order to verify this issue is caused by AutoLayout doing something funny, create a test UIImageView all in code without using any Stroyboards at all, by doing this (I'm not on my Mac right now, so syntax may be a little off):
var imageView: UIImageView = UIImageView(frame: CGRect(x: 0.0, y: 0.0, width: 100.0 height: 100.0))
imageView.layer.cornerRadius = (imageView.bounds.size.width/2)
imageView.layer.borderWidth = 5.0
imageView.layer.borderColor = UIColor.redColor()
imageView.backgroundColor = UIColor.yellowColor()
self.view.addSubview(imageView)

If you run this and it shows up as a proper circle.  Then this was the cause of your problem.  I've learned to create all my objects in strictly code now, I don't even use Storyboards anymore due to all the issues I have had in the past.


text:
Q: Create a 960px style with two solid bars that are 100% of page width? I am trying to create a wordpress style for a project site I am working on. I am an experience designer, but there is a concept that I can't figure out. I'd like to be able to have the width of the site set at 960px, but have two bars at the top. You can see what I mean in the picture below.
http://i.stack.imgur.com/pSShB.png
I really want to be able to use the blue bar as a menu system and keep all the content within the main 960px overall width. The logo image, needs to start at the very beginning of the content beginning(where the 960px starts). The image is just a mock up, but that's how I want my users to be able to see it. I want the whole site to be able to scale to look the same on any sized monitor.
I have been trying to come up with a solution to do this effectively all day, but haven't managed to think of anything.
Does anyone have an ideas for me? Something that'll work in all browsers?

A: You would have to create a relative container, and inside of in absolute containers, something like this:

{logo goes here float it right or something}

{menu structure goes here, float left or something}

Your Style:
#header_struct{
 position: relative;
 width: 960px;
}
#green_area{
 position: absolute;
 right: 700px; // makes it start 260px in from the left side
 width: 1000px; // makes it go off the left side of the screen for instance
 background-color: green;
}
#blue_area {
 position: absolute;
 left: 260px; // makes it start 260px in from the left side
 width: 1000px; // makes it go off the left side of the screen for instance
 background-color: blue;
}

Basically you need nested abosolute positioning divs inside the relative container #header_struct. I haven't tested this, but I recall doing something similar. I hope that gets you started.
Here is a cleaned up JSFIDDLE of it working:
http://jsfiddle.net/37Fmh/

A: something like this should get you started.
http://jsfiddle.net/pxfunc/DxW47/1/
css:
body {background:#eee url('http://files.me.com/pwb3/lo1t09') repeat 0 0;margin:0;padding:0;}

#greenBg {background:#00cb00;height:50px;width:50%;top:40px;right:50%;position:absolute;}
#blueBg {background:#00b8de;height:50px;width:50%;top:40px;left:50%;position:absolute;}

.clear {clear:both;}

#container {width:960px;margin:40px auto 0 auto;position:relative;}
#header {background-color:#00cb00;width:220px;float:left;padding:15px;}
#nav {background-color:#00b8de;width:678px;border-left:solid 2px #fff;float:left;padding:15px;}

#content {margin-top:10px;border:solid 1px #ddd;background-color:#fff;padding:15px;height:400px;}

html:

        site logo

nav

content

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dificuldade ao escrever um REGEX para validar URL Estou com dificuldade para criar uma expressão regular que valida a seguinte URL:
https://firebasestorage.googleapis.com/v0/b/nome-app/*
*seria qualquer coisa!
Alguém poderia me dar um surpote relacionado?

A: Está aqui como podes fazer :)
if (a_tua_variavel.indexOf('https://firebasestorage.googleapis.com/v0/b/nome-app/') > -1){
   alert("Tem parte do link");
}


text:
Q: jQuery .click function not working on  tag? So I am creating a table using Javascript and jQuery, and I want it so that when you click the td's on the first row of the table, then the rest of the td's in that column drop down. Let me try to explain it by showing my code. Here is my Javascript:
function createTr (heights) { //heights is just an array of words
    for (var h=0; h<heights.length; h++) {
        var theTr = $("
", { id: "rowNumber" + h});
        for (var i=0; i<heights.length-3; i++) {
            theTr.append($("", { "class": "row"+h + " column"+i,
                                     html: heights[h][i]
                                   }));
        }
        $('#newTable').append(theTr); // append
 to the table (#newTable), which is written in the html
    }
}

This basically creates td's and each td is similar to this format

I want it so that all td's are hidden except for the td's in .row0 and if you click the td in .row0 .columni, then all td's in .columni appear. The parameter 'heights' is jsut an array, for example, it can be
var heights = [['headerOne', 'headerTwo'], ['someTd', 'anotherTd'],];

and it would create a table using those words, headerOne and headerTwo would be in the first row, someTd and anotherTd would be in the second row.
Now, when I try to add a click function like so
function animation() {
    $('td').click( function() {
        alert('clicked');
    });
}

and then call it in my document.ready function like so
$(document).ready( function() {

    createTr(heights);
    animation();
});

it doesn't do anything when I click a td. How come?

A: Try like this :
$('body').on('click','td', function() {
        alert('clicked');
    });

A: http://api.jquery.com/on/
Since you are creating the elements after the DOM has been created. Use the "on" selector to get the precise element that is dynamically created.
From the URL:
   $("#newTable").on("click", "td", function() {
     alert($( this ).text());
   });

A: try this
function animation() {
    $(document).on('click','td',function() {
    alert('clicked');
    });
}

A: I like this.-
 $("#table tr").click(function(){
    console.log(this);
});

A: This code works just fine:
$(document).ready(function(){
    $("td").click(function(){
        if(this.title!=""){
            alert(this.title);
        }
    });
});

A: use this to catchs click events for spesifc tr and td;
$('#table_id').on('click', 'tr.statusP td:first-child', function () {
                    alert('clicked');
                });


text:
Q: How to create multiple database connections for different databases in java I have an application which uses four databases in different geographical locations. All the databases contains same tables and only the database name is different according to the location.
I have to create some reports in my application which uses data from each database. What would be the proper way to create those database connection from a java application and is there a suitable design pattern for this task which I could use?

A: As you have not tagged your question with any of this, hibernate, JPA, ORM, I assume you are dealing with plain JDBC.
Having said that, I suggest you to have a DAO layer to deal with underlying databases, and leave the connection details to specific implementations. You can configure your connection strings in some .properties files, lets say.
[Complement]
You can also make use of DAO factory, an implementation of Abstract Factory or Factory Method pattern, whichever suits here.
[Links]

*

*A very fine implementation of DAO and DAO Factory, by BalusC

*Core J2EE Patterns -- arguably dated but might provide some idea.

A: There are multiple ways you can achieve this:

*

*If you are using any Java EE container which supports distributed transaction then you can use there functionality.

*If you are with plain JDBC then you will have to maintain your own connection for every database.
For JDBC:

*

*Provide all connection details

*Have an Facade which gives you desired object by calling a abstract generic DAO.

*Have a factory which creates dao based on connection.

*Use ORM tools like Hibernate, where you can use configuration for multiple database. Tutorial.

*If you are using Spring, then you can configure one datasource per database. Docs
Design Patterns:

*

*Facade Pattern - for hiding the complexity and multiple database usage.

*Factory - In case you manage the database connection yourself.

*Singleton - For datasources

A: You can handle multiple connections easily using a ORM tool like Hibernate.. You can specify each connection in a separate configuration file and instantiate the required connection by getting a new session factory each time.
Other way would be to use datasource and JNDI : Java connecting to multiple databases
I think you can use a combination of Factory pattern and Singleton pattern for the purpose.

A: The Ideal way to achieve this is by using a multi-dimensional system like OLAP. But see if you can create a view out of those databases. Then you just need to query the view (i.e. just a single database connection). Also you can still use multiple database connections if you want.

A: is very easy :)
1.Create a Data Source to try connection to DB
public DataSource getDataSource(String db) throws Exception {
DataSource dt = null;
InitialContext ic = null;
try {
    if(db.trim().equals("you_database_name")) {
        dt = (DataSource)ic.lookup("jdbc/connection_name");
    } else if(db.trim().equals("you_database_name")) {
        dt = (DataSource) ic.lookup("jdbc/connection_name");
    }
    return dt;
} catch(NamingException n) {
    throw new Exception("Err getDataSource (ServiceLocator) NamingException - " + n.getMessage());
}

2.Create a class DataBase, remember close all connection in this point.
public class DataBases {
public YouNameDataSourceClass dataSrc;
public DataBases() throws Exception {
   super();
   dataSrc = new YouNameDataSourceClass.getDataSource();
}
public Connection getConnectionAS400() throws Exception {
    return locator.getDataSource("you_database_name").getConnection();
}

public Connection getConnectionOracle() throws Exception {
    return locator.getDataSource("you_database_name").getConnection();
}

public Connection getConnectionSQLServer() throws Exception {
    return locator.getDataSource("you_database_name").getConnection();
}
}

Good look.

A: Assuming you are using Spring MVC with Hibernate with XML configurations, follow these steps:

*

*Create beans of all the databases in your spring-servlet file.
<bean id="dataSource1" Class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
        <property name="url" value="jdbc:sqlserver://localhost:1433;databaseName=database1"/>
        <property name="username" value="abc" />
        <property name="password" value="abc@123" />
    </bean>

*Create sessionFactory beans of all the databases you want in the Spring-servlet file.
<bean id="datasource1SessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource"
          ref="database1"/>
        <property name="packagesToScan"
          value="com.id4.iprod.entity"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">
                </prop>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.SQLServer2012Dialect
                </prop>
            </props>
        </property>
    </bean>

*Now you just need to open session of the database you want to in DAO and access the desired results from desired database.
Session datasource1= this.datasource1SessionFactory.openSession();


text:
Q: Handling HTTP 303 redirects in zf2 I am building a small CMS system in zend framework 2. My new website will have a new url structure and I would like to create 303 error handler.
The ideal solution:
The user or search engine will visit the website via old url if page was not found it will check the list of old url stored in (db or array) if url found it will create 303 redirect. If the url was not found in the list it should create 404 page.
Example of urls:
the old (none exiting) url: www.example.com/category/product123.html this should be redirected to the new url: www.example.com/category/product-name/
In total i will have over 100 old pages that need to be redirected to the new url.
How should i do this properly?

A: HTTP 303 is a custom redirect header, not an error and should be used after a HTTP POST. If preserving some legacy url's is what you want (for SEO purposes etc..) you may consider using HTTP 301 - Moved Permanently header.
There are several ways exists to redirect any HTTP request to any other resource in both Http Server and application level. I would prefer nginx/apache level. Example for nginx:
server {

  # ...

  location ~ "^/category/([a-zA-Z0-9]+).html" {
      # Example: http://www.example.com/category/product123.html
      # The $1 will be product123
      return 303 http://www.example.com/category/$1;
  }

  # ...

}

Now, calling the old /category/product123.html url after reloading your http server's configuration will produce a response similar to this :
HTTP/1.1 303 See Other
Server: nginx/1.X.0
Date: Tue, 07 Oct 2014 20:47:29 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 168
Connection: keep-alive
Location: http://www.example.com/category/prodct123

In application level, you can easily redirect requests inside any controller action returning by a valid Response object:
public function anyControllerAction()
{
    $response = $this->getResponse();
    $response->getHeaders()->addHeaderLine('Location', 'http://www.example.com/category/prodct123');
    $response->setStatusCode(303);
    return $response;
}

Hope it helps.


text:
Q: Android Open Context Menu Whenever i select any Text anywhere across the device I am trying to work on one idea. whenever user selects any text anywhere in any application' on android device i want to show one option to user just like we get an option for copy.
Is it possible to change android's default behavior like this. When user selects any text i want to show one option just like "copy" and when user selects that option i want to perform some operation on that selected text.
Any idea how can i achieve this ?

A:
Is it possible to change android's default behavior like this

Not from Android 1.0 through 5.1.
The M Developer Preview offers a means of doing this. Activities supporting the PROCESS_TEXT action will show up in the floating action mode that appears when users select text:

However, as this is not well-documented, it remains to be seen if this will make it into the final edition of Android M.


text:
Q: Mongo Collection `Size` is *larger* than `storageSize`? I recently compacted my collection using the command:
 db.<collectionName>.runCommand( "compact" )

And now my collection size seems to be bigger than size on disk!
SECONDARY> db.<collectionName>.stats()
{
"ns" : "<databaseName>.<collectionName>",
"count" : 2937359,
"size" : 5681676492,                   # 5.6 GB
"avgObjSize" : 1934.2805874256433,
"storageSize" : 4292853728,            # 4.2 GB
"numExtents" : 2,
"nindexes" : 2,
"lastExtentSize" : 2146426864,
"paddingFactor" : 1.669999999836597,
"flags" : 1,
"totalIndexSize" : 220735648,
"indexSizes" : {
    "_id_" : 162326304,
    "e_1_" : 58409344
},
"ok" : 1

}
I don't understand how this is possible. Aren't all mongodb collections backed-by-disk at all times?
Can anyone explain these results?

A: storageSize is the sum of all extents for that data, excluding indexes.
So that collection takes up 2 extents, they are ~2GB each, hence ~4GB. size includes indexes and I believe a couple of other things which inflate the number. Neither really represents the proper on-disk size. For disk size, db.stats() has a filesize field which is closer to what you want I think you're looking for.
The manual is somewhat better at outlining what the various fields mean, see here for collections:
http://docs.mongodb.org/manual/reference/collection-statistics/
And here for database stats:
http://docs.mongodb.org/manual/reference/database-statistics/

Some other potentially relevant information:
The compact command does not shrink any datafiles; it only defragments deleted space so that larger objects might reuse it. The compact command will never delete or shrink database files, and in general requires extra space to do its work, usually a minimum of one extra extent.
If you repair the database it will essentially rewrite the data files from scratch, which will remove padding and store them on disk as efficiently as you are going to get.  However you will need to have ~2x the size on disk to do so (actually less, but it's a decent guide).
One other thing to bear in mind here - repair and compact remove padding.  The padding factor varies between 1 (no moves of documents caused by documents growing), to 2 (lots of moves caused by documents growing).  Your padding factor of ~1.67 would indicate you are growing (and hence causing moves) quite a bit.
When you compact or repair a database you remove that padding - subsequent document growth is therefore going to trigger even more moves than before.  Because moves are relatiely expensive operations, this can have a serious impact on your performance.  More info here:
http://www.mongodb.org/display/DOCS/Padding+Factor

A: For mongodb > 3.x
For MMAPv1:
datasize < storageSize

but For wiredTiger
datasize > storageSize (most cases due to compression but may be
                        storageSize greater, it varies on condition like
                        compression technique, whether compact/repair
                        command run or not)

For db.getCollection('name').stats()
size = total size in memory of all records in a collection + padding (excluded index size + record header which is 16 byte per header, header means  = field name)
avgObjSize = avg size of obj + padding
storageSize =  total amount of storage allocated to this collection for document storage. (totalIndex size excluded)
totalIndexSize : totalIndexSize (compressed in case of wiredTiger)

For db.stats()
dataSize = document + padding
storageSize = document + padding + deleted space
fileSize = document + padding extents +  index extents + yet-unused space

We can delete unused space or hole by this
db.getCollection('name').runCommand( "compact" )

After running compact or repair command we can get exact storage size and data size difference.
Compression Technique in mongodb wiredTiger:
- snappy : good compression, low overhead
- zlib: better compression, more CPU
- none (we can disable compression, by default its enable in WT)


text:
Q: Difference between array_walk() and array_walk_recursive() in php? What is the difference between array_walk() and array_walk_recursive() in php? Please provide with examples.

A: We can use array_walk_recursive() for multi-dimensional    array.
array_walk() // Its useful for one-dimensional array.

array_walk_recursive() // Calling array_walk() function in recursively (i.e., function call inside the same function).

A: More then enough explanation and examples
http://php.net/manual/en/function.array-walk.php
http://php.net/manual/en/function.array-walk-recursive.php


text:
Q: ejabberd http-bind prevents running parallel sessions with different resources I have a running ejabberd installation, with http-bind enabled, nginx proxy, and a mini jappix xmpp client for web browsers. I also have an external authentication program.
I can connect the same user on this server with different ressources if I use the classical 5222 port. But:

*

*If I have active sessions from classical xmpp clients (psi, empathy) for a given user I cannot connect this user with http-bind (401 authentication failure).

*I the first connection is made via http-bind no other connection can be done by other classical xmpp clients (and resources are of course different). I sometimes get the 401 already connected message

*I can only connect the same user in one browser, I cannot connect the same user several time on http-bind (resources are different on theses connections, but I also get a 401)

*I'm sure the external authentification program is never launched when I get theses auth failure

*max_user_sessions settings are ok (tested with infinity), and if I'm not connecting in http-bind I can run parallel sessions. But in case of I also tested the new resource_conflict setting values without any success (and it's not a re'source conflict in fact)

Installation: ejabberd-2.1.10 Debian (from ejabberd-2.1.10-linux-x86-installer.bin, but same problem tested in x86_64 version).
Extract of configuration:
    {5280, ejabberd_http, [
                     {request_handlers,
                      [
                       {["http_bind"], mod_http_bind}
                      ]},
                     %%captcha,
                     http_bind,
                     %%http_poll,
                     web_admin
                    ]}

On the logs, when this is happening I have:
=INFO REPORT==== 2012-01-27 10:18:55 ===
D(<0.335.0>:ejabberd_http_bind:684) : reqlist: [{hbr,154037,
                             "01775ec6fc089a2b0c84abb80a4b5b7b4bdd958d",
                             []},
                             {hbr,154036,
                             "01775ec6fc089a2b0c84abb80a4b5b7b4bdd958d",
                             [{xmlstreamelement,
                                   {xmlelement,
                                   "stream:features",[],
                                      [{xmlelement,
                                          "mechanisms",
                                          [{"xmlns",
                                            "urn:ietf:params:xml:ns:xmpp-sasl"}],
                                          [{xmlelement,
                                            "mechanism",[],
                                            [{xmlcdata,
                                              "PLAIN"}]}]}]}},
                                      {xmlstreamstart,
                                       "stream:stream",
                                       [{"version","1.0"},
                                        {"xml:lang","fr"},
                                        {"xmlns","jabber:client"},
                                        {"xmlns:stream",
                                         "http://etherx.jabber.org/streams"},
                                        {"id","3595609800"},
                                        {"from",
                                         "tchat.example.com"}]}]}]

=INFO REPORT==== 2012-01-27 10:18:55 ===
D(<0.335.0>:ejabberd_http_bind:732) : really sending now: [{xmlelement,
                                        "auth",
                                        [{"xmlns",
                                        "urn:ietf:params:xml:ns:xmpp-sasl"},
                                         {"mechanism",
                                          "PLAIN"}],
                                         [{xmlcdata<<"bGRhcHVzZX(...)3">>}]}]
=INFO REPORT==== 2012-01-27 10:18:55 ===
I(<0.336.0>:ejabberd_c2s:649) : ({socket_state,ejabberd_http_bind,{http_bind,<0.335.0>,{{127,0,0,1},50992}},ejabberd_http_bind}) Failed authentication for foo38@tchat.example.com

=INFO REPORT==== 2012-01-27 10:18:55 ===
D(<0.337.0>:ejabberd_http_bind:916) : OutPacket: [{xmlstreamelement,
                                       {xmlelement,"failure",
                                        [{"xmlns",
                                          "urn:ietf:params:xml:ns:xmpp-sasl"}],
                                        [{xmlelement,
                                          "not-authorized",[],
                                          []}]}}]

=INFO REPORT==== 2012-01-27 10:18:55 ===
D(<0.337.0>:ejabberd_http_bind:1054) :  --- outgoing data ---
<body xmlns='http://jabber.org/protocol/httpbind'><failure xmlns='urn:ietf:params:xml:ns:xmpp-sasl'><not-authorized/></failure></body>

So is this a "feature" in http-bind ? making it the only valid Resource for a given user while activated? And how to run several http-binded sessions for the same user if so? Any hints?

A: No there must be something wrong with your configuration. I have been successfully using ejabberd's http-bind for a long time and of course you can have multiple connections with different resources and independently of other clients connecting. I also use nginx as a proxy. In you ejabberd.cfg you should have:
  {5280, ejabberd_http, [
   http_bind,
   web_admin
  ]}

and
{modules,[
      {mod_http_bind,[]},
      ...
]}.

Also, in your logs I see {"from", "tchat.example.com"}, which seems to indicate a missconfiguration.


text:
Q: Load progress bar during loop in JavaScript I have a loop that processes data for a while, so I'd like to show a progress bar while the loop is processing. I've tried updating the progress bar within each loop iteration:

let data = new Array(1000000); //large input data

let progress_bar = document.getElementById('progress_bar');
let progress_text = document.getElementById('progress_text');
let progress = 0;
let full = data.length;

for (let row of data) {
    progress_bar.style.width = (100 * progress / full) + '%';
    progress_text.innerHTML = Math.round(100 * progress / full) + '%';

    processData(row);

    progress += 1;
}

function processData(input) {
    //process the line of data
}
#progress_track {
    height: 5px;
    width: 80vw;
    margin-left: 10vw;
    background: #888;
}
#progress_bar {
    background: #54f;
    height: 5px;
    width: 0;
}
#progress_text {
    font-size: 18px;
    width: 100vw;
    text-align: center;
}
<!DOCTYPE html>

0%

As you can see, it updates all at once at the end.
Here it explains that JavaScript only updates the UI at the end of something so rapid, so I tried replacing
    progress_bar.style.width = (100 * progress / full) + '%';
    progress_text.innerHTML = Math.round(100 * progress / full) + '%';

with
    if ((progress % 1000000) == 0) {
        progress_bar.style.width = (100 * progress / full) + '%';
        progress_text.innerHTML = Math.round(100 * progress / full) + '%';
    }

but that yields the same result.
I also tried using setTimeouts and setIntervals, but my understanding of callbacks isn't that great, so I ended up accidentally accessing the data before it was processed.

A: Long running loops in JS freezes the UI refresh, to show the progress of data, you may need to move the data processing logic to web worker. You can read about web worker on the following link.
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers


text:
Q: How to get Office 365 calendar event by time and location using Graph API? When I create a new event for a location, I need to check whether that location is busy and if it is, I need to send an email to existing event's creator that their event is going to be double booked.
First, I use calendar/getSchedule API call to get a schedule for the location(room) for given timeframe. That returns me the array of busy times for that room, but doesn't give me any extra information about the actual events or event creators.
Knowing the tie frame and location of an event (e.g. 2-3pm at War Room) how to I retrieve that particular event using Graph API (either REST or .NET SDK)?

A: user:calendar:calendarView endpoint returns all the events for the user and given timeframe


text:
Q: How to install acrobat reader 11 in ubuntu 12.04.1 using wine (32 bit system) I am using ubuntu 12.04.1 (32 bit). I would like to install acrobat reader 11 (32 bit)  using wine. I am unable to install it in my system, since it shows the message "set up is interrupted".
Please help.

A: You can install it directly with out wine.Open your terminal and paste these lines.
sudo add-apt-repository "deb http://archive.canonical.com/ precise partner"
sudo apt-get update
sudo apt-get install acroread

Credit Goes to Noobs lab adobe acrobat treader


text:
Q: Where do I find event declarations in Visual Studio I know that VS will open an eventhandler stub by doubleclicking on an event.
I found the underlying event declaration in InitializeComponent of the form on which the button is located.
this.buttonWorkOn.Click += new System.EventHandler(this.buttonWorkOn_Click);

Can I use this event declaration (of Visual Studio) and register another eventhandling method with it?
Upon instantiation of that other form its eventhandling method would need to register itself with the click event of the button on the main form.
I have no clue how to do that even though I have read quite a bit about delegates and events and in principle I do understand how it works.
Thank you

A: If you right click on an event handler in the code editor and browse the definition you will find the way that it is declared, which you can then use in your own code.
For example, the declaration for a Button's Click event is:
    public event EventHandler Click;

You can add these yourself and use them from other places to respond to events in any class you create.
Here's a sample form with a single button (added via the designer) that when clicked will raise its own event:
public partial class Form1 : Form
{
    public event EventHandler ButtonClicked;

    private void RaiseButtonClicked()
    {
        if (ButtonClicked != null)
            ButtonClicked(this, EventArgs.Empty);
    }

    public Form1()
    {
        InitializeComponent();
    }

    private void Button1_Click(object sender, EventArgs e)
    {
        RaiseButtonClicked();
    }
}

In another class you can then add a handler to that:
public class Responder
{
    public Responder(Form1 form)
    {
        form.ButtonClicked += OnButtonClicked;
    }

    private void OnButtonClicked(object sender, EventArgs args)
    {
        MessageBox.Show("Button was clicked");
    }
}

Now every instance of the Responder class will tell you when the button is clicked on the form.

A: By "Double clicking on an event", visual studio will generate an event handler for you. What you don't see is that visual studio also subscribes the generated event handler to the event, by adding a line of code in your designer file.
If goes something like this:

*

*Double click 'clicked' event

*Visual studio opens up your code file, and you have a new button1_clicked method, which is your event handler.

*Your designer is updated with a line like button1.Clicked += button1_clicked
If you want to do manual event subscriptions, you can do so from your code file, by adding something like <formelement>.<event> += <eventhandler>. If you cant see available events in your intellisense, you can always check the online documentation. MSDN
(You should never change your designer file, as this is a generated file)

A: If you like to get multiple methods been executed when an event occurs you can simply add all of them in your code (or you can even add the same method multiple times):
private void DoSomething(object source, EventArgs eventArgs)
{
    Console.WriteLine("Something happened.");
}

private void DoSomethingElse(object source, EventArgs eventArgs)
{
    Console.WriteLine("Something else happened.");
}

private void AttachToEvent()
{
    button1.Clicked += DoSomething;
    button1.Clicked += DoSomethingElse;
    button1.Clicked += DoSomething;
}

This would print out:

Something happened.
Something else happened.
Something happened.

A: OK – it was not my application, I just tried to improve on it.
Anyway, the question was who owns whom and who is visible where.
On the Mainform are controls for user input.
On MainForm a variable of type "class preview" is declared:
Preview pv

For the Preview class I added an event declaration named WorkOn:
   public class Preview
    {
        #region "Variables"
        #region "PublicEvent"

        public event EventHandler WorkOn;
    }

Then in the MainForm, the variable pv – declared as a class field - is instantiated within a method.
pv = new Preview()

after which the user input in the controls of the main form is checked and when ok saved in the variables of the preview class.
Then, the PreviewForm is instantiated within the preview class, with the instance of the owning class (preview -->  as instance pv) passed as a variable to the instantiation of the PreviewForm.
I had to create this overloaded constructor because from the PreviewForm an eventhandler must be registered with the preview class to make this work – as I realized.
formPreview formPreview = new formPreview(this);

// this --> is the class preview, the instance pv
// Instantiation of FormPreview
  public formPreview(Preview preview)
    {
      InitializeComponent();

      this.preview = preview;
// now for the event in the preview class an eventhandling method
// of the preview form is registered:
      preview.WorkOn += formPreview_Close;
    }

This is the registered method of FormPreview:
   private void formPreview_Close(object sender, EventArgs e)
    {
        this.Close();
    }

I was reminded again that events can only be raised from the class that publishes the event. So I had to create a public event raising method within the class preview – here named OnWorkOn:
  public void OnWorkOn()
    {
        if (WorkOn != null)
            WorkOn(this, EventArgs.Empty);
    }

And finally I could trigger the event from the MainForm within the button to whose underlying event I planned to register the eventhandling method of the PreviewForm in the first place.
Only now I had to use the class variable pv of the MainForm as it is the medium between the MainForm and the PreviewForm:
public void buttonWorkOn_Click(object sender, EventArgs e)
{
    pv.OnWorkOn();
// raising the event, informing whoever is registered to it
//...
}

So the design of the application did not allow for registering any eventhandling method of the preview form directly on the MainForm. That was the problem and I didn't quite see through the whole design yet.
Well – this is the outcome of a german C# tutorial – the only german one I know of.
You'll find it here:
[https://www.youtube.com/watch?v=-zCiwcgxMHw&list=PLvvL1HRuCBItyw45XnCqEXzuegKQd3MfL][1]
The code is not available for download anymore, but I could provide it as I am through.


text:
Q: Laplace's method, error bound reference Could anyone give a reference for the error bound in Laplace's approximation? Namely, reference for the proof of the following statement:
Let $f>0$ and $\phi$ be smooth functions on $[a,b]$ and $\phi$ achieves a unique maximum at $c \in (a,b)$ then
$$\int_a^b f(t) e^{x \phi(t)} \text{d} t = \sqrt{\frac{2\pi}{x |\phi''(c)|}} f(c) e^{x\phi(c)}\left(1 + O\left(\frac{1}{x}\right) \right) \qquad \text{as} \ x \rightarrow +\infty$$
P.S. wiki page has proof that the relative error goes to $0$ but it is not very readable for me.


text:
Q: Can I avoid deserializing JSON Jackson http response body twice if I want to set READ_UNKNOWN_ENUM_VALUES_AS_NULL?
I am deserializing a JSON http response and reading it into a Java object.

My first solution was:
javax.ws.rs.core.Response response = ...
MyClass obj = response.readEntity(MyClass.class);

I want to read unknown enum values of enum members in MyClass as null and not throw an exception, so I modified the above to:
String str = response.readEntity(String.class);
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
MyClass obj = mapper.readValue(string, Class<MyClass>);

Does anyone know how I could avoid the double deserialization here i.e. instead of Response -> String -> Class, just do Response -> Class?

A: So the solution to this is to register an ObjectMapperContextResolver with the client
private final ObjectMapperContextResolver OBJECT_MAPPER_CONTEXT_RESOLVER = new ObjectMapperContextResolver();

javax.ws.rs.client.Client client = ...
javax.ws.rs.client.WebTarget target = client.target("...");
client.register(OBJECT_MAPPER_CONTEXT_RESOLVER).target("...");

javax.ws.rs.core.Response response = target.path("...").request(MediaType.APPLICATION_JSON).get();
MyClass obj = response.readEntity(MyClass.class);


text:
Q: How to display table data at admin side in Drupal? I have created custom table and entries in that table are done from frontend side using webform.
That whole process working fine also mail is sent to admin,BUT I need to display that table information to admin in separate page like in grid view or table listing
So Is there any way to do make a page and only admin can see that?

A: It looks like you should be able to use Views and the Webform MySQL Views to achieve this. Basically, Views is a great module used to build and display data in Drupal (usually content). Webform data is not normally accessible in Views, but Webform MySQL Views fixes that.


text:
Q: How do i add names in /tellraw I'm working on a server and when a player joins i want it to say their name. I'm pretty good with commands so you don't have to give me a full command. just in case here is command:
/tellraw @p[count=1,y=~1,x=~,z=~,rm=1,r=2] ["",{"text":"[","color":"dark_blue"},{"text":"~","color":"blue"},{"text":"] ","color":"dark_blue"},{"text":"Welcome ","color":"green"},{"text":"[PlayerNameHere]","color":"red"},{"text":", To [Undecided]!","color":"aqua"},{"text":"\n"},{"text":"[","color":"dark_blue"},{"text":"~","color":"blue"},{"text":"] ","color":"dark_blue"},{"text":"[PlayerNameHere] ","color":"red"},{"text":"You must be new! ","color":"aqua"},{"text":"*Click Here*","color":"aqua","clickEvent":{"action":"run_command","value":"/tellraw @a {\"text\":\"Signed In As: {PlayerNameHere} Password:[Random], Do not forget\"}"}},{"text":" To sign Up!","color":"aqua"}]

A: You should use the selector component. For example:
/tellraw @a [{"text":"Welcome, "},{"selector":"@p"}]

Replace @p with the selector you want to use.


text:
Q: Terraform Error on AzureRM VM with 3rd Party Marketplace Image Citrix Netscaler Receiving an error when creating a AzureRM VM with a Marketplace Image and Managed Disk, I am missing something syntax ally, maybe a plan block {} how would one find information to put in Plan block ? - Does anyone have a working example of a managed disk based AzureRM VM using a 3rd Party Marketplace image from Azure in Terraform ?
Error applying plan:

1 error(s) occurred:

* azurerm_virtual_machine.VMns-vpx-1: 1 error(s) occurred:

* azurerm_virtual_machine.VMns-vpx-1: compute.VirtualMachinesClient#CreateOrUpdate: Failure sending request: StatusCode=200 -- Original Error: Long running operation terminated with status 'Failed': Code="VMMarketplaceInvalidInput" Message="Creating a virtual machine fro
m Marketplace image requires Plan information in the request. OS disk name is 'myosdisk1'."

Terraform does not automatically rollback in the face of errors.
Instead, your Terraform state file has been partially updated with
any resources that successfully completed. Please address the error
above and apply again to incrementally change your infrastructure.
PS C:\Users\eagle\Downloads\citrix\testingvpx>

In Addition Azure portal shows an error around the OS Disk:
General
Provisioning state Provisioning failed. Creating a virtual machine from Marketplace image requires Plan information in the request. OS disk name is 'myosdisk1'.. VMMarketplaceInvalidInput
Guest agent Unknown

Disks
myosdisk1 Provisioning failed. Creating a virtual machine from Marketplace image requires Plan information in the request. OS disk name is 'myosdisk1'.. VMMarketplaceInvalidInput

Terraform script being used:
resource "azurerm_virtual_machine" "VMns-vpx-1" {
  name                  = "VMns-vpx-1"
  location              = "${var.azu_location}"
  resource_group_name   = "${azurerm_resource_group.rgVMns-vpx.name}"
  network_interface_ids = ["${azurerm_network_interface.VMns-vpx-1-nic.id}"]
  vm_size               = "Standard_DS3_v2"

  storage_image_reference {
    publisher = "citrix"
    offer     = "netscalervpx120"
    sku       = "netscalerbyol"
    version   = "latest"
  }

  storage_os_disk {
    name              = "myosdisk1"
    caching           = "ReadWrite"
    create_option     = "FromImage"
    managed_disk_type = "Premium_LRS"
  }

  os_profile {
    computer_name  = ""
    admin_username = ""
    admin_password = ""
  }

  boot_diagnostics {
      enabled       = "true"
      storage_uri   = "${azurerm_storage_account.xxxx.primary_blob_endpoint}"
  }

  tags {
        Name = "xxxx"
        Service = "xxx"
  }
}

A: just like it says, you are missing a "plan" property definition. Marketplace images tend to have that.
Everything else in the vm definition looks fine, unless Terraform needs something else.


text:
Q: Show new field after button click I want to make a field that only shows up after a button click.
Heres my code so far:

                Password:

<input id="pw" type="password">

The "display:none" makes it invisible, after that I have my button and a javascript which should change the display to "block", thus making it visible again.

                <button class="btn btn-primary" onclick="showPWField()">Log-In</button>

But it just doesnt work. The function gets called I tested that with an alert, but I just can't change the style :/
Thanks for help in advance

A: the error is that getElementByID does not exist, you should use getElementById:
function showPWField() {
    document.getElementById("passwordfield").style.display = "block";
}

                Password:

<input id="pw" type="password">

            <button class="btn btn-primary" onclick="showPWField()">Log-In</button>

A: Javascript is a case sensitive,the method you used is getElementByID() won't work in javascript, better to use getElementById()
function showPWField() {
    document.getElementById("passwordfield").style.display = "block";
}enter code here


text:
Q: ExpandableListView в прокручивающемся экране. (Android)
Необходимо реализовать такую верстку. Основная проблема, что все в один экран не вмещается и приходится использовать ScrollView. А ListView и Scroll противопоказаны друг другу.
Как выйти из такой ситуации?

A: Просто засуньте всё что скролится в список (и возможно стоит уже переходить на RecyclerView вместо ListView) и избавьтесь от ScrollView. Как сделать несколько разных типов строк для RecyclerView можно посмотреть например тут или тут (на английском).


text:
Q: Plotting point based on angle and distance from another given point in QGIS? I am using QGIS 2.18.10.
If I have a given point with an easting and a northing, and know its distance and angle from a transit which took the initial point, how do I plot the location of the transit if I don't already have its easting and northing?
As a secondary question; the transit took a further 900 points (an archaeological scatter which I'm plotting). Once I have the location of the transit, how would I calculate and plot those other points as a batch, based on their distances and angles from the transit, instead of inputting them individually?

A: Look into the "Azimuth and Distance" plugin. There is a usage example here: https://www.northrivergeographic.com/qgis-azimuth-distance-plugin
That should do exactly what you need, and it is even possible to import a file to automatically treat  your 900 points.


text:
Q: py3compile error - Unable to get the locale encoding After reinstalled the python3.2, I got the error as below when call py3compile:
Fatal Python error: Py_Initialize: Unable to get the locale encoding
LookupError: no codec search functions registered: can't find encoding
Aborted

I know it may be the problem of missing environment variable. But I have no idea of how to fix it. I checked the env  output and didn't find any PYTHONXXX variables.

A: Mind that this is a late response, since someone has offered a bounty on this question. Also note that without reproducing this problem I can't verify if any solution works. I will just suggest a solution here, not provide one.
I think you have to set two variables as outlined here, because py3compile needs to know where certain resources are. It looks them up via these PYTHONXXX variables.
So
export PYTHONPATH='/usr/lib64/python3.21:/usr/lib64/python3.2/lib-dynload:/usr/lib64/python3.2/site-packages'
export PYTHONHOME='/usr/lib64/python3.2'

or rather
export PYTHONPATH='/path/to/pythondir:/path/to/pythondir/lib-dynload:/path/to/pythondir/site-packages'
export PYTHONHOME='/path/to/pythondir'

should do the trick.

A: Try following (replace opkg with your favorite package manager)
 # opkg install python3-modules
 # opkg install python3-misc

A: Here on voidlinux fixed this error by in addition to setting PYTHONHOME and PYTHONPATH relinking the symbolic link for the default python in /usr/bin from python3.5 to python2.7 for which I knew it was the one I set the paths for and which the program that requires python requires.
Note that setting the paths for 3.5 did not fix the python3.5 Py_Initialize error here.
Who said maintaining systems is easy.
Which is why we have 0install. If only it could be adopted by our open source world folks more. Currently we are struggling getting it to compile on voidlinux due to a libcurl OCaml issue. Most distributions have it in their package management repositories.
0install solves all these problems by fully encapsulating a program to have it run with the dependencies it requires without conflicting other version installed on the system or using 0install and saves package maintainers time because it eliminates those links inbetween the user system and the developers because the developers provide one 0install package for all systems directly (zero install is a cross platform package management system).


text:
Q: How to sort array of string by length and maintain their keys in PHP? There is an array of strings;
$arr=array('longstring','string','thelongeststring');

so the keys are:
0=>'longstring'
1=>'string'
2=>'thelongeststring'

I want to sort it by length of strings, from longest to shortest, but without changing their keys;
$arrSorted=array(**2**=>'thelongeststring', **0**=>'longstring', **1**=>'string');

I am working with PHP since 2 days so that is what I already know that could be helpful with this case:
...
    usort($twoDim, 'sorting');
}

function sorting($a, $b) {
    return strlen($b) - strlen($a);
}

That is giving me array with string sorted by length, but with new keys. Another thing is asort which sorts an array alphabetical and maintain its keys. But I have no idea how to do these two things in the same time...
Please help!

A: Use uasort:

uasort — Sort an array with a user-defined comparison function and maintain index association

usort doesn't maintain index associations.
Use it like this:
function sortByLength ($a, $b) {
    return strlen($b) - strlen($a);
}

$arr = ['longstring', 'string', 'thelongeststring'];

uasort($arr, 'sortByLength');

print_r($arr);

eval.in demo
This returns:
Array
(
    [2] => thelongeststring
    [0] => longstring
    [1] => string
)

A:
...how to do these two things in the same time

You're almost there.
usort + asort = uasort.


text:
Q: Using Office.onReady() Breaks Outlook 2013 add-ins We're building an Outlook add-in, and recently a customer reported that it does not load in Outlook 2013. I've been able to confirm this locally across a number of different versions of our Add-in. It loads and works fine in Outlook 2016, Outlook Web and Outlook for Mac.
We recently changed from Office.initialize to Office.onReady in order to simplify platform detection. This does not work for Outlook 2013. On the face of it, the problem appears to be that the HostType is coming back as Excel, and many of the API's under Office.context (e.g. diagnostics, roamingSettings, mailbox) are undefined.
If I set the entry-point up using Office.initialize, then everything works fine. If setup using Office.onReady, the add-in will load, so long as all the Office api calls have guardrails around them. This lets me get some context out, as I can access our internal logging system.
Is this a known issue? Our add-in is now completely broken in Outlook 2013.
Update: I previously believed this to be an issue with both onReady and initialize, however I've since found that initialize does in fact still work. It is only onReady that appears to be broken in Outlook 2013

A: This has been identified as a bug in the Office-JS API and a fix is incoming.
To work around the issue in the meantime, you can continue to use Office.initialize. You can get the context provided by onReady's info parameter using Office.context.diagnostics


text:
Q: Replicar conteúdo de val() em span Achei este código que funciona muito bem em inputs:

<input type="text" name="email" placeholder='email' />
<input type="text" name="login" placeholder='login' />

Porém fiz algumas modificações querendo fazer funcionar em outros elementos como por exemplo o span.

<input type="text" name="email" placeholder='email' />

porém não funciona, mas se eu colocar qualquer texto pronto no lugar do $(email).insertAfter ai funciona, existe uma forma de funcionar como funciona no input?

A: O normal seria adicionar o seletor do span e utilizar o metodo html() para inserir o texto desta forma:

$("[name='email']").keyup(function() {
  var email = $(this).val();
  $("[name='login']").val(email);
  $("#spanLogin").html(email);
});

<input type="text" name="email" placeholder='email' />
<input type="text" name="login" placeholder='login' />

A: Para inserir o texto no  pelo id="" você utiliza o .text().
segue o código.

$(function() {
    $("[name='email']").keyup(function() {
        var email = $(this).val();
        $("span.login").text(email);;
    });
});

<input type="text" name="email" placeholder='email' />


text:
Q: Deep Learning VM fails to deploy via UI - image resource not found - typo in the image url I've tried deploying the marketplace solution Deep Learning VM (Google Click to Deploy) using TF2.0 with a GPU. I'm doing this through the UI to select the zone and other instance options.
As soon as I deploy however and get taken to the Deployment Manager screen, I see the following error:
jupyterlab-eu-w-4c-vm: {"ResourceType":"compute.v1.instance","ResourceErrorCode":"400","ResourceErrorMessage":{"code":400,"errors":[{"domain":"global","message":"Invalid value for field 'resource.disks[0].initializeParams.sourceImage': 'https://www.googleapis.com/compute/v1/projects/click-to-deploy-images/global/images/tf-2-0-cu100-experimental-20190821'. The referenced image resource cannot be found.","reason":"invalid"}],"message":"Invalid value for field 'resource.disks[0].initializeParams.sourceImage': 'https://www.googleapis.com/compute/v1/projects/click-to-deploy-images/global/images/tf-2-0-cu100-experimental-20190821'. The referenced image resource cannot be found.","statusMessage":"Bad Request","requestPath":"https://compute.googleapis.com/compute/v1/projects/jupyterlab-instance/zones/europe-west4-c/instances","httpMethod":"POST"}}

The key being that the image resource cannot be found at that url:
https://www.googleapis.com/compute/v1/projects/click-to-deploy-images/global/images/tf-2-0-cu100-experimental-20190821

I searched for the available images on the cloud shell:
@cloudshell:~ (jupyterlab-instance)$ gcloud compute images list --project click-to-deploy-images --no-standard-images --uri | grep tf-2-0-cu100
https://www.googleapis.com/compute/v1/projects/click-to-deploy-images/global/images/tf-2-0-cu100--experimental-20190821

Notice, the URL is different, there is an extra "-" in the image name as compared to what the deployment script is trying to fetch:
tf-2-0-cu100-experimental-20190821
tf-2-0-cu100--experimental-20190821

This looks like an unintentional typo.
My question though, is how can I go about deploying this VM? Is there a way I can modify the deployment script that the UI generates before deploying or do I need to do the whole deployment via the CLI to add in the extra "-"?
Is there a way I can raise this to get someone to fix the typo? I presume this would be preventing anyone trying to deploy a TensorFlow 2 GPU instance via the UI tools using the Deep Learning VM.
Thanks for your help.

A: I encountered the same problem. that VM will not deploy with TF 2.0 version because the boot image URL is messed up it seems. it's not related to zone (I've tried deploying without GPUs and in different zones, it won't work)
One solution is to deploy the image with an instance directly (See documentation 1)
gcloud compute instances create $INSTANCE_NAME \
  --zone=$ZONE \
  --image-family=tf2-latest-gpu \(I used cpu the one but this one seems to fit)
  --image-project=deeplearning-platform-release \
  --accelerator=count=1,type=nvidia-tesla-k80

Add any options desired (GPU,etc...).
You can get help for the command with
gcloud compute instances create --help

To list all available images, use
gcloud compute images list --project deeplearning-platform-release --no-standard-images

A: I had a very similar problem and it turned out that I was trying to deploy a GPU model in a zone in which it wasn't supported. Take a look here to see whether the GPU type you're using is supported in "europe-west4-c". For example, if you're using a K80, then it's not available in that zone (see screenshot below).


text:
Q: How to save an image resize to storage folder? Why does not this work?
I want to change the size and save it in the storage folder.
public function store(Request $request)
{
    $image = $request->file('image') ?? null;
    if ($request->hasFile('image'))
    {
        $file = $request->file('image');
        $name = time();
        $extension = $file->getClientOriginalExtension();
        $imageResize = Image::make($image)->resize(600, 300)->stream();
        $fileName = $name . '.' . $extension;
        Storage::disk('public')->put('images/blogs/'.$fileName, $imageResize);
    }
    Blog::query()->create([
        'image' => $fileName,// or $image or $imageResize
    ]);
    return redirect()->route('admin.blogs.index');
}

When I upload an image, I see this path and I did not see an image

data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==


text:
Q: Detect characters that will require unicode converstion for SMS messages I've had a look around and can't find a definite answer to my problem.
Basically I have an SMS gateway I am using. To send GSM, chinese, arabic etc characters through their SMS gateway, I have to send the message as 16-bit unicode.
What I want to do is detect if the message will require to be sent as 16-bit unicode or just plain old 7-bit for simple English characters. All my characters are stored in UTF-8.
Here is my code that I am using to detect this:
if (preg_match("/^[a-zA-Z0-9 !@#$%^&*()-_+={\[\]}|\\`<>,.\?\/]*$/u", $string) == 1)
    return '7-bit';
else
    return '16-bit';

I've uploaded some test cases here: http://phpfiddle.org/lite/code/v7f-gi0 (just hit the Run button)
The code seems really messy to me. Am I going about this the wrong way?

A: Found my answer here thanks to Alix Axel: Check unicode in PHP
if (strlen($string) != strlen(utf8_decode($string)))
{
    echo 'is unicode';
}


text:
Q: Julia: Constructor Embedding a function inside a type I am new to OOP. Lets say I have a Type and function like this:
   type Person
      name::String
      male::Bool
      age::Float64
      children::Int

    end

    function describe(p::Person)
      println("Name: ", p.name, " Male: ", p.male)
      println("Age: ", p.age, " Children: ", p.children)
    end

    ted = Person("Ted",1,55,0)

    describe(ted)

Is there a way to have the describe function embedded inside the type. For example if I input something like this
ted.describe()

I would get:
Name Ted Male true
Age 55.0 Children 0

A: I'm new to Julia too, and had the same request some times ago.
Now I'd solve your problem with the following code,
thank to the help from
 Understanding object-oriented programming in Julia – Objects-part 1
,
I know that an anonymous fonction are not very fast, but I
think the overhead is not too bad for a "printing" function.
#!/usr/bin/env julia
mutable struct Person
    name::AbstractString
    male::Bool
    age::Float64
    children::Int
    describe::Function
    function Person(name,male,age,children)
        this = new()
        this.name = name
        this.male = male
        this.age = age
        this.children = children
        # anonymous functions are not known to be fast ;-)
        this.describe =  function() describe(this) end
        this
    end
end

function describe(p::Person)
    println("Name: ", p.name, " Male: ", p.male)
    println("Age: ", p.age, " Children: ", p.children)
end

ted = Person("Ted",1,55,0)
# describe(ted)
ted.describe()

However as 0xMB said: it's not the Julia way.
But I like the method chaining call system from Ruby,
So I hope a syntactical sugger will appear some day to be able
to easily create some alias to create such a "member function".
-- Maurice

A: Julia does not support this dot notation. This may differ from other object oriented languages where methods are part of your objects but in Julia function are considered to act on data in general and are therefore not defined inside your objects data.
Your example is just fine.


text:
Q: Can't enable port forwarding due to No base MAC address error I am trying to enable port-forwarding so i can access my vagrant box from my local machine, but whenever i run my vagrant box i get this error,
No base MAC address was specified. This is required for the NAT networking
to work properly (and hence port forwarding, SSH, etc.). Specifying this
MAC address is typically up to the box and box maintainer. Please contact
the relevant person to solve this issue.

But when I re-run vagrant up command, it works just fine except that I can't ping it from my host machine.
I am using the following line in my Vagrantfile to enable port forwarding,
   config.vm.network :forwarded_port, guest: 80, host: 4567

and I am trying to ping it in my host machine as follows,
ping 127.0.0.1:4567

Can someone please tell me how can I fix this mac error issue so that I can ping and access my box from my local machine ?
EDIT:
I have tried this code to set the MAC address but its not doing anything either.
 config.vm.provider "virtualbox" do |vb|
    vb.customize ["modifyvm", :id, "--macaddress1", "auto"]
  end


text:
Q: Jquery- Same object, multiple clicks, multiple functions I'm trying to figure out the best way to achieve an effect of clicking on object1 once and causing a function once (animating object A), then clicking on object1 again and causing another function (animating another object-B), etc.
Can someone please toss me a few terminologies for what to use here? I do know how to achieve animation via jQuery/CSS add/remove/toggle class but I'm looking for the most efficient approach.

A: You're looking for JQuery 'one-shot' event handlers.
http://api.jquery.com/one/
function first() {
    $('#a').animate();
};

function next() {
    $('#b').animate();
};

$('#button').one('click', function() {
    first();
    $('#button').click(next);
};

This runs the first function the first time the click event is fired, and then re-binds the click event to the next function for all subsequent clicks.
EDIT: Alternately, if you have two and want them to alternate, you can use Vishal's suggestion of toggle: http://api.jquery.com/toggle-event/
EDIT 2:
Another alternative is to keep a counter in the event handler, like so:
function fireA() { /*...*/ }
function fireB() { /*...*/ }
function fireC() { /*...*/ }

$('#button').click(function() {
   var events = [fireA, fireB, fireC];

   //declare counter
   if(!this.counter) { this.counter = 0; }

   events[this.counter]();
   this.counter = (this.counter + 1) % 3;
});


text:
Q: Are negative values acceptable for the Variance Ratio Criterion (VRC)? I'm using a tutorial for the Variance Ratio Criterion (VRC) by Calinski and Harabasz 1974 (pdf).  In my case this entails the following steps:

*

*Conduct k-means clustering on my dataset for k=2 to k=21

*From the ANOVA table add the F values of each variable for each execution of the k-means method. This leads to 20 VRC values (All positive)

*Next the guide says to get the "correct" number of segments by in the kase of k=3 using:
W(3) = (VRC(k=4)-VRC(k=3)) - (VRC(k=3)-VRC(k=2))

In my case this leads to some negative values for W(x). Is this acceptable?  If so, should I use absolute values and select the lowest absolute value? Or should I select the W(X) that is most negative?


text:
Q: Mod-Rewrite REGEX not working Apache I am trying to get the following working:
When a user uses a search box, the get sends the user to www.example.com/search/?s=Query+String
Sending the GET request is not a problem, however, grabbing it via a RewriteRule is. I'm not sure my REGEX is proper in this case.
RewriteRule ^search/\?s=(.*[^/])$ search.php?s=$1 [NC,L]

What needs to happen is that the /search/?s=Query+String Query string part has to be taken from that url and sent over to search.php?s=Query+String via the Rewrite Rule

A: Query string from request is stored in variable %{QUERY_STRING}. Rules use %{REQUEST_URI}. Just use QSA flag:
RewriteRule ^search/?$ search.php [NC,L,QSA]

Tested here.


text:
Q: how to structure VueJs Views with subviews I have a large VueJs Project with many views and subviews (route-childrens).
Unfortunately I can't find any good pattern how to structure the views folder best. (incl. filenames)
Is there any best practice?
Following an example of my current :

*

*views

*

*user

*

*UserIndex.vue

*UserShow.vue

*subviews

*

*UserRoles.vue //index-view

*role

*

*RoleIndex.vue

A: Remove User Prefix from vue component, it already got User folder to recognize, After all its your choice to use which is best for your need.
- Views
   - User
    - Index.Vue
    - Show.Vue
    - Edit.Vue
    - Roles
      - Index.Vue
      - Show.Vue
      - Edit.Vue


text:
Q: How do I stop the docker service from always using all of its allocated ram on my host? The docker service on Windows 10 seems to always use the maximum amount of memory it is permitted to allocate. For example, when I increased the memory in the Resources -> Advanced section from 2GB to 8GB and clicked on "Apply & Restart", this happened in task manager:

How can I get docker to only use memory when/if needed by any running containers, as opposed to just chewing it all up?
No containers are currently running, just the service.

A: While Docker differs from full hardware virtualization, it still functions in many of the same ways, and for the same reasons.
Hypervisors reserve the given amount of memory in order that this memory will be available to them and the containers (or virtual machines) when they require it without having to petition the OS for this memory.
The setting you set is specifically for this purpose and behaves in precisely the way you have observed for precisely this reason. It is not a bug, and to change how it behaves is to rewrite the basic behavior of Docker.
So, nothing is broken and things are behaving as they should.
I strongly suggest you read up on memory reservations in Docker to better understand how and why. Docker is a mature product and is, I assume, well documented.
To "solve" the issue you have come up against, install more memory or more carefully plan your Docker memory needs and use this setting as it was designed, not just on a whim as you are doing now.

A: Running the newer versions of docker desktop with the WSL2 backend resolves this problem. I can't give much more details than this as I don't understand it too well myself, but I've installed WSL2 and noticed that docker now allocates memory dynamically.

Docker Desktop uses the dynamic memory allocation feature in WSL 2 to
greatly improve the resource consumption. This means, Docker Desktop
only uses the required amount of CPU and memory resources it needs,
while enabling CPU and memory-intensive tasks such as building a
container to run much faster.

Source: Docker Desktop WSL 2 backend


text:
Q: Database error in Android from create method I get this logcat error:

Caused by: android.database.sqlite.SQLiteException: no such column: id (code 1): , while compiling: SELECT * FROM notes WHERE id=0

This my code:
public static final String dbName="notesDb";
public static final Integer DB_version=1;

public static final String key_id="id";
public static final String key_title="title";
public static final String key_subject="subject";

public static final String Table_notes="notes";

public DbNotes(Context context) {
        super(context, dbName, null, DB_version);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String create_table="create table "+Table_notes+"("+key_id+"Integer primary key,"+key_title+" varchar(30), "+key_subject+" varchar(50)) ";
    db.execSQL(create_table);
}

public Note getNoteByID(int id){
    Note note=null;
    SQLiteDatabase db=this.getReadableDatabase();
    String selectQuery="SELECT * FROM "+Table_notes+" WHERE "+key_id+"="+id;
    Cursor cursor=db.rawQuery(selectQuery,null);
    if (cursor.moveToFirst()){
        String title=cursor.getString(cursor.getColumnIndex(key_title));
        String subject=cursor.getString(cursor.getColumnIndex(key_subject));
        int id_item=cursor.getInt(cursor.getColumnIndex(key_id));
        note=new Note(title,subject,id_item);
    }
    cursor.close();
    return note;
}

How can I solve this?

A: Error is in your Create query, you need to provide appropriate space after column name.
"create table "+Table_notes+"("+key_id+" Integer primary key," // you missed space before Integer
So sqlite will create your column with name idInteger and not id, You can try using select query by referring id column as idInteger.


text:
Q: Finding the number in a list where an element is found for each element in prolog. Ι have attempted to implement a simple program to find the index for every time an element is traversed.
indexOf(Found,[Found| T],0).
indexOf(Found,[H| T],Index):- indexOf( Found,T, Newindex),Index is NewIndex+1.

I attempted this, but it didn't work; basically I tried recursion here, with incrementation.
If someone could give me insight that would be very appreciated.

A: You might find it works better (or at all) on long lists, if you write it as
index_of(X,L,N) :-
  index_of(X,Xs,0,N) .

index_of( X , [X|_] , N , N ) .
index_of( X , [_|L] , T , N ) :-
  T1 is T+1 ,
  index_of(X,L,T1,N) .


text:
Q: Tabbed Activity - Fragments I want to create a "Tabbed Activity" with tabs for make a user-friendly layout. I've already set the activity to work with PagerAdapter
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setTitleTextColor(Color.BLUE);
    toolbar.setSubtitleTextColor(Color.BLUE);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Chat"));
    tabLayout.addTab(tabLayout.newTab().setText("Appunti"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    tabLayout.setBackgroundColor(getResources().getColor(R.color.color_yahweh));

    final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    final PagerAdapter adapter = new PagerAdapter
            (getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener()
{
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
        }
    });
}
}

And then there is PagerAdapter
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;

public PagerAdapter(FragmentManager fm, int NumOfTabs) {
    super(fm);
    this.mNumOfTabs = NumOfTabs;
}

@Override
public Fragment getItem(int position) {

    switch (position) {
        case 0:
            TabFragment1 tab1 = new TabFragment1();
            return tab1;
        case 1:
            TabFragment2 tab2 = new TabFragment2();
            return tab2;
        default:
            return null;
    }
}

@Override
public int getCount() {
    return mNumOfTabs;
}
}

And finally, TabFragment1 code
public class TabFragment1 extends Fragment {

private static final String TAG = "ChatActivity";

private ChatArrayAdapter adp;
private ListView list;
private EditText chatText;
private Button send;
Intent intent;

private boolean side = false;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.tab_fragment_1, container, false);
}

public void onCreate (Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        Intent i = getIntent();
        setContentView(R.layout.tab_fragment_1);
        send = (Button) findViewById(R.id.btn);
        list = (ListView) findViewById(R.id.listview);
        adp = new ChatArrayAdapter(getApplicationContext(), R.layout.chat);

        list.setAdapter(adp);
        chatText = (EditText) findViewById(R.id.chat_text);
        chatText.setOnKeyListener(new OnKeyListener() {

            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {

                    return sendChatMessage();
                }

                return false;

            }

        });

        send.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View arg0) {
                sendChatMessage();
            }

        });

        list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);

        list.setAdapter(adp);
        adp.registerDataSetObserver(new DataSetObserver() {

            public void OnChanged(){
                super.onChanged();
                list.setSelection(adp.getCount() -1);
            }

        });

    }

    private boolean sendChatMessage(){

        adp.add(new ChatMessage(side, chatText.getText().toString()));

        chatText.setText("");
        side = !side;
        return true;

    }

}
}

And tab_fragment_1 XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    >

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="80dp"
        />

    <EditText
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:inputType="textMultiLine"
        android:ems="10"
        android:id="@+id/chat_text"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_toLeftOf="@+id/btn"
            />

    <Button
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="@string/button_send"
        android:id="@+id/btn"
        android:layout_alignBottom="@+id/chat_text"
        android:layout_alignParentRight="true"
            />

</RelativeLayout>

I get a lot of errors on TabFragment1.java, so i was wondering what i was doing bad. Then i found that getIntent(), setContentView, findViewById, getApplicationContext() are all related to an Activity, and cannot be called from a Fragment. So i tried to change my TabFragment1.java. Now it appears like this
public class TabFragment1 extends Fragment {

private ChatArrayAdapter adp;
private EditText chatText;
private boolean side = false;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.tab_fragment_1, container, false);
    EditText chatText = (EditText) root.findViewById(R.id.chat_text);
    Button send = (Button) root.findViewById(R.id.btn);
    ListView list = (ListView) root.findViewById (R.id.listview);
    list.setAdapter(adp);
    adp = new ChatArrayAdapter(getActivity(), R.layout.chat);
    list.setAdapter(adp);

    chatText.setOnKeyListener(new OnKeyListener() {

        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {

                return sendChatMessage();
            }

            return false;

        }
    });

    send.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View arg0) {

            sendChatMessage();

        }
    });

    list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
    list.setAdapter(adp);
    adp.registerDataSetObserver(new DataSetObserver() {

    });
return root;
}

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

private boolean sendChatMessage(){

        adp.add(new ChatMessage(side, chatText.getText().toString()));
        chatText.setText("");
        side = !side;
        return true;
    }
}

And i still get an error when i try to send a message on my app. It says:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference

What i've done bad?

A: You shadowed your EditText field
Replace
EditText chatText = (EditText) root.findViewById

With
this.chatText = (EditText) root.findViewById

fyi, tabbed activities aren't deprecated


text:
Q: JPA Inheritance :mapping derived entities to different tables I use SINGLE_TABLE inheritance startegy to map my usres (see code example bellow).
Is there a way to map UnActiveRegularUser and UnActiveBusinessUser from "ACTIVE_USERS" table to another table, for example "UNACTIVE_USERS" and keep the inheritance startegy?
Note:
-The point here is to avoid code duplication between ex. RegularUser Vs UnActiveRegularUser (since they use the same properties) but still to map them to 2 different tables: "ACTIVE_USERS" and "UNACTIVE_USERS".
-strategy = InheritanceType.SINGLE_TABLE should not be changed.
-May adding another abstraction layer solve this problem?
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table(name = "ACTIVE_USERS")
public class User {
    @Id @GeneratedValue
    protected Long id;

    @Column(nullable = false)
    protected String name;
}

@Entity
public class RegularUser extends User{
//more getters and settres
}

@Entity
public class UnActiveRegularUser extends User{
//same getters and setters as in RegularUser
}

@Entity
public class BusinessUser extends User {
//more getters and settres
}

@Entity
public class UnActiveBusinessUser extends User {
//same getters and setters as in BusinessUser
}

Thanks,
Nathan

A: Persisting fields to another table won't prevent code duplication. I think you should just make UnActiveBusinessUser extend BusinessUser, and UnactiveRegularUser extend RegularUser.
Note that if a user can become unactive (i.e. it is a RegularUser and becomes an UnactiveRegularUser), inheritance is not the right solution: an object can't go from one type to another. Since it seems UnactiveRegularUser doesn't have anything more than RegularUser, I'm not sure this subclass is useful.


text:
Q: Eureka TextRow layout problems I'm trying to configure a TextRow to have:

*

*subtitle cellStyle

*multiline text label

Sample:
 let textRow = TextRow() {
      $0.tag = "TextRow"
      $0.cellStyle = .subtitle
      $0.title = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,"
      $0.cell.textLabel?.numberOfLines = 0
    }

But, as you can see, the layout is not correct; any help? Thanks

Sample source code here

A: The problem seems fixed now after this pull request


text:
Q: iOS - 1000's of literal strings, how to handle? I have a few thousand literal strings in my app.
I currently have them all listed in my .m file.
I don't have a problem doing it this way, and it works for my app.
Is this not a best practice?  Should I house my string data in an external DB?
Thank You.

A: Several thousand literal strings sounds annoying, but that's the worst of it. A database probably would be overkill and hard to maintain. So long as you can localize your app when/if you need to, it should be fine.

A: This is the kind of thing SQLite was MEANT for.
The minute you instantiate that object, all those strings are taking up memory, including the vast majority of which you probably won't use on any particular trip through the app. I'd sure rather have a database I could just query up the ones I need.


text:
Q: To make macro that takes into account the variability of the files to be using it on. Where should i look to find options of codes? I made this macro. It works perfectly with the file I used to create it. This file is a csv ouput form a machine. The macro will make a standard line graph with specific settings.I have to filter some data out and then clear some data and highlight another set of data to create the graph. The number of rows to be filtered will be variable and the number of cells to be cleared will also be variable. The columns and rows to be highlighted to create the graph may also vary between machine run.
Im thinking I may not be able to adapt the macro to execute when the files will have such a high degree of variability. Im considering maybe finding a different solution. Does anyone have any suggestions on how to best approach this problem. As background this is my first foray into Macros. I have beginner to moderate python knowledge  and Im very good as most excel task.
Also note: all the scroll code is because its a long data file, approximate 1200 rows and 9 to 10 columns of data.
    Sub All()
'
' AllSteps Macro
' step1
'

'
    Selection.AutoFilter
    ActiveSheet.Range("$A$1:$W$1086").AutoFilter Field:=9, Criteria1:="<700000"
    Range("G99:I165").Select
    Selection.ClearContents
    Range("G1:L1083").Select
    ActiveSheet.Shapes.AddChart2(227, xlLine).Select
    ActiveChart.SetSourceData Source:=Range("'Raw Data'!$G$1:$L$1083")
   ActiveSheet.Shapes("Chart 1").ScaleWidth 1.9680555556, msoFalse, _
        msoScaleFromTopLeft
    ActiveSheet.Shapes("Chart 1").ScaleHeight 1.3912037037, msoFalse, _
        msoScaleFromBottomRight
    ActiveSheet.Shapes("Chart 1").ScaleWidth 1.0529287227, msoFalse, _
        msoScaleFromBottomRight
    ActiveSheet.Shapes("Chart 1").ScaleHeight 1.6805324459, msoFalse, _
        msoScaleFromTopLeft
    ActiveChart.Axes(xlCategory).Select
    Selection.TickLabelPosition = xlLow
    Application.CutCopyMode = False
    Application.CutCopyMode = False
    ActiveWindow.ScrollRow = 855
    ActiveWindow.ScrollRow = 833
    ActiveWindow.ScrollRow = 774
    ActiveWindow.ScrollRow = 711
    ActiveWindow.ScrollRow = 541
    ActiveWindow.ScrollRow = 497
    ActiveWindow.ScrollRow = 480
    ActiveWindow.ScrollRow = 463
    ActiveWindow.ScrollRow = 458
    ActiveWindow.ScrollRow = 360
    ActiveWindow.ScrollRow = 282
    ActiveWindow.ScrollRow = 254
    ActiveWindow.ScrollRow = 230
    ActiveWindow.ScrollRow = 217
    ActiveWindow.ScrollRow = 215
    ActiveWindow.ScrollRow = 213
    ActiveWindow.ScrollRow = 206
    ActiveWindow.ScrollRow = 179
    ActiveWindow.ScrollRow = 112
    ActiveWindow.ScrollRow = 92
    ActiveWindow.ScrollColumn = 2
    ActiveWindow.ScrollColumn = 4
    ActiveWindow.ScrollColumn = 5
    ActiveChart.Axes(xlCategory).TickLabelSpacing = 1
    ActiveChart.Axes(xlCategory).TickLabelSpacing = 100
    ActiveChart.Axes(xlValue).Select
    ActiveChart.Axes(xlValue).MinimumScale = -90
    ActiveChart.Axes(xlValue).MaximumScale = 30
    ActiveChart.FullSeriesCollection(6).Select
    ActiveChart.FullSeriesCollection(5).Select
    ActiveChart.FullSeriesCollection(4).Select
    ActiveChart.FullSeriesCollection(3).Select
    ActiveChart.FullSeriesCollection(3).AxisGroup = 2
    ActiveSheet.ChartObjects("Chart 1").Activate
    ActiveChart.FullSeriesCollection(3).Select
    ActiveChart.FullSeriesCollection(2).Select
    ActiveChart.FullSeriesCollection(2).AxisGroup = 2
    ActiveSheet.ChartObjects("Chart 1").Activate
    ActiveChart.FullSeriesCollection(2).Select
    ActiveChart.FullSeriesCollection(1).Select
    ActiveChart.FullSeriesCollection(1).AxisGroup = 2
    ActiveSheet.ChartObjects("Chart 1").Activate
    ActiveChart.FullSeriesCollection(1).Select
    ActiveChart.Axes(xlValue, xlSecondary).Select
    ActiveChart.Axes(xlValue, xlSecondary).MinimumScale = 100
    ActiveWindow.ScrollColumn = 4
    ActiveWindow.ScrollColumn = 1
    Range("A108").Select
    Selection.Copy
    ActiveSheet.ChartObjects("Chart 1").Activate
    ActiveChart.ChartTitle.Select
    ActiveChart.Paste
    ActiveChart.ChartTitle.Text = "017306T11FluCandida            "
End Sub

A: First, consider attempting a simpler project for your first foray into VBA.  Adapting this code to dynamically fit to multiple workbooks will be very intensive, using a lot of Find and If/Then recursives.
Second, any line recorded by the macro recorder that deals with scrolling, selecting, or activating, is functionally useless.  Try setting breakpoints at each line of your code and step through it slowly to see what is actually happening, and whether that step is necessary.  Duplications of cutcopymode=False are also useless.
Third, as to the actual error you mentioned in your comments:
ActiveChart.SetSourceData Source:=Range("'Raw Data'!$G$1:$L$1083")

VBA identifies ranges differently from Excel.  You have to use a separate function to call the sheet, such as:
Worksheets("Raw Data").Range("G1:L1083")

See https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-object-excel
The macro recorder can only get you so far, you're going to have to dig in a lot more in order to get where you're going.  Good luck!


text:
Q: MVCMailer SendAsync and deleting attachments I'm having trouble getting MVCMailer to delete attachments after sending an email asynchronously.
I can't figure out what to do to dispose of the message to free up processes attached to the message attachments.
Following the instructions here....
    private IUserMailer userMailer = new UserMailer();

    public IUserMailer UserMailer
    {
        get { return this.userMailer; }
        set { this.userMailer = value; }
    }

      using (SmtpClientWrapper client = new SmtpClientWrapper())
        {
            client.SendCompleted += (sender, e) =>
            {
                if (e.Error != null || e.Cancelled)
                {
                    // Handle Error
                }

                //Use e.UserState

                //?? How can I use the userstate?? There are no
                // instructions??

                // Delete the saved attachments now.
                // This will not work since the mailmessage process
                // is still attached.
                Parallel.ForEach(imageList, image =>
                {

                    if (System.IO.File.Exists(image))
                    {
                        System.IO.File.Delete(image);
                    }

                });

            };

            // SendAsync() extension method: using Mvc.Mailer
            // farm is my model imageList is a list of file locations for the
            // uploaded attachments
          UserMailer.Submission(farm, imageList).SendAsync("user state object",
                                                            client);
        }

A: You could run break the SmtpClientWrapper out of the using statement and call dispose on it manually just before you clean-up the attachment.

A: To show what my successful solution was:
        MailMessage message = UserMailer.Submission(farm, imageList);

        SmtpClientWrapper client = new SmtpClientWrapper();

        client.SendCompleted += (sender, e) =>
        {
            if (e.Error != null || e.Cancelled)
            {
                // Handle Error
            }

            if (message != null)
            {
                message.Attachments.Dispose();
                message.Dispose();

                // Delete the saved attachments now
                Parallel.ForEach(imageList, image =>
                {

                    if (System.IO.File.Exists(image))
                    {
                        System.IO.File.Delete(image);
                    }

                });

            }

            client.Dispose();

        };

        // SendAsync() extension method: using Mvc.Mailer
        message.SendAsync("farm message", client);


text:
Q: Creating a global variable on the fly. [PHP ENCRYPTION] Is there a way to dynamically create constant variables on the fly?
The idea is that upon logging into the system, a user would be asked to upload a small text file that would be fread, and assigned to a var that would be accessible throughout the system.
If this is possible, just to be clear, would this variable then only be accessible to that user and only while the session is alive?
Security being the main concern here, would it be more practical to store the var in a session variable?
The plan:
Data in the db will be encrypted via mcrypt, and the key will be stored on USB thumbdrives. The user will insert the thumbdrive when going to access the system. Upon logging in, the app will prompt the user to upload the key. They will navigate to the thumbdrive and key. Via fopen and fread, the key will be assigned to a global var which will then allow access to encrypted data, and will be used to encrypt new info being entered to the db.
When the user logs out, or session times out, the global var will become empty.
Thanks!

NB: the var would need to be persistent and accessible through many pages and cookies are out.

A: The best solution for you would probably be to store it in the Session variable, this seems to me to be the best way to manage this kind of data, though it might depend on how big the file is.

A: <?php

function first() {
 global $foo;
 $foo = 'bar';
}

function second() {
global $foo;
echo $foo;
}

first();
second();

?>

Just put the global keyword in and you can stick anything you like in global scope.
Although as luke said, it sounds like you should use the automatic session variable.
http://www.php.net/manual/en/reserved.variables.session.php

A: I've decided that the following solution will work:
When a user logs onto the system they will be prompted to upload their key. The upload script will assign a unique and random filename and place the file into a temporary directory.
The path to the file will be set into a session variable. When needed, the path will be called from the session var, and file_get_contents() will be used to retrieve the key.
When the session is ended or times out, the session variable will be deleted and the file itself will be removed via unlink().
Thanks!


text:
Q: How to stop changing text inside textbox with same ng-model I have more forms like this:
<form ng-submit="addReply(x)" class="dd animated slideInDown" >

                    <text-angular ng-model="form.reply"></text-angular>

                    <input type="submit" class="btn btn-default pull-right" value="Send" />

</form>

Have problem with text area because of ng-model="form.reply" when I change some textarea all other text areas are automatically changed... How to prevent it?
Here is example:
http://jsfiddle.net/oLv61qtr/
I just need change one not both...

A: The answer is: You can't do it.
If you have multiple text fields using the same model variable, they will always display the same value. At the end of the day it is the same variable, so how can it have different values in different places?
Use different model variable on different forms if you need. That seems like the best solution.


text:
Q: Улучшение производительности интерактивного SVG на html странице Всем привет! Имеется проблема с большим SVG. На странице необходимо отобразить SVG, но в нем порядка 20к элементов, весит под 20 мб. Сам SVG - это схема трубопроводов: 10 труб по 1500 метров каждая. Одна линия (path) - 1 метр трубы. Получается 15000 линий. id Каждой линии имеется в базе. База каждый день меняется, меняется именно параметр линии. В зависимости от параметра меняется цвет линии (красный, зеленый и т.д.). Трубы длинные, поэтому нужен зум, чтобы был виден текст(участок - 0, 1 метр и т.д. под каждой линией) и можно было перемещаться по этому SVG, используется svg-pan-zoom. Если бы элементов было не так много, то все шустро работало. Но чем их больше, тем медленнее работает. Весь код SVG вставлен в html как dom, то есть понимаете, как много строчек в html файле. Есть ли путь решения, как повысить скорость работы? Когда пытаешь зумить или перемещаться по свг - очень подтормаживает.Вот как выглядит (разумеется, вырезанная часть):

Вот так примерно будут подкрашиваться все элементы по клику


text:
Q: How to test drag and drop with vue and jest Is there a good way to test drag and drop with jest and vue and vue.draggable?
I tried to have a look at the test in the vue.draggable plugin, but I could not find any. Is it really untested?

A: Check: https://github.com/SortableJS/Vue.Draggable/tree/master/tests/unit
The unit tests are not faking drag and drop in itself, but there are emulating events and DOM manipulation performed by Sortable.js, and test vue.draggable reaction to these inputs

A: It does not seems to be tested.
This article shows how you could perform drag test with Jest:
const getTableCells = () =>
  Array.from(mountNode.querySelectorAll("tr td:nth-of-type(1)"));

const createBubbledEvent = (type, props = {}) => {
  const event = new Event(type, { bubbles: true });
  Object.assign(event, props);
  return event;
};

const tableCells = getTableCells();
const startingNode = tableCells[0];
const endingNode = tableCells[2];

startingNode.dispatchEvent(
  createBubbledEvent("dragstart", { clientX: 0, clientY: 0 })
);

endingNode.dispatchEvent(
  createBubbledEvent("drop", { clientX: 0, clientY: 1 })
);

expect(getTableCells().map(cell => cell.textContent)).toEqual([
  "Bob",
  "Clark",
  "Alice",
]);

A very well known library for draggable functionaility is from Shopify:
https://github.com/Shopify/draggable
I see they have some test, perhaps you can get some more information by looking at the repository?


text:
Q: javascript letter to digit hex Необходима функция, переводящая в десятичные числа hex буквы. A -> 10,
F -> 15 и тд. Чем выше будет порог (большие сс, где X тоже буква), тем лучше.

A:

let result = parseInt("1f", 16);
console.log(result); // -> 31

result = parseInt("1h", 19);
console.log(result); // -> 36

parseIntmdn
Здесь первый параметр - необходимое число, а второй - система счисления.


text:
Q: How to consolidate $.load() functions in jQuery I have code pulling in pieces of content from another page on my domain using the hashtag to target the correct div like so: $('#content').load('http://www.mysite.com/Default.aspx #homeText');
I have to grab 5 different div's from a single page, and rather than call the $.load() function 5 times, is there a more efficient way that wont require 5 different calls to the same page. I assume there is a way to parse the incoming page, but I'm not sure what the best way would be. Any suggestions?

A: You can use AJAX in this case.
$.ajax({
   url: "http://www.mysite.com/Default.aspx",
   success: function(response){
      var $response = $(response);
      var div1 = $response.find("div1Selector");
      var div2 = $response.find("div2Selector");
      var div3 = $response.find("div3Selector");
      var div4 = $response.find("div4Selector");
      var div5 = $response.find("div5Selector");
   }
});

A: I never tried something like this, but you should be able to do something like:
var temp = $('

').load('http://www.mysite.com/Default.aspx');
temp.find('#homeText');
temp.find('#someOtherDiv');
// etc


text:
Q: Sending commands to an application and reading its output via file descriptor in bash bluetoothctl is an application that has a shell and accepts input commands. I would like to send command to it from the shell of the linux arbitrarily and I would also like to read its output without colours. I am on debian based linux (Raspbian buster) and would like to do it from bash shell if possible.
What I have tried so far:
Method one (sending commands via fd)

*

*Run the process attached: $ bluetoothctl

*Then from another terminal: $ echo "my command" > /proc/$(pidof bluetoothctl)/fd/0 and $ echo -e "my command\n" > /proc/$(pidof bluetoothctl)/fd/0 and $ echo -e "my command\013" > /proc/$(pidof bluetoothctl)/fd/0 but my command just appears as an output of bluetoothctl and even pressing 'enter' key on my keyboard in the terminal of the program does not execute the command at all just gives a new line.

Method two (writing output to a text file)

*

*Run the process detached: $ bluetoothctl > my.output &, but it exits from the application immediately

Method three (sending command via pipe)

*

*Create a pipe mkfifo mypipe

*Redirect the pipe to bluetoothctl cat mypipe | bluetoothctl > my.output

*Write a command to the pipe echo "my command" > mypipe, but it closes the application immediately and the application has no time to process the command asynchronously. Hence, does not work.

I believe the feasible solution would be to start the application detached $ bluetoothctl & and then send command to it via /proc/$(pidof bluetoothctl)/fd/0 and read its stdout and stderr via /proc/$(pidof bluetoothctl)/fd/1 and /proc/$(pidof bluetoothctl)/fd/2 but I am totally lost.
One of the command I would like to execute and read it's output is 'scan on' and ideally one bluetoothctl instance would process multiple commands not only one that the pipe can do.
Can someone please advise how a command can be sent via fd, and how the output can be read via the another fd of the process. All of this in bash shell, if possible.

A: A coprocess is the appropriate tool for this job:
#!/usr/bin/env bash
case $BASH_VERSION in ''|[0-3].*|4.0*) echo "ERROR: bash 4.1+ required" >&2; exit 1;; esac

coproc btctl { bluetoothctl; }

echo "scan on" >&"${btctl[1]}"

while IFS= read -r -u "${btctl[0]}" line; do
  echo "Read line from btctl: $line" >&2
done

A: For everyones benefit: Following the accepted answer, I have resolved my issue with coprocess, however, I have used the /proc/$(pidof bluetoothctl)/fd/0 to send commands because it better suited to my application due to some of its assynchronous nature. The output was then diverted to a file and the colours were removed with sed upon read.
#!/bin/bash

readOutput() {
    echo "$(cat $TEMP/bluetoothctl.out | sed 's/\x1B\[[0-9;]\{1,\}[A-Za-z]//g'"
}

executeCommandInExistingProcess() {
  if [ -z "$(pidof bluetoothctl)" ]
  then
    exit -1
  else
    echo "$1" >&/proc/$(pidof bluetoothctl)/fd/0
  fi
}

startParallelProcess() {
  output="$TEMP/bluetoothctl.out"

  if [ ! -z "$(pidof bluetoothctl)" ]
  then
    echo "Bluetooth process is running..."
    exit -1
  fi

  if [ -f "$output" ]
  then
    rm $output
  fi

  coproc bctl { bluetoothctl > $output; }
  [ "$#" -ge 1 -a ! -z "$1" ] && executeCommandInExistingProcess "$1"

  sleep 30

  if [ ! -z $(pidof bluetoothctl) ]
  then
    [ "$#" -ge 2 -a ! -z "$2" ] && executeCommandInExistingProcess "$2"
    executeCommandInExistingProcess "quit"
  fi
}