text:
Q: How to make 5509.099999999999 as 5509.09 using javascript How to make 5509.099999999999 as 5509.09 using javascript.

A: Lots of mathy options that end up with .1 so how about;
var f = 5509.099999999999

if ((f = f.toString()).indexOf(".") >= 0)
    f = f.substr(0, 3 + f.indexOf("."))

print(parseFloat(f))

>>5509.09

A: Have you tried this?
var value = 5509.099999999999;
var str = value.toString();
var result = str.substr(0,7);

Then if you need it to be a float again you can do:
var FinalAnswer = parseFloat(result);

You don't need all these variables, but that is the step by step.

A: You can truncate the number to a certain number of decimal places using this function:
function truncateNumber(number, digits){
 var divisor = Math.pow(10,digits);
 return Math.floor(number*divisor)/divisor;
}

If you want to round the number instead, you can use JavaScript's built in Number.toFixed function. If you always want the number a certain number of digits long, you can use the Number.toPrecision function.

A: You could use .toFixed(2) but this will round the value, so in your example you'll end up with 5509.10 instead of 5509.09.
The next best option is to use Math.floor(), which truncates rather than rounding. Unfortunately, this only gives integer results, so to get the result to 2 decimal places, you'd need to multiply by 100, then use Math.floor(), and then divide by 100 again.
var value = 5509.099999999999;
var result = Math.floor(value*100)/100;

[EDIT]
Hmm, unfortunately, the above doesn't work due to problems with floating point precision -- even just the first step of multiplying it by 100 gives 550910.
Which means that the best answer is likely to be converting it to a string and chopping the string into bits.
var value = 5509.099999999999;
var str_value = value.toString();
var bits = str_value.split('.');
var result = bits[0]+"."+bits[1].substr(0,2);

I wouldn't normally suggest doing string manipulation for this sort of thing, because it is obviously a maths problem, but given the specific requirements of the question, it does seem that this is the only workable solution in this case.

A: if you want to take two decimal places, you can use .toPrecision(n) javascript function, where n is the total number of digits desired.
so, for your example, you'd have to do
var x = 5509.099999999999;
x = x.toPrecision(6);

this, however, rounds results in 5509.10

A:    var result = (Math.round((5509.09999 * 100) - 1)) / 100;


text:
Q: call connectionstring in sqldatasource How  can we call connection string in Sqldatasource from class instead of writing directly ?
    <asp:SqlDataSource  ID="sqldatasource" runat="server" ConnectionString="..." SelectCommand="sp"    SelectCommandType="StoredProcedure">

    </asp:SqlDataSource>

A: public class CXXX {
     public String ConnectionString() {
           return "data source=.\SQLEXPRESS;Initial Catalog=DB;Integrated Security=True;MultipleActiveResultSets=True;Pooling=false;";
        }
}

Declare an object
protected CXXX _myObject;

Then, in Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
         _myObject = new CXXX();
}

Then, in default.aspx, you can do:
<asp:SqlDataSource  ID="sqldatasource" runat="server" ConnectionString="<%= CXXX .ConnectionString() %>" SelectCommand="sp"    SelectCommandType="StoredProcedure">
</asp:SqlDataSource>

A: On code behind write
  SqlDataSource1.ConnectionString=Class1.StringConnectionObj;

http://www.codeproject.com/Questions/1121212/How-do-I-call-connection-string-in-sqldatasource-f

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cross joining to count values for a dates I'm on my 3rd attempt at solving this one now!
Trying to show how many holidays are 'live' on each calendar date.
At the moment I have a table with calendar dates and another with holidays.  I've joined them using an outer as there's nothing to join the two tables on.  So that's 4000 dates x 200,000 holidays, ouch!
The below runs for ages when top 10 selected so is not the way forward... (SQL Server)
SELECT top 10

C.CalendarDate,

Case when B.Depart <= C.CalendarDate and vwR.ReturnDate > C.CalendarDate then Count (B.ID) end as 'count'

FROM Calendar C
CROSS JOIN Booking B -- my issue!!
LEFT join vwReturnDate vwR on vwR.ID=B.ID -- bring in the return date
AND C.CalendarDate > '2013-10-01'
AND C.CalendarDate < '2013-10-30' -- narrow to October only

Group by C.CalendarDate, B.ID, B.depart, vwR.ReturnDate

order by c.CalendarDate

A: Something like this?
select
    calendarDate, COUNT(distinct bookings.id)
from calendarDate
    left join
        (
          select
            booking.id,
            booking.depart,
            vwReturnDate.returndate
          from booking
            left join vwReturnDate on booking.id = vwReturnDate.id
        ) bookings
             on calendarDate.calendarDate between bookings.depart and bookings.returndate
 where calendarDate between '2013-10-01' and '2013-10-31'
group by calendarDate


text:
Q: How to place comma separated values within braces and again separated by comma From user I will get the Input is in the form of (1, 21, 2, 7, 6,16)
but I want to Pass value in the form of ((1),(21), (2), (7), (6),(16)) to sql.
So, Can anyone suggest me a method to parse this values either in JQuery or in c# code.

A: var szData="(1, 21, 2, 7, 6,16)";
    szData = szData.replace("(","");
    szData = szData.replace(")", "");
    szData = szData.replace(/,/g, "),(")
    szData = "((" + szData + "))"
    console.info(szData)

A: Here is a sample how to do this in C#:
var input = "(1, 21, 2, 7, 6,16)";
var array = input
    .TrimStart('(').TrimEnd(')')  // Trim symbols ( and )
    .Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries) // Split into array, removing empty entries
    .Select(x=>x.Trim())        // Trim spaces from the number
    .Select(x=>string.Format("({0})", x));  // Select each item in format (x)
    var result = string.Format("({0})", string.Join(", ", array));  // create result
    // result is    ((1), (21), (2), (7), (6), (16))

A: If you are being passed a string of "1, 21, 2, 7, 6, 16" and looking for a way to convert that to a string of "(1), (21), (2), (7), (6), (16)", then you could do the following (in c#)
assuming your input is in the variable foo:
        var foo = "1, 21, 2, 7, 6, 16";
        var numbersWithPotentialSpaces = foo.Split(',');
        var numbers = numbersWithPotentialSpaces.Select(x => x.Trim());
        var numbersWithParens = numbers.Select(x => "(" + x + ")");
        var newString = string.Join(", ", numbersWithParens);


text:
Q: Converting a project from Python2 to Python3, strange error deep in a module now (astropy) I had this project running on my Mac here under python3.   It took a while after doing a 2to3 to update some other bits and pieces to it to finally get it to run.  Now though the project fails and all I recall of doing to my mac is:
Upgrading the OS
Upgrading Xcode and other pieces so that a 'brew install root' would work.
Not sure what else it touched but it is like it lost all the modules I had done a pip install on.  So i redid a pip install on several modules
astropy
matplotlib
scipy
now the project fails when I run it:
  File "/Users/shathoma/TUI3/TUI/Guide/GuideImage.py", line 26, in <module>
    import astropy.io.fits as pyfits
  File "/usr/local/lib/python3.9/site-packages/astropy/io/fits/__init__.py", line 70, in <module>
    from . import convenience
  File "/usr/local/lib/python3.9/site-packages/astropy/io/fits/convenience.py", line 63, in <module>
    from .diff import FITSDiff, HDUDiff
  File "/usr/local/lib/python3.9/site-packages/astropy/io/fits/diff.py", line 25, in <module>
    from .header import Header
  File "/usr/local/lib/python3.9/site-packages/astropy/io/fits/header.py", line 11, in <module>
    from .file import _File
  File "/usr/local/lib/python3.9/site-packages/astropy/io/fits/file.py", line 29, in <module>
    from astropy.utils.compat.optional_deps import HAS_BZ2
  File "/usr/local/lib/python3.9/site-packages/astropy/utils/compat/__init__.py", line 19, in <module>
    from .numpycompat import *  # noqa
  File "/usr/local/lib/python3.9/site-packages/astropy/utils/compat/numpycompat.py", line 14, in <module>
    NUMPY_LT_1_19 = not minversion('numpy', '1.19')
  File "/usr/local/lib/python3.9/site-packages/astropy/utils/decorators.py", line 546, in wrapper
    return function(*args, **kwargs)
  File "/usr/local/lib/python3.9/site-packages/astropy/utils/introspection.py", line 167, in minversion
    return Version(module_version) >= Version(version)
  File "/usr/local/lib/python3.9/site-packages/packaging/version.py", line 264, in __init__
    match = self._regex.search(version)
TypeError: expected string or bytes-like object

I have this project running fine still under a windows machine and the versions of the installed modules like astropy etc are the same.  Still fails on the mac with the above error.  I could go in and fix packaging/version.py to deal with a self._regex.search(str(version)) which is a bad Idea I know (I tried that and since reverted it gave an error on how version = none somewhere.
it is almost like I am missing a module but nothing knows it?  Not sure, and not sure how after working this broke with just probably the brew install command of the root (https://root.cern.ch/) package. Out of ideas what to look for or try next to get this running again?


text:
Q: Prove that $q(x)$ does not divide $p_k(x)$ Let $n \in \mathbb{N}$ and let $p_1(x), p_2(x), ... *p_n(x)$ be $n$ irreducible polynomials over $\mathbb{R}$. Define the polynomial $p(x) = p_1(x) * p_2(x) *... *p_n(x) + 1 $  where 1 is the constant polynomial $0x + 1$. Let $q(x)$ be an irreducible polynomial and suppose that $q(x)$ | $p(x)$. Prove that $q(x$) does not divide $p_k(x)$ for all $k \in ${$1..n$}
My attempt so far:
If $q(x)$ is an irreducible polynomial and $q(x)$ | $p(x)$, then gcd[$p(x), q(x)] = q(x)$
So $ap(x) + bq(x) = 1$ for some $a,b$ $\in \mathbb{R}[x]$
So $a(p_1(x) * p_2(x) *..*p_k(x)*.. *p_n(x) + 1) + bq(x) = 1$
So $(a(p_1(x) * p_2(x) *... *p_n(x) + 1)p_k(x) + bq(x) = 1$
Therefore $cp_k(x) + bq(x) = 1$ (where $c = a(p_1(x) * p_2(x) *... *p_n(x) + 1)$
Hence $p_k(x)$ and $q(x)$ are relatively prime so $q(x$) does not divide $p_k(x)$ for all $k \in ${$1..n$}

A: If $q$ divides $p_k$, then $q$ divides $p_1 \cdots p_n = p - 1$.  By hypothesis, $q$ divides $p$.  Hence $q$ divides $p - (p-1) = 1$.

A: The only units in this ring are the nonzero real numbers. Suppose $q$ divides some $p_k$ and $q$ divides p. Then $q$ divides $1$ which is a contradiction because irreducible elements are not units.


text:
Q: Error running testAction on CakePHP 2.4.6 error Undefined index: REMOTE_ADDR I am attempting to write tests for CakePHP 2.4.6 controllers. I am following the documentation which suggests that I can use testAction to product output to test against.
<?php
App::uses('UsersController', 'Controller');

class UsersControllerTest extends ControllerTestCase {
    public $fixtures = array(
      'app.user',
    );

    public function testIndex() {
      $result = $this->testAction('/users/view/10');
      debug($result);
    }
  }

When I run this test I receive the following error message:
UsersControllerTest::testIndex
Undefined index: REMOTE_ADDR

Please can you advise what I can do to initialise the controller and gain access to its methods for unit testing.

A: Found the problem, it was in a custom authorisation component which was not included in the stack trace for some reason. It was attempting to use the $_SERVER['REMOTE_ADDR'] which must not get set when testAction is called.


text:
Q: Android Testing AsyncTask with TextView Passed in I have an AsyncTask that I would like to write a test for.  It has a TextView that is passed in:
public LoadAssetTask(TextView target, boolean skipSingleLineBreak, InputStream in) { ...}

How do I write an Adroid JUnit test for this?  Is there a way to use a Mock Object to Mock an activity with a text field, I'd hate to create a whole activity or use one that is already since I want to test just this class.  I tried using a mock activity but you have to add that to the manifest and I don't want to do that for each and every AsyncTask that I have.

A: Have you tried using android.test.ActivityInstrumentationTestCase2? This class runs JUnit tests for methods in another Activity. In fact, it's the only way to run a JUnit test against a method in an Activity (or methods in a contained class of an Activity). AsyncTask has to run within an Android context (because it uses Android thread APIs), but I assume that ActivityInstrumentationTestCase2 can communicate with any thread in the process.
Documentation for ActivitInstrumentationTestCase2 is at http://developer.android.com/tools/testing/testing_android.html


text:
Q: pyzmq create a process with its own socket I have some code thats monitoring some other changing files, what i would like to do is to start that code that uses zeromq with different socket, the way im doing it now seems to cause assertions to fail somewhere in libzmq, since i may be reusing the same socket. how do i ensure when i create a new process from the monitor class the context will not be reused?  thats what i think is going on, if you can tell there is some other stupidity on my part, please advise.
here is some code:
import zmq
from zmq.eventloop import ioloop
from  zmq.eventloop.zmqstream  import ZMQStream
class Monitor(object):
    def __init(self)
        self.context = zmq.Context()
        self.socket = self.context.socket(zmq.DEALER)
        self.socket.connect("tcp//127.0.0.1:5055")
        self.stream =  ZMQStream(self._socket)
        self.stream.on_recv(self.somefunc)

    def initialize(self,id)
        self._id = id

    def somefunc(self, something)
        """work here and send back results if any """
        import json
        jdecoded = json.loads(something)
        if self_id == jdecoded['_id']
           """ good im the right monitor for you """
           work = jdecoded['message']
           results  = algorithm (work)
           self.socket.send(json.dumps(results))
        else:
           """let some other process deal with it, not mine """
           pass

 class Prefect(object):
    def __init(self, id)
        self.context = zmq.Context()
        self.socket = self.context.socket(zmq.DEALER)
        self.socket.bind("tcp//127.0.0.1:5055")
        self.stream =  ZMQStream(self._socket)
        self.stream.on_recv(self.check_if)
        self._id = id
        self.monitors = []
    def check_if(self,message):
        """find out from message's id whether we have
            started a proces for it previously"""
        import json
        jdecoded = json.loads(message)
        this_id = jdecoded['_id']
        if this_id in self.monitors:
            pass
        else:
            """start new process for it should have its won socket """
            new = Monitor()
            import Process
            newp = Process(target=new.initialize,args=(this_id) )
            newp.start()
            self.monitors.append(this_id) ## ensure its remembered

what is going on is that i want all the monitor processess and a single prefect process listening on the same port, so when prefect sees a request that it hasnt seen it starts a process for it, all the processes that exist probably should listen too but ignore messages not meant for them.
as it stands, if i do this i get some crash possibly related to concurrent access of the same zmq socket by something (i tried threading.thread, still crashes)  i read somewhere that concurrent access of a zmq socket by different threads is not possible. How would i ensure that new processes get their own zmq sockets?
EDIT:
the main deal in my app is that a request comes in via zmq socket, and a process(s) thats listening reacts to the message by:
1. If its directed at that process judged by the _id field, do some reading on a file and reply since one of the monitors match the messages _id, if none match, then:
2  If the messages _id files is not recognized, all monitors ignore it but the Prefect creates a process to handle that _id and all future messages to that id.
3. I want all the messages to be seen by the monitor processes as well as the prefect process, seems that seems easiest,
4. All the messages are very small, avarage ~4096 bytes.
5. The monitor does some non-blocking read and for each ioloop it sends what it has found out

more-edit=>and the prefect process binds now, and it will receive messages and echo them so they can be seen by monitors. This is what i have in mind, as the architecture but its not final.
    .
All the messages are arriving from remote users over a browser that lets the server know what a client wants  and the server sends the message to the backend via zmq(i did not show this, but is not hard)  so in production they might not bind/connect to localhost.
I chose DEALER since it allows asyc / unlimited messages in either direction (see point 5.) and DEALER can bind with DEALER, and initial request/reply can arrive from  either side. The other that can do this is possibly DEALER/ROUTER.

A: You are correct that you cannot keep using the same socket in a subprocess (multiprocessing usually uses fork to create subprocesses).  In general, what this means is that you don't want to create the socket that will be used in the subprocess until after the subprocess starts.
Since, in your case, the socket is an attribute on the Monitor object, you probably don't want to create the Monitor in the main process at all. That would look something like this:
def start_monitor(this_id):
    monitor = Monitor()
    monitor.initialize(this_id)
    # run the eventloop, or this will return immediately and destroy the monitor

... inside Prefect.check_if():

    proc = Process(target=start_monitor, args=(this_id,))
    proc.start()
    self.monitors.append(this_id)

rather than your example, where the only thing the subprocess does is assign an ID and then kill the process, ultimately having no effect.


text:
Q: When a force is applied on a body, which point does the body rotate around? I understand when a force is applied to a body it causes moments on all points not lying on the force's line of action. So which of these points acts as the pivot point around which the body actually rotates with a specific moment as a result of that applied force?

A: The motion caused by an applied force $F$ can be resolved into 2 components :

*

*A linear acceleration $a=F/m$ of the centre of mass (CM). If the force is an impulse the effect is to change the linear momentum of the CM.

*A rotational acceleration about the CM. The force produces a torque $\tau=r\times F$ about the CM, where $r$ is the position vector of the point of application of the force, relative to the CM. This torque causes rotational acceleration $\alpha=\tau/J$ where $J$ is the moment of inertia.
The overall motion is a combination of these 2 motions. The result usually means that there is one point in the body for which the instantaneous velocity is zero at some instant in time. This is called the instantaneous centre of rotation.


text:
Q: Using round function in QGIS expression? I created a grid of rectangular polygons with the Create Grid function, from the Vector Creation group of the Processing Toolbox in QGIS 3.4.2.
The rectangles measure half a degree of longitude by half a degree of latitude.
When I want to label the polygons, I write an expression that rounds the values of latitude and longitude attributes to 2 decimal places, since the attributes created in the grid brings many decimal places.
But the round function rounds the values badly.
I know that I can create new attributes that express the coordinates with fewer decimal places and label the entities based on those attributes, but I was struck by the behavior of the function. I expected it to round to the nearest value.
Does anyone know what the problem is that the round function wrongly rounds off the decimal number?
Attached screenshots of Source Fields and the Attribute Table.

A: Actually I cannot replicate the same behavior that you have. I created a grid with 0.5 degree width of latitude and longitude, and I round it to 2 decimal degree and it works fine. Then I added another column with a value of 50.49 and round it to 1 decimal and it worked as expected and I got 50.5. Here is the table with values:

I am not sure what was going wrong in your case. I used the exact version of QGIS 3.4.2.
Update
You are right. If I use negative latitude and longitude, I got strange results. I think this is a bug in QGIS 3.4.2. You should report this as a bug in QGIS 3.4.2 to the QGIS developer team here:

Update 2
The issue of rounding negative values was fixed in the latest stable release of QGIS 3.4.4-3. Now rounding negative numbers produces correct results:


text:
Q: Firebase Cloud Function onDelete variable param length I have the following code
//index.js
export const deletePicture = functions.region("europe-west1").database
  .ref("galleries/{galleryId}/{pictureId}")
  .onDelete(pictures.deletePicture)

//pictures.js
export const deletePicture = (snap, {params: {galleryId}}) => {
  console.log("Image deletion detected in the database, deleting images
  from the Storage...")
  const {fileName} = snap.val()
  const bucket = storage.bucket()
  const baseURL = `galleries/${galleryId}`
  // Thumbnails
  const promises = [sizes
    .map(size =>
      bucket.file(`${baseURL}/thumb_${size}_${fileName}`).delete())]
  // Original
  promises.push(bucket.file(`${baseURL}/${fileName}`).delete())

  return Promise
    .all(promises)
    .then(() => console.log(`All versions of ${fileName} are now deleted.`))
}

In my realtime database and Storage, I have the following structure:
galleries
|_rooms
| |_roomId
|   |_picture
|_foods
  |_picture

Is there any way that the above mentioned onDelete Cloud Function would trigger for the deletion of either of the pictures? The difference here is that the rooms picture is one level deeper, so I think that pictureId does not match roomId/picture.

A: Cloud Functions has no knowledge of the meaning of your JSON. So the trigger for delete of galleries/{galleryId}/{pictureId}, really just means that this function gets triggered whenever a node at the second level under galleries gets trigged.
In the structure you show, that means that this function will trigger whenever /galleries/room/roomId or /galleries/foods/picture gets deleted. The first of these will get triggered when you delete the last picture from a room.


text:
Q: Attribute based webapi2 routing returns 404 for some methods I'm presently working on a project that has been upgraded to Webapi2 from Webapi. Part of the conversion includes the switch to using attribute based routing.
I've appropriately setup my routes in the Global.asax (as follows)
 GlobalConfiguration.Configure(config => config.MapHttpAttributeRoutes());

and removed the previous routing configuration.
I have decorated all of my API controllers with the appropriate System.Web.Http.RouteAttribute and System.Web.Http.RoutePrefixAttribute attributes.
If I inspect System.Web.Http.GlobalConfiguration.Configuration.Routes with the debugger I can see that all my expected routes are registered in the collection. Likewise the appropriate routes are available within the included generated Webapi Help Page documentation as expected.
Even though all appears to be setup properly a good number of my REST calls result in a 404 not found response from the server.
I've found some notable similarities specific to GET methods (this is all I've tested so far)

*

*If a method accepts 0 parameters it will fail

*If a route overrides the prefix it will fail

*If a method takes a string parameter it is likely to succeed

*return type seems to have no affect

*Naming a route seems to have no affect

*Ordering a route seems to have no affect

*Renaming the underlying method seems to have no affect

Worth noting is that my API controllers appear in a separate area, but given that some routes do work I don't expect this to be the issue at hand.
Example of non-functional method call
[RoutePrefix("api/postman")]
public class PostmanApiController : ApiController
{
    ...
    [HttpGet]
    [Route("all", Name = "GetPostmanCollection")]
    [ResponseType(typeof (PostmanCollectionGet))]
    public IHttpActionResult GetPostmanCollection()
    {
        return Ok(...);
    }
    ...
}

I expect this to be available via http://[application-root]/api/postman/all
Interestingly enough a call to
Url.Link("GetPostmanCollection", null)

will return the above expected url
A very similar example of method calls within the same controller where some work and some do not.
[RoutePrefix("api/machine")]
public class MachineApiController : ApiController
{
    ...
    [HttpGet]
    [Route("byowner/{owner}", Name = "GetPostmanCollection")]
    public IEnumerable<string> GetByOwner([FromUri] string owner)
    {
        ...
    }
    ...

    [HttpGet]
    [Route("~/api/oses/{osType}")]
    public IEnumerable<OsAndVersionGet> GetOSes([FromUri] string osType)
    {
        ...
    }
    ...
}

Where a call to http://[application-root]/api/machineby/ownername  succeeds and http://[application-root]/api/oses/osType does not.
I've been poking at this far too long, any idea as to what the issue may be?

A: In my case it was a stupid mistake, I am posting this so people behind me making the same mistake may read this before they check everything else at quantum level.
My mistake was, my controller's name did not end with the word Controller.
Happy new year

A: Check that you configure your HttpConfiguration via the MapHttpAttributeRoutes method before any ASP.NET MVC routing registration.
In accordance to Microsoft's CodePlex entry on Attribute Routing in MVC and Web API the Design section states:

In most cases, MapHttpAttributeRoutes or MapMvcAttributeRoutes will be
  called first so that attribute routes are registered before the global
  routes (and therefore get a chance to supersede global routes).
  Requests to attribute routed controllers would also be filtered to
  only those that originated from an attribute route.

Therefore, within the Global.asax (or where registering routes) it is appropriate to call:
GlobalConfiguration.Configure(c => c.MapHttpAttributeRoutes()); // http routes
RouteTable.Routes.MapRoute(...); // mvc routes


text:
Q: Azure DevOps single pipeline for multiple projects without multiple azure-pipelines.yml files We have an Azure DevOps Pipeline defined as a template in a .yml file, and would like to use this to build 100+ projects.
There is zero parameterization to do, and the template essentially just runs against the project repo as-is.
Normally, we would just go into each of those project repos and create an azure-pipelines.yml file and reference the template pipeline, easy.
However, I would like to know if we can avoid creating these azure-pipelines.yml in each of the 100+ project repos. Is there some way to just run the template against 100+ repos, but as separate pipelines?

A: No.
YAML pipelines are based upon the YAML being stored in the application's repo, as code, alongside the application code. You can pull in templates from other repos, but you can't have one pipeline that is automatically valid for any repo.
Trying to use one template to build 100+ applications without the possibility of pinning the template to a specific version on an application by application basis is setting yourself up for a nightmare at some point in the future, when the template changes in such a way that it's no longer valid for a subset of your 100 applications.


text:
Q: Neo4j Blueprints vs Native Traversal Speed . . I am doing a performance test of neo4j's traversal speed between neo4j's blueprints and native implementation. I have created a graph of 1000 nodes with 1 node per level i.e.
O->O->O->O->. . . .->O
I have recorded an iteration (for loop code) time of 90ms, 93ms and 79ms (ran 3 times) using this blueprints code:
Iterable<Vertex> vertices = testGraph.getVertices();

//Code block which was measured.
for(Vertex vertex : vertices){};

and using native code 270ms, 268ms and 321ms:
Iterable<Node> nodes = Traversal.description().breadthFirst().relationships(CustomRelTypes.LINKED_TO, Direction.OUTGOING).evaluator(Evaluators.all()).traverse(rootNode).nodes();

//Code block which was measured.
for(Node node : nodes){}

I cant understand how is neo4j's blueprints implementation is faster. I havent done any special configuration for any one of them. Time is almost same for depthFirst too.
does anyone how i can speed up native performance to match blueprints'.
thank you.

A: Blueprints uses Neo4j's native getAllNodes() methods under the hood, not the traversal API:
https://github.com/tinkerpop/blueprints/blob/master/blueprints-neo4j-graph/src/main/java/com/tinkerpop/blueprints/impls/neo4j/Neo4jGraph.java#L339
So the equivalent native Neo4j Java code would be:
g = new EmbeddedGraphDatabase('/path/to/graph-dir');
g.getAllNodes();


text:
Q: Making and Angular form invalid when inputs aren't required I'm making a profile editor directly on the user's profile page in where I want to show a live preview of the changes they are making.
I'm basically updating the view using models attached to inputs and textareas.
Here is a preview, showing name, profile image, header image and a little blurb:

The idea is to update those live (not submitting as of yet) so the user can preview what they are doing before they save the changes.
So the issue I am running into is that, I don't want any of the fields to be required because I want them the have a choice to update their profile, so they can choose to update the profile image, header or text.
<div class="profile-editor" ng-if="name == '<?php echo $_SESSION['user']; ?>'">

{{profile.username}}

{{ updateProfileForm.blurbEdit.$valid ? editBlurb : profile.blurb }}

{{editBlurb}}

preview

    {{element.$valid}}

Update Profile

{{information}}

  <form role="form" name="updateProfileForm">
    <input name="backgroundUrl" class="edit-name-input" type="text" ng-model="editPhoto" placeholder="paste new photo url">

    <input name="photoUrl" class="edit-photo-input" type="text" ng-model="editBackground" placeholder="paste new background url">

    <textarea name="blurbEdit" class="edit-blurb" name="" id="" cols="30" rows="10" ng-model="editBlurb" placeholder="NEW BLURB"></textarea>

    <button ng-click="updateProfile(editPhoto,editBackground,editBlurb)" class="save-profile">save profile</button>
  </form>

However, in doing so, since they aren't required, angular is saying the form is valid on load (which is technically correct) but what happens is my view gets changed and shows nothing because the fields show as valid:

How would I approach this?

A: The easiest solution could be to provide the user a form already filled with the current values.

A: For me, I would set the defaults in the data up front, likely in the controller. I'd define the object or property, check if there was a set value, and if not I'd assign the default. Then, I'd just share the references to the model across the editable and display points on your view.
ng-model="profileBackground"`, for example.`

This may not seem entirely useful here, but it opens you up to watching those values from other sources. If the model changes in one place, it's easier for the rest to follow along with the updated info.


text:
Q: Codeigniter safe queries and xss clean I try to remake methods which got queries from ids to methods which work with slugs.
So basically this:
public function view($id)
{
 $id = (int)$id;
 $this->db->where('id', $id)->get('recipes')
}

To this:
public function view($slug)
{
   $this->db->where('slug', $slug)->get('recipes')
}

In the second method I'm aware that this is a xss not safe. I think that it will be best to remake all queries with query bindings.
Like so:
$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$this->db->query($sql, array(3, 'live', 'Rick'));

But I have too munch queries to remake is it possible to have some function whic to clean the slug from the codeigniter or something in the second method example?
Is it ok to use the security xss-clean method to the slug before to use it in the query:
$this->security->xss_clean($slug)

A: I guess all insert or update data come from a form, if you go to application/config/config.php and set
$config['csrf_protection'] = FASLE;

to
$config['csrf_protection'] = TRUE;

this helpyou to filter all inputs (xss_clean)

A: public function view($slug)
{
   $slug_new=$this->db->escape_str(trim($slug));
   $this->db->where('slug', $slug_new)->get('recipes')
}


text:
Q: How to restart another agent in the pipeline which I want to use later I have two jobs in my pipeline job1 executed with agent A1 and Job2 with with A2. Both A1 and A2 running as service on the same machine. I will be change environment variable in Job1 and it needs to restart agent2. Restarting agents sometime askes credentials. So I need to provide credentials at the time of restart
So How can I restart a service? I tried PowerShell and batch file. Both failing to restart the service. Any help?
Here are few ways I tried:

*

*With gwmi

$UserName = 'domain\username'
$Password = 'mypassword'
$ServiceName = "name='AgentName'"

$svc = gwmi win32_service -filter $ServiceName
Write-Host $svc.Name
$svc.StopService()
$svc.change($null,$null,$null,$null,$null,$null,$UserName,$Password,$null,$null,$null)
$result = $svc.StartService()

*Batch file:

net stop "servicename"
sc.exe config "servicename" obj="domain\username" password="mypwd"
net start "servicename"

*With Set-Service

$UserName = 'domain\user'
$Password = 'mypassword'
$Credential = New-Object System.Management.Automation.PSCredential ($UserName,$Password)

$ServiceName = 'servicename'

Set-Service -Name $ServiceName -Status Stopped

Set-Service -Name $ServiceName -Credential $Credential

Set-Service -Name $ServiceName -Status Running

all options fail because of credentials. If I try from UI it works.
As I need to automate the process, want to run as part of pipeline.
Where am I going wrong?


text:
Q: Change Bootstrap progress bar dynamically I have the following HTML code, using Bootstrap:

I want style="width: 0" to increase until it is 100%. I tried to use the code below as a test, but nothing happened.

    <title>Verifying Oracle database...</title>

    <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">

Can someone help to make this progress happen?
Thanks in advance.

A: The code you use to update width is correct, but as @Brennan pointed out it has to run after the progress bar is rendered - e.g. by placing the script tag after the progress bar tag (fiddle) or by running it in the document ready handler (fiddle).
The following is the minimal version which does what you tried (the fiddles emulate progress running from 0 to 100):
$(function() {
     $("#progress-bar").css("width", "50%");
});

Another note on the code: along with the width of the progress bar you should update the aria-valuenow attribute which represents the current value of a range widget (here the progress bar) for the assistive technology browsers. In your sample you have aria-valuenow 45 but width 0, which is inconsistent.


text:
Q: Working with large primes in Python What is an efficient way for working with large prime numbers with Python? You search on here or on google, and you find many different methods for doing so... sieves, primality test algorithms... Which ways work for larger primes?

A: For determining if a number is a prime, there a sieves and primality tests.
# for large numbers, xrange will throw an error.
# OverflowError: Python int too large to convert to C long
# to get over this:

def mrange(start, stop, step):
    while start < stop:
        yield start
        start += step

# benchmarked on an old single-core system with 2GB RAM.

from math import sqrt

def is_prime(num):
    if num == 2:
        return True
    if (num < 2) or (num % 2 == 0):
        return False
    return all(num % i for i in mrange(3, int(sqrt(num)) + 1, 2))

# benchmark is_prime(100**10-1) using mrange
# 10000 calls, 53191 per second.
# 60006 function calls in 0.190 seconds.

This seems to be the fastest. There is another version using not any that you see,
def is_prime(num)
    # ...
    return not any(num % i == 0 for i in mrange(3, int(sqrt(num)) + 1, 2))

However, in the benchmarks I got 70006 function calls in 0.272 seconds. over the use of all 60006 function calls in 0.190 seconds. while testing if 100**10-1 was prime.
If you're needing to find the next highest prime, this method will not work for you. You need to go with a primality test, I have found the Miller-Rabin algorithm to be a good choice. It is a little slower the Fermat method, but more accurate against pseudoprimes. Using the above mentioned method takes +5 minutes on this system.
Miller-Rabin algorithm:
from random import randrange
def is_prime(n, k=10):
    if n == 2:
        return True
    if not n & 1:
        return False

    def check(a, s, d, n):
        x = pow(a, d, n)
        if x == 1:
            return True
        for i in xrange(s - 1):
            if x == n - 1:
                return True
            x = pow(x, 2, n)
        return x == n - 1

    s = 0
    d = n - 1

    while d % 2 == 0:
        d >>= 1
        s += 1

    for i in xrange(k):
        a = randrange(2, n - 1)
        if not check(a, s, d, n):
            return False
    return True

Fermat algoithm:
def is_prime(num):
    if num == 2:
        return True
    if not num & 1:
        return False
    return pow(2, num-1, num) == 1

To get the next highest prime:
def next_prime(num):
    if (not num & 1) and (num != 2):
        num += 1
    if is_prime(num):
        num += 2
    while True:
        if is_prime(num):
            break
        num += 2
    return num

print next_prime(100**10-1) # returns `100000000000000000039`

# benchmark next_prime(100**10-1) using Miller-Rabin algorithm.
1000 calls, 337 per second.
258669 function calls in 2.971 seconds

Using the Fermat test, we got a benchmark of 45006 function calls in 0.885 seconds., but you run a higher chance of pseudoprimes.
So, if just needing to check if a number is prime or not, the first method for is_prime works just fine. It is the fastest, if you use the mrange method with it.
Ideally, you would want to store the primes generated by next_prime and just read from that.
For example, using next_prime with the Miller-Rabin algorithm:
print next_prime(10^301)

# prints in 2.9s on the old single-core system, opposed to fermat's 2.8s
1000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000531

You wouldn't be able to do this with return all(num % i for i in mrange(3, int(sqrt(num)) + 1, 2)) in a timely fashion. I can't even do it on this old system.
And to be sure that next_prime(10^301) and Miller-Rabin yields a correct value, this was also tested using the Fermat and the Solovay-Strassen algorithms.
See: fermat.py, miller_rabin.py, and solovay_strassen.py on gist.github.com
Edit: Fixed a bug in next_prime

A: I have written two articles on this, along with benchmarks, to see what methods are faster.
Prime Numbers with Python was written before the knowledge of the Baillie-PSW primality test.
Prime Numbers with Python v2 was written afterwards, benchmarking the Lucas pseudoprimes and the Baillie-PSW primality test.

A: In response to the possible inaccuracy of math.sqrt I have benchmarked two different methods for performing an isqrt(n) call. isqrt_2(n) is coming from this article and this C code
The most common method seen:
def isqrt_1(n):
    x = n
    while True:
        y = (n // x + x) // 2
        if x <= y:
            return x
        x = y

cProfile.run('isqrt_2(10**308)')

Benchmark results:
isqrt_1 at 10000 iterations: 12.25
Can perform 816 calls per second.

         10006 function calls in 12.904 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000   12.904   12.904 <string>:1(<module>)
        1    0.690    0.690   12.904   12.904 math.py:10(func)
    10000   12.213    0.001   12.213    0.001 math.py:24(isqrt_1)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        1    0.000    0.000    0.000    0.000 {range}
        2    0.000    0.000    0.000    0.000 {time.time}

This method is incredibly slow. So we try the next method:
def isqrt_2(n):
    if n < 0:
        raise ValueError('Square root is not defined for negative numbers.')
    x = int(n)
   if x == 0:
        return 0
    a, b = divmod(x.bit_length(), 2)
    n = 2 ** (a + b)
    while True:
        y = (n + x // n) >> 1
        if y >= n:
            return n
        n = y

cProfile.run('isqrt_2(10**308)')

Benchmark results:
isqrt_2 at 10000 iterations: 0.391000032425
Can perform 25575 calls per second.

         30006 function calls in 1.059 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    1.059    1.059 <string>:1(<module>)
        1    0.687    0.687    1.059    1.059 math.py:10(func)
    10000    0.348    0.000    0.372    0.000 math.py:34(isqrt_2)
    10000    0.013    0.000    0.013    0.000 {divmod}
    10000    0.011    0.000    0.011    0.000 {method 'bit_length' of 'long' objects}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        1    0.000    0.000    0.000    0.000 {range}
        2    0.000    0.000    0.000    0.000 {time.time}

As you can see, the difference in isqrt_1(n) and isqrt_2(n) is an amazing 11.858999967575 seconds faster.
You can see this in action on Ideone.com or get the code
note: Ideone.com resulted in execution timeout for isqrt_1(n) so the benchmark was reduced to 10**200


text:
Q: CDialog *m_pages[6]; vs CDialog *m_pages = new CDialog[6];? Not sure why I can't take CDialog and set the memory space in the cpp file.  It only works in the header file.   Isn't this the same thing???  thanks

Header file:
public:
    CDialog *m_pages[6];  // this works

Header file:
CDialog *m_pages;

cpp file
m_pages = new CDialog[6];  //this fails

After seeing what I did wrong(1st poster: "creating an array of six pointers to CDialog").
This is what I missed: (and now it works!)
CDialog **m_pages = new CDialog*[6]; //double pointer

A: Check the documentation. CDialogs require at least one parameter in their constructor, that's why you can't allocate them in your second example, since they don't have a default constructor.
In your first example, you're creating an array of six pointers to CDialog. That is completely different from an array of six CDialog, which is what you are trying to allocate in the second one.

A: Those decls are very different: this CDialog *m_pages[6]; is an array of 6 pointers to CDialog, while m_pages = new CDialog[6]; it's an array of 6 CDialog.
To use the second declaration, I think you could do something like
#include <iostream>
using namespace std;

struct Object  {
    Object(int id) : id(id) {}
    int id;
};

void main_construct_vector()
{
    Object *a = new Object[2] {Object(1), Object(2)};
    cout << a[0].id << ' ' << a[1].id << endl;
}

That code output as expected
1 2

Definitely, this is not the usual way to go...


text:
Q: How to change a file path in xcode 4? I have a project where a couple of files are in red, In XCode 3 I used to click the file Get Info and change the Path, but I have no idea how to do it in the new XCode 4.

A: Click on your file, and then open the right side pane (there is a button in the top right corner). There you will see Identity and Type. Under the location drop down there is a small icon of I'm not sure what. If you click it, it lets you choose a file. I think that is what you want.

A: My method of choice is to just drag in the files from the new location and delete the references to the ones in the old location.


text:
Q: Delphi function to C# I'm trying to convert this Delphi code to C#
function TWebModule1.DecodeA(Auth: string): Word;
var
  iAuth: Cardinal;
  r: Cardinal;
begin
  iAuth := StrToInt64(Auth);
  r := (iAuth and $FFFF0000) shr 16;
  Result := (iAuth and $FFFF) xor r xor $9752;
end;

Here is what I have written in C# but it's not giving me the expected results.
private Int64 DecodeA(Int64 auth)
{
    try
    {
        var r = (auth & 0xFFFF0000) >> 16;
        var result = (auth & 0xFFFF) ^ r ^ 0x9752;
        _log.DebugFormat("Decoding of {0} returned {1}", auth, result);
        return result;
    }
    catch (Exception ex)
    {
        _log.Fatal(ex);
        throw new Exception(ex.Message);
    }
}

Example:auth = 3216841950 should have a result of 41022
Thank you for any information you provide.

A: If you use the same datatypes in both languages then it works just out of the box:
Delphi version
function DecodeA(iAuth: Int64): Int64;
var
  r: Int64;
begin
  r := (iAuth and $FFFF0000) shr 16;
  Result := (iAuth and $FFFF) xor r xor $9752;
end;

C# version
private Int64 DecodeA(Int64 iAuth)
{
    Int64 r = (iAuth & 0xFFFF0000) >> 16;
    return (iAuth & 0xFFFF) ^ r ^ 0x9752;
}

In both languages DecodeA(3216841950) equals 13361

A: The key understanding this it to know why the Delphi developer chose to use StrToInt64 considering that the rest of the code operates on 32 bit integers. The reason for this is that StrToInt returns a signed 32 bit integer, and so for values in the range 2^31 to 2^32 - 1 results in an error. The developer of the original Delphi code handled this by treating the input as a 64 bit integer, a data type that includes the complete range of a 32 bit unsigned type.
Now, in your C# code you can translate it very literally, but you don't need to use 64 bit types, just as the Delphi code does not. The Delphi code operates on 32 bit unsigned integers, and returns a 16 bit unsigned integer.
ushort DecodeA(uint iauth)
{
    uint r = (iauth & 0xffff0000) >> 16;
    return (ushort) (iauth & 0xffff) ^ r ^ 0x9752;
}

ushort DecodeA(string auth)
{
    return DecodeA(uint.Parse(auth));
}

Here I have provided two overloads, one for string input which parses the string, and one receives an unsigned 32 bit integer as input. The former calls the latter.
Note that I have followed the lead of the Delphi code and returned a 16 bit unsigned integer, ushort.


text:
Q: Sample size effects comparision of correlations I have 2 datasets data1 and data2 (these are 2 different canals on television) that each contains promotion and new_users. So head(data1) gives
promotion    new_users
22                  23
4                    6
...

The same goes for data2. Now we notice that dim(data1) = 3119 2 and dim(data2) = 25488 2 so we have much more data on the second canal because we simply had more promotion-insertions on it.
I want to test if new_users correlate with promotion for data1 and data2. In R I have done this:
cor.test(data1$promotion, data1$new_users, alternative="greater",method="pearson")

and similar for the second dataset
cor.test(data2$promotion, data2$new_users, alternative="greater",method="pearson")

which both gives very low p-values which means that we have a positive correlation for both canals.
I want to compare the 2 correlations (the correlation for the first canal data1 and the second canal data2). I do this in R using Fisher's Correlation-test, where I get a p-value higher than 0.05 meaning that the positive correlation in canal 2 is significantly higher than the positive correlation in canal 1.
Is this a valid conclusion when the size of the two datasets is so different? data1 don't contains so much data as data2 - or does the size of the datasets even matter?
Thanks.

A: If you look at the formula for comparing two correlations using Fisher's hyperbolic arc tangent transformation you will see that it involves something like
Defining $z_i$ as $\tanh^{-1}{r_i}$ and $n_i$ as sample size for $i=1,2$
$$
   sdz = \sqrt{\frac{1}{n_1 - 3} + \frac{1}{(n_2 - 3)}}
$$
and
$$
   z = \frac{z_1 - z_2}{sdz}
$$
So you can see that the sample size has already been incorporated into the calculations.


text:
Q: The Values are not being populated when jumping to another view I'm learning Angular JS I'm I.m making a simple application that should start with a list of persons and when the user clicks in "Update User" it should be redirected to an edit page, which the data should be populated, which is not happening. Here is my code:
HTML of the starting page:

var app = angular.module('app', ['ngRoute']);

app.config(['$routeProvider', function ($routeProvider, $locationProvider) {

    $routeProvider
        .when('/listview',
            {
                controller: 'SimpleController',
                templateUrl: 'Partials/ListView.html'
            })
        .when('/tableview',
            {
                controller: 'SimpleController',
                templateUrl: 'Partials/TableView.html'
            })
        .when('/edit/:id',
            {
                controller: 'EditCtrl',
                templateUrl: 'Partials/Edit.html'
            })
        .otherwise({ redirectTo: '/listview' });
}]);

app.controller('EditCtrl', function ($scope, $location, $routeParams) {
    $scope.details = $scope.persons[$routeParams.id];

    $scope.save = function () {
        $location.path('/');
    };
});

app.controller('SimpleController', function ($scope) {
    $scope.persons = [{ name: 'Tiago', city: 'Lisbon', age: 26 },
                      { name: 'Ecem', city: 'Antalya', age: 24 },
                      { name: 'Derya', city: 'Istambul', age: 24 }
    ];
});
<!DOCTYPE html>

    <title>Galaksiyia - TableView</title>

            Index
            Name
            City
            Age

            {{$index}}
            {{details.name}}
            {{details.city}}
            {{details.age}}
            Update User

And the Html of the Edit page is:

<!DOCTYPE html>

    <title>Galaksiyia - Edit Page</title>

    <form>
        <input type="text" ng-model="details.name" placeholder="Name" />

        <input type="text" ng-model="details.city" placeholder="City" />

        <input type="text" ng-model="details.age" placeholder="Age" />

        <button ng-click="save()">Update User</button>
    </form>

Also, when the Save button is clicked nothing happening, and according with the code the user should be redirected to the Main Page.

A: A quick solution to your proplem is to put the data (that must be available in two controllers) into the $rootScope
app.controller('SimpleController', function ($scope) {
    $rootScope.persons = [{ name: 'Tiago', city: 'Lisbon', age: 26 },
                      { name: 'Ecem', city: 'Antalya', age: 24 },
                      { name: 'Derya', city: 'Istambul', age: 24 }
    ];
});

A better solution is to write a service (factory) and to get the data from that service.


text:
Q: gatsbyjs - should I use GraphQL or not for images? I am trying to use Saasland template into gatsby. I am new to gatsby and new to graphql  as well.
layout.js
import 'bootstrap/dist/css/bootstrap.min.css'
import "./layout.module.css"

layout.module.css has all the style classes from Saasland template. For images the css has:
background: url("../images/home5/shap_tecture.png")

I am already facing an issue with loading these images on a component (page).
From my previous question, I was told to follow https://www.gatsbyjs.org/docs/working-with-images/ to deal with images.
So, How can I use GraphQL for images that are referenced in css as shown above ? Do I need to write a query for each image ?


text:
Q: CoreData: How to correctly use migratePersistentStore to create a backup copy I'm really struggling with this. I'm trying to create a backup of my active core data base. According to Apple the best option is not to use the File Manager but the method migratePersistentStore. However I don't really understand this. I have my PersistentStoreCoordinator in my AppDelegate. So if I'm migrating the persistent store my coordinator will lose it after successfully moving it correctly? So the store is now just at the new location but not at the old anymore? So do you have any example program code for this of how my app still could keep running with the original copy?
Or can't i just copy all files using the filemanager with the same prefix instead of migrating?! So much easier...

A: You can create a separate NSPersistentStoreCoordinator for migration only, and continue using your regular one for CoreData stack. Also you can use NSMigrationManager for migration:
NSMigrationManager* manager = [[NSMigrationManager alloc] initWithSourceModel:sourceModel
                                                             destinationModel:targetModel];

BOOL migratedSuccessfully = [manager migrateStoreFromURL:sourceStoreURL
                                                    type:type
                                                 options:nil
                                        withMappingModel:mappingModel
                                        toDestinationURL:destinationStoreURL
                                         destinationType:type
                                      destinationOptions:nil
                                                   error:error];

Also I'm not sure you can migrate when your DB is opened, probably you'll need to lock it or something.


text:
Q: PowerShell script to create hundreds of sub sites What's the best way to create hundreds of sub sites in a site collection for testing purposes?  It doesn't matter what their names are.  Doing some research, I found a few scripts that either require that I enter each site's name or that I use an xml file that would still involve me manually entering hundreds of unique names for each sub site.  I would just need the sub sites to automatically be named test1, test2, or follow some kind of similar pattern.  There has to be some way to leverage the New-SPWeb cmdlet with a for loop maybe?  Can it be done without using a config or csv file?

A: Below script accepts the array of the sub sites name, But you can amend it instead of passing the SubSIte name arrays just add test(i)...i mean in the for loop instead of checking the array's count, check fix the number of subsite($i <100000)...then susbite url will be like this
$SiteUrl = $SiteCollectionURL + "/test" +$i

. Copy and Paste the code below and save it as CreateSubSite.ps1, see highlighted yellow sections to change configurable values:
Add-PsSnapin Microsoft.SharePoint.PowerShell

## SharePoint DLL
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

#Creating Sub Sites in top site collection.
Write-Output " "
Write-Output "Creating Sub Sites"

$SiteCollectionURL = "http://localhost/sites/SPFix"

$SiteCollectionTemplate = "STS#0"

$SiteCollectionLanguage = 1033

$SubSites = @("Central Services", "Knowledge Base", "Service Center", "IT", "HR", "Finance")

for($i=0 ; $i -lt $SubSites.count ; $i++)
{
$SiteUrl = ""
$SiteUrl = $SiteCollectionURL + "/"
$SiteUrl = $SiteUrl += $SubSites[$i]
Write-Output " "
#Write-Output "Creating Site for " += $SubSites[$i]
Write-Output " "
New-SPWeb $SiteUrl -Template $SiteCollectionTemplate -Name $SubSites[$i]  -UseParentTopNav -Language $SiteCollectionLanguage
Write-Output " "
#Write-Output "Site Created for " += $SubSites[$i]
Write-Output " "
}

Remove-PsSnapin Microsoft.SharePoint.PowerShell

http://www.sharepointfix.com/2011/04/powershell-script-to-create-subsites.html

A: The basic syntax for creating site would be New-SPSite -Url $WebSiteUrl -OwnerAlias $SiteOwner -Name "Store" -Template $webTemplate
 and creating subsite `New-SPWeb -Url $WebSiteUrl -OwnerAlias $SiteOwner -Name "Store" -Template $webTemplate.
Now for your requirement I think you have to use some kind of loop and call the above syntax for that many times.
Refer this question on syntax site-provisioning-example       `


text:
Q: java.io.IOException: No such file or directory I am encountering an issue to save/ create the file using java.
java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method) ~[na:1.7.0_79]

My environment is using Linux but having a mount on Windows (The place where I try to store the file).
It will hit everytime I tried to create when the filename having a chinese characters.
Could this happen because of encoding between Linux and Windows difference?
When I tried running and storing in similar OS (run apps in Linux, storing in Linux, same thing for windows) it run smoothly.
Any help is very appreciated.
The code i used to create the file
        File imgPath = new File(fullpath.toString());

        if (!imgPath.exists()){
            FileUtils.forceMkdir(imgPath);
            imgPath.setWritable(true, false);
        }

        fullpath.append(File.separator).append(fileName);

        outputStream = new FileOutputStream(new File(fullpath.toString()));

Thanks a lot.

A: Note: I'm a fairly new user and can't comment directly yet (only on my questions and answers so far), so I'm posting this as an answer.
Windows uses UTF-16 while Linux uses UTF-8; (considering that you haven't installed anything extra to change anything yet) UTF-8 and UTF-16 support the same range of characters. However, I remember correctly,  it had something to do with memory (UTF-8 starts at 8 bits and UTF-16 starts at 16?). Regardless, they're stored/ read a little differently. And then, InputStreamReader converts characters from their external representation in the specified encoding to the internal representation. It's mentioned in this stackoverflow post (Difference between UTF-8 and UTF-16?) about the exact way it's done in bytes.  They're the same for the basics, but different for others, like Chinese characters. would suggest looking for solutions along that line (I have to get to class!). I could be entirely wrong, but this is probably a good starting place. Good luck.


text:
Q: How to convert date to display properly in user form? When entering the date in a new record, the "Date Transferred" field is formatted for mm/dd/yyyy. When the same date filed is displayed it is showing as a string, "42353", instead of "12/15/2015".
Example of Current Code =
Private Sub Will18_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    If Will18 = vbEmptyString Then Exit Sub

    If IsDate(Will18) Then
        txtDateTxfr = Format(Will18, "mm/dd/yyyy")
    Else
        MsgBox "Please enter a valid date mm/dd/yyyy", vbCritical
    End If
End Sub

Would like dates in 3 fields to show as "Date Received", "Date Removed" and "Date Transferred" to show as "mm/dd/yyyy" not string value.


text:
Q: Can I Pod XMPPFramework Without All of Its XEP Extension? I've been struggling for archiving my project recently. 2 hours passed and the archiving process still in Running 2 of 2 custom shell scripts phase.

Apparently, after looking into the Report Navigator, the root cause of this is because I am using XMPPFramework Pod and the archiving process took too long in running Copy Pods Resources custom shell script for one of XMPPFramework Extensions XEP (the one which I even don't use).

Then, I think I can get out from this trouble by disabling some XMPPFramework Extensions that I don't use.
So, with me using CocoaPods to install XMPPFramework to my project, can I remove XMPPFramework XEPs that I won't use? I only use 3 XEPs, not all of them.

A: Unfortunately you can't just install the XEP you want when using the pod.
You still have 2 options:
You can install the framework manually:
Up to date instructions on how to install XMPPFramework manually?
Or you can edit the XMPPFramework.h to use only the XEP you want, but I don't recommend this one.


text:
Q: MIPS - Are characters which are stored as bytes the same as those not stored as bytes? I'm new to MIPS and I'm just wondering, I store a space character in the following ways:
li $t0, ' '
lb $t1, ' '

la $t2, myArray  # load array
sb $t0, 0($t2)   # myArray[0] = ' '

In this case is $t0 == $t1? And is the sb instruction valid? What I'm a bit confused is whether or not I can use byte and ints(words) interchangeably.

A: The byte vs word is not freely interchangeable, because byte is only 8 bits of information, and word is 32 bits of information (on MIPS platform). So the byte can be set to 256 different possible values (28 combinations of eight 0/1 bit values), and word can be set to 2564 different possible values (pattern of 32 bits).
You need four bytes to store the same possible-amount of information like what you can fit into single word (8 bits * 4 = 32 bits).
But depending on the values you are processing, if you can guarantee their ranges, you can predict how the code converting values between byte/half-word/word will behave, whether some values will survive such conversions without any damage, or it needs extra validation/handling. For example if your input values are ASCII characters (from string), then those are only 7 bit (when interpreted as signed integers, only values 0 to +127 are defined in ASCII).
So for example li $t0, ' ' will assemble as li $t0, 32 (because the "space" character is encoded in computer as value 32) and because the li instruction takes as operant signed integer immediate.
Actually the "li" is not real MIPS instruction, but a convenience pseudo-instruction, the assembler will convert it into one/two native instructions to encode/compose the desired immediate value. Try for example li $t0, ... with values +1, -1, +65000, -65000 and watch in debugger how it gets assembled into different native instructions, achieving the desired "load immediate" effect, for example the -65000 value needs at least two native instructions to be composed.
So you are technically loading 32 bit (word) value into $t0 (even if the ' ' is only value 32 which fits easily into byte).
But as you know you did load the ASCII "space" into t0, no matter the t0 is 32 bits "wide", you know it is enough to store only "byte" into memory, if you are for example creating new string in buffer, and you want to put space character into it. So then sb $t0, 0($t2) is correct. Would you have some larger value in t0, the upper 24 bits are ignored, and only low 8 bits of that value are written into memory with sb instruction (effectively "truncating" that value in the memory, it's not possible to read back from memory the full value, only the truncated part).

The conversion in other direction will happen often too in MIPS assembly, because for example lb will read only 8 bits from memory, but it will sign-extend them into full register (32 bits). If you don't pay attention to your values, you may easily trap yourself like for example this:
.data
test_value: .byte 234
.text
    li      $t0, 234
    lb      $t1, test_value
    tne     $t0, $t1     # throw exception if t0 is not equal to t1
    # terminate normally when values are equal
    li      $v0, 10
    syscall

This may look at first read as there's value 234 compared against 234, and thus the program will normally terminate, but if you will try to run it, it will instead end with exception at the tne instruction. Because  the lb does sign-extend the value and 234 fits in 8 bits only when you interpret that bit pattern as "unsigned 8 bit integer", if you interpret the same bit pattern as "signed 8 bit integer", it becomes value -22. And -22 does not equal 234.
Would you change the lb instruction to lbu, which loads "unsigned byte", the code will work and exit normally, as the tne will compare 234 vs 234 values, which are equal.
So while programming in assembly, you should be definitely aware of type of data you process, and correctly extend/truncate those values as needed.
(BTW the MARS assembler will warn you about "234" not fitting "signed byte" and possible truncation - but values up to 255 actually do fit 8 bits, just need to be interpreted in "unsigned" way .. values above 255 will get truly truncated, like some bits are completely missing, for example .byte 1025 will store in memory only value 1)


text:
Q: RxJava Observable and retrofit API calls I am developing a simple github client that retrieves a list of repositories from a particular username.
I have this method in my activity:
private void subscribeRepos(Observable<List<Repository>> repository) {
    disposable.add(repository
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(new DisposableObserver<List<Repository>>() {
                @Override
                public void onComplete() {

                }

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                }

                @Override
                public void onNext(List<Repository> list) {
                    adapter.setItems(list);
                    System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>> onNext Called");
                }
            }));
}

This is my Retrofit service:
public class RetrofitService {

private static final String BASE_URL = "https://api.github.com/";
private RepoAPI repoAPI;
private static RetrofitService INSTANCE;

/**
 * Method that returns the instance
 * @return
 */
public static RetrofitService getInstance() {
    if (INSTANCE == null) {
        INSTANCE = new RetrofitService();
    }
    return INSTANCE;
}

private RetrofitService() {
    Retrofit mRetrofit = new Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .baseUrl(BASE_URL)
            .build();
    repoAPI = mRetrofit.create(RepoAPI.class);
}

/**
 * Method that returns the API
 * @return
 */
public RepoAPI getRepoApi() {
    return repoAPI;
}

}

And my RepoAPI interface
public interface RepoAPI {

@GET("/users/{user_name}/repos")
Observable<List<Repository>> getRepositories(@Path("user_name") String userName);

}

So, whenever I actively call subscribeRepos(mainViewModel.getRepositories("whateverusername")); onNext is triggered as expected. But if I manually create a new repository on my github account, onNext is not called. Shouldn't onNext be called anytime I add or remove a new repo on my github account?

A: This is not actually how reactive streams work with network requests using Retrofit.
With a network request, once you have subscribed for an event and you receive its data, that's it. The stream is completed (you can check this logging onComplete callback).
Although you can make operations like map, switch, concat, and others with it, it is not a "real time" subscription.
As said here: "Retrofit Network call with RxJava: Use Single : As our API will not give data in a pieces or multiple times. Instead it will emit everything in just one call. So, in case of Observable onCompleted() will follow as soon as onNext() happens."
If you want something (almost) real time you could schedule a job to make this api call every few minutes (or seconds, or any time period that you want). Be aware with data leaks and thread handling!


text:
Q: MySQL returning the wrong Date/Time I am receiving a date of 33/22/2014 12:00:00 AM when the date in the MySQL Database is 2014-03-22.  Can anyone tell me why it is returning a weird date? I am assuming it has to do with the Convert Zero Datetime.. but I am not entirely sure.
Code:
public MySqlDataReader readerDB(string strSelectStmnt)
{
    //initializing command
    var comm = new MySqlCommand(strSelectStmnt, conn);

    //datareader for reading values from table
    dr = comm.ExecuteReader();

    //return the information from that was gathered by the datareader
    return dr;
}

while (dr.Read())
{
    Console.WriteLine(Convert.ToString(dr.GetValue(0)));
    Console.WriteLine(Convert.ToString(dr.GetValue(1)));
    Console.WriteLine(Convert.ToString(dr.GetValue(2)));
}

My Connection String:
string MyConString = "Server=" + strIP + ";" +
                     "PORT=" + strPort + ";" +
                     "DATABASE=" + strDB + ";" +
                     "Persist Security Info=no;" +
                     "Convert Zero Datetime=True;" +
                     "username=" + strDBUID + ";" +
                     "password=" + strDBPWD + ";";

My Query:
var dr = db.readerDB("SELECT `trial_1_end` , `trial_2_end` , `permanent_end` FROM " +
                      DataTable + " WHERE item_name= '"+ strTmpSubscription +
                      "' AND username='" + User + "'AND password='" + Password + "'");

My Results (from a Console.WriteLine):
31/1/0001 12:00:00 AM
31/1/0001 12:00:00 AM
33/22/2014 12:00:00 AM
ANSWER:
    DateTime.ParseExact(dr.GetDateTime(0).ToString("dd/MM/yyyy"), "dd/MM/yyyy", null)

A: You can use the SqlDataReader method GetDateTime:
Console.WriteLine(dr.GetDateTime(0).ToString());

And you can as well give it your custom formatting like:
Console.WriteLine(dr.GetDateTime(0).ToString("dd/MM/yy H:mm:ss"));


text:
Q: Crear un slider con valores recogidos de una API PHP El caso es que estoy recogiendo en forma de lista los valores de una API. El UL está fuera del valor que recorre el array del API y dentro del array están los elementos de lista que recojo. Cada valor me recoge un div y me lo posiciona horizontalmente en 3 divs (cada uno corresponde a un LI que ha recogido del API). Entonces mi pregunta es; ¿cómo hacer alguna clase de slider para que me aparezcan los elementos de la api e ir pasándolos de tres en tres con flechas?.
El segundo valor recoge la imagen, el primero la URL y el tercero el título, y así se generan los elementos de lista. El código sería algo así.
El esquema cutre sería algo así, con botones que van pasando elementos de lista de tres en tres.

<?php
  echo '
';
    echo '
';
      foreach($data as $valor){
      echo '
';
        echo '
';
          echo 'API[2]->value.'">
          echo '
API[1]->value.'">'.$valor->API[3]->value.'
';
          echo '
';
          echo '
;
       }
     echo '
';
     echo '
';
?>

A: Existe una librería llamada owl-carousel que podrá venirte al pelo. Es la que suelo recomendar a la hora de hacer carouseles, que es lo que parece que necesitas. Te ahorra mucho trabajo y además tiene una muy fácil implementación.
Básicamente funciona con unas clases que debes asignar a tus elementos HTML para que los CSS de la librería hagan su magia y además también funciona con un objeto que debes construir con Jquery, para que los JS de la librería hagan la suya. Te pongo un ejemplo:
HTML

1

2

3

4

5

6

7

8

9

10

11

12

JQUERY
$('.owl-carousel').owlCarousel({
    loop:true,
    margin:10,
    nav:true,
    responsive:{
        0:{
            items:1
        },
        600:{
            items:3
        },
        1000:{
            items:5
        }
    }
})

Este es el ejemplo más sencillo de uso, al que llaman básico, pero tienes muchos más en la web oficial, además de una sencilla guía de instalación. Creo que su estructura se adapta perfectamente a lo que necesitas y que con un par de retoques en el código del ejemplo podrías conseguir lo que te propones.
Referencia: Owl-Carosusel2


text:
Q: Clickable HTML table executes MySQL insert statement (PHP, Possibly JavaScript) I've got a HTML table that's populated by a select query from a MySQL table (using the values First_name, Last_name, PhoneNumber).
What I need is for these rows to be clickable, and upon being clicked, executing an "Insert into receivers_table (ReceiverNumber) values (PhoneNumber from said row), how do I go about doing this?

A: Generally, you need to do two things:

*

*Make a server-side PHP page that performs the database operation.  In PHP, read the ReceiverNumber from $_POST or $_GET and put that value into a SQL query, using your choice of SQL library.  (In production, make sure you sanitize/validate the value to prevent SQL injection.)
$phonenum = $_POST['PhoneNumber'];
//do validation, submit SQL query to DB...

*Bind click event handlers to the table rows that make an Ajax call to the PHP page you created.  You can do this easily in jQuery (assuming the <tr> tags are in a table with ID "receivertable" and the <td> cells with the numbers have the class "recnum"):
$("#receivertable tr").bind("click", function() {
    $.post('newreceiver.php', {
        PhoneNumber: $(this).children("td.recnum").text()
    });
});

If you're not using jQuery, you can use addEventListener("click", function(){...}) on your table rows and create an XMLHttpRequest object to perform the Ajax call.  Getting the data from the table row is done via DOM traversal, e.g, document.getElementById("receivertable").childNodes[2].textContent.


text:
Q: Populating react component results in "TypeError: Cannot read property 'map' of undefined" I'm trying to have a component populate with the results being returned from a GET request. The PageList component is below:
PageList.js
import React from 'react';
import Page from './Page';

const PageList = props => {
    return (

Your Pages:

            {props.pages.map(page => {
                return <Page page={page} key={page.id} />;
            })}

    );
};
export default PageList

When loading the page with this component, I get the error TypeError: Cannot read property 'map' of undefined. I imagine this is because the pages prop isn't correctly being passed to PageList from the actions and reducers? Not sure what I'm missing.
I'm mapping state to props in the following way in the container component that PageList sits in:
export default connect(
    mapStateToProps,
    {
        fetchPages,
        sendURL
    }
)(TestScraperFormContainer);

Here is the fetchPages action fxn:
export const fetchPages = () => {
    return dispatch => {
        dispatch({ type: FETCHING_PAGES });
        axios
            .get('*endpoint removed from post*', {
                headers: headers
            })
            .then(response => {
                dispatch({ type: PAGES_FETCHED, payload: response.data });
            })
            .catch(err => {
                console.log(err);
                dispatch({ type: PAGES_FETCH_ERROR });
            });
    };
};

and here is the respective reducer logic:
export const testScraperFormReducers = (state = initialState, action) => {
    switch (action.type) {
        case FETCHING_PAGES:
            return { ...state, fetchingPages: true };
        case PAGES_FETCHED:
            return {
                ...state,
                pages: action.payload,
                fetchingPages: false,
                pagesFetched: true
            };
        case PAGES_FETCH_ERROR:
            return {
                ...state,
                error: 'Error fetching pages'
            };
        default:
            return state;
    }
};

A: What do you get when you print your response?
then(response => { console.log(response)}

A: I suppose that you need to connect your reducer to PageList function because it doesn't know what is props.pages.
You should try something like this:
function mapStateToProps(state) {
  return {
    pages: state.pages
  }
}

export default connect(mapStateToProps)(PageList);

A: Probably state.pages is undefined initially, because reducer initial state dont have pages set as [];
Setting initialState = {pages: []} in reducer might solve this;


text:
Q: How to declare a byte array in Scala? In Scala, I can declare a byte array this way
val ipaddr: Array[Byte] = Array(192.toByte, 168.toByte, 1.toByte, 9.toByte)

This is too verbose. Is there a simpler way to declare a Byte array, similar to Java's
byte[] ipaddr = {192, 168, 1, 1};

Note that the following results in an error due to the . in the String
InetAddress.getByAddress("192.168.1.1".toByte)

A: I believe the shortest you can do is
val ipaddr = Array[Byte](192.toByte, 168.toByte, 1, 9)

You have to convert 192 and 168 to bytes because they are not valid byte literals as they are outside the range of signed bytes ([-128, 127]).
Note that the same goes for Java, the following gives a compile error:
byte[] ipaddr = {192, 168, 1, 1};

You have to cast 192 and 168 to bytes:
byte[] ipaddr = {(byte)192, (byte)168, 1, 1};

A: How about Array(192, 168, 1, 1).map(_.toByte)?

A: For your specific example you could simply use InetAddress.getByName instead:
InetAddress.getByName("192.168.1.1")

In general Didier is right, Bytes are -128 to 127, so this works:
Array[Byte](1,2,3)

but this doesn't:
Array[Byte](192, 168, 1, 1)

A: By adding methods to StringContext one can easily define various methods for converting String literals into Byte arrays. For example, we can do this:
val bytes = ip"192.168.1.15"

or this:
val bytes = hexdump"742d 6761 2e00 6f6e 6574 672e 756e 622e"

Notice that it is especially useful for working with byte arrays in hexadecimal notation, because writing out the "0x" prefix in front of every byte can become very annoying very quickly, as can be seen in this example. When using hexadecimal notation as in Array(0xAB, 0xCD, 0xEF).map(_.toByte), it's not the call to map that is awkward, it's the repeated "0x"-prefix that generates all the noise.
Here is a little code snippet that shows how several different ways for byte array creation could be implemented by providing an implicit class that wraps a StringContext:
implicit class ByteContext(private val sc: StringContext) {

  /** Shortcut to the list of parts passed as separate
    * string pieces.
    */
  private val parts: List[String] = sc.parts.toList

  /** Parses an array of bytes from the input of a `StringContext`.
    *
    * Applies `preprocess` and `separate` and finally `parseByte`
    * to every string part.
    * Applies `parseByte` to every vararg and interleaves the
    * resulting bytes with the bytes from the string parts.
    *
    * @param preprocess a string preprocessing step applied to every string part
    * @param separate a way to separate a preprocessed string part into substrings for individual bytes
    * @param parseByte function used to parse a byte from a string
    * @param args varargs passed to the `StringContext`
    * @return parsed byte array
    *
    * Uses a mutable `ListBuffer` internally to accumulate
    * the results.
    */

  private def parseBytes(
    preprocess: String => String,
    separate: String => Array[String],
    parseByte: String => Byte
  )(args: Any*): Array[Byte] = {

    import scala.collection.mutable.ListBuffer
    val buf = ListBuffer.empty[Byte]

    def partToBytes(part: String): Unit = {
      val preprocessed = preprocess(part)
      if (!preprocessed.isEmpty) {
        separate(preprocessed).foreach(s => buf += parseByte(s))
      }
    }

    // parse all arguments, convert them to bytes,
    // interleave them with the string-parts
    for ((strPart, arg) <- parts.init.zip(args)) {
      partToBytes(strPart)
      val argAsByte = arg match {
        case i: Int => i.toByte
        case s: Short => s.toByte
        case l: Long => l.toByte
        case b: Byte => b
        case c: Char => c.toByte
        case str: String =>  parseByte(str)
        case sthElse => throw new IllegalArgumentException(
          s"Failed to parse byte array, could not convert argument to byte: '$sthElse'"
        )
      }
      buf += argAsByte
    }

    // add bytes from the last part
    partToBytes(parts.last)

    buf.toArray
  }

  /** Parses comma-separated bytes in hexadecimal format (without 0x-prefix),
    * e.g. "7F,80,AB,CD".
    */
  def hexBytes(args: Any*): Array[Byte] = parseBytes(
    s => s.replaceAll("^,", "").replaceAll(",$", ""), // ,AB,CD, -> AB,CD
    _.split(","),
    s => Integer.parseInt(s, 16).toByte
  )(args: _*)

  /** Parses decimal unsigned bytes (0-255) separated by periods,
    * e.g. "127.0.0.1".
    */
  def ip(args: Any*): Array[Byte] = parseBytes(
    s => s.replaceAll("^[.]", "").replaceAll("[.]$", ""), // .1.1. -> 1.1
    _.split("[.]"),
    s => Integer.parseInt(s, 10).toByte
  )(args:_*)

  /** Parses byte arrays from hexadecimal representation with possible
    * spaces, expects each byte to be represented by exactly two characters,
    * e.g.
    * "742d 6761 2e00 6f6e 6574 672e 756e 622e".
    */
  def hexdump(args: Any*): Array[Byte] = parseBytes(
    s => s.replaceAll(" ", ""),
    _.grouped(2).toArray,
    s => Integer.parseInt(s, 16).toByte
  )(args: _*)

  /** Parses decimal unsigned bytes (0-255) separated by commas,
    * e.g. "127.0.0.1".
    */
  def decBytes(args: Any*): Array[Byte] = parseBytes(
    s => s.replaceAll("^,", "").replaceAll(",$", ""), // ,127, -> 127
    _.split(","),
    s => Integer.parseInt(s, 10).toByte
  )(args:_*)
}

As soon as this class is in the implicit scope, we can use all of the following notations to define byte arrays:
  def printBytes(bytes: Array[Byte]) =
    println(bytes.map(b => "%02X".format(b)).mkString("[",",","]"))

  // bunch of variables to be inserted in the strings
  val a: Int = 192
  val b: Long = 168L
  val c: Byte = 1.toByte
  val d: String = "0F"
  val e: String = "15"

  printBytes(ip"192.168.1.15")
  printBytes(ip"192.$b.1.$e")
  printBytes(ip"$a.$b.$c.$e")
  printBytes(hexBytes"C0,A8,01,0F")
  printBytes(hexBytes"C0,$b,$c,0F")
  printBytes(hexBytes"$a,$b,$c,0F")
  printBytes(decBytes"192,$b,1,15")
  printBytes(decBytes"192,168,$c,$e")
  printBytes(decBytes"$a,$b,1,$e")
  printBytes(hexdump"C0A8 010F")
  printBytes(hexdump"$a $b $c $d")
  printBytes(hexdump"C0 $b 01 $d")

Note that the string literals can also contain references to variables using the $varargVar syntax inside of the string. All examples generate the same byte array [C0,A8,01,0F].
On performance: all of the above is build around method calls, the literals are not transformed to byte-arrays at compile time.

A: You can use implicit

    implicit def int2byte(int: Int) = {
      int.toByte
    }

And that will convert all Int values in scope in places where byte is required.

A: split on a String could do the trick:
val ipaddr: Array[Byte] =
  "192.168.1.1".split('.').map(_.toInt).map(_.toByte)

Breaking this down we have
"192.168.1.1"
  .split('.')    // Array[String]("192", "168", "1", "1")
  .map(_.toInt)  // Array[Int](192, 168, 1, 1)
  .map(_.toByte) // Array[Byte](-64, -88, 1, 1)

A: To expand on Chris Martin's answer, if you're feeling lazy and like you don't want to type out Array(...).map(_.toByte) over and over again, you can always write a variadic function:
def toBytes(xs: Int*) = xs.map(_.toByte).toArray

Now you can declare your byte array just about as concisely as in Java:
val bytes = toBytes(192, 168, 1, 1) // Array[Byte](-64, -88, 1, 1)


text:
Q: Measuring the complexity of a knot by minimum number of simplices to tile the complement
This is essentially a duplicate of: Lower bound on number of tetrahedra needed to triangulate a knot complement

Suppose a knot $K\subseteq\mathbb S^3$ is such that the complement $\mathbb S^3\setminus K$ has an ideal triangulation with $n$ simplices.  What is the best bound on the crossing number $\operatorname{cr}(K)$ in terms of $n$? [perhaps we want to restrict to hyperbolic knots]
I'm half expecting that there is no such bound (probably because of twisting around a fixed unknot in the complement of $K$).  In such a case, I'd like to ask for the following weaker bound in the same spirit, which I strongly suspect exists (though I'm not sure what it should be):
Suppose a knot $K\subseteq\mathbb S^3$ is such that the complement $\mathbb S^3\setminus K$ has an ideal triangulation with $n$ simplices.  This of course gives a triangulation of the boundary torus $\partial N_\epsilon(K)$, and I define $A(\text{an isotopy class of simple closed curve in }\partial N_\epsilon(K))$ to be the minimum number of geometric intersections between the curve and the $1$-simplices in the triangulation of $\partial N_\epsilon(K)$.  What is the best bound on $\operatorname{cr}(K)+A(m)$ (where $m$ is the meridian of $K$) in terms of $n$?


text:
Q: Array doesn't update when i call it from another class Im trying to program the reversi game for a school assignment but i have a
 problem when im calling an array from another class.
I used this if statement to check if a move is legal. It calls the CheckLegal move method from the playermove class.
 if(PlayerMove.CheckLegal(Yarray,Xarray))
                {
                    //changes the turn
                    if (turn) { turn = false; } else { turn = true; }
                    if (turn) { value = 1; } else { value = -1; }

                    GameState[Yarray, Xarray] = value;

                    Board.Invalidate();
                }

The CheckLegal method like this.
public bool CheckLegal(int Yarray,int Xarray)
        {
            var Form1 = new Form1();
            bool result;
            if(Convert.ToInt32(Form1.GameState.GetValue(Yarray,Xarray)) == 0) { result = true; }
            else { result = false; }
            return result;
        }

The If statement, if true, changes the value of the Gamestate array at a certain point. The only problem is, is when I call for the Gamestate array in the Checklegal method, I don't get the updated value.   But if the CheckLegal method isn't in antother class I do  get the updated value.
Can anyone please explain how this works?
And how i can get the updated Gamestate value in my PlayerMove class?

A: You are creating a new form to check the array, this is bound to fail.
public bool CheckLegal(int Yarray,int Xarray)
{
    var Form1 = new Form1();

Its like building a new car to check if you left your wallet in the console. i mean sure you can make a new car, there is no chance your wallet will be there though
Consider making the array static, or passing the array around when you need it

Further Reading
static (C# Reference)

Use the static modifier to declare a static member, which belongs to
  the type itself rather than to a specific object. The static modifier
  can be used with classes, fields, methods, properties, operators,
  events, and constructors, but it cannot be used with indexers,
  finalizers, or types other than classes.

Passing arrays as arguments (C# Programming Guide)

Arrays can be passed as arguments to method parameters. Because arrays
  are reference types, the method can change the value of the elements.


text:
Q: HBase, is there any faster ways to get all regions and their corresponding start and end keys? I'm trying to override a HBase method: MultiTableInputFormat.getSplits()
I have implementations like this:
public List<InputSplit> getSplits(JobContext context) throws IOException {
    List<Scan> scans = getScans();
    List<InputSplit> splits = new ArrayList<>();
    Scan sampleScan = scans.get(0);
    byte[] tableNameBytes = sampleScan.getAttribute(Scan.SCAN_ATTRIBUTES_TABLE_NAME);

    TableName tableName = TableName.valueOf(tableNameBytes);
    Table table = null;
    RegionLocator regionLocator = null;
    Connection conn = null;
      conn = ConnectionFactory.createConnection(context.getConfiguration());
      table = conn.getTable(tableName);
      regionLocator = conn.getRegionLocator(tableName);
      regionLocator = (RegionLocator) table;
      Pair<byte[][], byte[][]> keys = regionLocator.getStartEndKeys();

      RegionSizeCalculator sizeCalculator = new RegionSizeCalculator(
        regionLocator, conn.getAdmin()
      );
      int regionCount = keys.getFirst().length;

      for (int i = 0; i < regionCount; i++) {
        calculateSplits(
          keys.getFirst()[i],
          keys.getSecond()[i],
          regionLocator,
          sizeCalculator,
          splits
        );
      }
    return splits;
  }

  private void calculateSplits(
    final byte[] startKey,
    final byte[] endKey,
    RegionLocator regionLocator,
    RegionSizeCalculator sizeCalculator,
    List<InputSplit> splits
  ) throws IOException {
    HRegionLocation hregionLocation = regionLocator.getRegionLocation(startKey, false);
    String regionHostname = hregionLocation.getHostname();
    HRegionInfo regionInfo = hregionLocation.getRegionInfo();

    for (Scan scan : getScans()) {
      byte[] startRow = scan.getStartRow();
      byte[] stopRow = scan.getStopRow();

      // determine if the given start and stop keys fall into the range
      if (
        (startRow.length == 0 || endKey.length == 0 || Bytes.compareTo(startRow, endKey) < 0) &&
        (stopRow.length == 0 || Bytes.compareTo(stopRow, startKey) > 0)
        ) {
        byte[] splitStart = startRow.length == 0 || Bytes.compareTo(startKey, startRow) >= 0 ?
          startKey : startRow;
        byte[] splitStop =
          (stopRow.length == 0 || Bytes.compareTo(endKey, stopRow) <= 0) && endKey.length > 0 ?
            endKey : stopRow;

        long regionSize = sizeCalculator.getRegionSize(regionInfo.getRegionName());
        TableSplit split = new TableSplit(
          regionLocator.getName(), scan, splitStart, splitStop, regionHostname, regionSize
        );
        splits.add(split);
      }
    }
  }

The basic idea of this piece of code is get all regions and their start and end key. We also have a list of scans. We will examine all scans * all regions to get all splits.
But this piece of code is very slow mostly because we have about 10,000 regions. So the process of scanning and calculating each region's information will take a lot of time.
I noticed that in regionLocator we also have a method named:
getAllRegionLocations()
I think I can use this method to get all regions at a time and save a lot of time.
But the problem is if I use this method, I can't get the corresponding start and end key, then I can't decide the range of split.
Any ideas of better solutions to make this method faster?

A: Solved!
I found that we can get startkey and endkey from regionInfo.
So first get a list, scan all regionLocation in the list and the 2nd method becomes:
private void calculateSplits(
    HRegionLocation hRegionLocation,
    RegionLocator regionLocator,
    RegionSizeCalculator sizeCalculator,
    List<InputSplit> splits
  ) throws IOException {
    String regionHostname = hRegionLocation.getHostname();
    HRegionInfo regionInfo = hRegionLocation.getRegionInfo();
    final byte[] startKey = regionInfo.getStartKey();
    final byte[] endKey = regionInfo.getEndKey();
    ...
}


text:
Q: Is the posterior a sufficient statistic when observations are conditionally independent? Suppose there are two random variables, $X_1$ and $X_2$, and we're trying to infer $\theta$.
If $X_1$ and $X_2$ are conditionally independent, then is $f(\theta|X_1)$ a sufficient statistic for $X_1$?
I.e., will this hold:
$f(\theta|X_1,X_2) = f(\theta|X_2,f(\theta|X_1))$
This seems to be the case for the Kalman filter (yesterday's posterior is sufficient statistic for all prior information). Is this a general rule?
I'm sure this is well-studied but I can't find the right terminology.


text:
Q: Django query for multiple fields with list values I have below Django model
class Post(models.Model):
    author = models.ForeignKey(CustomUser,on_delete=models.CASCADE,)
    title = models.CharField(max_length=200,null=True)
    text = models.TextField()
    post_url = models.URLField(max_length = 200, blank = True)
    post_tier = models.ForeignKey(Tiers, on_delete=models.CASCADE, null= True)
    post_tier_value = models.IntegerField(default=0)
    slug = models.SlugField(unique=True, blank=True)

I have author_list = [author1@gmail.com, author2@gmail.com] and tier_value_list = [2000,3000]. I want to query in the above model for (author = author1@gmail.com and post_tier_value <= 2000) or (author = author2@gmail.com and post_tier_value <= 3000).
Can someone help me how to make query for this?

A: Use Q() operator
from django.db.models import Q

author_list = ['author1@gmail.com', 'author2@gmail.com']
tier_value_list = [2000, 3000]
query = Q()
for author, value in zip(author_list, tier_value_list):
    query = query | Q(author=author, post_tier_value__lte=value)

Post.objects.filter(query)

Note: I have used author__email which is a nested lookup since the author_list contain the email_ids


text:
Q: Can't get WebClient.UploadFile from C# Rest service I'm currently trying to migrate some aspx pages into a C# Rest service.
I can't change the caller but only the called service.
Here is how I'm called:
var myWebClient = new WebClient();
// here I'm dealing with cookie but not sure it is worth explaining how I pass it cause it isn't the problem
var response = myWebClient.UploadFile(sURL, fileFulName); // fileFulName is the path of my local file

When in aspx, the file could be get this way:
HttpPostedFile file = Request.Files[0];

First I tried the same with this code:
var file = HttpContext.Current.Request.Files[0];

Which throws an exception that I could manage by adding this into the web.config (appSettings section):
<add key="wcf:serviceHostingEnvironment:useClassicReadEntityBodyMode" value="true" />

But now, it throws no Exception but is an empty array.
Here is my endpoint method:
[OperationContract]
 [WebInvoke(
        Method = "POST",
        BodyStyle = WebMessageBodyStyle.Bare,
        ResponseFormat = WebMessageFormat.Xml,
        UriTemplate = "/upload?myParam={myGetParam}]
void Upload(Stream fileStream, string myGetParam);

I don't know how to do to get it working. I tried to use a byte array as input but the response was a 400 Bad Request. I then tried to see what is in the fileStream but it doesn't contains my file, only a few characters.
I have no idea on how I could get the uploaded file.

A: Here is how you create a route that you can upload files to in a .NET core REST API service:
[HttpPost]
[Route("api/upload")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
    foreach (var formFile in files)
    {
        if (formFile.Length > 0)
        {
            using (var reader = new StreamReader(formFile.OpenReadStream()))
            {
                 // do something with the file content.
            }
        }
    }

    return Ok();
}

A: You can view the code of my upload file function:
public void UploadFile(string fileName, Stream fileContents)

        {

            byte[] buffer = new byte[10000];

            int bytesRead, totalBytesRead = 0;

            do

            {

                bytesRead = fileContents.Read(buffer, 0, buffer.Length);

                totalBytesRead += bytesRead;

            } while (bytesRead > 0);

            Console.WriteLine("Service: Received file {0} with {1} bytes", fileName, totalBytesRead);

        }

The service contract:

   [ServiceContract]

    public interface IReceiveData

    {

        [WebInvoke(UriTemplate = "UploadFile/{fileName}")]

        void UploadFile(string fileName, Stream fileContents);

    }

The main function:

static void Main(string[] args)

        {

            string baseAddress = "http://" + Environment.MachineName + ":8000/Service";

            ServiceHost host = new ServiceHost(typeof(RawDataService), new Uri(baseAddress));

            host.AddServiceEndpoint(typeof(IReceiveData), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior());

            host.Open();

            Console.WriteLine("Host opened");

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(baseAddress + "/UploadFile/Test.txt");

            req.Method = "POST";

            req.ContentType = "text/plain";

            Stream reqStream = req.GetRequestStream();

            byte[] fileToSend = new byte[12345];

            for (int i = 0; i < fileToSend.Length; i++)

            {

                fileToSend[i] = (byte)('a' + (i % 26));

            }

            reqStream.Write(fileToSend, 0, fileToSend.Length);

            reqStream.Close();

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

            Console.WriteLine("Client: Receive Response HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);

            host.Close();

        }

Here is the result:

For more information, you can refer to this link:
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/create-a-service-arbitrary-data-using-wcf


text:
Q: Why WakeOnLAN frames are sent to broadcast I'm trying to figure out why wake on lan frames, in the simplest form, are designeted to the ethernet broadcast address (FF:FF:FF:FF:FF:FF) and not to the address of the machine to be powered on.
Does it has to do with the network switch internal table that assings a mac address to ports?

A: Yes. Since the mappings expire after some time (generally it's 4 hours if I recall correctly), it needs to be broadcast so it has a chance of reaching the target machine after the mappings are gone.
Edit:
Correction: If the mappings expire, the message is broadcast anyway.
The only reason why you would need to use broadcast is in case the machine physically moved to a different port and you tried to use Magic packets to wake up the machine before the mappings expired. Sounds like that would be handy in a datacenter, but I can't say if it's actually used.
While the example I've given probably never happens, it's likely the reason why broadcast is generally chosen - it's more reliable in case of bad/outdated mappings.

A: According to AMD's spec the destination doesn't have to be the all-ones address. It can also be the receiving station's address or a multicast address. The payload is a different story. It must be the sequence ff:ff:ff:ff:ff:ff followed by the receiving station's MAC address repeated 16 times.
The presence of absence of the station's entry in the switch's CAM table shouldn't matter in this case. If the entry isn't present the packet should be forwarded out all ports.


text:
Q: Multiple test case execution: I want to wait for entire page load in selenium in java I used below code .Wait time is to be defined in milliseconds for each step. It will be good if we have better way of doing it (like wait till page loading is complete). please give me some answers.
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

A: By default webdriver waits for a page to load to completion before moving forward to the next statement. But things such as AJAX calls (or) Javascript calls that trigger after a page is loaded and which alter the dom structure after loading of the page is complete cannot be dealt with by selenium automatically as part of page load completion.
You should instead consider using one of the helper methods within ExpectedConditions API to wait for the element that determines that a page load has been complete.