text:
Q: Счетчик реферальной системы сломался( Вот код:
main.py
...
elif message.text == 'Ваши рефералы':
    count = Users.get_ref_count(message.chat.id)
    bot.reply_to(message, text=f'Count: {count}')
...

models.py
from peewee import *

db = SqliteDatabase('users.db')

class BaseModel(Model):
    class Meta:
        database = db

class Users(BaseModel):
    user_id = IntegerField(unique=True)
    ref = IntegerField(default=0)

    @classmethod
    def get_user(cls, user_id):
        return cls.get(user_id == user_id)

    @classmethod
    def get_ref_count(cls, user_id):
        return cls.get(Users.user_id == user_id).ref

    @classmethod
    def increase_ref_count(cls, user_id):
        user = cls.get_user(user_id)
        user.ref += 1
        user.save()

    @classmethod
    def user_exists(cls, user_id):
        query = cls().select().where(cls.user_id == user_id)
        return query.exists()

    @classmethod
    def create_user(cls, user_id):
        user, created = cls.get_or_create(user_id=user_id)

Вот ошибка:
Traceback (most recent call last):
  File "/home/runner/hz/venv/lib/python3.8/site-packages/peewee.py", line 6970, in get
    return clone.execute(database)[0]
Traceback (most recent call last):
  File "/home/runner/hz/venv/lib/python3.8/site-packages/peewee.py", line 6970, in get
    return clone.execute(database)[0]
Traceback (most recent call last):
Traceback (most recent call last):
  File "/home/runner/hz/venv/lib/python3.8/site-packages/peewee.py", line 6970, in get
    return clone.execute(database)[0]
  File "/home/runner/hz/venv/lib/python3.8/site-packages/peewee.py", line 4339, in __getitem__
    return self.row_cache[item]
IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "main.py", line 75, in <module>
    bot.polling(none_stop=True)
  File "/home/runner/hz/venv/lib/python3.8/site-packages/telebot/__init__.py", line 620, in polling
    self.__threaded_polling(non_stop=non_stop, interval=interval, timeout=timeout, long_polling_timeout=long_polling_timeout,
  File "/home/runner/hz/venv/lib/python3.8/site-packages/telebot/__init__.py", line 694, in __threaded_polling
    raise e
  File "/home/runner/hz/venv/lib/python3.8/site-packages/telebot/__init__.py", line 650, in __threaded_polling
    self.worker_pool.raise_exceptions()
  File "/home/runner/hz/venv/lib/python3.8/site-packages/telebot/util.py", line 143, in raise_exceptions
    raise self.exception_info
  File "/home/runner/hz/venv/lib/python3.8/site-packages/telebot/util.py", line 89, in run
    task(*args, **kwargs)
  File "main.py", line 54, in new_func
    count = Users.get_ref_count(message.chat.id)
  File "/home/runner/hz/models.py", line 21, in get_ref_count
    return cls.get(Users.user_id == user_id).ref
  File "/home/runner/hz/venv/lib/python3.8/site-packages/peewee.py", line 6522, in get
    return sq.get()
  File "/home/runner/hz/venv/lib/python3.8/site-packages/peewee.py", line 6973, in get
    raise self.model.DoesNotExist('%s instance matching query does '
models.UsersDoesNotExist: <Model: Users> instance matching query does not exist:
SQL: SELECT "t1"."id", "t1"."user_id", "t1"."ref" FROM "users" AS "t1" WHERE ("t1"."user_id" = ?) LIMIT ? OFFSET ?
Params: [1870006389, 1, 0]



text:
Q: CORS Error in Google App Engine on java server I have two apps.
Frontend(Angular) running on Firebase
Backend Spring Boot (Java11) running on App Engine
Got this error while trying to reach any endpoints in app engine
"Access has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource"
An interesting thing that, everything works fine in my local machine. No issues with cors.
So, I guess the problem is in the configuration of app engine or smth else.
Could someone help me to solve this problem? I've already spent a lot of time trying to fix it.
Already read a lot of stackoverflow similar issues.
The last one: How to configure CORS in a Spring Boot + Spring Security application?
Can't find anything helpful in google docs.
Here my app.yaml file
runtime: java11
instance_class: F4
vpc_access_connector:
  name: projects/<project_id>/locations/<location>/connectors/<connectors_name>

Here my config files:
CorsFilterConfig.java
@Configuration
public class CorsFilterConfig {

    @Value("${allowed-origin}")
    private String allowedOrigin;

    @Bean
    public FilterRegistrationBean<CorsFilter> simpleCorsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.setAllowedOrigins(Collections.singletonList(allowedOrigin));
        config.setAllowedMethods(Collections.singletonList("*"));
        config.setAllowedHeaders(Collections.singletonList("*"));
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }
}

allowedOrigin points to the https://<firebase.domain>
SecurityConfig.java
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .csrf().disable()
                .authorizeRequests().anyRequest().authenticated()
                .and()
                .oauth2Login()
                .and()
                .oauth2ResourceServer().jwt();

Endpoint example
@RestController
@RequestMapping("/test")
@AllArgsConstructor
public class TestController {

    @GetMapping
    public String hello() {
        return "hello world";
    }
}

A: I guess that you can't use app.yaml to control HTTP headers for dynamic handlers. It is only applicable for static content
That's why this config fails to deploy with this error "Unexpected attribute "http_headers" for mapping type script."
instance_class: F4
vpc_access_connector:
  name: projects/<project_id>/locations/<location>/connectors/<connectors_name>
handlers:
  - url: /.*
    script: auto
    http_headers:
      Access-Control-Allow-Origin: *

A: I think your app engine yaml file needs to allow cors in the handler,
You can use this example
handlers:
- url: /images
  static_dir: static/images
  http_headers:
    Access-Control-Allow-Origin: https://frontend.firebase.url.com

You can also use * instead of specifying the url to allow access

A: I had the wrong URLs of allowed origin in my properties. So the config files and all cors configuration in my question are correct.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Type org.hibernate.validator.method.methodvalidator not supported for unwrapping While doing migration of a legacy application in JBoss 4.2/jdk 1.5 to Jboss 7.4/JDK 1.8
we are getting this error. Please help if you have experienced this error in similar conditions.
Spring and hibernate are used.
javax.servlet.ServletException: javax.servlet.jsp.jspException: HV000036: Type org.hibernate.validator.method.MethodValidator not Supported for unwrapping.
org.apache.jasper.runtime.....


text:
Q: TreeViewItem parent node & child node IsSelected separation when hovering over a child node I don't really know how to ask this, but I have a specific style that I want to implement on my TreeView.
So as I understand the TreeView control, when you expand a TreeViewItem node to view it's children, it creates a new ItemsPresenter that's a container for the new child node's TreeViewItem. That means that all the child nodes are connected to each of their parents.
What I want to achieve is, when a child is expanded into view and the parent node is selected, the user hovers over one of the child nodes, that the parent node still has the default selected style activated. Instead of having the IsMouseOver style activated from hovering over one of it's children nodes.
Here is an example:
Selected parent color

What is happening when parent is selected and hovering over child node

What I want it to look like when parent node is selected and when hovering over one of it's children (excuse my amazing paint skills with this one)

Here is my coding for reference
TreeView
    <TreeView Background="{x:Null}" BorderThickness="0" Margin="0,3,0,0">
        <TreeViewItem  Header="Root Node" IsExpanded="True">
            <TreeViewItem Header="Parent Node" IsExpanded="True">
                <TreeViewItem Header="Child Node" IsExpanded="True">
                    <TreeViewItem Header="Child Node" IsExpanded="True">
                        <TreeViewItem Header="Child Node" IsExpanded="True" IsSelected="True"/>
                    </TreeViewItem>
                </TreeViewItem>
            </TreeViewItem>
            ...
            <TreeViewItem Header="Child Node">
                <TreeViewItem Header="Child Node"/>
                <TreeViewItem Header="Child Node"/>
            </TreeViewItem>
            <TreeViewItem Header="Child Node"/>
        </TreeViewItem>
    </TreeView>

Style
<Style x:Key="{x:Type TreeViewItem}" TargetType="{x:Type TreeViewItem}">
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="HorizontalContentAlignment" Value="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
    <Setter Property="VerticalContentAlignment" Value="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
    <Setter Property="Padding" Value="1,0,0,0"/>
    <Setter Property="Foreground" Value="Black"/>
    <Setter Property="FocusVisualStyle" Value="{StaticResource TreeViewItemFocusVisual}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TreeViewItem}">
                <StackPanel>
                    <Border x:Name="Bd" Grid.ColumnSpan="3" BorderThickness="1" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true" Margin="3,0,3,-1" MinHeight="20">
                        <Border.Style>
                            <Style TargetType="{x:Type Border}">
                                <Style.Triggers>
                                    <Trigger Property="IsMouseOver" Value="true">
                                        <Setter Property="Background" Value="Red"/>
                                        <Setter Property="BorderBrush" Value="Black"/>
                                    </Trigger>
                                    <Trigger Property="IsMouseOver" Value="false">
                                        <Setter Property="Background" Value="Transparent"/>
                                    </Trigger>
                                </Style.Triggers>
                            </Style>
                        </Border.Style>
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition MinWidth="19" Width="Auto"/>
                                <ColumnDefinition Width="Auto"/>
                            </Grid.ColumnDefinitions>
                            <ToggleButton x:Name="Expander" ClickMode="Press" IsChecked="{Binding IsExpanded, RelativeSource={RelativeSource TemplatedParent}}" Style="{StaticResource ExpandCollapseToggleStyle}"/>
                            <ContentPresenter x:Name="PART_Header" ContentSource="Header" Grid.Column="1" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                        </Grid>
                    </Border>

                    <ItemsPresenter x:Name="ItemsHost" Grid.ColumnSpan="2" Grid.Column="1" Grid.Row="1"/>
                </StackPanel>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsExpanded" Value="false">
                        <Setter Property="Visibility" TargetName="ItemsHost" Value="Collapsed"/>
                    </Trigger>
                    <Trigger Property="HasItems" Value="false">
                        <Setter Property="Visibility" TargetName="Expander" Value="Hidden"/>
                    </Trigger>
                    <Trigger Property="IsSelected" Value="true">
                        <Setter Property="Background" TargetName="Bd" Value="Green"/>
                        <Setter Property="BorderBrush" TargetName="Bd" Value="Black"/>
                    </Trigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsSelected" Value="true"/>
                            <Condition Property="IsMouseOver" Value="true"/>
                        </MultiTrigger.Conditions>
                        <Setter Property="Background" TargetName="Bd" Value="Red"/>
                    </MultiTrigger>
                    <Trigger Property="IsEnabled" Value="false">
                        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

If anyone has any tips that could help me achieve this, I would appreciate it a lot. Also if I'm trying to do most of this in XAML and not in C#, but if it can't be done, I would be happy to do it in C#. Thanks.

A: I just added some code here.
<Style x:Key="{x:Type TreeViewItem}" TargetType="{x:Type TreeViewItem}">
                <Setter Property="Background" Value="Transparent"/>
                <Setter Property="HorizontalContentAlignment" Value="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
                <Setter Property="VerticalContentAlignment" Value="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
                <Setter Property="Padding" Value="1,0,0,0"/>
                <Setter Property="Foreground" Value="Black"/>
                <Setter Property="FocusVisualStyle" Value="{StaticResource TreeViewItemFocusVisual}"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type TreeViewItem}">
                            <StackPanel>
                                <Border x:Name="Bd" Grid.ColumnSpan="3" BorderThickness="1" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true" Margin="3,0,3,-1" MinHeight="20">
                                    <Border.Style>
                                        <Style TargetType="{x:Type Border}">
                                            <Style.Triggers>
                                                <Trigger Property="IsMouseOver" Value="true">
                                                    <Setter Property="Background" Value="Red"/>
                                                    <Setter Property="BorderBrush" Value="Black"/>
                                                </Trigger>
                                                <Trigger Property="IsMouseOver" Value="false">
                                                    <Setter Property="Background" Value="Transparent"/>
                                                </Trigger>
                                            </Style.Triggers>
                                        </Style>
                                    </Border.Style>
                                    <Grid>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition MinWidth="19" Width="Auto"/>
                                            <ColumnDefinition Width="Auto"/>
                                        </Grid.ColumnDefinitions>
                                        <ToggleButton x:Name="Expander" ClickMode="Press" IsChecked="{Binding IsExpanded, RelativeSource={RelativeSource TemplatedParent}}" Style="{StaticResource ExpandCollapseToggleStyle}"/>
                                        <ContentPresenter x:Name="PART_Header" ContentSource="Header" Grid.Column="1" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                                    </Grid>
                                </Border>

                                <ItemsPresenter x:Name="ItemsHost" Grid.ColumnSpan="2" Grid.Column="1" Grid.Row="1"/>
                            </StackPanel>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsExpanded" Value="false">
                                    <Setter Property="Visibility" TargetName="ItemsHost" Value="Collapsed"/>
                                </Trigger>
                                <Trigger Property="HasItems" Value="false">
                                    <Setter Property="Visibility" TargetName="Expander" Value="Hidden"/>
                                </Trigger>
                                <Trigger Property="IsSelected" Value="true">
                                    <Setter Property="Background" TargetName="Bd" Value="Green"/>
                                    <Setter Property="BorderBrush" TargetName="Bd" Value="Black"/>
                                </Trigger>
                                <MultiTrigger>
                                    <MultiTrigger.Conditions>
                                        <Condition Property="IsSelected" Value="true"/>
                                        <Condition Property="IsMouseOver" Value="true"/>
                                    </MultiTrigger.Conditions>
                                    <Setter Property="Background" TargetName="Bd" Value="Red"/>
                                </MultiTrigger>
                                <Trigger Property="IsEnabled" Value="false">
                                    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                                </Trigger>

                                <!--begin: I added just this, but you can cleanup your xaml and made it better, this just showing how you can do-->
                                <MultiDataTrigger>
                                    <MultiDataTrigger.Conditions>
                                        <Condition Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsSelected}" Value="true"/>
                                        <Condition Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsMouseOver}" Value="true"/>
                                        <Condition Binding="{Binding ElementName=ItemsHost, Path=IsMouseOver}" Value="True"/>
                                    </MultiDataTrigger.Conditions>
                                    <Setter Property="Background" TargetName="Bd" Value="Green"/>
                                </MultiDataTrigger>
                                <!--end-->

                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>


text:
Q: Simple code to read local file from a selection from dropdown box and display it in a textarea (Javascript/ XHTML) I've been trying for days to create a simple code to create a page that can display text files from a local directory. These are the specifications.

*

*XHTML/ Javascript only

*Files are local and from the same directory as the homepage

*Files are in txt/ log form

*Files to be displayed are to be selected from a dropdown box

*Files are to be displayed in a text area

*Compatible for all web browsers, can't use ActiveXObject

This was my closest attempt.
JavaScript
function populate(filename)
{
 var file = document.getElementById('log1').files.(0);
 var reader = new FileReader();
 reader.onload = function(e)
 {
  document.getElementById('myTextarea').value = e.target.result;
 };
 reader.readAsText(file);
}

(X)HTML

    <form id="log1">
        Select File from cng1wlsbe1b:

        <select name="file1">
            <option value="CCS1be1" onclick="populate('log1','ACCS1be1.txt')">CCS1be1</option>
            <option value="CCS1beadm1" onclick="populate('log1','cng1wlsbe1bCCS1beadm1.txt')">CCS1beadm1</option>
            <option value="engine_A" onclick="populate('log1','cng1wlsbe1bengine_A.txt')">engine_A</option>
        </select>
    </form>
    <textarea rows="10" id="myTextarea" name="comment" form="log1" style="width:100%"></textarea>

I just learned coding and I've been taking in bits and pieces of codes from everywhere, so I'm quite sure it's littered with errors. Will any kind Samaritan please enlighten me?
Thank you!

*

*Robin :)

A: I have enough time to at least get you on track with some very insightful things that will put gas in your tank and across the desert.

*

*Use XHTML5 (file names ending with .xhtml until you learn how to work with server code). HTML is parsed (looked at and done stuff with) by the HTML parser which is akin to the army recruiting 4channers only there will be no lulz. XHTML is rendered by the XML parser, it's strict and while not perfect it will (while using Firefox) tell you when you reload the page what the error is as well as what line and column it's located at so you can fix the problem now instead of lulz-wat-problem?

*In JavaScript when you have an array (more than one item being contained it will use solid brackets. In example document.getElementById('example)is singular though if you want to usedocument.getElementsByTagName('a)[0] it will use [0] for the first occurrence, [1] for second, [2] for third and so forth (without quotes).

*Use double quotes for (X)HTML <element attribute="values" /> and single quotes for JavaScript syntax, it will save you a lot of hassle in the future. Also don't mind the whitespace, if you code well you'll use minimal spaces and only ever have more than one space in a row (or more) in JavaScript and your server (aka back-end) code. HTML is text/html whereas XHTML is only XHTML if it's served as application/xhtml+xml; what version the (X)HTML is has nothing to do with the media type/mime.

*When in doubt check MDN (Mozilla Developer Network). Just append mdn to your search queries. https://developer.mozilla.org/en/docs/Web/API/FileReader

*Never use a framework if you want to be competent, most people can't do actual real code and the more dependencies you add the weaker your code becomes and the easier an update to something third party will break everything...on your wedding day.

*Use WinMerge to compare old code to new code, it's freeware and I've never stopped using it.

*Use your browser's developer tools (specifically the console) when trying to debug any JavaScript code. Keep in mind that not all errors will produce output, silent errors suck and hopefully you won't have to deal with silent errors for a good while.

*Save this code using Notepad++ and ensure it's encode as UTF-8 without a BOM (byte order mark) which is only necessary for UTF-16 (you won't be using that unless you're exceptionally local to India I think it is). There is no perfect editor though for freeware once you get used to it you'll find it fairly capable and not sucking up 4GB of RAM, a very respectable balance.

I've cleaned up the code in general and made a basic application. I've never worked with local text files...I know that the user will have to initiate a request to the client (while testing your computer is both the client and the server). The user will have to use a file input element to select files before anything can happen.
This is a fairly advanced topic for you to take on initially though with enough tenacity you'll be able to conquer it.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>

<title>Sample XHTML5 Application</title>

<form id="log1">
<fieldset>

Select File from cng1wlsbe1b:

<input onclick="populate(document.getElementById('file1').value);" type="button" value="clicky clicky" />
<input id="file_upload" type="file" value="" />

<select id="file1" name="file1">
<option value="CCS1be1" onclick="populate('log1','ACCS1be1.txt')">CCS1be1</option>
<option value="CCS1beadm1" onclick="populate('log1','cng1wlsbe1bCCS1beadm1.txt')">CCS1beadm1</option>
<option value="engine_A" onclick="populate('log1','cng1wlsbe1bengine_A.txt')">engine_A</option>
</select>

<textarea rows="10" id="myTextarea" name="comment" form="log1" style="width:100%"></textarea>
</fieldset>
</form>

This won't directly answer your question though it will help you get a couple years past the challenges you'd face on your own and put you in striking distance of your goal. Good luck!


text:
Q: Generating F-distribution from uniform distribution Is it possible to generate a F-distribution from the uniform distribution just how a chi-square distribution is produced by combination of a uniform and exponential all by transformation of variables?
For example, we know that
$$\left(\frac{\frac{U_1}{m}}{\frac{U_2}{n}}\right) \sim F_{m,n}$$
when $U_1=U_1 \sim \chi_m^2$ and $U_2 \sim \chi_n^2$ with $m, n$ degrees of freedom.
For example, we know that $$Y=-2\sum_{j=1}^v\log(U_j) \sim \chi_{2v}^2$$
if $U_j$ are iid uniform$(0,1)$ random variables, and $Y_j=-\lambda \log(u_j)$ are iid exponential$(\lambda)$.
From this, how can I generate a $F_{m,n}$ random variable?


text:
Q: playframework - IOException unable to allocate memory My system is Mint 12 64bit.
I've installed the typesafe stack and created a new play application. Without modifying the code I've tried to run it. This is the output:
http://pastebin.com/6XwmsbAE
Play complains with this error message:
IOException: Cannot run program "javac": java.io.IOException: error=12, Cannot allocate memory

How can I fix this ?
UPDATE:
@Mef
Ok you were definitely right. I've increased the initial RAM from 1 GB to 2 GB (running this on virtualbox). Compiling worked exactly once.
Unfortunately java has made up his mind that even 2 GB aren't enough: Running eclipse and firefox my system uses 1 GB. Then I start sbt and the memory usage rises to about 1.2 GB. One might think that this is sufficient. It isn't. Compilation fails with the same error although 800 MB are still available. Moreover after trying to compile the application the memory usage goes up to 1.6 GB. Strangely enough even while compiling the project it never reaches 2 GB but peaks at about 1.8 GB.
Nevertheless I've tried again and fed 3 gigs of RAM to the virtual machine. Now compiling and running the application works fine. As another miracle with 3 GB available the memory usage never rises above 1.6 GB and stays well below the maximum of 1.8 GB that I saw in the 2 GB iteration.

A: Since this is a general javac error, I doubt that it is Play related. Most likely you really ran out of memory.

A: Actually this is not entirely a system error: tweaking the play config files will allow you to make it work on a system with less than 1GB of memory.
In play-2.0.4/framework/build (or build.bat), you just need to change
java ${DEBUG_PARAM} -Xms512M -Xmx1536M ...

to
java ${DEBUG_PARAM} -Xms128M -Xmx512M ...

Now there can be other issues running play with less memory, but at least the basic setup works.

A: This is very well described in another post and it seems to be a problem with OpenJDK.
How to solve "java.io.IOException: error=12, Cannot allocate memory" calling Runtime#exec()?
Try the following:
# echo 1 > /proc/sys/vm/overcommit_memory

This has worked for me :-)


text:
Q: String extraction in c# winforms I've an xml file like this

  Employee details

now i want to get the empid (i.e 134) from the given xml file in c# winforms. Can somebody help me how to get the emp id
Thanks in advance

A: For quick EmpID, see following:
    string xml = @"
Employee details
";
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);
    string strEmpID = node.Attributes[@"href"].Value.ToString().Split(new char[] { '=' })[1];

Should you want all of the EmpIDs, then can do something like following:
private List<string> GetAllEmpIDs(string xml, string strTag/*Example: @"href" */, char[] caSplitBy, int nItemNumber /*second item in array, 1*/)
{
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);

    List<string> lstEmpID = new List<string>();
    foreach(XmlNode node in doc.DocumentElement.ChildNodes)
    {
        lstEmpID.Add(node.Attributes[strTag].Value.ToString().Split(caSplitBy)[nItemNumber]);
    }

    return lstEmpID;
}

Usage:
    List<string> lstEmpID= GetAllEmpIDs(@"
Employee details
",
                @"href",
                new char[] { '=' },
                1
                );

Let me know, if above is of no help! (0:

A: *

*First load the xml file in a XMLDocument/XMLReader, then get to the href attribute value which is "/Details/Empinfo.asp?empid=134".

*Then use this to instantiate a new Uri class and then use the Uri.Query property which will get you "?empid=134".

*Now look for the first = and extract the entire subsstring after that which should get you 134

A: function NameYourFunction(string xmlFile){
   XmlDocument xml = new XmlDocument();
        xml.Load(xmlFile);
        XmlNode xnode = xml.DocumentElement;
        for (int i = 0; i < xnode.ChildNodes.Count; i++)
        {
            string href = xnode.ChildNodes[i].Attributes["href"].Value;
            string empid = href.Substring(href.IndexOf('='),(href.Length -    href.IndexOf('='))+1);
        }

}

Please check it out. Haven't tried it yet.

A: If you're sure the xml file won't contain other digits you could simply do:
Regex.Match(File.ReadAllText(filename), @"\d+").Value

Also if you have multiple IDs, you could use Regex.Matches. Otherwise you have to parse the xml file to find the right element as pointed out in another answer.
Update per comments:
Regex.Match(File.ReadAllText(filename),
    @"empid=(?<EmployeeID>[^""]+)").Groups["EmployeeID"].Value

A: Try something like this:
using System;
using System.Linq;
using System.Xml.Linq;
using System.Web;

class Example
{
    static void Main()
    {
        String xml = @"

                Employee details

";

        String[] queryString = XElement.Parse(xml)
            .Descendants("a")
            .Attributes("href")
            .FirstOrDefault()
            .Value
            .Split('?');

        String empId = HttpUtility
            .ParseQueryString(queryString[1])["empid"];
    }
}

I wouldn't recommend using regular expressions for something like this - it is better to use an XML API of some sort (I am using LINQ to XML here) and then parse the resulting string.

A: I suggest Read the xml file as Text then extract the employee using RegEx Expression.
Like this way
Using System.Text.RegularExpression;

public ArraList() GetEmployeeList(string XmlText){
  ArrayList lst = new ArrayList();
  RegEx regExp = new RegEx(@"\d{3}");
  MatchCollection mstLst = regExp.Matches(Xmltext);
  foreach(Match iMatch in mstLst){
      lst.Add(iMatch.Value.ToString());
  }

Return lst;
}


text:
Q: Reading CRS using lidR I have a similar issue that reported here: R lidR does not read the CRS of my las file. lidR cannot read the CRS while lasinfo from lastools can.
readLAS("USGS_LPC_MS_Tupelo_UTM15_2015_15RYQ605365_LAS_2016.laz")
#> proj_create: crs not found
#> proj_create: crs not found
#> class        : LAS (v1.2 format 1)
#> memory       : 253.4 Mb
#> extent       : 761421.7, 762000, 3436500, 3438000 (xmin, xmax, ymin, ymax)
#> coord. ref.  : NA
#> area         : 0.84 kunits²
#> points       : 3.32 million points
#> density      : 3.97 points/units²

But the LAS file is not 1.4 (1.2) and the use of rlas 1.4 and lidR 3.2 from github don't help. The laz file can be found here

A: Neither LAStools nor lidR understand the CRS properly. But lasinfo displays more information read in the header.
lidR uses the key 3072 in the GeoTiff Projection Keys which is exected to be the epsg code. In your case it contains 32767 which is not a valid epsg code.
sp::CRS(SRS_string = "ESPG:32767")
#> Error in sp::CRS(SRS_string = "ESPG:32767") : NA

In your case the header contains much more than the EPSG code so maybe there is something you can use to build a valid CRS. But there is nothing that can be parsed automatically in R (as far as I know) except the epsg code.
library(lidR)
readLASheader("USGS_LPC_MS_Tupelo_UTM15_2015_15RYQ605365_LAS_2016.laz")
#> File signature:           LASF
#> File source ID:           0
#> Global encoding:
#>  - GPS Time Type: Standard GPS Time
#>  - Synthetic Return Numbers: no
#>  - Well Know Text: CRS is GeoTIFF
#>  - Aggregate Model: false
#> Project ID - GUID:        1388176b-ba63-483e-1485-144d0f79a00a
#> Version:                  1.2
#> System identifier:        Woolpert ALS70 Merged
#> Generating software:      GeoCue LAS Updater
#> File creation d/y:        326/2015
#> header size:              227
#> Offset to point data:     897
#> Num. var. length record:  3
#> Point data format:        1
#> Point data record length: 28
#> Num. of point records:    3320964
#> Num. of points by return: 2040179 984218 261869 32880 1789
#> Scale factor X Y Z:       0.01 0.01 0.01
#> Offset X Y Z:             0 0 0
#> min X Y Z:                761421.7 3436500 86.85
#> max X Y Z:                762000 3438000 141.06
#> Variable Length Records (VLR):
#>    Variable Length Record 1 of 3
#>        Description: GeoTiff Projection Keys
#>        Tags:
#>           Key 1024 value 1
#>           Key 1026 value 59
#>           Key 2048 value 32767
#>           Key 2049 value 124
#>           Key 2050 value 32767
#>           Key 2051 value 8901
#>           Key 2054 value 9102
#>           Key 2055 value 9
#>           Key 2056 value 7019
#>           Key 2057 value 6
#>           Key 2059 value 7
#>           Key 2061 value 8
#>           Key 3072 value 32767
#>           Key 3073 value 0
#>           Key 3074 value 32767
#>           Key 3075 value 1
#>           Key 3076 value 9001
#>           Key 3077 value 5
#>           Key 3081 value 0
#>           Key 3082 value 1
#>           Key 3083 value 2
#>           Key 3088 value 3
#>           Key 3092 value 4
#>           Key 4097 value 97
#>           Key 4099 value 9001
#>    Variable Length Record 2 of 3
#>        Description: GeoTiff double parameters
#>        data: 0 5e+05 0 -93 0.9996 1 6378137 298.2572 0 0.01745329
#>    Variable Length Record 3 of 3
#>        Description: GeoTiff ASCII parameters
#>        data: NAD_1983_2011_UTM_Zone_15N|projection: Transverse Mercator|PCS Name = NAD_1983_2011_UTM_Zone_15N|NAVD88 - Geoid12A (Meters)|GCS Name = GCS_NAD_1983_2011|Datum = NAD_1983_2011|Ellipsoid = GRS_1980|Primem = Greenwich|
#> Extended Variable Length Records (EVLR):  void

Created on 2021-03-06 by the reprex package (v1.0.0)


text:
Q: I am trying to add an authentication routine to a JEE / jquery /datatables application I have a JQuery / DataTables appilcation that works correctly.  I want to add a routine to the load (actually before load) of index.jsp that checks to see if the current user is authorized to use the app.
My problem is I am not having any luck getting the Authenticate class to run.  Here is my code:
index.jsp:
  <%@page contentType="text/html" pageEncoding="UTF-8"%>
  <%@page import="member.Authenticate" %>
 <!DOCTYPE html>

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

    <link rel="stylesheet" type="text/css" href="css/datatables.min.css"/>
    <link rel ="stylesheet" type="txt/css" href="css/dataTables.jqueryui.min.css"/>

    <title>MEMBER TXN</title>

Member TXN Display

        <form>
            (Enter: last name or last name,first name)
            <input type="text" id="txtSearchCriteria" style="width:222px"/>
            <input id="btnFind" type="button" value="Find" />

            <input id="chkSubsOnly" type="checkbox"  checked="true" />
            Subscribers Only

            <input id="chkCurrentOnly" type ="checkbox" checked="false"/>
            Current Contracts Only
        </form>

                    Subscriber
                    Last Name
                    First Name

                    Transaction
                    Transaction Description
                    Effective Date

My problem appears to be that Authenticate does not get called.
here is the Authenticate Routine (IDE:  NetBeans)  --- appears to work in standalone
    package member;
 import java.io.IOException;
 import javax.servlet.ServletException;
 import javax.servlet.annotation.WebServlet;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import java.sql.Connection;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import javax.servlet.http.HttpSession;
 import oracle.jdbc.pool.OracleDataSource;

 /**
  *
  * @author Ainsworth
  */
 @WebServlet(name = "Authenticate", urlPatterns = {"/Authenticate"})
 public class Authenticate extends HttpServlet {

/**
 * Processes requests for both HTTP GET and POST
 * methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 * @throws java.sql.SQLException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException {
    HttpSession session = request.getSession(true);
    try {

        String userName =
      System.getProperty("user.name").trim().toUpperCase();
        String userName2  = new
   com.sun.security.auth.module.NTSystem().getName().trim().toUpperCase();

        String oracleConnectionString
                = "jdbc:oracle:thin:@(description=(address=(host=oraclehost)(port=1521)(protocol=tcp))(connect_data=(sid=testsid)))";

        OracleDataSource ods = new OracleDataSource();
        ods.setURL(oracleConnectionString);
        ods.setUser("oracleUser");
        ods.setPassword("oraclePassword");
        Connection ora = ods.getConnection();

        String strGetAuthRecordCount
                = "SELECT COUNT(*) "
                + "FROM APP_USERS "
                + "WHERE UPPER(USER_ID) = ? AND APP_NAME = 'MEMBER_TXN' ";

        PreparedStatement stmtAuthRecordCount;

        stmtAuthRecordCount = ora.prepareStatement(strGetAuthRecordCount);
        stmtAuthRecordCount.setString(1,userName);

        ResultSet rsAuth = stmtAuthRecordCount.executeQuery();
        rsAuth.next();
        if (rsAuth.getInt(1) > 0) {
            session.setAttribute("OK","true");

        } else {

        session.setAttribute("OK","false");
                }

    } catch (Exception ex) {
        session.setAttribute("OK","error");
    }
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
 * Handles the HTTP GET method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        processRequest(request, response);
    } catch (SQLException ex) {
    }
}

/**
 * Handles the HTTP POST method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        processRequest(request, response);
    } catch (SQLException ex) {
    }
}

/**
 * Returns a short description of the servlet.
 *
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}

A: I changed the first part of my javascript to the following:


text:
Q: Python Programming: Classes I have just started learning Python and wanted to gain a better understanding of classes.
Here are two examples that are in my textbook, the first I understand pretty well, however, I do not understand the use of "self" and "other" in the second example.
Could someone break the code down for me in layman terms, step-by-step and explain to me what is happening? I want to fully grasp how to use the parameters in the class' methods. Would appreciate any help, I really want to get the hang of this! Thanks.
class Album(object):
    def __init__(self, name, player, year, tracks):
        self.name = name
        self.player = player
        self.year = year
        self.tracks = tracks

    def num_years_ago(self, current_year):
        "Return the number of years since album was released"
        return current_year - self.year

from math import gcd

class Fraction(object):
    def __init__(self, num, denom):
        g = gcd(num, denom)
        self.num = num//g
        self.denom = denom//g

    def __add__(self, other):
        return Fraction(self.num * other.denom + self.denom * other.num,
                       self.denom * other.denom)

    def __eq__(self, other):
        return self.num == other.num and self.denom == other.denom

A: Great question! I'm excited you're reaching out to get a better understanding of it rather than floating along like I did in the beginning, haha!
You can basically think of classes like a small robot. The robot has some specific characteristics like a face and world domination plans (attributes) and the robot can do stuff like world domination (functions).
If we think about your first class like a small robot:
class Album(object):
    def __init__(self, name, player, year, tracks):
        self.name = name
        self.player = player
        self.year = year
        self.tracks = tracks

    def num_years_ago(self, current_year):
        "Return the number of years since album was released"
        return current_year - self.year

The name of our robot is Album. So Album has a sense of self, and it also knows its name, who made it ("player"), the year it was made, and some sick beats on some tracks. The robot can do some math and tell you how long ago it was made.
In Pythonic speak, this means you can "build" Album by initializing an Album object with Album(). However, Album needs to know stuff about himself! So you have to include some arguments in that constructor. That looks like Album("Dirty Computer", "Janelle Monae", 2018, "Pynk"). (You don't need to include "self" because Album already knows its a robot!)
To break down the constructor, since you've given Album some stuff to know about itself, it needs to really internalize that, so you set Album's attributes to the ones you told it. That's what the self.name = name, self.player = player, self.year = year, and self.tracks = tracks lines are for.
Now if I ask it "How long have you been on this earth, Album?", it may think "longer than humans can comprehend", but it will definitely answer with the num_years_ago function. To call this, since you have to have a robot to ask this question, it looks like exampleRobot.num_years_ago(2019). The dot operator (.) is basically a way of indicating that the num_years_ago function is called from the robot.
In code, this may look like
cindy = Album("Dirty Computer", "Janelle Monae", 2018, "Pynk")
age = cindy.num_years_ago(2019)
print(age)

Hope this helps! Feel free to drop questions in the comments and I'll clarify!

A: The __add__ and __eq__ _ are operators.
The idea is simply to manipulate your instance through classic python operators.
__add__ makes you able to do a + b with a and b both instances of Fraction.
__eq__ makes you able to compare two fractions like
a= Fraction(3,4)
b= Fraction(5,7)

if a==b:
  return "OMG it equal"


text:
Q: jquery google feed plugin w/ no output I am using the JQuery Google Feed plugin (gFeed) to output an RSS feed. I've successfully used this alternative before, but unfortunately I've stumbled into a bit of a problem. The RSS feed refuses to output into the specified div. I have confirmed the feed  https://www.phpbb.com/community/feed.php?mode=news displays correctly with Google Reader..
My site is http://removed/index and I also consulted the [Google Feed API developers page][3].
This is my code:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<!-- include this plugin -->
<script type="text/javascript" src="jquery.gfeed.js"></script>
<script type="text/javascript">

 // when the DOM is ready, convert the feed anchors into feed content
  $(document).ready(function() {
   // add a feed manually
    $('#feeds').gFeed({
       url: 'https://www.phpbb.com/community/feed.php?mode=news',
         title: 'A List Apart Feed (Added by Brute Force)'
     });
    });
    </script>

     <div id="feeds">

     </div>

A: The JQuery gFeed plugin is quite old (2007) and it uses FeedControl which I believe was deprecated by Google.
I would recommend using the jquery-feeds plugin, and then using code like:
$('#feeds').feeds({
    feeds: {
        feed1: 'https://www.phpbb.com/community/feed.php?mode=news'
    }
});

Fiddle here with a demo.


text:
Q: Superposition of random smooth waves to user defined smooth path I need to complete a simple task of adding some random smooth perturbations to a generally specified smooth path in Tikz, as specified by the plot together with some user defined coordinates as shown below. From Roland Ws answer
Adding vertical noise to a path
I gather it can be done with a decorator. Ideally inputs into the random waves that are added to the path are wavelength and amplitude. I know that this will come down to just adding some randomness to the x/y values at every nth point of my path but Im not sure how I can access the full path to do this starting from the code below. Any suggestions?
\documentclass[crop,tikz]{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}

\draw [thick, black,yshift=-100] plot [smooth, tension=1] coordinates {(1,1) (2.5,2) (3.5,1.5) (5,2) (5.5,1.5)};

\end{tikzpicture}
\end{document}

EDIT:
I can sort of accomplish the effect I want manually but it is extremely tedious as can be seen below. The first draw is the rough smooth shape I want to superimpose perturbations onto. The second one starts to show some of these waves but its obviously a pain to play around with.
\draw [thick, black] plot [smooth cycle, tension=0.75] coordinates { (-0.5,2.7) (0,2.75) (0.5,2.9) (1.0,2.95) (2.0,2.9) (2.5,2.95) (2.75,2.7) (2.8,2.5) (2.7,2.3) (2.65,2.1) (2.5,1.95) (2.4,1.8) (2.2,1.75) (2,1.8) (1.5,1.7) (1.2,1.9) (1,2.1) (0.7,2.3) (0.5,2.5) (0.3,2.55) (0,2.48) (-0.3,2.5) (-0.5,2.53) (-0.6,2.56) };

\draw [thick, black] plot [smooth cycle, tension=0.75] coordinates { (-0.5,2.7) (-0.25,2.65) (0,2.75) (0.25,2.92) (0.5,2.9) (0.62,2.99) (1.0,2.95) (1.5,2.88) (1.65,2.95) (1.72,2.97) (2.0,2.9) (2.5,2.95) (2.75,2.7) (2.85,2.5) (2.7,2.45) (2.65,2.1) (2.5,1.95) (2.38,1.91) (2.4,1.8) (2.2,1.75) (2,1.8) (1.75,1.75) (1.7,1.78) (1.5,1.7) (1.35,1.85) (1.2,1.9) (1.1,2) (1,2.1) (0.7,2.3) (0.5,2.5) (0.3,2.55) (0,2.48) (-0.3,2.5) (-0.5,2.53) (-0.6,2.56) };

A: Here is an ad hoc proposal. The problem which I encountered with the usual decorations is that the outcome tends not to be smooth. So in this proposal I add randomly displaced coordinates along the curve and connect them by a smooth plot afterwards.
\documentclass[crop,tikz]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc,decorations.pathmorphing,patterns,decorations.markings}
\tikzset{random waves/.style args={#1and#2with name #3}{postaction={decorate,decoration={markings,
mark=at position 0.1 with {\coordinate[xshift={rand*#1},yshift={rand*#2}] (#3-1);},
mark=at position 0.2 with {\coordinate[xshift={rand*#1},yshift={rand*#2}] (#3-2);},
mark=at position 0.3 with {\coordinate[xshift={rand*#1},yshift={rand*#2}] (#3-3);},
mark=at position 0.4 with {\coordinate[xshift={rand*#1},yshift={rand*#2}] (#3-4);},
mark=at position 0.5 with {\coordinate[xshift={rand*#1},yshift={rand*#2}] (#3-5);},
mark=at position 0.6 with {\coordinate[xshift={rand*#1},yshift={rand*#2}] (#3-6);},
mark=at position 0.7 with {\coordinate[xshift={rand*#1},yshift={rand*#2}] (#3-7);},
mark=at position 0.8 with {\coordinate[xshift={rand*#1},yshift={rand*#2}] (#3-8);},
mark=at position 0.9 with {\coordinate[xshift={rand*#1},yshift={rand*#2}] (#3-9);}
}}}}
\begin{document}
\begin{tikzpicture}
\draw [thick, black,yshift=-100,random waves=1mm and 3mm with name pfft] plot [smooth, tension=1]
coordinates {(1,1) (2.5,2) (3.5,1.5) (5,2) (5.5,1.5)};

\draw [thick, blue,yshift=-100] plot [smooth, tension=0.5]
coordinates {(1,1) (pfft-1) (pfft-2) (pfft-3) (pfft-4)
(pfft-5) (pfft-6) (pfft-7) (pfft-8) (pfft-9) (5.5,1.5)};

\draw [thick, black,yshift=-200,random waves=1.1mm and 5mm with name pfft] plot [smooth, tension=1]
coordinates {(1,1) (2.5,2) (3.5,1.5) (5,2) (5.5,1.5)};

\draw [thick, blue,yshift=-200] plot [smooth, tension=0.5]
coordinates {(1,1) (pfft-1) (pfft-2) (pfft-3) (pfft-4)
(pfft-5) (pfft-6) (pfft-7) (pfft-8) (pfft-9) (5.5,1.5)};

\end{tikzpicture}
\end{document}


text:
Q: Specific compiler flags for specific files in Xcode I've been tasked to work on a project that has some confusing attributes.
The project is of the nature that it won't compile for the iPhone Simulator And the iPhone Device with the same compile settings. I think it has to do with needing to be specifically compiled for x86 or arm6/7 depending on the target platform.
So the project's build settings, when viewed in Xcode's Build Settings view doesn't enable me to set specific compiler flags per specific files. However, the previous developer that worked on this project has somehow declared the line:
CE7FEB5710F09234004DE356 /* MyFile.m in Sources */ = {isa = PBXBuildFile; fileRef = CE7FEB5510F09234004DE356 /* MyFile.m */; settings = {COMPILER_FLAGS = "-fasm-blocks -marm -mfpu=neon"; }; };

Is there any way to do this without editing the project file by hand? I know that editing the project file can result in breaking it completely, so I'd rather not do that, as I obviously don't know as much as the previous developer.
So to clarify, the question is:
The build fails when compiling for simulator unless I remove the -fasm-blocks flag. The build fails when compiling for device unless I add the -fasm-blocks flag. Is there a way to set this flag per file without editing the project file by hand?

A: This blog post by Joshua Nozzi explains how to do this in Xcode 4, where he says:

... select your project in the Project Navigator, select the relevant target (you may have only one), then select the Build Phases tab. Expand the Compile Sources phase and viola! A Compiler Flags column lets you set each file's flags for that target.

A: You can define additional compiler flags for individual source files as follows:

*

*first select the target you are going to build

*right click on the source file

*select "Get Info"

*click on the "Build" tab

*define your additional compiler flags

However it sounds like a better solution in your case is just to duplicate the target and have two targets - one for an actual device and one for the simulator. Inherit common build settings from the project level and just tweak the per-target build settings as necessary.

A: Call GetInfo for the specific file, you can set the Build settings there for this file. See also the XCode Project Management Guide about this.


text:
Q: get the row id from a groupBy in laravel I have a groupBy data it is working but I am wondering how can I get the row ID of the nested record?
from my index function
public function index(Request $request)
{
    $collectorBorrowers = CollectorMember::get()
      ->groupBy('collector.name');
}

return view('dashboard.collector-members.index', compact('collectorBorrowers'));

Here's what my collector_member's table

Here's how I display the groupBy on my blade
@foreach ($collectorBorrowers as $collector => $users_list)

        {{ $collector }}: ({{ $users_list->count() }} borrowers)

    @foreach ($users_list as $user)

borrower['avatar']) }});">

            borrower['id'] }}" target="_blank">{{ $user->borrower['name'] }}
            {{ $user->borrower['email'] }}
            +{{ $user->borrower['country_code'] }}{{ $user->borrower['phone_number'] }}

                @if ($user->borrower['email_verified_at'])
                    <button class="btn btn-success btn-sm trans" data-toggle="tooltip" title="Email Verified"></button>
                @else
                    <button class="btn btn-light btn-sm trans"></button>
                @endif

                @if ($user->borrower['phone_verified_at'])
                    <button class="btn btn-success btn-sm trans" data-toggle="tooltip" title="Phone Number Verified"></button>
                @else
                    <button class="btn btn-light btn-sm trans"></button>
                @endif

            {!! Form::open([
                'method'=>'DELETE',
                'url' => ['/dashboard/collector-members', $users_list],
                'style' => 'display:inline'
            ]) !!}
                {!! Form::button('', array(
                        'type' => 'submit',
                        'class' => 'btn btn-custom-danger btn-sm trans',
                        'title' => 'Remove user',
                        'onclick'=>'return confirm("Confirm delete?")',
                        'data-toggle' => 'tooltip',
                        'data-original-title' => 'Edit'
                )) !!}
            {!! Form::close() !!}

        {{-- {{dd($users_list)}} --}}
    @endforeach
@endforeach

that gives me this output

everything is ok my only concern is the row id from collector_member's table so that i can remove the record from  specific collector.
is is possible? thanks!
UPDATE:
public function index(Request $request)
{
    $collectorBorrowers = CollectorMember::get()
        ->keyBy('id')
        ->groupBy('collector.name');

    dd($collectorBorrowers);
}

A: Try to key collection by row ID before grouping:
https://laravel.com/docs/5.8/collections#method-keyby
$collectorBorrowers = CollectorMember::get()
      ->keyBy('id')
      ->groupBy('collector.name');

And then in your view traverse groups like that:
@foreach ($users_list as $key => $user)
      ...
      {!! Form::open([
            'method'=>'DELETE',
            'url' => ['/dashboard/collector-members', $key],
      ]) !!}
      ...
@endforeach

P.S. Avoid Form Helper, cause it deprecated.
Why are Form and HTML helpers deprecated in Laravel 5.x?


text:
Q: How can I reuse some functions in a Perl script? I am facing a problem that require the reuse some of the functions within another Perl script. I am writing some test scripts. The test scripts are basically build on each other.
Say Script 1 does:
Some code to prepare the test.
A.
B.
C.
Some code to determine the success.
Then Script 2 does:
Some code to prepare the test.
A.
B.
C.
D.
E.
Some code to determine the success.
How can I reuse A.B.C of script 1 in script 2?
Calling script 1 from script 2 will not work because of the code to determine the success of the script. What is the best way to do this?
Thanks

A: Foo/Common.pm:
package Foo::Common;
use strict;
use warnings;
use parent 'Exporter';
our @EXPORT_OKAY = qw(frob borf);

sub frob {}
sub borf {}

1;

In some script or module, give or take a use lib to get Foo/Common.pm in @INC:
use Foo::Common qw(frob borf);
frob();

A: Put the functions in a module and include that from both files.
See http://perldoc.perl.org/perlmod.html for more info.


text:
Q: Collisions in Java Swing As of late I have been programming a 2D sandbox populated with several shapes in motion, specifically circles. The speed and size of each circle can be controlled by a two JSlider at the top and bottom of the window.
Animation Class
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;

public class Animation extends JFrame {

    public final int HEIGHT = 500;
    public final int WIDTH = 735;
    public int speed = 10, size = 50;
    JSlider sl1, sl2;
    JPanel panel, panel2;
    JLabel label, label2;
    GraphicsDemo gD;

    public Animation() {
        this.setSize(WIDTH+35,HEIGHT+90);
        this.getContentPane();
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        panel = new JPanel(); panel2 = new JPanel();
        panel.setLayout(new FlowLayout());
        panel2.setLayout(new FlowLayout());
        label = new JLabel("Current Speed: 10");
        label2 = new JLabel("Current Size: 50");

        Dimension length = label.getPreferredSize();
        label.setBounds(150, 200, length.width, length.height);
        setSlider();
        Animation.event e1 = new Animation.event();
        Animation.event e2 = new Animation.event();
        sl1.addChangeListener(e1);
        sl2.addChangeListener(e2);

        panel.add(sl1); panel2.add(sl2);
        panel.add(label); panel2.add(label2);
        gD = new GraphicsDemo(HEIGHT, WIDTH, speed, size, sl1, sl2);
        this.add(gD);

        this.add(panel, BorderLayout.NORTH);
        this.add(panel2, BorderLayout.SOUTH);
        this.setVisible(true);

    }

    public void setSlider() {
        sl1 = new JSlider(JSlider.HORIZONTAL, 0, 20, speed);
        sl1.setMajorTickSpacing(5);
        sl1.setPaintTicks(true);

        sl2 = new JSlider(JSlider.HORIZONTAL, 20, 100, size);
        sl2.setMajorTickSpacing(5);
        sl2.setPaintTicks(true);
    }

    public class event implements ChangeListener {

        @Override
        public void stateChanged(ChangeEvent e) {
            speed = sl1.getValue();
            label.setText("Current speed: " + speed);

            size = sl2.getValue();
            label2.setText("Current size: " + size);
        }
    }
}

GraphicsDemo Class
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;

public class GraphicsDemo extends JPanel implements ActionListener {

    public ArrayList<Balls> balls = new ArrayList<>();
    Image spaceImage;
    JSlider sl, sl2;
    Timer timer;
    public int h, w, s, size;
    public GraphicsDemo(int WIDTH, int HEIGHT, int SPEED,
                        int SIZE, JSlider slide, JSlider slide2) {
        h = HEIGHT; w = WIDTH;
        sl = slide; sl2 = slide2;
        s = SPEED; size = SIZE;
        init();
        spaceImage = new ImageIcon("C:\\Users\\admin\\Downloads\\space.jpg").getImage();
        timer = new Timer(100, this);
        timer.start();
    }

    public void init() {
        for (int i = 0; i < 10; i++) {
            int x = (int) ((Math.random()*700)+1);
            int y = (int) ((Math.random()*400)+1);
            if (i % 2 == 0) {
                balls.add(new Balls(size, x, y, 10, -10));
            } else {
                balls.add(new Balls(size, x, y, -10, 10));
            }
        }
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        this.setBackground(Color.BLACK);

        Graphics2D g2D = (Graphics2D) g;

        g2D.drawImage(spaceImage, 0,0, 735, 490, null);

        GradientPaint paint = new GradientPaint(0,0,Color.RED, 420,0,Color.BLUE);
        g2D.setPaint(paint);
        for (Balls ball : balls) {
            ball.render(g2D);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        for (Balls ball : balls) {
            ball.checkBounds();
            ball.changeVel(sl);
            ball.changeSize(sl2);
            for(Balls b : balls) {
          //      ball.collision(b);
            }
        }
        repaint();
    }

    static class Balls {
        Shape oval;
        private int radius;
        private int cx;
        private int cy;
        private int velX, velY;

        Balls(int r, int x, int y, int velX, int velY) {
            this.radius = r;
            this.cx = x;
            this.cy = y;
            this.velX = velX;
            this.velY = velY;
            oval = new Ellipse2D.Double(cx, cy, radius, radius);
        }

        void checkBounds() {
            cx += velX;
            cy += velY;
            if (cx >= 735-radius || cx <= 0) {
                velX *= -1;
            }
            if (cy  >= 490-radius || cy  <= 0) {
                velY *= -1;
            }
        }

        public void collision(Balls o) {
            Area areaA = new Area(oval);
            areaA.intersect(new Area(o.oval));
            if (!areaA.isEmpty()) {
                velX *= -1;
            }
        }

        void changeVel(JSlider sl) {
            if (velX < 0) {
                velX = -sl.getValue();
            } else {
                velX = sl.getValue();
            }
            if(velY < 0) {
               velY = -sl.getValue();
            } else {
                velY = sl.getValue();
            }
        }

        void changeSize(JSlider sl) {
            radius = sl.getValue();
        }

        void render(Graphics2D g) {
            oval = new Ellipse2D.Double(cx, cy, radius, radius);
            g.fill(oval);
        }
    }
}

However, I have been stuck on creating an algorithm that not only handles all collisions between  objects, but also accurately plans a trajectory from which both shapes would move away from each other once coming in contact. As of now, I have hypothetical class that would handle these collisions, but after several attempts of testing this along with the rest of the program it has onl bugs or breaks in the program logic.
Collision Class
import java.awt.geom.Area;
import java.util.ArrayList;

public class Collisions {

    public boolean collision(ArrayList<GraphicsDemo.Balls> balls, Shape o1) {
        Area areaA = new Area(o1);
        for (GraphicsDemo.Balls ball : balls) {
            areaA.intersect(new Area(ball.oval));
            return !areaA.isEmpty();
        }
        return true;
    }
}

Any help or tips would be most helpful in figuring a viable solution for this problem. Thanks!

A: There is an error in your collision class :
import java.awt.geom.Area;
import java.util.ArrayList;

public class Collisions {

    public boolean collision(ArrayList<GraphicsDemo.Balls> balls, Shape o1) {
        Area areaA = new Area(o1);
        for (GraphicsDemo.Balls ball : balls) {
            areaA.intersect(new Area(ball.oval));
            return !areaA.isEmpty();  // HERE
        }
        return true;
    }
}

Your loop return a value without any assertion at the first step !


text:
Q: Solution Verification: 6 people arranged in a table where same sex cannot sit together The Question
How many can we arrange $3$ men and $3$ women around a circular table in such a way that no man sits with another man, and no woman sits with another woman. Combinations that can be obtained from another seating arrangement by rotation are considered identical. This was given as a problem by my professor at the end of lecture. Already read this question I got a different answer than their accepted answer, which I don't think is right.
My Work
The first step is to determine how many ways to arrange men and women alternating in a line with no restrictions. First we must decide if we are starting with a man or a woman, there are $2$ choices for this. From there, regardless of choice there are $3*3*2*2*1*1$ ways to arrange the ladies and gents. Now we account for all the rotations there are 6 rotations, so we divide by 6 to avoid overcounting. $\frac{2*3*3*2*2*1*1}{6} = 3*2*2*1*1 =12 $ ways to arrange them like this.

A: To avoid the initial overcounting in the knowledge that rotations will be ignored, you can arbitrarily reserve one seat to a particular woman. Then there are two ways to seat the other two women, and 3!=6 ways to seat the men.
As you say, 12 total seatings ignoring rotations.
As a further refinement, you could also ignore reflections - that is, if each person has the same neighbours in two patterns, the seating patterns are regarded as equivalent. This would lead to only 6 possibilities.


text:
Q: Expo: how to add expo code to existing Android project? I have an Android app (standard java Android app) that allows the user creating its own 3D models. Now, I want to add a 3D viewer in this app so that the user can view his model and interact with it.
I plan to develop my 3D viewer with Expo.
Nevertheless, I wonder how I will be then able to integrate this 3D viewer in one of the activities of my Android java app.
Anybody could explain the process?
Thanks a lot for your help.

A: Expo by itself is only working for standalone apps. If you want to integrate it into an existing app, you have to use the "Bare" Workflow to integrate expo in an existing app. As all the tooling integration is a bit complicated I would suggest the following steps:

*

*generate a standard Expo-App

*use expo eject to convert it to the Bare Workflow

*Integrate your existing App into this created app.


text:
Q: how to delete NaN values in pandas while adding other columns' value to the very next row which has not NaN value? Here is my dataframe view:
index   date    B   N   S   y_B   y_N   y_S  f_price    y_price  p_change   price_day_t-2
1   2021-01-12  1   29  0   2.0   57.0  0.0  10250.0    10760.0  -1.0        11060.0
2   2021-01-13  0   67  0   1.0   29.0  0.0  9810.0     10250.0  -1.0        10760.0
3   2021-01-14  2   19  0   0.0   67.0  0.0  NaN         NaN     NaN           NaN
4   2021-01-15  1   6   0   2.0   19.0  0.0  NaN         NaN     NaN           NaN
5   2021-01-16  2   46  0   1.0   6.0   0.0  9340.0     9810.0   -1.0        10250.0
6   2021-01-17  3   22  0   2.0   46.0  0.0  NaN         NaN     NaN           NaN
7   2021-01-18  1   34  0   3.0   22.0  0.0  8890.0     9340.0   -1.0        9810.0

I want to delete rows with null values but at the same time, I want to add the other columns' values to the very next row without null values. which the result would be like this:
index   date    B   N   S   y_B   y_N   y_S  f_price    y_price  p_change   price_day_t-2
1   2021-01-12  1   29  0   2.0   57.0  0.0  10250.0    10760.0  -1.0        11060.0
2   2021-01-13  0   67  0   1.0   29.0  0.0  9810.0     10250.0  -1.0        10760.0
5   2021-01-16  5   71  0   3.0   92.0  0.0  9340.0     9810.0   -1.0        10250.0
7   2021-01-18  4   56  0   5.0   68.0  0.0  8890.0     9340.0   -1.0        9810.0

for example in row n.5 column "B", the result is 5 because of the aggregation 2+1+2. (the two other values [1] and [2] are from deleted rows)
How can I do this?

A: You can create groups by comapre last column from back for non missing values with cumulative sum, then aggregate sum for all columns without date, it aggregate by last values per groups:
g = df.iloc[::-1, -1].notna().cumsum()

d = dict.fromkeys(df.columns, 'sum')
d['date'] = 'last'

df = df.groupby(g, sort=False).agg(d).reset_index(drop=True)
print (df)
         date  B   N  S  y_B   y_N  y_S  f_price  y_price  p_change  \
0  2021-01-12  1  29  0  2.0  57.0  0.0  10250.0  10760.0      -1.0
1  2021-01-13  0  67  0  1.0  29.0  0.0   9810.0  10250.0      -1.0
2  2021-01-16  5  71  0  3.0  92.0  0.0   9340.0   9810.0      -1.0
3  2021-01-18  4  56  0  5.0  68.0  0.0   8890.0   9340.0      -1.0

   price_day_t-2
0        11060.0
1        10760.0
2        10250.0
3         9810.0


text:
Q: jQuery UI Datepicker - color dates after the selected date I'm using the jQuery UI datepicker  to allow the user to select a date. I need to color 7 days after the selected date.
For example, if the user has selected 1.1.2015, the days 2.1.2015 to 8.1.2015 shall be colored upon click (on the 1.1.2015). I was following this guide but I am not able to make this work.
Basically what I'm doing is creating an array of future dates (based on the calculation of milliseconds from the selected date + 86400000 milliseconds for each day), and then trying to apply css class on this array. Please advise.
EDIT:
Maybe I should have mentioned, but this picker is inline so the changes must take place instantly.
EDIT2:
Here's an example via jsfiddle.
JS:
var arrayOfFollowingWeekDates = [];
var selectedStartingDate;

//date picker configuration
    $('#datepicker').datepicker({
        onSelect: function(dateText, inst){

            selectedStartingDate = dateText;
            var selectedDateAsObject = $(this).datepicker('getDate');
            arrayOfFollowingWeekDates = calcFollowingtWeekDates(selectedDateAsObject);
            if(selectedDateAsObject > new Date){
                console.log(selectedStartingDate);

            }else{
                console.log("bad date.");
            }
        },
        inline: true,
        showOtherMonths: true,
        beforeShowDay: function(day, date){
            var day = day.getDay();
            if (day == 5 || day == 6){
                return [false, ""];
            } else {
                return [true, ""];
            }
            var highlight = arrayOfFollowingWeekDates[date];
            if (highlight) {
                 return [true, "event", highlight];
            } else {
                 return [true, '', ''];
            }
        }
    });

//this creates an array of the desired week, based on date objects
    function calcFollowingtWeekDates(selectedDateObj){
        var followingWeek = [];
        var tempArrayOfNextDates = [];
        var selectedDateInMilliseconds = selectedDateObj.getTime();
        console.log("selected date in milliseconds: "+selectedDateInMilliseconds);
        tempArrayOfNextDates[0]=selectedDateInMilliseconds;
        var day;
        var prevDay=selectedDateInMilliseconds;
        for(var i=0;i<7;i++){
            tempArrayOfNextDates[i] = 86400000 + prevDay;
            day = new Date(tempArrayOfNextDates[i]);
            prevDay = tempArrayOfNextDates[i];
            followingWeek[i]=day;
            console.log("next day is : "+ day);
        }
        return followingWeek;
    }

CSS:
.event a {
    background-color: #42B373 !important;
    background-image :none !important;
    color: #ffffff !important;
}

A: Here is a working fiddle: http://jsfiddle.net/97L93a3h/2/
var selectedDay = new Date().getTime();

$('.datepicker').datepicker({
    onSelect: function (date) {
        selectedDay = $(this).datepicker('getDate').getTime();
    },
    beforeShowDay: function (date) {
        var d = date.getTime();
        if (d > selectedDay && d < selectedDay + 1 + 86400000 * 7) {
            return [true, 'ui-state-highlight', ''];
        } else {
            return [true, ''];
        }
    }
});

Merge this method into your existing script.


text:
Q: Resampling and doing Linear Interpolation in Pandas I have a data which contains Id, DateTime and Value Column. Data are supposed to be collected in every 10 mins. However, there are some data which has gaps of over 10 mins ( for example gaps of over 20 mins, 1hr, 2 hr). Data are collected for one full month.  I want to use re sampling and use linear interpolation on my Value Column so that every Value columns contain data for fixed interval of time ( let say for every 1 hr and (weekly based)).
This is my sample data
 Id DateTime              Value
20  2018-04-08 00:28:52     10
20  2018-04-08 00:38:34     11
20  2018-04-08 00:48:57     9
20  2018-04-08 01:18:22     7
............................
205  2018-04-08 01:08:28    11
205  2018-04-08 01:18:33    13
205  2018-04-08 01:27:22    8
205  2018-04-08 01:37:02    7
205  2018-04-08 01:56:44    6
205  2018-04-08 02:16:14    10

.....
2053  2018-04-08 02:06:03   11
2053  2018-04-08 02:17:10   12
2053  2018-04-08 02:26:33   8
2053  2018-04-08 02:36:53   9
2053  2018-04-08 03:26:33   13

Any suggestions ?
Thanks

A: I believe need:
print (df)

      Id            DateTime  Value
0     20 2018-04-08 00:28:52     10
1     20 2018-04-08 00:38:34     11
2     20 2018-04-08 00:48:57      9
3     20 2018-04-08 01:18:22      7
4    205 2018-04-08 01:08:28     11
5    205 2018-04-08 01:18:33     13
6    205 2018-04-08 01:27:22      8
7    205 2018-04-08 01:37:02      7
8    205 2018-04-08 01:56:44      6
9    205 2018-04-08 02:16:14     10
10  2053 2018-04-08 10:06:03     11
11  2053 2018-04-08 10:17:10     12
12  2053 2018-04-08 10:26:33      8
13  2053 2018-04-08 10:36:53      9
14  2053 2018-04-08 10:26:33     13

df = df.set_index('DateTime')['Value'].resample('1H').mean().interpolate()
print (df)

DateTime
2018-04-08 00:00:00    10.000000
2018-04-08 01:00:00     8.666667
2018-04-08 02:00:00    10.000000
2018-04-08 03:00:00    10.075000
2018-04-08 04:00:00    10.150000
2018-04-08 05:00:00    10.225000
2018-04-08 06:00:00    10.300000
2018-04-08 07:00:00    10.375000
2018-04-08 08:00:00    10.450000
2018-04-08 09:00:00    10.525000
2018-04-08 10:00:00    10.600000
Freq: H, Name: Value, dtype: float64

EDIT:
If need resample per groups also add groupby with reindex for same DatetimeIndex per each unique Ids:
df = df.set_index('DateTime').groupby('Id')['Value'].resample('1H').mean()
mux = pd.MultiIndex.from_product([df.index.levels[0], pd.date_range(df.index.levels[1].min(), df.index.levels[1].max(), freq='h')])
df = df.reindex(mux)
df = df.groupby(level=0).apply(lambda x: x.interpolate())

print (df)

20    2018-04-08 00:00:00    10.0
      2018-04-08 01:00:00     7.0
      2018-04-08 02:00:00     7.0
      2018-04-08 03:00:00     7.0
      2018-04-08 04:00:00     7.0
      2018-04-08 05:00:00     7.0
      2018-04-08 06:00:00     7.0
      2018-04-08 07:00:00     7.0
      2018-04-08 08:00:00     7.0
      2018-04-08 09:00:00     7.0
      2018-04-08 10:00:00     7.0
205   2018-04-08 00:00:00     NaN
      2018-04-08 01:00:00     9.0
      2018-04-08 02:00:00    10.0
      2018-04-08 03:00:00    10.0
      2018-04-08 04:00:00    10.0
      2018-04-08 05:00:00    10.0
      2018-04-08 06:00:00    10.0
      2018-04-08 07:00:00    10.0
      2018-04-08 08:00:00    10.0
      2018-04-08 09:00:00    10.0
      2018-04-08 10:00:00    10.0
2053  2018-04-08 00:00:00     NaN
      2018-04-08 01:00:00     NaN
      2018-04-08 02:00:00     NaN
      ...
      2018-04-08 07:00:00     NaN
      2018-04-08 08:00:00     NaN
      2018-04-08 09:00:00     NaN
      2018-04-08 10:00:00    10.6
Name: Value, dtype: float64

Another solution if need interpolate each group separately:
df = (df.set_index('DateTime')
       .groupby('Id')['Value']
       .resample('1H')
       .mean()
       .groupby(level=0)
       .apply(lambda x: x.interpolate()))

print (df)

Id    DateTime
20    2018-04-08 00:00:00    10.0
      2018-04-08 01:00:00     7.0
205   2018-04-08 01:00:00     9.0
      2018-04-08 02:00:00    10.0
2053  2018-04-08 10:00:00    10.6
Name: Value, dtype: float64


text:
Q: Unicode normalization in Postgres I have a large number of Scottish and Welsh accented place names (combining grave, acute, circumflex and diareses) which I need to update to their unicode normalized form, eg, the shorter form 00E1 (\xe1) for á instead of 0061 + 0301 (\x61\x301)
I have found a solution from an old Postgres nabble mail list from 2009, using pl/python,
create or replace function unicode_normalize(str text) returns text as $$
  import unicodedata
  return unicodedata.normalize('NFC', str.decode('UTF-8'))
$$ LANGUAGE PLPYTHONU;

This works, as expected, but made me wonder if there was any way of doing it directly with built-in Postgres functions. I tried various conversions using convert_to, all in vain.
EDIT: As Craig has pointed out, and one of the things I tried:
SELECT convert_to(E'\u00E1', 'iso-8859-1');

returns \xe1, whereas
SELECT convert_to(E'\u0061\u0301', 'iso-8859-1');

fails with the ERROR:  character 0xcc81 of encoding "UTF8" has no equivalent in "LATIN1"

A: PostgreSQL 13 has introduced string function normalize ( text [, form ] ) → text, which is available when the server encoding is UTF8.
> select 'päivää' = 'päivää' as without, normalize('päivää') = normalize('päivää') as with_norm ;
 without | with_norm
---------+-----------
 f       | t
(1 row)

Note that I am expecting this to miss any indices, and therefore using this blindly in a hot production query is prone to be a recipe for disaster.
Great news for us who have naively stored NFD filenames from Mac users in our databases.

A: I think this is a Pg bug.
In my opinion, PostgreSQL should be normalizing utf-8 into pre-composed form before performing encoding conversions. The result of the conversions shown are wrong.
I'll raise it on pgsql-bugs ... done.
http://www.postgresql.org/message-id/53E179E1.3060404@2ndquadrant.com
You should be able to follow the thread there.
Edit: pgsql-hackers doesn't appear to agree, so this is unlikely to change in a hurry. I strongly advise you to normalise your UTF-8 at your application input boundaries.
BTW, this can be simplified down to:
regress=> SELECT 'á' = 'á';
 ?column?
----------
 f
(1 row)

which is plain crazy-talk, but is permitted. The first is precomposed, the second is not. (To see this result you'll have to copy & paste, and it'll only work if your browser or terminal don't normalize utf-8).
If you're using Firefox you might not see the above correctly; Chrome renders it correctly. Here's what you should see if your browser handles decomposed Unicode correctly:


text:
Q: Why is "the" used here?
We just wanna party
  Party just for you
  We just want the money
  Money just for you

This is one line in the lyrics of "This is America"
So I don't understand why "the" is used before "money".
Why is "the money" used, not just "money"?

A: The definite article is used when the speaker is in the belief that their audience know what the speaker is referring to and the thing(s) that the speaker refers to is unique in the context of the conversation.
So here the money refers to some money the narrator of the song (the point of view from which the lyrics are written) has in mind.
The lyrics are pretty clear in this regard.

We want the money
Money just for you (this specifies the money that is under discussion)

For example, say an employee has been fired and comes to her manager disgruntled.

Employee: That is so unfair! Where is my severance check? I want the money!

Here the employee is talking about some specific money that she thinks the company owes her.


text:
Q: Back-end functionality for a file sharing website How file uploads to a clustered environment are typically handled using PHP?
I am currently working on a backend system for a cloud storage/sharing website
I would like to make sure that a clients upload is stored to the node with least load and most available resources, creating a unique file reference stored to the database. Also multiple uploads of the same file should be detected to reduce space.
Are there any best practices, design patterns documentation covering this topic and might help illustrating what is needed to get things done here.


text:
Q: query outside the for loop I am trying to query outside the for loop . But i have no idea do that process .I shared the code below.
public class OpportunityEmailNotification1 implements  Database.Batchable<SObject> {

    public void execute(SchedulableContext context)
    {
      Database.executeBatch(this);
    }

public Database.QueryLocator start(Database.BatchableContext context) {

    return Database.getQueryLocator(  [SELECT Id,name,ownerid,accountID, Channel_Partner_KAM_Email__c,Channel_Partner_Manager__c,CloseDate,
                                        Account.KAM__r.email,  Account.TL_for_Integration__r.email,
                                        Account.SAM_for_Integration__r.email ,RecordType.Developername
                                        FROM opportunity  where Status__c =:'Open']);

    }

    public static Map<String,Messaging.SingleEmailMessage> createDummyEmail(EmailTemplate templateName, List<String> whatIds){
    //  templateId  must be ID of an Email template
    //  targetObjId must be a Contact Id -- also used in merge fields of template recipient.xxxx
    //  whatId      must be an SObject that is used in the merge fields of the template relatedTo.xxxx
    //  fromId      if non null, use current user, otherwise, use this ID (most likely an org wide no reply id)
    Contact cnt = [Select Id, FirstName, Email From Contact Where Email != Null LIMIT 1];

   Map<String,  Messaging.SingleEmailMessage> oppEmail = new   Map<String,    Messaging.SingleEmailMessage>();
   List<Messaging.SingleEmailMessage> msgList= new List<Messaging.SingleEmailMessage>();

   //system.debug('%%%%%%%%%%%%%%%%'+mapKam);
   for(String whatID :whatIds){
     opportunity  oppti  = [SELECT Id,name,ownerid,accountID, Channel_Partner_KAM_Email__c,Channel_Partner_Manager__c,CloseDate,
                                        Account.KAM__r.email,  Account.TL_for_Integration__r.email,
                                        Account.SAM_for_Integration__r.email from opportunity where id =:whatID ];
    list<String> ccTo = new list<String>();

   // system.drbug('&&&&&&&&&&&&&&&&&&&&&&&&&'+whatIds.get(whatID));
    Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
    user u =[select email from user where id =:oppti.ownerId];
    msg.setTemplateId(templateName.id );
    msg.setWhatId(whatID);
    msg.setTargetObjectId(cnt.id);
    ccTo.add(oppti.Account.KAM__r.email);
    ccTo.add(oppti.Account.TL_for_Integration__r.email);
    ccTo.add(oppti.Account.SAM_for_Integration__r.email);
    ccTo.add(u.email);
    msg.setToAddresses(ccTo);
   // msg.setToAddresses(new List<String>{[Select Email From User where name=:'narendra jagwan'].Email});

    msgList.add(msg);
  oppEmail.put(whatID, msg );
   }
    // Send the emails in a transaction, then roll it back
   Savepoint sp = Database.setSavepoint();
    Messaging.sendEmail(msgList); // Dummy email send
    Database.rollback(sp); // Email will not send as it is rolled Back
    // Send Actual email
    system.debug(':::::::::::SSSSSSSSSSSSSSSSS:::::::::::'+oppEmail);
 List<Messaging.SingleEmailMessage> EmailList= new List<Messaging.SingleEmailMessage>();
    String body ='';
    String Subject ='';
    list<string> sender = new list<String>();
   for(id key :oppEmail.keyset()){
     Messaging.SingleEmailMessage msg1 = new Messaging.SingleEmailMessage();
     body=oppEmail.get(key).getPlainTextBody();
     Subject =oppEmail.get(key).getSubject();
     sender =oppEmail.get(key).getToAddresses();
     system.debug('*********subject*********'+oppEmail.get(key).getsubject());
     msg1.setSubject(Subject);
     msg1.setPlainTextBody(body);
     msg1.setToAddresses(sender);
     EmailList.add(msg1);
   }
    Messaging.sendEmail(EmailList);
    return null ;
}

public void execute(Database.BatchableContext context, list<opportunity> records) {
    list <String> testString = new list<String>();

     id oppID;
     String ChannelKAMEmail ;
     String ChannelPartnerEmail ;
     date closerDate;

     Contact cnt = [select id from Contact  limit 1];
     system.debug('AAAAAAAAAAAAAAAA'+cnt );
     EmailTemplate em =[SELECT Id  FROM EmailTemplate WHERE Name = 'CP - Opportunity Expected Closure date Alert'];

     system.debug('TTTTTTTT'+em );
     system.debug('AAAAAAAAAAAAA'+records);
     for(opportunity  opp :records){
         oppID= opp.id;
         closerDate= opp.CloseDate ;
         if(Date.Today() == closerDate-1|| Date.Today() ==closerDate-3 || Date.Today()==closerDate-5){
           testString.add(oppID);
          }
      }
       createDummyEmail( em , testString);

}
public void finish(Database.BatchableContext context) {
    // No need to do anything, but this needs to be here

}
 }

A: Replace the for loop with the following:
for(opportunity oppti: [SELECT Id,name,ownerid,accountID, Channel_Partner_KAM_Email__c,Channel_Partner_Manager__c,CloseDate,
                                   Account.KAM__r.email,  Account.TL_for_Integration__r.email,
                                   Account.SAM_for_Integration__r.email from opportunity where id IN: whatIds ]){
            list<String> ccTo = new list<String>();

            // system.drbug('&&&&&&&&&&&&&&&&&&&&&&&&&'+whatIds.get(whatID));
            Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
            user u =[select email from user where id =:oppti.ownerId];
            msg.setTemplateId(templateName.id );
            msg.setWhatId(oppti.id);
            msg.setTargetObjectId(cnt.id);
            ccTo.add(oppti.Account.KAM__r.email);
            ccTo.add(oppti.Account.TL_for_Integration__r.email);
            ccTo.add(oppti.Account.SAM_for_Integration__r.email);
            ccTo.add(u.email);
            msg.setToAddresses(ccTo);
            // msg.setToAddresses(new List<String>{[Select Email From User where name=:'narendra jagwan'].Email});

            msgList.add(msg);
            oppEmail.put(oppti.id, msg );
        }

A: You could do something like this and move the query to the users outside of the loop as well.
//Query the opportunities

List<Opportunity> opportunities = [SELECT Id,name,ownerid,accountID, Channel_Partner_KAM_Email__c,Channel_Partner_Manager__c,CloseDate, Account.KAM__r.email,  Account.TL_for_Integration__r.email, Account.SAM_for_Integration__r.email from opportunity where id in :whatIds ];

// Sort them by Id
Map<Id, Opportunity> oppsById = new Map<Id, Opportunity>(opportunities);

//Get the ownerIds from the opportunities
Set<Id> ownerIds = new Set<Id>();
for( Opportunity opp : opportunities )
  ownerIds.add(opp.ownerId);

// Get the Users
List<User> users = [select email from user where id in :ownerIds];

// Sort the emails by User Id
Map<Id, String> emailsByUserId = new Map<Id, String>();
for( User u : users )
{
  if( !emailsByUserId.keySet().contains( u.Id ) )
    emailsByUserId.put( u.Id, u.email );
}

// now the for loop can become like this
for( String whatId : whatIds )
{
  Opportunity opp = oppsById.get( whatId );
  String userEmail = emailsByUserId( opp.ownerId );

  list<String> ccTo = new list<String>();

  Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
  msg.setTemplateId(templateName.id );
  msg.setWhatId(whatID);
  msg.setTargetObjectId(cnt.id);
  ccTo.add(opp.Account.KAM__r.email);
  ccTo.add(opp.Account.TL_for_Integration__r.email);
  ccTo.add(opp.Account.SAM_for_Integration__r.email);
  ccTo.add(userEmail);
  msg.setToAddresses(ccTo);
}


text:
Q: How to use twillio to text a weather update using weather api in node.js I have twillio texting me everyday at 8am, a message from aws lambda but I want it to text me the weather for the day. Im trying to use a weather api but I cant figure out how to do it
I tried JSON.stringify() but it didnt work
const axios = require("axios");

const options = {
  method: 'GET',
  url: 'https://dark-sky.p.rapidapi.com/30.4383,-84.2807',
  params: {units: 'auto', lang: 'en'},
  headers: {
    'X-RapidAPI-Key': 'XXXXXXXX',
    'X-RapidAPI-Host': 'dark-sky.p.rapidapi.com'
  }
};

axios.request(options).then(function (response) {
    console.log(response.data);

}).catch(function (error) {
    console.error(error);
});

exports.handler = (event, context, callback) => {

    const accountSid = process.env.ACCOUNT_SID;
    const authToken = process.env.AUTH_TOKEN;

    const client = require('twilio')(accountSid, authToken);

    // Send a text message
    client.messages.create({
        body: 'TEXT MESSAGE EXAMPLEi',
        to: 'XXXXX',  // your phone number
        from: 'XXXXXXX' // a valid Twilio number
    })
        .then((message) => {
            // Success, return message SID
            callback(null, message.sid);
        })
        .catch((e) => {
                // Error, return error object
            callback(Error(e));
        });

};


text:
Q: Select rows in dataset table based on other dataset table I have a dataset that has two tables in it. I want to do the following (or something like it) is it possible and is how I have it correct?
dsTabData.Tables("FilingTabs").Select("fs_ID not in (select fsp_fsid from ParentTabs)")

how do you reference data from other table in the same dataset?

A: ok ok before y'all flame me! ;)
I did some more looking around online and found what looks like the stuff I need, now off to read some more from here:
Navigating a Relationship Between Tables


text:
Q: startMonitoringSignificantLocationChanges Delegate only called once I have a problem with startMonitoringSignificantLocationChanges. If I call this method for my locationManager the locationManager:didUpdateLocations: Method is called exactly once. Now if I start a Drive in Simulator (as described here - Debug -> Location -> Freeway Drive) it is not called anymore. By Apple it is specified that it should be called every 500m or even every 5 to 15 Minutes. And I waited and waited and waited with no success.
Here is the little code and I made also a Github minimal example. Of course error method is also never called. It is not tested on a real Device in car because I thought it should work in Simulator first. What am I missing here?
- (void)viewDidLoad {
    [super viewDidLoad];

    if(self.locationManager == nil){
        self.locationManager = [[CLLocationManager alloc] init];
    }

    // Set the delegate
    self.locationManager.delegate = self;
    [self.locationManager requestAlwaysAuthorization];

    [self.locationManager startMonitoringSignificantLocationChanges];

}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLLocation *currentLoc = [locations lastObject];
    NSLog(@"New Location: %f/%f, Locations: %lu", currentLoc.coordinate.latitude, currentLoc.coordinate.longitude,(unsigned long)[locations count]);
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    NSLog(@"Loc Error: %@", [error userInfo]);
}

A: Okay I just downloaded my own minimal Project from Github and tried it with iPhone 5S Simulator. There it works. Before I had only tried it with 6S and there it didn't work. Now will try on device 6(S) and hopefully will work there as well..
But maybe will help somebody in the near future :)


text:
Q: os.getenv("xxx") shows different result while using sudo or not to run python3 It happened to me when I try to use os.getenv.
I have edited the "\etc\profile" file to add an env variable and ran the source command.
And I wrote some codes to test it.It worked well and I can get the env variable I set when I run python just using python3 command in the command line.
But I find it doesn't work when I using sudo python3.The os.getenv("xxx") returns None.
That's the question.Why it doesn't work just because of using sudo.

A: sudo does not keep the user's environment variables. Maybe this can help:
How to keep Environment Variables when Using SUDO


text:
Q: AngularJS: How to change URL parameter without using reloadOnSearch and not to reload controller using ui route? I want to change URL query parameter without reloading my controller. And I can't use reloadOnSearch  property, because it does not meet my other requirements.
For Example: Path: /score?interval
i want to change interval value without using reloadOnSearch and controller should not be reload.
Can this be done with Angularjs? And, if so, then how?
Thank you in advance!!

A: Take a look at the following Plunker. It uses Angular's $location service to change the URL without reloading the controller. You can use this method to update URL parameters also:
$location.path('/test/item/' + $scope.itemId);

If you want to change just the URL parameters you can do this as shown in this Plunker. (Preview in windowed mode to see it working) You can use $location.search() to do this as shown below:
$location.search('id', testId);

Hope this helps.


text:
Q: Declaring int array inside struct In C, I have defined the struct seen below, and would like to initialize it inline. Neither the fields inside the struct, nor the array foos will change after initialization. The code in the first block works fine.
struct Foo {
  int bar;
  int *some_array;
};

typedef struct Foo Foo;

int tmp[] = {11, 22, 33};
struct Foo foos[] = { {123, tmp} };

However, I don't really need the tmp field. In fact, it will just clutter my code (this example is somewhat simplified). So, instead I'd like to declare the values of some_array inside the declaration for foos. I cannot get the right syntax, though. Maybe the field some_array should be defined differently?
int tmp[] = {11, 22, 33};
struct Foo foos[] = {
  {123, tmp},                    // works
  {222, {11, 22, 33}},           // doesn't compile
  {222, new int[]{11, 22, 33}},  // doesn't compile
  {222, (int*){11, 22, 33}},     // doesn't compile
  {222, (int[]){11, 22, 33}},    // compiles, wrong values in array
};

A: First, there are 2 ways:

*

*You know that array's size

*You don't know that size.

In the first case it is a static programming problem, and it is not complicated:
#define Array_Size 3

struct Foo {
    int bar;
    int some_array[Array_Size];
};

You can use this syntax to fill the array:
struct Foo foo;
foo.some_array[0] = 12;
foo.some_array[1] = 23;
foo.some_array[2] = 46;

When you dont know the array's size, it is a dynamic programming issue.
You have to ask the size.
struct Foo {

   int bar;
   int array_size;
   int* some_array;
};

struct Foo foo;
printf("What's the array's size? ");
scanf("%d", &foo.array_size);
//then you have to allocate memory for that, using <stdlib.h>

foo.some_array = (int*)malloc(sizeof(int) * foo.array_size);
//now you can fill the array with the same syntax as before.
//when you no longer need to use the array you have to free the
//allocated memory block.

free( foo.some_array );
foo.some_array = 0;     //optional

Second, typedef is useful, so the when you write this:
typedef struct Foo {
   ...
} Foo;

it means you replace the "struct Foo" words with this: "Foo".
So the syntax will be this:
Foo foo;   //instead of "struct Foo foo;

Cheers.

A: My answer is for the following code section:-
int tmp[] = {11, 22, 33};
struct Foo foos[] = {
  {123, tmp},   // works
  {222, {11, 22, 33}},  // doesn't compile
  {222, new int[]{11, 22, 33}},  // doesn't compile
  {222, (int*){11, 22, 33}},  // doesn't compile
  {222, (int[]){11, 22, 33}},  // compiles, wrong values in array
};

All the above compilation issues is due to it not being compatible with the ANSI standards, the aggregate 'foos' is having subaggregates some of which are bracketed while others are not. So if you remove the internal brackets to
represent the array 'tmp' it would compile without fail. For eg.
struct Foo foos[] = {
  {123, tmp},   // works
  {222,  11,22,33 },  // would compile perfectly.
}

A: int *some_array;

Here, some_array is actually a pointer, not an array. You can define it like this:
struct Foo {
  int bar;
  int some_array[3];
};

One more thing, the whole point of typedef struct Foo Foo; is to use Foo instead of  struct Foo. And you can use typedef like this:
typedef struct Foo {
  int bar;
  int some_array[3];
} Foo;


text:
Q: Dangling meta character + in regex to detect GaussianRational public GaussianRational read()
{
    Scanner s = new Scanner(System.in);     // associate Scanner object with standard input stream
    Long p,q,m,n;
    s.findWithinHorizon("(-?\\d+)\\s*/\\s*(-?\\d+)\\s*(\\+? \\s* -?\\d+)\\s*/\\s*(-?\\d+\\s*i)",0);// scan standard input for regular expression pattern

    MatchResult result = s.match();           // collect subtrings matched by "capturing groups" in the pattern (in parentheses)
    s.close();                                // scanner no longer needed
    p = Long.parseLong(result.group(1));
    q = Long.parseLong(result.group(2));
    m = Long.parseLong(result.group(3));
    n = Long.parseLong(result.group(4));
    System.out.print(p);
    return new GaussianRational(p,q,m,n);
}

I am trying to parse 4 long numbers from a GaussianRational input using regex below
(-?\\d+)\\s*/\\s*(-?\\d+) \\s*(+?)\\s* (-?\\d+)\\s*/\\s*(-?\\d+\\s*i)

but I keep getting exception dangling + or  dangling ? that are used in the middle of the expression
Thanks!

A: You forget to add . before +?. Without dot + alone would be  meaningless since it's unescaped.
"(-?\\d+)\\s*/\\s*(-?\\d+)\\s*(.+?)\\s*(-?\\d+)\\s*/\\s*(-?\\d+)\\s*i"

If you actually mean a plus.
"(-?\\d+)\\s*/\\s*(-?\\d+)\\s*\\+?\\s*(-?\\d+)\\s*/\\s*(-?\\d+)\\s*i"

A: You need to escape the plus symbol and move the last capturing group boundaries to the number:
Long p,q,m,n;
s.findWithinHorizon("(-?\\d+)\\s*/\\s*(-?\\d+)\\s*(\\+?)\\s*(-?\\d+)\\s*/\\s*(-?\\d+)\\s*i",0);
//                                                                                ^
MatchResult result = s.match();           // collect subtrings matched by "capturing groups" in the pattern (in parentheses)
s.close();                                // scanner no longer needed
p = Long.parseLong(result.group(1));
q = Long.parseLong(result.group(2));
m = Long.parseLong(result.group(4));
n = Long.parseLong(result.group(5));
 // With "1/2+3/4 i" as input, the results are
System.out.println(p); // => 1
System.out.println(q); // => 2
System.out.println(m); // => 3
System.out.println(n); // => 4

See IDEONE demo


text:
Q: Stirling proof guidance I would like some guidances:
Prove that $$\lim_{n\to\infty}\frac{2^nn!}{n^n} = 0$$
Any help is greatly appreciate.

A: $$n!\sim \sqrt{2\pi n}\left(\frac{n}{e}\right)^n$$
Plugging this equivalent in our sequence, we get
$$\lim_{n\to\infty} \frac{2^n n!}{n^n}=\lim_{n\to\infty}\frac{2^n\sqrt{2\pi n}}{e^n}=0$$

A: Note that you can use a direct argument that doesn't require Stirling's formula.
If you consider the ratio of successive terms you get:
$$
\frac{a_{n+1}}{a_n} = \frac{2^{n+1}(n+1)!}{(n+1)^{n+1}} \frac{n^n}{2^n n!} = 2\left(1 + \frac{1}{n}\right)^{-n}
$$
The limit of this ratio is $2/e<1$, so each ratio is less than, say $4/5$ for suitably large $n$.  Then you have a fixed $N$ such that $a_{N+n} \le (4/5)^n a_N$, for all $n$, and thus the sequence converges to zero.

A: Hint: Firstly, separate off $2n/n$.  Then  $2(2n-2),4(2n-4)$ and so on are all less than $n^2$, and $2(2n-2)/n^2\to0$.