text stringlengths 70 452k | dataset stringclasses 2 values |
|---|---|
Swift 3, Xcode 8- Test case project compilation errors
I have got a project from a company to develop where the original developers left.
Project details:
carthage for dependancy management
Pivotal Cedar, Quick and Nimble for test case project
The project was developed in Swift 2.0.
I converted the project to swift 3 in Xcode 8. The main target (main app) is converted properly and is getting compiled and run on the device.
But the Test case target has compilation errors.
Could't figure out the problem.
Please help
import Foundation
protocol SessionManager {
var token: String? { get set }
var selectedContract: String? { get set }
var contracts: [String] { get set }
}
class LoginSessionManager: SessionManager {
var token: String?
var selectedContract: String?
var contracts: [String] = []
}
You'll need to post some code so we can see what's going on. Chances are that Xcode didn't properly convert the test target and you'll need to make some updates manually.
Added code, please check
| common-pile/stackexchange_filtered |
Plotly dash dropdown boarder not coming as expected
I am creating a Plotly dash with a dropdown menu. I am providing a border for the dropdown menu. I have a main heading. I need the dropdown menu to come after the main heading with a box. Please see my code below.
Now, what is happening is my border is covering my main heading also. I don't need that. I need the border for the dropdown section only. Please see the attached image which shows my current situation.
May I know where I went wrong
fig_dropdown = html.Div([
html.Div(html.H1(children="TEST SUIT1"),style={'textAlign': 'center','color': '#5742f5', 'fontSize': 20}),
dcc.Dropdown(
id='fig_dropdown',
options=[{'label': x, 'value': x} for x in fig_names],
value=None
)], style= {
'border': '#eb345b',
'color': '#5e34eb',
'borderStyle':'dashed',
# # 'width': '50%',
'font-size': '20px'
}
)
looks like you are styling the outer div, not the dropdown.
I am new to Dash. if you don't mind could you please show me how to style the dropdown.
I didn't render this, but wrapping the dropdown in a div, and then applying the style there may give you what you're looking for. From your example, you are applying the style to the very first html.Div()
fig_dropdown = html.Div([
html.Div(
html.H1(children="TEST SUIT1"),
style={
'textAlign': 'center',
'color': '#5742f5',
'fontSize': 20}),
html.Div(
dcc.Dropdown(
id='fig_dropdown',
options=[{'label': x, 'value': x} for x in fig_names],
value=None
), style= {
'border': '#eb345b',
'color': '#5e34eb',
'borderStyle':'dashed',
# 'width': '50%',
'font-size': '20px'
}
)])
EDIT: I myself placed the style in the wrong position. :)
yes I am getting error .style= {
^
SyntaxError: invalid syntax
Should be all set now. Tested.
| common-pile/stackexchange_filtered |
Run function when cicking off a div thats Contenteditable
I currently have a table that has a couble od tds, the tds contain divs that allows the user to change the value within it. If the user presses enter a function is called but I would now like to make it so the user only has to click away from the div for the function to run. is this possible?
You are looking for a blur or focusout event handler. https://developer.mozilla.org/en-US/docs/Web/Events/blur
blur solved the problem i had thanks
You can use the blur event:
$('.edit-me').prop('contentEditable', true);
$('.edit-me').on('blur', function() { console.log( $(this).text() ); });
table { width: 100%; }
table td { width: 50%; }
.edit-me { padding: 10px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
<tr>
<td><div class="edit-me"></div></td>
<td><div class="edit-me"></div></td>
</tr>
<tr>
<td><div class="edit-me"></div></td>
<td><div class="edit-me"></div></td>
</tr>
</table>
First you need to be able to select an element based on whether or not it has the contenteditable attribute:
$('[contenteditable="true"]')
Then apply event to it
The OP hasn't suggested that they're struggling with selecting the element. Also, then apply event to it isn't useful. What event?!
If the user presses enter a function is called but I would now like to make it so the user only has to click away from the div for the function to run. The event is blur the selection is according to the contenteditable attribute
| common-pile/stackexchange_filtered |
use complex analysis to evalaute series involving the square of coth
This is some what related to a sum I previously posted a week or so ago.
Using complex analysis, is there a way to show:
$\displaystyle \sum_{n=1}^{\infty}\frac{\coth^{2}(\pi n)}{n^{2}}=\frac{2}{3}K+\frac{19{\pi}^{2}}{180}$, where K is the Catalan constant.
I have tried, but failed to see how the Catalan constant could be incorporated in the closed form solution.
The residue at z=0 is $\frac{-8{\pi}^{2}}{45}$.
The residue at $z=n$ is $\displaystyle \lim_{z\to n}\frac{(z-n)\pi \cos(\pi z)\coth^{2}(\pi z)}{z^{2}\sinh^{2}(\pi z)}=\frac{\coth^{2}(\pi n)}{n^{2}}$
The residue at $z=ni$ (the zeroes of $\sinh^{2}(\pi z)$) are where I hit a snag.
$\displaystyle \lim_{z\to ni}\frac{(z-ni)\pi \cot(\pi z)\cosh^{2}(\pi z)}{z^{2}\sinh^{2}(\pi z)}$
I used L'Hopital and arrived at an undefined result.
Apparently, this is more involved than the typical sum using $\pi\cot(\pi z)$ to sum a series. Especially, some how incorporating the Catalan constant.
Thanks.
| common-pile/stackexchange_filtered |
Why is my program unable to access its required files?
I have written a program using Qt libraries for an embedded device that runs on Linux generated by Buildroot. To start my program I've created a script called S80custom and placed it in /etc/init.d/ directory. The content of the script is:
#!/bin/sh
if [ ! -d "/root/files/" ]; then
mkdir /root/files/
fi
if [ ! -d "/root/Test/" ]; then
mkdir /root/Test/
fi
if [ ! -d "/root/Test/Log/" ]; then
mkdir /root/Test/Log/
fi
export TSLIB_CONSOLEDEVICE='none'
export TSLIB_FBDEVICE='/dev/fb0'
export TSLIB_TSDEVICE='/dev/input/event1'
export TSLIB_PLUGINDIR='/usr/lib/ts'
export TSLIB_CONFFILE='/etc/ts.conf'
export TSLIB_CALIBFILE='/etc/pointercal'
export QWS_MOUSE_PROTO=tslib:'/dev/input/event1'
/root/Test/Test -qws
However when my program runs at system start-up, it can't access the files placed at /root/files. I've used QFile class and its member functions for the same. Iโve tried Standard C++ Libraries and they work, but strangely QFile is unable to open the files and I must use QFile for this task.
What am I doing wrong here?
I should also mention here that when I run my application from command prompt after I login, it works perfectly.
EDIT
As requested in the comments this is the portion of the code that is suppose to open a file:
QDir directory = QDir::home();
if(!directory.cd("files")){
LOG << directory << "does not exist or path incorrect. trying to make it";
if(directory.mkdir("files"))
{
LOG << "made directory \"files\" at" << directory.absolutePath();
directory.cd("files");
}
else
LOG << "couldn't make diretory... do we have enough priviledges?";
}
fileName = directory.absoluteFilePath("PARMLIST.BIN");
qDebug() << "filename to open:" << fileName;
QFile file(fileName);
QDataStream in(&file);
if(!file.open(QIODevice::ReadOnly))
{
if(CONF_INT("rdu.active") != 1)
AlarmManager::getInstance().setAlarm(102, true);
else
AlarmManager::getInstance().setAlarm(184, true);
paramMissing = true;
return;
}
The mechanism for setting alarms is activated, and that code tells me the files are missing or corrupted. Apart from that I get no errors. Also I tried giving the full path as file name but that didn't work either.
you need to add some info about the error you get.
i added the portion of the code. i don't get any error by kernel or anything else it's just that i can't for some reason access my files...
I suspect that your problem is due to a missing enviroment variable.
Let's start from here:
Under non-Windows operating systems the HOME environment variable is
used if it exists, otherwise the path returned by the rootPath().
so, if you log in, you have the HOME variable correctly set and it works, but when you launch the program from init, you don't have it. Try to add
export HOME="/root"
to you init script
yeah you are right... before i see your answer i changed my QDir directory = QDir::home(); to QDir directory = QDir::root(); and it worked but by adding what you said to the script my program was able to access the files without the need to change the code. Thank you
| common-pile/stackexchange_filtered |
Not sure what is causing index error in my code
I am working on a small project which is intended to read, create, and manipulate virtual to-do lists. There is a checkbox class, a function open_create_boxes to create a list of checkbox objects based on the contents of a plaintext file, and a function create_to_do_list_file to write a file which can be read by the other function.
# Define the checkbox class
class checkbox:
def __init__(self,label):
self.label = label
self.checked = False
def check(self):
self.checked = True
def read(self):
if self.checked:
return f"x | {self.label}"
if not self.checked:
return f"o | {self.label}"
def open_create_boxes(file):
# Open the to-do list
opened_list = open(f"{file}.dat", "r")
#Split the to-do list by line
parsed_line = opened_list.read().split("\n")
next_parsed = []
# Split each element in parsed list by the pipe symbol
for i in parsed_line:
next_parsed.append(i.split("|"))
to_do_list = []
# Iterates through the new list, creates checkbox object, checks to see if it is "checked" or not
for i in next_parsed:
b = checkbox(i[1])
if i[0] == "x":
b.check()
to_do_list.append(b)
return to_do_list
def create_to_do_list_file(list,label):
# Open or create a file label.dat
new_file = open(f"{label}.dat", "w")
for n in list:
new_file.write(f"\no|{n}")
create_to_do_list_file(["Task"],"filename")
open_create_boxes("filename")
Running this code gives me the error:
File "/home/genie/Desktop/checkboxes/checkboxes.py", line 41, in <module>
open_create_boxes("filename")
File "/home/genie/Desktop/checkboxes/checkboxes.py", line 28, in open_create_boxes
b = checkbox(i[1])
IndexError: list index out of range
So something is going wrong in my open_create_boxes function, where the list is coming out with <2 elements. I have re-written this code several times and get the same, or similar, errors.
Any help here? I'm a beginner, so I imagine there's an obvious fix, but I can't seem to manage.
Thanks!!
Quickly running your code and examining the created file reveals that its first line is empty. Of course you will only get one field if you attempt to split that. Why are you writing \n in front of the data?
Similarly, your code to read the file fails to account for the empty line, whether at the beginning or the end of the file.
More tangentially, you are forgetting to close the file you write, and generally overcomplicate matters.
Here is a quick refactoring of the two file-management functions.
def open_create_boxes(file):
to_do_list = []
with open(f"{file}.dat", "r") as lines:
for line in lines:
i = line.rstrip("\n").split("|")
# print("#", i)
b = checkbox(i[1])
if i[0] == "x":
b.check()
to_do_list.append(b)
return to_do_list
# Don't call your variable "list"
def create_to_do_list_file (items ,label):
with open(f"{label}.dat", "w") as new_file:
for n in items:
new_file.write(f"o|{n}\n")
As a general first tip for how to debug things, break your problem into smaller steps and add a print statement at various points to verify that the variables contain what you hope they should, or use a debugger and set a breakpoint to examine the program's state at those spots.
\n should be in the back, I put it in the front to see if it would fix my problem. Thank you for the refactoring and the tips.
| common-pile/stackexchange_filtered |
sign in with wechat feather for my application.
I want sign in with wechat feather for my application. I am unable to find any sample code or help document for integration with wechat. Please help me out on the same topic.
Check out http://dev.wechat.com/ for details on the WeChat SDK for iPhone and Android
| common-pile/stackexchange_filtered |
Errors with SSL verification with my python webscraping program using selenium and chromedriver
I have just started another class for my program I am making to help with school and have run into many errors that all seem to be connected to the website requiring SSL verification. This is currently my code:
from selenium import webdriver
from time import sleep
from webdriver_manager.chrome import ChromeDriverManager
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class ratingBot:
def __init__ (self):
#ignoring ssl verifications through chrome webdriver options
self.driver=webdriver.Chrome()
teacher='Jason Yalim'
self.driver.get('https://www.ratemyprofessors.com/search.jsp?queryoption=HEADER&queryBy=teacherName&schoolName=Arizona+State+University&schoolID=45&query=jennie+si')
sleep(4)
driver.get('/html/body/div[10]/button[1]').click()
sleep(2)
driver.find_element_by_xpath('//*[@id="searchr"]').send_keys(teacher)
mybot=ratingBot()
and these are the errors I am getting. Keep in mind that everything is up to date an I have set my chromedriver in my windows PATHS
[16436:16516:1214/210007.796:ERROR:device_event_log_impl.cc(211)] [21:00:07.796] USB: usb_device_handle_win.cc:1020 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
[16056:25032:1214/210013.515:ERROR:ssl_client_socket_impl.cc(960)] handshake failed; returned -1, SSL error code 1, net_error -113
[16056:25032:1214/210013.759:ERROR:ssl_client_socket_impl.cc(960)] handshake failed; returned -1, SSL error code 1, net_error -113
[16056:25032:1214/210018.171:ERROR:ssl_client_socket_impl.cc(960)] handshake failed; returned -1, SSL error code 1, net_error -113
[16056:25032:1214/210018.354:ERROR:ssl_client_socket_impl.cc(960)] handshake failed; returned -1, SSL error code 1, net_error -113
Any help would be greatly appreciated.
Does this answer your question? ERROR:ssl_client_socket_openssl.cc(1158)] handshake failed with ChromeDriver Chrome browser and Selenium
| common-pile/stackexchange_filtered |
How can I bind the position of a line to the transforming position of an Ellipse in XAML
I've got an ellipse that is being translated about by a transform, as specified by the following template:
<DataTemplate x:Key="VectorTemplate">
<Ellipse>
<Ellipse.RenderTransform>
<TranslateTransform X="{Binding Path=X, Converter={StaticResource SomeValueConverter}}" Y="{Binding Path=Y, Converter={StaticResource SomeValueConverter}}" />
</Ellipse.RenderTransform>
</Ellipse>
</DataTemplate>
Elsewhere, I'm defining the ContentControl this renders:
<HierarchicalDataTemplate x:Key="SkeletonTemplate">
<Grid>
<Grid.Resources>
<Style TargetType="{x:Type ContentControl}">
<Setter Property="ContentTemplate" Value="{StaticResource VectorTemplate}" />
</Style>
</Grid.Resources>
<ContentControl Content="{Binding Head}" x:Name="HeadCtrl"/>
<ContentControl Content="{Binding ShoulderCenter}" x:Name="ShoulderCenterCtrl"/>
<Line X1="{Binding Path=????, ElementName=HeadCtrl}" Y1="{Binding Path=????, ElementName=HeadCtrl}" X2="{Binding Path=????, ElementName=ShoulderCenterCtrl}" Y2="{Binding Path=????, ElementName=ShoulderCenterCtrl}" />
</Grid>
</HierarchicalDataTemplate>
As you'll see from the portion that is question marks, I'm not sure how to retrieve the X or Y position from the ContentControl.
This is somewhat simplified from what the code actually contains, so I do have a reason for wanting to bind to the translated position and not just binding to the X value itself (I wind up using a ValueConverter on it). I could just add the same ValueConverter to each and every X and Y coordinate and just specify the field back on the viewmodel, but that seems clunky.
I should be able to bind to the position of these moving elements - can anyone help me out?
If I understood well, you want your line to link the head to the shoulders.
If so, I would directly bind the line positions to the model being the datacontext of the hierarchichalDataTemplate:
<Line X1="{Binding Path=Head.X}" Y1="{Binding Path=Head.Y}" X2="{Binding Path=ShoulderCenter.X}" Y2="{Binding Path=ShoulderCenter.Y}" />
Hope this help.
Antoine
As you'll see in the second to last paragraph of my post, I don't want to bind to the model itself. I'm applying a ValueConverter to those values to position the Vectors, and I don't want to have to reapply the converter over and over again if there's a way to bind to the ellipses themselves.
Perhaps I should have written those into the implementation I pasted, but I figured it would be sufficient to mention it in the body of the post. I went ahead and edited to make it extra clear.
| common-pile/stackexchange_filtered |
How can I get my own User in controller in Asp.net core mvc
I have User class:
public class User : Entity
{
public void AcceptMenu(Menu menu)
{
//AcceptMenu
}
public string Login { get; set; }
public string Password { get; set; }
public string Salt { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
And I create authorization logic. Authenticate method looks like this:
private async Task Authenticate(User user)
{
var claims = new List<Claim>
{
new Claim(ClaimsIdentity.DefaultNameClaimType, user.Login),
new Claim(ClaimsIdentity.DefaultRoleClaimType, user.Role)
};
ClaimsIdentity id = new ClaimsIdentity(claims, "ApplicationCookie", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(id));
}
As you can see I have AcceptMenu method in User. How can I get User in Controller and execute AcceptMenu method?
@AntonToshik, Which function?
Controller has property User with IPrincipal type. You can get name of user with User.Identity.Name But it is name of Authenticated asp.net user. You can map this Authenticated user with your user class.
in controller
ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
ApplicationUser user = await UserManager.FindByEmailAsync(User.Identity.Name);
Where ApplicationUserManager is class with identity config , and ApplicationUser is IdentityUser from this class. But it is not your db User derived from entity class, it should be mapped manually
Are you suggesting get user like: var user = appContext.Users.Single(a => a.Login == User.Identity.Name); ?
Yes it is correct way, also you could use [dbo].[AspNetUsers] but it is not extendable approach
How to get the current logged in user Id in ASP.NET Core
Once you get the value from ClaimsPricipal, you can pass the value as a parameter.
You can always use var loggedInUser = await useManager.GetUserAsync(User) to get the user if you are logged in.
| common-pile/stackexchange_filtered |
Predict gaps between 9 digit 2-palindromes?
$p^2$ $\text{(or 2-palindrome) definition: }$
I call a palindrome $n$-palindromic or $p^n$ if it is palindromic in $n$ consecutive number bases.
For example, $10$ is $p^2$ since it is palindromic in two consecutive bases $10=101_3=22_4$
A number is palindromic in base $b$ if its representation in that base is read the same from both ends. Example: $121$ is palindromic in base $10$. The $9$ is palindromic in binary since $9=1001_2$ .
In this question, I'm concerned with $p^2$s which have $9$ digits in their palindromic bases.
Q: More precisely, given number base $b$, how do you find all $p^2$'s
palindromic in $b$ and $b+1$, which also have $9$ digits in the given
number base?
If we observe all $9$ digit palindromes in some base $b$, then a small amount of them will also be palindromic in base $b+1$ as well. The number of $p^1$s between two consecutive $p^2$s is the gap between those two $p^2$s.
If we could predict the gaps, we could directly land on $p^2$s when iterating palindromes.
I've observed that each number base $b\ge10$ has one smallest gap which repeats between other unique gaps. That gap is always:
$$ g_0= b^2 + 3 b + 4 $$
Thus lets only observe the nontrivial gaps and denote the $k^{\text{th}}$ such gap with $g_k$.
Gap $1$
I believe I've found the patterns to the first gap:
For number bases $(b=2\dots34)$ I have computed the sizes of the first gap:
0, 67, 43, 503, 1986, 1953, 11375, 3448, 25678, 34359, 45878, 64958, 70156, 5272, 111102, 1062, 175244, 212989, 256885, 310741, 367115, 431413, 503739, 584729, 674285, 763967, 873321, 1000468, 1127673, 1253127, 1409964, 1582265, 1769818
Then for number bases $(b=35\dots48)$, we can get the first gap using following expressions:
$$
g_1(b) =
\begin{cases}
3939 n^4 + 11330 n^3 + 911097 n^2 + 5806354 n + 17285844, & \text{$b=32+3n$} \\
- 127 n^4 + 29350 n^3 + 392617 n^2 + 3298772 n + 9622146, & \text{$b=33+3n$} \\
n^3 + 216972 n^2 + 1768636 n + 5397267 , & \text{$b=34+3n$}
\end{cases}
$$
The next pattern is in $(b=49\dots62)$, given by:
$$
g_1(b) =
\begin{cases}
16 n^4 + 1596 n^3 + 59626 n^2 + 988940 n + 6144706, & \text{$b=47+2n$} \\
16 n^4 + 1628 n^3 + 62046 n^2 + 1049870 n + 6655509, & \text{$b=48+2n$}
\end{cases}
$$
The following pattern is in $(b=63\dots92)$, given by:
$$ g_1(b) = b^4+12b^3+b^2-39b-59 $$
Next we have (the final pattern?) for $(b\ge93)$, the following:
$$ g_1(b) = b^4+12b^3+34b^2+60b+74 $$
This was verified palindrome-by-palindrome up to $115$, and verified under assumption that the next gap is always bigger than previous, up to $300$. This leads me to believe that this last pattern holds for all number bases $b\ge93$.
Gap $2$
After the first gap comes the first $p^2$, then we have multiple consecutive gaps of size $g_0$ and some $p^2$s between them (the bigger the base, the more $g_0$'s). Then comes the gap $g_2$. I also believe to have found the pattern for this gap:
For first number bases $(b=2\dots92)$ I have computed the gaps $g_2(b)=$
0, 0, 458, 30, 0, 7277, 2078, 15474, 538, 634, 2056, 33914, 2907, 87573, 5259, 136771, 1127, 824, 3758, 17833, 19999, 17513, 5270, 10589, 12158, 10584, 6074, 39244, 6926, 20138, 22517, 25070, 26541, 78787, 60625, 35657, 39092, 39451, 43144, 45245, 47396, 49597, 53920, 56313, 61016, 63609, 68708, |66406, 69059, 74522, 77385, 83274, 89437, 95880, 99301, 109630, 113407, 120910, 128721, 136846, 141257, 154062, 158873, 168182, 177833, 187832, 193353, 208898, 214863, 226170, 237853, 249918, 153955, 163913, 168225, 172593, 183339, 187979, 192677, 204241, 209221, 214261, 226673, 232005, 237399, 250689, 256385, 262145, 276343, 282415, 288553
I believe there are patterns among these like the patterns for bases $b\lt92$ in gaps $g_1$.
Then we have patterns for $(b=93\dots140)$, as follows:
$$
g_2(b) =
\begin{cases}
2 (24 n^3 + 1614 n^2 + 36184 n + 270429), & \text{$b=89+4n$} \\
2 (24 n^3 + 1626 n^2 + 36721 n + 276436) , & \text{$b=90+4n$} \\
2 (24 n^3 + 1646 n^2 + 37631 n + 286788) , & \text{$b=91+4n$} \\
4 (12 n^3 + 833 n^2 + 19276 n + 148696) , & \text{$b=92+4n$}
\end{cases}
$$
And patterns which I believe to hold for all $(b\ge141)$, below:
$$ g_2(b) = \begin{cases} 4 (4 n^3 + 497 n^2 + 20033 n + 263850) ,
& \text{$b=137+4n$} \\ 2 (8 n^3 + 998 n^2 + 40425 n + 535346) , &
\text{$b=138+4n$} \\ 2 (8 n^3 + 1002 n^2 + 40785 n + 543047) , &
\text{$b=139+4n$} \\ 2 (8 n^3 + 1014 n^2 + 41712 n + 560815) , &
\text{$b=140+4n$} \end{cases} $$
This was verified up to base $400$ and at that point I was convinced the pattern won't change anymore. This was also assuming every next gap is larger than previous (by this I mean I can skip terms equal to the previous gap when checking), as all patterns so far suggest for larger bases. (notice this is not true for small bases, see computed examples where some gaps jump up and down, due to patterns not being "stabilized" yet)
Gap $k$?
I could compute examples for some gap $k$ in number bases $b\gt X$ where $X$ is some big number base where we have the last pattern, and then try to fit them into polynomial equations like it was possible for $g_1$ and $g_2$.
But can these final patterns be reached algebraically or be generated?
This would make things much easier. (Also, knowing $X$ for some $g_k$
helps)
And what about the patterns for bases $b\le X$? How can we find those
patterns without needing to compute and check almost every palindrome?
And looking at the small bases for first two gaps, is there actually a
pattern to these or we have no choice but to check every palindrome to
make sure we haven't jumped over some $p^2$?
You can download 9.html from my google drive and see all gaps for first $55$ number bases. (It is not .txt since a text file breaks lines. Download and open it in browser to be able to scroll around nicely without broken lines.)
(Would've posted it here as code but the character limit is beyond exceeded)
The other file contains all gaps for first $222$ number bases but only up to the $g_3$ which itself is marked with [?] as the first two gaps (and trivial gaps bewteen them) were being computed only.
(Trivial gaps are marked by * after them)
I can perhaps tidy up my python code and post it if you wish to compute more/other gaps like that. (I used wolfram alpha to fit computed results into polynomials and verify them for more terms)
P.S. All this here is one approach towards solving $P_9$ by osberving gaps bewteen palindromes, which here represents solutions for $p^2$'s of nine digits.
Taking a second look, is it possible to have an algorithm that if you
give it base $b$ and some $k$, it outputs at least some lower bound
for gap $g_k$ (if $b\lt X$ for that $k$, otherwise the final pattern
should exist, thus it finds and uses that) ?
| common-pile/stackexchange_filtered |
solving a univariate equation with a sum of exponentials
I am interested in a method to find the roots of the following equation:
\begin{equation}
f(t) = \sum_{i=1}^n \alpha_i e^{\beta_i t} + \gamma t + \delta = 0.
\end{equation}
For my application, coefficients $\alpha_i$, $\beta_i$, $\gamma$, and $\delta$ are real. $n$ is typically a small integer, say 10. In particular I am interested in the smallest positive real root of $f$.
For those interested, this equation arises when attempting to compute the point of intersection between the solution to the linear ODE
\begin{align}
\dot x(t) &= Ax(t) + b & (A = A^T) \\
x(0) &= x_0
\end{align}
and the boundary of a set of linear constraints
\begin{equation}
Cx(t) \ge d.
\end{equation}
The initial point is always feasible $(Cx_0\ge d)$. For my purposes, all matrices and vectors are real.
Assuming $\alpha_i, \beta_i, \gamma$, and $\delta $ are givens, any numeric root finder should make quick work of this. There won't be an algebraic solution. There is good info at Numerical Recipes chapter 9.
As an additional reminder: unless you have good starting points for the roots, you would do well to 1.) plot the function in the range of interest to be able to see where the roots might be; and 2.) use a "safe" rootfinding algorithm like Brent's method.
Numerical Recipes suggests strongly that even if you can't look at all the cases, at least look at a bunch to see what they look like. This will give you some ideas. Certainly starting with t=0 for one end of your bracket will help. If you can find a t where the function has the opposite sign, the root is bracketed and you can find it. The risk is that there are three (or more) roots and you don't find the smallest.
Thanks Ross and J.M. I have to solve this equation many times in my code. Visual inspection is not an option. Also I need a guarantee that I find the smallest positive real root. When $\gamma = 0$ and $n = 2$, I can reliably use fzero in Matlab to meet my requirements. I first solve $f'(t)=0$ to find the critical points. For the general problem I've been using chebfun, which works, but ends up being slow. I was/am hoping there is a specific algorithm to solve the equation directly.
| common-pile/stackexchange_filtered |
regex help, pulling last two verbs seperated by semi-colons
Verb_1;Verb_6;Verb_7;EXT_80;CAP_81;TREE_26;END;
In the example above, I am trying to figure out how to regex out CAP_81, and TREE_26, basically the last two verbs in the string seperated by semi-colons. So the BigQuery SQL field would equal
CAP_81;TREE_26;
I am not sure how to work regex.
You can use regexp_extract():
select regexp_extract(val, '([^;]+;[^;]+;)END;$')
Sorry for the low effort question, but to be honest you saved me like an hour trying to figure it out on my own. So I thank you for that. Reviewing your answer helped me learn more also
| common-pile/stackexchange_filtered |
MySQL too many processes and Consuming RAM
I am suddenly having this problem of too many mysqld processes.
When my PC starts the occupied RAM is around 2GB and then when I start XAMPP, slowly and gradually the RAM is occupied at around 14 GB. I currently am running on a 16 GB Memory and using Linux Mint.
Can anyone help?
In the config file for MySQL, lower max_connections to, say, 20. That setting is what controls the list you are seeing.
Meanwhile, how much RAM can you give to MySQL? That is, how much RAM do you need to give to other processes? What is the value of innodb_buffer_pool_size? The buffer_pool grows until it reaches that value. It is very important for performance, so it is a tradeoff between performance and running out of RAM. Lowering the buffer_pool setting is the primary way to shrink MySQL.
(Questions on configuring MySQL belong in dba.stackexchange.com)
first update server(for centos: yum update)
anden set this value on your my.cnf file in /etc
innodb_buffer_pool_size => 70% or 80% of your ram
innodb_buffer_pool_size = innodb_buffer_pool_chunk_size * innodb_buffer_pool_instances * N
example for 6G ram:
innodb_buffer_pool_size =<PHONE_NUMBER>
innodb_buffer_pool_chunk_size =<PHONE_NUMBER>
innodb_buffer_pool_instances = 4
| common-pile/stackexchange_filtered |
Invite Facebook Friends in iOS 9
I used this code to invite friend in my iOS App
[FBWebDialogs presentRequestsDialogModallyWithSession:nil
message:@"Test1"
title:@"Title 1"
parameters:parameters
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error)
{
if(error)
{
NSLog(@"Some errorr: %@", [error description]);
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:@"Invitiation Sending Failed" message:@"Unable to send inviation at this Moment, please make sure your are connected with internet" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alrt show];
}
else
{
if (![resultURL query])
{
return;
}
NSDictionary *params = [self parseURLParams:[resultURL query]];
NSMutableArray *recipientIDs = [[NSMutableArray alloc] init] ;
for (NSString *paramKey in params)
{
if ([paramKey hasPrefix:@"to["])
{
[recipientIDs addObject:[params objectForKey:paramKey]];
}
}
if ([params objectForKey:@"request"])
{
NSLog(@"Request ID: %@", [params objectForKey:@"request"]);
}
if ([recipientIDs count] > 0)
{
//[self showMessage:@"Sent request successfully."];
//NSLog(@"Recipient ID(s): %@", recipientIDs);
UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:@"Success!" message:@"Invitation(s) sent successfuly!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alrt show];
}
}
}
friendCache:nil];
//sample code 2
[FBWebDialogs
presentRequestsDialogModallyWithSession:nil
message:@"Yeeeeep Check my app"
title:@"Burp War"
parameters:nil
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// Error launching the dialog or sending the request.
NSLog(@"Error sending request.");
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
// User clicked the "x" icon
NSLog(@"User canceled request.");
} else {
// Handle the send request callback
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
if (![urlParams valueForKey:@"request"]) {
// User clicked the Cancel button
NSLog(@"User canceled request.");
} else {
// User clicked the Send button
NSString *requestID = [urlParams valueForKey:@"request"];
NSLog(@"Request ID: %@", requestID);
}
}
}
}];
But unfortunately this is not working getting error "Game request only for game app". How to get email id of friends? thanks in advance.
Define "not working". Any error?
@Raptor Game request error. could you please help me.?
what is the purpose of get email?explain what you want
you can't get email but you got name & id who install your app
@Maulik. In my app i am sending invitations based on email.any help did ?
you can't send invitation via email... for facebook app invite https://developers.facebook.com/docs/app-invites/ios
@Maulik. ohh this invitation not related to facebook it's about own app by web service
not possible....after 2.0 api
Let us continue this discussion in chat.
The new graph api only supports User Invitable Friends only for games
https://developers.facebook.com/docs/graph-api/reference/v2.5/user/invitable_friends
https://developers.facebook.com/docs/games/services/gamerequests
Note: There is no way for apps to obtain email addresses for a user's friends.
facebook policy statement states this
How can I get facebook friends list email addresses?
How to get a facebook user's friends emails
| common-pile/stackexchange_filtered |
How does Thickbox work for displaying another page Like Login page?
I ask this because I want to display a page in iframe and on clicking any link in iframe content, it should display it in the same iframe.
Check this site. and see how an iframe alow me to surf other sites.
that's not anything special, that's just how iframes work.
however if any of those sites had an
<a href="LINK" target="_top">text</a>
It would break out of the iframe and load in the main page.
There is no way that I am aware of to stop an iframe from taking over your window with target=_top links. You can't modify someone else's content in the iframe from your parent window, there are security issues with talking cross frame that prevent you from doing this.
With Thickbox just load your html file and make sure you dont target=_top in any of thage pages you want to stay in the iframe.
So copy & pasting from ThickBox's example, with some jQuery:
<script>
var height = 300;
var width = 300;
$(function(){
$("#execute").click(function(){
$("#link1").attr('href',$('#go').val() + "?height=" + height *"&width=" + width).trigger('click');
});
});
</script>
<input type="text" name="go" id="go" />
<button id="execute">Go >></button>
<a id="link1" href="ajaxOverFlow.html?height=300&width=300" title="add a caption to title attribute / or leave blank" class="thickbox">Scrolling content</a>
The Facebox plugin will pull in remote pages in a Thickbox way.
| common-pile/stackexchange_filtered |
How to pass data from vaadin webapp to C# GUI app
I have webapp in Vaadin Framework 8. I have Windows GUI app in C#.
The gui app is using WebBrowser component to display webapp. WebBrowser component is internally using IE11 core through ActiveX. I can successfully load and display the webapp in the gui app browser component.
I need to pass data from webapp to the gui app.
The webapp has many rows loaded on server side, only few are displayed in grid. I want to pass all data from webapp to gui app in some format (csv or json).
I have tryed some approaches, but I wasn't successfull.
[Approach 1]
Webapp: attach downloadable resource (csv) to Link with predefined id using FileDownloader. Download by user mouse click works fine, file save dialog pops up and data are downloaded successfully.
Link link = new Link("Data");
link.setId("myId");
StreamResource resource = getMyResource(data);
FileDownloader downloader = new FileDownloader(resource);
downloader.extend(link);
Page.getCurrent().getJavaScript().addFunction("test", new JavaScriptFunction() {
@Override
public void call(JsonArray arguments) {
Page.getCurrent().getJavaScript()
.execute("document.getElementById('myId').click()");
}
});
Gui app: raise onClick event on link and capture WebBrowser.FileDownload event, capture WebBrowser.Navigate event.
I have failed to raise onClick event from C# using:
HtmlElement el = webBrowser.Document.GetElementById("myId");
el.RaiseEvent("onClick");
el.InvokeMember("click");
webBrowser.Document.InvokeScript("document.getElementById('myId').click();", null);
webBrowser.Document.InvokeScript("test", null);
Result:
WebBrowser.FileDownload event doesn't work (is fired but can't capture url nor data), capture WebBrowser.Navigate event works partialy (can see resource url, but can't download data using byte[] b = new WebClient().DownloadData(e.Url);).
[Approach 2]
Similar to approach 1. I tryed to get resource url, put the direct url to Link and download the resource in c# using direct link. I can construct the same resource url as is used by browser to download data when user clicks the link.
Extended file downloader that keeps resource, key and connector:
public class ExtendedFileDownloader extends FileDownloader {
private String myKey;
private Resource myResource;
private ClientConnector myConnector;
public ExtendedFileDownloader(StreamResource resource, ClientConnector connector) {
super(resource);
myConnector = connector;
}
@Override
protected void setResource(String key, Resource resource) {
super.setResource(key, resource);
myKey = key;
myResource = resource;
}
public String getResourceUrl() {
ResourceReference ref =
ResourceReference.create(
myResource,
(myConnector != null) ? myConnector : this,
myKey);
String url = ref.getURL();
return url;
}
}
In view:
// fix app://path... urls to /<base-path>/path urls
private String fixResourceReferenceUrl(String resourceReferenceUrl) {
String resourceReferencePath = resourceReferenceUrl.replace("app://", "");
String uiBaseUrl = ui.getUiRootPath();
String fixedUrl = uiBaseUrl + "/" + resourceReferencePath;
return fixedUrl;
}
Link link2 = new Link("Data2");
link2.setId("myId2");
StreamResource resource = getMyResource(data);
ExtendedFileDownloader downloader = new ExtendedFileDownloader(resource, this);
String fixedResourceUrl = fixResourceReferenceUrl(downloader.getResourceUrl());
link2.setResource(new ExternalResource(fixedResourceUrl));
Result:
The data cannot be downloaded using this link, server error 410 or NotFound errors.
Any Ideas ? Any other approaches to try ?
Would it be possible for your webapp and GUI app to use the same database or backend service for sharing the data?
Yes, common backend service can help, but I would like to find some direct method. Do you think it would be possible to download data using direct resource link (approach 2) when I use all cookies from gui app Webbrowser component in a WebClient component (or another downloader) ?
I have finally solved the problem. The solution is very close to approach 2.
The resource url is passed in element with custom attribute. C# WebClient needs to set cookies from WebBrowser and Referer HTTP headers. The data can be successfully downloaded by C# app.
Element attribute in vaadin webapp can be set using Vaadin-addon Attributes.
Cookies in C# app can be retrieved using this solution.
// Fix resource urls begining with app://
public String fixResourceReferenceUrl(String resourceReferenceUrl) {
try {
String uiRootPath = UI.getCurrent().getUiRootPath();
URI location = Page.getCurrent().getLocation();
String appLocation = new URIBuilder()
.setScheme(location.getScheme())
.setHost(location.getHost())
.setPort(location.getPort())
.setPath(uiRootPath)
.build()
.toString();
String resourceReferencePath = resourceReferenceUrl.replace("app://", "");
String fixedUrl = appLocation + "/" + resourceReferencePath;
return fixedUrl;
}
catch (Exception e) {
return null;
}
}
In view (using ExtendedFileDownloader from above):
Link link = new Link("Data");
link.setId("myId");
StreamResource resource = getMyResource(data);
ExtendedFileDownloader downloader = new ExtendedFileDownloader(resource);
downloader.extend(link);
Attribute attr = new Attribute("x-my-data", fixResourceReferenceUrl(downloader.getResourceUrl()));
attr.extend(link);
link.setVisible(true);
In C# app:
[DllImport("wininet.dll", SetLastError = true)]
public static extern bool InternetGetCookieEx(
string url,
string cookieName,
StringBuilder cookieData,
ref int size,
Int32 dwFlags,
IntPtr lpReserved);
private const Int32 InternetCookieHttponly = 0x2000;
public static String GetUriCookies(String uri)
{
// Determine the size of the cookie
int datasize = 8192 * 16;
StringBuilder cookieData = new StringBuilder(datasize);
if (!InternetGetCookieEx(uri, null, cookieData, ref datasize, InternetCookieHttponly, IntPtr.Zero))
{
if (datasize < 0)
return null;
// Allocate stringbuilder large enough to hold the cookie
cookieData = new StringBuilder(datasize);
if (!InternetGetCookieEx(
uri,
null, cookieData,
ref datasize,
InternetCookieHttponly,
IntPtr.Zero))
return null;
}
return cookieData.ToString();
}
private void button_Click(object sender, EventArgs e)
{
HtmlElement el = webBrowser.Document.GetElementById("myId");
String url = el.GetAttribute("x-my-data");
String cookies = GetUriCookies(url);
WebClient wc = new WebClient();
wc.Headers.Add("Cookie", cookies);
wc.Headers.Add("Referer", WEB_APP_URL); // url of webapp base path, http://myhost/MyUI
byte[] data = wc.DownloadData(url);
}
| common-pile/stackexchange_filtered |
Levenstein distance limit
If I have some distance which I do not want to exceed. Example = 2.
Do I can break from algoritm before its complete completion knowing the minimum allowable distance?
Perhaps there are similar algorithms in which it can be done.
It is necessary for me to reduce the time of work programs.
Not sure if I understand correctly. Levenshtein distance has a runtime complexity of O(n*m) where n and m are the length of the two words. Are you asking for a lower bound such that you can avoid performing the distance computation? One simple lower bound is LD(a, b) >= |len(a)-len(b)| having only a O(1) complexity.
@SaiBot The question is whether it is possible to exit the algorithm before it is fully executed knowing the minimum permissible distance
Yes you can do early stopping if every cost in row or column is already larger than 2. Additionally, you can use the lower bound I proposed. However, if you want to find all words that have a lower distance than 2 to a query in a large set of words there are probably better ways of doing this, e.g., through precomputation.
If you do top-down dynamic programming/recursion + memoization, you could pass the current size as an extra parameter and return early if it exceeds 2. But I think this will be inefficient because you will revisit states.
If you do bottom-up dp, you will fill row by row (you only have to keep the last and current row). If the last row only has entries greater than 2, you can terminate early.
Modify your source code according to my comment:
for (var i = 1; i <= source1Length; i++)
{
for (var j = 1; j <= source2Length; j++)
{
var cost = (source2[j - 1] == source1[i - 1]) ? 0 : 1;
matrix[i, j] = Math.Min(
Math.Min(matrix[i - 1, j] + 1, matrix[i, j - 1] + 1),
matrix[i - 1, j - 1] + cost);
}
// modify here:
// check here if matrix[i,...] is completely > 2, if yes, break
}
I use this algorithm - https://gist.github.com/Davidblkx/e12ab0bb2aff7fd8072632b396538560. Last row i will know after fully executed this method
@noobprogrammer ok, you keep all rows, but the last row I reference is the one you last update. I added a part of your src code, hope it helps
You shouldn't iterate through the entire second string, only through a narrow window around i (i-max_distance, i+max_distance) you will only find larger values outside it. As it stands you still have O(N*M) complexity.
@Sorin yes, it doesn't change the complexity. your idea is great
Yes you can and it does reduce the complexity.
The main thing to observe is that levenstein_distance(a,b) >= |len(a) - len(b)| That is the distance can't be less than the difference in the lengths of the strings. At the very minimum you need to add characters to make them the same length.
Knowing this you can ignore all the cells in the original matrix where |i-j| > max_distance. So you can modify your loops from
for (i in 0 -> len(a))
for (j in 0 -> len(b))
to
for (i in 0-> len(a))
for (j in max(0,i-max_distance) -> min(len(b), i+max_distance))
You can keep the original matrix if it's easier for you, but you can also save space by having a matrix of (len(a), 2*max_distance) and adjusting the indices.
Once every cost you have in the last row > max_distance you can stop the algorithm.
This will give you O(N*max_distance) complexity. Since your max_distance is 2 the complexity is almost linear. You can also bail at the start is |len(a)-len(b)| > max_distance.
I have max distance value = 4 and two strings - "#kjhEISV" and "#kjhDRSGBG". Final distance = 5 but I not break algorithm use "last row > max_distance you can stop the algorithm."
@noobprogrammer You interpret it wrong. You said that your max distance value = 4. So you don't care if the distance is 5 or more. The algorithm will break and tell you the distance is more than 4. The algorithm will return the correct value only if it's within max distance. You can make a nicer wrapper to return an error code or throw an exception or whatever it's better in your context.
@noobprogrammer The fact that you get a 5 as a result you need to interpret as the distance between the strings is more than max distance (4).
| common-pile/stackexchange_filtered |
Multiple photos upload via Cloudinary.DotNet
I have configured my CloudinaryService to upload JUST ONE photo on my cloud on cloudinary. But i have really great troubles with configuring this to make it work on multiple uploads. Please help me, here is my code for single upload:
public async Task<string> UploadPictureAsync(IFormFile pictureFile, string fileName)
{
byte[] destinationData;
using (var ms = new MemoryStream())
{
await pictureFile.CopyToAsync(ms);
destinationData = ms.ToArray();
}
UploadResult uploadResult = null;
using (var ms = new MemoryStream(destinationData))
{
ImageUploadParams uploadParams = new ImageUploadParams
{
Folder = "cars",
File = new FileDescription(fileName, ms),
PublicId = "audizone"
};
uploadResult = this.cloudinaryUtility.Upload(uploadParams);
}
return uploadResult?.SecureUri.AbsoluteUri;
}
}
}
I change IFormFile pictureFile to List<IFormFile> pictureFiles, going on with foreach (file in pictureFiles)...the only thing this service is doing is just uploading 2 or 3 times the same picture(the first one of three or two)...just not uploading two or three different photos.
<form asp-action="Create" method="post" enctype="multipart/form-data">
<input type="file" multiple
class="form-control text-primary text-center"
id="picture"
name="picture"
placeholder="Picture..." />
<input type="submit" value="Submit" class="btn btn-dark" style="border-bottom-left-
radius:25%;border-bottom-right-radius:25%" />
</form>
I managed to successfully loop using this method:
public static void BulkUpload(List<string> filePaths, ResourceType resourceType = ResourceType.Image, string type = "upload")
{
var cloudinary = GetCloudinary(); // Initializing Cloudinary
foreach (var path in filePaths)
{
byte[] bytes = File.ReadAllBytes(path);
var streamed = "streamed";
using (MemoryStream memoryStream = new MemoryStream(bytes))
{
ImageUploadParams uploadParams = new ImageUploadParams()
{
File = new FileDescription(streamed, memoryStream)
};
ImageUploadResult uploadResult = cloudinary.Upload(uploadParams);
if (uploadResult.StatusCode == HttpStatusCode.OK)
Console.WriteLine("uploaded: " + uploadResult.PublicId);
else
Console.WriteLine("Failed: " + uploadResult.Error);
}
}
}
Thank you for help but ...i'm afraid i cant implement it to my code... in my Create (List pictures) and the multiple photos come from ....i couldnt handle the List filepaths... :(
But i made it work for myself...thank you thank you a lot...now i have to assign the urls to the object collection ...
| common-pile/stackexchange_filtered |
Set Soap Header ksoap2 android
First, I apologize for asking a question that is already common here in the SOF.
But I am a beginner and I'm certainly cruel.
I am creating an android application that communicates with a WS. So I can make requests to the WS, I have to add a value to the header of the envelope, but I can not add.
I found some answers about it here in the SOF, however, could not fully understand how it works. Perhaps, my doubts are due to the nodes of the header, which ended up confusing me even more.
One of the answers I found I ended up not helping: "How to set soap header using ksoap2 android"
Below is the XML request that needs to be done:
?xml version="1.0" encoding="utf-8"?
soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
soap:Header
ValidationSoapHeader xmlns="http://tempuri.org/"
DevToken>string/DevToken
/ValidationSoapHeader
/soap:Header
soap:Body
ListaCidades xmlns="http://tempuri.org/" /
/soap:Body
/soap:Envelope
And my code below:
SoapObject request = new SoapObject(ApplicationData.NAMESPACE, ApplicationData.METHOD_NAME_LISTA_CIDADES);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
How exactly do I use the envelope.HeaderOut? Is it really necessary to create a helper method to build an Element even having to pass only one parameter (DevToken)?
Thank you for your attention!
Solved!!! Finally managed to solve!
Element h = new Element().createElement(NAMESPACE, "AuthHeader");
Element Username = new Element().createElement(NAMESPACE, "Username");
Username.addChild(Node.TEXT, "CBROWN");
h.addChild(Node.ELEMENT, Username);
Element wssePassword = new Element().createElement(NAMESPACE, "wssePassword");
wssePassword.addChild(Node.TEXT, "welcome");
h.addChild(Node.ELEMENT, wssePassword);
envelope.headerOut = new Element[]{h};
add above code for add header in envelope
Kels can u please connect me here https://chat.stackoverflow.com/rooms/146715/soap
| common-pile/stackexchange_filtered |
How to fix oracle PL/SQL: ORA-00909: invalid number of argumentsCompilation failed,line 8 (13:53:12)
I am creating a procedure with the following code in Oracle Apex
create or replace Procedure weekely_report
(W_start IN weekely_report.StartDate%TYPE, W_end IN
weekely_report.EndDate%TYPE)
IS
BEGIN
UPDATE weekely_report
SET commission_amount = Sales_Amount*Com_Rate
where (StartDate-EndDate) = (w_start- W_end);
SELECT concat('New Commission amount of',ID,' is
',commission_amount,' dollars,
is equal to',commission_amount,'% of the total sale amount of ',Sales_Amount,' dollars.')
COMMIT;
END;
But When I execute this, It give following error
Compilation failed,line 8 (13:53:12) PL/SQL: ORA-00909: invalid number
of argumentsCompilation failed,line 8 (13:53:12) PL/SQL: SQL Statement
ignored
But the number of arguments is already completed, I checked twice.
Your select statement is invalid. It is allowed in Mysql. I think there is the issue.
@AnkitBajpai I think select statement has no issue
In Oracle you cannot run any select without dual table.
@RamiFar - it does; as well as the concat() call having too many arguments, you have no from clause (and no into clause).
" I think select statement has no issue" Oracle disagrees. Guess where my money is. In oracle, a SELECT statement must select FROM something. If the data being SELECTed is not coming from a table or view (that is, it is just selecting the results of a function) then that is what oracle provides the DUAL table for . It is a dummy table to be the target of the FROM clause when there is nothing else.
Besides the missing FROM clause in Oracle the concat function takes exactly 2 parameters, yours has 8. You can nest them so you have concat(concat(cancat(...)))))) or convert to the concatenation operator (||). Words of Wisdom: Do not argue with the compiler it wins every time. Your job is to figure out what is wrong, not to declare the compiler incorrect.
Oracle's concat() function only takes two arguments. You could nest calls:
SELECT concat(concat(concat(....
but that gets messy and hard to manage. it's simpler to user the concatenation operator ||:
SELECT 'New Commission amount of ' || ID || ' is ' || commission_amount
|| ' dollars, is equal to ' || commission_amount || '% of the total sale amount of '
|| Sales_Amount || ' dollars.'
Your % looks like it should be a calculation, incidentally.
However, in Oracle you have to select from something, which in this case could be the table you just updated if your where condition identifies a single row; though a condition based on the number of days between two dates doesn't seem likely to do that - maybe that should be looking for matching start and end dates, rather than the size of the range? Then it might be unique. But in PL/SQL you also have to select into something such as a local variable or OUT parameter.
You could perhaps use the returning into clause in your update statement instead.
It isn't clear what you expect to happen to that generated string though.
First of all, you have to add "from DUAL" to your SELECT statement. After that, you have to store the result into a variable using INTO clause. Finally, in Oracle, the CONCAT function will only allow you to concatenate two values together. If you want to concatenate more values than two, you can nest multiple CONCAT function calls.
For example:
SELECT CONCAT(CONCAT('A', 'B'),'C')
FROM dual;
Result: 'ABC'
Using pipe || is a more comfortable solution.
| common-pile/stackexchange_filtered |
How to hide EDGE icon from statusbar in Android 5.1?
After 5.1 upgrade this EDGE with a red circle appeared in the statusbar. It's useless and the size is wrong. How do I remove or hide it?
Is your phone rooted? And please add your phone model. And this will be displayed if you turn on the mobile data. To hide the icon you need to turn off the mobile data.
It's Moto X (1 gen.). Updated to 5.1 a week ago. Not rooted. Mobile data is turned off already. I guess that's why there's a red circle.
Oh. You didn't mentioned that earlier. I guess it's only with 5.1 even if the data is off.
| common-pile/stackexchange_filtered |
SwiftUI - How does a View know to update and why does ForEach need an id parameter?
First, is it true that SwiftUI Views are automatically redrawn on their own as needed?
Also, why is id a required parameter to ForEach?
For example, I want to loop over the elements of an array ["a","a","a"] with ForEach,
VStack {
ForEach(array, id:\.self) { item in
Text(item)
}
If the array is changed to become ["b","b","b"] what causes the Views to be redrawn?
Does ForEach simply recognize that the array changed?
It's important that the id of a data element doesn't change unless you replace the data element with a new data element that has a new identity. If the id of a data element changes, the content view generated from that data element loses any current state and animations.
Thinking ForEach is a loop instead of a View and using id:\.self instead of a proper identifier are probably the 2 most common mistakes in SwiftUI.
it goes over the loop again and creates a view for each element again
Don't think of a view like a UIKit "UIView". A SwiftUI view is just a description. The foreach is creating a value struct that is compared against the previous value struct. The diffs, if any, are used by the SwiftUI runtime to work out how to mutate the on screen drawing objects, including, for example, animating the changes. SwiftUI automatically works out how it will make changes to what was drawn previously in order to get to what should be being drawn now.
The id is needed so that you can work out from the diff how exactly something changed, for example if you only know:
["A", "B", "C"]
->
["B", "C", "C"]
That could be:
(1) A changing to B, the B to C
or
(2) the A being removed, and then a C being added to the end.
By adding in an ID we can tell which thing is which:
[("A", 1), ("B", 2), ("C", 3)]
->
[("B", 1), ("C", 2), ("C", 3)]
= change A to B, change B to C
= animate cells 1 and 2
or
[("A", 1), ("B", 2), ("C", 3)]
->
[("B", 2), ("C", 3), ("C", 4)]
= delete 1, append 4 = "C"
= animate deletion of 1, shift cells left, animate new cell in from right
The magic of how SwiftUI view notices it needs to recompute a View body and work out if anything/what has changed, and potentially update its drawing state is based around the property wrappers of State, ObservedObject, StateObject etc (not ForEach). These propertyWrappers wrap the variables like your "array" such that when they are set (when their setter function is called), additional work is performed to call your view's body function to give a new value for the view's description and then the diffing, possible updating etc all happens.
In your case where the array is ["a", "a", "a"] you're setting the id to \.self which is "a"(i.e self). Similarly, if you change that array to ["b", "b", "b"] the id changes to "b" causing a redraw.
Identifiable
We use the id in order to make the array act like the Identifiable protocol. Try this:
ForEach(0..<someArray.count) { index in
...
}.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
self.someArray.append(someElement)
}
}
When you run the above snippet, the ForEach doesn't get redrawn. That behavior is the result of not using Identifiable or assigning a uniques identifier, ForEach can't identify each unique element, hence it will give you a runtime warning(purple colored).
ForEach
Only use ForEach(0..<array.count) { index in when your data is
static.
If it is dynamic, use the Identifiable protocol: ForEach(someIdentifiableArray) { element in
Or using id: ForEach(someIdentifiableArray, id: \.uniqueProperty) { element in
Note: When an array contains duplicates, make sure to have an id property used for identification like UUID.
Wait but so what exactly is causing a redraw? The fact that I mutated the array right? And why does it specifically need the ID though? Can you maybe give me an example where the ID is necessary? If I have some array with "a" 3 times and I add "b" or something it will redraw it because the array got mutated but why is the ID ever important I need like an example of it being useful
it is important if you have a dynamic array, the redraw happens when mutating the array.
| common-pile/stackexchange_filtered |
how to get nova client (v1.1) to use ssh tunnel when retrieving server list
the openstack nova client is giving me fits. i can't figure out how to get it to use a local ssh tunnel url i specify instead of the one it retrieves. so:
from novaclient.v1_1 import client as nova_client
from pprint import pprint
self.__nova_client = nova_client.Client(
'myusername',
'mypassword',
'mytenantname',
'https://localhost:5443/v2.0',
service_type='compute',
insecure=True
)
for server in self.__nova_client.servers.list():
pprint(server)
yields...
requests.exceptions.ConnectionError: HTTPConnectionPool(host='os-compute.vip.mysubdomain.mydomain.com', port=8774): Max retries exceeded with url: /v2/aa0dffecaef543aca072a26fdff5c92b/servers/detail (Caused by <class 'socket.error'>: [Errno 111] Connection refused)
because the "os-compute.vip.mysubdomain.mydomain.com:8774" address is unreachable from where the script is running.
the self.__nova_client = nova_client.Client() bit connects fine because it uses 'https://localhost:5443/v2.0' - the established tunnel i provide. i just need a way to override the "os-compute.vip.mysubdomain.mydomain.com:8774" that it's trying to connect to with a "localhost:8774" tunnel that i set up. but i can't figure out whether/how that's possible.
any guidance will be greatly appreciated.
Your nova client is pulling the service catalogue from keystone through the tunnel setup on your localhost. You will need to explicitly override the endpoint specified in the service catalogue.
One way is to explicitly specify the endpoint, while some of the clients allow you to directly specify the endpoint on construction novaclient doesn't, take a look at nova_client.management_url after you've constructed the object and replace it with your localhost address.
| common-pile/stackexchange_filtered |
Venturi Meter and Pascal's principle
When trying to understand how the venturimeter works, I got stucked with the following affirmation:
Then, we have the equation $P_1 = P_2 + \rho g d$
Where $d$ is the distance between the two points, $P_1$ and $P_2$ being the respective pressures, and $\rho$ is the blue liquid's density (which also fills the entire tube). As I understand, that equation follows from Pascal's Principle.
Here's the problem: As far as I know, Pascal's principle only applies to Fluids at rest, but the Fluid in the tube has velocity $V > 0$, which is not static. So, my question is: Why can we apply Pascal's principle here?. If Pascal's principle is indeed the case, how do you derive that equation in the case of fluids in motion and how do I determine when Pascal's principle can be applied? (Because not all fluids in motion obbey this law)
Obs: This formula has been derived in this question and impied in Halliday, Renick. Fundamentals of Physics, 14th Chapter, 10th edition in the problems section 14-7, problem 65. This video also touches this topic.
Something is wrong with your equation. Is the blue liquid water? Is the silver liquid mercury? With two liquids involved, there are two different densities to worry about.
To be clear: There are two fluids involved in the whole problem. However, note that Pascal principle is being used only in the red column of (lets suppose) water. Why it does not matter that there are two fluids in the artifact? Because I'm just considering one part of the whole venturimeter (namely, again, the left red column of water, and applying possibly pascal's principle to that reduced system)
Maybe what's confusing you is the fact that I didn't specify whose density is $\rho$. Made an update to fix that.
EDIT:-Pascal's principle can NOT be applied on the fluid below the tube because the interpretation of Pascal's law which says pressure is same everywhere in a static liquid holds only under zero gravity condition unlike the case of a venturimeter.But if we interpret Pascal's law as given in Encyclopaedia Brittanica which says " a pressure change in one part is transmitted without loss to every portion of the fluid and to the walls of the container " then Pascal's Law will hold under all situations but it has nothing to do with our current derivation. So we cannot say that this relation is derived from Pascal's Law.
For any liquid column at rest the pressure at a depth h is h$\rho$g. Here the liquid in the pipe may be moving but the liquid in the connected manometer( which is the u tube connected to pipe) is at rest.So here this formula is applicable.For a more elaborate explanation:
Here the liquid in the U column is at rest while the liquid in the pipe is moving.So the net force on the liquid in the column is zero .This liquid faces a downward force due to P$_2$ which is equal to P$_2 A$ and an upward force due to P$_1$ equal to P$_1$A as shown in the picture .Now the net resultant of these two must equal the weight of the liquid column. If the length of the column is d and density id $\rho$ the weight is Volume$\times$density$\times$g i.e dA$\rho$g.
So $$ P_1A - P_2A = dA\rho g$$ or
$$P_1 - P_2 = d\rho g$$ or
$$ P_1 = P_2 + d\rho g$$
Let me know if this was helpful.
Mobius, with all due respect, I note the following: "d" is shown as the height of the water column (assuming light blue represents water) in the left leg of the manometer and it is also shown as the dimension of the throat of the venturi meter. In addition, no accounting is given of the difference in height of the mercury in the legs of the manometer (assuming that dark blue represents mercury). Since there are two different densities involved in these fluids, the equation $P_1=P_2 + d \rho g$ is quite ambiguous.
@Mรถbius, I completely agree that Pascal principle can be applied on the fluid below the tube, but my question is not about how to derive pressure differences inside a Venturimeter (as I am already aware of them), but rather it seems that the derivation that other people are applying seems to violate Pascal's Law.
In this sense, you are comparing pressures at two different heights which happen to have statis fluid between them. My problem is that other people seem to compare pressure P1 with pressure in the middle of the tube, since Bernoulli's Equation must be applied.
Well ,to apply Bernoulli we assume pressure is uniform at all points on a cross-section of the fluid so the pressure at the middle of the tube is same as the pressure near the opening of the manometer. As for your other doubt about pascal's law, I have edited my answer.
Let me know what you think of it
Ok @Mรถbius, I think it works for me!
Alexp9,
this isn't intended to be an answer, but I need more room than I can get in a comment. I looked at your link that was tied to "in this question" in your original post. In the part where the author derived the pressure across the manometer, he wrote the following:
"This pressure difference causes the fluid in U-tube connected at the narrow neck to rise in comparison to the other arm. The difference in height his seen as the pressure difference.
$P1โP2=ฯ_mgh$
...
where ฯm is the density of mercury and ฯ is the density of the liquid in the Venturimeter".
I did this EXACT experiment when studying for my B.S. in chemical engineering some years back. If the fluid flowing through the venturi is something like a gas with a very low density, the equation is correct. However, if the fluid flowing through the manometer is something like water, which has a relatively high density, a correction must be made whereby the difference in density between mercury and the flowing fluid is the correct value. This means that the equation should have read
$P1โP2=(ฯ_m - \rho _f)gh$
where $\rho _f$ can be ignored if it is much smaller than the density of mercury. For water flowing through the venturi, with a mercury manometer measuring the pressure difference, the density of the water cannot be ignored, so the rest of the derivation in your link is questionable.
Thanks for your time David. It is a missfortune that you quoted the part of the question I didn't want to discuss about. My choose of terminology does not help either. Please note that my P1 and P2 are his PA and PB, respectively. Just read the section "My derivation" in that post. Also, for clarity, I will made an update on this question in 12 hours, to avoid more confusion
@alexp9, note that the part of the question that I quoted is directly related to the picture and equation that you posted. Also note that in the picture that you posted, you should start measuring at the top of the left part of the manometer tube. Starting a measurement in a flowing stream and using that for a manometer calculation has never been done as far as I know.
@alexp9, based on your comment to Mobius, if you want to see a derivation for how to calculate the pressure difference across a venturi using a manometer, please post another question asking this exact thing. I (and no doubt others) already have a derivation for this measurement.
At the moment I don't need the derivation. I just wanted to know whether it was possible to apply a formula in a derivation. However, after some time thinking, I believe I have come to a conclusion, and it was thanks to your help. Thank you!
Sorry for my poor english. My native language is french.
Strictly speaking, you can only apply the result of statics (what you call "Pascal's principle") for the part of the fluid at rest.
For the moving part of the fluid, there is a theorem, applicable here, which indicates that, for a unidirectional non-viscous flow, the pressure varies as in static in a direction perpendicular to that of the flow. This theorem is easy to prove by projecting Euler's equation perpendicular to the flow.
Finally, it remains to prove the continuity of the pressure through the hole which serves as a junction between the fluid at rest and the fluid which flows. The proof of this point is not simple because it requires a close look at what is happening there.
| common-pile/stackexchange_filtered |
How can i access etherpad on local domain?
So i installed Etherpad-Lite on an (Ubuntu 20.04) VM on our server.
I also installed Nginx and set up the following vhost.
In my sites-available there are 2 entries: default and etherpad.conf
This is my etherpad.conf
upstream etherpad {
server localhost:9001;
keepalive 32;
}
server {
listen 80;
server_name example.etherpad.at;
location / {
client_max_body_size 50M;
proxy_set_header X-Real-IP $remote_addr;
proxy_http_version 1.1;
proxy_pass http://etherpad;
}
}
And this is my settings.json for Etherpad (ip set to <IP_ADDRESS>)
* IP and port which Etherpad should bind at.
*
* Binding to a Unix socket is also supported: just use an empty string for
* the ip, and put the full path to the socket in the port parameter.
*
* EXAMPLE USING UNIX SOCKET:
* "ip": "", // <-- has to be an empty string
* "port" : "/somepath/etherpad.socket", // <-- path to a Unix socket
*/
"ip": "<IP_ADDRESS>",
"port": 9001,
I've also added a DNS entry in my host file and in my Firewall, just for testing purpose.
But when i go to the domain or the IP, i get an "This website is not reachable.....right dns...proxy...)
Ultimate when i set the ip of etherpad to something else i always get:
Error: listen EADDRNOTAVAIL
What am i doing wrong?
So apparently i had everything configured right but only after a reinstallation it worked.
| common-pile/stackexchange_filtered |
Simple typescript example of "supplied parameters do not match call signature of target"
I'm learning Typescript and have been working on this example:
interface Thing {
a: number;
b: boolean;
c: string;
}
let obj = <Thing>{
a: 5,
b: true,
c: 'string that says string'
}
function x(someObj: Thing): string {
return someObj.c;
}
function func(someObj: Thing, x: () => string) {
return x(someObj);
}
console.log(func(obj, x))
I get the same error for both x(someObj), which in the return statement in the func function, and the x within the call to func in the last line.
This is the error:
Supplied parameters do not match call signature of target
However, if I take the compiled version and just paste it into the console it works by logging 'string that says string'.
var obj = {
a: 5,
b: true,
c: 'string that says string'
};
function x(someObj) {
return someObj.c;
}
function func(someObj, x) {
return x(someObj);
}
console.log(func(obj, x)); //string that says string
I'm using the compiler in the Typescript Playground:
https://www.typescriptlang.org/play/index.html
I have looked at other questions and answers on stackoverflow with this error but they seem to relate to more complicated Angular questions and I do not understand them.
Shouldn't it be: x: (someObj: Thing) => string? You have to match the signature of x which takes one argument of the interface Thing.
Oh yes, that works. Thank heaps. I guess I figured that since I had declared x's typings in it's own definition then I was done with it.
To expand upon your comment, to Andrew Li's (what should be) correct answer, you've actually locked yourself in a corner that you created, by OVER-TYPING.
It may look like you're being extra-safe, by explicitly typing all of the things, but you're actually providing extra space to let inconsistencies in.
Had func looked like:
function func (obj: Thing, x): string {
return x(obj);
}
it might have worked just fine (or complained about "NO IMPLICIT ANY") depending on your version and your settings.
What you did was to provide it a type which didn't match, because you just wanted to provide a throwaway to appease the system.
I don't mean to sound confrontational, or anything; we're all guilty of it. But needing to appease type systems makes us sloppy all the time.
I'd argue that the less painful way to look at it would be like this:
interface Transform<A, B> {
(x:A):B;
}
interface Thing {
a: number;
b: boolean;
c: string;
}
type ThingC = Transform<Thing, string>;
const x = (obj: Thing) => obj.c;
const func = (obj: Thing, x: ThingC) => x(obj);
const c = func({ a: +!0, b: !0, c: "I work fine." }, x);
If you were to load that up in VSCode, I'm sure you would be pleasantly surprised with the type information you get from it.
Types are really for the benefit of method signatures.
Feel free to add type information to consts, if you want tooling around them, of course:
const obj: Thing = { a: 1, b: true, c: "Yes" };
But that's not really where it's most beneficial; especially because even if obj had a different type, like OtherThing, it could still go into x or func if it also met the criteria of Thing, even if it has nothing to do with it, and knows nothing about it.
To make that an even more general case:
interface Transform<A, B> {
(x:A):B;
}
interface Apply<A, B> {
(x:A, f: Transform<A, B>):B;
}
interface Thing {
a: number;
b: boolean;
c: string;
}
const x: Transform<Thing, string> = obj => obj.c;
const f: Apply<Thing, string> = (obj, x) => x(obj);
const c = f({ a: 1, b: true, c: "" }, x);
It's going to yell at you if you make any type mistakes, and still, you're calling functions with literals that are still being rigorously type-checked.
Want something zany?
const g = <A, B>(o: A, x: Transform<A, B>):B => x(o);
const d = g({ a: 1, b: true, c: "" }, x);
You didn't tell g ANYTHING about what types it was dealing with. It's an anonymous function, with anonymous types, which is handed a transform.
It still knows what type is getting returned into d, and it still knows that o is a Thing (regardless of what class it is or what interface it has). It knows this, because it pulled those types from x and worked backward.
So now you have:
interface Transform<A, B> { (x:A):B; }
interface Thing { a: number; b: boolean; c: string; }
const x = (obj: Thing) =>
obj.c;
const g = <A, B>(o: A, x: Transform<A, B>):B =>
x(o);
const d = g({ a: 1, b: true, c: "" }, x);
And it still gets d right.
Using types like this might seem counter-intuitive to you, but you can actually be doing yourself big favours, in terms of correctness, by leaning on the strengths of type inference, rather than leaning on manually making the type-system happy with extra noise that might conflict with what it thinks it should have.
Wow, this is a great answer Norguard. Thank you for putting so much work into it.
I have marked it as correct but because of my lack of reputation points my up vote is not visible. Also, I really appreciate how you've done this with arrow functions. And, yes this works really well!
| common-pile/stackexchange_filtered |
Converting NSString to NSDate adds one year in some cases
I have some issues converting an NSString to NSDate since the end of the year. The code have always worked great before, but it suddenly started to behave wierd...
For example 2013-01-05 becomes 2014-01-05 when converted to NSDate.
Since it's a whole year it doesn't feel like it's the timezone spooking.
It's not doing this with dates from 2012.
Does anybody have an idea of what might be wrong?
Code:
NSString *dateString = postInfo.noteDate;
NSString *newDateString = [dateString substringToIndex:10];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYY-MM-dd"];
NSDate *date = [[NSDate alloc] init];
date = [dateFormat dateFromString:newDateString];
newDateString returns 2013-01-05
date returns 2014-01-05
From the docs:
Y 1..n 1997 Year (in "Week of Year" based calendars). Normally the length specifies the padding, but for two letters it also specifies the maximum length. This year designation is used in ISO year-week calendar as defined by ISO 8601, but can be used in non-Gregorian based calendar systems where week date processing is desired. May not always be the same value as calendar year.
y 1..n 1996 Year. Normally the length specifies the padding, but for two letters it also specifies the maximum length.
So you want 'yyyy'
This 'bug' is also discussed in the fantastic WWDC 2011 Video "Session 117 - Performing Calendar Calculations", a must-see for any iOS/Cocoa-Developer.
Wikipedia article on ISO 8601
NSDate *date = [[NSDate alloc] init];
date = [dateFormat dateFromString:newDateString];
You create a NSDate and than you create another and overwrite the first one. Just do
NSDate *date = [dateFormat dateFromString:newDateString];
make sure you watch the linked video. They are explaining some more gotchas that you might run into. (i.e. You are deleting the time component. this can โ but not must โ lead to trouble)
Yeah, thought the same, when I heard this bug should disappear at 7th
Use yyyy in small letters, YYYY is another thing:
Year (in "Week of Year" based calendars). This year designation is used in ISO year-week calendar as defined by ISO 8601, but can be used in non-Gregorian based calendar systems where week date processing is desired. May not always be the same value as calendar year.
see http://www.unicode.org/reports/tr35/tr35-19.html#Date_Format_Patterns
Thanks all for the effort to answer, unfortunately I can't check you all... :/
use yyyy for year not YYYY, which gives week year. see the ISO standard.
Thanks all for the effort to answer, unfortunately I can't check you all... :/
you are welcome. vikingosegundo answer covers the details rather well with excellent references. cheers.
I hope this will helps u. Try this
- (NSDate*) dateFromString:(NSString*)aStr
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];
[dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm:ss a"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSLog(@"%@", aStr);
NSDate *aDate = [dateFormatter dateFromString:aStr];
[dateFormatter release];
return aDate;
}
| common-pile/stackexchange_filtered |
Is it possible to log function(cities) return value to console in JavaScript for testing whether the output is correct?
I am busy with a challenge and I know the code is correct as it passes the assignment but I'm having a tough time testing the out put.
<code>
function nonMutatingSplice(cities) {
// Only change code below this line
return cities.slice(0, 3);
// Only change code above this line
}
console.log(cities)
const inputCities = ["Chicago", "Delhi", "Islamabad"]
nonMutatingSplice(inputCities);
</code>
When I initiate the console log() call, the output to the console returns "ReferenceError: cities is not defined"
How can I console log the return value of the function to return the correct mutated array's values?
I am expecting to see the following in the console to validate that the code is returning the correct output:
["Chicago", "Delhi", "Islamabad"]
Assign the result of nonMutatingSplice() to a variable and log that. You'll probably need it in a variable anyway assuming you actually use the result somewhere.
Hi there could I please ask for an example?
What's the point of nonMutatingSplice() given that it doesn't emulate the splice() function at all, and always returns a predefined subset of the input Array? This isn't meant as a criticism, but I'm trying to preempt subsequent questions in which you might need to insert new Array elements, or delete elements, at particular indices.
You need to log the output from nonMutatingSplice
cities is never defined, because you don't allocate a value to the variable.
You can do it by using the following code.
const cities = nonMutatingSplice(inputCities);
Here's the code with a working output.
function nonMutatingSplice(cities) {
return cities.slice(0, 3);
}
const inputCities = ["Chicago", "Delhi", "Islamabad"]
console.log(nonMutatingSplice(inputCities))
non-mutable example:
function nonMutatingSplice(cities) {
return cities.slice(0, 2);
}
const inputCities = ["Chicago", "Delhi", "Islamabad"]
const cities = nonMutatingSplice(inputCities);
console.log(cities) //[ 'Chicago', 'Delhi' ]
console.log(inputCities) //[ 'Chicago', 'Delhi', 'Islamabad' ]
I get that but now doesn't that mean I am mutating the original array?
Here's the assignment below:
Rewrite the function nonMutatingSplice by using slice instead of splice. It should limit the provided cities array to a length of 3, and return a new array with only the first three items.
Do not mutate the original array provided to the function.
No, that will not mutate the original array since we are returning a value. I have edited my answer to include an example.
It's a little confusing as the original array provided is:
const inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
nonMutatingSplice(inputCities);
| common-pile/stackexchange_filtered |
Liferay Grails portlet taglib issue
I am using Liferay 6.0.6 and have successfully created a test portlet using the Grails Liferay Portlets Plugin. I am now trying to use some of the Liferay taglibs so my portlet will have the same look and feel as other portlets. My problem now is I can't get any of the liferay-ui controls to render. Should I be able to use the Liferay taglibs from Grails? I have inspected the war file for my portlet and all the Liferay taglibs and jar files seem to be in the right places. Can someone point me in the right direction?
| common-pile/stackexchange_filtered |
How do I detect a Faraday bag?
How do I detect a Faraday bag coming into or leaving my store?
The intention of detecting Faraday bags is to be aware of customers who have the ability to walk out of the store with an RFID-tagged product that hasn't been paid for.
Have all bags pass through a magnetic field... But you might loose a few customers... with pacemakers...
@solarmike what do you mean by "loose"?
@user263983 Like a catapult, or archery...LOOSE! lol. I think he misspelled "lose".
Aren't most anti theft tags magnetic rather than RF?
@user1850479 Some are RF resonant, some are actually powered by the scanner and communicate, some are RFID. There's been many designs over the years. In the early years, Best Buy had one that you could actually see the coil (inductor) on in their DVD cases.
You could put a box prominently labeled "Faraday Bag Detector" with flashing LEDs by the exit and observe any suspicious behavior on the part of customers.
Arent the 58 kHz magnetostrictive shopping tags too low in frequency to be blocked by any such bag in the first place?
I think this is a good theory question, even if the implementation of it is not necessarily something that may be achieved by a simple Q&A.
OP asked specifically about RFID, which uses higher frequencies than old-school Sensormatic tags.
@SpehroPefhany Not by the exit ... but at the entrance!
With a clearly readable warning at the entrance, use a "big" EMP at the frequency of the RFID tag which would "burn" everything inside ... <<< Make "open" ALL bags before the exit, please >>> :-)
Lots of people carry shielded wallets for their credit cards, etc. -- all perfectly legitimate. Do you plan to stop all of them?
@Dave Tweed yes, thatโs an important point. I made note of that - you as a shop owner only have the right to detain anyone if certain โprobable causeโ is met - eyewitness, surveillance, etc - as defined by local law. Detecting a Faraday bag isnโt by itself probable cause; and thereโs plenty of legit reasons to want to use one.
Let me re-phrase: Is RFID a must or is 58 kHz magnetostrictive tags an option for you?
First, the problem/challenge. The Faraday bag suppresses RF energy in both directions: RF to the tag, which energizes it, and RF return from the tag.
A classic conductive Faraday cage works by distributing RF energy across its surface, cancelling any effect on the interior. These may be grounded (like a shield room) to shunt energy away, or ungrounded, relying only on distribution of charge and skin effect.
More about Faraday cages here: https://nationalmaglab.org/about/around-the-lab/what-the/faraday-cage
In practice, a shield bag won't be a Faraday cage, but instead will be made of a lossy, absorptive material which converts RF to heat.
Example: https://slnt.com/products/faraday-bag
Anyway, I suppose you could sniff out such a lossy bag by measuring the overall return signal with a beam aimed at bag-height. If you see a dip in this signal compared to a person walking through without such a bag, then you might have something to act upon, assuming you have other evidence (such as surveillance footage showing them placing the item in the bag) that would legally entitle you to stop them.
Faraday cage doesn't need to be grounded in order to shield what is inside of it.
What @Aaron said -- a grounded Faraday cage is nice, but one that's free-floating in space should still isolate the inside. That's not saying that what's out there isn't made of lossy material.
| common-pile/stackexchange_filtered |
i want to count sum of specific IDs
My votes table looks like in my database;
ID CandidateID
1 205
2 209
3 203
4 205
5 205
6 209
Code:
<?php $votes_query=mysql_query("select * from votes where CandidateID='$id'");
$vote_count=mysql_num_rows($votes_query);
echo $vote_count;
?>
The above code gives individual results like, CandidateID 205 =3 votes, CandidateID 209=2 votes
What code can sum these votes in the table to be like,candidateID 205 + CandidateID 209 = 3+2=5 ?
use select sum(votes) from votes where CandidateID='$id'
sum
if you have multiple candidate_id then use in clause...select sum(votes) from votes where CandidateID in ($id)
thanks a million man..it worked..you saved my work ..really appreciate all your responses....#1stackoverflow
To Get all candidate vote count candidate-wise:
<?php
$rs = mysql_query("select CandidateID, count(*) as vote_count from votes group by CandidateID");
while(mysql_fetch_array($rs)){
$CandidateID = $rs['CandidateID'];
$vote_count = $rs['vote_count'];
echo $CandidateID . " " . $vote_count;
}
?>
To Get Vote Count of all selected candidates
<?php
$rs=mysql_fetch_array(mysql_query("select count(*) as vote_count from votes where CandidateID in ($id)")); // where look like as $id = "'205','209'";
$vote_count=$rs['vote_count'];
echo $vote_count;
?>
select * from votes where CandidateID in (1,5,7);
You can get sum of all the votes using following query:
select count(*) count from votes;
The above query can give you the total count of votes.
If you want count of individual vote from a query, you can use following query:
select CandidateID, count(*) count from votes group by CandidateID;
You need to use the COUNT aggregate function:
select count(*) as count_votes
from votes
where CandidateID='$id'");
And be sure to use a better database approach than mysql functions. You should use, at least, mysqli functions, as they are more robust against SQL injection.
| common-pile/stackexchange_filtered |
Compare only part of two of three items in triple
I have a list that goes something like this, and new content is added in a loop.
list = [("banana", "a", 0), ("banana", "b", 1), ("coconut", "a", 2)]
In the loop I want to add items like so:
list.append(("strawberry", "b", 4))
however, this cannot occur if the first and second item in that sequence is already in the list together. For instance, the following list cannot be added to list because the first item already contains "banana" together with "a".
("banana", "a", 5) # Should NOT be appended
("banana", "c", 6) # SHOULD be appended
("strawberry", "a", 7) # SHOULD be appended
In a regular list we'd do something like the following to avoid duplicates:
if not item in list:
list.append(item)
but note that my case does only involve partial duplicate, i.e. the first two items cannot be identical between sublists.
I am looking for a very efficient solution because the list can contain thousands of items.
I think you actually want to list.append(("strawberry", "b", 4)) (better) or list.extend([("strawberry", "b", 4)]) instead of list.extend(("strawberry", "b", 4))
@janbrohl You are right! Edited.
I would highly recommend using a dictionary for this type of data coupling structure, along with O(1) look-up times, you'll also be implementing better design. However, you could do this with your current data structure using the following:
Sample output:
With current structure:
l = [ ("banana", "a", 0), ("banana", "b", 1), ("coconut", "a", 2) ]
items_to_add = [("banana", "a", 5), ("banana", "c", 6), ("strawberry", "a", 7)]
for item_to_add in items_to_add:
if not item_to_add[:2] in [i[:2] for i in l]:
l.append(item_to_add)
print l
>>> [('banana', 'a', 0), ('banana', 'b', 1), ('coconut', 'a', 2),
('banana', 'c', 6), ('strawberry', 'a', 7)]
Other wise, you can use a dictionary (factor out your two first elements to be your key):
With dictionary:
d = { ("banana", "a") : 0, ("banana", "b") : 1, ("coconut", "a") : 2 }
items_to_add = [("banana", "a", 5), ("banana", "c", 6), ("strawberry", "a", 7)]
for item_to_add in items_to_add:
key = item_to_add[:2]
value = item_to_add[-1]
if not key in d:
d[key] = value
print d
>>> {('coconut', 'a'): 2, ('strawberry', 'a'): 7, ('banana', 'c'): 6,
('banana', 'a'): 0, ('banana', 'b'): 1}
A dictionary works very well in this scenario as you're trying to leverage properties of key/value data structure. Unique keys are ensured, and this will be the most efficient route as well.
You can use tuples as keys in a dictionary:
fruits = {
('banana', 'a'): 0,
('banana', 'b'): 1,
('coconut', 'a'): 2,
}
Then, you can just check if (item[0], item[1]) is already in the dictionary:
item = ('strawberry', 'b', 4)
if (item[0], item[1]) not in fruits:
fruits[item[0], item[1]] = item[2]
If you want to preserve order, you can use OrderedDict instead of the built-in dictionary.
This avoids using more memory to store a set of keys and is also efficient regarding lookup.
And how could I efficiently compare the keys from a new item with all the keys from the list? (I am not proficient in Python...)
you may check the presence of an new item with
#check for every item if newItem matches an Item in the list
if not any( True for item in list if newItem[:2]==item[:2] ):
# add your newItem
data = [("banana", "a", 0), ("banana", "b", 1), ("coconut", "a", 2)]
items = [("banana", "a", 5), ("banana", "c", 6), ("strawberry", "a", 7)]
for item in items:
if item[:2] not in map(lambda x: x[:2], data):
data.append(item)
Output:
[('banana', 'a', 0),
('banana', 'b', 1),
('coconut', 'a', 2),
('banana', 'c', 6),
('strawberry', 'a', 7)]
A time-efficient solution would be to keep a set with added items
li = [("banana", "a", 0), ("banana", "b", 1), ("coconut", "a", 2)]
se= set(t[:2] for t in li)
add=[
("banana", "a", 5), # Should NOT be appended
("banana", "c", 6), # SHOULD be appended
("strawberry", "a", 7) # SHOULD be appended
]
for t in add:
ct=t[:2]
if ct not in se:
li.append(t)
se.add(ct)
after that, li is [('banana', 'a', 0), ('banana', 'b', 1), ('coconut', 'a', 2), ('banana', 'c', 6), ('strawberry', 'a', 7)]
| common-pile/stackexchange_filtered |
Probability Question: Who's right, me or the book?
I'll be giving some classes on probability theory later this year, and so I've been going through the textbook to check that I'm up to speed. I came across the following question:
The discrete random variable $X$ has the cumulative distribution function $\mathrm{F}$ defined by
$$\mathrm{F}(x) = \left\{ \begin{array}{ccc} 0 & & x=0 \\
\frac{(x+k)^2}{16} & & x=1,2,3 \\
1 & & x > 3 \end{array}\right.$$
Find the value of $k$.
As far as I can tell, there isn't enough information to solve the problem. Using the fact that $\mathrm{F}(x) = \mathrm{P}(X\le x)$, and so $\mathrm{P}(X=x)=\mathrm{F}(x)-\mathrm{F}(x-1)$, I have obtained
$$\begin{eqnarray*}
P(X=0) &=& 0 \\ \\
P(X=1) &=& \tfrac{1}{16}(1+k)^2 \\ \\
P(X=2) &=& \tfrac{1}{16}(3+2k) \\ \\
P(X=3) &=& \tfrac{1}{16}(5+2k) \\ \\
P(X=4) &=& \tfrac{1}{16}(1-k)(7+k) \\ \\
P(X \ge 5) &=& 0
\end{eqnarray*}$$
As far as I can tell, these satisfy $\mathrm{F}(x)=\mathrm{P}(X \le x)$ for all $x \in \mathbb{N}$, independently of $k$.
Since all probabilities must lies between $0$ and $1$, I imposed the conditions $0 \le \mathrm{P}(X=x) \le 1$ for all $x \in \mathbb{N}$. Solving these inequalities tells us that $-\frac{3}{2} \le k \le 1$.
The books says that $k=1$ is the answer, but I think that $k$ with $-\frac{3}{2} \le k \le 1$ are all valid answers.
What have I missed?!
By continuity from the right, $\Pr(X\le 3)=1$. The book is right. They were a bit sloppy about making clear that the cdf is defined everywhere.
@AndrรฉNicolas Please post "answers" as answers. That way I can up-vote.
It's very simple: (i) A c.d.f. has to be right-continuous. Therefore, (ii) $F(3)=1$. Therefore, (iii) $(k+3)^2=16$.
@FlybyNight: Are you sure you copied the question faithfully? Instead of "defined by", the question should say "which satisfies". Because the so-called definition leaves the values of $F(x)$ unspecified for non-integral values in $(0,3)$. (The answer to the question is not affected by this, however.)
I do not know whether the book defines the cdf properly, as being defined for all real $x$. If it does, then what we have is only a partial description of the cdf.
However, the description is sufficient to determine $k$.
A cdf is continuous from the right, so from $F(x)=1$ for $x\gt 3$ we can conclude that $F(3)=1$. The formula for $F(3)$ then shows that $(3+k)^2=16$. That yields $k=1$ or $k=-7$. However, $k=-7$ is impossible. For if $k=-7$ then $F(1)\gt 1$.
It just says that $\mathrm{F}(x) = \mathrm{P}(X\le x)$. Having said that, it makes reference to $\mathrm{F}(2.6)$ and says "$\mathrm{F}(2.6)$ means $\mathrm{P}(X\le 2.6)$ but $X$ doesn't take any values between $2$ and $3$ so $X \le 2.6$ is the same as $X \le 2$ and thus $\mathrm{F}(2.6) = \mathrm{F}(2)$."
Surely $F(n) = \sum_{k=0}^n p { k }$? with $F$ being a right-continuous step function on non-integral values of the parameter?
From the fact that it discusses $F(2.6)$, one concludes it defines the cdf properly.
@AndrรฉNicolas Not really; I have given you all that it says. That's a pretty lousy definition. If it were defined properly then I wouldn't be making this post! I'm still unsure that all of the probabilities listed in my OP don't meet the criteria of the question, and the book.
@FlybyNight I think right continuity is sufficient to weed out other values of $k$. No?
I don't see where continuity enters into this. The formula $F$ defines the cdf for values $0,1,2,3$. Since it is discrete, it seems reasonable to assume that $F$ is constant (and right-continuous) for values other than $0,1,2,3$? I would concur that $k \in [-1.5,1]$ will define a valid cdf. (again assuming that $F$ is extended to other values in the usual way).
I see the ambiguity (or my misinterpretation). The question is does $x>3$ above mean $(3,\infty)$ or ${4,5,6,...}$.
We are told explicitly that $F(x)=1$ for $x\gt 3$. I take that at face-value.
@copper.hat: I don't see any ambiguity here. $x > 3$ means $x \in (3,\infty)$ unless we are told otherwise.
Yes, I see. It was my misinterpretation. I interpreted it as $k>3$ and integral.
Well, the question was about a discrete random variable, so it is not entirely unreasonable.
@copper.hat: The c.d.f. of a discrete random variable is defined on the whole of $\mathbb R$.
@TonyK: If you read the comments you will see my line of reasoning.
Yes, OK, if by "line of reasoning" you mean "thought processes" :-) But the question is not perfectly posed $-$ see my second comment to the OP.
@TonyK: I apologise for my snippy response earlier.
| common-pile/stackexchange_filtered |
Steps and involvement of implementing a parser (in .Net - and in this case XPath 2.0)
In the lack of any good free XPath 2.0 implementations for .Net build upon Linq to XML I have thought about implementing my own (also for the experience). But just to be clear (and not building something that exists) these are the XPath 2.0 implementations I have found:
Saxon .Net
Query Machine - I had problems with this - exceptions with the examples
XQSharp - may be good, but is commercial (single developer ~300 $)
Now, I want some thoughts on how difficult it is to implementing some language such as XPath 2.0 expressions. I have found this link which have a EBNF for XPath 2.0 expression: http://www.w3.org/TR/2007/REC-xpath20-20070123/#id-grammar and I'm thinking of making it in F# with the fslex/fsyacc combination.
My background (subjective): I have played with these tools before, but only for some simple expressions and a very simple programming language. Furthermore, I have read most of the Dragon book and Appelยดs Modern compiler implementation in ML - but unfortunately, I have not put the theory in practice while reading. I've studied computer science in a year now where I have completed courses with theory about ex finite automaton, CFL and algorithms but I have been a developer for years before university (a few years with professional jobs - back-end of websites mainly).
Now, the steps of parsing and what I tend to cover:
Lex - Parsing - Reductions: FsLex/FsYacc. I will properly not cover ALL of Xpath 2.0 at first but at least all of what XPath 1.0 can do + a little more.
Sematic analysis - I'm not sure about how much there is to this
Optimization - I do not tend to cover this (at least not at first)
Actual traversing etc.
...?
Now, the concrete questions in addition to the above:
How difficult is it to make a parser of this size? based on my background, would I could to it?
Is there any crucial steps I have missed in regards to XPath 2.0 in particular?
Is there any technology I have missed; Do I have to cover more than just XPath 2.0 and XDocument etc. to be able to make the parser?
To be clear: I want to make a XPath 2.0 expression parser and traverse XDocument etc. with this parsed expression. Which I guess combined is a query engine.
Update: I found this: http://www.w3.org/2007/01/applets/xpathApplet.html which contains code to parsing and traversing. I think it would be a nice start or reference :-)
Your answers will be appreciated.
I dont really understand your question. XPath is a query language. It needs no parser, it needs an existing well-formed XML document with schema. The XML schema is what determines the structure of the XML, so in effect, that would be your 'yacc' for XML. That said, .NET all supports this. I see no need to re-invent the wheel here.
@leppie I may not have been clear in my use of terms. I want to parse //pf:*[@name='some']/@* so it is a XPath 2.0 expression parser I want to make.
@lasseespeholt: But why? Is The XPath 2 query engine (which I believe are compiled queries) not working? Or do want to use your little 'dsl' qeuries?
@leppie What XPath 2.0 query engine in .Net? I want to make an alternative to Saxon .Net for XPath 2.0. I do not understand exactly what you mean, please enlightened me ;-)
@lasseespeholt: http://msdn.microsoft.com/en-us/library/system.xml.xpath.aspx
@leppie XPathExpression.Compile only supports XPath 1.0. And I think they only supports the XPath 2.0 data model and not the parsing and traversing itself.
@lasseespeholt: Where do you see that? From what I can see, it supports XPath 2.0 and XQuery 1.0.
@leippe http://msdn.microsoft.com/en-us/library/ms163317.aspx look at return types under Remarks. It only returns nodeset, bool, string or number.
@lasseespeholt: I see. If I may ask, what else do you need?
@leppie Basically, all the functions here is relevant: http://www.w3schools.com/xpath/xpath_functions.asp (for building a testsuite)
@lasseespeholt: You are saying a lot of those cant be called from an XPath expression? I am just interested :)
@leppie I believe so, yes. At least not from a XPath 1.0 expression.
@lasseespeholt: The XQSharp page says: "XQSharp is free for non-commercial use"
@lasseespeholt: Good question (+1). See my answer for a shared experience.
@leppie: At present there is no Microsoft XPath 2.0 engine. SQL Server supports a limited (as per earlier working draft) subset of the XQuery, but this is not a full W3C XPath 2.0 Recommendation - compliant implementation.
@leppie Yes, I have noted the 'free' version. It might be okay for my project but nevertheless I will keep the question open because it interests me. And a version where I have the source AND not have to update my .dllยดs every half year (you have to with the trial) would be nice for me. And also the challenge would be nice - unless it is way to complicated.
I implemented an XPath 2.0 parser entirely in XSLT 2.0 three years ago.
I used my LR Parsing Framework in FXSL and this was not so difficult. The grammar is quite big -- 209 rules, if I remember well. I used a modificationn of YACC (done by me) which I call Yaccx to generate the parsing tables as XML. These are the input for the general LR Parser, written in XSLT.
For such kind of project you need to allocate at least 6 months full time, maybe 1 year. The difficulty is in implementing the enormous function library (F & O).
Also, XPath is not a standalone language -- it must be hosted by another language. Due to this reason I didn't use this parser for anything meaningful, as I didn't have the access, influence and possibility to alter an existing hosting language.
So, be prepared for all these difficulties.
+1 The work you have done sounds very interesting. May I ask why you used your own yacc and parseing framework and not just other implementations? I don't have 6 months full time :/ I guess I have a few hours each day but I'm studying currently. Also, the last point seems very rational, my initial usage of this was to make a online xpath tester but if it can't be used to anything besides that and others ain't requesting it it might be waste of time.
@lasseespeholt: This is not my own YACC. This is Berkley YACC, only slightly modified to output the parsing tables in XML format. Normally it outputs the parsing tables as C arrays. As for an XPath 2.0 Visualizer, I developed such four years ago and am considering publishing it.
I am one of the developers of XQSharp, so I have experience in this area. XQSharp actually began its life as an XPath implementation before we expanded it to support XQuery.
Our initial implementation took us about 6 months, although this was not the only thing we were working on at the time.
After this time we had an implementation that was feature complete. There were many areas in which this was not fully conformant, where the standard .NET methods did not behave quite the same as the specification required. Some examples of this are with converting values to and from strings, regular expressions, a lot of unicode stuff, problems with the .NET representations of XML (eg handling of xml:base) and so on.
There were several areas that needed to be done to implement this:
Parsing:
The parser itself was straightforward, and mostly generated from the EBNF in the spec. I would estimate that this initially represented a few weeks work.
Data Model:
How the data is represented. In order to have a full XPath implementation there are a lot of new data types (like xs:gDay) that need to be implemented. In our case we have all our items derive from a base type and all our expressions would return enumerators of these. You also need to be able to identify whether the type of an item matches a particular XPath type. We supported static typing and schema-awareness from the outset, without these features this section probably becomes trivial, but you are still looking at several weeks worth of work.
Expressions/Abstract Syntax Tree
This is the model of the expression itself. We used the XQuery Formal Semantics document to produce a mapping from the various XPath constructs (for example axes and predicates) to a simpler core grammer (which ends up with huge amounts of let, for if and typeswitch expressions!). In our initial implementation all these expressions had evaluate methods and so were the final representation of the expression. In our case the expressions all had type check methods too, but this can be skipped initially (The main purpose of these is for optimization). Creating all these expressions again took several weeks.
Functions
As a previous commenter pointed out the function library for XPath is rather large. The entire XPath library took us several months to implement.
Static Analysis
A small amount of static analysis is required. Variable references and function calls must be bound to the correct variables and functions. Most XPath implementations are stack based, and so a stack allocation phase is required to assign pointers (or indexes) to all the variables. This static analysis took a week or two. The Dragon Book should set you up very nicely to solve most of these problems.
You are probably looking at another month's worth of work for all the extra bits of work that do not fall directly into these categories.
After all this work we were left with a mostly functional implementation of XPath; but it was far to slow for real world use (maybe 100x slower than XPath 1 in .NET). So after this comes the fun work - Optimization.
Bringing the engine up to 100% conformance and adding optimizations probably took another 12-18 man months (although we probably went a little overboard with optimization!), but by that point we had already made the transition to being an XQuery implementation.
My advice would be to start by tackling a subset of XPath (maybe forward axes only and a very limited function library) and you might be able to knock together an implementation in a month or two, but a serious XPath2 implementation will be a big investment in time.
Make sure that you use XPathNavigator for your node representation, as it has methods like SelectChildren which can take advantages of indexes in the underlying representations (for example XPathDocument).
+1 I really appreciate you took the time to write about it :) It seems like a long journey. I did think it was a smaller project than that but I often do. Right now, I'll return to the studies and use XQuery for non-commercial stuff (at least for now). Thanks...
If I may add a little suggestion to XQuery, then I really think you guys should make your LINQ equivalent methods like XPathEvaluate, XPathSelect etc. behave just like the .Net XPath 1.0 version.
@lasseespeholt: I don't think we realised how big a journey this was when we started either! What differences are you referring to with the behaviour of the extension methods? If you could post this to our forum (http://www.xqsharp.com/forum) this would be greatly appreciated.
To address your third concrete question, the Dragon Book makes no mention of Parsing Expression Grammars (PEGs)/Packrat parsers/parser combinator libraries, which are quite the rage now, especially when it comes to functional languages. See FParsec, for example.
+1 I have never encountered PEGs (in class CFL and reg.) so I really appreciate your answer and will look into the tool :)
| common-pile/stackexchange_filtered |
jQuery getJSON callback function doesn't update the DOM until it finishes
I have a jQuery ui progressbar
var item = 4;
$('<div/>', { id: 'progressBar' + item, 'class': 'ui-widget-default flpb' }).appendTo($('#test'));
$('#progressBar' + item).progressbar({ value: 0 });
here the progressbar shows up on the page
then I do a ajax call like this
$.getJSON("http://" + jsonServiceUrl + "/data/for/" + item + "/from/" + $('#dtStart').val() + "/to/" + $('#dtEnd').val() + "?callback=?",
function (results) {
var pbScale = 100 / results.count,
startTime = new Date().getTime();
$.each(result, function (r, result) {
//here the progress bar doesn't update.
$('<div/>', { html: " Date: " + new Date(parseInt(result.TimeOfMeasurement.substr(6))) }).appendTo('#test');
$('#progressBar' + item).progressbar('value', r * pbScale);
});
console.debug('elapsed milisecs: ' + new Date().getTime() - startTime;
});
The progressbar gets updates to "100%" after the callback function finishes.
EDIT:
I'm not trying to get the progress of my json call, I'm trying to get the progress of looping through the collection of things I get back from the server. Next to updating the progress bar I also draw a div for every item in the collection. There are upto 200 items in the collection so there is progress enough to be shown.
Next to the progress bar not updating, the newly generated divs also don't show up until the callback function finishes.
I added the timer and the processing time is about 1000 miliseconds (which must be enough to update the progressbar a couple items).
Did you ever get this working? I'm having exactly the same issue.
Hmmm - http://code.google.com/p/chromium/issues/detail?id=45196
Appears it's a bug in webkit :(
No I never got this working. While javascript is busy it will not update the dom. And if you force the dom to update things get really slow.
Yeah, the bug is 3 years old so I'm guessing it's not going to be fixed any time soon. From what I can see I'll probably have to send the file via AJAX.
$.each is a synchronous call, which is equivalent to a for(;;;) loop. The iteration over your results is instantaneous, and whilst the progressbar will be updating in the background, it's too quick for you to notice.
You want to be showing the progress of your AJAX request, not your progress of iterating over the result set. Furthermore, because the $.each is synchronous, if it ever becomes large enough to warrant a progressbar for it, you'll have bigger problems to worry about; such as the unresponsiveness of your application until the iteration completes, than showing a progress bar.
I updated the question. I do show the progress of the ajax request with a barber-pole but I want to show how far it's along after that. there are quite a few of these requests per page :P
It appears modern browsers don't update the dom every time something changes they wait for a couple milliseconds before updating. If I force the update by calling the offset of an element things become V slow.
The Callback function only fires when the call is successful.
the 2 methods that can be used to get the solution you want would be:
partial calls,
have your server return only a chunk of the result, it will then fire the callback function, from within that callback fire a next ajax call to fetch the next chunk,
this would however result in a few ajax calls instead of one, but you can have your progressbar working.
second method would be to do something with sockets and stream your data from the server to your pc, I doubt you can do something like that with regular jquery, you will need at least some plugin for that, and your server side code will also need to support it.
for more info take a look at socket.io and
| common-pile/stackexchange_filtered |
How long time to travel distance? Teacher and I disagree?
This is the problem:
Assume that the maximum linear velocity and the maximum linear acceleration of the car are given by
$V_{max} = 2 m/s$ and $a_{max} = 3 m/s^2$, respectively. Assuming a trapezoidal velocity profile, find the minimum travelling
time for the trajectory for traveling 3m.
My reasoning:
I assume we do not have to end at a stand still, we therefore give full throttle for all distance.
First we need to accelerate:
The time taken to accelerate from 0 to 2 m/s when a=3 is $t=\frac{2}{3}s$. The distance this covers is $s=at^2=3(\frac{2}{3})^2=\frac{4}{3}m$. We therefore need to travel $3-\frac{4}{3}=1.66m$ at 2m/s which will take $\frac{1.66}{2}=0.8333$. Total time is therefore $0.8333+\frac{2}{3} = 1.5s$.
My teachers solution, I do not fully understand but he got 2.16s:
Am I thinking completely wrong? My method is pretty much what I learned in physics, but I do not understand why it would not work, or does my teacher have the wrong answer?
Whilst undergoing constant acceleration, $s\ne at^2$ but rather $s=\frac 12 at^2$
The problem is that the cited problem doesn't state what either initial or terminal velocity is. So, I'd answer the minimum travelling time is 1 second (assuming full speed before and after covering the 3 m). The rectangular velocity profile is also trapezoidal, just a special case.
Initial velocity is 0
The teacher's equations can be written as
$$
h=v_{max}t_f-v_{max}T_a,.
$$
Looks pretty weird. Apart from the factor $1/2$ you missed in $s=\frac{1}{2}at^2$ as pointed out by Farcher your solution is correct. You should get $1.8333$ seconds.
The requirement of a trapezoidal velocity profile eliminates the possibility of a full throttle acceleration for all distance. In my opinion, that velocity profile strongly implies that the car started from rest and ended at rest.
@KurtG. I managed to get 1.833s, thank you, I completely missed that error. However the teacher still get another result, are the teacher wrong?
@J.Doe . David White just made some important comment. Your velocity profile is a linear ly increasing one. Please discuss with your teacher if that's trapezoidal or not. It is a matter of clarifying that point. Nothing that PSE users could resolve I think. (To me your profile is trapezoidal and your solution correct. Perhaps for your teacher your profile is not trapezoidal.)
A velocity against time graph can sometimes provide a good overview of a problem.
I have done some research and found a lecture where the teacher goes through a similar example with the same formulas. The teachers answer is wrong, because he have completely ignored the distance the robot travels while accelerating. The teachers answer is basically: how long time to drive 3m at 2m/s + the time to accelerate to 2m/s without taking the distance during acceleration into account. Thank you for your help, and also the figure Farcher drew is correct. I am not sure if this question will help anyone else, but maybe the moral of the story should be that, even the teacher is a human, and humans make errors
| common-pile/stackexchange_filtered |
Understanding how a hardware RAID controller works
I am currently looking at a specific product:
https://www.amazon.com/gp/product/B004JPUZWU/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1
This is a hardware RAID controller and I just want to understand how to use it very well before actually implementing it and risking any data loss. So I will be using a RAID 10 setup. I see that I just put the dial to RAID 10 and press the change mode button to create the initial RAID. Once the RAID is going, if I take a drive out ever and have to replace it it seems I would press this button again and it should rebuild the RAID.
How does the controller know to copy the data over to the new drive as opposed to just building a new RAID setup and eliminating all of my data?
I did look at the documentation for this device but it doesn't appear to answer how this is done.
If something as fundamental as this isn't clear, do you really want to be risking your data with this product?
@djsmiley2k Well just because I don't understand the interface doesn't mean the product is poor in performance.
No, but I like products which I can understand, no matter how well they perform. A Ferrari who's steering wheel is back to front isn't much use to anyone.
But if you owned a bicycle that is easy to use but low in performance, and then learned to drive that Ferrari, you would be much better off in the long run with the Ferrari. I am doing as you state and making sure I understand and test the product before I use i
Per talking to someone from the company that makes this device, this seems to be how this particular RAID controller works:
Initial setup:
Plug in all drives, connections, and power (separate power supply) select RAID mode on dial, press Change Mode button.
This simply configures the mode so anything viewing will see the drives as one volume. Drives still need to be formatted to get a file system on the volume.
If a drive fails:
The buzzer onboard will beep and red LED on front will be solid indicating there is a drive failure. If leds are hooked up individually to each header for each drive, the specified LED will light up showing which drive has failed.
Power down unit and replace bad drive with new one.
Turn unit back on. Red light on front will now be blinking, rather than on solid. This indicates that the new drive is being written to and being rebuilt. No pressing of buttons or use of software needed.
Doing offsite backups with this unit:
Following the same procedure for if a drive fails, you can unplug a drive and store it in another location. The unit will see this as a missing drive.
Power unit off and install a new drive in place. Red light will be blinking indicating that the new drive is being written to, rebuilding the RAID.
I confirmed with the company and there is a small partition that exists on each drive when it is built that is hidden from the rest of the drive that contains the RAID volume. When the device sees a drive missing this section, and the data doesn't match what it is looking for, then it assumes that drive is new.
Different RAID Types with this device
The different RAID types are slightly different from their normal definitions for this device.
RAID 10
According to the company, the drives are not "paired" like in a traditional RAID 10 setup (where each pair would be a RAID 1 and then a RAID 0 layer on top of that). They are all "equal" drives. In this setup you can need 4 drives and 2 can fail at max and still allow data to be safe. It does not matter which 2 in combination. Capacity seen from the resulting RAID = about half of the total capacity of the drives put together.
RAID 5
So on the RAID 5 configurations, data is stored on a minimum of 3 drives (in theory can be an infinite maximum). For this particular unit, it was confirmed that each drive contains the parity and the data is striped across them all. In this configuration, you can lose one drive and still have your data backed up. It does not matter which drive is lost. Capacity = approximately 90% of the total capacity. The parity on a RAID 5 = about 10% of the total drive capacity.
RAID 3
Raid 3 stripes its data and has parity data like RAID 5. Instead of the parity scattered among the drives, it has one drive that contains the parity. This makes it a slower option in general than a RAID 5 or RAID 10 but still is an option for this unit. Raid 3 needs a minimum of 3 drives as well and will allow one drive failure with keeping data safe. Capacity on a RAID 3 is the total drive capacity of all of the drives minus the one being used for parity.
"Clone"
Clone on this device is the same thing as a RAID1
In a RAID 1 setup, every drive connected is a copy of the other. Since this unit supports 5 drives, you would have 5 times the redundancy. Your RAID storage space would = 1/5 of the total capacity. You could lose a maximum of 4 drives and still have your data backed up safely.
RAID 0
RAID 0 only does striping. This will improve performance as data read / writes are spread across multiple drives but no data is backed up. Minimum drives = 2. Maximum = unlimited. Data capacity = total drive capacity.
Large
On this device the "Large" mode will make all of the drives just show up by themselves as they are. In this mode the device just acts like a HUB and does no RAID at all.
I can not be 100% sure about this special controller - I don't know which chipset and firmware it uses, but most products of this making use the last sector(s) of the disk as a canary:
All valid: RAIDset is OK
one invalid: This is a new disk, so the sync source
none valid: New diskset
So, on pressing the button, the controller reads the canary sectors and reacts accordingly.
Yeah. Better ones will put a few "configuration records" on the HD, in various places - like beginning, middle, and end - for protection against damage.
I bet you are right on this. I can definitely test with dummy data before I put anything real on it to confirm
I am using a very similar device, the Lian-Li EX-503, with the same chip built-in a SMP393 by JMicron. In fact I use 6 of them great Hardware-RAID devices each configured as RAID5 for about 7 years already.
They have been serving me without any glitch ever (no BS!). Make sure to use Disks supporting TLER (=Time limited error control).
All other (software) RAIDs I tried required regular & cumbersome maintenance.
The only drawback (today) is that the available Interfaces USB 3.0 and eSATA became rather slow compared to todays transfer speeds for data.
Hence my question: Where & what are the Hardware RAIDs meeting todays transfer speeds?
| common-pile/stackexchange_filtered |
How to apply variable specific condition in query's WHERE clause in Stored Procedure
Please tell me what I am doing wrong in below procedure query
CREATE PROCEDURE `DB`.`getReportsTotal`(customerId int(11),reportType varchar(20))
BEGIN
SELECT
`table1`.`column1`,
`table2`.`column2`,
reportType as `reportType`
FROM table1
LEFT JOIN table2
ON table1.id = table2.table1_id
WHERE table2.customer_id = customerId
IF (reportType = "school")
AND `table1`.`column2` != "value";
END
I want, if reportType = "school" then only AND table1.column2 != "value"; this condition will apply. but this query giving mysql syntax error.
I also tried below query
CREATE PROCEDURE `DB`.`getReportsTotal`(customerId int(11),reportType varchar(20))
BEGIN
SELECT
`table1`.`column1`,
`table2`.`column2`,
reportType as `reportType`
FROM table1
LEFT JOIN table2
ON table1.id = table2.table1_id
IF (reportType = "school") WHERE table2.customer_id = customerId AND `table1`.`column2` != "value";
ELSE WHERE table2.customer_id = customerId ;
END
but getting the mysql error
Please help...
You cpuld use following logic.
if it is not school use "value"+1 so that the "value"+1 != "value" is always true
If it is school you check against the column2
SELECT
`table1`.`column1`,
`table2`.`column2`,
reportType as `reportType`
FROM table1
LEFT JOIN table2
ON table1.id = table2.table1_id
WHERE table2.customer_id = customerId AND
IF (reportType = "school",`table1`.`column2`,"value"+1) != "value";
| common-pile/stackexchange_filtered |
Validating IP address by regular expression - Unknown escape sequence
I am working on an iOS project that require using regular expression to validate ipv4 address.
I use following code
// only support ip4 currently
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:@"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
options:0
error:nil];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:IpString options:0 range:NSMakeRange(0, [IpString length])];
return (numberOfMatches==1?TRUE:FALSE);
XCode keep warning me "unknown escape sequence .". When return true when I type "1.3.6.-6" or "2.3.33".
How can I use dot(.) in regex? Thanks
You need to double backslash your ., as the first backslash is being interpreted by NSString, and it's looking for an escape character for . (which doesn't exist). Double backslashing (\\.) will cause the first backslash to escape the second backslash (which does exist), meaning you can use \ normally.
So for example, your regex will be:
@"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"
| common-pile/stackexchange_filtered |
How to add fragments to Navigation Drawer template in Android Studio
I've searched all over Google trying to find the answer but haven't been able to find an answer. I'm using the "Create Navigation Drawer Activity" template in Android Studio. How do I add my fragments to the Navigation Drawer?
Here's where I assume I add the fragments:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camara) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Based on tutorials I've seen, I've tried adding the following in the if statements with no success:
fragment = new ItemFragment();
Possible duplicate of Switch between Fragments with onNavigationItemSelected in new Navigation Drawer Activity template (Android Studio 1.4 onward)
@user3424545 this isn't a duplicate. I didn't see that one. I gave up on this question though. Didn't solve my problem. If I run into this issue again, I'll be sure to check that link. Thanks
| common-pile/stackexchange_filtered |
Break down ... ใซใฏใชใใชใ
The context of my question is the usage of a grammar point from a JLPT ๆๆณ textbook. It is not the grammar point itself that I am asking about, but rather the grammar used to explain the grammar point. Sorry for this complexity.
The textbook explains how to form sentences using the pattern ใใ๏ผใฎ๏ผใชใ...ใ:
ๆฎ้ๅฝข๏ผใๅฝข ใ ๏ผ-ใงใใใปๅ ใ ๏ผ-ใงใใ๏ผ๏ผ๏ผใฎ๏ผใชใ
ใๅฝข ใ ใๅ ใ ใฎๅ ดๅใฏใใฎใชใใใซใฏใชใใชใ
(Basically, the second line is saying that if ~ is a na-adjective or a noun, for instance ้จ, one can have ้จใชใ, or ้จใงใใใชใ, or ้จใงใใใฎใชใ, but NOT ้จใฎใชใ.)
My question is this. How to break down the ใซใฏใชใใชใ in bold font in the second line above? I think it could be one (or neither) of the following possibilities:
Is it just the negative of ...ใซใชใ, with ใฏ in ใซใฏใชใใชใ being there for emphasis? If so, what exactly does ใซใชใ mean in this context? To become? To be?
Alternatively, does ใชใใชใ here mean "must not"? If so, what exactly is the usage of ใซใฏ here?
Allow me to reveal the answer that it's #1, but what do you mean by "what exactly does ใซใชใ mean"? Does it become weird if you translate it with your suggested words?
@broccolifacemask-cloth Thank you very much for the answer. "X becomes Y" implies a change from "X wasn't Y" to "X is now Y". So I can understand it when ๅคงไบบใซใชใ is translated as "to become an adult". There is a change from being a child to being an adult. Ifใใฎใชใใใซใฏใชใใชใ is translated as "does not become ใฎใชใ", I would then wonder what it is that does not change. I suspect that "to become" does not exactly correspond to ใซใชใ, because generally there is no one-to-one correspondence between the vocabularies of two languages. To a Japanese speaker, is the ใซใชใ in ๅคงไบบใซใชใ similar to ใซใชใ in ใใฎใชใใใซใฏใชใใชใ?
| common-pile/stackexchange_filtered |
how to make my URL short using MOD Rewrite in a clustered apache tomcat environment
Here is my actual URL
http://www.getinfotowin.com/virtual/PageRouteone?actionName=best_television_Series&service=T&id=50&customerId=81&KeyId=1&IsVisible=N&service=Nothing
Expected short URL
http://www.getinfotowin.com/best_television_Series/T/50/81/1/N/Nothing
My MOD_REWRITE logic is as given below
RewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$
virtual/PageRouteone?actionName=$1&service=$2&id=$3&customerId=$4&KeyId=$5&IsVisible=$6&service=$7 [NC,L] # Process product requests
Our apache communicates with Tomcat using AJP protocal. I have tried the above given logic but it's not working.
In the actual URL "virtual" is my war file name and "PageRouteone" is my java servlet name.
I want to know whether or not my rewrite rule is correct. If not, what is it that's wrong?
Which mvc are you using?
below lines are what i get in my rewrite logs init rewrite engine with requested uri /virtual/PageRouteone
applying pattern '^([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$' to uri '/virtual/PageRouteone'
pass through /virtual/PageRouteone
@Stefoan we are using apache and tomcat servers in a clustered environment jsp is our view java class acts as model and controller
Even if you get this regex right, it's going to be slow and painful to maintain & debug (like if you need to add more parameters).
You might think about parsing that URL server side. For instance, you could set up a Servlet Filter to split the URL and set each section as a request parameter.
@tina Your rule simply not accept underscores. See my answer for details.
You anchor your pattern to the beginning of the string (the URI path), but the start of the pattern does not match the '/' character that will always start the URI path. This pattern would probably work better:
^/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/([A-Za-z0-9-]+)/?$
Since you are using the NC option for case-insensitive matching, you should be able to reduce that to:
^/([a-z0-9-]+)/([a-z0-9-]+)/([a-z0-9-]+)/([a-z0-9-]+)/([a-z0-9-]+)/([a-z0-9-]+)/([a-z0-9-]+)/?$
You could even consider simplifying it to this (in which case NC will no longer be relevant):
^/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$
That will pick out each path segment regardless of the characters in it, leaving validation of the parameters to your application.
In any case, you may need to use the PT (passthrough) option to get AJP to claim the rewritten URL (but test, because it's more efficient to not passthrough).
Sources: Apache HTTPD 2.4 documentation, specifically http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewriterule (specifying that the (first) rule matches against URI(URL) path, and documenting the RewriteRule options), and http://httpd.apache.org/docs/current/mod/directive-dict.html#Syntax (defining URL path).
I think your RewriteRule is almost correct, but I would remove the last question mark and the last slash. Make sure that the RewriteEngine is on.
RewriteEngine On
RewriteBase /
Options -MultiViews
RewriteRule ^([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)$ virtual/PageRouteoneactionName=$1&service=$2&id=$3&customerId=$4&KeyId=$5&IsVisible=$6&service=$7 [NC,L]
In your code use your provided URL:
http://www.getinfotowin.com/best_television_Series/T/50/81/1/N/Nothing
NOTE: URLs with a slash will not work. You have to define another rule for that.
If you want that URLs with a trailing slash are also working, you have to add following lines:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} (.*)$
RewriteRule ^(.+)/$ http://www.domain.com/$1 [R=301,L]
Solution:
Your URL contains underscores (_), which are not accepted by your pattern [A-Za-z0-9-]+.
Change it for [\w-]+ (which is equal to [A-Za-z0-9_-]+).
Here is your final rule :
RewriteRule
^([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/([\w-]+)/?$
virtual/PageRouteone?actionName=$1&service=$2&id=$3&customerId=$4&KeyId=$5&IsVisible=$6&service=$7
[NC,L] # Process product requests
Side note:
It should be obvious, but I suspect a misunderstanding : you must use the short URL everywhere, this rule will redirect the short (virtual) URL to the servlet with some parameters, but don't expect it to shorten your URL automatically.
I wanted to clarify this point because this is your first mod-rewrite question, and many people on SO think this module is here to beautify the (full) URLs they've used everywhere.
| common-pile/stackexchange_filtered |
How to fill part of a link after the slash with a value from an array
I want to create a "dynamic" link in a page that changes according to a value from an array. Sort of a f-string in Pythonโฆ
So I have this variable with an array:
let movies = [
{
"originalTitle": "The Shawshank Redemption",
"director": "Frank Darabont",
"year": 1994,
"genre": "Drama",
"runtimeMinutes": 142,
"averageRating": 9.3
},
{
"originalTitle": "The Godfather",
"director": "Francis Ford Coppola",
"year": 1972,
"genre": "Crime",
"runtimeMinutes": 175,
"averageRating": 9.2
}
]
And I want in my HTML to "fill" the URL with the title of the movie. Changing this part domain.com/search?q=The%20Godfather where the "The Godfather" section could be another movie, like domain.com/search?q=The%20Shawshank%20Redemption
<p><a href="domain.com/search?q=The%20Godfather">Click here</a> to search where you can watch this movie.</p>
Keep in mind that I have a variable that selects which movie will be inserted already. I just need to know how to make this "dynamic" anchor tag and insert the movie inside that variable.
I know how to do this with .textContent with span tags in my HTML. But what I want to replace is inside the anchor tag. How can I achieve this?
You can use URLSearchParams API
const movies = [{
"originalTitle": "The Shawshank Redemption",
"director": "Frank Darabont",
"year": 1994,
"genre": "Drama",
"runtimeMinutes": 142,
"averageRating": 9.3
},
{
"originalTitle": "The Godfather",
"director": "Francis Ford Coppola",
"year": 1972,
"genre": "Crime",
"runtimeMinutes": 175,
"averageRating": 9.2
}
];
const anchor = document.querySelector('#anchor');
const searchParams = new URLSearchParams(window.location.search);
searchParams.set("?q", movies[0].originalTitle);
anchor.href += searchParams.toString();
console.log(anchor.href)
<p><a id="anchor" href="https://domaintest.com/">Click here</a> to search where you can watch this movie.</p>
You can get the anchor element with querySelector and then set the href attribute, try this:
let movies = [
{
"originalTitle": "The Shawshank Redemption",
"director": "Frank Darabont",
"year": 1994,
"genre": "Drama",
"runtimeMinutes": 142,
"averageRating": 9.3
},
{
"originalTitle": "The Godfather",
"director": "Francis Ford Coppola",
"year": 1972,
"genre": "Crime",
"runtimeMinutes": 175,
"averageRating": 9.2
}
];
let anchor = document.querySelector('#anchor');
anchor.href = `domain.com/${movies[0].originalTitle}`;
<a id="anchor">Click</a>
https://stackoverflow.com/help/how-to-answer
@ScottMarcus answer updated Scott
| common-pile/stackexchange_filtered |
Store Widgets in Dictionary
I would like to store my various checkboxes in a dictionary so that I can later call upon them. Since I would like to perform actions based on the number of widgets with len(self.il['Line2']) I need some way of storing them all in an array. Storing each of widgets in a unique entry like:
for i in range(7): #INPUT LINE 2
self.il['Line2',i] = QtWidgets.QCheckBox(self.il2info[i],self)
print(self.il['Line2',i])
--------output----------
<PyQt5.QtWidgets.QCheckBox object at 0x0000021A4398EE58>
<PyQt5.QtWidgets.QCheckBox object at 0x0000021A4398EF78>
<PyQt5.QtWidgets.QCheckBox object at 0x0000021A439690D8>
<PyQt5.QtWidgets.QCheckBox object at 0x0000021A43969168>
<PyQt5.QtWidgets.QCheckBox object at 0x0000021A439691F8>
<PyQt5.QtWidgets.QCheckBox object at 0x0000021A43969288>
<PyQt5.QtWidgets.QCheckBox object at 0x0000021A43969318>
but then my len(self.il['Line2']) command does not work.
I have tried something like the following:
self.il['Line2'[i]] = QtWidgets.QCheckBox(self.il2info[i],self)
but get an error of:
IndexError: string index out of range
I have also tried to do:
self.il['Line2':[i]] = QtWidgets.QCheckBox(self.il2info[i],self)
but I am met with the following error of:
TypeError: unhashable type: 'slice'
Is there some syntax error that I am missing? Can widget objects not be stored in dictionaries? Is there a way for me to ID widgets that would allow me to store the ID in dictionary?
EDIT: My original problem has been solved as I was incorrectly defining the keys/values of my dictionary. Using a temp dictionary to collect all widgets into an array and then equating them to my master dictionary with a key of 'Line2' fixed the issue.
You're storing a slice object, not whatever your desired key is. Can you update your example?
I'm afraid I don't understand your comment. I would like the "object" to be stored as a value for my 'Line2' key. I do not want the object to be sliced.
@JN3 see my answer
When you add an element as follows:
d[val1, val2] = some_value
is similar to:
d[(val1, val2)] = some_value
That is, the key is a tuple, so you must pass the tuple as a key so that it returns the value.
new_value = d[(val1, val2)]
In your case:
self.il['Line2', i] = some_value
new_value = self.il['Line2', i]
When you indicate for example:
self.il['Line2'[2]]
It is equivalent to:
self.il['n']
Or worse if you pass an index higher than the number of letters.
self.il['Line2'[6]]
Note: What you put a tuple as a key does not generate an array, if you want to get the structure of an array you must create a dictionary with dictionaries.
tmp_dict = {}
for i in range(7):
tmp_dict[i] = QtWidgets.QCheckBox(self.il2info[i],self)
self.il['Line2'] = tmp_dict
Then when you want to access you use:
#read
new_value = self.il['Line2'][i]
#write
self.il['Line2'][i] = some_value
Example:
for i in range(len(self.il['Line2'])):
new_value = self.il['Line2'][i]
self.il['Line2'][i] = some_value
So if I understand you correctly, what I have been doing is creating a bunch of unique keys, and not one key 'Line2' with multiple values. A key that has an array of values would require dictionary within dictionary?
@JN3 I have added an example of how to do it
Can I determine the number of values in self.il['Line2'] by using the len() command?
Yes, len() is for iterables, and the dictionary of those that belong to the list.
| common-pile/stackexchange_filtered |
SSIS error, import csv file to destination
Hello I have a csv file with 1 million row. And i try to import from the file to my source which is a database. Why do I get error exactly?
Please click at the images bellow and try to correct me and help me!
I can't see your screenshots, but attempting to import to a source won't work. You import to a destination.
The error is pretty clear. It's telling you that there is a mismatch in column lengths. Your source (CSV file) contains columns that may get truncated when they are imported into the the destination (database).
The CSV column lengths are all 255, while your database shows to have columns that are length 50.
So how do I fix it? Because I have tried to have all the length into 255 but it still complains. Do I have to edit in the database as well? In that case where exactly?
Well, you could change the columns on the database table to be length 255, but that's not a great solution.
When you select your flat file source, you can set options for the columns, including output length and database. Make sure all of these match. There is also an option to ignore truncation warnings.
You can right-click on the source -> show advanced editor -> input and output properties - and that will let you adjust your column lengths to match your DB or else change the data type
But when I try to change value on database the system complains, saying that I am not permitted and tables need to be droped and re-created
It would really be better if you fixed the import settings instead of mucking about the database. But if you insist on changing the DB table columns, it would help if you could show us the exact error you're getting.
| common-pile/stackexchange_filtered |
how to get the default HTTP USER AGENT from the android device?
How to get the default HTTP USER AGENT and its default settings from the android device?
thanks
Nohsib
Edit: See Prakash's answer, which is better for 2.1+.
Try http://developer.android.com/reference/android/webkit/WebSettings.html#getUserAgentString
Note that this User Agent will only apply for the embedded WebKit browser that's used by default in Android. Unfortunately, you'll need to create a new WebView object to get the user agent. Fortunately, the user agent doesn't change often, so you should only need to run this code once in your application lifetime (unless don't care about performance). Just do:
String userAgent = new WebView(this).getSettings().getUserAgentString();
Alternatively, you can use the JavaScript method navigator.getUserAgent().
Thankyou Oleg, if you could kindly share some code snippet on the same, would help.
Alright, I edited my response. (And next time, don't forget to do a search first.)
why is it better?
as Varundroid mentioned in his answer,
String userAgent = System.getProperty("http.agent");
is better way to do it for Android 2.1 and above.
====================
From android source code.
public static String getDefaultUserAgent() {
StringBuilder result = new StringBuilder(64);
result.append("Dalvik/");
result.append(System.getProperty("java.vm.version")); // such as 1.1.0
result.append(" (Linux; U; Android ");
String version = Build.VERSION.RELEASE; // "1.0" or "3.4b5"
result.append(version.length() > 0 ? version : "1.0");
// add the model for the release build
if ("REL".equals(Build.VERSION.CODENAME)) {
String model = Build.MODEL;
if (model.length() > 0) {
result.append("; ");
result.append(model);
}
}
String id = Build.ID; // "MASTER" or "M4-rc20"
if (id.length() > 0) {
result.append(" Build/");
result.append(id);
}
result.append(")");
return result.toString();
}
This is good, but if the scheme changes in future devices then it may not be accurate.
The scheme is a spec, so you can add any values to it as long as it conforms the spec.
When you use web view to access the user-agent, make sure you run the
new WebView(this).getSettings().getUserAgentString();
on the UI thread.
If you want access the user agent on background thread.
use
System.getProperty("http.agent")
To check whether a user-agent is valid or not use this
https://deviceatlas.com/device-data/user-agent-tester
Android get User Agent
An alternative
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
String userAgent = WebSettings.getDefaultUserAgent(context);
}
| common-pile/stackexchange_filtered |
Setting YAML variables depending on trigger branch
I'm trying to get my head around the yaml syntax for defining build pipelines in devops.
I'd like to set variables in the file dependent on which branch triggered the build.
# trigger:
batch: true
branches:
include:
- master
- develop
- staging
variables:
buildConfiguration: 'Release' # Can I set this according to the branch which triggered the build?
I've tried the following but can't seem to define variables twice.
variables:
solution: '**/*.sln'
buildPlatform: 'Any CPU'
variables:
condition: eq(variables['Build.SourceBranch'], 'refs/heads/develop')
buildConfiguration: 'Develop'
variables:
condition: eq(variables['Build.SourceBranch'], 'refs/heads/release')
buildConfiguration: 'Release'
Thanks for your help :-)
I'd probably add a script step to calculate those. so create some sort of script that will check the value of $(Build.SourceBranch) and set the value of buildConfiguration like you normally would:
echo '##vso[task.setvariable variable=buildConfiguration]something'
Thank you. I've not come across those yet. Reading time.
just look at the variables article for azure devops, it has info about those. basically all you have to do is echo out a string that looks like that
Thank you. I've stumbled across this for setting up multiple YAML files... but it seems a bit clunky so I'll try with the variables. https://sethreid.co.nz/using-multiple-yaml-build-definitions-azure-devops/
If anyone's interested, I ended up with this.
trigger:
batch: true
branches:
include:
- master
- develop
[truncated]
#https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch#set-a-job-scoped-variable-from-a-script
- pwsh: |
If ("$(Build.SourceBranch)" -eq "refs/heads/master") {
Write-Host "##vso[task.setvariable variable=buildConfiguration;]Release"
}
If ("$(Build.SourceBranch)" -eq "refs/heads/develop") {
Write-Host "##vso[task.setvariable variable=buildConfiguration;]Debug"
}
- script: |
echo building configuration $(buildConfiguration)
- task: VSBuild@1
inputs:
solution: '$(solution)'
msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'
platform: '$(buildPlatform)'
configuration: '$(buildConfiguration)'
clean: true
vsVersion: '15.0'
under where does this pwsh come exactly?
This is the full file. It is in azure-pipelines.yml in the root of my project https://gist.github.com/damiensawyer/8c7f70fc3eff720631be964d1d3bfd2e
Maybe this is due to enhancements in Azure Pipelines, but as of July 2024, the following works as well. Let's suppose the git repo to build defines a CI pipeline as follows:
trigger:
- main
- feature/*
resources:
repositories:
- repository: pipelineTemplates
type: git
name: libraries/Yaml.Pipeline.Templates
extends:
template: pipelines/continuous-integration.yml@pipelineTemplates
And an external git repo containing all the YAML definitions, imported as a resource, that defines the continuous-integration.yml as follows:
variables:
- name: configuration
${{ if eq(variables['Build.SourceBranch'], 'refs/heads/main') }}:
value: Release
${{ else }}:
value: Debug
stages:
- template: /stages/build-dotnet-assemblies.yml
parameters:
configuration: ${{ variables.configuration }}
- template: ...
HTH
| common-pile/stackexchange_filtered |
Jquery Tabs not displaying properly after upgrading to 1.8.9
Hey all, I'm having a strange issue today after upgrading to the latest jqueryui. My tab containers aren't working anymore. Its styling the tabs, but appearing like so:
As well, all three content frames are being shown in a large column, instead of one at a time. Has anybody seen this problem before? It works fine if I go back to 1.8.5, but I need to use the newer version now. Help!?
I'm not styling these tabs in any way outside of jquery, and the markup is exactly like the examples. Removing the content from the tabs has the same result, all three frames show up in a column.
*edit *
It does appear that jquery-ui-1.8.9.custom.min.js is causing the problem, not the theme. The tabs stop working when I update to 1.8.9. I take it from the lack of responses so far that this isn't a common problem.
I'm pretty sure that if you update your theme the problem will go away. If not, then I will adopt a puppy. But since I already have eight of the little beasties, I will do nothing.
Looks like you'll be making a trip to the spca, I'm using 1.8.9 themes.
Damn it. Not again! Hmmm, I will think on this some more.
I honestly don't know what to suggest. If I was in your position, I would probably 1) Work out if the theme or jQuery UI is causing the problem. 2) Use a text comparison app (such as Beyond Compare) to see exactly what has changed. These types of problems are generally headachy, I hope someone else here as a better suggestion.
Get this - redownloaded 1.8.9 and overwrote the file, same size in KB, tabs are working. I forgot to save the original to compare, but maybe this indicates a bug with how JqueryUI packages the .zip?
@Gallen - Maybe; interesting stuff and scary at the same time.
| common-pile/stackexchange_filtered |
Issue with shutil move when path is unknown
So I have files saved in multiple subdirecties, I want to move all files with certain extensions to a new directory. This is what I have:
path = 'C:/Users/R/Documents/16-2/gsi_14-01-2019'
dest_path = 'C:/Users/R/Documents/Hyperspectral/Datafiles/Raw'
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if '.raw' in file:
shutil.move((path + '/' + file), (dest_path + '/' + file))
This is throwing this error
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/R/Documents/16-2/gsi_14-01-2019/16-2_132_564m65_569m00_2019-01-11_12-30-56.raw'
because the file is in a subdirectory of the path, I think?. First part is able to find the file, but I need to feed to feed the full (originally unknown, determined) path to the shutil move function. Is there a way to do this?
On windows, you should use backslashes "" instead of "/" as path separator.
It looks like you are trying to move a file to another file. What you need to do is move the file to a directory. Does it work if you just use shutil.move((path + '/' + file), dest_path)
No I tried using just dest_path and it throws the same error
The source will be os.path.join(r, file). This is a common FAQ with os.walk.
| common-pile/stackexchange_filtered |
Angular ng-repeat over directive
I've got a simple directive
directive('animalCard',function(){
return {
restrict:'E',
template: '<div>time for {{a}}</div>'
}
});
that I want to iterate over an array
$scope.animals = ['penguins','cows','turtles'];
with HTML
<div ng-repeat="a in animals">
<animal-card>{{a}}</animal-card>
</div>
inside the curly braces for the template I'm using a as the expression to iterate over, and in this case it makes enough sense to say a in animals. But what if I wanted to use this same directive when iterating over something where the variable a wouldn't make sense? Is there a better solution to this other than using some generic interpolatable expression like {{item}}?
Why would you use this directive for other things? It's called animalCard.
perhaps this was a poor example to demonstrate what I'm actually curious about. It seems not quite as reusable as it could be given that if I wanted to iterate over a set of animals I always have to use the variable a (since it's in the HTML of the template. I suppose it doesn't really matter, just seems like it could be dynamic, maybe.
You should pass dependencies through directive attributes, and use the directive's scope config to specify how it binds it's data.
Seems like your question is more 'What should I call my loop variable?`In the end it really doesn't matter. As long as you (or others looking at your code) understand what it's doing it's fine.
If you want it to be more semantically readable, then you will need to change the name to something generic:item,data,str,d(for data),i(as i is often used for iterations/loops.
If OP is iterating over 'animals' why wouldn't a single item in that list be an 'animal'? Why would you want to use a generic name like 'item'?
I wouldn't use something like that. But from reading his question, I got the impression (from reading the last 2 sentences of post) that he isn't asking a question about how to do something, but rather what should he name a variable.
It is all just developer preference in the end.
You directive is literally incorrect. First of all, to insert something into directive from outside, you need transclude: true. Second, you must bind your variable a in ng-repeat="a in animals" to scope of directive, so it can understand what you want.
So working directive should look like
directive('animalCard',function(){
return {
restrict:'E',
transclude: true,
scope:{
a: '@'
},
template: '<div><div>time for {{a}}</div><div ng-transclude></div></div>'
}
});
And the last thing.
<div ng-repeat="a in animals">
<animal-card a="{{a}}">this content will be placed at the end, because of ng-tranclude attr in directive</animal-card>
</div>
Demo
Edit
oh, i glanced at code and seems misunderstood point of question. But naming convention really shouldn't make sense, i usually use item. But if you want to reuse it for very different object models, you probably should use different directive with additional decoration. And yes, it will be not reusability at this point. But for same object models, it's reusable, and you shouldn't meet any problems with naming, as they are same type. imo
| common-pile/stackexchange_filtered |
tikz: Labeled line aligned with node position
I am not sure how to create a axis with a labeling and some text above the line, aligned to my nodes. (for details see desired result below).
Desired result: (Ignore colors and size of nodes)
Current approach:
MWE:
\documentclass{scrreprt}
\usepackage{tikz}
\usetikzlibrary{shapes,arrows,matrix,intersections,positioning}
\tikzset{every picture/.style={/utils/exec={\sffamily}}}
\begin{document}
\begin{figure}[h]
\centering
\small
\begin{tikzpicture}[node distance = 0cm]
% Style
\tikzstyle{MP} = [rectangle, text width=1.5cm, minimum height=1.0cm, text centered, draw=black, fill=red!30]
\tikzstyle{D} = [rectangle, text width=0.5cm, minimum height=1.0cm, text centered, draw=black, fill=orange!30]
\tikzstyle{T} = [rectangle, text width=0.5cm, minimum height=1.0cm, text centered, draw=black, fill=blue!30]
\tikzstyle{CYS} = [rectangle, text width=1.0cm, minimum height=1.0cm, text centered, draw=black, fill=green!30]
\tikzstyle{S} = [rectangle, text width=1.5cm, minimum height=1.0cm, text centered, draw=black, fill=gray!30]
\tikzstyle{CUB} = [rectangle, text width=0.8cm, minimum height=1.0cm, text centered, draw=black, fill=yellow!30]
% Nodes
\node (S1) [MP] {A};
\node (S2) [D, right=of S1] {B};
\node (S3) [T, right=of S2] {C};
\node (S4) [CYS, right=of S3, xshift=0.2cm] {D};
\node (S5) [S, right=of S4] {E};
\node (S6) [T, right=of S5] {F1};
\node (S7) [T, right=of S6] {F2};
\node (S8) [T, right=of S7] {F3};
\node (S9) [T, right=of S8, xshift=0.4cm] {F4};
\node (S10) [T, right=of S9] {F5};
\node (S11) [T, right=of S10] {F6};
\node (S12) [T, right=of S11] {F7};
\node (S13) [CUB, right=of S12, xshift=0.6cm] {G};
\node (S14) [CUB, right=of S13] {H};
% Lines
\draw [line width=0.1cm] (S3) -- (S4);
\draw [line width=0.1cm] (S8) -- (S9);
\draw [line width=0.1cm] (S12) -- (S13);
\end{tikzpicture}
\end{figure}
\end{document}
Here is one approach, using perpendicular coordinates (see TikZ: What EXACTLY does the the |- notation for arrows do?) to draw the ticks.
Note also that \tikzstyle is considered deprecated, so I moved the style definitions into the optional argument to the tikzpicture. I also defined a base style that all the other styles inherit, so that there is less repetition of code.
And just to show an alternative approach, I used a chain to position the nodes, but you don't have to use that of course.
(Some of the numbers were somewhat randomly chosen and placed, so you need to fix that yourself, or clarify what goes where. I did increase the gaps in the line in order to make the numbers fit next to each other, which in hindsight was perhaps a silly thing to do, but let me know and I'll change back.)
\documentclass{scrreprt}
\usepackage{tikz}
\usetikzlibrary{chains}
\tikzset{every picture/.style={/utils/exec={\sffamily}}}
\begin{document}
\begin{figure}
\centering
\small
\begin{tikzpicture}[
node distance = 0cm,
% Style
base/.style={rectangle,minimum height=1cm,text centered,draw=black,on chain,fill=#1},
MP/.style={text width=1.2cm, base=red!30},
D/.style={text width=0.5cm, base=orange!30},
T/.style={text width=0.5cm, base=blue!30},
CYS/.style={text width=1.0cm, base=green!30},
S/.style={text width=1.2cm, base=gray!30},
CUB/.style={text width=0.8cm, base=yellow!30},
connection/.style={line width=0.1cm}
]
\begin{scope}[start chain=S]
% Nodes
\node [MP] {A};
\node [D] {B};
\node [T] {C};
\node [CYS, xshift=0.6cm] {D};
\node [S] {E};
\node [T] {F1};
\node [T] {F2};
\node [T] {F3};
\node [T, xshift=0.6cm] {F4};
\node [T] {F5};
\node [T] {F6};
\node [T] {F7};
\node [CUB, xshift=0.6cm] {G};
\node [CUB] {H};
\end{scope}
% Lines
\draw [connection] (S-3) -- (S-4);
\draw [connection] (S-8) -- (S-9);
\draw [connection] (S-12) -- (S-13);
% extensions
\draw [connection] (S-1.west) -- ++(-0.5,0);
\draw [connection] (S-14.east) -- ++(0.5,0);
% define coordinates for start and end point of axis
\path (S-1.north west) ++(-0.5,1) coordinate (start)
(S-14.north east) ++(0.5,1) coordinate (end);
% draw axis
\draw (start) -- (end) node[above left] {Some text};
% draw ticks
\foreach \Anchor/\Number in {%
start/0,
S-1.north east/100,
S-2.north east/200,
S-3.north east/300,
S-4.north west/320,
S-8.north east/620,
S-9.north west/640,
S-12.north east/720,
S-13.north west/740,
end/860}
\draw (start -| \Anchor) -- ++(0,-5pt) node[below] {\Number};
\end{tikzpicture}
\end{figure}
\end{document}
This has the same method for making the axis, it just demonstrates a variation for how to create the boxes in the first place, with a style that sets both the name and the node contents of the nodes, to the same thing. (Which in general is probably not a good plan, but in this case it works well.)
\documentclass{scrreprt}
\usepackage{tikz}
\usetikzlibrary{chains}
\tikzset{every picture/.style={/utils/exec={\sffamily}}}
\begin{document}
\begin{figure}
\centering
\small
\begin{tikzpicture}[
node distance = 0cm,
% Styles
nameandcontent/.style={
name=#1, % sets name, i.e. \node [name=foo] .. instead of \node [...] (foo)
node contents={#1} % the node text
},
base/.style={rectangle,minimum height=1cm,text centered,draw=black,on chain,fill=#1},
MP/.style={text width=1.2cm, base=red!30},
D/.style={text width=0.5cm, base=orange!30},
T/.style={text width=0.5cm, base=blue!30},
CYS/.style={text width=1.0cm, base=green!30},
S/.style={text width=1.2cm, base=gray!30},
CUB/.style={text width=0.8cm, base=yellow!30},
connection/.style={line width=0.1cm}
]
\begin{scope}[start chain]
% Nodes
% due to the use of node contents (in nameandcontent)
% we don't need (in fact can't use) the braces with the node text
% the parsing of the node ends after the closing ] of the node options
\node [MP, nameandcontent=A];
\node [D, nameandcontent=B];
\node [T, nameandcontent=C];
\node [CYS, nameandcontent=D, xshift=0.6cm];
\node [S, nameandcontent=E];
\node [T, nameandcontent=F1];
\node [T, nameandcontent=F2];
\node [T, nameandcontent=F3];
\node [T, nameandcontent=F4, xshift=0.6cm];
\node [T, nameandcontent=F5];
\node [T, nameandcontent=F6];
\node [T, nameandcontent=F7];
\node [CUB, nameandcontent=G, xshift=0.6cm];
\node [CUB, nameandcontent=H];
\end{scope}
% Lines
\draw [connection] (C) -- (D);
\draw [connection] (F3) -- (F4);
\draw [connection] (F7) -- (G);
% extensions
\draw [connection] (A.west) -- ++(-0.5,0);
\draw [connection] (H.east) -- ++(0.5,0);
% define coordinates for start and end point of axis
\path (A.north west) ++(-0.5,1) coordinate (start)
(H.north east) ++(0.5,1) coordinate (end);
% draw axis
\draw (start) -- (end) node[above left] {Some text};
% draw ticks and values
\foreach \Anchor/\Number in {%
start/0,
A.north east/100,
B.north east/200,
C.north east/300,
D.north west/320,
F3.north east/620,
F4.north west/640,
F7.north east/720,
G.north west/740,
end/860}
\draw (start -| \Anchor) -- ++(0,-5pt) node[below] {\Number};
\end{tikzpicture}
\end{figure}
\end{document}
@marmot Thanks. (By the way, why the \gettikzxy in your answer?)
@marmot OK, it seemed out of place, as you don't use it in the answer at all.
as exercises and for fun ... small variation of Torbjรธrn T. (actually combination of my first attempt to answer, but i was also few minutes to late and my solution was very similar but not so good; i'm very impressed with concept of nodes naming and writing their contains).
differences in comparison to Torbjรธrn T. answer are in style definitions, writing of numbers on axis (above nodes) and use positioning library. even entire code is shorter.
\documentclass[tikz, margin=3mm]{standalone}
\usetikzlibrary{chains,
positioning}
\begin{document}
\begin{tikzpicture}[
node distance = 12mm and 0mm,
% Styles
NaC/.style = {% Name and Content
name=#1, % sets name, i.e. \node [name=foo] .. instead of \node [...] (foo)
node contents={#1} % the node text
},
base/.style args = {#1:#2}{rectangle, minimum height=1cm ,draw=black,
minimum width=#1,
fill=#2,
font=\small\sffamily,
on chain},
MP/.style = {base=12mm:red!30},
D/.style = {base= 5mm:orange!30},
T/.style = {base= 5mm:blue!30},
CYS/.style = {base=10mm:green!30},
S/.style = {base=12mm:gray!30},
CUB/.style = {base= 8mm:yellow!30},
connection/.style={line width=1mm},
every pin/.append style = {pin distance=4mm, font=\footnotesize\sffamily}
]
\begin{scope}[start chain]
% Nodes
% due to the use of node contents (in nameandcontent)
% we don't need (in fact can't use) the braces with the node text
% the parsing of the node ends after the closing ] of the node options
\node [MP, NaC=A];
\node [D, NaC=B];
\node [T, NaC=C];
\node [CYS, NaC=D, right=5mm of C];
\node [S, NaC=E];
\node [T, NaC=F1];
\node [T, NaC=F2];
\node [T, NaC=F3];
\node [T, NaC=F4, right=5mm of F3];
\node [T, NaC=F5];
\node [T, NaC=F6];
\node [T, NaC=F7];
\node [CUB, NaC=G, right=5mm of F7];
\node [CUB, NaC=H];
\end{scope}
% Lines
\coordinate[left =5mm of A.west] (in);
\coordinate[right=5mm of H.east] (out);
\draw [connection] (in) -- (A)
(C) -- (D)
(F3) -- (F4)
(F7) -- (G)
(H) -- (out);
% define coordinates for start and end point of axis
\coordinate[above=of in |- A.north] (start);
\coordinate[left =of start -| out ] (end);
% draw axis
\draw (start) node[above right] {Some text} --
(end) node[above left] {Some text};
% draw ticks and values
\foreach \PIN/\Num in {%
start/0,
A.east/100,
B.east/200,
C.east/300,
D.west/320,
F3.east/620,
F4.west/640,
F7.east/720,
G.west/740,
end/860}
\coordinate[left=of start -| \PIN,
pin=below:\Num] (aux);
\end{tikzpicture}
\end{document}
| common-pile/stackexchange_filtered |
How to use intel python from anaconda?
I used this
conda create --name intelpy --channel intel --override-channels intelpython
to create an environment and install intelpython
and conda info --envs shows
# conda environments:
#
intelpy * /home/admin-pc/anaconda3/envs/intelpy
py27 /home/admin-pc/anaconda3/envs/py27
root /home/admin-pc/anaconda3
However, when I source activate intelpy
admin-pc@Precision-Tower:~$ source activate intelpy
(intelpy) admin-pc@Precision-Tower:~$ which python
/home/admin-pc/anaconda3/bin/python
it still uses the anaconda python, what is wrong?
Thanks to orangeInk. Adding python=3.6 works
conda create --name intelpy --channel intel --override-channels intelpython python=3.6
You should add the python argument to your create command. Omitting it will make the new environment use the system default Python interpreter rather than installing a new one.
conda create --name intelpy python=3.6
(use 2.7 instead of 3.6 for a Python 2 environment)
One small clarification, if you do not include the Python argument, it will not install Python at all (hence, as the OP shows, which python points to the Python in the base environment). Omitting the argument does not make the environment use the system default Python, it means that there is no Python in that environment and you will not be able to import packages installed in that environment in the base environment's Python
@darthbith Not 100% sure what you mean. When you create an environement without the python argument and activate it you can fully use the root environment's interpreter in that environement (not that that's useful). Either I'm missing your point or the confusion arose from me simply assuming that conda root env == system default interpreter.
I guess I had two points, both of which you mentioned in the comment here: 1) conda root env != system default interpreter, and 2) it's not very useful to use the root environment's Python in a separate environment (I guess unless you have R or something else in that environment, I shouldn't be so "python-normative") :-)
| common-pile/stackexchange_filtered |
Regular expression: extract css class out of string with multiple classes
I've got a string that I have to match and extract a css class name out of it. The string:
.c.-my-text-overlay-second
the class I have to match has to contain text-overlay inside or at the end of the class name.
So in this case, what I want to extract is .-my-text-overlay-second.
I have tried multiple things, but I either get the .c:
(.*\..*?text-overlay.*)
or I get only text-overlay:
.*(\..*?media-overlay-active)
What should be the correct expression?
Maybe you are tying to do it this way \.[\w-]*text-overlay[\w-]*
@revo this is correct. Great regex work! The link is useful, I will be able to understand how the hell it works :)
You shouldn't use a greedy dot .* in your Regular Expression since it will match everything from beginning to the point the next pattern (if exists) matches. That's the reason of matching whole input string while text-overlay exists in it.
Your regex should begin with a dot and the rest should correspond to class naming rules:
\.[\w-]*text-overlay[\w-]*
| common-pile/stackexchange_filtered |
Does packages from Ubuntu LTS 20.04 work on LTS 22.04?
I am planning to upgrade to the Ubuntu version but I wonder if some of the packages I used before won't be compatible with the new version.
I am using it as a business laptop for programming and my biggest concern is the VPN client, I am using FortiClient, and according to their Linux download page, there are no instructions for installation on LTS 22.04:
FortiClient Linux Download
You'll need to look at its requirements; if it's an open source program (be in Ubuntu, Debian etc) you can look up what those requirements are without it being installed, if it's closed source & only package is provided (without specifics), you need a system with it installed to know what is required. FYI: Some packages will work; eg. a package filled with wallpapers will work on any release as it'll have no depends requirements, alas this isn't so for more technical packages..
Forticlient is 3rd party software. You need to ask them that. Or try it out yourself using the live session ;)
My problem is that my dpkg is messed up and currently I can install nothing, not even balenaEtcher to create bootable device. That is the reason to reinstall my os.
If you know what you're doing, you can make a rather accurate guess as to if you'll have problems or not (ie. using packages built from one release, on a different release) as it's pretty easy to guess using open source code (99% accurate for Ubuntu software), even for third party (though accuracy isn't anywhere near as high), but IF YOU'RE ASKING CAN I, you're more likely to run into problems as you're unlikely to be able to examine the requirements of the package contained within the depends etc rules.
"My problem is that my dpkg is messed up" That's the question you should ask about. Asking about your proposed solution instead is a classic XY Problem. Whatever caused the "messed up" condition might be much easier to fix.
It's doubtful.
Software packages on Debian-based systems are compiled against a common set of dependencies. One definition of a "new release" is that the common set of dependencies has changed: Versions changed, APIs broken, etc.
Software compiled against one release of Ubuntu (one set of dependencies) is unlikely to work on a different release of Ubuntu (a different set --or versions-- of dependencies).
Indeed, some of the most common help requests come from folks who have attempted to bolt wrong-version software onto their release of Ubuntu...and discovered that it has broken apt and/or the software simply doesn't work anymore. (There's even a name for it)
| common-pile/stackexchange_filtered |
Read multiple files from S3 using golang
I am a novice in golang.
I want to read multiple files from Amazon S3. I am using the s3gof3r library.
The go routine is as follows:
for i := 1; i <= fileNo; i++ {
go test(i, b)
}
func test(i int, b *Bucket) () {
fmt.Println("Loading file no:" + strconv.Itoa(i))
defer wg.Done()
r, _, err := b.GetReader("testFile_" + strconv.Itoa(i) + ".htm", nil)
buf := new(bytes.Buffer)
buf.ReadFrom(r)
fmt.Println(err)
fmt.Println("Completed file no:" + strconv.Itoa(i))
r.Close()
}
This code works alright if I have about 200 files (i.e. 200 go routines reading from 200 files) but it crashes if I have to read more files (I have to read more than 10,000 files)
The error that i get is
panic: runtime error: invalid memory address or nil pointer dereference
panic(0x39fde0, 0xc8200100f0)
/usr/local/go/src/runtime/panic.go:464 +0x3e6
bytes.(*Buffer).ReadFrom(0xc8200d3f18, 0x0, 0x0, 0x0, 0x0, 0x0)
/usr/local/go/src/bytes/buffer.go:176 +0x239
main.test(0x4c, 0xc8200bc8e0)
The error comes from using 'ReadFrom'. Is there a problem using ReadFrom in this way? Or is this a wrong way to accomplish the task of reading so many files?
check your errors first.
https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables
As JimB mentions, you perform a r, _, err := ... but do not check your error: it's perfectly possible that something goes wrong and the returned r is nil, which would explain your crash. You should handle that case first, making sure that err is nil before attempting to access r.
Sorry there was a type there. Its bytes.Buffer
Probably you ran out of memory.
Is it a typo buf := new(bytes.Reader) in your example, did you mean bytes.Buffer? I guess so.
r, _, err := b.GetReader(...)
//...
n, err := buf.ReadFrom(r)
Check for errors there. Probably it will be bytes.ErrTooLarge in ReadFrom call.
ErrTooLarge is passed to panic if memory cannot be allocated to store data in a buffer.
No, if you run out of memory, you will get an "out of memory" error. This is a nil pointer dereference.
Yeah, thats exactly what happens when you ran out of memory and internal bytes.Buffer's buffer is set to nil pointer. And since you did not check for the error, you are dereferencing nil pointer.
Good point, forgot that bytes package tries to return ErrTooLarge when it can. I would still check the error before making any assumptions though.
| common-pile/stackexchange_filtered |
PHP Time and Date
I have a database with dated articles. What I want to do is select articles between 2 dates - for example from 7 days ago to today.
Can anybody help me. I have been trying to write a code for it but it hasn't worked for me.
Thanks in advance
What kind of database and how are you storing article dates?
If your database is SQL based, try this...
SELECT * FROM articles WHERE published > DATE_SUB(NOW(), INTERVAL 7 DAY)
If you are working just in PHP, you can manipulate dates a bit like this...
$now = time();
// go back 7 days by working out how many seconds pass in 7 days
$lastweek = $now - (60*60*24*7);
// format the date from last week any way you like...
echo date("r", $lastweek);
If you are using timestamps you can try something like this:
<?php
$toDate = time();
$fromDate = $now - (60 * 60 * 24 * 7);
$query = 'SELECT * FROM table WHERE time>='.$fromDate.' AND time<='.$toDate;
?>
SELECT `whatever`
FROM `article`
WHERE `publish_date` >= '2009-06-16'
AND `publish_date` <= '2009-06-23'
SELECT *
FROM yourTable
WHERE articleDate >= '2009-05-01'
AND articleDate <= '2009-05-31'
I suspect you're having trouble formatting dates, so I'd suggest looking into the PHP date() and strtotime() functions.
| common-pile/stackexchange_filtered |
libGDX can not see Android SDK
I am a newbie android develiper. I have just installed the most recent Android Studio and downloaded libGDX setup tool. However, when I try to generate a new project, it shows the error:
Your Android SDK path doesn't contain an SDK! Please install the Android SDK, including all platforms and build tools!
I am pretty sure I have Android SDK installed and I put a correct location C:\Users\Denis\AppData\Local\Android\Sdk, because I copied it from Android studio.
This is how libGDX is checking if android SDK location valid:
public static boolean isSdkLocationValid (String sdkLocation) {
return new File(sdkLocation, "tools").exists() && new File(sdkLocation, "platforms").exists();
}
However, I don't have tools folder in my setup. Probably, in fresh Android SDK it was renamed or I don't have required tools installed, not sure (pls suggest in comments). However, the workaround is to create an empty tools folder in C:\Users\Denis\AppData\Local\Android\Sdk
I just had the same issue to day. I think the problem is that the SDK that comes with Android Studio dos not contain the "tools" folder. You'll have to download it manually and add it to the SDK. Here is the link. I hope this helps you.
I found a lot of questions similar to this and found the following information
"Where does Android Studio install sdk on Mac?
Configure Android SDK Variable In macOS.
Generally, the Android SDK is installed in the /Users/user-name/Library/Android/sdk folder on macOS."
https://www.dev2qa.com/how-to-set-android-sdk-path-in-windows-and-mac/
In your "Android SDK: " area on libGDX you can type in the following path and just replace with your username
/Users/"user-name"/Library/Android/sdk
| common-pile/stackexchange_filtered |
Could time have tertiary directions?
This is a late night thought, but it seems interesting enough to ask: Has anyone considered the possibility that time might have more directions that forward and backward? Could time go sideways?
Define "sideways".
I have a feeling that extra time-like dimensions give rise to tachyonic KK states. I don't know if that means additional time-like dimensions are impossible.
http://physics.stackexchange.com/q/43322/72487 http://physics.stackexchange.com/q/43630/72487 These posts may be useful.
While I gave the answer below an up-vote, you may want to additionally consider the idea that time is not really a dimension. Time is directional and depends on the existence of thermodynamic non-equilibrium.
Possible duplicates: http://physics.stackexchange.com/q/43322/72487 , http://physics.stackexchange.com/q/43630/72487 (cf. @Meer Ashwinkumar's comment) and links therein.
I know that there are theories that include multiple dimensions of time (this would be required for a direction other than forward/backward). People have gotten so used to being surprised by counterintuitive truths in physics that a lot of non-typical theories have been developed. They tend to depend on things which are difficult or impossible to verify experimentally (or else they would have been proven incorrect already).
To answer the question directly: I have never seen any proof that time cannot have additional dimensions. There is also a duplicate of this question that comes to the same conclusion here. Therefore, until I come upon such proof, I will assume that time could have additional dimensions.
It's certainly an interesting idea. I might read the wikipedia article now:
https://en.wikipedia.org/wiki/Multiple_time_dimensions
Additional sources include a short chat by Neil deGrasse Tyson about this:
https://www.youtube.com/watch?v=CvKuEgzElec
Cheers,
Felix
A few quick introductory comments: whether time goes in any direction is not universally accepted. Have a look at the answers to Is the flow of time regular? and Is there a proof of existence of time? for some discussion of this question.
As far as relativity is concerned time is just a dimension. We line in a four dimensional spacetime, which means we need four numbers $(t, x, y, z)$ to identify points in spacetime. Time is just one of the four dimensions in spacetime. One way to interpret your question would be to ask if there can be more than one time dimension e.g. could we have a five dimensional spacetime $(t_1, t_2, x, y, z)$ with two time dimensions? This is an idea that crops up from time to time, but the big problem with it is that two time dimensions generally allow closed timelike curves i.e. time travel and that causes havoc with physics because it implies a loss of causality. Since observations suggest the universe does exist and is reasonably predictable, that strongly implies there is only one time dimension.
The physicist Itzhak Bars has developed theories with two time dimensions, and these seem to avoid the worst of the problems though you should note that his approach is not widely accepted. There is also a theory called F-theory that can have two time dimensions, though these aren't really what we would normally think of as time dimensions.
| common-pile/stackexchange_filtered |
Let $S=\{a,b\}$. Which binary operation $*$ on $\wp(S)$ makes $(\wp(S),*)$ a cyclic group?
Let $S=\{a,b\}$ be a set, and $\wp(S)$ the power set of $S$. It is well known that $$(\wp(S),\triangle,\emptyset)\cong \mathbb{Z}_2\times \mathbb{Z}_2\,,$$ where $\triangle$ is the symmetric difference of two sets.
Now, there are $24$ bijections $f\colon \mathbb{Z}_4 \to \wp(S)$, and hence as many operations "$*$" in $\wp(S)$ such that $$(\wp(S),*,f(0))\cong \mathbb{Z}_4.$$ I tried by trial and error several times, but I couldn't succeed in finding any of such operations as a symmetric (being the group abelian), closed formula in terms of the basic set operations $\cup, \cap,\setminus$, just like the symmetric difference formula.
You can just make an assignment $f:\mathbb{Z}/4\mathbb{Z}\to \mathcal{P}(S)$ by sending, for example, $0\mapsto \emptyset$, $1\mapsto {a}$, $2\mapsto {a,b}$, and $3\mapsto {b}$. Then, for $A,B\in\mathcal{P}(S)$, define $A*B$ to be $$f\big(f^{-1}(A)+f^{-1}(B)\big),.$$
I know that, but can you express your $*$ with a closed formula using set union, intersection, difference?
It is unclear why you think such an operation should exist.
@user1729, I assumed the existence to be settled by the argument recalled by Batominowski. If you mean that none of the operations gotten via those 24 bijections can be given a closed formula in terms of the basic set operations, well this would be a fortiori the answer to my question.
I made a question that generalizes your problem. I hope somebody finds an answer. See https://math.stackexchange.com/questions/3754768/.
Let $(B,+,\cdot)$ be the Boolean algebra with two generators $u$ and $v$. The multiplication in $B$ is given by $u\cdot u=u$, $v\cdot v=v$, and $u\cdot v=v\cdot u=0$. Therefore, $e:=u+v$ is the multiplicative identity of $B$.
We identify $0$, $u$, $v$, and $e$ with $\emptyset$, $\{a\}$, $\{b\}$, and $\{a,b\}$, respectively. Then, we can associate any set operation on $\mathcal{P}(S)$ with a polynomial operator in $B$. This is because the symmetric difference operator $\triangle$ is associated to the polynomial $d(x,y):=x+y$, the union operator $\cup$ is associated to the polynomial $f(x,y):=x+y+x\cdot y$, the intersection operator $\cap$ is associated to the polynomial $g(x,y):=x\cdot y$, the set difference operator $\setminus$ is associated to $h(x,y):=x+x\cdot y$, and the complement operator is associate to the polynomial $k(x):=e+x$.
Suppose that there exists a polynomial $p(x,y)\in B[x,y]$ such that the binary operation on $\mathcal{P}(S)$ equips $\mathcal{P}(S)$ with a structure of $G:=\mathbb{Z}/4\mathbb{Z}$. Let $z\in B$ be the element that acts as the identity of $G$. Since $G$ is abelian, we get $p(x,y)=p(y,x)$, whence
$$p(x,y)=\alpha+\beta\cdot x+\beta\cdot y+\gamma\cdot x\cdot y$$
for some $\alpha,\beta,\gamma\in B$. Now,
$$0=p(0,z)=\alpha+\beta\cdot z\,.$$
Therefore,
$$\beta\cdot z=\alpha\,.$$
We also have
$$z=p(z,z)=\alpha+\beta\cdot z+\beta\cdot z+\gamma\cdot z\cdot z=\alpha+\gamma\cdot z\,.$$
Hence,
$$(e+\gamma)\cdot z=z+\gamma\cdot z=\alpha\,.$$
Furthermore,
$$\begin{align}e=p(e,z)&=\alpha+\beta\cdot e+\beta\cdot z+\gamma\cdot e\cdot z
\\&=\alpha+\beta+\alpha+(\alpha+z)=\alpha+\beta+z\,.\end{align}$$
Consequently,
$$z=e+\alpha+\beta\,.$$
From $\beta\cdot z=\alpha$, we conclude that $\alpha\cdot\beta=\alpha$, or $$\alpha\cdot(e+\beta)=0\,.$$
Case I: $\beta=0$. Then, $\alpha=\beta\cdot z=0$. Therefore, $z=e+\alpha+\beta=e$. As $(e+\gamma)\cdot z=\alpha$, we conclude that $\gamma=e$. Hence, $p(x,y)=x\cdot y$, which clearly does not work. (Alternatively, note that $p(0,0)=0$, which contradicts the result that $z=e$ is the identity of $G$.)
Case II: $\beta=u$. Then, $\alpha\cdot v=\alpha\cdot(e+\beta)=0$. Hence, either $\alpha=0$ or $\alpha=u$.
If $\alpha=0$, then from $z=e+\alpha+\beta$, we get $z=v$. From $(e+\gamma)\cdot z=\alpha$, we conclude that $\gamma=0$ or $\gamma=v$. In the case $\gamma=0$, we get $p(x,y)=u\cdot(x+y)$, which means that the image of $p(x,y)$ can only be $0$ or $u$, leading to a contradiction. In the case $\gamma=v$, we get $$p(x,y)=u\cdot(x+y)+v\cdot(x\cdot y)\,,$$
whence
$$p(u,0)=u\cdot(u+0)+v\cdot(u\cdot 0)=u\,,$$
but this contradicts the conclusion that $z=v$ is associated to the identity of $G$.
If $\alpha=u$, then $z=e+\alpha+\beta=e$. From $(e+\gamma)\cdot z=\alpha$, we conclude that $\gamma=v$. Ergo,
$$p(x,y)=u+u\cdot(x+y)+v\cdot(x\cdot y)\,.$$
Thus,
$$p(u,u)=u+u\cdot(u+u)+v\cdot(u\cdot u)=u\,.$$
This contradicts the result that $z=e$ is associated to the identity of $G$.
Case III: $\beta=v$. The argument is the same as Case II.
Case IV: $\beta=e$. Then, $z=e+\alpha+\beta=\alpha$, and from $(e+\gamma)\cdot z=\alpha$, we get $\gamma\cdot\alpha=0$.
If $\alpha=0$, then $z=0$ and $$p(x,y)=(x+y)+\gamma\cdot(x\cdot y)\,.$$
Therefore, $p(\gamma,\gamma)=\gamma$ implies that $\gamma$ is associated to the identity of $G$, making $\gamma=z=0$. Thus, $p(x,y)=x+y$, which clearly does not work. (Alternatively, note that $p(0,0)=0$, which contradicts the result that $z=e$ is the identity of $G$.)
If $\alpha=u$, then $z=u$ and $$p(x,y)=u+(x+y)+\gamma\cdot(x\cdot y)\,.$$ Note that $\gamma\cdot \alpha=0$ implies $\gamma=0$ or $\gamma=v$. If $\gamma=0$, then $p(0,0)=u=p(v,v)$, which contradicts the fact that $G$ has only one element of order $2$. If $\gamma=v$, then $p(e,v)=v$, which contradicts the result that $u$ is associated to the identity of $G$.
If $\alpha=v$, then we have a similar contradiction to the previous subcase.
If $\alpha=e$, then $z=e$ and $\gamma=0$, making $$p(x,y)=e+(x+y)\,.$$ Now, $p(x,x)=e$ for all $x\in B$ contradicts the fact that $G$ has only one element of order $2$.
Therefore, such a polynomial $p(x,y)\in B[x,y]$ does not exist. Hence, there is no binary operator $*$ on $\mathcal{P}(S)$ given by the usual set operations that makes $\mathcal{P}(S)$ isomorphic to the group $\mathbb{Z}/4\mathbb{Z}$.
P.S. See a much simpler argument to a more generalized setting here.
| common-pile/stackexchange_filtered |
HttpBuilder uploading file without extension
So I got this gradle script that let's me upload apks to Nexus. The issue is that those files end up without file extension on the server which is a problem if you want to download an app from there.
It seems that I'm passing the proper mime type but even with that I'm still getting a file without extension.
Here is the code:
def uploadToRepository(File file,
String folder,
String url,
String userName,
String password){
HTTPBuilder http = new HTTPBuilder(url)
String basicAuthString = "Basic " + "${userName}:${password}".bytes.encodeBase64().toString()
http.client.addRequestInterceptor(new HttpRequestInterceptor() {
void process(HttpRequest httpRequest, HttpContext httpContext) {
httpRequest.addHeader('Authorization', basicAuthString)
}
})
try {
http.request(Method.POST, "application/vnd.android.package-archive") { req ->
uri.path = "/content/repositories/releases/${folder}"
MultipartEntity entity = new MultipartEntity()
def fileBody = new FileBody(file, "application/vnd.android.package-archive")
entity.addPart("file", fileBody)
req.entity = entity
response.success = { resp, reader ->
if(resp.status == 201) {
println "File ${file.name} uploaded"
}
}
}
} catch (Exception e) {
e.printStackTrace()
}
}
Have you tried new FileBody(file, ContentType.create("application/vnd.android.package-archive"), file.name)
it was all fine, the issue was that Nexus needs to have the file name as part of the url or else is not going to work.. Basically I just changed uri.path = "/content/repositories/releases/${folder}" to be uri.path = "/content/repositories/releases/${folder}/nameofapp.apk"
| common-pile/stackexchange_filtered |
How do you erase only part of an imported "placed" image in Illustrator?
I have drawn an image in Illustrator and am working on drawing a second and unrelated image. Part of the new project requires another clip-art image I drew previously.
I "placed" the older image into my current project, but it is showing up as one unified object and I would like to erase part of it.
Is there some way to "break apart" the imported image or just erase a section of it?
You can edit the original art and the placed image will update.
If you don't want to alter the original, highlight the placed art in the Links Panel and then choose Embed from the Link Panel menu.
This will embed the placed artwork and make it actually editable artwork in the file you are working in. This also breaks the link or relationship to the original file. Therefore any edits to the original file will not be reflected in the new file you are working on.
If you just want to erase part of the image, it might be easier to put it in a clipping mask that surrounds everything but has a hole over the part you want to erase. This would keep the link with the original file.
So for example if you'd placed this black and white image below, and wanted to keep the link with the original but wanted to erase the huh? text in this place only, you could do it like this:
| common-pile/stackexchange_filtered |
How to replace % with html tag in PHP
I have the following code in PHP:
$fullString = "a %sample% word go %here%";
And I want to replace % with html tag (<span style='color:red'> and </span>). This is what I want after replacing:
$fullString ="a <span style='color:red'>sample</span> word go <span style='color:red'>here</span>";
What should I do to accomplish this result using PHP function like str_replace, preg_replace etc.?
Thanks.
Something like this? http://www.phpliveregex.com/p/aVk
You could do....
$string = "a %sample% word go %here%";
echo preg_replace('~%(.*?)%~', '<span style="color:red">$1</span>', $string);
That says replace everything between the first % and next occurring % sign with the spans. The () groups everything inside those percents into the $1.
Output:
a <span style="color:red">sample</span> word go <span style="color:red">here</span>
| common-pile/stackexchange_filtered |
Does climbing during combat consume your Action?
During combat a player of mine wanted to climb an easily scaled 10' rock wall. Normally climbing requires extra Movement costs, and I called for a DC 10 Strength (Athletics) check to make the climb without a rope. His intention was to climb atop a cliff and then use his Attack Action. My question is would climbing consume his Action?
I'm aware of the Use Object Action when using an object that would consume your action and not fall under the 'free object interaction' category, but does 'interacting' with a wall (i.e. climbing) count as an Action normally or is it simply part of your Movement?
TL;DR: Yes, he can attack if he has enough Movement to make the climb and does not have to use two interactions to both stow and draw a weapon.
Walls can be covered under "special types of movement." (PHB, p. 182). The rules-as-written allows that attack if he has enough movement left to climb that distance, since you can generally move and attack in the same turn.
Climbing, Swimming, and Crawling
While climbing or swimming, each foot of movement costs 1 extra foot (2 extra feet in difficult terrain), unless a creature has a climbing or swimming speed. At the DMโs option, climbing a slippery vertical surface or one with few handholds requires a successful Strength (Athletics) check. (Basic Rules, p. 64 / PHB. p. 182)
If he had at least 20' of movement left, it fits RAW that he'd complete the move up the 10' wall and then attack, providing the character succeeded in the Strength (Athletics) Check you required. Since you have already determined that the wall isn't that hard to climb, there seems no reason not to allow the attack. If you had ruled it difficult terrain, he'd have needed 30' of movement to make the climb and then attack.
Other Activity on Your Turn:
[โฆ] You can interact with one object or feature of the environment during either your move or your action. (PHB, p. 190, Basic Rules, p. 70)
What you may wish to rule on is whether or not he must
stow the weapon (interaction)
climb the wall (movement)
and then draw the weapon (interaction)
If he needs two interactions (only one interaction is free) that would most often preclude the attack. (In some cases, a bonus action could still allow it.)
You state that this wall is not hard to climb. You may or may not allow him to climb this wall with a weapon in hand. You could increase the DC of the climb if he attempts it with weapon in hand. As that wasn't specified in the question, I'm can't suggest a ruling either way.
Your Turn
On your turn, you can move a distance up to your speed and take one action. You decide whether to move first or take your action first. Your speedโsometimes called your walking speedโis noted on your character sheet. (PHB, p. 189; From Basic Rules, p. 69)
Movement and Position
You can use as much or as little of your speed as you like on your turn, following the rules here. Your movement can include jumping, climbing, and swimming. These different modes of movement can be combined with walking, or they can constitute your entire move. However youโre moving, you deduct the distance of each part of your move from your speed until it is used up or until you are done moving. (PHB, p. 190; Basic Rules, p. 70)
If the character is a Rogue with Second-Story Work (Thief Archetype) then he'd not need all 20 feet of move, just the 10 feet.
Second-Story Work
When you choose this archetype at 3rd level, you gain the ability to climb faster than normal; climbing no longer costs you extra movement. (PHB p. 97;
Basic Rules, p. 28):
PHB page 182:
While climbing or swimming, each foot of movement costs 1 extra foot (2 extra feet in difficult terrain), unless a creature has a climbing or swimming speed. At the DMโs option, climbing a slippery vertical surface or one with few handholds requires a successful Strength (Athletics) check. Similarly, gaining any distance in rough water might require a successful Strength (Athletics) check.
There are class abilities that negate or modify this.
| common-pile/stackexchange_filtered |
Python code error
import arcpy
inputlayer=arcpy.GetParameterAsText(0)
output=arcpy.GetParameterAsText(1)
arcpy.Select_analysis( inputlayer, output,"LAYER = 'Unknown Line Type'")
I am new to Python migrating from VB.Net. I want to select all items of a feature where the field LAYER = Unknown Line Type.
But I am always having problem in executing this code.
This image remains for more than an hour and nothing happens.
I Have only 80 features with no index.
What error are you getting when you run the code that you have presented?
Please [Edit] the Question to specify the number of features that are involved, and whether you have constructed an index on the column. Even when I select from millions of rows, my query time rarely drifts into minutes, but I always build indexes on my query column(s).
Are you presenting every line of code in Script1?
What gets printed with print inputlayer and print output
| common-pile/stackexchange_filtered |
how to vectorize nested for loops in numpy
I have been trying to solve this question but I was stuck in limbo
v,u,j=file.shape
for v in range(height):
for u in range(width):
start[v,u,0] = -0.5 + u / (width-1)
start[v,u,1] = (-0.5 + v / (height-1)) * height / width
start[v,u,2] = 0
after I used this function I couldn't go further
v,u,j=file.shape
x,y,z=np.mgrid(0:v,0:u,0:j)
I hope you help me with a detailed solution to understand well the mechanism
thanks in advance
Your code is not clear, what's height and weight? Does j do anything?
You should always provide a minimal working example. Otherwise we can only guess.
I've converted your code into this working example. It may or may not reflect what you are really trying to do:
file = np.random.random((300, 200, 3))
start = np.empty_like(file)
height, width, _ = file.shape
for v in range(height):
for u in range(width):
start[v, u, 0] = -0.5 + u / (width - 1)
start[v, u, 1] = (-0.5 + v / (height - 1)) * height / width
start[v, u, 2] = 0
The following code produces the same result. Notice how an individual value is replaced by a vector in each of your expressions:
start_bis = np.zeros_like(file)
u = -0.5 + np.arange(width) / (width - 1)
v = (-0.5 + np.arange(height) / (height - 1)) * height / width
start_bis[..., 0], start_bis[..., 1] = np.meshgrid(u, v)
| common-pile/stackexchange_filtered |
Is ifelse() in R efficient for determining which function to call on a large vector?
I'm currently writing a code that will call a specific function, depending on the value of an element in a vector. My question, then, is whether or not this is efficient. If I understand the ifelse algorithm correctly, whatever values I put as the 2nd and 3rd arguments to the function are calculated in their entirety and then subsetted based on the TRUE or FALSE values of my condition. This is in contrast to the typical if/else structure we see in coding, where we'd evaluate a condition and then run a function on the element only once we know which function to run. To test this out, I tried to use the following:
test1 <- function() {
x <- sample(1:1e9, 1e6, replace = TRUE)
y <- ifelse(x %% 2 == 0, x**2, x/2)
return(y)
}
test2 <- function() {
x <- sample(1:1e9, 1e6, replace = TRUE)
y <- numeric(length(x))
for (i in 1:length(x)) {
if (x[i] %% 2 == 0) {
y[i] <- x[i]**2
} else {
y[i] <- x[i]/2
}
}
return(y)
}
microbenchmark::microbenchmark(test1(), test2(), times = 1000)
Unit: milliseconds
expr min lq mean median uq max neval
test1() 2.366067 2.494746 8.27343 2.580164 2.706826 1690.049 1000
test2() 21.773385 23.050818 29.70450 23.712907 29.468783 3169.008 1000
The mean values seem to indicate that the ifelse approach is favorable over if/else.
The reason I'm asking is because I'll have relatively large XML files that I'm parsing and the parsing methods I implement will vary depending on the layout of the children in the tree and I'm trying to be as efficient as possible.
So two questions: 1) Are my conclusions above correct, that ifelse is faster than if/else, and 2) does ifelse calculate all values for both yes and no vectors and then subset them?
Thanks in advance.
Edit
The code above, as well as some of the question text, has been modified to reflect the comments below.
ifelse has a whole bunch of checking of inputs etc that your test2 function does not have. This probably accounts for most of the nanoseconds of difference. The core of ifelse is essentially an if/else the same as what you have + some adjustment for NA values.
Your test2 has an error in it; try running it by itself. Also your benchmark command should call test1() and test2(), otherwise it's not actually running the code.
And if you really want to see the performance difference, pre-simulate x and pass it in to your functions.
@aaron Good call! I'll update the question to reflect that.
You should find that ifelse is substantially faster for this example.
@Aaron Yeah, that's what I just found. Had I actually formatted my reproducible example correctly, this question probably wouldn't have even been asked. I'll be deleting it since there's no longer a real question here.
In response to 2), according to the help file, "yes will be evaluated if and only if any element of test is true, and analogously for no," so the answer is yes except for the case where one is never needed.
Also see the suggestions in the help file under the Warning section that give an example of a type of construction that might be preferred.
@gregor I don't necessarily have a question anymore, but SO wouldn't let me delete the question because it had an answer.
The way you've coded does worse than ifelse, but as suggested in the warning section of ?ifelse it's possible to do better. With your simple functions, x^2 and x / 2, the test3() function below is faster - about 2 to 3 times faster than ifelse and 30 times faster than test2(). With more computationally intensive functions (but still vectorized!) the margin might be bigger.
The speed gain is (I think) mostly due to two sources:
ifelse does input checking and error handling that test3() skips. ifelse is more general and more flexible... test3() is hardcoded to only return a numeric vector).
As demonstrated at Does ifelse really calculate both of its vectors every time? Is it slow?, ifelse will calculate its entire TRUE response vector as long as there is at least 1 TRUE value of the test, and similarly for its FALSE. test3() bypasses the extra calculations by creating TRUE and FALSE sub-vectors.
I've modified your test1() and test2() to simplify a bit, pulling out the data simulation (since that's not what we want to test). I added test3 that uses logical subsets. I also drastically reduced the size of the test vector so it runs reasonably quickly.
set.seed(47)
x <- sample(1:1e6, 1e4, replace = TRUE)
test1 <- function(x) {
ifelse(x %% 2 == 0, x**2, x/2)
}
test2 <- function(x) {
y <- numeric(length(x))
for (i in seq_along(x)) {
if (x[i] %% 2 == 0) {
y[i] <- x[i]**2
} else {
y[i] <- x[i]/2
}
}
return(y)
}
test3 <- function(x) {
y = numeric(length(x))
cond = x %% 2 == 0
y[cond] = x[cond] ^ 2
y[!cond] = x[!cond] / 2
return(y)
}
identical(test1(x), test2(x))
# TRUE
identical(test1(x), test3(x))
# TRUE
microbenchmark::microbenchmark(test1(x), test2(x), test3(x), times = 1000)
# Unit: microseconds
# expr min lq mean median uq max neval cld
# test1(x) 1563.270 1642.3540 1701.3877 1669.2180 1697.894 3159.743 1000 b
# test2(x) 17909.833 18788.9635 23682.1516 19882.8600 20679.436 116206.536 1000 c
# test3(x) 627.241 668.7445 691.8433 680.6675 696.061 1340.507 1000 a
It seems as if the answer is that ifelse is much faster than if/else, but code can typically be rewritten in a way that is even faster than ifelse, which makes total sense to me. Thanks!
| common-pile/stackexchange_filtered |
Dynamically change application icon at compile time? (.NET)
I have two applications that I'm creating off of one codebase, resulting in two executables. Is there any way to dynamically change the executable's icon depending on a compilation flag (or something of that nature)?
I'm using VS2010 and code is C# if that matters.
You might find a solution using compiler flags here ; http://stackoverflow.com/questions/10125034/how-to-assign-a-custom-icon-for-an-application-which-is-compiled-from-source-fil
The /win32res option qualifies. Creating the .res file is a bit unfun.
The only way I found is replacing the icon in the batch file I use for compilation
copy \Resources\%VENDOR%.ico \icon.ico
| common-pile/stackexchange_filtered |
How to deploy a web site on IIS by using .dll file
I want to deploy on IIS my web site but I do not want to take whole project. I just need to take .dll file. Is their any way to do so.
I do not want to use visual studio only .dll file from the project to deploy.
The basic steps for deploying to IIS on windows server are as follows:
log onto the machine that is or will be hosting your application.
Use IIS Manager to create a new website for your application.
Create a new application in that site. I believe this also will automatically create an application pool with the same name for you and use it by default.
Specify the virtual directory for your application. This is going to tell IIS where to look for your mvc application. For this case lets assume it is C:\myApp
On your own machine Build the application however you build it with the correct solution configuration (i.e. Release mode). Let say the result of your build is located at C:\MyProject\bin
Copy C:\MyProject\bin from your machine onto your hosting machine at C:\myApp
You should be able to search these steps and find a step by step guide of how to accomplish them. Here is a link to some info on what sites, applications and app pools are to help you better understand.
http://www.iis.net/learn/get-started/planning-your-iis-architecture/understanding-sites-applications-and-virtual-directories-on-iis
Based on your sites requirements there will be some additional steps to set up security and alter bindings if you need to change them.
thanks mmilleruva, i follows the steps but when i browse, it shows only dll file,not the web page.
I am beginner to these things.
You don't need to deploy your entire website if you only make a change in a single assembly. You could copy the .DLL assembly directly to the bin folder of your website. This will trigger the Application Pool to be recycled in IIS and the changes will be taken into effect on the next request.
but i don't know how to deploy without using visual studio. is their any tutorial to do so.
| common-pile/stackexchange_filtered |
MYSQL can't run in MAMP on mac after osx buitin upgrade php to 7.1
I have got this error logs after upgrade builtin PHP to version7.1 but I not mean from this cause.
InnoDB: directories yourself, InnoDB does not create them.
InnoDB: Error: could not open single-table tablespace file ./shopping/migrations.ibd
InnoDB: We do not continue the crash recovery, because the table may become
InnoDB: corrupt if we cannot apply the log records in the InnoDB log to it.
InnoDB: To fix the problem and start mysqld:
InnoDB: 1) If there is a permission problem in the file and mysqld cannot
InnoDB: open the file, you should modify the permissions.
InnoDB: 2) If the table is not needed, or you can restore it from a backup,
InnoDB: then you can remove the .ibd file, and InnoDB will do a normal
InnoDB: crash recovery and ignore that table.
InnoDB: 3) If the file system or the disk is broken, and you cannot remove
InnoDB: the .ibd file, you can set innodb_force_recovery > 0 in my.cnf
InnoDB: and force InnoDB to continue crash recovery here.
161006 20:08:24 mysqld_safe mysqld from pid file /Applications/MAMP/tmp/mysql/mysql.pid ended
161006 20:15:32 mysqld_safe Starting mysqld daemon with databases from /Applications/MAMP/db/mysql56
2016-10-06 20:15:32 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2016-10-06 20:15:32 0 [Note] /Applications/MAMP/Library/bin/mysqld (mysqld 5.6.28) starting as process 8447 ...
2016-10-06 20:15:32 8447 [Warning] Setting lower_case_table_names=2 because file system for /Applications/MAMP/db/mysql56/ is case insensitive
2016-10-06 20:15:32 8447 [Note] Plugin 'FEDERATED' is disabled.
2016-10-06 20:15:32 8447 [Note] InnoDB: Using atomics to ref count buffer pool pages
2016-10-06 20:15:32 8447 [Note] InnoDB: The InnoDB memory heap is disabled
2016-10-06 20:15:32 8447 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2016-10-06 20:15:32 8447 [Note] InnoDB: Memory barrier is not used
2016-10-06 20:15:32 8447 [Note] InnoDB: Compressed tables use zlib 1.2.8
2016-10-06 20:15:32 8447 [Note] InnoDB: Using CPU crc32 instructions
2016-10-06 20:15:32 8447 [Note] InnoDB: Initializing buffer pool, size = 128.0M
2016-10-06 20:15:32 8447 [Note] InnoDB: Completed initialization of buffer pool
2016-10-06 20:15:32 8447 [Note] InnoDB: Highest supported file format is Barracuda.
2016-10-06 20:15:32 8447 [Note] InnoDB: The log sequence numbers 1802852 and 1802852 in ibdata files do not match the log sequence number 1804211 in the ib_logfiles!
2016-10-06 20:15:32 8447 [Note] InnoDB: Database was not shutdown normally!
2016-10-06 20:15:32 8447 [Note] InnoDB: Starting crash recovery.
2016-10-06 20:15:32 8447 [Note] InnoDB: Reading tablespace information from the .ibd files...
2016-10-06 20:15:32 8447 [ERROR] InnoDB: Attempted to open a previously opened tablespace. Previous tablespace mysql/slave_master_info uses space ID: 4 at filepath: ./mysql/slave_master_info.ibd. Cannot open tablespace shopping/migrations which uses space$
2016-10-06 20:15:32 7fff7b87b000 InnoDB: Operating system error number 2 in a file operation.
InnoDB: The error means the system cannot find the path specified.
InnoDB: If you are installing InnoDB, remember that you must create
InnoDB: directories yourself, InnoDB does not create them.
InnoDB: Error: could not open single-table tablespace file ./shopping/migrations.ibd
InnoDB: We do not continue the crash recovery, because the table may become
InnoDB: corrupt if we cannot apply the log records in the InnoDB log to it.
InnoDB: To fix the problem and start mysqld:
InnoDB: 1) If there is a permission problem in the file and mysqld cannot
InnoDB: open the file, you should modify the permissions.
InnoDB: 2) If the table is not needed, or you can restore it from a backup,
InnoDB: then you can remove the .ibd file, and InnoDB will do a normal
InnoDB: crash recovery and ignore that table.
InnoDB: 3) If the file system or the disk is broken, and you cannot remove
InnoDB: the .ibd file, you can set innodb_force_recovery > 0 in my.cnf
InnoDB: and force InnoDB to continue crash recovery here.
161006 20:15:32 mysqld_safe mysqld from pid file /Applications/MAMP/tmp/mysql/mysql.pid ended
I had the same issue after upgrading from MAMP 3.x to 4.x
I just went to:
edit template in mamp pro and edited the my.cnf template. I added just this line to the file:
innodb_force_recovery = 1
now everything is working and mysql is starting again.
| common-pile/stackexchange_filtered |
Shadows black even when a light is on top of it
I'm building a game engine in ThreeJS, and I'm having an issue with lighting.
Basically I'm building a grid-based RPG, each cell(dimension is 10 x 10) contains a floor and optionally a ceiling. I want the ceiling to cast a soft shadow on the floors(to simulate open environments as well as dungeons). I have 3 lights to achieve this.
This is a basic diagram, showing the 3 lights, the floor are built with 4 meshes, the ceiling are 2 meshes, using LambertMaterial
I'm a beginner in the topic of lights/shadows in ThreeJS...basically I notice the shadow projected is entirely black, even when the lower PointLight is there.(On the 2 meshes on the "ceiling", only the mesh nearest to the camera is casting shadows, for the purpose of this example). How can I achieve a more "enlightened" shadow?
Also, I'm noticing several artifacts being generated in the meshes...can this be produced by the used of several meshes instead of only two, one for the ceiling and other for the floor? I'm doing this with one mesh per floor cell because I want to have more than one texture on the map.
Well, I've ditched three.js, ported the code to http://www.babylonjs.com/ and follow the MUCH better documentation and tutorials I've found there. Everything worked as a charm.
| common-pile/stackexchange_filtered |
Generating PDF Succesfully but I failed when I added Qr Code
I have google form with response as in table (spreadsheet) below.
This script can't generate qr code. QR code formula in header so it is automatically generate qr code in spreadsheet in column B with data from column D.I don't know how to solve it.
var docTemplate = "doc ID";
var docName = "Vehicle check with images";
function onFormSubmit(e) {
var replaceTextToImage = function(body, searchText, fileId) {
var width = 300; // Please set this.
var blob = DriveApp.getFileById(fileId).getBlob();
var r = body.findText(searchText).getElement();
r.asText().setText("");
var img = r.getParent().asParagraph().insertInlineImage(0, blob);
var w = img.getWidth();
var h = img.getHeight();
img.setWidth(width);
img.setHeight(width * h / w);
}
//Get information from form and set as variables
var email_address =<EMAIL_ADDRESS> var qrCode = e.values[1].split("=")[3];//I want to try
var empName = e.values[2];
var empId = e.values[3];
var photo = e.values[4].split("=")[1];
// Get document template, copy it as a new temp doc, and save the Docโs id
var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName+' for '+empName)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the documentโs body section
var copyBody = copyDoc.getBody();
replaceTextToImage(copyBody, 'qrcode', qrCode);//problem could not be generated
copyBody.replaceText('name', empName);
copyBody.replaceText('id', empId);
replaceTextToImage(copyBody, 'photo', photo);
copyDoc.saveAndClose();
var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");
var subject = "sample attachment file";
var body = "sample text: " + empName + "";
MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf});
DriveApp.getFileById(copyId).setTrashed(true);
}
Timestamp
={"QR CODE";ARRAYFORMULA(IF(D2:D<>"";IMAGE("https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl="&D2:D);))}
Name
Id
Photo
10/07/2021 8:35:24
QR CODE
Robert
1234
https://drive.google.com/open?id=14SAL5EK8tqOESgZyAayScbTqhSEE89Wa
Do you see QR-codes or your Spreadsheet? Perhaps it makes sense to replaced it with simpler variant (for 'B2' cell): =IMAGE("https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl="&D2)
Yes. I see QR code in my spreadsheet using array formula. When I used =IMAGE("https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl="&D2) I had to drag it down. Event though, I need pdf file as attachment after someone submitting google form.
Probably the cause is here: var blob = DriveApp.getFileById(fileId).getBlob(); You can insert this way a file. A photo from Drive, for instance. But I suspect that the qrCode = e.values[3].split("=")[1]; doesn't return fileID of a file, since you nave no such file on Drive at all. I don't know what exactly it returns. URL?. Text? Probably you need to get the blob of the QR code another way, via UrlFetchApp.fetch(url).getBlob(). See my example.
Can you show what exactly contains the variable qrCode when you send it into the function replaceTextToImage()? Is it a fileID of your qr code? Since the function takes file id.
I didn't manage to reproduce the problem. I repeated all the steps more or less and it works as intended. Here is the minimal reproducible example.
const doc_template_ID = 'template ID';
const ss_ID = 'spreadsheet ID';
const email_address =<EMAIL_ADDRESS>
function make_doc_and_send_it_as_pdf() {
// get data from spreadsheet
const sheet = SpreadsheetApp.openById(ss_ID).getSheets()[0];
const QR_text = sheet.getRange('B1').getValue();
// make copy of the template and make changes in the doc
const doc_file = DriveApp.getFileById(doc_template_ID).makeCopy('QR_code');
const doc_ID = doc_file.getId()
const doc = DocumentApp.openById(doc_ID);
var body = doc.getBody();
body = body.replaceText('{{text}}', QR_text);
// insert a pic of the QR code
const url = "https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=" + QR_text;
const resp = UrlFetchApp.fetch(url);
const image = resp.getBlob();
replaceTextToImage(body, '{{QR}}', image);
doc.saveAndClose();
// send the doc via email as pdf
var pdf = doc_file.getAs("application/pdf");
var subject = "QR pdf";
var body = "sample text";
MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf});
doc_file.setTrashed(true);
}
// modified Tataike's function from here
// https://tanaikech.github.io/2018/08/20/replacing-text-to-image-for-google-document-using-google-apps-script/
// now it takes image (blob) instead of fileId
function replaceTextToImage(body, searchText, image) {
var next = body.findText(searchText);
if (!next) return;
var r = next.getElement();
r.asText().setText('');
r.getParent().asParagraph().insertInlineImage(0, image);
return next;
};
My spreadsheet looks like this:
My doc template looks like this:
The PDF in email look like this:
It gets data from spreadsheet, makes a copy of doc template, changes text in the doc, inserts image of QR code in the doc (it replaces all the paragraph that contains '{{QR}}', I left it as it was, probably it can replace just a word in the paragraph)), and sends the doc via mail as PDF.
In your code, probably you need to change the function replaceTextToImage() this way:
var replaceTextToImage = function(body, searchText, blob) {
var width = 300; // Please set this.
var r = body.findText(searchText).getElement();
r.asText().setText("");
var img = r.getParent().asParagraph().insertInlineImage(0, blob);
var w = img.getWidth();
var h = img.getHeight();
img.setWidth(width);
img.setHeight(width * h / w);
}
It makes the function to take a blob instead of a fileId.
And to change these two lines:
var qrCode = e.values[3].split("=")[1];
var photo = e.values[4].split("=")[1];
with this:
var qrCode = UrlFetchApp.fetch(e.values[3].split("=")[1]).getBlob();
var photo = DriveApp.getFileById(e.values[4].split("=")[1]).getBlob();
I suppose that e.values[3].split("=")[1] contains a text of QR code, and e.values[4].split("=")[1] contains file ID. But I can be wrong.
I'm sure you can add installabe trigger onFormSubmit() to my code this way https://stackoverflow.com/questions/26037556/form-answer-spreadsheet-onchange-trigger And it will work. It will send email with pdf (with qr code) after submit form.
| common-pile/stackexchange_filtered |
free sms gateway for .Net client
Does anyone know any good free sms gateway which can be accessed using the C# client?
I also need some C# sample wrappers for interacting with the sms gateway for sending and receiving the SMSs.
Thanks in advance.
S.
Ive done some of my own searching in the past, and im curious about this myself
As far as "free" goes, nothing reliable (No surprise there) but there are some very cheap options, as listed bellow
Have a look at these gateways:
http://www.intellisoftware.co.uk/sms-gateway/
http://www.ozekisms.com/
http://www.redoxygen.com/developers/c-sharp/
he asked for a free gateway, all those companies you posted there website URL are not free!
You could also use https://codecanyon.net/item/wordpress-sms-gateway/16935285
From what I understand, it's a full SMS Gateway you can install in your WordPress website and use from any other website with CURL. The SMS messages are sent by Android devices you connect to your WordPress website.
| common-pile/stackexchange_filtered |
How to easily perform this random matrix multiplication with numpy?
I want to produce 2 random 3x4 matrices where the entries are normally distributed, A and B. After that, I have a 2x2 matrix C = [[a,b][c,d]], and I would like to use it to produce 2 new 3x4 matrices A' and B', where A' = a A + b B, B' = c A + d B.
In order to produce the matrices A and B, I was thinking to use this line of code:
Z = np.random.normal(0.0, 1.0, [2,3, 4])
But, given the matrix C, I don't know how to use simple Numpy vectorization to achieve the matrices A' and B' or, equivalently, a 2x3x4 array containing A' and B'. Any idea?
I think you can use np.einsum
np.einsum("ij, jkl -> ikl", C, Z)
where "ij, jkl -> ikl" specifies the contraction pattern, where i and j are the indices of the C matrix, and j, k, and l are the indices of the Z array.
Example
Given dummy data like below
np.random.seed(0)
Z = np.random.normal(0.0, 1.0, [2, 3, 4])
C = [[1,2],[3,4]]
You will see
print("AB_prim(einsum): \n", np.einsum("ij, jkl -> ikl", C, Z))
shows
AB_prim(einsum):
[[[ 3.2861278 0.64350724 1.86646445 2.90824185]
[ 4.85571614 -1.38759441 1.57622382 -1.85954869]
[ -5.20919848 1.71783569 1.87291597 -0.03005653]]
[[ 8.33630794 1.68717169 4.71166688 8.05737691]
[ 11.57899026 -3.75246669 4.10253606 -3.87045458]
[-10.52161582 3.84626989 3.88987551 1.39416044]]]
and
A, B = Z[0], Z[1]
print("A_prim: \n", C[0][0] * A + C[0][1] * B)
print("B_prim: \n", C[1][0] * A + C[1][1] * B)
shows
A_prim:
[[ 3.2861278 0.64350724 1.86646445 2.90824185]
[ 4.85571614 -1.38759441 1.57622382 -1.85954869]
[-5.20919848 1.71783569 1.87291597 -0.03005653]]
B_prim:
[[ 8.33630794 1.68717169 4.71166688 8.05737691]
[ 11.57899026 -3.75246669 4.10253606 -3.87045458]
[-10.52161582 3.84626989 3.88987551 1.39416044]]
Thank you @ThomasIsCoding, it is indeed a very useful function!
You can try this:
import numpy as np
np.random.seed(0)
Z = np.random.normal(0.0, 1.0, [2, 3, 4])
C = np.array([[1,2],[3,4]])
AB = (Z.T @ C.T).T
print(AB)
It gives:
[[[ 3.2861278 0.64350724 1.86646445 2.90824185]
[ 4.85571614 -1.38759441 1.57622382 -1.85954869]
[ -5.20919848 1.71783569 1.87291597 -0.03005653]]
[[ 8.33630794 1.68717169 4.71166688 8.05737691]
[ 11.57899026 -3.75246669 4.10253606 -3.87045458]
[-10.52161582 3.84626989 3.88987551 1.39416044]]]
Hi @bb1! Thank you for this! Can you please explain me how does "@" work here? And what Z.T and C.T are? Sorry, I'm new to these
| common-pile/stackexchange_filtered |
Which Democratic members of Congress continue to support US military aid to Israel?
A Politico article from April 4th, "A blinking red light for Israel in American politics",
opens with the observation that US leadership is "nearly" out of patience.
The Politico article went on to say something that would've been unimaginable just a few months ago:
A House Democrat who didnโt want to run afoul of the White House added that Biden is โfeeling a ton of pressure from outside of his inner circle. Most of us are fed up, and I think the bottom is going to fall out on support for additional Israel security funding, at least in the Democratic caucus.โ
Biden speaking to the Israeli PM, again asked Israel to dial it down a bit. However, this isn't the first such request. The killing of aid workers has been going on for months in full view of the media, approaching 200 killed, per the UN Secretary General.
If Netanyahu continues to blow off requests from Biden, the record of US Congressional support or opposition could take on more political significance - especially if the humanitarian crisis continues on the current trend.
Is there any organization (on either side of the issue) tracking where members of US Congress stand on this?
Alternatively, which Democratic members of Congress have taken a stand on the issue, in light of recent developments?
I would wager that before the recent months (and certainly before October) military aid for Israel in Congress was universal. So it would actually be a much smaller list showing which congressmen are opposed to aid. The same can be said for Ukraine, etc.
Most of those killed previously were UNRWA so Palestinians. However with Israel rejecting UNRWA cooperation altogether as supporters of terrorism, the more Western-staffed ones took over. Which is why the WCK strikes killed 1 Palestinian (Dubai resident apparently though), 3 Brits (the 'security team'), 1 US-Canada dual citizen, Australian, 1 Pole. https://edition.cnn.com/2024/04/03/middleeast/world-central-kitchen-workers-gaza-israel-strike-intl/index.html
@thegodsfromengineering - that's certainly part of why the outrage finally broke now. Though Israel has occasionally killed US citizens too, typically young activists of unremarkable origin. The WCK head is apparently in the circle of Biden's courtiers. That's tangential to my interest in action in Congress though. IMO really the only pressure point US policymakers have, that's exposed to the public.
Well, the most criticism seem to come from Jon Stewart. https://youtu.be/RkwgnlPRdHg?t=346 Yeah Bernie Sanders too.
After the Iranian counter-strike that was widely condemned in the West (brilliant move by Netanyahu to copy Trump in Damascus), a lot more Dems no longer have objections to arms aid to Israel than last week. https://www.voanews.com/a/israel-iran-conflict-eases-pressure-on-biden-to-condition-aid/7577207.html Will know the exact numbers in the vote tomorrow.
@thegodsfromengineering - yes, unfortunately. Netanyahu's gambit got the Biden admin to give up the pretense of being interested in Gaza, and if I were to take a wild guess, also to give up ambitions to get rid of Netanyahu personally. The Israel and Ukraine aid deal was already made a while ago I think - I think they were waiting for Zelensky's government to pass the mobilization law to round up the next half million men and kick that can down the road another year.
Many people seem to fall for islamic propaganda, even politicians in Congress or elsewhere.
The kill ratio is ca. 11000 terrorists to ca. 23000 civilians in Gaza until mid April.
This ratio is completely normal - if not even high - for wars in Middle East against terrorists, f.e. the civilian death ratio for the re-conquer of Mosul was in the order of 1 to 4 or worse. The reason of huge delays was claimed to be to avoid civilian casualties in Mosul.
UNRWA members seemed to directly support the terrorists in Gaza, but still Israel most likely did not systematically attack aid workers.
The numbers are in as of 20 April 2024. In the U.S. Senate, all Democrats voted in support of military aid to Israel with the exceptions of two Democrats, Sens. Jeff Merkley and Peter Welch and Independent Sen. Bernie Sanders. Despite those three votes against, all of the other 48 Democrat senators voted in favor.[1]
Military aid to Israel was voted on and approved in the "lower house" of Congress, the House of Representatives. There were 37 of 213 Democrats of who didn't support military aid to Israel but it passed 366 - 58.[2]
The following 37 Democrat House members voted against: Reps. Becca Balint (D-VT), Don Beyer (D-VA), Earl Blumenauer (D-OR), Jamaal Bowman (D-NY), Cori Bush (D-MO), Greg Casar (D-TX), Joaquin Castro (D-TX), Judy Chu (D-CA), Mark DeSaulnier (D-WA), Lloyd Doggett (D-TX), Maxwell Frost (D-FL), John Garamendi (D-CA), Chuy Garcia (D-IL), Al Green (D-TX), Jonathan Jackson (D-IL), Pramila Jayapal (D-WA), Hank Johnson (D-GA), Ro Khanna (D-CA), Dan Kildee (D-MI), Barbara Lee (D-CA), Summer Lee (D-PA), Jim McGovern (D-MA), Mark Pocan (D-WI), Chellie Pingree (D-ME), Alexandria Ocasio-Cortez (D-NY), Ilhan Omar (D-MN), Ayanna Pressley (D-MA), Delia Ramirez (D-IL), Jamie Raskin (D-MD), Mark Takano (D-CA), Rashida Tlaib (D-MI), Bennie Thompson (D-MS), Jill Tokuda (D-HI), Nydia Velazquez (D-NY), Maxine Waters (D-CA) and Bonnie Watson Coleman (D-NJ) voted against the bill.
Sens. Jeff Merkley and Peter Welch and Independent Sen. Bernie Sanders all continue to support defensive aid to Israel. It's the offensive aid they oppose with respect to the ongoing Gaza operations.
On March the 5th some 30 House Democrats signed a letter to Biden expressing concern at the situation in Gaza and putting forward the view that any attack on Rafah would likely to be a contravention of international law. That is roughly 30 from amongst 212 (I'm not counting Tom Suozzi as he has yet to be sworn in). So there is clearly still support for Israel amongst Democrats.
Of course, the letter was signed before famine, caused by the Israeli blockade, really started to take a hold in Gaza and before Israel killed 7 aid workers, 6 of whom were non-Palestinian and one of who was a US citizen. These events are likely to have swayed a few more Democrats, but I imagine there are probably still many who support Israel.
"Expressing concern" is barely related to "opposing military support for Israel". Just saying.
Question:
Which Democratic members of Congress continue to support US military aid to Israel?
Short Answer:
There are less than a handful of Democrats who don't support miliary aid to Israel across the executive and legislative branches. It's really not even being discussed. The only thing being paused, is certain offensive weapons like the 2000lb bombs and they are only being "paused", until Israel provides a "creditable plan" on how they will use this munition in an urban environment while safeguarding civilians. Like that is possible.
Longer Answer
Both Democrats and Republicans in Congress and the Senate are strongly pro-Israel. Almost no American politicians wish to discontinue military aid to Israel, it's not currently being discussed with any seriousness. The Question should read, with creditable American Reports of atrocities, with UN reports suggesting genocide, with Israel claiming their leaders are about to face indictment by the ICC and with numerous Israeli government officials calling for genocide, which pro-Israeli American political leaders wish to curb 2000 lb bombs shipments to Israel unless the Israeli's express a "creditable plan" to avoid civilians.
Almost no American politicians are suggesting eliminating all military aid to Israel in either party; especially defensive aid. The only thing being "paused" is the 2000 lb bombs. Denying Israel, this invaluable weapon against the densely packed overwhelming civilian urban landscape. Nothing says targeting Hamas like a weapon which can level a city block (blast radius 35 meters). Of which the Israeli's have dropped scores of them already.
Eventually:
the House's actions during a rare Saturday session put on display some cracks in what generally is solid support for Israel within Congress. Recent months have seen progressive Democrats express anger with Israel's government and its conduct of the war in Gaza.
Saturday's vote, in which the Israel aid was passed 366-58, had 37 Democrats and 21 Republicans in opposition.
Note that this was after the widely condemned in the West Iranian [counter-]strike on Israel, and its aftermath, all of which may have swayed some votes according to FDD & VOA.
The first source also gives the tally for the Ukraine vote as as 311-112; all of the nays were Republican on that. So at least in Congress overall, aiding Israel is still more popular than aiding Ukraine, but among the Democrats that trend is reversed.
N.B. related Q posted by someone else as I was writing this https://politics.stackexchange.com/questions/87097/constitutionality-of-house-of-congress-passing-separate-bills-and-then-combining#87097 although that one is not about vote tallies.
| common-pile/stackexchange_filtered |
How do I implement a wait_for function into my command?
I am trying to make a bot that will pick a word from a text file and then scramble it and then the user unscrambles the word and types it. But I do not know how to implement the wait_for function into the command.
@client.command()
async def start(ctx):
await ctx.send('Time for chaos')
Unscrambled_word = random.choice(list(open('C:\\Users\\user\\Desktop\\Discord Bots\\Fake Speedjar\\words.txt')))
I suggest reading the documentation here
It comes with a good simple example.
There is another library called dpytools that has a helper (wait_for_author) for this kind of simple cases you can check it here
Basically the wait_for method will wait for something and then return it to you. In this case a "message".
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel
message = await client.wait_for('message', check=check)
The check function takes only the awaited object(s) and returns a bool indicating if the message Is what you're expecting.
Please check the documentation for further information.
| common-pile/stackexchange_filtered |
Passing Function Pointers to Native functions as parameters
I am working with the android NDK trying to use an existing library to build an Application.
The following function is declared in the library...
BYTE __stdcall InitRelay(fp_setbaud _setbaud, fp_get _get, fp_put _put, fp_flush _flush, fp_delay _delay){
These are the declarations for the parameters passed to InitRelay...
typedef void (__stdcall *fp_setbaud)(WORD);
typedef short (__stdcall *fp_get)(WORD);
typedef void (__stdcall *fp_put)(BYTE);
typedef void (__stdcall *fp_flush)(void);
typedef void (__stdcall *fp_delay)(WORD);
typedef short (__stdcall *fp_ProgressUpdate)(WORD);
I've been to this thread, but still am not sure what to do. The difference between what I am doing and what they are doing, is that I want to call a native function in C that requires a function pointer as a parameter.
I was considering writing a wrapper function in the Native code, does that sound right? My main problem is that I cannot change the native code i've been given, but I can add new functions. I know people will ask me to post my java code, so I will, but it is literally useless. It is just a method call with parameters that currently don't make sense to java.
// InitRelay
InitRelay( fp_setbaud _setbaud, fp_get _get, fp_put, fp_flush _flush, fp_delay _delay );
Yes, write native wrappers. You will need to do this anyway as jni has very particular naming requirements for the interface functions. Non-trivial data types will also require copy conversion from/to jni references.
Process-level static state in the library can also give you a lot of headaches, since android does not link the lifetime of a process to a user perceptible session lifetime. Android will also quite happily put multiple distinct sessions into the same process.
Thank you, I actually have no experience in C, and have only been working android for about five weeks, is there anywhere you know of I can learn more about this situation?
Well, start by building the hello-jni example from the ndk samples, and look at the function naming and what it has to do to create a string that java can use.
Yeah, I've done it. I'm comfortable calling functions from the native code in my Android code. What I'm not comfortable is writing wrappers in C, but I guess that's a very broad topic.
Basically you need to create things that are called in a jni-compatible way, and call the native library in the way it expects. That is fairly straightforward on a detail level; the real challenge will be figuring out if an overlall plan of mapping one onto the other is workable, or if you may need to consider a different overall mapping.
Not asking you to write my code for me, but if you find the time to edit the post and add some sort of example code for the wrapper, I'd really appreciate it.
| common-pile/stackexchange_filtered |
Recovering files using extundelete
I've accidentally deleted some files in my package managers's cache after an update (so I've deleted all packages that were downloade and unforunately they weren't even installed).
Here's what I've done:
Booted to a Ubuntu System that's on the same HDD as the Arch system.
Now that I booted into Ubuntu the root partition of the Arch System is unmounted so, extundelete gave me this output:
$ sudo extundelete /dev/sda1 --restore-directory /var/cache/pacman/pkg/
WARNING: Extended attributes are not restored.
Loading filesystem metadata ... 232 groups loaded.
Loading journal descriptors ... 30722 descriptors loaded.
Searching for recoverable inodes in directory /var/cache/pacman/pkg/ ...
9385 recoverable inodes found.
Looking through the directory structure for deleted files ...
9385 recoverable inodes still lost.
No files were undeleted.
Is there anything I can do about it? Or am I completely screwed?
Was the disk mounted when you ran extundelete?
@terdon no, if it was, it'd have error'd out. I ran this through another Linux system not on Arch.
OK just asking cause I saw some emails on the extundelete mailing list that gave the N found and N still lost message on mounted partitions. Could you [edit] your question and explain exactly what you have done? I.e. logged in through ssh from another machine, unmounted the / partition on a running system and ran extundelete?
I did my best to explain. Hope this is enough
From the author of extundelete:
I guess that it is not finding a way to link the inodes with a file name, in which case the --restore-all method is your best shot at getting your files back.
https://sourceforge.net/p/extundelete/mailman/message/30159985/
So in your case, you would instead run:
sudo extundelete /dev/sda1 --restore-all
Although from my experience the output is deceptive because the files (inodes) that are still "lost" are for the whole partition and not just for the directory you specified, meaning that most of what it's able to restore has already been restored. But it doesn't hurt to try --restore-all since it may find some file fragments that it doesn't know the path for.
| common-pile/stackexchange_filtered |
How to set Timestep in vtk-file(s) to visualize in Paraview
Sorry this might be quite a simple question but I'm new to this so I'll just ask straight away.
I want to visualize data in paraview, therefore I created a vtk file containing Structured Points with Point data= Vectors.
This works good for one timestep but now I want to append data or create other files for further time steps
I found a way to do so via .csv files (https://www.paraview.org/Wiki/ParaView/Data_formats#CSV_time_series )
but not with .vtk files
Thank you for your help :)
how do you "create a vtk file" ?
@Mathieu Westphal: According to this User Guide:
https://www.vtk.org/wp-content/uploads/2015/04/file-formats.pdf
fair engouh. afaik .vtk can be opened as file series in ParaView without any problem. See attached :
https://wetransfer.com/downloads/4a893ab412ff919df2ecb7f6e138beaf20180606115943/b67688fe44c2b9ba8b9ae4906d217e9020180606115943/72c135
please note that ParaView can open other formats that natively supports timesteps.
I have answered this question in another SO question.
I think I found an answer:
It is now possible to animate legacy VTK file series. ParaView recognizes file series named using certain patterns including:
fooN.vtk
foo_N.vtk
foo-N.vtk
foo.N.vtk
...
Where N is an integer (with any number of leading zeros).
https://www.paraview.org/Wiki/Animating_legacy_VTK_file_series
| common-pile/stackexchange_filtered |
Extract part of sql query (numbers) using regex
I need to extract part of sql query (saved in file) - numbers in section IN. But sql query also has other numbers (but not in section IN) What pattern should i use?
Pattern '(\d+)' extract more numbers that i need (from other part of sql query).
" IN ('7',
'9',
'11',
'13',
'14',
'24')"
What is the regex flavor? (?:\G(?!^)',\s*'|\bIN\s*\(')\K\d+ might do the job, see https://regex101.com/r/4muX0O/1
Which dbms are you using?
You can use
(?:\G(?!^)',\s*'|\bIN\s*\(')\K\d+
(?<=\bIN\s*\([^()]*)\d+
See regex demo #1 and regex demo #2.
Regex #1 (compliant with Boost, PCRE, Onigmo regex libraries):
(?:\G(?!^)',\s*'|\bIN\s*\(') - end of the previous match and then ', ,, zero or more whitespace and then a ', or a whole word IN followed with (' substring
\K - match reset operator that discards the currently matched text
\d+ - one or more digits
Regex #2 (compliant with JavaScript ECMAScript 2018+, .NET, PyPi regex):
(?<=\bIN\s*\([^()]*) - a location that is immediately preceded with
\bIN - whole word IN
\s* - zero or more whitespaces
\( - a ( char
[^()]* - zero or more chars other than ( and )
\d+ - one or more digits.
| common-pile/stackexchange_filtered |
One field of the two will be required in Model
I have a situation where I want to be in the model was required only one field of the two.
public int AutoId { get; set; }
public virtual Auto Auto { get; set; }
[StringLength(17, MinimumLength = 17)]
[NotMapped]
public String VIN { get; set; }
If someone entered the vin, it is converted in the controller on the AutoID. How to force the controller to something like this work?
public ActionResult Create(Ogloszenie ogloszenie) {
information.AutoId = 1;
if (ModelState.IsValid)
{
...
}..
sorry, hmm I have a form. In this form, the two fields. User has to fill one of them. Filling one will be required. One field shows the AutoID and the other on the VIN. When the user fills AutoID, everything is ok. When complete VIN, ModelState.IsValid is false: (Before checking ModelState AutoID field is completed.
You can implement a custom validation attribute that will check presence of either of the required fields.
more on custom validatio attributes: How to create custom validation attribute for MVC
Try to use this approach:
controller:
public ActionResult Index()
{
return View(new ExampleModel());
}
[HttpPost]
public ActionResult Index(ExampleModel model)
{
if (model.AutoId == 0 && String.IsNullOrEmpty(model.VIN))
ModelState.AddModelError("OneOfTwoFieldsShouldBeFilled", "One of two fields should be filled");
if (model.AutoId != 0 && !String.IsNullOrEmpty(model.VIN))
ModelState.AddModelError("OneOfTwoFieldsShouldBeFilled", "One of two fields should be filled");
if (ModelState.IsValid)
{
return null;
}
return View();
}
view:
@using(Html.BeginForm(null,null,FormMethod.Post))
{
@Html.ValidationMessage("OneOfTwoFieldsShouldBeFilled")
@Html.TextBoxFor(model=>model.AutoId)
@Html.TextBoxFor(model=>model.VIN)
<input type="submit" value="go" />
}
| common-pile/stackexchange_filtered |
C/C++ Sockets HTTP Request: Connection reset by peer
I'm trying write a C++ program that can make GET requests to a given URL with sockets to learn more about how HTTP works. I've coded up what I think is the basic structure of what I should be doing:
Create a socket
Connect the socket to host
Send request byte by byte
Received response byte by byte
I get this error most of the time when I'm reading the response from the server: ERROR reading response from socket Connection reset by peer. This is getting triggered by an if statement in the while loop where I'm reading the response when read returns -1. I'm using SOCK_STREAM.
How should I change the way I'm receiving the response/the type of socket I'm using to prevent this from happening?
The first thing I'd try is using Wireshark to make sure you're actually sending the right data
You need a space between the route and HTTP/1.1
There is a space, sorry it isn't clear in how I'm constructing it there but it gets added when I parse the route from the URL.
The GET requests always send correctly (don't return status 400), but the server usually closes the connection before I can finish receiving all of the data.
In that case please provide a [mre]
Done; I had trouble getting it working in an online C++ compiler, but there isn't that much code if you'd like to run it on your own machine. Thank you!
"but the server usually closes the connection before I can finish receiving all of the data." - How do you know where "all of the data" ends? There is nothing in your code which computes where the end of the response should be. See this part in the standard how to compute the expected length of the message body based on the information from the response header. And note that it might be much easier to use HTTP/1.0 instead of HTTP/1.1 since HTTP/1.0 is the simpler protocol.
As the code currently is it already fails for me when sending. This is because you are trying to send MAX_CONTENT_LENGTH bytes instead of only the length of message.
With the latest edit the question now contains no useful details to tackle the problem. There is no code to reproduce the problem. This might be even worse than the previous edit which had at least code even though this one failed with different problems than described.
| common-pile/stackexchange_filtered |
paypal IPN - 'Pending' status when buyer is "USD" and seller is "Euro" account
I am working on PaypalIPN, i have seen that if my buyer and seller both have same currency account,It is verify automatically.
if any one of them having different currency account, it is not verify and i have to do from user business account manually?
why it is so?
can some one explain me the real time case?
It's a PayPal Profile setting. Set 'Website Preferences' to accept and convert all currencies automatically, or open a USD balance.
Thanks robert,your comment guide me about the setting. Please check the answer, so you get the answer.
I found the solution.
Thanks to ROBERT's comment. It guide me about the settings to do.
The answer is Go to Business acount profile -> More Options -> Payment Receiving Option.
Make the "Block payments sent to me in a currency I do not hold:" -- set this to NO.
| common-pile/stackexchange_filtered |
text on xlabel is cutted off in matplotlib
I want to plot this data:
datetime
2021-12-06 00:00:00 40354
2021-12-06 00:05:00 94557
2021-12-06 00:10:00 53314
2021-12-06 00:15:00 91334
2021-12-06 00:20:00 94168
2021-12-06 00:25:00 92049
2021-12-06 00:30:00 89400
2021-12-06 00:35:00 86499
2021-12-06 00:40:00 87517
I use
plt.plot(data)
plt.xticks(rotation=90)
plt.axis('tight')
plt.savefig('plot.png')
plt.close()
But the x label is cutted off :
I went through this question X-axis Label Gets Cut Off Of Graph - Python Matplotlib and I tried to use plt.tight_layout() and plt.savefig('plot.png', bbox_inches='tight') but it did not help. Can you help me please?
You can try this
import numpy as np
from datetime import datetime
from matplotlib import pyplot as plt
date_t = [str(datetime(2021,12,6,0,item,0,0)) for item in range(0,50,5)]
y_vals = np.random.randint(100,200,len(date_t))
fig,ax = plt.subplots(figsize=(8,6))
ax.plot(y_vals)
ax.set_xticks(range(len(y_vals)))
ax.set_xticklabels(date_t)
ax.tick_params(axis='x',labelrotation=90)
The output is like
| common-pile/stackexchange_filtered |
Java classloader issue in Spring Boot
I am seeing a class-loader issue while deploying Spring Boot application.
All the library jars are inside the single Spring Boot jar. I have verified that using jar -tf command.
Now, I ran the application using java -verbose -jar, but it's facing a weird classloader issue.
In the logs, I am able to see the class already loaded:
java.lang.NoClassDefFoundError: Could not initialize class com.asd.myconnector.MyPPManager
at com.asd.db.datamanager.MySystemDataManager.getProjectSystemProperties(SystemDM.java:195) ~[core-0.0.1.jar!/:na]
and just few lines above, I am able to see this class already loaded:
[Loaded com.asd.myconnector.MyPPManager from jar:file:/home/abhay/myconnections-0.1.15.jar!/BOOT-INF/lib/core-0.0.1.jar!/]
Can anyone help any pointers where I can look into?
Thanks and Regards,
Abhay Dandekar
| common-pile/stackexchange_filtered |
Recommendable Ruby gems for form builder and PDF generator
I'm new to Rails and trying to build a web app which has forms to let users answer those and migrate the data what users answered to actual PDF file.
Any recommendable gems or other web-app frameworks for this usage?
| common-pile/stackexchange_filtered |
How to pass passphrase of ssh in bash script?
I am discovering the bash scripting. I need to write a bash script to automatically connects my remote server with ssh. I am using MACOSX.
I were able to do with sudo as below
echo <root_pass> | sudo -S ls
However all my attempts were unsuccessful to pass the passphrase.
I have tried these below already:
echo <my_passphrase> | sudo ssh -i /Users/path_to_ssh_public_key/ssh <my_username>@<remote_ip>
sudo ssh -i /Users/path_to_ssh_public_key/ssh <my_username>@<remote_ip> <<< echo <my_passphrase>
The command uses "-i" to get public key from a custom folder
Any help is welcome...
EDIT: I want to fully control the terminal outputs and inputs. I don't want to use sshpass or declare any variables to the shell.
ssh reads the passphrase from /dev/tty rather than stdin so echo ... | ssh ... would not work here. you can use tools like [tag:expect] (for Tcl), [tag:pexpect] (for Python) or my sexpect (for shells).
Or you can use sshpass, which was designed for exactly this purpose. Or better yet, stop using passwords and configure ssh key-based authentication.
I see, thanks for info @larsks . So let me know if I can feed dev/tty in c program or python or even bash script as providing the password.
@cachius no it is not, actually I have seen it before, but my intention is to take control the terminal fully in a bash script. But the issue you mentioned suggests me to use sshpass or some other extra variable declaring to access ssh.
BTW, I wonder why people downgrade the question immediately if they do not like it :D rather than asking why he asked this question while there are questions similar
For your Info After voting one can only change the vote after the post was edited. So good you did
Not my downvote, but this type of question is very common, and your question contains no indication that you searched existing questions before asking.
As others mentioned in comments, you can use sshpass like so:
sshpass -p !4u2tryhack ssh<EMAIL_ADDRESS>
But using .ssh/config file is much more convenient.
Sample
Host fedora
Hostname <IP_ADDRESS>
Port 22
User shm
With which I can do
ssh fedora
And since it does not have any key - it uses the default id_rsa.
Thanks @Shakiba Moshiri I will check other login methods too.
| common-pile/stackexchange_filtered |
Retrieving unsupported image shape(1,224,224,64) error
I have the following code, I am trying to receive predictions through the TCP socket. While doing so I am able to receive the data but I retrieve error
while True:
frame = footage_socket.recv_pyobj()
print(type(frame)) # <class 'numpy.ndarray'>
predictions = img_to_array(frame)
tmp = np.zeros( predictions.shape )
for i in range( 0, 1 ):
tmp[i,:] = predictions[i, :]
predictions_result = m2.predict( tmp )
label_vgg16 = decode_predictions( predictions_result )
footage_socket.close()
Error
predictions = img_to_array(frame)
ValueError: Unsupported image shape: (1, 224, 224, 64)
Thanks, help is highly appreciated.
If you already have a numpy array, there is no need to use img_to_array
Thanks alot for your wonderful help you saved my day @Dr.Snoopy
| common-pile/stackexchange_filtered |
Should I pause Mirroring and stop SQL Server services before running windows updates?
I am running Windows update on my SQL Servers (which are in a Principal-Mirror partnership, in High Safety mode).
I am starting with updating the mirror and I was wondering, to increase safety, should I pause mirroring and stop SQL Server Services and then run Windows Update? Or is this totally unnecessary?
Suggest you to PAUSE mirroring and then patch the windows.
Ideally, I would follow below approach :
If you have a witness configured, turned it OFF as during the patching, if sql server service is restarted or the server reboots, then a witness will initiate a failover.
ALTER DATABASE [db_name] SET WITNESS OFF
Always patch the current mirrored server, so if things go wrong, then you atleast have your principal ON.
Reboot the mirror server (if necessary)
Now failover to the newly patched mirror server. Run below T-SQL on the current Principal server ALTER DATABASE [your database] SET PARTNER FAILOVER
Once the failover is completed, patch the current mirror (which was originally primcipal)
Reboot if necessary
Now failback to the original principal server.
Add back the witness (if removed from step 1)
ALTER DATABASE [db_name] SET WITNESS = 'TCP://[FQDN]:[port_number]'
As a saftey measure, run DBCC CHECKDB on your databases.
From BOL :
I thought if Witness and Mirror are unavailable, Principal will refuse all transactions?
@Dina that is not true. Why would Principal refuse connections ? Readup on database mirroring to avoid any confusion.
Right, I'm confusing myself with this scenario: http://sqlblog.com/blogs/tibor_karaszi/archive/2010/04/16/mirroring-what-happens-if-principal-loses-contact-with-both-mirror-and-wittness.aspx
@Dina Good point and I can see why the confusion happens. The scenario that the article describes is called split-brain scenario. Also, if you see my answer, I have explicitly told to turn-off the witness. HTH.
Normally if the updates are SQL based (and certain conditions are met), the program will handle the stopping/starting of related services.
| common-pile/stackexchange_filtered |
Issues with onclick/onserverclick with buttons, HtmlButtons, and LinkButtons
I'm having an issue with the functions to be called not firing off.
I have moved from hardcoding the buttons on HTML, to using the add controls method in the cs; and I have shifted from using Button and HtmlButton to using LinkButton. However none of these seem to work. In Onserverclick and onclick not work Anup Sharma recommends using the LinkButton, and Keyvan Sadralodabai indicates that if the runat="server" is displayed in the insect element, then he control was set up wrong.
So here's a stripped down simplified version of what I'm working with:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Web.Services;
using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;
public partial class backCodeExper : System.Web.UI.Page
{
protected void saveRecord(string recordID, string buttonId, string dropdownId)
{
PlaceHolder db = Page.FindControl("TestingCS") as PlaceHolder;
HtmlTable tbl = db.FindControl("TestTable") as HtmlTable;
HtmlTableRow tr = tbl.FindControl("TheRow") as HtmlTableRow;
HtmlTableCell tc = tr.FindControl("TheCell2") as HtmlTableCell;
DropDownList ddl = tc.FindControl(dropdownId) as DropDownList;
var status = ddl.SelectedValue.ToString();
HttpContext context = HttpContext.Current;
MySqlConnection conn = new MySqlConnection();
conn.ConnectionString = "Server=localhost; Database********; User=********; Password=********; Port=3306";
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "updatetesttable";
cmd.Parameters.AddWithValue("@param", status);
cmd.ExecuteNonQuery();
}
protected void Page_Load(object sender, EventArgs e)
{
HtmlTable myTable = new HtmlTable();
myTable.ID = "TestTable";
myTable.BorderColor = "teal";
myTable.BgColor = "black";
TestingCS.Controls.Add(myTable);
HtmlTableRow newRow;
HtmlTableCell cell;
DropDownList DropList;
LinkButton saveButton;
newRow = new HtmlTableRow();
newRow.ID = "TheRow";
cell = new HtmlTableCell();
cell.ID = "TheCell1";
DropList = new DropDownList();
DropList.ID = "StatusDD";
DropList.Items.Add(new ListItem("", "0"));
DropList.Items.Add(new ListItem("A", "1"));
DropList.Items.Add(new ListItem("B", "2"));
DropList.Items.Add(new ListItem("C", "3"));
cell.Controls.Add(DropList);
newRow.Cells.Add(cell);
cell = new HtmlTableCell();
cell.ID = "TheCell2";
cell.BgColor = "black";
saveButton = new LinkButton();
saveButton.ID = "saveButton";
saveButton.CommandName = "saveRecord";
saveButton.CommandArgument = "'1A',this.id,'StatusDD'";
saveButton.BackColor=Color.Green;
saveButton.ForeColor=Color.Cyan;
saveButton.BorderColor=Color.Maroon;
saveButton.Text = "Save";
saveButton.Visible = true;
cell.Controls.Add(saveButton);
newRow.Cells.Add(cell);
myTable.Rows.Add(newRow);
}
}
It loads the screen just fine with the simple dropdown and with the (unstylish) button (frankly the HtmlButton looks much nicer, but I'm aiming for functionality first).
When I select an item from the dropdown and then click save, the screen appears to refresh, keeping the value of the dropdown the same as that which was selected. However, when I check the database, the procedure hasn't fired. Additionally I cannot get this code segment Response.Write("<script>alert('Hello');</script>"); to execute when placed in the method/function saveRecord.
Furthermore, when I run the debugging mode and put break points in saveRecord, none of them are hit.
After inspecting element, this is what I get:
InspectElementResults
Any suggestions? What am I missing?
If I don't use LinkButton (or Button/HtmlButton with onServerClick) then I get errors saying the function isn't defined - which makes since as the function/method is define on the aspx.cs not the aspx within JS script tags.
I've got it figured out. At least, it is functional.
I was trying to set the function to pass the values I want in the format I wanted, but apparently the when you set up a LinkButton, it prefers the object and Event Args as parameters, and the object is the ListButton itself, so if that ListButton object holds the values you need in its attributes, then when the function is called you parse out the attributes you need. There's likely a better way than to assign the two values I need to CommandName and CommandArgument, but this works. (I had thought of using .Attributes.Add("ROW_ID","1a") and .Attributes.Add("DD_ID","StatusDD") ... but couldn't initially figure out how to retrieve those values from the sender object...to be investigated later, in the meantime, rolling forward with a functional solution.
...
protected void saveRecord(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
string ROW_ID = (string)lb.CommandName;
string DD_ID = (string)lb.CommandArgument;
Response.Write("<script>alert('Hello');</script>");
...
}
protected void Page_Load(object sender, EventArgs e)
{
...
saveButton.CommandName = "1a";
saveButton.CommandArgument = "StatusDD";
saveButton.Click += new EventHandler(saveRecord);
...
}
}
| common-pile/stackexchange_filtered |
How to log Spring transaction content
There have been various posts of logging the activity (start, commit & rollback) of Spring's transaction manager. However, I recently came across a deadlock issue for which logging just the activity isn't enough.
The fundamental issue in our code is a messy usage of transaction propagations REQUIRED and REQUIRES_NEW. There are so many method calls back- and forth that we end up with a lot of transactions stacked onto each other. Alas, the code base is huge and the solution urgent... (We all know what this is.)
The issue was a deadlock because code was added to query entities in a transaction that were sub-sequentially modified in another transaction. Spring spits out an exception telling the update of entity X times out because it's locked. Now, Knowing this is nice, but how does one find the faulty code: The query which does the early locking.
My question (at last) : Is there a way to log the entities being added to a transaction ? This way I can specifically look for transactions locking the entity Spring is complaining about.
Thanks ! :-)
Spring delegates to a transaction manager, so Spring doesn't know what entities are touched in the transaction, the transaction manager does. As Donz said, looking at the transaction manager for information is the best investigative approach.
You could also go over all transaction definitions and remove REQUIRES_NEW from everything except write only/write always type methods (like auditing or logging). If you have REQUIRES_NEW in your main business logic it is a bug or some very odd design. Blindly removing it might have less side effects than you think.
Try to log queries in your ORM. May be it will be easier way to find "bad" transaction.
| common-pile/stackexchange_filtered |
Converting a lead while workflow is active
I have a time-based workflow on my lead, which acts on a date field. If a lead is inactive for 30 days, then it is assigned to a queue. The problem is that a lead cannot be converted if I have this workflow active. So, I added a checkbox to the lead object, and when this checkbox is ticked, the workflow is broken.
The problem now is that I obviously don't want to click that checkbox everytime before I want to convert a lead, so I was wondering if there is an easy way of doing this behind the scenes?
Option 2 of the answer by @jpmonette sounds very good, I was just wondering whether I need to rebuild all the logic of converting a lead, or is there a possiblity to create a link to that process?
Here are two options:
Use a Scheduled Apex running on a daily basis replicating the logic of that Time-based workflow.
Keep that checkbox & create a replica of your Convert Lead button, with some JavaScript to automatically populate that checkbox on click.
Thanks @jpmonette - for option 2, is it possible to link to all the convert lead logic when I create a new button, or will I have to create a New Account, New Opportunity myself?
| common-pile/stackexchange_filtered |
Required assistance how to add specifics source file with same string (date) in file name in splunk query
I am having one requirement where we are getting files every day with the respective date mentioned in the files:
for example the file names are:
test_dev_08_07_2021.json
test_dev_09_07_2021.json
test_prod_08_07_2021.json
test_prod_09_07_2021.json
Now the requirement we have here is to add the files content which have same dates. The splunk query we are using is below :
eventtype="metric:sample:example" source="test_dev_.json" OR source="test_prod_.json" | stats sum(number_of_car) as "# Total_Car ",
sum(Parked_cars) as "# Stopped_Cars", sum(Buses) as "# Total_Bus", sum(Parked_buses) as "# Stopped_Buses " by source | addcoltotals
but there it's getting combined result of all the four file:
source # Total Car # Stopped Cars # Total Bus # Stopped Buses
test_dev_08_07_2021.json 23 21 295 124
test_dev_09_07_2021.json 22 22 297 123
test_prod_08_07_2021.json 2 3 429 66
test_prod_09_07_2021.json 2 3 427 66
49 49 1448 379
What we are trying to achieve only content of file with same date should get added. For example if the date is mentioned 08_07_2021 in test_dev and test_prod then only these two file content should get added and it should show the result and same for the files with date 09_07_2021 as well. We should be getting separate result after the addition of the addition.
Please Note: Also we will be getting these files every day. hence the date and month range will varies in each file and no way we can't change the file name now
Is there any way can we achieve this task or if someone can help us with the respective splunk query will much help.
Please assist.
The trick is to extract the date and use that as a grouping field.
eventtype="metric:sample:example" source="test_dev_.json" OR source="test_prod_.json"
| rex field=source "_(?<groupBy>\d\d_\d\d_\d\d\d\d)"
| stats list(source) as sources sum(number_of_car) as "# Total_Car",
sum(Parked_cars) as "# Stopped_Cars", sum(Buses) as "# Total_Bus",
sum(Parked_buses) as "# Stopped_Buses" by groupBy
| fields - groupBy
| table sources "# Total_Car" "# Stopped_Cars" "# Total_Bus" "# Stopped_Buses"
| addcoltotals
| common-pile/stackexchange_filtered |
With KVO in Objective-C is there a way to detect what observers my object has set on other objects?
Let there be an object A that observers a property on object B. Is there a way to ask A what properties it is observing and then see that it is observing a property on object B.
For for example:
[B addObserver:(A*)self forKeyPath:@"bytesUploaded"
options:NSKeyValueObservingOptionNew
context:A_KVOContext];
Now is there a way to ask A what object's its observing?
I think even A doesn't know, that he is something observing. B should know, at which object call observeValueForKeyPath...
is this really the caseโฝ I wouldn't actually be surprised, just a bit disappointed...
| common-pile/stackexchange_filtered |
How configure time zone in MariaDB Azure?
How can I change the time zone in the configuration of my maria DB?
I can put hours directly but in my case as there are 2 time changes during the year I would have to change it each time.
Is there any way I can put the time zone instead of the time difference?
It says here that it can't be done, but I don't know if this problem has already been solved.
Configure time zones on MySQL Database on Azure
The doc page you linked to is outdated. Please refer to Working with the time zone parameter instead.
Specifically:
Populate the time zone tables with the command:
CALL mysql.az_load_timezone();
Then you can set the time_zone global parameter to a named time zone from the list of IANA time zone names, such as Europe/Madrid.
| common-pile/stackexchange_filtered |
jquery Ajax Request SyntaxError: Unexpected token <
I am trying to return an array of products using a get request. The response returns XML with a 200 request.
Web Service:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public List<product> GetAllProducts()
{
using (SchulteDesignYourOwnEntities db = new SchulteDesignYourOwnEntities())
{
return db.products.ToList();
}
}
Here is my code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: 'http://www.organizeliving.com/designwebservice.asmx/GetAllProducts',
dataType: 'json',
success: function (result) {
alert("Result: " + result.length);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("Status: " + xhr.status);
console.log("Message: " + thrownError);
}
});
});
</script>
</head>
<body></body>
</html>
check whether any of the string properties in returned product list contains < character
It does. My problem appears that I cannot return json from my .asmx web service. My response is Soap/ XML.
You have the dataType as 'json'. jQuery will automatically try to parse JSON from the response. If it cannot, it considers it an error.
XML is not valid JSON (it will really hate the opening <). You can either change the dataType to 'xml' (or nothing) or actually emit pure JSON from the server instead.
It succeeds, however, my method says result is undefined. It appears it never parses the data.
It says undefined because result is a JSON object, not a string. Either use $.param(result).length or use your own JSON serialiser.
| common-pile/stackexchange_filtered |
check if something is divisble by 3
i have something to read a text file, and then a function file like this
int Myiseven(int x)
{
int isOdd = 0;
if (x % 2 == 1) {
isOdd = 1;
}
}
so that all odd numbers would have isodd = 1
how would i go about checking if a number is divisible by three
the original main file is this
#define _CRT_SECURE_NO_DEPRECATE
#include<stdio.h>
#include "ProblemHeader_4.h"
int main()
{
FILE *myfile = fopen("input.txt", "w");
for (int i = 1; i <= 33; i++)
{
fprintf(myfile, "%d\n", i);
}
fclose(myfile);
FILE *myfileRead = fopen("input.txt", "r");
FILE *myfileWrite = fopen("outputEven.txt", "w");
int readBuff;
while (!feof(myfileRead))
{
fscanf(myfileRead, "%d", &readBuff);
printf("These numbers were read: %d\n", readBuff);
int isOdd = Myiseven(readBuff);
if (isOdd == 1)
{
fprintf(myfileWrite, "%d\n", readBuff);
printf("This number is divisible by 3: %d\n", readBuff);
}
}
fclose(myfileWrite);
fclose(myfileRead);
return 0;
}
and header
#ifndef MY_VAR
#define MY_VAR
#include<stdio.h>
int Myiseven(int x);
#endif
What have you tried doing? You seem to know the modulo operator % already 2. Your Myiseven function exhibits undefined behavior because it is missing a return statement
You know about the modulo operator %. I suggest you experiment with it. For example for (int i = 0; i < 10; ++i) { printf("%d % 3 = %d\n", i, i % 3) }
Looks like you only want to print odd numbers that are divisible by 3. You can do this as follows:
if (isOdd == 1 && readBuff%3==0)
{
fprintf(myfileWrite, "%d\n", readBuff);
printf("This number is divisible by 3: %d\n", readBuff);
}
Additionally, you need a return statement in Myiseven() function in order to execute your code successfully:
int Myiseven(int x)
{
int isOdd = 0;
if (x % 2 == 1) {
isOdd = 1;
}
return isOdd;
}
thanks, was trying to get any number divisible by 3 but i changed it and it works now :)
if you want to check for all number than no need to check for isOdd==1
| common-pile/stackexchange_filtered |
Configure Chrome or Firefox to have an "open link in default browser" action
I would like to open some webapps in a secondary browser, so that they are grouped in a separate window outside of my main browser.
In a secondary browser's webapp, I would like to be able to right-click a link and select "Open in the default browser", so that the link opens in my primary browser.
How do I do that?
Create a browser extension that uses Native Messaging to execute open url on the command line when you right-click a link.
This is all I could think of. I wanted this too so I built it for Chrome.
Hey @kumar303, thank you for chiming in! I've tried your extension and it didn't work for me. Can I contact you via an instant messenger to figure it out?
Sorry to hear that. The best thing would be to file a bug in the repo.
On Windows 10 with Chrome, I have found that opening a link in an incognito window will open a link in a new incognito window if none existed, or open a link in a new tab in an incognito window that does exist.
| common-pile/stackexchange_filtered |
Can consummation validate a one-witness Kiddushin?
Can consummation validate a one-witness Kiddushin?
Halacha states, something like: "When a man consecrates a woman in the presence of a single witness, the kiddushin is not binding."
But Halacha also says, something like, "If a man consecrates a woman through sexual relations (no matter how much such action is frowned upon) ... the kiddushin is binding."
My question: is the second statement a Halacha loophole against the first one; that is / or, if a-man-and-a-woman so unfortunately have only one witness, then should they go ahead and have sex (or consummate), in order to have a binding kiddushin?
If the consummation effects a binding kiddushin then isn't that validating a NO witness kiddushin and obviating the testimony of any 1 witness?
Why do you think consecration through relations is different than kiddushin with one witness? Consecration is just a translation of kiddushin, which you pointed out doesn't work without two witnesses.
Consummation needs two witnesses, or "public knowledge" (i.e. living together as a married couple) to be a valid kiddushin. So if we know they were together with the intention of being a married couple that would be a kiddushin even if it was not formally declared, but if only they know about it then it has no effect.
There are three valid types of Kiddushin: money, using a document, and biah. (Kiddushin 1:1) All three need two witnesses to be effective.
Can consummation validate a one-witness Kiddushin?
If it is done in the correct way, i.e. he says to her in front of 2 kosher witnesses ืืชืงืืฉื ืื ืืืืื ืื and then immediately secludes himself with her. (As per Rashi on ืืืกืฃ ืืืฉืืจ in Kidushin 2b who says ืืืื- ืื ืขืืื ืืืืจ ืืชืงืืฉื ืื ืืืืื ืื.โ)
But then he may as well give her the ring again (after she gives it back to him) and redo the Kidushin properly in front of 2 kosher witnesses.
My (second) question: is the second statement a Halacha loophole against the first one; that is / or, if a-man-and-a-woman so, unfortunately, have only one witness, then should they go ahead and have sex (or consummate), in order to have a binding kiddushin?
Nope. Wouldn't help.
I'm not sure I'd call Kiddushei Biah "consummation" since after it is done they still need Nisuin to be fully married.
The first answer should be edited for clarity. If there are two witnesses, by definition it is not one witness.
| common-pile/stackexchange_filtered |
Software Updater could not update
I have 2 computers with the same model, https://www.bee-link.com/beelink-mini-s-n5095-mini-pc and the same OS, Ubuntu 22.04 LTS.
One computer, Software Updater could not update for a few days.
This is the result:
bl00004@bl00004:~$ sudo apt update
[sudo] password for bl00004:
Hit:1 https://dl.google.com/linux/chrome/deb stable InRelease
Hit:2 http://security.ubuntu.com/ubuntu jammy-security InRelease
Ign:3 http://th.archive.ubuntu.com/ubuntu jammy InRelease
Ign:4 http://th.archive.ubuntu.com/ubuntu jammy-updates InRelease
Ign:5 http://th.archive.ubuntu.com/ubuntu jammy-backports InRelease
Ign:3 http://th.archive.ubuntu.com/ubuntu jammy InRelease
Ign:4 http://th.archive.ubuntu.com/ubuntu jammy-updates InRelease
Ign:5 http://th.archive.ubuntu.com/ubuntu jammy-backports InRelease
Ign:3 http://th.archive.ubuntu.com/ubuntu jammy InRelease
Ign:4 http://th.archive.ubuntu.com/ubuntu jammy-updates InRelease
Ign:5 http://th.archive.ubuntu.com/ubuntu jammy-backports InRelease
Err:3 http://th.archive.ubuntu.com/ubuntu jammy InRelease
Cannot initiate the connection to th.archive.ubuntu.com:80 (2001:3c8:9009:81::101:34). - connect (101: Network is unreachable) Could not connect to th.archive.ubuntu.com:80 (<IP_ADDRESS>), connection timed out
Err:4 http://th.archive.ubuntu.com/ubuntu jammy-updates InRelease
Cannot initiate the connection to th.archive.ubuntu.com:80 (2001:3c8:9009:81::101:34). - connect (101: Network is unreachable)
Err:5 http://th.archive.ubuntu.com/ubuntu jammy-backports InRelease
Cannot initiate the connection to th.archive.ubuntu.com:80 (2001:3c8:9009:81::101:34). - connect (101: Network is unreachable)
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
4 packages can be upgraded. Run 'apt list --upgradable' to see them.
W: Failed to fetch http://th.archive.ubuntu.com/ubuntu/dists/jammy/InRelease Cannot initiate the connection to th.archive.ubuntu.com:80 (2001:3c8:9009:81::101:34). - connect (101: Network is unreachable) Could not connect to th.archive.ubuntu.com:80 (<IP_ADDRESS>), connection timed out
W: Failed to fetch http://th.archive.ubuntu.com/ubuntu/dists/jammy-updates/InRelease Cannot initiate the connection to th.archive.ubuntu.com:80 (2001:3c8:9009:81::101:34). - connect (101: Network is unreachable)
W: Failed to fetch http://th.archive.ubuntu.com/ubuntu/dists/jammy-backports/InRelease Cannot initiate the connection to th.archive.ubuntu.com:80 (2001:3c8:9009:81::101:34). - connect (101: Network is unreachable)
W: Some index files failed to download. They have been ignored, or old ones used instead.
bl00004@bl00004:~$
And another computer took a long time to shut down.
It happened at the same period of time.
What should be done to solve these problem ?
In our office we use only Ubuntu.
I can't find the reference just now but ISTR there was a question about this before for which the answer was that Canonical spread the update load across the user base so not everyone is "hit" at the same time if there is an issue.
The repository mirror server you are using (in Thailand?) may be down for some reason. Try again later, maybe? The long time to shut down may not be related. Here you have to ask one question at a time.
Your output clearly shows that the problem with the system-that-wouldn't-update seems to be at your end: 101: Network is unreachable. That's not an Ubuntu software issue -- that's a your-network issue. Were the problem at the server, you would get a 300-series or 400-series error. Insufficient data to determine if your takes-too-long-to-shutdown system is related to your network problem or has some other cause.
Each of the "Err:" lines mentions an IPv6 address (.(2001:3c8:9009:81::101:34) Try; open your network settings and disable IPv6. Looks like somebody isn't fully IPv6. Fall back to IPv4.
@user68186
I switched from 'Server for Thailand' to 'Main server'. Now, Software Updater works smoothly. And I will use your comment as the answer of this question.
I live in Thailand, after switching the Setting of Software Updater from Server for Thailand to Main Server. The problem has gone. And I will try to switch back to Server for Thailand everyday to check if it will be available.
| common-pile/stackexchange_filtered |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.