text:
Q: IndexError: index 4 is out of bounds for axis 0 with size 4 Hey I am having this Index Error where I am trying to composite events but my indices start at 0 and not 1 and while have tried to do a number of things like trying to .append[i+1] I am unable to fix this error I am having.
Theres apparently something wrong with this specific line of code : dset_IDX[offset:offset_next] = event_id[file_indices]
While the .py file is over a 1000 lines of code so I can not show all of it I am able to show the part of the function that is giving me the error
def count_events(files):
    # Because we want to remove events with 0 hits,
    # we need to count the events beforehand (to create the h5 file).
    # This function counts and indexes the events with more than 0 hits.
    # Files need to be iterated in the same order to use the indexes.
    """ This is where we manually specify the file"""
    num_events = 0
    nonzero_file_events = []
    for file_index, f in enumerate(files):
        data = np.load(f, allow_pickle=True)
        nonzero_file_events.append([])
        hits = data['digi_hit_pmt']
        for i in range(len(hits)):
            if len(hits[i]) != 0:
                nonzero_file_events[file_index].append(i)
                num_events += 1
    return num_events, nonzero_file_events

def GenMapping(csv_file):
    mPMT_to_index = {}
    with open(csv_file) as f:
        rows = f.readline().split(",")[1:]
        rows = [int(r.strip()) for r in rows]

        for line in f:
            line_split = line.split(",")
            col = int(line_split[0].strip())
            for row, value in zip(rows, line_split[1:]):
                value = value.strip()
                if value:  # If the value is not empty
                    mPMT_to_index[int(value)] = [col, row]
    npmap = np.zeros((max(mPMT_to_index) + 1, 2), dtype=np.int)
    for k, v in mPMT_to_index.items():
        npmap[k] = v
    return npmap

def GenerateMultiMuonSample_h5(avg_mu_per_ev=2.5, sigma_time_offset=21.2):
    """
    Inputs:
     avg_mu_per_ev == Poisson distribution mean for number of muons in each spill
     sigma_time_offset == Width of spill (Gaussian) in nanoseconds
    """
    files = ['event998.npz']

    # Remove whitespace
    files = [x.strip() for x in files]

    # Check that files were provided
    if len(files) == 0:
        raise ValueError("No files provided!!")
    print("Merging " + str(len(files)) + " files")

    # Start merging

    num_nonzero_events, nonzero_event_indexes = count_events(files)
    print(num_nonzero_events)

    # np.random.poisson( avg_mu_per_ev, number_of_throws )
    num_muons = np.random.poisson(avg_mu_per_ev, num_nonzero_events - 2954)

    # creates h5 file to generate the h5 file

    dtype_events = np.dtype(np.float32)
    dtype_labels = np.dtype(np.int32)
    dtype_energies = np.dtype(np.float32)
    dtype_positions = np.dtype(np.float32)
    dtype_IDX = np.dtype(np.int32)
    dtype_PATHS = h5py.special_dtype(vlen=str)
    dtype_angles = np.dtype(np.float32)
    # sets h5 file to be written
    h5_file = h5py.File('multimuonfile(2).h5', 'w')
    dset_event_data = h5_file.create_dataset("event_data",
                                             shape=(num_nonzero_events,) + IMAGE_SHAPE,
                                             dtype=dtype_events)
    dset_labels = h5_file.create_dataset("labels",
                                         shape=(num_nonzero_events,),
                                         dtype=dtype_labels)
    dset_energies = h5_file.create_dataset("energies",
                                           shape=(num_nonzero_events, 1),
                                           dtype=dtype_energies)
    dset_positions = h5_file.create_dataset("positions",
                                            shape=(num_nonzero_events, 1, 3),
                                            dtype=dtype_positions)
    dset_IDX = h5_file.create_dataset("event_ids",
                                      shape=(num_nonzero_events,),
                                      dtype=dtype_IDX)
    dset_PATHS = h5_file.create_dataset("root_files",
                                        shape=(num_nonzero_events,),
                                        dtype=dtype_PATHS)
    dset_angles = h5_file.create_dataset("angles",
                                         shape=(num_nonzero_events, 2),
                                         dtype=dtype_angles)

    # 22 -> gamma, 11 -> electron, 13 -> muon
    # corresponds to labelling used in CNN with only barrel
    # IWCDmPMT_4pi_full_tank_gamma_E0to1000MeV_unif-pos-R371-y521cm_4pi-dir_3000evts_329.npz has an event
    # with pid 11 though....
    # pid_to_label = {22:0, 11:1, 13:2}

    offset = 0
    offset_next = 0
    mPMT_to_index = GenMapping(PMT_LABELS)
    # Loop over files
    for file_index, filename in enumerate(files):
        data = np.load(filename, allow_pickle=True)
        nonzero_events_in_file = len(nonzero_event_indexes[file_index])
        x_data = np.zeros((nonzero_events_in_file,) + IMAGE_SHAPE,
                          dtype=dtype_events)
        digi_hit_pmt = data['digi_hit_pmt']
        # digi_hit_charge = data['digi_hit_charge']
        # digi_hit_time = data['digi_hit_time']
        # digi_hit_trigger = data['digi_hit_trigger']
        # trigger_time = data['trigger_time']
        delay = 0
        # Loop over events in file
        # Loop over number of muons in each event
        event_id = np.array([], dtype=np.int32)
        root_file = np.array([], dtype=np.str)
        pid = np.array([])
        position = np.array([])
        direction = np.array([])
        energy = np.array([])
        labels = np.array([])

        # with open("ResultFile.txt", "w") as text_file:
        # sys.stdout = open("Result2.txt", "w")

        for i, nmu in enumerate(num_muons):
            # np.savetxt(text_file, i, nmu,fmt="%d")
            # text_file.write("processing output entry " + str(i) + " with " + nmu + " muons")
            print("processing output entry ", i, " with ", nmu, " muons")
            indices = np.random.randint(0, len(digi_hit_pmt), max(1, nmu))
            time_offs = [0.]
            if nmu > 1:
                time_offs = np.append(time_offs, np.random.normal(0., sigma_time_offset, nmu - 1))
            hit_pmts, charge, time = SumEvents(indices, time_offs, data, nmu == 0)
            hit_mpmts = hit_pmts // 19
            pmt_channels = hit_pmts % 19
            rows = mPMT_to_index[hit_mpmts, 0]
            cols = mPMT_to_index[hit_mpmts, 1]
            x_data[i - delay, rows, cols, pmt_channels] = charge
            x_data[i - delay, rows, cols, pmt_channels + 19] = time

            # fix below!!!
            idx0 = indices[0]
            event_id = np.append(event_id, data['event_id'][idx0])
            root_file = np.append(root_file, data['root_file'][idx0])
            pid = np.append(pid, data['pid'][idx0])
            position = np.append(position, data['position'][idx0])
            direction = np.append(direction, data['direction'][idx0])
            energy = np.append(energy, np.sum(data['energy'][indices]))
            labels = np.append(labels, nmu)

        offset_next += nonzero_events_in_file

        file_indices = nonzero_event_indexes[file_index]

        dset_IDX[offset:offset_next] = event_id[file_indices]
        dset_PATHS[offset:offset_next] = root_file[file_indices]
        dset_energies[offset:offset_next, :] = energy[file_indices].reshape(-1, 1)
        dset_positions[offset:offset_next, :, :] = position[file_indices].reshape(-1, 1, 3)
        dset_labels[offset:offset_next] = labels[file_indices]
        print(event_id)
        direction = direction[file_indices]
        polar = np.arccos(direction[:, 1])
        azimuth = np.arctan2(direction[:, 2], direction[:, 0])
        dset_angles[offset:offset_next, :] = np.hstack((polar.reshape(-1, 1), azimuth.reshape(-1, 1)))
        dset_event_data[offset:offset_next, :] = x_data

        offset = offset_next
        print("Finished file: {}".format(filename))

    #sys.stdout.close()
    print("Saving")
    #h5_file.close()
    print("Finished")

# In[ ]:

GenerateMultiMuonSample_h5(avg_mu_per_ev=2.5, sigma_time_offset=21.2)

Traceback
Merging 1 files
2958
processing output entry  0  with  3  muons
processing output entry  1  with  1  muons
processing output entry  2  with  3  muons
processing output entry  3  with  3  muons

Traceback (most recent call last):
  File "C:/Users/abdul/OneDrive/Desktop/ISSP/ISSP-AA/TriumfCNN-AA/EventDisplay.py", line 1068, in <module>
    GenerateMultiMuonSample_h5(avg_mu_per_ev=2.5, sigma_time_offset=21.2)
  File "C:/Users/abdul/OneDrive/Desktop/ISSP/ISSP-AA/TriumfCNN-AA/EventDisplay.py", line 1044, in GenerateMultiMuonSample_h5
    dset_IDX[offset:offset_next] = event_id[file_indices]
IndexError: index 4 is out of bounds for axis 0 with size 4

A: not much info is provided but what i have understood,
the error says that axis 0 has size=4 and you are trying to access index 4 which is not possible with size 4 as it starts with 0 and max index could be 3.


text:
Q: Big Query exports I am trying to export some data from Big Query.
This is done by first saving the table and then exporting it to google cloud storage.
This used to work just fine but recently apparently some tables have nested schemas so exporting as csv does not work anymore. Exporting as a JSON should work, and the export job claims to succeed, but data is not available on google cloud storage.
Anyone experiencing similar issues? Is Google having some problems?
Thanks!

A: well, you can either export them as JSON or flatten the nested fields.
See here the official documentation or this other question on the matter
Did it work?

A: Apparently there is a 5GB limit on the buckets in google cloud which prevented us from exporting our datasets. Pity that the job doesn't just fail with an outofstorage error.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I put an increment o the shopping cart icon in the action bar? I am working on a shop application in Android. On the action bar there is a shopping cart icon and when the icon is clicked it enters in another fragment that lists all the products in the cart. I want to put an increment in the corner of the icon and every time I add an item to the cart that increment shows how many items I have.
Just like this:

Is there any way that I can achieve this? I searched on Google but I couldn't find anything. Thank you in advance.
EDIT: This is the method that adds my items
public boolean findProduct(ProductItem product) {
    if (cartList != null) {
        for (CartItem item : cartList)
            if (item.product.getId() == product.getId()) {
                item.amount++;
                item.setTotalPrice();
                return true;
            }
        cartList.add(new CartItem(product));
    } else cartList.add(new CartItem(product));
    return false;
}

A: I am not exactly sure about your domain so far, but I can put here a pseudo-code for how can you use call back, Hope it will help you.
Suppose below is the fragment in which you are adding into the cart:
public class MyCartFragment extends Fragment{

  private DoSomething myDoSomethingCallBack;// callBack interface
 //Below is your adding/counting function

  public MyCartFragment(DoSomething callback){
    myDoSomethingCallBack = callback;
  }

public boolean findProduct(ProductItem product) {
if (cartList != null) {
    for (CartItem item : cartList)
        if (item.product.getId() == product.getId()) {
            item.amount++;
            item.setTotalPrice();
            return true;
        }
  myDoSomethingCallBack.doPostExecute();
    cartList.add(new CartItem(product));
} else cartList.add(new CartItem(product));
return false;
}

  public interface DoSomething {

    void doPostExecute();
}

}

And Suppose Below is the Activity having Action Bar in it.
public class MyMainActivity extends Activity implements MyCartFragment.DoSomething{

Main_Method()//could be onCreateView or something else
 {
           //here call your MyCartFragment like this.
           MyCartFragment mFragment=new MyCartFragment(MyMainActivity.this);

 }

 @Override
public void doPostExecute() {
 //Now this method will be called when your **findProduct** method will  done calculating and customize this method according to your domain
}

  }


text:
Q: Orderby my needs in foreach loop like by title or something? in a cpt i can check some values (checkboxes) in a metabox. i can access this values by
$meta = get_post_meta(get_the_ID(), '_custom-meta-box', true );

after that, i do a foreach loop:
foreach ($meta as $key11 => $value11) {
if($meta[$key11] > 1) {
    $my_postid11 = $value11;
    $funktion11 =  get_post_meta($my_postid11, 'funktion', true );
    echo ''.get_the_title($my_postid11).'

';
}   }

works fine so far. but: i don't have a clue to order them by my needs like in usual wp_query like
$args=array('order'=>'asc','orderby'=>'wpse_last_word' );

All i need is to order the results in the foreach loop by "wpse_last_word" or by title..
Any ideas?

A: Try below code to filter the data by title in Ascending Order:
$meta = get_post_meta(get_the_ID(), '_custom-meta-box', true );

$title_array = array();

foreach ($meta as $key11 => $value11) {
    if($meta[$key11] > 1) {
        $my_postid11 = $value11;
        $title = get_the_title($my_postid11);
        $id = $my_postid11;
        $title_array[$id] = $title;
    }
}
asort($title_array);
foreach ($title_array as $key22 => $value22) {
    $my_postid22 = $key22;
    $funktion11 =  get_post_meta($my_postid22, 'funktion', true );
    echo ''.$value22.'

';
}

A: If you are trying to order an array (what you are iterating over in a foreach loop) by something you are finding out within the loop itself then it's not going to be possible without first gaining that information.
One way of doing that would be to have a foreach loop beforehand to gain this information.
$array = [ 1, 8, 12, 16 ];
foreach ($array as $key => $entry) {
    unset($array[$key]);
    $array[$key]['value'] = $entry;
    $array[$key]['title'] = uniqid(); // This could be your title (
}

Returns
Array
(
    [0] => Array
        (
            [value] => 1
            [title] => 5ecfb2ee803fa
        )

    [1] => Array
        (
            [value] => 8
            [title] => 5ecfb2ee803fd
        )

    [2] => Array
        (
            [value] => 12
            [title] => 5ecfb2ee803fe
        )

    [3] => Array
        (
            [value] => 16
            [title] => 5ecfb2ee803ff
        )

)

So you can then order the array using PHP Sort Functions For Arrays to order by 'title'
Where I was pointing you to in my comment would be that it is entirely possible to do this instead with wp_query
If you are already looking up posts and post data and meta - you can do it in one go.
If your $meta = get_post_meta(get_the_ID(), '_custom-meta-box', true ); is getting an array of post IDs.
$meta = get_post_meta(get_the_ID(), '_custom-meta-box', true );
$args = array(
    'post_type'  => 'my_custom_post_type',
    'orderby'    => 'tite',
    'order'      => 'ASC',
    'post__in'   => $meta,
);

Would be your query.
You would then cycle through the loop like that to retrieve your titles, permalinks etc.


text:
Q: Get the NAT translated IP and port of some local port I have some software running on port 50885 on a computer behind a NAT
How can I access this port from the internet?
I can initiate something from the computer as I have to launch the app.
If I get it correctly : with my local address:port, lets say : 192.168.0.10:50885
If something goes trough the NAT initiated by the computer, Then there should be some sort of port forwarding created automatically and there should be some sort of publicly IP:PORT that should knock on the 50885 port on the computer behind the NAT. Am I right?
If so, wouldn't it be possible to ask a server-side script like in php, Hey, tell me what this publicly IP & Port are?
I'm a bit confused about Port Forwarding.

A: Per my understanding, assuming you use socket local_ip:local_port to connect remote1_ip:remote1_port. After NAPT device local_ip:local_port becomes translated_ip:translated_port. remote1 can get translated_ip:translated_port but I have not found such service. Next time you establish a new connection with remote2_ip:remote2_port with the same client local_ip:local_port, will translated_ip:translated_port be kept unchanged? Normally NAPT sever will reserve it for some time, say 5 minutes. So if someone from remote3:remote3_port to connect translated_ip:translated_port within 5 minutes (since the last packet sent to translated_ip:translated_port), NAPT server will direct traffic to local_ip:local_port. If remote3_port=remote1_port, though remote1_ip!=remote1_ip, the connection will be accepted by the local socket. If the information expired, NAPT sever will allocate a new translated_ip2:translated_port2.

A: Yes, you would have to query an external script to retrieve the public info from the other side of the router.  There are plenty of websites to get the IP (http://whatismyip.com, http://iplookup.flashfxp.com, etc) but I have never seen one that reports both the IP and Port, they usually only report the IP.  Most NATs use a 1-to-1 relationship on ports, though they CAN use different ports.  If you have your own website (or have a friend that does), it would not be very difficult to write your own script to retrieve the public port.
If you make an OUTBOUND TCP connection from your LAN PC through the router to the outside, then the router generates and keeps track of the necessary NAT lookup info automatically so it can then forward traffic back and forth for that connection.
If you make an INBOUND TCP connection from the outside through the router to your LAN PC, there is no NAT lookup info established automatically.  The router needs to be told ahead of time, via a Port Forwarding rule, which private LAN IP:Port to direct an incoming connection to when it receives a new client connection on a specific public IP:Port.  If your router supports uPNP (and if it is enabled) then your app can use a uPNP API/library to programmably create a Port Forwarding rule in the router when the app opens a listening socket.  Otherwise, if uPNP is not available then you have to configure the router manually instead.


text:
Q: is there a way to not stop script if errors found? i have a php script which sometimes makes some light errors that are not important, but the script stops executing next lines. i want some ini_set or something to make it executes all the script even if there is warning or errors.
note: i can't fix those errors.
Thanks

A: If there are fatal errors, the script will stop no matter what and you can do nothing about it. You see there is nothing like "Resume on error" thing like that is in vb. You can suppress the errors though with @ character.

A: You could try wrapping the "unimportant" code in a try/catch block: http://php.net/manual/en/language.exceptions.php
You probably want to understand why the errors are happening first, though. I'm concerned about the fact that you say the errors aren't important and that you can't fix them.


text:
Q: Script Search users outlook autocomplete Currently I need to loop through all Users on a computer to check if their Outlook autocomplete file contains a certain display name and delete it.
The script will be tested through windows Powershell ISE.
and the script will be a batch file, running a txt file through NK2Edit.
I got the script to run for a specific user and a specific auto completefile
you can see tools and tutorials I used here:
NK2Edit Script
As well as the changes Outlook auto complete files here:
Outlook Auto Complete file differences
I am using the 2010 Outlook model so the file will be different for every user
unlike the older versions that used the profile name with a NK2 at the end.
Here are the commands I am running
C:\Users\name\Desktop\NK2EditTest\NK2Edit.exe /script "C:\Users\name\Desktop\NK2EditTest\remove-old-support.txt" "C:\Users\name\AppData\Local\Microsoft\Outlook\RoamCache\Stream_Autocomplete_X_XXXXXXXX.dat"
while X's represent the random 16 byte key in hexadecimal format.
MY Question:
How can I specify Stream_Autocomplete_X_XXXXX...dat files for multiple users
without hard coding it for every user?

A: So you are asking how to execute the program nk2edit.exe using relative paths for both the executable itself as well as its configuration files. One solution is to place nk2edit.exe as a file in a GPO user logon script and reference the configuration files relative to the executing script. For example (not tested):
# Get path of currently executing PowerShell script
$scriptPath = Split-Path $MyInvocation.MyCommand.Path -Parent
# Form path to nk2edit.exe (must sit in same directory as PowerShell script)
$nk2edit = Join-Path $scriptPath "nk2edit.exe"
# Form path to nk2edit.exe script (must sit in same directory as PowerShell script)
$scriptFile = Join-Path $scriptPath "remove-old-support.txt"
# Execute nk2edit.exe command for each Stream_AutoComplete_* for current user
Get-ChildItem (Join-Path $Env:LOCALAPPDATA "Microsoft\Outlook\RoamCache\Stream_Autocomplete_*") | ForEach-Object {
  & $nk2edit /script $scriptFile $_.FullName
}


text:
Q: How to store integers sepated by commas in a variable in Python I am trying to store randomly generated integers in a single variable. They need to be separated by commas such that I can put the variable into a function and it will accept the syntax.
from SimpleGraphics import *

import random

pieColourR = random.randint(0, 255)
pieColourG = random.randint(0, 255)
pieColourB = random.randint(0, 255)

colourA = (pieColourR, pieColourG, pieColourB)

setFill(colourA)
rect(200, 100, 400, 400)

The three RGB values need to be accepted by the "setFill" function. I am doing this to randomly generate 3 different colours that will be consistent for the entire run time of the program.
Right now I get this error:
_tkinter.TclError: unknown color name "166 134 15"

A: You need to pass the argument to setFill in an expected format. An acceptable one is thus:
colourA = color_rgb(pieColourR, pieColourG, pieColourB)
setFill(colourA)

See here for more info:
http://anh.cs.luc.edu/handsonPythonTutorial/graphics.html#random-colors

A: ukemi has answered your question correctly.  You do not want to pass three arguments into the setFill() function, you want to pass a single argument with a known name or, alternatively, a pseudo-name created using the method ukemi described.
However, there are cases in which you want to convert a tuple or list into separate arguments to pass into a function. This can be done with Python's unpacking syntax:
someFunction(*colorA)


text:
Q: Why an ASP.NET MVC Configuration Error With Sub Folder as Web Application that cannot load Site Master Type Inside of my MVC application, I have a sub-folder named "Admin" that was "Converted to Web Application".  In IIS, the Admin folder has also been setup as a web-application.
After publishing my full application, I get a Configuration Error when trying to open Default.aspx within the Admin folder.
EDIT
I made the suggested change and added:
<location path="." inheritInChildApplications="false">
  <system.web>...</system.web>
</location>

I am now getting a new error:

Parser Error:
  Description: An error occurred during the parsing of a resource required to service this  request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: Could not load type 'UI.Administration.Site'.
Source Error:
Line 1:  <%@ Master Language="C#" CodeBehind="Site.master.cs" Inherits="UI.Administration.Site" %>

A: Looks like an issue with web.config inheritance (parent project has a reference the child project doesn't). You can find a related question on SO here and here.


text:
Q: Cannot connect to MariaDB Columnstore database on Docker I'm running MariaDB 10.5 Columnstore on Docker as described here. This works fine when I connect to the database starting a command line in the container itself.
But when I try to connect with an SQL Client (such as DBeaver) from localhost on port 3306, I get the following error:
Host '_gateway' is not allowed to connect to this MariaDB server

I tried to fix that changing the /etc/my.sql.d/server.cnf file setting:
[mysqld]
bind-address = 0.0.0.0

but the container always fails after restart.
How to make a MariaDB Columnstore container accept connections from localhost and/or other IP addresses?

A: There's no need to change the config file as bind-address is commented out.
The issue is that you need a user to be authorized to a host that's not localhost, root is authorized to localhost only. Creating a new user from inside the container solved the problem.
mysql -u root -p
CREATE USER 'user1'@'%' IDENTIFIED BY 'xxxxxxx';
GRANT ALL PRIVILEGES ON *.* TO 'user1'@'%' WITH GRANT OPTION;


text:
Q: from commandline howto call userdefined functions in shell script Unix shell script:
I have 7 functions those need to be executed as command line inputs, I tried with below code it's not executing function.
if [ "$VAL" == "1" ]
then
fun1
elif [ "$VAL" == "2" ]
then
fun2
elif [ "$VAL" == "3" ]
then
fun3
elif [ "$VAL" == "4"]
then
fun4
elif [ "$$VAL" ==" 5" ]
then
fun5
elif [ "$VAL" == "6" ]
then
fun6
elif [ "$VAL" == "7" ] then
fun7
else
echo -e "Invalid input.............\n"
Help
  exit
fi

Output:
Usage:  ./script  $VAL
#   ./script  2
Invalid input...........

A: Being honest I don't see any bug in your code (besides $$VAL when comparing to 5). Are you sure that VAL is equal 2? Maybe try to call your code in this way ./script 2 instead of ./script $VAL. What is more I would recommend to use case statement:
 case "$VAL" in
 "1")
    fun1
    ;;
 "2")
    fun2
    ;;
 "3")
    fun3
    ;;
 *)
    echo -e "Invalid input.............\n"
    ;;
 esac

A: Hi this is a code for functions in linux, hope this helps
func()
{
if [ thisconditionistrue ]
then
a=100
else
a=500
fi
}

#CallerScript
a=50
passme=Thisisvalue
func $passme


text:
Q: Noise of same order of magnitude than seasonality in a time series everyone! I'm new in this field of statistics and I looked for an answer to this question here but couldn't find any related questions. I'm working with the Lending Club Loan Data, available on Kaggle and I'm trying to decompose a time series into trend, seasonality and noise. This is what I got using the decompose command from R, setting its type to additive. The plot on the right side is the same graph in the log scale.

The random noise seems to be of the same order of magnitude as the seasonality without even considering those strange peaks after 2014. Does this fact (noise of same magnitude as seasonality) mean the time series has no seasonality at all?

A: First of all welcome to StackExchange!
Thank you for uploading the log scale plot which makes more clear what happens.
What decompose(ts, type = 'additive' ) does is to rewrite the time series as:
$X_t = Trend_t + Seasonal_t + Random_t$
The series you are studying has no particular seasonality and this can be seen once you detrend the series: I didn't download the data, but you can see it with:
decompose(log(ts))$x - decompose(log(ts))$trend

which corresponds to:
$log(X_t) - Trend_t = Seasonal_t + Random_t$
If you have patience just upload the that plot and then you'll see there is no periodicity (so no seasonal part there).


text:
Q: LibreOffice x-axis log2 I'm making a chart in LibreOffice, and for my data, I want the x-axis to be a logarithmic scale, but with base 2 instead of 10. How can I do that, if possible?

A: If I've understood you correctly, it appears to be possible to "fake it" by setting the logarithmic major interval to a value of

You will likely need to modify the axis number formating as well, to prevent the axis labels from showing as ugly decimal expansions - for example, setting it to 0 or 1 decimal place.


text:
Q: NumPy: sort ndarray 1st axis by selected 2nd axis element I have an array n x m x k. The task is to sort 1st axis by selected 2nd axis element. Currently i do it like in example below. The input array is 3x3x3, axis 1 is sorted by 1st element of 2nd axis. Is there more efficient way using nditer?
import numpy as np
a = np.random.rand(27).reshape(3,3,3)
print(a)

for i in np.arange(np.shape(a)[0]):
    idx = np.argsort(a[i,:,1])
    a[i]=a[i,idx]

print(a)

A: Approach #1
Get the argsort indices selecting all elements along the first axis in one-go and then use NumPy's advanced-indexing to index along the second axis to get the re-arranged output -
idx = np.argsort(a[:,:,1])
a_out = a[np.arange(a.shape[0])[:,None], idx]

Approach #2
If we are doing in-situ edits in the input array (writing back the results to input), we can run a loop after pre-computing those argsort indices, like so -
idx = np.argsort(a[:,:,1])
for i,indx in enumerate(idx):
    a[i] = a[i,indx]

Benchmarking
# Original method
In [130]: np.random.seed(0)
     ...: a = np.random.rand(100,100,100)

In [131]: %%timeit
     ...: for i in np.arange(np.shape(a)[0]):
     ...:     idx = np.argsort(a[i,:,1])
     ...:     a[i]=a[i,idx]
1000 loops, best of 3: 1.63 ms per loop

# Approach #1
In [132]: np.random.seed(0)
     ...: a = np.random.rand(100,100,100)

In [133]: %%timeit
     ...: idx = np.argsort(a[:,:,1])
     ...: a_out = a[np.arange(a.shape[0])[:,None], idx]
1000 loops, best of 3: 1.6 ms per loop

# Approach #2
In [134]: np.random.seed(0)
     ...: a = np.random.rand(100,100,100)

In [135]: %%timeit
     ...: idx = np.argsort(a[:,:,1])
     ...: for i,indx in enumerate(idx):
     ...:     a[i] = a[i,indx]
1000 loops, best of 3: 1.24 ms per loop


text:
Q: RAM compatability with motherboard - not POSTing in Dual Channel setup I have a problem in installing 2 DIMMs of G.SKill memory in my motherboard.
To start with

*

*motherboard is
http://www.msi.com/product/mb/KA790GX.html#/?div=Detail

*and the RAM is
http://geizhals.at/de/g-skill-dimm-kit-4gb-pc2-8000u-cl5-5-5-15-ddr2-1000-f2-8000cl5d-4gbpq-a286178.html
The scenario is like this:
The RAM works in Single Channel mode, installed on Dimm 0 and 3. But as soon as I try to install it on Dimm 0 and Dimm 1 (for Dual Channel) it simple do not POST, just the CPU Fan power up but no signal on screen.
Additional tips

*

*BIOS is flashed to the latest version.

*I tested with another motherboard, same problem.

*I tested with another pair of identical RAM, same problem.

*Also tested with another PSU, same problem.

That means, I'm getting crazy! :)
Could it be the 2.1v rating? Or because the RAM is PC2-8000?

A: The memory your attempting to use is not supported by your motherboard.  The memory you purchase is expecting 300mv additional voltage then your motherboard can supply.  Of course if you have the memory in the wrong slots then the system also wouldn't even turn on.


text:
Q: Storing outputs from input parameters into the rows of a panda data frame I have a list containing values that I want to perform mathematical operations on with different input parameters that are also stored in a list. For each value in the list, I want to store the results from performing the operation - with each distinct input parameter - row-by-row, where each row corresponds to the subsequent input parameter in the list. Here is a minimal reproducible example of my code:
N = 2 #number of rows
index = []

for i in range(N):
    index.append(i)

df = pd.DataFrame(columns=['Events','Electrons','Photons'], index=index)

vals = [1,2,3]

param = [1,2]

for idx in df.index:

    df['Events'] = param[idx] + vals[0]

    df['Electrons'] = param[idx] + vals[1]

    df['Photons'] = param[idx] + vals[2]

All this code currently does for me is add param[1] to each element in vals and stores them into each of my two specified rows. What I want is to add param[0] to each element in vals, store and save it to the first row of my data frame, then step forward with param[1], store it in the second row, etc...
Eventually, I want to apply this to a much larger data set with more input parameters, but for now I would just like to know how I can best accomplish this task before scaling it up. Any guidance or advice is greatly appreciated!

A: The intent is unclear, but does this do what you want?
param = [1, 2]
vals = [1, 2, 3]

df = pd.DataFrame(columns=["Events", "Electrons", "Photons"], index=range(len(param)))

for i, p in enumerate(param):
    df.iloc[i, :] = np.array(vals) + p

df:
  Events Electrons Photons
0      2         3       4
1      3         4       5

A: By using vectorization you can achieve the task way more efficiently.
Pandas have a lot of vectorization capabilities, but sometimes, NumPy (a pandas dependancy btw) is more flexible. So let assume that we imported NumPy like this:
import numpy as np

Let us also assume that we have a function that receives a params list, a vals list and a list of column names cols:

*

*First, we convert the list to arrays to have vectorization capabilities:

vals = np.array(vals)
params = np.array(params)

*Then, we reshape vals and params to match their role. vals is to be applied on columns, so you can see it as a DF or operator with 1 row and 3 columns. params is to be applied on rows, so you can see it as a DF or operator with 2 rows and 1 columns.

# -1 means fit all the remaining size in here.
vals = vals.reshape(1, -1)
params = params.reshape(-1, 1)

*Then, we do the vectorize operation and save it in a new var. Here, Numpy will distribute the data in a very efficient way. In the example above, the output shape should be the desired (2 rows, 3 columns).

df_numpy = vals + params

*Finally, we create the DataFrame for our need. Note that the pandas will infer the index itself.

df = pd.DataFrame(df_numpy, columns=cols)

So if we gather all the bits in one function (with type annotation for clarity):
from typing import List

import numpy as np
import pandas as pd

def efficient_op(params: List[int], vals: List[int], cols: List[str]) -> pd.DataFrame:
    vals = np.array(vals)
    params = np.array(params)

    vals = vals.reshape(1, -1)
    params = params.reshape(-1, 1)

    df_numpy = vals + params

    df = pd.DataFrame(df_numpy, columns=cols)

    return df


text:
Q: Convergence to $1$ or $-1$ I'm looking for a recurrent sequence $x_0, x_1,\dots, x_n$ that converges to $1$ if $x_0$ is positive and to $-1$ if $x_0$ is negative. The recurrent relation should be something that can be approximated by a polynomial.
Is there such a sequence in mathematics?
P.S. I'm sorry for the lack of formality.

A: This is not possible without restrictions. Indeed, the recurrence that you want must be contracting as it eventually maps any positive to $1$, while a polynomial does the opposite.
You can achieve the desired property with the simple non-polynomial recurrence
$$x_{n+1}=\sqrt[3]{x_n}.$$

For a quasi-linear solution,
$$x_{n+1}=\frac{x_n+\text{sgn}(x_n)}2.$$
But this is of little interest, as
$$x_{n+1}=\text{sgn}(x_n)$$ is enough.

A: Although the term can be approximated by a polynomial is not rigorous, here's something you may like:
$$
x_{n+1} = x_{n} + (x_{n} - x_{n}^{3}) e^{-x_{n}^{2}}
$$
which satisfies the limit condition (by the proof with my intuition and python experiment) and the function $f(x) = x + (x - x^{3})e^{-x^{2}}$ can be approximated by $p(x) = x$ when $|x|$ is large.

A: A possible function for your recursion could be
$$f(x) = \frac 4{\pi}\arctan x$$
The interesting fixpoints here are $x=1$ and $x=-1$.
$f$ can be approximated by its Taylor polynomials but it is unclear what you expect if you replace $f$ by an approximating polynomial. The recursion might not have the same fixpoints and might not converge the way you would like to have it.
Back to $f(x) = \frac 4{\pi}\arctan x$:
Since $f$ is an odd function, you only need to check convergence of $x_{n+1} = f(x_n)$ to $1$ for $x_0>0$.
For $x_0>1$ you have $1< x_n < 2$ and $f$ is contracting on $[1,2]$, hence the recursion converges to the fixpoint $x=1$.
For $0<x_0<1$ you have $0<x_n <1$ and additionally $f(x)>x$ (which you may check for yourself). Hence, $x_n$ is increasing and bounded from above, hence it converges as well to the fixpoint $x=1$.

A: The rational function
$$f(x)={2x\over x^2+1}$$
should do the job. It has fixed points at $x=0$, $1$, and $-1$. It's easy to verify that if $x\gt1$ then $0\lt f(x)\lt1$, and if $0\lt x\lt 1$ then $x\lt f(x)\lt1$, so for any $x_0\gt0$, the sequence defined by $x_{n+1}=f(x_n)$ will converge to $1$. By symmetry (since $f$ is an odd function), any $x_0\lt0$ will give a sequence converging to $-1$.


text:
Q: Nuget pack does not recognize $version$ in dependencies So, previously we called nuget pack with the nuspec file (nuget pack myproj.nuspec). The nuspec looked something like this:
<package>
  <metadata>
    <version>$version$</version>
    [more properties]
    <dependencies>
      <dependency id="MySubProj" version="$version$" />
      [more explicit dependencies]
    </dependencies>
  </metadata>
</package>

I switched the call to (nuget pack myproj.csproj) so our always-outdated explicit dependencies would be auto-generated.
Everything works great, except now the finished nuspec is something like
<package>
  <metadata>
    <version>1.2.3.4</version>
    [more properties]
    <dependencies>
      <dependency id="MySubProj" version="0.0.0.0" />
      [more explicit dependencies]
    </dependencies>
  </metadata>
</package>

While the correct version of MySubProj would also be 1.2.3.4.
More infos:

*

*MySubProj is a project in the same solution

*It is bundled into a separate nuget package

*The version of the MySubProj nuget package as well as the version of the bundled dll are correct.

I don't get what I am doing wrong really and why it would work when using the nuspec directly vs the csproj :/

A: Seems like a very old bug while using a csproj combined with nuspec (which is still there with NuGet 3.5) ...
One way of making this working is by adding an extra property
<package>
  <metadata>
    <version>$version$</version>
    [more properties]
    <dependencies>
      <dependency id="MySubProj" version="$PackageVersion$" />
      [more explicit dependencies]
    </dependencies>
  </metadata>
</package>

And then update your command
NuGet.exe pack myproject.csproj -Version 1.2.3.4 -Properties "PackageVersion=1.2.3.4"

It is not that clean, but it works.


text:
Q: ESLint not recognising Docusaurus aliases when using Typescript? I'm working on a Docusaurus project running TypeScript/ESLint. More specifically, I have the rule:
{
  'import/no-unresolved': 'error',
}

I have got the setup:
 "devDependencies": {
    "@docusaurus/module-type-aliases": "...",
    "@tsconfig/docusaurus": "...",
    "typescript": "..."
  }

and my tsconfig.json extends the Docusaurus TS config:
 "extends": "@tsconfig/docusaurus/tsconfig.json"

When I run the linter I get a few errors:
  2:18  error  Unable to resolve path to module '@docusaurus/Head'         import/no-unresolved
  3:25  error  Unable to resolve path to module '@docusaurus/BrowserOnly'  import/no-unresolved
  5:20  error  Unable to resolve path to module '@theme/Layout'            import/no-unresolved

I suspect these modules are aliases that Docusaurus knows how to resolve, but ESLint doesn't. When I cmd + click on the import, it takes me to the declared module.
I found a proposed solution here but this does not seem to fix my issue:
  settings: {
    'import/no-unresolved': [
      2,
      { ignore: ['^@theme', '^@docusaurus', '^@site'] },
    ],
  }

It could be purely a regex thing? I cannot find anything else on the internet regarding this niche issue so any help would be appreciated.

A: I think the issue here is that you are adding it to the settings portion of the eslintrc. you need to add the snippit to your rules section:
 rules: {
    "import/no-unresolved": [
      2,
      { ignore: ["^@theme", "^@docusaurus", "^@site"] },
    ],

works for me.


text:
Q: Aggregate function outside pivot Is it possible to use a aggregate function outside the pivot?Am trying to do that. Here I write a query which contain an aggregate function outside Pivot it wasn't work.
select id,**sum(num),**jan,feb
from ( select id, num, month(date) as date, val
......
.......
)p
pivot(sum(val) for date in ([jan],[feb])) as pivotanble

if i omit the sum(num) or only use num it is working otherwise not. What will be the solution?
initial input
      id   date       num    val

       1---2001.06.03--2------3

       2---2002.02.05--10-----5

       3----2002.02.09---4----2

Expected
          JAN FEB MAR... year

           0--- 8 --0  -- 14

year will be given as an input here year=2002

A: Could you please refer below URL
Pivoting Without Aggregation

A: Of course, you could just add up all the monthly values to get the yearly value:
SELECT
  id,
  Jan,
  Feb,
  ...
  Year = Jan + Feb + ...
FROM (
  SELECT
    id,
    num,
    date = LEFT(DATENAME(MONTH, date), 3)
  FROM ...
  WHERE ...
) AS s
PIVOT (
  SUM(num)
  FOR date IN (Jan, Feb, ...)
) AS p
;

But you could also calculate the yearly value beforehand in the subselect, using SUM() OVER ():
SELECT
  id,
  Jan,
  Feb,
  ...
  Year
FROM (
  SELECT
    id,
    num,
    date = LEFT(DATENAME(MONTH, date), 3),
    Year = SUM(num) OVER (PARTITION BY LEFT(DATENAME(MONTH, date), 3))
  FROM ...
  WHERE ...
) AS s
PIVOT (
  SUM(num)
  FOR date IN (Jan, Feb, ...)
) AS p
;


text:
Q: What would be an elementary way to prove that $3<\pi<4$ My definition for $\pi$ is twice the first positive real number such that $\cos(x)=0$.
I think it's not even feasible to evaluate that $3.14 <\pi < 3.15$ in elementary level.
Well, the only tool i've learned is the Gamma function. (Such as $\int_0^\infty e^{-x^2} dx = \frac{\sqrt{\pi}}{2}$,$\Gamma(1/2)=\sqrt{\pi}$)
I don't want really much but at least i want to show that $3<\pi<4$.

A: When $x>0$, the Taylor series for $\cos x$ is alternating and eventually decreasing in absolute value, so we can get an upper bound for it by truncating after any positive term after it starts decreasing, and a lower bound by truncating after any negative term after it starts decreasing.
In particular,
$\cos 2 < 1 - \frac{2^2}{2!} + \frac{2^4}{4!} = -\frac{1}{3}$.
Similarly, for $0 \leq x \leq 3/2$, $\cos x > p(x) = 1 - \frac{x^2}{2!} + \frac{x^4}{4!}-\frac{x^6}{6!}$. I claim that $p$ is positive on this interval. To see this, note that $p'(x) = - x + \frac{x^3}{3!} - \frac{x^5}{5!} < -x + \frac{x^3}{6}$, which is negative on the interval $[0, \sqrt{6}]$, so $p$ is decreasing on $[0, \sqrt{6}]$. Also, $p(3/2) = \frac{359}{5120} > 0$; thus $p$ is positive on all of $[0, 3/2]$.
It follows by the intermediate value theorem that $\cos x$ has a zero between $3/2$ and $2$. Since $\cos x$ is positive on $[0, 3/2]$, this is its first positive zero; thus $3 < \pi < 4$.

A: Inscribe a hexagon of side 1 inside a circle of radius 1. Then the triangle inequality (with limits) shows that $6 < 2 \pi$.
There is an elementary proof (see Wikipedia) that $\pi < { 22 \over 7}$
(which is $<4$).
Alternative answer: (I feel the need to redeem myself :-).)
Micah's answer is far more succinct, but I like the following approach as it forges a link between the analytical and geometric aspects.
I am assuming that $\cos $ (and $\sin$) are defined using the usual power series, and $\pi$ is defined as in the question. Since $\sin' = \cos$, we see that $\sin$ is increasing (and hence positive) on $(0,{ \pi \over 2}]$.
By differentiating the function $x \mapsto \cos^2 x+ \sin^2 x$ and evaluating at $x=0$ we can establish the identity $\cos^2 x+ \sin^2 x = 1$. (This gives $\sin {\pi \over 2} = 1$.)
Similarly, by differentiating the function $x \mapsto (\cos x -\sin({\pi \over 2} -x))^2 + (\sin x -\cos({\pi \over 2} -x))^2$ we see that it is constant and by evaluating at $x=0$, we obtain the identities $\cos x =\sin({\pi \over 2} -x)$ and
$\sin x =\cos({\pi \over 2} -x)$.
From this we get $\cos { \pi \over 4} = \sin { \pi \over 4} = {1 \over \sqrt{2}}$.
If $\gamma:[0,1] \to \mathbb{R}^2$ is $C^1$, we define the length as  $l(\gamma) = \sup_{{\cal P}} \sum_k | \gamma(t_{k+1}) -\gamma(t_k)|$, where ${\cal P}$ are the partitions of $[0,1]$ and we note that
$l(\gamma) = \int_0^1 \|\gamma'(t)\| dt$.
Now consider the curves $\lambda(t) = (1,0) + t ({1 \over \sqrt{2}}-1, {1 \over \sqrt{2}})$,
$\gamma(t) = (\cos (t { \pi \over 4}), \sin (t { \pi \over 4}))$, and
$\upsilon(t) = (1,0)+t (0,1)$.

We have $\|\lambda'(t)\| = \sqrt{2 -\sqrt{2}}$, $\|\gamma'(t)\| = {\pi \over 4}$, and $\|\upsilon'(t)\| =1$.
Note that for the straight lines $\lambda, \upsilon$, for any partition $(0=t_1,...,t_n=1)$ we have $l(\lambda) = \sum_k |\lambda(t_{k+1})-\lambda(t_k)|$, and similarly for $\upsilon$. In particular, for any strictly increasing continuous function $\eta:[0,1] \to [0,1]$ with $\eta(0) = 0, \eta(1) = 1$, we have $l(\upsilon) = l(\upsilon \circ \eta)$ (this is true more generally, of course).
We have $\lambda(0) = \gamma(0), \lambda(1) = \gamma(1)$, and taking any partition of the form $(0,t,1)$ with $t \in (0,1)$ we have $l(\gamma) = |\lambda(1)-\lambda(0)| = |\gamma(1)-\gamma(0)| < |\gamma(1)-\gamma(t)| + |\gamma(t)-\gamma(0)| \le l(\gamma)$, and so
$\sqrt{2 -\sqrt{2}} < {\pi \over 4}$. A little manipulation shows that $4(\sqrt{2 -\sqrt{2}}) >3$, which gives $\pi > 3$.
For the other bound, let $\eta(t) = {\sin (t { \pi \over 4}) \over \cos (t { \pi \over 4})}$, then we have $\eta'(t) = {\pi \over 4} {1 \over \cos ^2(t { \pi \over 4})}>0$, and $\|(\upsilon \circ \eta)'(t) \| = {\pi \over 4} {1 \over \cos ^2(t { \pi \over 4})}$. In particular, $\|\gamma'(t)\|  < \|(\upsilon \circ \eta)'(t) \|$ for all $ t \in (0,1]$. It follows that $l(\gamma) < l(\upsilon \circ \eta) = l(\upsilon)$, from which we get $\pi < 4$.


text:
Q: RDS 2012 - Starting RemoteApp from RDWeb Prompts for credentials I have the following Windows 2012 R2 RemoteApp Setup

*

*Server1 - Role (Web Access, connection broker, RD Host) 192.168.100.1

*Server2 - Role (connection broker, RD Host) 192.168.100.2

DNS Entries used for Round Robin

*

*RDWA 192.168.100.1, 192.168.100.2

*RDCB 192.168.100.1, 192.168.100.2

Connection Broker is setup using HA (Server1, Server2) - it uses the RDCB Alias for DNS Round Robin (ClientAccessName)
Collection Name: "General" and am publishing just Notepad. Applied wildcard Cert.
Configured IIS: Default Website Redirection to /RDWeb/..., Allowed for single Signon
GPEDIT on Client machines.. To allow for default Credential Delegation and allowed TERMSRV/* for my testing.
So basically.
From a client if I open up my browser and point to RDWA (remote web access)... i get the remote web form.. I can see notepad. When I click on notepad. I get the following prompt:
Your credentials did not work
Your system administrator does not allow the use of default credentials to log onto the remote computer RDCB.TEST.LOCAL because its identity is not fully verified. Please enter new credentials.
Note:
Before I setup Connecton Broker HA, I was not prompted for this message. It would do the single sign-on OK.
I was maybe thinking that I needed to setup a Kerberos identity called RDCB like I did in Windows 2008 R2. But this looks different in Windows 2012 and wasn't able to find the Powershell command to do this.

A: I did a wee bit of digging around and read that 2012 doesn't use a Kerberos Identity like 2008 R2. So what I tried was enabling the following "Allow delegating default credentials with NTLM-only Server authentication".
This seem to do the trick and now I have single sign-on working correctly.
Thanks for your help.
cheers

A: I start by suggesting you separate your roles, especially if you want to test pre-production. An issue with a session host would directly affect your CB and cause additional problems. If you are covered on dev licensing and using VMs, go nuts. CB role doesn't take much on resources, you could even do Server Core.
As for the issue, I suspect it stems from your permissions group assignment. Try a test domain group, or even just a user.
A lot of the tricks and nonsense from 2008 RDSH seems to be gone from 2012+, but it still has some kinks.


text:
Q: problema con posicionamiento de pantalla cuando el teclado se activa con React native Sucede que cuando se activa el teclado, parece que se coloca por encima de mi vista y esto oculta el input.

A: render() {
    return (<KeyboardAvoidingView
        style={styles.container}
        behavior='position'
        keyboardVerticalOffset={32}>
{... tu vista ...}
</KeyboardAvoidingView>);
}

y a me funciona bien puedes jugar con el keyboardVerticalOffset con números positivos o negativos según te convenga


text:
Q: EditBox character limitation in android In my app i have placed some EditBoxes . When the user types some data i want to stop him from entering too much of characters. i.e When the number of characters exceed 80, the characters typed next to them must be stopped and it must be invisible.
Is there any option for this in android or should I write a code of my own. If I have to write a code of my own please help me friends.

A: Use setFilters or android:maxLength in xml


text:
Q: jQuery .on(); vs JavaScript .addEventListener(); Can someone explain me why is there a difference in the order in which the event handlers are being executed depending on how they have been attached? In the example below I'm using the .on() and .addEventListener() methods to handle a specific event on different DOM elements.
jsfiddle: http://jsfiddle.net/etsS2/
I thought that in this particular example the order in which the event handlers are going to be executed will depend on the event-bubbling - so starting from the original event target and moving up to the document element.
document.getElementById('outer').addEventListener('mouseup', function (event) {
//$('#outer').on('mouseup', function (event) {
    alert('This alert should not show up!');
}, false);

If I uncomment the on(); version everything works as expected - is there a difference in how jQuery handles events contrary to plain JavaScript?

A: When you use .on() at the document level, you're waiting for the event to bubble all the way up to that point. The event handler for any intermediate container will already have been called.
Event "bubbling" is the process by which the browser looks for event handlers registered with parents of the element that was the actual original recipient of the event. It works upwards in the DOM tree.  The document level is the last level checked.  Thus, your handler registered with .on() won't run until that level is reached. In the meantime, the other event handler at the "outer" level is reached first and it is executed by the browser.
Thus, that return false; in the handler registered with .on() is pretty much useless, as would be a call to event.stopPropagation(). Beyond that, mixing native event handler registration with the work that a library like jQuery will do is probably a really bad idea unless you seriously know what you're doing.
There was a question asked almost exactly like this one just a little while ago today.

A: Look at the addEventListener version:
document.getElementById('outer').addEventListener('mouseup', function (event) {
    alert('This alert should not show up!');
}, false);

That works fine because the third argument is useCapture, which specifies whether or not the capture phase of the event should be used.
When you switch to the jQuery version:
$('#outer').on('mouseup', function (event) {
    alert('This alert should not show up!');
}, false);

I think what is happening is the third argument simply overrides your event handler function and causes the event handler to do nothing but return false; which is clearly not what is meant to happen.
From the jQuery docs (emphasis added):

A function to execute when the event is triggered. The value false is
  also allowed as a shorthand for a function that simply does return
  false.

Remove the false argument and the jQuery version will work correctly too:
$('#outer').on('mouseup', function (event) {
    alert('This alert should not show up!');
});

Note that the alert should show up, so the addEventListener approach is working correctly. See @Pointy's answer for why that is.


text:
Q: Understanding Oracle stored procedure I see the syntax for writing procedure in oracle as below
PROCEDURE name [ ( parameter_list ) ]
{ IS | AS }
[ declarative_part ]
BEGIN -- executable part begins
statement; [ statement; ]...
[ EXCEPTION -- executable part ends, exception-handling part begins]
exception_handler; [ exception_handler; ]... ]
END;

Can some one guide me when i should  use AS and IS.

A: SO there is no difference between in using AS and IS Stored procedure


text:
Q: Illegal Divide by Zero exception in cpp and C Here is a simple program which counts number of Individual digits that exactly divides given number.
#include<stdio.h>

int main()
{
    long long t, val, temp, count = 0, val1;
    scanf("%lld", &t);
    while (t--)
    {
        count = 0;
        scanf("%lld", &val);
        val1=val;
        while(val1 != 0)
        {
            temp = val1 % 10;
            val1 = val1 / 10.0 ;
            if (val % temp == 0)
            {
                count++;
            }
        }
        printf("%lld", count);
    }
}

It throws divide by zero exception when my input is
1
300

meaning number of test cases is 1 and value is 300.
But here I am dividing it by a constant 10 so why is that throwing that exception. So what should I do now to handle here?
*I even tried in cpp and faced same problem

A: val%temp

if temp is 0 (which seems to be the case in your program), you are invoking undefined behavior.


text:
Q: how to float hint right? I am trying to achieve a certain "look" in Android that was easy in swift on iOS.
This is my code so far:
  <!-- Email Label -->
        <android.support.design.widget.TextInputLayout
            android:id="@+id/tilUsername"
            android:layout_width="match_parent"
            android:layout_height="80dp"
            android:layout_marginLeft="@dimen/padding_large"
            android:layout_marginRight="@dimen/padding_large"
            android:layout_marginBottom="1dp"
            android:layout_marginTop="4dp"
            app:hintTextAppearance="@style/TextAppearance.App.TextInputLayout"
            android:textColorHint="@color/niceblue"
            android:hint="Username"
            android:theme="@style/TextAppearance.App.TextLabel">
            <EditText android:id="@+id/txtUsername"
                android:layout_width="match_parent"
                style="@style/AppTheme"
                android:background="@drawable/textlines_hint"
                android:ems="10"
                android:padding="6dp"
                android:singleLine="true"
                android:inputType="textEmailAddress"
                android:layout_height="64dp"
                android:hint="Login Email" />
        </android.support.design.widget.TextInputLayout>

This however produces this effect which is bad because the hint and the label overlap..

What I am going for is the ios variant look..

Does anyone have any ideas how we can right align the hint (and optionally the text) but it can't be rtl because it is still "roman" alphabet, I just require it to hint right align and text right align including the hint

A: It's always better to have a single hint or placeholder for TextInputEditText which should be part of TextInputEditText and TextInputLayout parent will use the hint from child view.
But as you need different hint & placeholder for both EditText & TextInputLayout. You can try to use illusion in EditText with transparent text colour till it's not focused.
Your original Layout:
<android.support.design.widget.TextInputLayout
        ....//Should be same as your xml properties
         >
        <EditText android:id="@+id/txtUsername"
            ...//Should be same as your xml properties
            android:textColorHint="@drawable/hint_selector"
            ...
         />
    </android.support.design.widget.TextInputLayout>

Color Selector - EditText Hint - hint_selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_focused="true" android:color="?android:textColorHint" />
  <item android:color="@android:color/transparent" />
</selector>

The above selector will make hint color in EditText as transparent till that view is not focused which will not overlap your TextInputLayout.


text:
Q: google cloud sdk :failed to install, ImportError, DLL load failed I tried to install and requirements was python 2.7.9 , i have same version(and can't up to 15 even 10), i have w8.1 64 and python 32bits
I search how to pass the installer because it says in the image a abstract of installer logs:
paste of installer logs

A: Ok as i said arch of python and win is not the same and google probably give the detected arch for the download:
I will try restart if its the environement variables else i ll try manual install with 32 bits from here
Install sdk cloud
One of the first error line reported persist


text:
Q: Angular material autocomplete: How to prevent valuechange on option selection I have a form field connected to an autocomplete. The markup code looks like this:
<mat-form-field>
  <mat-label>{{'label.descrizione'|translate}}</mat-label>
  <input matInput placeholder="{{'label.descrizione'|translate}}" formControlName="descrizione" required
    [matAutocomplete]="suggestionsAutocomplete">
  <mat-autocomplete #suggestionsAutocomplete>
    <mat-option *ngFor="let suggestion of this.suggestions" [value]="suggestion.value"
      (click)="suggestionSelected(suggestion)">
      {{suggestion.value}} {{suggestion.descrizioneCategoria}}
    </mat-option>
  </mat-autocomplete>
  <mat-error *ngIf="editFG.get('descrizione')?.invalid">{{'validations.required' | translate}}</mat-error>
</mat-form-field>

The autocomplete options are fed in the code that follows. The idea is that while the user is typing, a server request is sent to get the option to be displayed.
// connect suggestions
this.editFG.get('descrizione')?.valueChanges.pipe(
  debounceTime(300),
  filter(value => value.length >= 3),
  switchMap((term: string) => this.operazioni.getSuggestions(TipoOperazione.CASH, this.editFG.get('currency')?.value, term))
).subscribe(suggestions => {
  console.log("Fired value change")
  // console.dir(suggestions)
  this.suggestions = suggestions;
});

The idea here is, every time the user wrote more than 3 chars, but not more frequently than 300ms, the options are "re-updated" based on the typed term.
It works perfectly, but with one drawback. Once the user selects a value in the options, the valuechange emits another event, that triggers another - useless - server call, and I would like to prevent it.
What happens in the selection callback occurs later, and so far the callback is empty.
Is there a way to filter out that event, and just that?


text:
Q: How do I cast data into non-equi columns? I have a dataset of events, grouped by let like so:
set.seed(3)
events <- data.frame(
  let = rep(LETTERS[1:2], each=3),
  age = c(0,sample(1:20, size=2),
          0,sample(1:20, size=2)),
  value = sample(1:100, size=6))

  let age value
1   A   0    61
2   A   4    60
3   A  16    13
4   B   0    29
5   B   8    56
6   B   7    99

How can I cast the data frame so that age is multiple columns grouped into weeks? So for each column, take the value of the largest age that is less than or equal to 0, 7, 14, 21 days.
events.cast <- data.frame(
  let = LETTERS[1:2],
  T0_value = c(61,29),
  T1_value = c(60,99),
  T2_value = c(60,56),
  T3_value = c(13,56))

 let T0_value T1_value T2_value T3_value
1   A       61       60       60       13
2   B       29       99       56       56

A: One option is to cut the 'age' into buckets, get the max row by that group and 'let', then reshape into 'wide' format
library(dplyr)
library(tidyr)
library(stringr)
events %>%
  group_by(grp = cut(age, breaks = c(-Inf,0, 7, 14, 21),
        labels = str_c("T", 0:3, "_value")), let) %>%
  slice(which.max(value)) %>%
  ungroup %>%
  select(-age) %>%
  group_by(let) %>%
  complete(grp = unique(.$grp)) %>%
  fill(value) %>%
  pivot_wider(names_from = grp, values_from = value)
# A tibble: 2 x 5
# Groups:   let [2]
#  let   T0_value T1_value T2_value T3_value
#  <chr>    <int>    <int>    <int>    <int>
#1 A           61       60       60       13
#2 B           29       99       56       56

data
events <- structure(list(let = c("A", "A", "A", "B", "B", "B"), age = c(0L,
4L, 16L, 0L, 8L, 7L), value = c(61L, 60L, 13L, 29L, 56L, 99L)),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))


text:
Q: How do you create an SQL trigger that contains logic from another table I have a messaging application and I'm trying my first trigger.  What I would like to do is on an insert check against a database view to see if the user has exceeded their quota.  If they have insert a message into the messaging table to notify the user.
USE [PhoneMessaging]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[trgAfterInsert] ON [dbo].[Messages]
FOR INSERT
AS

declare @uid smallint;
    declare @Message nvarchar(1000);
    declare @MessageFrom smallint;
    declare @vdate date;
    declare @priority smallint;
    declare @MessageLimit smallint;

    select @uid=i.MessageTo from inserted i;

    set @Message='You have reached your storage limit.';
    set @vdate = CONVERT(VARCHAR,GETDATE(),111);
    set @MessageFrom = 0
    set @priority = 3

    set @MessageLimit = (SELECT dbo.vUserMessageTotals.MessageLimit from dbo.vUserMessageTotals WHERE uid = @uid)

    /*IF (SELECT dbo.vUserMessageTotals.MessageReceivedTotal from dbo.vUserMessageTotals) >= @MessageLimit*/

    insert into Messages
           (MessageTo,[Message],vDate,MessageFrom)
    values(@uid,@Message,@vdate,@MessageFrom)

    PRINT 'AFTER INSERT trigger fired.'


text:
Q: Реализация плавающей линии под элементами меню Всем привет. на сайте есть меню, состоящее из нескольких элементов(слов))
Пытаюсь сделать так, чтобы при наведении на текст - "пункт меню", появлялась линия под ним и перемещалась при наведении на другой элемент меню. Это вроде как сделал, но при скролле, эта линия начинает перемещаться с экраном, т.е. не остается под текстом, пока не наведешь снова.
Не могу понять, что нужно в коде дописать, чтобы она постоянно  находилась под текстом.
ниже код JS и HTML

// create line under menu
// получаем все меню состоящее из элементов
const menu = document.querySelector('.menu__list');
// получаем блок, который будет перемещаться под выбранным элементом меню
const menuLine = document.querySelector('.menu__line');

document.addEventListener('mouseover', function (e) {
    const hoverItemMenu = e.target;
    if (hoverItemMenu.closest('.menu__link')) {

        //получаем положение элемета на который навели
        const hoverItemMenuPageX = hoverItemMenu.getBoundingClientRect();
        //добавим позиционирование полосы
        menuLine.style.cssText = "position:fixed;";

        //устанавливаем координаты полосы
        menuLine.style.left = hoverItemMenuPageX.left + "px";
        menuLine.style.top = hoverItemMenuPageX.bottom + "px";
        menuLine.style.width = hoverItemMenuPageX.width + "px";

        //добавляем класс
        e.target.classList.add('_choosen');

        //убираем класс
        hoverItemMenu.onmouseout = function (event) {
            let targetOut = event.target;
            e.target.classList.remove('_choosen');
        };
    }
})

Orion

Home

Solutions

Features

Resources


text:
Q: Issues with Maven & GitLab CI I'm having an issue with building a project of mine. We have a self-hosted GitLab and maven repo, however, I'm running into issues when trying to pull dependencies from it. I keep on getting the error; Not authorized, ReasonPhrase: Unauthorized.
I can push artifacts fine, it's just pulling.
I have double-checked that the passwords & usernames are correct, the server and repo ID's match.
EDIT:
Here are my files;
GitLab CI Output
ci_settings.xml
pom.xml
.gitlab.ci


text:
Q: Adding usercontrol dynamically through XAML I have 5 UserControls in my project. On Button click of the main window, I have to load the respective user control to main window. Is it possible to achieve through XAML?
I am working with MVVM framework.

A: Well you could do the following {ulternative to Kazuo's suggestion}... worked fine during my quick test.
<Windows.Resources>
    <ComboBox x:Key="options">
        <ControlTemplate x:Name="Button" TargetType="Control">
            <Button/>
        </ControlTemplate>
        <ControlTemplate x:Name="ComboBox" TargetType="Control">
            <ComboBox/>
        </ControlTemplate>
    </ComboBox>
</Windows.Resources>

Then in your window item you put something like this
<Control x:Name="myCotrol" Margin="364,70,27,215" Template="{Binding Mode=OneWay, Source={StaticResource options},Path=SelectedItem}"  />
<TextBox x:Name="Test" HorizontalAlignment="Left" Height="23" Margin="398,83,-1,0"  Text="{Binding Source={StaticResource options},Path=SelectedIndex}" VerticalAlignment="Top" Width="120"/>

with Test being Whatever item decides which control to use.  you can test by putting either 0 or 1 in the Text field of text when you run.  This will then switch between Button or combobox.
Hope this helps :)

A: You could have the user controls already on the main window in Xaml and have them collapsed. You would have a bool value in your viewmodel that you would bind to the visibility of your user controls via a converter (e.g. true converts to Visibility.Visible). When the button on your main window is clicked you would set your bool value to true and the controls would appear.
Not exactly a pure xaml approach so this may not help you


text:
Q: Why does my Alpakka SFTP connector never connect? I'm new to Alpakka/Akka Streams and I'm trying to set up a stream where I stream data between two SFTP servers with my system in the middle, here's the code.
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.alpakka.ftp.scaladsl.Sftp
import akka.stream.alpakka.ftp.{FtpCredentials, SftpSettings}
import akka.stream.scaladsl.Keep
import net.schmizz.sshj.{DefaultConfig, SSHClient}

import java.net.InetAddress

class StreamingSftpTransport {
  implicit val system: ActorSystem = ActorSystem("dr-service")
  implicit val materializer: ActorMaterializer = ActorMaterializer()

  private val PORT = 22
  private val USER = "testsftp"
  private val CREDENTIALS = FtpCredentials.create(USER, "t3st123")
  private val BASEPATH = s"/home/$USER"
  private val FILE_NAME = "testfile"

  // Set up the source system connection
  private val SOURCE_HOSTNAME = "host1"

  private val sourceSettings = SftpSettings.apply(host = InetAddress.getByName(SOURCE_HOSTNAME))
    .withCredentials(CREDENTIALS)
    .withPort(22)

  private val sourceClient = new SSHClient(new DefaultConfig)
  private val configuredSourceClient = Sftp(sourceClient)

  // Set up the destination system connection

  private val DEST_HOSTNAME = "host2"
  private val destSettings = SftpSettings.apply(host = InetAddress.getByName(DEST_HOSTNAME))
    .withCredentials(CREDENTIALS)
    .withPort(22)

  private val destClient = new SSHClient(new DefaultConfig)
  private val configuredDestClient = Sftp(destClient)

  /**
   * Execute the stream from host1 to host2
   */
  def doTransfer(): Unit = {
    val source = configuredSourceClient.fromPath(s"$BASEPATH/$FILE_NAME", sourceSettings)
    val sink = configuredDestClient.toPath(s"$BASEPATH/$FILE_NAME", destSettings)
    val runnable = source.toMat(sink)(Keep.right).run()
  }
}

I've called this from a unit test with new StreamingSftpTransport.doTransfer() but it never attempts to connect.  What am I doing wrong?

A: As suggested by artur in the comment on my question, I wasn't blocking on the future so the JVM was exiting before the connection could be established.
Adding the following line allowed the connections to be established
Await.result(runnable, 180 seconds)

PS: Don't do this in production :)


text:
Q: why \see and \seealso "overwrites" page number? Why  \see and \seealso overwrites page number?
Can i redefine indexing command to keep page number(s) before see output?
Something like:
Cats 1,3,6-7 see also Dog

MWE form this site:
        \documentclass{article}
        \begin{filecontents*}{test2.xdy}
        (require "page-ranges.xdy")
        (define-location-class "arabic-page-numbers"
                               ("arabic-numbers") :min-range-length 1)
        (markup-locref :open "\hyperpage{" :close "}")
        \end{filecontents*}
        \usepackage[hyperindex=false]{hyperref}
        \usepackage{index}
        \newindex{testindex}{idx}{idn}{Index}
        \makeindex
        \begin{document}
        Let's discuss letter d\index[testindex]{d}\index[testindex]{letter|see{d}}
        and c.\index[testindex]{c}\index[testindex]{letter|see{c}}

        \newpage
        \printindex[testindex]
        \end{document}

p.s.
I need some dictionary like entries, but don't want to use glossary, because we need some glossies to define before we use it and there can be different definitions depending in contents of use...Actually I need to  some text after page number and see command looked promising..
Here is a related question (unanswered) Put ';' after page number in index but this removes linebrake in all indexies


text:
Q: Order of application communication in a live score MEAN stack app I want to create a live score web app using the MEAN stack where multiple concurrent users are able to visit the site without any authentication and get scores for up to 6 different sports.
Data within the system can be updated via RESTful requests to a third-party API that I found on the internet.
I understand that socket.io allows for concurrent users/ clients to connect to the application but I'm a little confused as to how the structure and the order of data transfer should look like in this web app.
Is the order something like.. ?:

*

*User goes onto the site

*User selects Football from a dropdown menu

*Web application sends request to the API

*Response is saved in a mongo DB

*Web application queries the DB

*Web application updates latest score on the website

This seems incorrect to me?
I just want to know what would be the most efficient way of getting the scores from the API then displaying it to the users all in real time.
I read in another stack overflow question that:
"
Realtime is when something changes in you database, push that data into website, web page or whatever.

*

*some script receives new data

*you insert that data into db

*you push that data into page
" Realtime Scoring
How would this 'script' work? Do I have to poll the API on every tick and update the database using that? Seems very 'expensive'


text:
Q: What exactly is the Auto Provider in Web Deploy (msdeploy.exe) Can somebody explain (better than the technet/msdn docs) what the auto provider exactly does, how it works, and when to use it.
This is in regard to Web Deploy. I've seen a lot of documentation specifying -dest:auto and it's not really making sense to me.

The auto provider specifies that the provider on a destination will be
  the same as the source provider.
Example
msdeploy.exe -verb:sync -source:appHostConfig="MySite"
  -dest:auto,computername=Server1
The auto provider enables you to avoid entering the full path for the
  -dest argument when the destination argument is the same as the
  -source argument. It also removes the need to copy the manifest file
  separately from an archive or package.
The auto provider takes the source that you specify and uses a
  corresponding location on the destination computer. For example, if
  you specify appHostConfig=Site1 as the source, the destination on the
  target computer will be Site1. This is useful when you want to
  synchronize a Web site "as is" to a remote machine.

technet docs for auto provider
Example that doesn't make sense:
msdeploy.exe -verb:sync -source:package=myapp.zip -dest:auto

Why would you ever set the destination exactly to the source? What is the point? Aren't you simply overwiting the source with iteslf?
The generated cmd file generated from publishing a package in VS2010 generates something like this:
"C:\Program Files\IIS\Microsoft Web Deploy V2\\msdeploy.exe" -source:package='MySourcePath' -dest:auto"

Doesn't auto mean the source will just overwrite itself? But it doesn't, it actually updates the IIS web site (based on the settings in the manifest)
I've tried using package as the destination and in this case it did update the source package and not the IIS site.
The catalyst for this question is that I'm implementing CI and I 've always used msbuild/xcopy in the past. I want to utilize msdeploy now. I want to understand it rather than simply calling the myproject.cmd that's generated from visual studio.
For example, this SO link specifies using the auto provider for the dest argument.
Thanks

A: I think you've actually figured out the answer for yourself.
If the source is a package and the destination is auto, that simply means that the components specified inside the package will be "unzipped" and placed on the destination server. In the -source:package -dest:auto syntax, "auto" does not mean that the package itself is the destination.
And, as you observe, if you specify a package as the destination, whatever you specify for the source will indeed be packaged up as a zip file that you can later use as a source to deploy elsewhere.


text:
Q: how to perform a case-insensitive attribute selector in xquery I'm trying to query an XML column in SQL server, and I want to select records where an attribute value matches a case-insensitive string.
For instance, consider the following value for the XML column:
<items>
  <item k="Description" v="hello" />
</items>

Right now, my select looks like this:
SELECT
MyXmlColumn.value('(/items/item[@k="Description"]/@v)[1]', 'nvarchar(max)') as v
FROM Table

The problem is that the value of the "k" attribute could be 'Description', 'description', or 'DESCRIPTION'.
How do I write the XQuery so that it performs a case-insensitive match?

A: You can use the lower-case function fn:lower-case (which will make the attributes you are searching on lower-case) and then make sure that in your query you use lower-case:
SELECT
MyXmlColumn.value('(/items/item[fn:lower-case(@k)="description"]/@v)[1]', 'nvarchar(max)') as v
FROM [Table]


text:
Q: CSS is only drawing left and top borders, ignoring right and bottom So I have this array
[["1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"],
    ["1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"],
    ["1","1","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","1"],
    ["1","1","1","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","1","1"],
    ["1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","0","0","1","1"],
    ["1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"],
    ["0","0","0","0","0","0","0","0","0","1","1","0","0","0","0","0","0","0","0","0"],
    ["0","0","0","0","0","0","0","0","0","1","1","0","0","0","0","0","0","0","0","0"],
    ["0","0","0","0","0","0","0","0","0","1","1","0","0","0","0","0","0","0","0","0"],
    ["0","0","0","0","0","0","0","0","1","1","1","1","0","0","0","0","0","0","0","0"],
    ["0","0","0","0","0","0","0","1","1","1","1","1","1","0","0","0","0","0","0","0"],
    ["1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"]]

That represents this map

And this function that will draw a border to a blank tile, based on where the 1 is positioned in relation to the 0.
function lagTile(color,a,b){
var div=document.createElement("div");
var size=32;
div.style.width=div.style.height=size+"px";
div.style.left=a*size+"px";
div.style.top=b*size+"px";
canvas.appendChild(div);
if(color.substr(color.length-3,color.length)=="png"){
    div.style.backgroundImage="url(map/"+color+")";
}else{
    div.style.backgroundColor=color;
}
if(b>0 && map[b-1][a]==1 && map[b][a]==0)
{
    div.style.borderTop="4px solid #630";
    div.innerHTML="Top ";
}
if(b<map.length-1 && map[b+1][a]==1 && map[b][a]==0)
{
    div.style.borderBottom="4px solid #630";
    div.innerHTML+="Bottom ";
}
if(a<map[b].length-1 && map[b][a+1]==1 && map[b][a]==0)
{
    div.style.borderRight="4px solid #630";
    div.innerHTML+="Right ";
}
if(a>0 && map[b][a-1]==1 && map[b][a]==0)
{
    div.style.borderLeft="4px solid #630";
    div.innerHTML+="Left ";
}

And gives this result

As you can see, only the left and top border is displayed. And you can see that the text clearly is correct.
Any suggestions on why the bottom and right borders are not drawn?

A: The border is in addition to the size, so the elements grow bigger, and is overlapped by those coming after it (below or to the right). So the border is there, just hidden below the boxes drawn after it. See CSS Box Model for how sizing works. In short, the total width of your boxes are the width of the div + left border size + right border size.
You can fix this by subtracting the border sizes from the sizes of the divs (for instance, when you add a left-border of 4px, you also remove 4px from the width), or by adding box-sizing: border-box to their styling.


text:
Q: Dict columns extraction using for loop There is a dict named 'data'
{
   "error":false,
   "message":"Ok",
   "data":{
      "numFound":1845,
      "start":0,
      "numFoundExact":true,
      "docs":[
         {
            "sub_farmer_id":0,
            "grade_a_produce":320,
            "commodity_image":"red_carrot.jpg",
            "farm_image":"",
            "batch_status":"completed",
            "batch_count":30,
            "franchise_type":"TELF",
            "sr_assignee_id":0,
            "farm_status":"converted",
            "state_name":"RAJASTHAN",
            "farmer_id":1648,
            "grade_a_sell_price":0,
            "id":"11",
            "commodity_name":"Carrot Red",
            "acerage":1,
            "soil_k":0,
            "lgd_state_id":8,
            "soil_n":0,
            "unique_key":"11_8",
            "historic_gdd":0.41,
            "farm_type":"soiless",
            "soil_test_report":"",
            "user_id":1648,
            "expected_yield_delivery_date":"2020-04-30T00:00:00Z",
            "current_gdd":0,
            "soil_p":0,
            "expected_grade_a_produce":636,
            "water_ph":0,
            "end_date":"2020-04-30T00:00:00Z",
            "batch_id":8,
            "expected_delivery_date":"2020-04-30T00:00:00Z",
            "previous_crop_ids":"0",
            "batch_updated_at":"2021-12-29T17:50:58Z",
            "grade_c_rejection":0,
            "water_test_report":"",
            "farm_updated_at":"2021-12-29T17:51:00Z",
            "water_ec":0,
            "start_date":"2019-10-30T00:00:00Z",
            "assignee_id":0,
            "pest_problems":"",
            "expected_production":1060,
            "is_active":true,
            "mobile":"7015150636",
            "grade_b_sell_price":0,
            "irrigation_type":"drip",
            "total_acerage":0,
            "current_pdd":0,
            "commodity_id":68,
            "stage":"flowering",
            "farm_health":"0",
            "expected_grade_b_produce":424,
            "grade_b_produce":740,
            "historic_pdd":0.31,
            "username":"Agritecture",
            "variety_name":"",
            "sr_assignee_name":"",
            "lng":0,
            "locality":"",
            "assignee_name":"",
            "subfarmer_mobile_no":"",
            "commodity_image_96px_icon":"",
            "subfarmer_name":"",
            "batch_end_date":"",
            "lat":0,
            "_version_":1720553030989906000
         }

But I am trying to extract data from list and append in a new csv with different columns so that it looks neat and clean
so, Here I am trying code
       writer = csv.DictWriter(response_data, fieldnames=['Farmer Name', 'Mobile', 'Irrigation Type', 'Batch Status',
                                                           'Soil Parameters',
                                                           'Water Parameters', 'Crop Name', 'Farm Status', 'Farm Type',
                                                           'Franchise Type', 'Farm Total Acerage', 'Batch Acerage',
                                                           'Farm Health(%)', 'Historical Yield(/Acre)',
                                                           'Expected Produce',
                                                           'Actual Yield(/Acre)', 'Actual Produce', 'Crop health(%)',
                                                           'Stage', 'SOP Adherence', 'Assignee', 'Sub Farmer',
                                                           'Last Activity Update', 'Exp. Delivery Date'], delimiter=",")
        writer.writeheader()

        for docs in data.keys():
            writer.writerow(
                {"Farmer Name": docs.get('username'), "Mobile": docs.get('mobile')
                 "Irrigation Type": data.get('irrigation_type'), "Batch Status": data.get('batch_status'),
                 "Soil Parameters": {'N:-': data.get('soil_n'), 'P:-': data.get('soil_p'),
                                     'K:-': data.get('soil_k')},
                 "Water Parameters": {'ec:-': data.get('water_ec'), 'pH:-': data.get('water_ph'), },
                 "Crop Name": data.get('commodity_name'), "Farm Status": data.get('farm_status'),
                 "Farm Type": data.get('farm_type'),
                 "Franchise Type": data.get('franchise_type'), "Farm Total Acerage": data.get('total_acerage'),
                 "Batch Acerage": data.get('batch_count'), "Farm Health(%)": data.get('farm_health'),
                 "Historical Yield(/Acre)": data.get(''),
                 "Expected Produce": data.get('expected_production'), "Actual Yield(/Acre)": data.get('username'),
                 "Actual Produce": data.get('username'), "Crop health(%)": data.get('username'),
                 "Stage": data.get('stage'),
                 "SOP Adherence": data.get('sope'),
                 "Last Activity Update": data.get('end_date'),
                 "Exp. Delivery Date": data.get('expected_delivery_date')
                 })

SO that the data extract from that dict and keep on append on the cdv file as methioned column
But It shows an error
AttributeError: 'str' object has no attribute 'get'

I could not get the columns value in my header from the dict

A: Firstly, it is confusing that you have a dict called data which has a key called "data", and that you are iterating over docs in a dict with a key called "docs".
However, the error is because you are iterating over data.keys(), which returns a string for each value.
An illustrative example:
my_dict = {
    "foo" : "bar",
    "baz" : "luhrmann"
}

for each_key in my_dict.keys():
    print(f"{each_key} : {type(each_key)}")

This will return:
foo : <class 'str'>
baz : <class 'str'>

So in the line docs.get('username'), you are trying to call the get method on a string. The error is telling you that strings do not have this method. I think what you are trying to do is data['docs'].get('username').


text:
Q: Verifying ideals are distinct. In the ring of $Z[\sqrt-5]$, I need to show that the ideals generated by 2, 3 , $1+\sqrt-5$ and $1-\sqrt-5$ are all distinct.
Ideal generated by 2 and ideal generated by 3 are distinct, is obvious. But how to I show that I cannot have $1+\sqrt-5$ as a multiple of 2, for example? Any help is appreciated. Thanks.

A: Use the  norm: $\;N(2)=4$, $N(3)=9$, whereas $\;N(1\pm\sqrt{-5})=6$. If one of $1\pm\sqrt{-5}$ were a multiple of $2$ or $3$, their norms would be multiples of $4$ or $9$.
As to $1+\sqrt{-5}$ being a multiple of $1-\sqrt{-5}$ (or vice versa), as they have the same norm, one of them would be a unit factor of the other. As the only units in this ring are $\pm1$, we see this is impossible.


text:
Q: Typescript: Empty output file when compiling I compile the following code using the latest typescript compiler (1.4)
/// <reference path="typescript.d.ts" />

//import ts = require("typescript");
module cc {
console.log("Hello");
}

using the following compile args
node /TypeScript/built/local/tsc.js -m commonjs --noEmitOnError app.ts -out myApp.js

which compiles Ok and generates the "myApp.js" file.
When I uncomment the import line, I get no error on compiling, but it generates an empty (zero size) "myApp.js" and a file "app.js", even I have specified the --noEmitOnError switch.
This is a strip down example, in fact I specify multiple ".ts" files and I get no error on compiling, the empty "myApp.js" file and for each ".ts" file I specified, I get a ".js" file.
I am using node 0.10.30 on Windows 8.1

A: The --out flag generally should not be used with external modules. Only code that is not part of an external module will be written to the specified output file. Files with a top-level import are an external module.
See also modules documentation, this GitHub issue tracking


text:
Q: Dockerizing Go API not working without setting up git project repo I have a very simple project - a Go API with the following directory structure
├── Dockerfile
├── go.mod
├── go.sum
├── main.go
└── user
    ├── repository.go
    └── user.go

My Dockerfile looks like so
FROM golang:1.17-alpine
WORKDIR /app
COPY go.mod ./
COPY go.sum ./
RUN go mod download
COPY *.go ./
RUN go build -o /api
CMD [ "/api" ]

and I keep getting this error:

[7/7] RUN go build -o /api:
#11 0.462 main.go:4:2: package api/user is not in GOROOT (/usr/local/go/src/api/user)

After reading a bit it looks like I might need to setup a github repository and let go pull the code from git? I think that's honestly crazy since the code is RIGHT THERE in the Docker image.
How can I build/Dockerize this Go project without setting up the git repo like github.com/alex/someproject? Asking because I don't want to publish this onto github - this should be dead simple from local.

A: You do not need to publish your Go code to a service like github.com just to be able to compile it.
All you need to do is to make sure that the code you want to compile is on the machine on which you are compiling it. Your go build command is failing because the package mentioned in the error message is nowhere on the machine to be found.

The following assumes that the Go project itself is in order and you are able to compile it on your local machine. If that is not the case and the answer that follows does not help you resolve the problem then you'll need to include more information in your question, like the content of your go.mod file, main.go file, and also the user package.
Note that COPY *.go ./ will NOT copy all the go files recursively, i.e. it will not copy the files in the ./user/ directory.
COPY:

Each <src> may contain wildcards and matching will be done using Go's
filepath.Match rules.

filepath.Match:

The pattern syntax is:
pattern:
  { term }
term:
  '*'         matches any sequence of non-Separator characters
  '?'         matches any single non-Separator character
  '[' [ '^' ] { character-range } ']'
              character class (must be non-empty)
  c           matches character c (c != '*', '?', '\\', '[')
  '\\' c      matches character c

character-range:
  c           matches character c (c != '\\', '-', ']')
  '\\' c      matches character c
  lo '-' hi   matches character c for lo <= c <= hi

Notice that the '*' term matches any sequence of non-Separator characters, this means that *.go will not match foo/bar.go because of the separator /.

It should be enough to have the following in your Dockerfile:
FROM golang:1.17-alpine

WORKDIR /app
COPY . ./
RUN go build -o /api

CMD [ "/api" ]

But if you want to be selective about the files you copy, then you can do:
COPY go.mod ./
COPY go.sum ./
COPY user/ ./user/
COPY *.go ./


text:
Q: Can I use 'Featured Image' as a hero image and a thumbnail? I am finding a lot of great information for using the_post_thumbnail() to use this feature as a post hero OR a thumbnail, but I'm struggling to figure out how to use the 'Featured image' as both in my templates.
Here's the gist of what I'm trying do:

*

*user uploads a featured image to post, which is cropped to 2400 x 1350 px (hero)

*image is also scaled and saved as a thumb at 880 x 495 px (pixel perfect scaling ratio from hero)

*embed hero size the_post_thumbnail('large') in single.php template and the_post_thumbnail('thumb') on the homepage for the post preview

I think I understand how to access and embed the sizes that I would like to use in the appropriate places but I don't understand the workflow for cropping the image on upload and scaling it to multiple sizes. I found set_post_thumbnail_size(), which gets me halfway there, but how do I create multiple sizes?


text:
Q: Where can I find sample code for Nucleo.NET? I've been researching MVP frameworks for .NET, and Nucleo.NET looks very interesting. I have read (alright, skimmed) the documentation, but I find it a bit hard to get started.
Can anybody point me to any sample code or tutorial to get my feet wet?
Thanks!

A: http://nucleo.codeplex.com/ is a reference to nucleo.net not sure if it is the same as what you want though

A: This project is new, not very popular. That's why there is no samples, tutorials. Try to understand yourself and then create your own sample code to help other people.

A: You can find several blog posts regarding the Nucleo framework (including some examples) on the project coordinator's blog.
http://msmvps.com/blogs/bmains/archive/tags/Nucleo/default.aspx
Hope this helps!


text:
Q: javascript method to catch assigning to missing property I know this has probably been asked everywhere but I'm not sure what it's called to look for it.  Basically I have a javascript object:
var foo = Class.create();
foo.prototype = {
   ...
};

At this point, if somebody says myFooObject.bar = 7 I'd like it to hit some special method as bar is not defined, where I get the key (bar) and the value (7) and then I can do whatever with it.


text:
Q: Rubymine throws a **[BUG] Segmentation fault** when trying to run rspec test I am trying to run my rspec tests from rubymine, but getting this error:
 ...[BUG] Segmentation fault at 0x00000000000438
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-darwin13.0]

-- Crash Report log information --------------------------------------------
   See Crash Report log file under the one of following:
     * ~/Library/Logs/CrashReporter
     * /Library/Logs/CrashReporter
     * ~/Library/Logs/DiagnosticReports
     * /Library/Logs/DiagnosticReports
   for more details.

-- Control frame information -----------------------------------------------
c:0051 p:-17566078017732 s:0152 e:000151 TOP    [FINISH]
c:0050 p:---- s:0150 e:000149 CFUNC  :require
c:0049 p:0022 s:0146 e:000145 BLOCK  /Users/Sunday/workspace/resilience/vendor/bundle/ruby/2.1.0/gems/nokogiri-1.6.6.2/lib/nokogiri.rb:29
c:0048 p:0149 s:0143 e:000142 TOP    /Users/Sunday/workspace/resilience/vendor/bundle/ruby/2.1.0/gems/nokogiri-1.6.6.2/lib/nokogiri.rb:25 [FINISH]
c:0047 p:---- s:0141 e:000140 CFUNC  :require
c:0046 p:0064 s:0137 e:000136 TOP    /Users/Sunday/workspace/resilience/vendor/bundle/ruby/2.1.0/gems/loofah-2.0.2/lib/loofah.rb:3 [FINISH]
c:0045 p:---- s:0135 e:000134 CFUNC  :require...

I have checked on google and followed some stack-overflow answers on how to solve this, but non seems to be working for me.
I have also tried to upgrade the rubymine debugger with the following commands: gem install ruby-debug-base19x --pre and gem install ruby-debug-ide --pre.
the first threw an error:
ruby_debug.c:861:98: error: no member named 'bp' in 'struct rb_control_frame_struct'
if (debug_context->frames[debug_context->stack_size - 1].info.runtime.bp <= thread->cfp->bp),
 but the second was successful. Even then I still get the initial error on rubymine when I try to run my tests.
BTW: the tests run well from the terminal, and tests from other projects run well on rubymine. Only this perticular project is not running.
what can I do to make my rubymine run these rspec test from my projects. Thanks for any help.

A: I finally got it right. I have to go into Rubymine's preferences => Languages and Frameworks => Ruby SDK and Gems to update the version of ruby for the project from 2.1.2 to what is specified in the .ruby-version file for the project, which is 2.1.6.
After doing this, everything worked fine as expected.


text:
Q: $x(y^2+u)u_x-y(x^2+u)u_y=(x^2-y^2)u$ with $u(x,-x)=1$ for $x>0$ Not homework but exercices I like to do...
Solve $x(y^2+u)u_x-y(x^2+u)u_y=(x^2-y^2)u$ with $u(x,-x)=1\;x>0$
Manipulating the auxiliar system of ODEs $\dfrac{dx}{x(y^2+u)}=\dfrac{dy}{-y(x^2+u)}=\dfrac{du}{(x^2-y^2)u}$
I get a pretty simplified expression $(x+y)d(x^2+y^2)=2du$ that I see unusable to find the general solution. I found no better expression. I know the solution has a not very complicated closed form, but I am stuck... Help appreciated.

A: This is a Lagrange method, assuming you know how to do it. I'll give you a hint to find $\varphi$ and then you can similarly find $\psi$, check the Jacobian and solve it.
$$ \frac{\lambda dx + \mu dy + \nu du}{\lambda x(y^2+u)-\mu y(x^2+u)+\nu u(x^2-y^2)} = \frac{dx}{x(y^2+u)}=\frac{dy}{-y(x^2+u)}=\frac{du}{u(x^2-y^2)}$$
For $\lambda=x$, $\mu=y$ and $\nu=-1$ you get
$$ \varphi_x=x \quad \varphi_y=y \quad \varphi_u=-1 $$
and solve it to get $\varphi(x,y,u)=\frac{x^2}{2}+\frac{y^2}{2}-u$.

A: Hint: Left details to you:
$$\dfrac{x\ dx}{x^2y^2+x^2u}=\dfrac{y\ dy}{-x^2y^2-uy^2}=\dfrac{du}{(x^2-y^2)u}$$
$$\dfrac{x\ dx+y\ dy}{x^2y^2+x^2u-x^2y^2-uy^2}=\dfrac{du}{(x^2-y^2)u}$$
$$\color{blue}{d(x^2+y^2)=2du}$$
$$\dfrac{y\ dx}{xy(y^2+u)}=\dfrac{x\ dy}{-xy(x^2+u)}=\dfrac{du}{(x^2-y^2)u}$$
$$\dfrac{y\ dx + x\ dy}{xy(y^2-x^2)}=\dfrac{du}{(x^2-y^2)u}$$
$$\color{blue}{\dfrac{d(xy)}{xy}=-\dfrac{du}{u}}$$


text:
Q: Counting the number of visible rows after autofilter How do you count the number of visible/not null rows (from row 3 onwards, checking if column A is empty) after an autofilter? Right now I am only getting 26...
Full code:
Sub GetPrimaryContacts()

Dim Col As New Collection
Dim itm
Dim i As Long
Dim CellVell As Variant

'Get last row value
LastRow = Cells.SpecialCells(xlCellTypeLastCell).Row

'Loop between all rows to get unique values
For i = 3 To LastRow
    CellVal = Sheets("Master").Range("F" & i).Value
    On Error Resume Next
    Col.Add CellVal, Chr(34) & CellVal & Chr(34)
    On Error GoTo 0
Next i

' Create workbooks - Token Not activated
Call TokenNotActivated
For Each itm In Col
    ActiveSheet.Range("A2:Z2").Select
    Selection.AutoFilter Field:=6, Criteria1:=itm
    Call CountFilterAreaRows
Next

End Sub

A: Here's a function that will count the visible rows in an autofiltered range, even if there are none:
Function CountFilterAreaRows(ws As Excel.Worksheet) As Long
Dim FilterArea As Excel.Range
Dim RowsCount As Long

Set ws = ActiveSheet
For Each FilterArea In ws.AutoFilter.Range.SpecialCells(xlCellTypeVisible)
    RowsCount = RowsCount + FilterArea.Rows.Count
Next FilterArea
'don't count the header
RowsCount = RowsCount - 1
CountFilterAreaRows = RowsCount
End Function

To call it as a function, see the edits above. Using your example you would could call it something like this (Untested):
Sub UseIt()
Dim ws As Excel.Worksheet
Dim itm
Dim col As Collection

'... your col logic

For Each itm In col
Set ws = ActiveSheet
    ActiveSheet.Range("A2:Z2").AutoFilter Field:=6, Criteria1:=itm
    Debug.Print CountFilterAreaRows(ws)
Next itm
End Sub

Note that you should avoid the use of Select.

A: I could be wrong, because I am guessing at what your code is actually doing, but see if this gets what you want done.
For Each itm In Col
    RowCount = Sheets("Master").Rows(itm.Row).Count
    MsgBox RowCount
Next

A: Say we have an AutoFilter with the first row containing headers and nothing below the filtered table:
Sub visiCount()
    Dim r As Range, n as Long
    n = Cells(Rows.Count, 1).End(xlUp).Row
    Set r = Range("A1:A" & n).Cells.SpecialCells(xlCellTypeVisible)
    MsgBox r.Count - 1
End Sub

EDIT ............started at A1 rather than A2