text:
Q: Can I move the static access to the base class? I have a base and derived class like so:
public abstract class MyBase
{
   protected string _data;
   protected string GetData_Internal() {return _data;}
   protected abstract void SetData(string data);
}

public class MyDerived : MyBase
{
   protected override void SetData(string data) {_data = "my data";}

   public static string GetData()
   {
      var instance = new MyDerived();
      return instance.GetData_Internal();
   }
}

The desired usage of this class is like this:
string data1 = MyDerived.GetData();
string data2 = MyDerived2.GetData(); // another class dervied from MyBase

I can't make the classes static, because static classes and derived classes don't play well together. So I made the function GetData() static, and this allows me to use the class like I want to.
I am going to have multiple classes that all identical to MyDerived, except for the data values set in SetData().
I would like to move GetData() out of the derived class and into the base class so that I'm not duplicating that code in every single derived class.
I can't figure out how to do that, because a static method in the base class has no idea what type of object to new up.
So, is there any way to do what I'm trying to do, keeping a static interaction with the class, while avoiding code duplication to make it happen?

A: If you are working with static data, maybe what you need are singleton objects that can be instantiated only once. They have the advantage of supporting inheritance and interface implementation, as well as being accessible statically. Also, unlike static classes, they can be passed as arguments to methods and stored in fields, properties and variables.
You can use properties instead of getter and setter methods. This simplifies your base class:
public abstract class MyBase
{
    public string Data { get; set; }
}

You can implement the singleton pattern like this:
public class MyDerived : MyBase
{
    #region Singleton Pattern

    public static readonly MyDerived Instance = new MyDerived();

    private MyDerived()
    {
    }

    #endregion
}

Create a public static readonly field that returns the only instance of the class and make the constructor private in order to forbid creating instances outside of the class itself. The constructor can also initialize the value of Data if required.
You can use the singletons like this:
MyDerived.Instance.Data = "my data";
string data = MyDerived.Instance.Data;

MyDerived2.Instance.Data = "my data 2";
...

See also: Implementing Singleton in C# for various ways of implementing the singleton pattern.

A: First, I am not completely sure what it is you are trying to accomplish. So, I am making no comment on if any of this is a good idea. You can get behavior that acts somewhat like overridden methods on base classes with statics. Instead, you overwrite the base then call into it. I do something similar to this for fetching instances or collections of instances from the class:
public class Dog
{
    public static Dog GetById(int dogId)
    {
        //Return dog
    }
}

public class Lab : Dog
{
    public new static Lab GetById(int dogId)
    {
        //Return same dog, as a lab
    }
}

A quick and terrible, but hopefully useful, version might start like the following. I might be able to make it into something practical if I understand your intentions a bit better.
public abstract class MyBase
{
    public static string GetData()
    {
        return "BASE STUFF";
    }
}

public class MyDerivedA : MyBase
{
    protected const string MySpecialData = "AAAAAA";

    public new static string GetData()
    {
        return MyBase.GetData() + MySpecialData;
    }
}

public class MyDerivedB : MyBase
{
    protected const string MySpecialData = "BBBBBBB";

    public new static string GetData()
    {
        return MyBase.GetData() + MySpecialData;
    }
}


text:
Q: java get only one prime number randomly I'm trying to figure out how to take a prime number randomly.
I mean, the result must be one prime number only.
I already created a method checkPrime(int a, int b) to check whether the number is prime or not.
Then, I loop from 0 to 256 and search for prime numbers.
After that, I must get one of those prime numbers randomly.
From my part of code below, it printed result: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
    System.out.println("Prime number: ");
    for(int a = 0; a < 256; a++){
        boolean checkIt = checkPrime(a, 5); //check whether the number is prime or not
        if(checkIt){
            System.out.print(a + " ");
        }
    }

Result I expected is only one prime number. It might 3 or 43 or 17 or 31 or etc.
What must I do to solve this?

A: You can stop the execution of a loop if you like; so you would do something like this:
System.out.println("Prime number: ");
for(int a = 0; a < 256; a++){
    boolean checkIt = checkPrime(a, 5); //check whether the number is prime or not
    if(checkIt){
        System.out.print(a + " ");
        break;
    }
}

That way once your loop has found its first prime number it will abort the calculation.
EDIT: To add a random element you'll have to choose the numbers you check randomly or choose where to stop randomly. One example could be this:
System.out.println("Prime number: ");
Ramdom rand = new Random();
for(int a = 0; a < 256; a++){
    int check = random.nextInt();
    boolean checkIt = checkPrime(check, 5); //check whether the number is prime or not
    if(checkIt){
        System.out.print(check + " ");
        break;
    }
}

This will check up to 256 random numbers. If you want to make sure you'll find one, I'd suggest something like this:
System.out.println("Prime number: ");
Ramdom rand = new Random();
int prime;
do {
    prime = rand.nextInt();
} while(!checkPrime(prime, 5));
System.out.print(prime + " ");

A: You can for example put each prime number in a table and then randomly take one element from that table.
Random generator = new Random();
List<Integer> primes = new ArrayList<Integer>();
System.out.println("Prime number: ");
     for(int a = 0; a < 256; a++){
          if(checkPrime(a, 5)){
                primes.add(a);
          }
     }
System.out.print(primes.get(generator.nextInt(primes.size())));

Be careful, I did not test it ;)

A: You can do as below :
Store all prime number in arraylist and then shuffle it or get random index.
ArrayList<Integer>  lista = new ArrayList<Integer>();

    for(int a = 0; a < 256; a++){
            boolean checkIt = checkPrime(a, 5); //check whether the number is prime or not
            if(checkIt){
                lista.add(a);
            }
        }

Collections.shuffle(lista);
System.out.println(lista.get(0));

 // or

Random r = new Random();
int index = r.nextInt(lista.size());

Integer RandPrimeNum = lista.get(index);
 System.out.println(""+RandPrimeNum);

A: Do this

*

*Store prime numbers retrived in loop in ArrayList<Integer>

*Get the size of arraylist and use random function to access number from that array list

for example. Say ArrayList size is 10 than use Random function to generate random number between 0 to 9 so what ever number you get use that number to access arrayList element.

A: You can you an Array where to put you Prime numbers.
Then you choose randomly an index from the array.
int[] array = new int[100];
int i = 0 ;
    System.out.println("Prime number: ");
    for(int a = 0; a < 256; a++){
        boolean checkIt = checkPrime(a, 5); //check whether the number is prime or not
        if(checkIt){
            array[i] = a ;
            i++;
        }
    }
int minimum = 0 ;
int maximum = array.length();
int randomNum = minimum  + (int)(Math.random()*maximum);
System.out.println(array[randomNum]);

A: You can do like this:
Create a list to store the prime numbers:
ArrayList<Integer> primeNums = new ArrayList<>();

Store each prime in the list:
System.out.println("Prime number: ");
for(int a = 0; a < 256; a++){
    if(checkPrime(a, 5)){
        primeNums.add(a);
    }
}

Choose a random index in the list's range:
Random r = new Random();
int randomIndex = r.nextInt(primeNums.size());

Pick the prime number:
Integer myRandomPrime = primeNums.get(randomIndex);

A: First, Insert Prime Numbers :
for(int a = 0; a < 256; a++){
        boolean checkIt = checkPrime(a, 5); //check whether the number is prime or not
        if(checkIt){
          PrimeNumebrArray.add(a); //PrimeNumebrArray is array list object
          arraySize++; //array index counter, initialized at 0
        }
    }

Now, Generate random Number
int index = Math.random() * arraySize;

This would return a value in the range [0,arraySize].
int PrimeNumebr = PrimeNumebrArray.get(index);

A: maybe this?
public int getPrime() {
  List<Integer> primes = getPrimes();
  int idx = System.currentTimeMillis() % primes.size();
  return primes.get(idx);
}

private List<Integer> getPrimes() {
  List<Integer> primes = new ArrayList<>();
  for(int a = 0; a < 256; a++){
    boolean checkIt = checkPrime(a, 5); //check whether the number is prime or not
      if(checkIt){
        primes.add(a);
      }
    }
  }
}

It's not very robust, however might be enough depending on your use case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: TLC5955 Combining 48 outputs to 3 | PCB Can I combine the TLC5955 outputs in this way to connect one 350mA RGB LED? I calculated that 6 mil at 1 oz Cu would be enough for 32 mA.
What thickness of PCB should I choose for heat removal from TLC5955 (32 mA * 48)? Probably need a radiator? I've never ordered a PCB, I made just a few simple single-layer PCBs myself. This is the first two-layer PCB with interlayer junctions - Vias. I installed EAGLE on the recommendation of PCBWay and drew this layout. PCBWay will print Via with a 0.3 mm hole and a ring around 0.5 mm for $5? I drew pairs of Via to avoid problems with metallization of the holes, I think this is a smart solution for delivering 32 mA from one layer to another.
Basically the led will glow red, so I chose direct connection for red, without Via. The blue one will have the least intensity, so I chose a long track with Via for it. I don't know how to draw polygons for the heat sink yet, so I've marked it this way for now. There is no connector for connection yet. I am open to opposition points of view.

A: No.
Regulators need to explicitly designed to allow putting their outputs in parallel, and this is seldom done because the complexity of that is usually not worth it. You can see regulators like this mostly in computer mainboard designs with currents upwards of 100A.
To drive a 1A LED, use a single constant current regulator. The current is too high for linear regulators without elaborate cooling solutions, so a switching regulator is a way better idea here even if it needs a bit of stuff around it. Trace width should not be much of an issue there, but it is a good idea to use zones instead of traces nonetheless.
For manufacturing, use 2 oz copper thickness and either 1.6mm or 1mm PCB thickness. There's nothing wrong with others, but these are standard, so these will be cheap as your design can be combined with others for manufacturing (so the fab house will not make a huge PCB with ten copies of your design, but ten PCBs each containing ten customers' designs).
I've packed up an older project of mine, a four channel 700mA LED driver, feel free to steal parts of the design. There will be a lot of impractical aspects for you like the connector that you need to change, and you might also want to separate the LED supply and the regulator supply (for which I use the same 5V rail). Each of the components I use is in the smallest possible package, so if you don't want to solder 0402, you can use 1206 or larger instead if you rearrange the board a bit, and you definitely need to change the value of the resistor setting the target current.


text:
Q: angular bootstrap datepicker disable dates with $http request in dateDisabled function So i have uibDatepicker directive (https://angular-ui.github.io/bootstrap/#datepicker) where i want to send request for each day provided in datepicker, hit server with that date, and return if it should be disabled or not.
The problem is that it's async call, and dateDisabled function does not handle promises.
Any suggestions?
<span uib-datepicker datepicker-options="datepickerOptions" ng-model="selectedDate"></span>

-
$scope.datepickerOptions: {
    dateDisabled: function (dateAndMode) {
        if (dateAndMode.mode !== "day") {
            return false;
        }
        //async call
        TimeService.getIsDateAvailable(dateAndMode.date).then(function (data) {
          //returns true or false
            return data.data;
        });
    }

I tried a lot of solutions. I found this answer: Disable dates using factory response UI Bootstrap Datepicker
But i can't apply this to my code.

A: You could preload the disabled dates and store them in a scope variable and then search for current date in the cached data. I think this is the best solution.

A: So i managed to fix this with preloading dates that are disabled. The trick i needed is first to get all 42 visible dates from datepicker, and than pass them to server, filter them and return back. Also if we change month, we will have new 42 visible dates, so we need to update disabled dates again.
You can see part of getting datepicker visible dates in this question:
angular bootstrap datepicker get visible dates (day mode)


text:
Q: How to rename a file on server that is mounted locally? I try to rename a whole directory programmatically. The directory is on a server that is mounted on the local file system. I'm trying it to do like this:
public static void main(String[] args) {
    File dir = new File("/Volumes/video/Serien/Scrubs/Season 1");
    System.out.println("Start renaming: " + dir);

    String[] files = dir.list();
    for (String file : files) {
        System.out.println("Old name: " + file);
        File renamedFile = new File(file);
        System.out.println(renamedFile.toString());
        boolean success = renamedFile.renameTo(new File("Test " + renamedFile.toString()));
        System.out.println("New name: "+ renamedFile.toString());
        System.out.println(success);
        break;
    }
}

I now that it tries only to rename the first one, but nevertheless it returns false and doesn't rename.
So any hints why? I do not get any exceptions. I think it is because the server requires authentication?
Edit: Since renameTo() seems to be platform-dependent: I'm using Lion OSX

A: Try using a fullpath + the directory name when you are trying to rename for both old and renamed directory. I believe list() returns the directory name only without the fullpath. I had similar problem before and it worked when I did that. Hopefully that works for you as well.


text:
Q: GeoPandas .clip() on example from the docs throws TypeError I am unable to reproduce the .clip()-example from the GeoPandas docs without error. I suspect it has something to do with my setup, since the same thing worked a few months ago in a different environment and I have not found reports of this happening to others. But I cannot figure out what the problem is--I am hoping someone here has an idea.
Copying and pasting the example code into my jupyter notebook looks something like this:
import geopandas
from shapely.geometry import Polygon

# get a set of points
capitals = geopandas.read_file(geopandas.datasets.get_path("naturalearth_cities"))

# Create a custom polygon
polygon = Polygon([(0, 0), (0, 90), (180, 90), (180, 0), (0, 0)])

# Attempt to clip points by polygon
capitals_clipped = capitals.clip(polygon)

Running it gives me the following error:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [7], in <cell line: 1>()
----> 1 capitals_clipped = capitals.clip(polygon)

File ~/.conda/envs/test-env/lib/python3.8/site-packages/pandas/util/_decorators.py:311, in deprecate_nonkeyword_arguments.<locals>.decorate.<locals>.wrapper(*args, **kwargs)
    305 if len(args) > num_allow_args:
    306     warnings.warn(
    307         msg.format(arguments=arguments),
    308         FutureWarning,
    309         stacklevel=stacklevel,
    310     )
--> 311 return func(*args, **kwargs)

File ~/.conda/envs/test-env/lib/python3.8/site-packages/pandas/core/frame.py:10917, in DataFrame.clip(self, lower, upper, axis, inplace, *args, **kwargs)
  10905 @deprecate_nonkeyword_arguments(
  10906     version=None, allowed_args=["self", "lower", "upper"]
  10907 )
   (...)
  10915     **kwargs,
  10916 ) -> DataFrame | None:
> 10917     return super().clip(lower, upper, axis, inplace, *args, **kwargs)

File ~/.conda/envs/test-env/lib/python3.8/site-packages/pandas/core/generic.py:7569, in NDFrame.clip(self, lower, upper, axis, inplace, *args, **kwargs)
   7567 result = self
   7568 if lower is not None:
-> 7569     result = result._clip_with_one_bound(
   7570         lower, method=self.ge, axis=axis, inplace=inplace
   7571     )
   7572 if upper is not None:
   7573     if inplace:

File ~/.conda/envs/test-env/lib/python3.8/site-packages/pandas/core/generic.py:7417, in NDFrame._clip_with_one_bound(self, threshold, method, axis, inplace)
   7414 else:
   7415     threshold_inf = threshold
-> 7417 subset = method(threshold_inf, axis=axis) | isna(self)
   7419 # GH 40420
   7420 return self.where(subset, threshold, axis=axis, inplace=inplace)

File ~/.conda/envs/test-env/lib/python3.8/site-packages/pandas/core/ops/__init__.py:470, in flex_comp_method_FRAME.<locals>.f(self, other, axis, level)
    466 axis = self._get_axis_number(axis) if axis is not None else 1
    468 self, other = align_method_FRAME(self, other, axis, flex=True, level=level)
--> 470 new_data = self._dispatch_frame_op(other, op, axis=axis)
    471 return self._construct_result(new_data)

File ~/.conda/envs/test-env/lib/python3.8/site-packages/pandas/core/frame.py:6973, in DataFrame._dispatch_frame_op(self, right, func, axis)
   6970 if not is_list_like(right):
   6971     # i.e. scalar, faster than checking np.ndim(right) == 0
   6972     with np.errstate(all="ignore"):
-> 6973         bm = self._mgr.apply(array_op, right=right)
   6974     return self._constructor(bm)
   6976 elif isinstance(right, DataFrame):

File ~/.conda/envs/test-env/lib/python3.8/site-packages/pandas/core/internals/managers.py:302, in BaseBlockManager.apply(self, f, align_keys, ignore_failures, **kwargs)
    300 try:
    301     if callable(f):
--> 302         applied = b.apply(f, **kwargs)
    303     else:
    304         applied = getattr(b, f)(**kwargs)

File ~/.conda/envs/test-env/lib/python3.8/site-packages/pandas/core/internals/blocks.py:402, in Block.apply(self, func, **kwargs)
    396 @final
    397 def apply(self, func, **kwargs) -> list[Block]:
    398     """
    399     apply the function to my values; return a block if we are not
    400     one
    401     """
--> 402     result = func(self.values, **kwargs)
    404     return self._split_op_result(result)

File ~/.conda/envs/test-env/lib/python3.8/site-packages/pandas/core/ops/array_ops.py:283, in comparison_op(left, right, op)
    280     return invalid_comparison(lvalues, rvalues, op)
    282 elif is_object_dtype(lvalues.dtype) or isinstance(rvalues, str):
--> 283     res_values = comp_method_OBJECT_ARRAY(op, lvalues, rvalues)
    285 else:
    286     res_values = _na_arithmetic_op(lvalues, rvalues, op, is_cmp=True)

File ~/.conda/envs/test-env/lib/python3.8/site-packages/pandas/core/ops/array_ops.py:73, in comp_method_OBJECT_ARRAY(op, x, y)
     71     result = libops.vec_compare(x.ravel(), y.ravel(), op)
     72 else:
---> 73     result = libops.scalar_compare(x.ravel(), y, op)
     74 return result.reshape(x.shape)

File ~/.conda/envs/test-env/lib/python3.8/site-packages/pandas/_libs/ops.pyx:107, in pandas._libs.ops.scalar_compare()

TypeError: '>=' not supported between instances of 'str' and 'Polygon'

So far I have tried to repeat this in a clean conda environment obtained like so:
conda create -n test-env
conda activate test-env
conda install ipykernel geopandas
ipython kernel install --user --name=test_ipython
conda deactivate test-env

According to conda, running python 3.7.11 and geopandas 0.9.0. Even using this fresh test_ipython-Kernel, I get the same TypeError when I attempt clipping the stock world map.
I don't currently think this is a bug, and am assuming mere ignorance on my part.

A: This was a problem with geopandas versions.
It turns out that geopandas.GeoDataFrame.clip() did not work the same way in v0.9.0. Checking the docs for the appropriate version of geopandas reveals that back then, clip was not a GeoDataFrame-method but a standalone one, making the solution simply
capitals_clipped = geopandas.clip(capitals, polygon)


text:
Q: Laravel's validator passes for empty string with 'nullable' rule Example:
Validator::make(['x' => ''], ['x' => 'nullable|integer|min:1'])->errors()->all();

Output:
[]

When x is null or 1,2,3, etc. it works fine.
When x is something else except empty string validator says about errors.
Column in database can be NULL or positive integer so when I pass empty string, validator tells me that it's fine, but mysql throws exception because it tries to save '' (empty string) in nullable integer column.
Only allowed values for field are: null, 1,2,3,4,..., everything else should fail.
If I add required rule then validator fails for null value ('nullable|required|integer|min:1')

A: Laravel 5.4 comes with a global middleware to convert all empty strings to null by default. If you don't want this then comment out the middleware from the list.
app/Http/Kernel.php
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,

A: Reading through the source code there's this function (in Validator.php)
protected function isValidatable($rule, $attribute, $value)
{
    return $this->presentOrRuleIsImplicit($rule, $attribute, $value) &&
           $this->passesOptionalCheck($attribute) &&
           $this->isNotNullIfMarkedAsNullable($attribute, $value) &&
           $this->hasNotFailedPreviousRuleIfPresenceRule($rule, $attribute);
}

 protected function presentOrRuleIsImplicit($rule, $attribute, $value)
 {
    if (is_string($value) && trim($value) === '') {
        return $this->isImplicit($rule);
    }

    return $this->validatePresent($attribute, $value) || $this->isImplicit($rule);
}

The function presentOrRuleIsImplicit basically says that if the value is '' then only validate it if the rule is "implicit" (basically if the attribute is required).
In that case if it is both required and nullable validation would fail because '' is not the same as null.
Laravel 5.4 has a built-in middleware called ConvertEmptyStringsToNull which basically helps deal with this discrepancy by taking all '' values and converting them to null.


text:
Q: Timeout setting will cause undefined method error I want to set the the global timeout in my project.
For example, when I click a button and head for an new page.
I want to give it a timeout in 5 seconds.
However when the exception occurs it only give me the NoMethodError: undefined method
# @driver.manage.timeouts.implicit_wait = 30
# @driver.manage.timeouts.page_load = 5

A: Are you sure you are attempting to call the method on a Selenium::WebDriver::Driver object? Before you make the method call, try doing a puts @driver.class and seeing what's output. You should see Selenium::WebDriver::Driver returned.
For simplicity, try making the calls when you first instantiate your driver object. For example:
@browser ||= Selenium::WebDriver.for :firefox
@browser.manage.timeouts.implicit_wait = 30
@browser.manage.timeouts.page_load = 5

Let me know if this doesn't work for you.


text:
Q: Why does interpolating NaNs result in an empty plot? I think my toy example below is self-explanatory. Basically, I can plot a line based on 5 values, yet if I interpolate NaNs the resulting line plot is empty. I would expect that matplotlib would still be able to connect the discrete existing points in my data (which are all still present).
a = pd.DataFrame([1,2,3,4,5], index=range(0, 10, 2), columns=['value'])
print(a)

  value
0   1
2   2
4   3
6   4
8   5

a.plot()

b = pd.DataFrame([np.NaN]*5, index=range(1, 11, 2), columns=['value'])
print(pd.concat([a, b]).sort_index())

    value
0   1.0
1   NaN
2   2.0
3   NaN
4   3.0
5   NaN
6   4.0
7   NaN
8   5.0
9   NaN
pd.concat([a, b]).sort_index().plot()


text:
Q: Need formula from excel to get the text (organisation name) from the email id I need a formula in excel with if condition.
if the mail id abcd@xyz.com then the result should come as XYZ, if the mail id is abcd@.in.xyz.com then the result should come as XYZ.
result should be XYZ if any of the above mail id is there.
for the first one i got the formula as if mail id is in C2 then the formula is as
UPPER(SUBSTITUTE(LEFT(MID(C2,FIND("@",C2)+1,LEN(C2)),FIND(".",MID(C2,FIND("@",C2)+2,LEN(C2)))),"."," "))

A: Assuming your email is in A1 - use this monster:
=UPPER(MID(A1,IFERROR(FIND("#",SUBSTITUTE(A1,".","#",LEN(A1)-LEN(SUBSTITUTE(A1,".",""))-1)),FIND("@",A1))+1,FIND("#",SUBSTITUTE(A1,".","#",LEN(A1)-LEN(SUBSTITUTE(A1,".",""))))-IFERROR(FIND("#",SUBSTITUTE(A1,".","#",LEN(A1)-LEN(SUBSTITUTE(A1,".",""))-1)),FIND("@",A1))-1))
Sample file: https://www.dropbox.com/s/23p3a7hf9pbodiw/OrgEmail.xlsx

A: Here's an alternative approach
=UPPER(TRIM(LEFT(RIGHT(SUBSTITUTE(SUBSTITUTE(A1,"@","."),".",REPT(" ",100)),200),100)))


text:
Q: How to add SplitViewController on the third view in the application I need some help.
I had created login page from that page user with redirect to tableview.
After selecting row the next view which i want to show is splitviewcontroller.
I cannot add these please help me.
Thanks in advance.

A: You can check the following tutorial for using splitviewcontroller
SplitViewController Tutorial

A: I find alternative option for this because it is not possible to add SplitViewController on other then Window.


text:
Q: XML reforming with DOM I am trying to reformat XML adding intermediate level node.
Here is what I have as input:
<channel>
  <item>
    <title>Advanced PHP Book</title>
  </item>
  <item>
    <title>MySQL primer</title>
  </item>
  <item>
    <title>C++ for beginners</title>
  </item>
</channel>
I need it to be like that at the end (page node added between channel and item):

<channel>
  <page>
    <item>
      <title>Advanced PHP Book</title>
    </item>
    <item>
      <title>MySQL primer</title>
    </item>
    <item>
      <title>C++ for beginners</title>
    </item>
  </page>
</channel>

Here is my testing code:

$sxe = simplexml_load_string($string);

$dom_sxe = dom_import_simplexml($sxe);

$dom = new DOMDocument('1.0');

$channel = $dom->appendChild($dom->createElement('channel'));

$page = $channel->appendChild($dom->createElement('page'));

$dom_sxe = $dom->importNode($dom_sxe, true);
$dom_sxe = $page->appendChild($dom_sxe);

$dom->formatOutput = true;

echo $dom->saveXML();

The problem I have is that channel element is doubled.
Please help.

A: I don't think this should be too hard: I think you're overcomplicating it by using the simplexml stuff.
$dom = new DOMDocument;
$dom->loadXML($string);

// create the <page> element
$page = $dom->createElement('page');

while ($dom->firstChild->firstChild) {
    // move the items in <channel> to the <page> element
    $page->appendChild($dom->firstChild->firstChild);
}

// insert the <page> element into <channel>
$dom->firstChild->appendChild($page);
$dom->saveXML();

A: $xml = '<channel> <item> <title>Advanced PHP Book</title> </item> <item> <title>MySQL primer</title> </item> <item> <title>C++ for beginners</title> </item> </channel>';

$dom = new DOMDocument;
$dom->loadXML($xml);
$page = $dom->createElement('page');
$items = $dom->getElementsByTagName('item');

while ($items->length) {
    $page->appendChild($items->item(0));
}

$dom->getElementsByTagName('channel')->item(0)->appendChild($page);
echo $dom->saveXML();

Output
<?xml version="1.0"?>
<channel>    <page><item> <title>Advanced PHP Book</title> </item><item> <title>MySQL primer</title> </item><item> <title>C++ for beginners</title> </item></page></channel>

See it.


text: Q: Constrained optimization with several equality constraints In maximizing a function of $n$ variables with $m$ equality constraints, it is required that the Jacobian derivative of constraints has full rank at optimal points. Can some one provide me with the geometric intuition behind this?


text:
Q: What is the most common reason I lose 4G? I only transiently have 4G on my phone. What is the main cause of its unavailablity?
I would have thought it was caused (in reality) by a weak signal from the base station that cannot carry the phones data above a critical error rate. Is this right?

A: Yes sometimes having no 4G means that the signal is too weak.
It works both ways, also the signal from your phone to the base station has to be strong enough to make the connection.
It might be possible to force your phone to stick to 4G but then the resulting data rate might be so low that 3G is a better option.


text:
Q: Does the pipeline object in sklearn transform the test data when using the .predict() method? When I use a pipeline object,

*

*Does the pipeline object fit and transform the train data when I use the .fit() method? Or should I use the .fit_transform() method? What is the difference between the two?

*When I use the .predict() method on the test data, does the pipeline object transform the test data and only then predict it? That is, should I  transform the test data using the .transform() method before I use the .predict() method?
This is the code I have:
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.decomposition import PCA
from sklearn.tree import DecisionTreeClassifier

#creating some data
X, y = np.ones((50, 1)), np.hstack(([0] * 45, [1] * 5))

#creating the pipeline
steps = [('scaler', StandardScaler()), ('SelectKBest', SelectKBest(f_classif, k=3)), ('pca', PCA(n_components=2)), ('DT', DecisionTreeClassifier(random_state=0))]
model = Pipeline(steps=steps)

#splitting the data
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.33, random_state=42)

model.fit(X_train,y_train)

model.predict(X_test)

A: The Pipeline object is exposing the methods of its last step. As your last step is a DecisionTreeClassifier (an Estimator), the pipeline will not have a fit_transform() but estimator functions such as fit(), predict(), score() etc.
When using fit(), the pipeline will call fit_transform() on all transformer and finally a fit() on the estimator.
When using predict() the pipeline will transform() all the data and then call predict() on the estimator.
As depicted in this picture: (Image from Raschka, Sebastian. Python machine learning. Birmingham, UK: Packt Publishing, 2015. Print)


text:
Q: How to change class when Active img source will change in jQuery

Major Millions
RMB 1000.00

Major Moolah
RMB 3,266.41

Major Moolah Isis
RMB 4,982.78

发大财
RMB 8,888.88

我发我发我发发发
RMB 9,999.99

I want to change the image source when the li in class = "Active" while the class of "winner-nameMoolar" remain.
Only change particular of image source as below and the class remain.
Kindly advise

My HTML:

Major Millions
RMB 1000.00

Major Moolah
RMB 3,266.41

Major Moolah Isis
RMB 4,982.78

发大财
RMB 8,888.88

我发我发我发发发
RMB 9,999.99

A: I hope this code will help you..
if ( $('ul > li').hasClass('Active')){
        $('ul > li.Active').children('img').attr('src', 'here write path you want');
}

My check this code and work perfect for me.


text:
Q: Multiple ajax calls after button click I have the following button function which calls calculate.php and saves a string that is contained in the #select-result div to txt file:

with html:

 <button id='sub1'>Submit</button>
";

whenever I click the button I get multiple executions. Any ideas why? If you need more information/code please let me know.
UPDATE:
For some reason once I declared the button in the html and not in thephp function the problem was solved...
I had this:
<?php
    $sql->dl();
?>

dl() was:
function dl(){
        none
            //notice the button declaration here
            <button id='sub1'>Submit</button>";

        $query = "SELECT col1,col2,col3,col4 FROM t1 order by col1";
        if($stmt = $this->conn->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($c1,$c2,$c3,$c4);
            $stmt->store_result();

            echo "
";
            while($stmt->fetch()){
                echo "
";
                echo $t."
".$d;
            }
        echo "

";
        }
        $stmt->close();

}

When I removed the button from this function and updated the html like this:
<button id='sub1'> Submit</button>

<?php
    $sql->dl();
?>

The problem was solved.
Any ideas why?
Thanks.


text:
Q: react component disappears on heroku after a second my website is https://swiftdeskph.herokuapp.com/
when you access my site, it will show the component for a second then its empty
My observations/question:

*

*accessing any route not specified shows my Error404 component just fine.

*even if there is an error on my api call, it should return and display the error in component. Which is whats happening on my dev server.

*no error on heroku logs

*If i rewrite my server.js and just put

app.get("/", (req, res) => {

    res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
  });

The whole app is working just fine BUT will only work if you start accessing from "/" route.
App.js
import React, { useEffect } from "react";
import { useDispatch } from "react-redux";
import "./sass/App.scss";
import "bootstrap/dist/css/bootstrap.min.css";
import { Route, BrowserRouter as Router, Switch } from "react-router-dom";

// COMPONENTS---------------------------------------
import Navbar from "./components/NavbarComponent";
import Footer from "./components/Footer";
import Dashboard from "./components/Dashboard/Dashboard";
import { Orders } from "./components/Orders/Orders";
import UserInventory from "./components/UserInventory/UserInventory";
import Error404 from "./components/Error404";

//Import fetch actions
import { fetchProducts } from "./redux/userInventory/inventoryActions";
import { fetchOrder } from "./redux/order/orderActions";

function App() {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(fetchOrder());
    dispatch(fetchProducts());
  }, []);

  return (
    <React.Fragment>
      <Router>
        <Navbar />
        <div className="appContainer">
          <Switch>
            <Route path="/" exact component={Dashboard} />
            <Route path="/orders" component={Orders} />
            <Route path="/inventory" component={UserInventory} />
            <Route path="*" component={Error404} />
          </Switch>
        </div>
      </Router>
      <Footer />
    </React.Fragment>
  );
}

export default App;

server.js
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
require("dotenv").config();

const app = express();
const PORT = process.env.PORT || 80;
const { MONGO_URI } = require("./config/keys");
const connection = mongoose.connection;

app.use(cors());
app.use(express.json());

mongoose.connect(MONGO_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useCreateIndex: true,
  useFindAndModify: false,
});

connection.once("open", () => {
  console.log("MongoDB database connection established successfully.");
});

if (process.env.NODE_ENV == "production") {
  app.use(express.static("client/build"));

  const path = require("path");
  app.get("*", (req, res) => {
    res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
  });
}

//ADDING OF ROUTES
const products = require("./routes/products");
const userInventory = require("./routes/userInventory");
const transactions = require(".//routes/transactions");
app.use("/api/products", products);
app.use("/api/user/inventory", userInventory);
app.use("/api/transactions", transactions);

app.listen(PORT, () => {
  console.log(`Server is running on port: ${PORT}`);
});

A: if you look at your console, you get this

Looks like you are calling map on orders, where orders is not an array. Its possibly null/undefined/object/value type.
look at DashboardOrders.jsx

A: Issue fix. Since issue is conflict with routes, i just manually coded the routes.
if (process.env.NODE_ENV == "production") {
  app.use(express.static("client/build"));

  const path = require("path");
  app.get("/", (req, res) => {
    res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
  });
  app.get("/orders", (req, res) => {
    res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
  });
  app.get("/inventory", (req, res) => {
    res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
  });
}


text:
Q: Python - Regex replace a character only if after a pattern I have a lot of strings with this pattern [INTEGER]-[URL-SLUG]. Examples:
234234-url-slug-1
2-urlslug2
301-url-slug4

I need to replace the '-' after the integer with a '/' but leave the other '-' intact. So final strings would be:
234234/url-slug-1
2/urlslug2
301/url-slug4

A: This should work using re.sub:
> import re

> s = '234234-url-slug-1'
> re.sub(r'(\d)\-', r'\1/', s)
'234234/url-slug-1'

\1 in the replacement string refers to the first captured group in the matching pattern: '(\d)'.

A: re.sub function has the optional argument count which is the maximum number of pattern occurrences to be replaced:
s = '234234-url-slug-1'
result = re.sub(r'^(\d+)-', r'\1/', s, 1)

print(result)

The output:
234234/url-slug-1


text:
Q: How to animate one child but not others using jQuery? Hey guys, I have written this code from the ground up using jQuery (first real jQuery project), and so far, I have some toggle animation. My code looks like this:
HTML

jQuery
$(document).ready(function(){
  $('.featured-img').toggle(
  function() {
   $(this).animate({
          height: "600px",
          marginTop: "-100px"
 }, 500 );
        $(".featured-img > img").animate({
          marginTop: "0px"
 }, 500 );
  },
  function() {
   $(this).animate({
          height: "150px",
          marginTop: "100px"
 }, 1500 );
        $(".featured-img > img").animate({
          marginTop: "-200px"
 }, 1500 );
  }
   );
 });

This works fine with one element, BUT it applies the same animation to every element assigned .featured-img on each click. Is there any way I can only animate the element I clicked, without disturbing the other ones at all?
I have tried playing with :not(:animated), and other stuff, but it only made it worse. I would appreciate any help or suggestions.
Thanks in advance!

A: Hey everyone, after doing some more research, I figured it out. I knew from the beginning that the reason the other objects were animated because the classes were shared throughout. The way to avoid that is to target only the child of the element we clicked using the jQuery child selector $(this).children(). You can see the functional demo here. My code looks like this:
$(document).ready(function(){
    $('.featured-img').toggle(
        function() {
            $(this).animate({
                height: "593px",
                marginTop: "-100px"
      }, 500 );
            $(this).children().animate({
                marginTop: "0px"
      }, 500 );
        },
        function() {
            $(this).animate({
                height: "150px",
                marginTop: "100px"
      }, 1500 );
            $(this).children().animate({
                marginTop: "-200px"
      }, 1500 );
        }
      );
    });

I hope you guys have learned something new. Thanks for all those who helped.


text:
Q: Should there be a signum function in the derivative of this sum? Say we want to derive the following sum with respect to $A_i$ $$S=\sum_{j=1}^M\left(\sum_{i=0}^NA_ix_j^i-y_j\right)^2$$ In the book the derivative is given as $$\frac{dS}{dA_i}=2\sum_{j=1}^M\left(\sum_{i=0}^NA_ix_j^i-y_i\right)x_j^l$$ where $l$ equals the degree of $x$ that corresponds to $A_i$ which we're deriving with respect to. Now this makes perfect sense, when $A_i>0$ for all $i$. But I'm wondering what if we drop the assumption that all of $A_i$ must be positive, wouldn't the derivative look like this $$\frac{dS}{dA_i}=sgn(A_i)\sum_{j=1}^M\left(\sum_{i=0}^NA_ix_j^i-y_i\right)x_j^l$$ since we can stumble upon some $A_i$ that is negative and if we derive by it a minus sign will go in front, changing the equation. Is this a mistake?

A: Assuming all $y_j$ are zeros. Moreover, let all $x_j^i$ be zeros too except $x_1^1=t$. Then we have $S=(A_1t)^2$. What is the derivative of $S$ with respect to $A_1$:

*

*$2(A_1t)t$ (the book),

*$\operatorname{sgn}(A_1)(A_1t)t$ (your suggestion)?


text:
Q: Recovering the saved VM ALL,
I made a VirtualBox VM on the external USB HDD.
Then I closed as "Saved" and disconnected the HDD.
Now, I connected drive but when I try to open the VM back up it errors out:
VD: error VERR_FILE_NOT_FOUND opening image file.

Is there a way to recover and open the VM?
Thank you.

A: Like in all such cases I would create an image (full copy) of the USB HDD immediately, before you start recovery attempts that may harm the recoverability.
The easiest apporach would be to check the file system of the USB HDD, but this might also just remove the remains of the file metadata, that is why an image should be done beforehand.
You miss quite some required information for more details, like the operating system (Windows, Linux, MacOS and the distribution/version) you use, the file system that is used on the USB HDD and information about which files of the VM are still shown on the USB HDD by your file manager.
In general, it may be possible that the image is alright, but cannot be found by virtual box, e.g. because it is looking at the wrong place.


text:
Q: Click linked image to close / hide div This is what I have so far. I've tried different solutions, but I'm missing something. :(
Here's is my html:

Content goes here

`

Here's my css:
.container {
    width: 333px;
    display: block;
    position: fixed;
    top: 30%;
    left: 0;
}
.box {
    background: rgba(255, 255, 255, 0.8);
}
a.close-x {
    position: absolute;
    top:-15px;
    right:-15px;
}

Here's my attempt at script
http://jsfiddle.net/shanamiami/T6hE9/

A: Use document.ready() instead of window.load()
You can furthur simplify your code.
Try this:
$(document).ready(function () {
    $('.close-x').click(function () {
        e.preventDefault();
        $('.box').slideToggle();
    });
});

JSFiddle Demo

A: First of all your fiddle is missing jquery library.
Secondly instead of window load use document ready event.
Here is how you can do it:
    $(function () { // short way of writing document.ready
    $('div.container a.close-x').click(function (e) {

        e.preventDefault();
        var div = $(this).next('.box').slideToggle();
    });

});

FIDDLE

A: $(window).load(function(){
  $('.close-x').click(function(e){
     e.preventDefault();
     var div =$('div.box').slideToggle();
  });
});

A: There was nothing wrong with your code, only minor tweaks required.

*

*You just need to include jquery in fiddle

*whatever code in fiddle's JavaScript window, that code is copied inside window.load but when you are not on fiddle, make sure to add your code inside window.load or document.ready.

$(window).load(function()
//your code is copied here by default in fiddle at runtime
});


text:
Q: Data Structure choices based on requirements I'm completely new to programming and to java in particular and I am trying to determine which data structure to use for a specific situation. Since I'm not familiar with Data Structures in general, I have no idea what structure does what and what the limitations are with each.
So I have a CSV file with a bunch of items on it, lets say Characters and matching Numbers. So my list looks like this:
A,1,B,2,B,3,C,4,D,5,E,6,E,7,E,8,E,9,F,10......etc.
I need to be able to read this in, and then:
1)display just the letters or just the numbers sorted alphabetically or numerically
2)search to see if an element is contained in either list.
3)search to see if an element pair (for example A - 1 or B-10) is contained in the matching list.
Think of it as an excel spreadsheet with two columns. I need to be able to sort by either column while maintaining the relationship and I need to be able to do an IF column A = some variable AND the corresponding column B contains some other variable, then do such and such.
I need to also be able to insert a pair into the original list at any location. So insert A into list 1 and insert 10 into list 2 but make sure they retain the relationship A-10.
I hope this makes sense and thank you for any help! I am working on purchasing a Data Structures in Java book to work through and trying to sign up for the class at our local college but its only offered every spring...

A: You could use two sorted Maps such as TreeMap.
One would map Characters to numbers (Map<Character,Number> or something similar). The other would perform the reverse mapping (Map<Number, Character>)
Let's look at your requirements:

1)display just the letters or just the numbers sorted alphabetically
  or numerically

Just iterate over one of the maps. The iteration will be ordered.

2)search to see if an element is contained in either list.

Just check the corresponding map. Looking for a number? Check the Map whose keys are numbers.

3)search to see if an element pair (for example A - 1 or B-10) is
  contained in the matching list.

Just get() the value for A from the Character map, and check whether that value is 10. If so, then A-10 exists. If there's no value, or the value is not 10, then A-10 doesn't exist.
When adding or removing elements you'd need to take care to modify both maps to keep them in sync.


text:
Q: Prevent same function from firing twice I'm using jquery's bPopup() to open a modal window. When the user clicks a button, jquery loads an ajax page and then shows the modal windows. Due to this small delay when loading the page, the button remains active, and if the user clicks twice, it will fire twice, making two ajax requests to the server and opening two windows.
Is there a simple way to prevent this from happening? Since it's relatively a common problem, I wonder if there's a "right" way the pros handle it.
I've tried assigining the popup to a window.object, so that it would be overwritten on the second call, but it's still opening two popups.

A: That depends on what UX you're after, but I'd suggest you disable the button.
That way your user will:

*

*Know the click was "registered".

*Not try to click again.

*Not crash / confuse you code.

EDIT
According to the comment, the "button" is actually not a <button>, but an element with an onclick handler. So:

*

*You can disable the click handler by reversing what you did to set it (removeEventHandler, onclick=null...), but you'd then have to set it back once the pop-up is done, and that might be quite annoying.

*You'd have to somehow manipulate the UI to indicate the button was clicked and is disabled. Could probably be quite simple to do with a CSS class.

But really, you're probably better off having 2 "versions" of your button element (<div>...), with only 1 visible at a time, with the other hidden via display: none. The "clicked" version should not have a click event handler set at all. Then, when the button is clicked, you immediately switch between the 2 (can be done with a single CSS class), and once the pop-up is done, switch back.


text:
Q: how to decode color in xml? Not hex and rgb color I dont know how decode this color in XML file, pleas help me! This color is not in hexadecimal format and not in RGB format! And in this code the colors are XML, not 6 characters, but 8!
This is xml code:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="0">
    <solid android:color="@0106000B" />
</shape>


text:
Q: Mark all the functions by constexpr implicitly Are there reasons not to marking all the functions contexpr implicitly after C++11? I think the principle "Caedite eos! Novit enim Dominus qui sunt eius" would work here, because in case of:
template< typename T >
constexpr
T f(T t) { return t; }

int main(int argc, char *argv[])
{
    f(1);
    f(argc);
    return 0;
}

f(argc) automatically recognized as not constexpr, as opposed to f(1). On the one hand compiler can defenitely infer applicability of constexpr specifier by itself for functions, which can be constexpr generally, on the other hand it can ensure, that functions can never be constexpr if they not matches the rules for constexpr functions.
Also there is a plenty of problems with STL. Say, regarding non-constexpr operator [] of non-const std::array in constant expressions or regarding non-constexpr std::swap, which prevents using of std::swap in constant expressions.
Why there no such language feature as implicit constexpr specifier enabled by default for all the functions (or even for statements, expressions and subexpressions)? Is there performance reasons or something else?


text:
Q: REACT-Improving my code multiple condition is there a way to improve my code (Very Important, Important, Medium, Low, Good,  Excellent,...) :
 {
    Header: "Opinion",
    accessor: (row) => row.opinion,
    Cell: props =>

            {props.value === "Very important" ?

                    {props.value}

                : props.value === "Important" ?
                    : .... //other conditions
            }

},

A: You might be able to do something like this, which looks a bit cleaner in my opinion!
{"Very Important": {props.value},
 "Important": ...,
 "Medium": ...,
 ...
}[props.value]

A: Well, I think that this depends also on the number of conditions.
If they are 1-2, I might render the JSX directly in the ternary.
If they are more, I'd say that you either use partial renderers (extracting the JSX in separate components) or if there many, as @amit-maraj said, using an inline-switch might be a good variant to avoid too much nesting, even though it's a syntax that it's not that often used (since you don't have to do this kind of stuff).
Additionally, I would extract the JSX rendered from the inline-switch in separate functions, especially if the have logic or they have a large size, in order to keep the file readable.
If this example represents only a way of coloring the text, it might be helpful to have a small component that assigns the class based on the prop value.
eg:
const renderOpinion = (value) => {
    const getColor = () => {
      switch(value){
        case "Very Important":
          return "text-black"
        //...other cases
        default: break;
      }
    }

    return {value}
  }

And of course, if they have base classes, using something like classnames or doing directly like:
className={`text-small ${getColor()}`}

and then just call it as :
    //...
    Cell: props => renderOpinion(props.value)


text:
Q: Convert HTML table code to asp:table control I have an HTML table code (starts with
 and ends with
), how can I make my asp web page to add this table programmatically?

A: If you have purely HTML code generated in server side, then you can add that HTML code having
 into your asp page like this.

*

*Add a placeholder to aspx page like this.

<asp:PlaceHolder ID="plc" runat="server" />

*In page_load event write this.
String str = "

TD VALUE

";
plc.Controls.Add(new LiteralControl(str));
This will emit html code , and place them to placeholder.
ASSUMPTION This is just a readonly html code , that you wan to show in page, you are not intended to get those value in server side code on post back. Nor there is any editable field inside the generated table.

A: Either redo it in asp:table as you already mentioned or add runat="server" to your existing table and you will be able to alter it in codebehind.
After runat = server you can do things like
protected void Page_Load(object sender, EventArgs e)

    {

       var str= tbl1.Rows[0].Cells[2].InnerHtml;

    }

But I would probably redo it in <asp:table> if you are using webforms. See full example here
Add rows to a table dynamically

A: if you want to access this table programatically then use

it will then let you access this control through asp.net


text:
Q: Proof of Projective Nullstellensatz In the proof of the Nullstellensatz for projective varieties, I can't understand the following remark (which comes from Hulek, Elementary algebraic geometry, pag. 72)
" ... if $f=\sum f_i$ is a polynomial with homogeneous components $f_i$ then (using the fact that the field $k$ has infinitely many elements) $f(\lambda x_0,\ldots,\lambda x_n)=0$ for all $\lambda$ if and only if $f_i(x_0,\ldots,x_n)=0$ for all $i$...."
The only if part is trivial. I can't understand the if part. Can you help?

A: Hint: Can you see why the equality $f_i(\lambda x_0,\ldots,\lambda x_n)=\lambda^if_i(x_0,\ldots,x_n)$ holds for all $i$?


text:
Q: Tensorflow Serving mobilenet_1.0_224_quant All,
I'm trying to serve a retrained model based on the mobilenet_1.0_224_quant architecture.
python -m retrain
    --architecture=mobilenet_1.0_224_quant
    --bottleneck_dir=/mypath/bottlenecks
    --how_many_training_steps=500
    --model_dir=/mypath/models
    --summaries_dir=/mypath/training_summaries/mobilenet_1.0_224_quant
    --output_graph=/mypath/graph.pb
    --output_labels=/mypath/labels.txt
    --image_dir=/mypath/images
    --saved_model_dir=/mypath/models/saved_models

tensorflow_model_server is able to load the servable version properly, but I haven't been able to consume it.
I'm using the same strategy that is used to consume inception_v3 based models.
for filename in filenames:
    f = open(filename, 'rb')
    files.append(f)
    data = f.read()
    imagedata.append(data)

request = predict_pb2.PredictRequest()
request.model_spec.name = 'default'
request.model_spec.signature_name = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY

for data in imagedata:
    request.inputs['image'].CopyFrom(
        make_tensor_proto(data))
    result = stub.Predict(request, 10.0)  # 10 secs timeout
    print(result)

Nevertheless, I get the error:
grpc.framework.interfaces.face.face.AbortionError: AbortionError(code=StatusCode.INVALID_ARGUMENT, details="Expects arg[0] to be float but string is provided")

Any idea what I could be doing wrong?

A: The model expects the input to be floats but you are providing strings. You can use the SavedModel command-line tool to inspect the input and output specifications of the model.


text:
Q: Pass parameter from Excel to SQL in PowerQuery I want to set local variables or pass parameters from Excel to SQL. I've found similar questions, but all referred to old versions of Excel and/or the answers showed how to filter or manipulate output from a generic SQL query in the Power Query Editor, rather than pass a parameter or modify the SQL, so that the SQL Server supplies data in the needed form.
I'm building a large Microsoft Excel spreadsheet that depends on ten different SQL queries, all against a common SQL Server database. Excel and SQL Server are installed on my laptop and are current versions (as of 16 Mar 2022). All ten queries share a common date restriction, imposed in the WHERE clauses of the queries. The tables accessed and the form of output are very different, so there is no easy way to combine the ten queries into a single query. The queries contain multiple levels of aggregation (e.g. SUM(...)) so I need to restrict the records accessed prior to aggregation and passing results from the query back to Excel.
As currently written, each query begins by setting two date values in local variables. For example,
 DECLARE @BEGIN_DATE AS smalldatetime;
 DECLARE @END_DATE AS smalldatetime;
 @BEGIN_DATE = CAST('2021-03-01 00:00' AS smalldatetime);
 @END_DATE = CAST('2021-03-02 23:59' AS smalldatetime);

Every one of the ten queries includes a line in the WHERE clause similar to
WHERE
    PickUpDate BETWEEN @BEGIN_DATE AND @END_DATE

Every query will use the same pair of dates. However, the column filtered (PickUpDate above) changes from one query to the next.
As it is, I have to manually edit each of the ten queries to change the two dates--twenty edits in all. This is time-consuming and error-prone. Ideally, I'd like to set the date range in the spreadsheet, in a pop-up dialog box, or any other convenient way and pass the dates to the SQL queries. Then by selecting Data > Refresh All in Excel, update all my tables at once.
Is this possible, and if so, how does one do it?

A: The answer from David Browne is generally on-target. But I found some difficulties reading data from an Excel table directly into the SQL, given security restrictions in the latest version of Excel/Power Query. Also, since this was the first time I worked directly in M-code and the advanced editor, it was challenging to fill-in the gaps.
I finally got a nice solution running; here is what worked for me.
First, I stored the parameter values in a two-column table. My table is named "ParameterTable" with column headers named "Parameter_Name" and "Value". The value(s) to pass to SQL Server are stored in the Value column. My table has two rows with row entries labeled "Begin_DateTime" and "End_DateTime".
Secondly I created a callable function named "ftnGetParameter." Select Data > Get Data > From Other Sources > Blank Query. Then select "Advanced Editor." Delete any boilerplate added by Excel, and enter and save this function
let theParameter=(TableName,ParameterLabel) =>
let
    Source=Excel.CurrentWorkbook(){[Name=TableName]}[Content],
    value = Source{[Parameter_Name=ParameterLabel]}[Value]
in
    value
in
    theParameter

Thirdly, code-up your SQL statement as usual. I was trying to pass dates to SQL, so I initially coded with string literals. Enter the query in the usual way. I used Data > Get Data > From Database > From SQL Server Database. Then pasted in the SQL. The two relevant lines in my query looked like this:
DECLARE @BEGIN_DATE AS SMALLDATETIME='2021-01-01 00:00';
DECLARE @END_DATE AS SMALLDATETIME='2021-12-31 23:59';

You could skip this step, but it allowed me to get complex SQL code entered, formatted, and running before I invoked the function to pass the parameters.
Finally, simply replace the string literals in the SQL with code to call the function. My first few lines of M-code looks like this:
let
    Source = Sql.Database("DESKTOP-04P8E8C", "nfbdata",
[Query=
"
DECLARE @BEGIN_DATE AS SMALLDATETIME= '" & ftnGetParameter("ParameterTable","Begin_DateTime") & "';
DECLARE @END_DATE AS SMALLDATETIME='" & ftnGetParameter("ParameterTable","End_DateTime") & "'  (… the query continues )

Excel will issue some warnings about running the query and prompt you to edit permissions. Once permission has been granted, the function reads the text from the parameter table and passes it into the SQL.
I found that the function call was not optional. Apparently, importing the code directly into a native call to SQL Server is considered an unacceptable security risk.
Many thanks to Mr. David Browne. His post definitely points in the right direction.

A: You can reference a table on a sheet from Power Query and integrate values from that table into your other queries.  Eg if ParameterTable is a single-row table on some worksheet with a column called "StartDate", something like
let
    theDate = Date.From( Record.Field(Table.First(ParameterTable),"StartDate") ),
    Source = Sql.Databases("localhost"),
    AdventureWorksDW2017 = Source{[Name="AdventureWorksDW2017"]}[Data],
    dbo_DimDate = AdventureWorksDW2017{[Schema="dbo",Item="DimDate"]}[Data],
    #"Filtered Rows" = Table.SelectRows(dbo_DimDate, each [FullDateAlternateKey] = theDate )
in
    #"Filtered Rows"

for M query folding, or
let
    theDate = Date.From( Record.Field(Table.First(ParameterTable),"StartDate") ),
    sql = "
      select *
      from dimDate
      where FullDateAlternateKey = '" & Text.From(theDate) & "'
    ",
    Source = Sql.Database("localhost", "adventureworksdw2017", [Query=sql])
in
    Source

for dynamic SQL.


text:
Q: Notion of $G$-stable subsets in Moerdijk and Mrčun's Introduction to foliations and Lie groupoids This question is related to this this older question.
Let $M$ be a smooth manifold and $G$ be a group of diffeomorphisms of $M$. In page 35 of Introduction to Lie foliations and Lie groupoids, Moerdijk and Mrčun call an $S\subset M$ a $G$-stable subset of $M$ when it is connected and given $g\in G$, either $S\cap gS=S$ or $S\cap gS=\emptyset$. Just after the definition, they point out that the $G$-stable subsets of $M$ are precisely the components of $G$-invariant subsets of $M$.
I am having a hard time to understand the implication, i.e., how a $G$-stable subset would need to be a connected component of a $G$-invariant subset of $M$. For instance, consider $M=\mathbb{C}$, $G=\mathbb{S}^1$ and $S=\{1\}$, where $G$ acts on $M$ by rotations around $0\in M$. In this case, $S$ is $G$-stable yet it is not a connected component of its group-action closure, $gS=G$.
In this context, don't we have to modify a little the definition of $G$-stable subsets only to include open subsets of $M$ or restrict it to finite subgroups of diffeomorphisms of $M$?


text:
Q: Unable to perform SetExtension on 'repeated inside extensions' import "IpInterfaces.proto";
package IpInterfaces;

message DNSServerNames{
    repeated string dnsServers=11;//limited only to optional?
}
extend IpInterfaces.IpInterfaceAddress{
    optional DNSServerNames dnsServerNames=1000001;
}

Unable to perform SetExtension(dnsServers,value).
Is this supported or is it limited only to OPTIONAL? I get below error on VS2012
"Error no instance of the overloaded function matches the argument list"

And when i modify the Proto to
extend IpInterfaceAddress{
                repeated string dnsServers=1000000;
}

i get below error message:
error C2664: 'google::protobuf::internal::RepeatedStringTypeTraits::Get' : cannot convert parameter 3 from 'const std::string' to 'int'
1>          No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called


text:
Q: Data recovery site mesaures our ASP.Net application is currently deployed over the farm with the below specs:

*

*2 web front end servers controlled by an NLB

*1 Application server hosting windows services and a workflow engine

*An Active/Passive SQL Server cluster

we are required to provide a specific strategy to deploy a Data recovery site. is there any specific measures or configuration to be considered in such a farm or just adapt a replica of the whole farm.
including (IIS sites,services,SQL databases...)

A: As always there are a number of ways in which you can provide disaster recovery for your solution.

*

*You could use you SAN to replicate in real-time (assuming you have VMs setup for your primary site) data written.

*You could do some form of log shipping at the database level and have a cold spare setup mirroring the primary configuration.

*Add another NLB web server and move your passive SQL server to your DR site, although deepening on the data centre latency may be an issue.
My preference would be option 1 however it will depend on the exact business need, cost and risk to the business in needing DR.


text:
Q: Object chang size(android) Sorry for my English. I have a dynamically created TextView and ImageView, they are added to the LinearLayout. But when I start to write a TextView that it changes its size and thus reduces the ImageView. The picture below is an example of how the size of the

 final LinearLayout row = new LinearLayout(this);
             row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
             row.setOrientation(LinearLayout.HORIZONTAL);

             //params editTExt
             android.widget.LinearLayout.LayoutParams paramsEtext = new android.widget.LinearLayout.LayoutParams(
                        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f);
             paramsEtext.gravity = Gravity.LEFT;

             //params image View
             LinearLayout.LayoutParams paramsImageView = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 0.25f);
             paramsImageView.gravity = Gravity.CENTER_VERTICAL;

             //create edit text
             final EditText etext = new EditText(QuicklyCreateQwestions.this);
             etext.setLayoutParams(paramsEtext);

             //add et in ArrayList
             et.add(etext);

             //set text in textView
             etext.setText(qwestions.get(i).toString());
             row.addView(etext);

             //add ImageView in edit text
             final ImageView imV = new ImageView(this);
             imV.setLayoutParams(paramsImageView);
             imV.setImageResource(R.drawable.t_del_poll);
             imV.setId(i);

             //set button in layaut
             row.addView(imV);

             //action if button click
             imV.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View view) {
                        row.removeView(etext);
                        row.removeView(imV);
                    }
                });

             //add editText and button in layaut
             LinearLayoutTextQwestions.addView(row);


text:
Q: Is there a way to run opengl command on a thread other than gtk's ui thread? I am working on an project that requires the pipeline creation and render calls to gtk's glarea be made from another thread.
I am using epoxy as the gl loader. I am also using mingw's gtk+ build on a windows system. Using a sample triangle code, creating the pipeline and rendering using glarea's realize and render signals works. But any gl call on another thread would cause the app to crash.
Here is the rendering and thread logic. I still configure the pipeline using the realize signal, but the rendering is done on a different thread.
window class
#include "window.h"
#include <thread>
#include <chrono>

namespace M
{

Window::Window()
{
    set_border_width(6);
    set_default_size(640, 480);

    _box.set_spacing(6);
    add(_box);

    _box.pack_end(ngl, Gtk::PACK_EXPAND_WIDGET); // ngl : the GLArea variable

    show_all();

    thread = std::thread( [this] { render(); } );
}

void Window::render()
{
    using namespace std::chrono_literals;
    std::this_thread::sleep_for(5s);

    ngl.renderTri();
}

}

GLArea class
#include "glarea.h"

namespace M
{

GLArea::GLArea()
    : _points(0),
      _colors(0),
      _matrix(0),
      _isButton3Pressed(false),
      _isKeyWPressed(false),
      _isKeyAPressed(false),
      _isKeySPressed(false),
      _isKeyDPressed(false)
{
    set_has_window(false);

    // It is important to explicitely allow events on the GLArea!
    _glArea.add_events(Gdk::POINTER_MOTION_MASK
            | Gdk::BUTTON_PRESS_MASK
            | Gdk::BUTTON_RELEASE_MASK
            | Gdk::KEY_PRESS_MASK
            | Gdk::KEY_RELEASE_MASK);

    pack_end(_glArea, Gtk::PACK_EXPAND_WIDGET);

    _glArea.signal_realize().connect(
            sigc::mem_fun(*this, &GLArea::realize));
    // It is important that the unrealize signal calls our handler to clean up
    // GL resources *before* the default unrealize handler is called, hence the
    // "false".
    _glArea.signal_unrealize().connect(
            sigc::mem_fun(*this, &GLArea::unrealize), false);
    /*_glArea.signal_render().connect(
            sigc::mem_fun(*this, &GLArea::render));*/

    _glArea.signal_key_press_event().connect(
            sigc::mem_fun(*this, &GLArea::on_key_press_event), false);
    _glArea.signal_key_release_event().connect(
            sigc::mem_fun(*this, &GLArea::on_key_release_event), false);

    // Grab the focus to get all key events no matter what!
    _glArea.set_can_focus(true);
    _glArea.grab_focus();

    show_all();
}

GLArea::~GLArea()
{
}

void GLArea::renderTri()
{
    while(true)
    {
        GLArea::render();
        _glArea.queue_draw();
    }
}

bool GLArea::render()
{
    try {

    _glArea.make_current();
        _glArea.throw_if_error();

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        //draw();
        if(_isKeyWPressed) {
            _matrix[13] += 0.01;
        }
        if(_isKeyAPressed) {
            _matrix[12] -= 0.01;
        }
        if(_isKeySPressed) {
            _matrix[13] -= 0.01;
        }
        if(_isKeyDPressed) {
            _matrix[12] += 0.01;
        }

        glUniformMatrix4fv(_matrixLocation, 1, GL_FALSE, _matrix);
        glDrawArrays(GL_TRIANGLES, 0, 3);

        return true;
    } catch(const Gdk::GLError &error) {
        std::cerr
            << error_string()
            << "Something went wrong in the render callback\n\t"
            << "\n\tDomain: " << error.domain()
            << "\n\tCode: " << error.code()
            << "\n\tWhat: " << error.what()
            << std::endl;
        return false;
    }
}
}

full original sample can be found here. https://github.com/mschwan/glarea-animation
I expect  triangle to be show, or if there be any gl errors or warnings, it be printed, but I get a segmentation fault.
[Info] Realizing GL context
        Intel(R) HD Graphics 4400
        3.2.0 - Build 20.19.15.4963
Segmentation fault


text:
Q: Modifying Avada WordPress Theme I am trying to modify the Avada WordPress Theme. It doesn't seem to write header tags in H1 so I've been looking through the code in /themes/Avada/ to see if I can modify it myself.
I've looked in these files: header.php, page.php, index.php and I can't seem to find anything with the headers.
Looking at their page.php
<div class="post-content">
            <?php the_content(); ?>
            <?php fusion_link_pages(); ?>
        </div>

Does anyone know where the_content(); calls from?

A: You can change the header tags for posts in the file single.php.
You need to look for this code:
avada_render_post_title( $post->ID, false, '', '2' )

And change the 2 to a 1 (which represents the H1) tag.
avada_render_post_title( $post->ID, false, '', '1' )

Now your posts title should appear using the H1 tag.
Source: Avada SEO


text:
Q: Can we include a third parameter inside define function? I saw code in RequireJS where define() contains a third parameter other than dependency modules and callback function. Can we include a third parameter inside the define function? Code:
define("app/tmpl/mainTmpl", ["ax/ext/ui/Button",
                  "ax/ext/ui/Label", "ax/ext/ui/Layout"],
    function (Button, Label, Layout) {
        return function () {
            return {
                //some code
            };
        };
    });

A: The first parameter in your example code is the module name (AKA module id) you may optionally pass to define(). It's not recommended to set the name explicitly under normal circumstances. If omitted, a name is inferred and assigned by the AMD loader or it might be generated by the optimization tool of RequireJS. See this section of the official RequireJS API docs or the AMD API spec.


text:
Q: why does angularJS treat spaces as empty? In angularJS, I have a input field bind with ng-model, have something show if input is not empty.
<input id="name" type="text" ng-model="typeSignature" placeholder="Type your name here">

 Something

When I press space key, the boolean of typeSignature=='' is still true. However, in jQuery the boolean $('#name').val() == '' will be false if I have pressed space.
Why is angularJS treating space differently? How can I make jQuery val() function consistent with anguLarJS, namely treating space as empty as well?

A: The default behavior of angular is to trim the model value.
So, if you want to listen to space in model you can set the flag ng-trim="false"
<input ng-model="test" ng-trim="false"/>


text:
Q: Artifacts in text file I have a test project which allows upload of various text(subs), then content of these text file gets displayed. Problem occurs when characters used, are not alphabet, i.e Cyrillic as in diacritics as ŠŽČĆ. Characters in text file are ok pre upload, but when i opened a uploaded file on server, all characters ŠŽČĆĐ get replaced by a  . Yes, you saw it correctly, it's a rectangle thingy.
I use this line which work great on localhost, but on shared hosting throws a fit.
$temp = iconv(mb_detect_encoding($tmp, mb_detect_order(), true), "UTF-8", utf8_encode($tmp));

Where $temp variable is the string to be decoded.
Is it hosting thing, could i do something to prevent it?
PS: If i don't use utf8_encode on $tmp variable, server throws an error.
Edit1:
First image shows how it looks when file is opened on shared hosting.

And when i copy/paste that thing, it looks like this

sadly it doesn't get rendered on SO. Or lucky, depends of how you look at it ...
Above this sentence is an image, not typed out characters. It is how ever, a text i typed and character that is in a uploaded file copied then pasted when you making post on SO.
Edit2:
I sort a figured it out what's the problem. File is correctly saved as utf8 which contains previously said letters.
When file gets uploaded, these letters get changed to rectangle thing. So when i open file on server, instead ŠŽČĆĐ, i get rectangles. How to prevent server changing anything and to upload as is?
So it's not a formatting thing, athrough setting encoding to utf8 seems to help to at least display it and if i don't set encoding to utf8, it throws an error.
I'm using Laravel as backend.
Edit3:
If i test specific char after being read from file with this
mb_convert_encoding(file($path)[8][9])//It should be **š** character

It shows it's utf8, but if it was it will be shown.
If i try this line:
mb_convert_encoding(file($path)[8][9], "UTF-8", "ISO-8859-1")

then it shows rectangle thing like in file on server.
If i use to detect encoding with additional parameters like:
mb_detect_encoding(file($path)[8], "UTF-8", TRUE);

to determine if it's actual utf8, it says it's false.
And if i paste rectangle thing into google translate it shows an "š".

which is correct letter.
If i use bin2hex() to see hex code and for example argument is š letter, i get 9a hex code.
If anybody has any idea how to recreate function that will differentiate between these rectangles and show correct hex code or char itself, or how to upload to shared hosting without allowing it to change letters encoding in text file, or how to approach whole problem, it would be much obliged.

A: Do not use utf8-encode. It is only to converting from ISO-8859-1 and it doesn't work with Windows-1252.
https://www.php.net/manual/en/function.utf8-encode.php
The second problem is that your code do a double encoding. I have marked two function that convert a string to UTF-8.
$temp = iconv(mb_detect_encoding($tmp, mb_detect_order(), true), "UTF-8", utf8_encode($tmp));
/*      ^^^^^                                                             ^^^^^^^^^^^      */

If the code below do not work, I would debug output of mb_detect_encoding($tmp, mb_detect_order(), true). The default values for mb_detect_order() may be far for optimal for Your situation.
https://www.php.net/manual/en/function.mb-detect-encoding.php
https://www.php.net/manual/en/function.mb-detect-order.php
$temp = iconv(mb_detect_encoding($tmp, mb_detect_order(), true), "UTF-8", $tmp);

You can use mb_convert_encoding() in place of iconv.
https://www.php.net/manual/en/function.mb-convert-encoding.php
For Your problem I would write this code:
/* If there are no Asian languages, the UTF-8 is the only encoding the mb_detect_encoding can recognize. */
if (mb_detect_encoding($tmp, 'UTF-8')) {
    $temp = $tmp;
} else {
    /* It is not UTF-8. Assume WINDOWS-1252. */
    $temp = mb_convert_encoding($tmp, 'UTF-8', 'WINDOWS-1252');
}

It is very hard to reliably detect a particular single byte encoding. I am not aware of any build in PHP function for this.


text:
Q: specifying a hierarchical model in JAGS for R I have data on some dependent varaible y that can be modeled as a function of covariates x1 and x2. y and x1 are observed at the "plot" level, and and x2 is observed at the "site" level. Plot is nested within site, hierarchically. Here are 100 observations of y with associated covariate data.
#generate covariate data at plot and site scales.
x1 <- runif(100,0,1)  #100 plot level observations of x1
x2 <- runif(10,10,20) #10  site level observations of x2

#generate site values - in this case characters A:J
site_1 <- LETTERS[sort(rep(seq(1,10, by = 1),10))]
site_2 <- LETTERS[sort(seq(1,10, by = 1))]

#put together site level data - 10 observations for 10 sites.
site_data <- data.frame(site_2,x2)
colnames(site_data) <- c('site','x2')

#put together plot level data - 100 observations across 10 sites
plot_data <- data.frame(site_1,x1)
colnames(plot_data) <- c('site','x1')
plot_data <- merge(plot_data,site_data, all.x=T) #merge in site level data.

#pick parameter values.
b1 <- 10
b2 <- 0.2

#y is a function of the plot level covariate x1 and the site level covariate x2.
plot_data$y <- b1*plot_data$x1 + b2*plot_data$x2 + rnorm(100)

#check that the model fits. it does.
summary(lm(y ~ x1 + x2, data = plot_data))

I can model y as a function of x1 and x2 no problem in jags using the data frame plot_data which basically replicates the site level observations of  x2 10 times per site.
What I would really like to do however is fit the model hierarchically such that
y[i] ~ x1[i] + x2[j], where [i] indicates the plot level observation and [j] indexes the site. How can I modify the below JAGS code to do this?
#fit a JAGS model
jags.model = "
model{
# priors
b1 ~ dnorm(0, .001)
b2 ~ dnorm(0, .001)
tau <- pow(sigma, -2)
sigma ~ dunif(0, 100)

#normal model
for (i in 1:N){
y[i] ~ dnorm(y.hat[i], tau)
y.hat[i] <- b1*x1[i] + b2*x2[i]
}

} #end model
"

#setup jags data as a list
jd <- list(y=plot_data$y, x1=plot_data$x1, x2=plot_data$x2, N=length(plot_data$y))

library(runjags)
#run jags model
jags.out <- run.jags(jags.model,
                     data=jd,
                     adapt = 1000,
                     burnin = 1000,
                     sample = 2000,
                     n.chains=3,
                     monitor=c('b1', 'b2'))
summary(jags.out)

A: You just need an indexing vector at the response level that corresponds to the unique levels within site (which is easiest if it is coded as a factor). The following model is exactly equivalent to what you already have:
jags.model = "
model{
    # priors
    b1 ~ dnorm(0, .001)
    b2 ~ dnorm(0, .001)
    tau <- pow(sigma, -2)
    sigma ~ dunif(0, 100)

    # Response:
    for (i in 1:N){
        y[i] ~ dnorm(y.hat[i], tau)
        y.hat[i] <- b1*x1[i] + site_effect[plot_site[i]]
    }

    # Effect of site:
    for (s in 1:S){
        site_effect[s] <- b2 * x2_site[site_site[s]]
    }

}
"
# Ensure the site is coded as a factor with the same levels in both data frames:
plot_data$site <- factor(plot_data$site)
site_data$site <- factor(site_data$site, levels=levels(plot_data$site))

#setup jags data as a list
jd <- list(y=plot_data$y, x1=plot_data$x1, plot_site=plot_data$site,
            site_site=site_data$site, x2_site=site_data$x2,
            N=length(plot_data$y), S=nrow(site_data))

library(runjags)
#run jags model
jags.out <- run.jags(jags.model,
                     data=jd,
                     adapt = 1000,
                     burnin = 1000,
                     sample = 2000,
                     n.chains=3,
                     monitor=c('b1', 'b2'))
summary(jags.out)

The advantage of the hierarchical approach is that the effect of site can now be modified to e.g. incorporate a random effect or whatever.
Matt

Edit to add an example of a random effect

The following code adds a random effect of site along with the fixed effect corresponding to x2:
jags.model = "
model{
    # priors
    b1 ~ dnorm(0, .001)
    b2 ~ dnorm(0, .001)
    tau <- pow(sigma, -2)
    sigma ~ dunif(0, 100)
    tau.site <- pow(sigma.site, -2)
    sigma.site ~ dunif(0, 100)

    # Response:
    for (i in 1:N){
        y[i] ~ dnorm(y.hat[i], tau)
        y.hat[i] <- b1*x1[i] + site_effect[plot_site[i]]
    }

    # Effect of site (fixed and random effects):
    for (s in 1:S){
        site_effect[s] <- b2 * x2_site[site_site[s]] + random[site_site[s]]
        random[site_site[s]] ~ dnorm(0, tau.site)
    }

}
"
# Ensure the site is coded as a factor with the same levels in both data frames:
plot_data$site <- factor(plot_data$site)
site_data$site <- factor(site_data$site, levels=levels(plot_data$site))

#setup jags data as a list
jd <- list(y=plot_data$y, x1=plot_data$x1, plot_site=plot_data$site,
            site_site=site_data$site, x2_site=site_data$x2,
            N=length(plot_data$y), S=nrow(site_data))

library(runjags)
#run jags model
jags.out <- run.jags(jags.model,
                     data=jd,
                     adapt = 1000,
                     burnin = 1000,
                     sample = 2000,
                     n.chains=3,
                     monitor=c('b1', 'b2', 'sigma.site', 'sigma'))
summary(jags.out)

This may or may not be a sensible model for your application - it is just an example. In this case, sigma.site is estimated as being quite small because it did not feature in the data simulation.


text:
Q: Center align image action in UIAlertController I have a UIAlertController:
let alert = UIAlertController(title: "Add your photo", message: "", preferredStyle: .alert)

var image = UIImage(named: "avatar.png")

image = image?.withAlignmentRectInsets(UIEdgeInsetsMake(0, view.frame.width/2 - (image?.size.width)!/2, 0, 0))

let imageAction = UIAlertAction(title: "", style: .default, handler: nil)

imageAction.setValue(image?.withRenderingMode(.alwaysOriginal), forKey: "image")

alert.addAction(imageAction)

By default, the icon is being left aligned and I tried to center align it by using UIEdgeInset (line 3 above). Considering the top left corner being the origin (0,0), I tried to position the image at the center along the horizontal axis with the left inset value as in the code but the image is obtained as below. So I know this is not correct. I can manage to get it in the center by trial and error. But I would like to come up with a proper way to center align it. What would be the right way to achieve this? Thank you.

A: You shouldn't use forKey: "image", because is a private api.
If you want to add an image inside an alert controller, you might try with NSLayoutConstraint, doing so:
let alert = UIAlertController(title: "Add your photo", message: "\n\n\n", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Upload", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "Add later", style: .default, handler: nil))
let image = UIImageView(image: UIImage(named: "avatar"))
alert.view.addSubview(image)
image.translatesAutoresizingMaskIntoConstraints = false
alert.view.addConstraint(NSLayoutConstraint(item: image, attribute: .centerX, relatedBy: .equal, toItem: alert.view, attribute: .centerX, multiplier: 1, constant: 0))
alert.view.addConstraint(NSLayoutConstraint(item: image, attribute: .centerY, relatedBy: .equal, toItem: alert.view, attribute: .centerY, multiplier: 1, constant: 0))
alert.view.addConstraint(NSLayoutConstraint(item: image, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 64.0))
alert.view.addConstraint(NSLayoutConstraint(item: image, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 64.0))
self.present(alert, animated: true, completion: nil)

result is:

A:         let alert = UIAlertController(title: "Unfollow John Doe?", message: "", preferredStyle: .actionSheet)

        let imageAction = UIAlertAction(title: "", style: .default, handler: nil)
        let image = UIImage(named: "user_img_a")
        let alertViewPadding: CGFloat = 65.0 //Adjust this as per your need
        let left = -alert.view.frame.size.width / 2 + image!.size.width/2 + 20
       // let left = alert.view.frame.size.width/2 - image!.size.width/2
        let centeredTopoImage = image?.withAlignmentRectInsets(UIEdgeInsetsMake(0, left, 0, 0)).withRenderingMode(.alwaysOriginal)
        imageAction.setValue(centeredTopoImage, forKey: "image")

        let  deleteButton = UIAlertAction(title: "Unfollow", style: .destructive, handler: { (action) -> Void in
            print("Delete button tapped")
            self.arrLikes[sender.tag]=0

            self.tblList.reloadData()
        })

        let cancelButton = UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) -> Void in
            print("Cancel button tapped")

        })

        alert.addAction(imageAction)
        alert.addAction(deleteButton)
        alert.addAction(cancelButton)
        self.present(alert, animated: true, completion: nil)


text:
Q: Cyclical Loop Between OneHotEncoder and KNNImpute in Scikit-learn I'm working with a really simple dataset. It has some missing values, both in categorical and numeric features. Because of this, I'm trying to use sklearn.preprocessing.KNNImpute to get the most accurate imputation I can. However, when I run the following code:
imputer = KNNImputer(n_neighbors=120)

imputer.fit_transform(x_train)

I get the error: ValueError: could not convert string to float: 'Private'
That makes sense, it obviously can't handle categorical data. But when I try to run OneHotEncoder with:
encoder = OneHotEncoder(drop="first")

encoder.fit_transform(x_train[categorical_features])

It throws the error: ValueError: Input contains NaN
I'd prefer to use KNNImpute even with the categorical data as I feel like I'd be losing some accuracy if I just use a ColumnTransform and impute with numeric and categorical data seperately. Is there any way to get OneHotEncoder to ignore these missing values? If not, is using ColumnTransform or a simpler imputer a better way of tackling this problem?
Thanks in advance

A: There are open issues/PRs to handle missing values on OneHotEncoder, but it's not clear yet what the options would be.  In the interim, here's a manual approach.

*

*Fill categorical missings with pandas or SimpleImputer with the string "missing".

*Use OneHotEncoder then.

*Use the one-hot encoder's get_feature_names to identify the columns corresponding to each original feature, and in particular the "missing" indicator.

*For each row and each original categorical feature, when the 1 is in the "missing" column, replace the 0's with np.nan; then delete the missing indicator column.

*Now everything should be set up to run KNNImputer.

*Finally, if desired, postprocess the imputed categorical-encoding columns.  (Simply rounding might get you an all-zeros row for a categorical feature, but I don't think with KNNImputer you could get more than one 1 in a row.  You could argmax instead to get back exactly one 1.)


text:
Q: Ethernet link not detected in ubuntu 14.04 after update Since I ran some update in the past week or so, I have not been able to get a wired connection. Specifically:

*

*Initially, during boot up, the ethernet link light is on As ubuntu
boots up, the link light will go off Ubuntu reports cable is
disconnected If I boot into Windows 7, I can use the internet without
issue.

My problem is similar to what is described at:
Ethernet Lights Not On When Cable Connected And Not Working
lspci entry:
Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 06)

sudo ethtool eth0:
Settings for eth0:
    Supported ports: [ TP MII ]
    Supported link modes:   10baseT/Half 10baseT/Full
                            100baseT/Half 100baseT/Full
                            1000baseT/Half 1000baseT/Full
    Supported pause frame use: No
    Supports auto-negotiation: Yes
    Advertised link modes:  10baseT/Half 10baseT/Full
                            100baseT/Half 100baseT/Full
                            1000baseT/Half 1000baseT/Full
    Advertised pause frame use: Symmetric Receive-only
    Advertised auto-negotiation: Yes
    Speed: 10Mb/s
    Duplex: Half
    Port: MII
    PHYAD: 0
    Transceiver: internal
    Auto-negotiation: on
    Supports Wake-on: pumbg
    Wake-on: g
    Current message level: 0x00000033 (51)
                   drv probe ifdown ifup
    Link detected: no

ifconfig -a
eth0      Link encap:Ethernet  HWaddr d4:3d:7e:26:b2:20
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:300 errors:0 dropped:0 overruns:0 frame:0
          TX packets:300 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:25463 (25.4 KB)  TX bytes:25463 (25.4 KB)

lxcbr0    Link encap:Ethernet  HWaddr 7a:01:dd:5c:17:99
          inet addr:10.0.3.1  Bcast:10.0.3.255  Mask:255.255.255.0
          inet6 addr: fe80::7801:ddff:fe5c:1799/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:77 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 B)  TX bytes:11788 (11.7 KB)

syslog:
Feb  8 18:20:42 newdesk kernel: [    4.048721] r8169 0000:03:00.0 eth0: link down
Feb  8 18:20:42 newdesk kernel: [    4.048751] r8169 0000:03:00.0 eth0: link down
Feb  8 18:20:42 newdesk kernel: [    4.048760] IPv6: ADDRCONF(NETDEV_UP): eth0: link is not ready
Feb  8 18:20:42 newdesk kernel: [    4.048905] IPv6: ADDRCONF(NETDEV_UP): eth0: link is not ready

As I lack another network card, I can only use windows right now. Advice on how to fix this is appreciated.
Thanks!

A: I can confirm this bug.
Faced same issue and It's not wiring problem, it's problem of r8169 driver that appeared recent update. I think they have already found a bug in this module
https://lkml.org/lkml/2015/2/21/161
A temporary fix could be building original realtek driver (r8168) and replace current r8169 with it.
https://unixblogger.wordpress.com/2011/10/18/the-pain-of-an-realtek-rtl8111rtl8168-ethernet-card/

*

*install requirements

sudo apt-get install build-essential

*get and extract the latest driver from Realtek website, enter the directory you unpacked driver to

*build & install driver:

sudo make clean modules
sudo make install

*make sure r8168.ko is present in your kernel drivers:

sudo locate -i r8168

one of lines in the output should be something like this:

/modules/3.13.0-46-generic/kernel/drivers/net/ethernet/realtek/r8168.ko

*ban r8169 and rebuild kernel depencies

sudo echo "blacklist r8169″ >> /etc/modprobe.d/blacklist.conf
sudo depmod -a

*Make it available for boot

sudo echo "r8168″ >> /etc/modules

*After reboot check the loaded driver

lspci -v|grep -A 7 Realtek

Last line should be "Kernel driver in use: r8168″
I hope this helps.


text:
Q: Confused about reverse URL in testing mode In my test file, there is one class with :
INGREDIENTS_URL = reverse("recipe:ingredient-list")

    def setUp(self):
        self.client = APIClient()

    def test_Auth_required(self):
        res = self.client.get(INGREDIENTS_URL)

I have one recipe app, but there are no "recipe-list" anywhere else.
Ingredient endpoint is defined with a router in the view.py :
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('ingredients', views.IngredientViewSet)

And the serializer.py
class IngredientSerializer(serializers.ModelSerializer):

    class Meta:
        model = Ingredient
        fields = ['id', 'name']
        read_only_fields = ['id']

So I wonder how the reverse is working in this case
EDIT 1
I guess the reverse("recipe:ingredient-list") it related with viewsets.ModelViewSet and would inherit of my views.py :
class IngredientViewSet(mixins.ListModelMixin,
                        mixins.UpdateModelMixin,
                        mixins.DestroyModelMixin,
                        viewsets.GenericViewSet):


text:
Q: Trouble slicing based on function +1 I am trying to search c_item_number_one = (r'12" Pipe SA-106 GR. B SCH 40 WALL smls'.upper()) for " to pull both it and all information in front of it. i.e. I want 12"
I thought I could just search for what position " is in...
def find_nps_via_comma_item_one():
    nps = '"'
    print(c_item_number_one.find(nps))
find_nps_via_comma_item_one()

Image showing above function results in 2
and then slice everything off after it
c_item_number_one = (r'12" Pipe SA-106 GR. B SCH 40 WALL smls'.upper())

def find_nps_via_comma_item_one():
    nps = '"'
    print(c_item_number_one.find(nps))
find_nps_via_comma_item_one()

item_one_nps = slice(3)
print(c_item_number_one[item_one_nps])

Issue: It is returning an error
print(c_item_number_one[item_one_nps])

TypeError: slice indices must be integers or None or have an __index__ method

How can I turn the results of my function into an integer? I've tried changing print(c_item_number_one.find(nps)) to return(c_item_number_one.find(nps)) but then it stopped giving a value entirely.
Lastly, the slice portion does not produce the full answer I am looking for 12". Even if I enter the value produced by the function 2
item_one_nps = slice(2)
print(c_item_number_one[item_one_nps])

It only gives me 12. I need to +1 the function results.

A: You could do
sep_char = "\""
c_item_number_one.split(sep_char)[0] + sep_char

A: The print statement prints a value to the console whereas a return returns a value where the function is call.
In your code you are not storing the value but just printing it to the console even when you used return instead of print you weren't making use of the returned value.
1 is being added to the slice since while slicing python excludes the stop index so to include the stop index you add 1
c_item_number_one = (r'12" Pipe SA-106 GR. B SCH 40 WALL smls'.upper())

def find_nps_via_comma_item_one():
    nps = '"'
    return(c_item_number_one.find(nps))

item_one_nps = slice(find_nps_via_comma_item_one()+1)
print(c_item_number_one[item_one_nps])

The following code is more verbose.
c_item_number_one = (r'12" Pipe SA-106 GR. B SCH 40 WALL smls'.upper())

def find_nps_via_comma_item_one():
    nps = '"'
    return(c_item_number_one.find(nps))

index = find_nps_via_comma_item_one()

item_one_nps = slice(index+1)
print(c_item_number_one[item_one_nps])


text:
Q: Can i use Bundling [Bundle.Config] in .net 4 Asp.Net web Application I have my application in .Net framework 4.It is a Asp.Net Web Application.i need to use Bundle.Config in order to use Bundling feature.
I have read many documents saying that, it is feature in .Net framework 4.5 and that to in Asp.Net MVC Application.
I need to make a bundle for Scripts in aspx pages.
Can i include Bundle.Config in my file so that Bundling works.

A: Over couple trial and Reading Bundling i found the solution
Install Web Optimizer framework from NuGet package Manager for the solution include System.Web.Optimization in following file, even in Apsx file.
in Application_StartUp () :
 var bundles = BundleTable.Bundles;
 bundles.UseCdn = true;   //enable CDN support
 var jqueryCdnPath = "http://code.jquery.com/jquery-1.9.1.js";
 var jQueryUICdnPath = "http://code.jquery.com/ui/1.10.3/jquery-ui.js";
 bundles.Add(new ScriptBundle("~/bundles/jquery",jqueryCdnPath));
 bundles.Add(new ScriptBundle("~/bundles/jqueryui", jQueryUICdnPath));

In Aspx page :
  <script src="<%=BundleTable.Bundles.ResolveBundleUrl("~/bundles/jqueryui")%>" type="text/javascript"></script>
  <script src="<%=BundleTable.Bundles.ResolveBundleUrl("~/bundles/jquery")%>" type="text/javascript"></script>

~/bundles/jqueryui : for UI java script
~/bundles/jquery   : for functionality java script.

A: Yes, you can use bundling in ASP.net 4. Use Nuget Package Manager to install Microsoft ASP.Net Web Optimization Framework to your project. Then in global.asax register the bundles in Application_Start method. something like this -
    var jqueryBundle = new ScriptBundle("~/Scripts/jquery");
    jqueryBundle.Include(new string[] {
        "~/Scripts/jquery-1.8.3.js",
        "~/Scripts/jquery-ui-1.9.1.custom.min.js",
        "~/Scripts/jquery-ui-timepicker-addon.js",
        "~/Scripts/jquery.validate.js",
        "~/Scripts/jquery.validate-additional-methods.js"
    });

    BundleTable.Bundles.Add(jqueryBundle);

Then in your aspx page or masterpage call the bundle-
    <%= System.Web.Optimization.Scripts.Render("~/Scripts/jquery") %>

A: *

*Add dll file WebGrease.dll in Reference

*Add Bellow code for js and css in global.asax
dynamic solutioncss = new System.Web.Optimization.StyleBundle("~/bundles/solutionDetailCSSBundle");
solutioncss.Include("~/Style.css", new CssRewriteUrlTransform());
solutioncss.Include("~/incs/highslide/highslide.css", new CssRewriteUrlTransform());
solutioncss.Transforms.Add(new CssMinify());
System.Web.Optimization.BundleTable.Bundles.Add(solutioncss);
dynamic HeaderLinkBundle = new System.Web.Optimization.ScriptBundle("~/bundles/HeaderLinkBundle");
HeaderLinkBundle.Include("~/js/jquery.js");
HeaderLinkBundle.Include("~/js/headerlink.js");
HeaderLinkBundle.Transforms.Add(new JsMinify());
System.Web.Optimization.BundleTable.Bundles.Add(HeaderLinkBundle);
System.Web.Optimization.BundleTable.EnableOptimizations = true;

*Add this bundle of css and js to aspx page.