text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: ERROR 1045 (28000): Access denied for user 'admin'@'localhost' (using password: YES) I'm trying to log in to mysql via a bash script or to be more specific, I want to check if the passed parameters for the mysql user are thes of an admin user.
For this reason it has to be possible to log in to mysql via a one line command e.g.
mysql -u $dbadmin -p$dbadminpass
To test why I didn't work, I tried it myself on the command line an I'm getting this Error:
ERROR 1045 (28000): Access denied for user 'admin'@'localhost' (using password: YES)
I created the use on @localost and gave all privileges. All my reasarch had no reasults so far.
I checked for any typos
A: You can try this:
GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%';
FLUSH PRIVILEGES;
or try to connect to 127.0.0.1 not to localhost
A: This is not a problem with MySQL installation or set-up.
Each account name consists of both a user and host name like 'user_name'@'host_name', even when the host name is not specified. From the MySQL Reference Manual: https://dev.mysql.com/doc/refman/8.0/en/privileges-provided.html#priv_usage
MySQL account names consist of a user name and a host name. This enables creation of accounts for users with the same name who can connect from different hosts.
This also allows MySQL to grant different levels of permissions depending on which host they use to connect.
When updating grants for an account where MySQL doesn't recognize the host portion, it will return an error code 1133 unless if it has a password to identify this account.
Also, MySQL will allow an account name to be specified only by it's user name, but in this case it is treated as 'user_name'@'%'.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68984510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to exit from nested for loop using break statement in Python [tmp.py]
#is_skip = False # Alt. approach
for i in range(5):
for j in range(3):
if j == 2:
# is_skip = True # Alt. approach
break
print('I, J => ', i, j)
# if is_skip: # Alt. approach
# break # Alt. approach
[Expected]
I, J => 0 0
I, J => 0 1
[Current]
I, J => 0 0
I, J => 0 1
I, J => 1 0
I, J => 1 1
I, J => 2 0
I, J => 2 1
I, J => 3 0
I, J => 3 1
I, J => 4 0
I, J => 4 1
Any other best approach is available, except the above commented one.
Thanks,
A: make a function and then return from that when condition matches:
def loopBreakExample():
for i in range(5):
for j in range(3):
if j == 2:
return
print('I, J => ', i, j)
loopBreakExample()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57603399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Python Named Pipes Behavior I am primarily a PLC programmer who has been tasked with writing some code to run on a Raspberry Pi2B (Raspbian Wheezy) to grab some data from another process running on the RPi and making that data available on a Modbus TCP (old PLC protocol) interface. I have it working, but am now trying to bulletproof it. I chose Named Pipes for IPC and therein lies my question. In my Python (v2.7) example code, If I start my reader, it opens and goes to the readline command and blocks as expected. When I go and fire up my writer and choose to open, write, and close the pipe, it does as expected and writes a record to the pipe. The reader, however, just sits there blocking at the readline command. When the writer loops back around and asks whether to open the pipe or not, if I choose "y" my reader spits out the record written in the prior loop. I'm happy that I got my data, but don't understand why "opening" the pipe in the writer causes the reader to grab the data at that time. I would think that I would see read data after my writer has written the record. Additionally, I think "closing" the pipe in the Writer code doesn't do anything, because I can open the pipe on the first time through the logic, write a record, and then on the next pass through the logic I can choose not to open the pipe and still successfully write it.
*
*What am I missing here? (rhetorical, sort of)
*What is the proper way to write to a Named Pipe in a loop?
*Why does the reader only grab a record after the Writer "opens" the pipe (whether it was open or not from the previous pass through the loop)?
Thanks in advance and be nice to me...Remember, I'm just an old PLC programmer who has been forced into Python-World!
Writer:
#!/usr/bin/env python
import logging
logging.basicConfig(format='%(asctime)s %(message)s')
log = logging.getLogger()
log.setLevel(logging.DEBUG)
log.debug('Logging has started')
log.debug('DocTest Pipe Writer')
import os, time, sys
PipeName = 'DocTestPipe'
if not os.path.exists(PipeName):
log.debug('Pipe not present...Creating...')
os.mkfifo(PipeName, 0777)
log.debug('Pipe is made')
else:
log.debug('Pipe already present')
ModbusSeed = 0
while True:
OpenPipe = raw_input ('Open pipe? y or n')
if OpenPipe == 'y':
log.debug('Opening pipe')
PipeOut = open(PipeName, 'w')
log.debug('Pipe is open for writing.')
else:
log.debug('Chose not to open pipe')
DataPipeString = '%05d' % ModbusSeed+','+'%05d' % (ModbusSeed+1)+','+'%05d' % (ModbusSeed+2)+','+ \
'%05d' % (ModbusSeed+3)+','+'%05d' % (ModbusSeed+4)+','+'%05d' % (ModbusSeed+5)+','+ \
'%05d' % (ModbusSeed+6)+','+'%05d' % (ModbusSeed+7)+','+'%05d' % (ModbusSeed+8)+','+ \
'%05d' % (ModbusSeed+9)+'\n'
print 'Pipe Data to write: '+DataPipeString
WritePipe=raw_input('Write Pipe? y or n')
if WritePipe == 'y':
log.debug('Writing pipe')
PipeOut.write(DataPipeString)
log.debug('Pipe is written.')
ClosePipe = raw_input('Close pipe? y or n')
if ClosePipe == 'y':
log.debug('Closing pipe')
PipeOut.close
log.debug('Pipe is closed')
else:
log.debug('Pipe left open')
ModbusSeed=ModbusSeed+1
Reader:
#!/usr/bin/env python
import logging
logging.basicConfig(format='%(asctime)s %(message)s') #,filename='DocTestLog')
log = logging.getLogger()
log.setLevel(logging.DEBUG)
log.debug('Logging has started')
log.debug('Modbus Server started.')
import os, time, sys
PipeName = 'DocTestPipe'
if not os.path.exists(PipeName):
log.debug('Pipe not present...Creating...')
os.mkfifo(PipeName, 0777)
log.debug('Pipe is made')
else:
log.debug('Pipe already present')
log.debug('Open pipe for reading')
PipeIn = open(PipeName, 'r')
log.debug('Pipe is open for reading')
while True:
#raw_input('Press any key to read pipe')
log.debug('Reading Line')
try:
PipeString = PipeIn.readline() [:-1]
except:
print 'Nothing there'
#PipeString = PipeIn.read()
log.debug('PipeString = '+PipeString)
A: After much head scratching, scouring the internet, and trial and error, I have my answer. The crux of the problem was that when I opened my pipe for writing, I didn't specify a "buffering" argument. This caused my pipe write to be cached somewhere in a buffer instead of being immediately written to the pipe. Whenever I "opened" my write pipe, it flushed the buffer to the pipe and my reader then picked it up. The solution was to add ",0" as an additional argument to my "open" command (PipeOut = open(PipeName, 'w',0) instead of PipeOut = open(PipeName, 'w')), thus setting the buffer size to zero. Now when I "write" to the pipe, the data goes directly to the pipe and doesn't sit around in limbo until flushed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33855556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Creating/Saving a Vim Layout Everytime I open a project/directory I use the exact same vim pane layout:
---------
| |pane|
|pane|pane|
| |pane|
---------
I would like to be able to open a new vim session with this layout, all of the panes on the right would start in :Explore mode, while the left pane would start in :terminal mode (specific to neovim).
Is there any way to create a vim "layout" for a new session?
A: Try something like this:
nvim -c ':vsp|Explore|sp|Explore|sp|Explore'
Placing terminal in front is tricky because it steals focus.
Now I got a idea.
nvim -c ':vsp|Explore|sp|Explore|sp|Explore|wincmd w|te'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34211242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: The application does not start (error due to _stprintf_s) When I execute code in Visual studio 2015, I get the following message
Triggered a breakpoint.
It seems that the error occurs in stdio.h at line 1265
{
int const _Result = __stdio_common_vswprintf_s( // this is line 1265
_CRT_INTERNAL_LOCAL_PRINTF_OPTIONS,
_Buffer, _BufferCount, _Format, _Locale, _ArgList);
return _Result < 0 ? -1 : _Result;
}
Problem in this line, but I cannot understand why?
_stprintf_s(info_temp, _T("\r\n%s"), infoBuf);
Here is my code:
TCHAR* envVarStrings[] =
{
TEXT("OS = %OS%"),
TEXT("PATH = %PATH%"),
TEXT("HOMEPATH = %HOMEPATH%"),
TEXT("TEMP = %TEMP%")
};
#define ENV_VAR_STRING_COUNT (sizeof(envVarStrings)/sizeof(TCHAR*))
#define INFO_BUFFER_SIZE 32767
void main()
{
DWORD i;
TCHAR infoBuf[INFO_BUFFER_SIZE];
DWORD bufCharCount = INFO_BUFFER_SIZE;
...
bufCharCount = ExpandEnvironmentStrings(envVarStrings[1], infoBuf,
INFO_BUFFER_SIZE);
TCHAR info_temp[MAX_PATH];
_stprintf_s(info_temp, _T("\r\n%s"), infoBuf);
SetWindowText(GetDlgItem(hWnd, ID_EDIT), info_temp);
...
}
A: You are not calling _stprintf_s correctly. The second argument should be the size of the destination string.
_stprintf_s(info_temp, MAX_PATH, _T("\r\n%s"), infoBuf);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43836957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Receive annotation value from annotated field Is it possible to receive annotation value inside a field, that was annotated?
Imagine that I have this interface:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value();
}
And I have such implementation:
class SomeClass {
@MyAnnotation("Annotation")
private MyClass myClass;
}
What I want to understand is: is it possible to receive value of MyAnnotation inside MyClass? I want to implement a method inside class MyClass, which will return a value of assigned annotation. So, that myClass.getAssignedAnnotationValue() will return "Annotation".
If it is not possible, please inform me.
A:
is it possible to know annotation value inside annotated field
It's not possible.
You may have 2 different classes
class SomeClass {
@MyAnnotation("Annotation")
private MyClass myClass;
public SomeClass(MyClass myClass) {
this.myClass=myClass;
}
}
and
class SomeClassNo Annotation {
private MyClass myClass;
public SomeClassNo(MyClass myClass) {
this.myClass=myClass;
}
}
Then you create an instance of MyClass
MyClass instance = new MyClass();
then 2 classes instances
new SomeClass(instance) and new SomeClassNo(instance) both have reference to the same instance. So the instance does not know whether the reference field annotated or not.
The only case when it is possible is to pass somehow the container reference to MyClass.
A: There is no straight forward way of implementing what you are asking.
WorkAround:
Limitations:
*
*This workaround doesn't enforce any kind of compile time check and it is completely your responsibility to handle it.
*This only works if MyClass is going to be a spring bean.
class MyClass {
public String annotatedValue;
}
You can write a Spring BeanPostProcessor the following way.
public class SampleBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
Field[] fields = bean.getClass().getDeclaredFields();
for (Field field : fields) {
if (field instanceof MyClass && field.isAnnotationPresent(MyAnnotation.class)) {
String value = field.getDeclaredAnnotation(MyAnnotation.class).value();
((MyClass) field).annotatedValue = value;
return bean;
}
}
return bean;
}
}
The above BeanPostProcessor will be called for every bean during the app start up. It will check all the fields of a given bean to see if the field is of type MyClass. If it is, it will extract the value from the annotation and set it in the annotatedValue field.
The problem with this approach is that you can use MyAnnotation on any property in any class. You cannot enforce the annotation to be used only on MyClass.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44112392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Combining Excel COUNTIFS with aggregate functions Say I have an Excel spreadsheet containing student details and dates of courses the student attended. Lets say the row headers are:
Name - Student Grade - Date of course A - Date of course B - Date of course C etc...
Then obviously a separate row per student containing their grade and dates of the courses the student was present in. I want to avoid making modifications to the sheet as the format has been established for a while.
I'm looking for some way of counting all the students with a grade a specific grade, which attended courses between specific dates. For example, count all students with a "C" grade, which attended courses between 1st Jan 2012 to 31st March 2012.
I guess the final formula will be some sort of combination of COUNTIFS and MAX on the date range columns, but I can't see how I can apply this on a row-by-row basis.
All suggestions much appreciated!
Best regards,
Chris
A: Assuming you have grades in B2:B100 and dates in 5 columns C2:G100 then you can use this formula to count the number of students with a specific grade who took courses in a specific date period.
=SUMPRODUCT((MMULT((C$2:G$100>=J2)*(C$2:G$100<=K2)*(B$2:B$100=I2),{1;1;1;1;1})>0)+0)
where J2 and K2 are the start and end dates of the period (1-Jan-2012 and 1-Mar-2012) and I2 is a specific grade (C)
the {1;1;1;1;1} part depends on the number of date columns, so if there are 7 date columns then you need to change that to {1;1;1;1;1;1;1}.....or you make the formula dynamically adjust by using this version
=SUM((MMULT((C$2:G$100>=J2)*(C$2:G$100<=K2)*(B$2:B$100=I2),TRANSPOSE(COLUMN(C2:G100))^0)>0)+0)
The latter formula, though, is an "array formula" which you need to confirm with CTRL+SHIFT+ENTER
Update
For the number of distinct grades within a specific date range then assuming you have a finite list of possible grades then list those somewhere on the worksheet, e.g. M2:M10 and then you can use this "array formula"
=SUM(1-ISNA(MATCH(M$2:M$10,IF(MMULT((C$2:G$100>=J2)*(C$2:G$100<=K2),{1;1;1;1;1}),B$2:B$100),0)))
confirmed with CTRL+SHIFT+ENTER
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9962881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how to Get hosting WAS 7.0 server url inside a webservice code? I have a common codebase deployed in four different servers for various purposes like testing env, development env, production env etc.
But I need to know inside the code, which server's code is running to decide the flow of my code. Anybody know how to fetch the sever url or id inside the web service code which is deployed on the server?
A: Approach 1 :
4 different servers, mean four different URLs ok.
suppose ur application url is
http(s)://ipaddress:port/application
now it is possible that all four server instances are on same machine. in that case "ipaddress" would be same. but port would be different. if machines are different in that case both ipaddress and port would be different.
now inside your code you can get absoultepath. absolutepath would consist of the complete URL of the file absolutepath is requested on. like
http://ipaddress:port/application/abc/def/x.java.
Now from this you can extract the port/ipaddress and write your logic.
Approach2:
have a property file inside your application that contains the server its being deployed on. ( right now I cant think of something to set this automatically, but while deployment you can set the server name in this property file)
later on when you need. you can read the property file and you will know which version of application you are running on.
personally I`d prefer approach2 (and should be prefered in case we can think of initializing the properties file automatically)
Hope it helps :-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12558852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MATLAB: Specify a fixed color for zero in imagesc I have sets of 2D data that spread across negative value to positive value. When plotted using imagesc for different set of data, it'll be inconsistent to look at as the zero value is not always at a fixed color. Is it possible to fix a color for 0 value and then both negative and positive value to progress from there?
Thank you!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49551782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a way to select only the contents of the ImageView and the Textview and download them as an image file to save in the device storage? I want to create a download button so that users can download the contents of the ImageView and TextViews (which is on top of the ImageView) as an image file and save it in the device storage.
Here is the code block:
<ImageButton
android:id="@+id/back_btn"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@mipmap/ic_back"
android:layout_marginTop="20dp"/>
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/quotes_background"
android:layout_centerInParent="true"/>
<TextView
android:id="@+id/quoteBody"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="20sp"
android:typeface="monospace"
android:textColor="@color/white"
android:gravity="center"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"/>
<TextView
android:id="@+id/author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="25sp"
android:layout_below="@id/quoteBody"
android:textColor="@color/white"
android:layout_marginTop="20px"
android:gravity="center"/>
I just want to select the ImageView and the two TextViews and download them as an image (PNG). Any help will be appreciated.
Thank You.
A: What you probably want is to save a Bitmap of what you see on the screen. See this answer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46886504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: splitting string with regular expression in php using preg_split I am looking for a regular expression (using preg_split()) that can be used to split the following string:
hello<span id="more-32"></span>world
Desired result:
$var[0]=hello
$var[1]=world
I tried using this code put it didn't work
preg_split('/<span id="more-\d+"></span>/','hello<span id="more-32"></span>world')
A: First: You should escape the fore slash by a backslash.
Second: You should put the semicolon at the end of code.
This will work:
<?php
$string = 'hello<span id="more-32"></span>world';
$pattern = '/<span id="more-\d+"><\/span>/';
$out = preg_split($pattern,$string);
?>
Print the splitted string:
foreach ($out as $value) {
echo $value . '<br />';
}
Output:
hello
world
or:
print_r($out);
Output:
Array (
[0] => hello
[1] => world
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18792070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: python regular expression repeating pattern matching entire string I am working with python regular expression basics .I have a string
startabcsdendsffstartsdfsdfendsstartdfsfend.
How do i get the strings in between consecutive start and end without matching the entire string?
A: use the start.*?end in the re. The question mark means "as few as possible".
A: >>> s = "startabcsdendsffstartsdfsdfendsstartdfsfend."
>>> import re
>>> p = re.compile('start(.*?)end')
>>> p.findall(s)
['abcsd', 'sdfsdf', 'dfsf']
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15202913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: WPF | C# - When WindowStyle = "None" and the window is maximized the Task Bar doesn't show up How can I be able to see the taskbar when WindowStyle="None". I'm trying to have my own buttons (Close, Maximize, Minimize) by removing the actual window title bar and using a dll too remove the border. Easy to maintain and easy to put in my code would be greatly appreciated.
A: One of the possible fix to do this is: to limit the max size of window. For example:
C# code:
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
if (WindowState == WindowState.Normal)
{
System.Drawing.Rectangle rec = System.Windows.Forms.Screen.FromHandle(new System.Windows.Interop.WindowInteropHelper(this).Handle).WorkingArea;
MaxHeight = rec.Height;
MaxWidth = rec.Width;
ResizeMode = ResizeMode.NoResize;
WindowState = WindowState.Maximized;
}
else
{
MaxHeight = double.PositiveInfinity;
MaxWidth = double.PositiveInfinity;
ResizeMode = ResizeMode.CanResize;
WindowState = WindowState.Normal;
}
}
}
You need to set maxsize just before changing of window state. Otherwise, in some cases it works wrong. Also don't forget about ResizeMode.
And xaml:
<Window x:Class="WpfApplication2.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" WindowStyle="None" Height="300" Width="300">
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Top" Width="75" Click="ButtonBase_OnClick"/>
</Grid>
</Window>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24189280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Enable/ Create SSO (Single Sign On) in Asp.Net MVC applications I want to implement/enable SSO (Single Sign On) on my Asp.Net MVC applications.
Please consider the points below below for your kind suggestions:
*
*I have 3 Asp.Net MVC applications where I want to enable SSO for them.
*I know I can achieve SSO by ADFS (Active directory Federation Services), but I don't want to use it as I want my external users (end-users) to login in all my 3 applications via SSO.
*(Correct me If I wrong here because as far as I know, ADFS can be used for Active Directory users (meaning company-wide internal users) and not for external end-users. If we can use ADFS for external users, please do let me know how we should achieve it.
*I also don't want to use OpenID.
*I want to build SSO own for these 3 applications and want to enable SSO between them.
*I want to build SSO that can be used in production environment for
these 3 applications.
Could you please give me your suggestions on it about how would I achieve SSO by considering all above points?
Thanks in advance and all suggestions are welcome!
A: The suggestion would be to use the IdentityServer (http://thinktecture.github.com/Thinktecture.IdentityServer.v2/), a replacement for ADFS, which uses the same authentication protocol (WS-Federation) but allows you to plugin your custom membership provider.
In addition, the IdentityServer supports some features ADFS lacks and is quite extensible.
A: Are your applications in the same domain? If so, can you use Forms Authentication Across Applications?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13738589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Can you pipe into the bash strings command? The strings command is a handy tool to extract printable strings from binary input files.
I've used it with files plenty.
But what if I wish to stream to it?
A use case is grepping a stream of data that may be binary for specific strings.
I tried
data-source | strings -- - | grep needle to see if the - had it treat stdin as a file type, but this doesn't work, strings just waits.
A: If you look at the help for strings:
Usage: strings [option(s)] [file(s)]
Display printable strings in [file(s)] (stdin by default)
You see that stdin is the default behavior if there are no arguments. By adding - the behavior seems to change, which is strange, but I was able to reproduce that result too.
So it seems the correct way to do what you want is:
data-source | strings | grep needle
In a comment, you asked why not strings datasource |grep -o needle ?
If you could arrange that command so datasource is a stream, it might work, but it's usually easier to arrange that using |.
For example, the below are roughly equivalent in zsh. You'd have to figure out a way to do it in your shell of choice if that's not zsh.
strings <(tail -f syslog) | grep msec
tail -f syslog | strings | grep msec
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72000727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Send email in asp.net,html This is my index.aspx form.
<form role="form" method="post" action="SendMail.aspx">
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Name"
required>
</div>
<div class="form-group">
<input type="text" class="form-control" id="mobile" name="mobile" placeholder="Mobile Number"
required>
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" name="email" placeholder="Email"
required>
</div>
<button type="submit" id="submit" name="submit" class="btn btn-primary pull-right">
Submit Form</button>
</form>
And this is my SendMail.aspx form.
<%
Response.Write("Need : " & Request.Form("whatneed") & "<br>")
Response.Write("Budget : " & Request.Form("budget") & "<br>")
Response.Write("When : " & Request.Form("whenneed") & "<br>")
Response.Write("Location : " & Request.Form("location") & "<br>")
Response.Write("Name : " & Request.Form("name") & "<br>")
Response.Write("Description : " & Request.Form("address") & "<br>")
Response.Write("Mobile No : " & Request.Form("mobile") & "<br>")
Response.Write("Landline No : " & Request.Form("landline") & "<br>")
Response.Write("Email Id : " & Request.Form("email") & "<br>")
MailMessage mailMessage = new MailMessage();
mailMessage.To.Add("[email protected]");
mailMessage.From = new MailAddress("[email protected]");
mailMessage.Subject = "ASP.NET e-mail test";
mailMessage.Body = "Hello world,\n\nThis is an ASP.NET test e-mail!";
SmtpClient smtpClient = new SmtpClient("mail.feo.co.in");
smtpClient.Send(mailMessage);
Response.Write("E-mail sent!");
%>
I don't know why mail is not sending here.Please help me to fix this.
A: As per your JsFiddle, I found that there are so many silly mistakes in your HTML code.
Here is your ASP.NET code:-
<form id="form1" runat="server">
<div class="form-group">
<asp:TextBox ID="txtname" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div class="form-group">
<asp:TextBox ID="txtmobileno" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div class="form-group">
<asp:TextBox ID="txtEmail" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<div class="form-group">
<asp:TextBox ID="txtSubject" runat="server" CssClass="form-control"></asp:TextBox>
</div>
<asp:Button ID="btnSubmit" runat="server" CssClass="btn btn-primary pull-right" OnClick="btnSubmit_OnClick" Width="100" Text="Submit" />
</form>
Code behind cs code
Created a SendMail() function which will fire on buttonclick
Note:- I haven't added validations on the controls, so if you want it you can add as per your requirement.
protected void SendMail()
{
// Gmail Address from where you send the mail
var fromAddress = "[email protected]";
// any address where the email will be sending
var toAddress = txtEmail.Text.ToString();
//Password of your gmail address
const string fromPassword = "Your gmail password";
// Passing the values and make a email formate to display
string subject = txtSubject.Text.ToString();
// Passing the values and make a email formate to display
string body = "From: " + txtname.Text + "\n";
body += "Email: " + txtEmail.Text + "\n";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(fromAddress, toAddress, subject, body);
}
Now the above function will be called on Button click so that every time you enter the details you can call that function.
protected void btnSubmit_OnClick(object sender, EventArgs e)
{
try
{
SendMail(); // Send mail function to send your mail
txtname.Text = "";
txtEmail.Text = "";
txtmobileno.Text = "";
txtSubject.Text = "";
}
catch (Exception ex)
{
ex.Message.ToString();
}
}
For a detail explanation have a look at below link:-
http://www.codeproject.com/Tips/371417/Send-Mail-Contact-Form-using-ASP-NET-and-Csharp
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34588595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How do I stop a uWSGI server after starting it? I have a Python pyramid application that I am running using uwsgi like so:
sudo /finance/finance-env/bin/uwsgi --ini-paste-logged /finance/corefinance/production.ini
Once it's running and my window times out, I am unable to stop the server without rebooting the whole box. How do I stop the server?
A: If you add a --pidfile arg to the start command
sudo /finance/finance-env/bin/uwsgi --ini-paste-logged /finance/corefinance/production.ini --pidfile=/tmp/finance.pid
You can stop it with the following command
sudo /finance/finance-env/bin/uwsgi --stop /tmp/finance.pid
Also you can restart it with the following command
sudo /finance/finance-env/bin/uwsgi --reload /tmp/finance.pid
A: You can kill uwsgi process using standard Linux commands:
killall uwsgi
or
# ps ax|grep uwsgi
12345
# kill -s QUIT 12345
The latter command allows you to do a graceful reload or immediately kill the whole stack depending on the signal you send.
The method you're using, however, is not normally used in production: normally you tell the OS to start your app on startup and to restart it if it crashes. Otherwise you're guaranteed a surprise one day at a least convenient time :) Uwsgi docs have examples of start scripts/jobs for Upstart/Systemd.
Also make sure you don't really run uwsgi as root - that sudo in the command makes me cringe, but I hope you have uid/gid options in your production.ini so Uwsgi changes the effective user on startup. Running a webserver as root is never a good idea.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38938440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Akka Generic Custom Directives I am using custom directives to validate my params:
def optionalIntParamAs[C](parameterName: String, validator: Int => C Or ErrorMessage): Directive1[Option[C]] =
parameter(parameterName.as[Int].?)
.recoverPF[Tuple1[Option[Int]]] {
case Seq(MalformedQueryParamRejection(name, msg, cause)) =>
reject(MalformedQueryParamRejection(name,
s"Invalid value '${msg.split("'")(1)}' for query parameter '$name'.", cause))
}
.flatMap {
case Some(intParam) =>
validator(intParam) match {
case Good(c) => provide(Some(c))
case _ => reject(ValidationRejection(s"Invalid value '$intParam' for query parameter '$parameterName'."))
}
case _ => provide(None)
}
to be used in my route as :
optionalIntParamAs[PageSize]("pageSize", PageSize.validate) { pageSize =>
...
}
I would like to have a generic directive so I can write:
optionalParam[Int].as[PageSize]
optionalParam[String].as[...]
Any suggestion ?
Update: with Stefano's solution we will get this compile error:
found : akka.http.scaladsl.common.NameOptionReceptacle[In] [error]
required:
akka.http.scaladsl.server.directives.ParameterDirectives.ParamMagnet
[error] parameter(parameterName.as[In].?)
why ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42792100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Media Foundation - Sequencer Source Loop I'm trying to make a video player that plays videos in sequence, seamlessly and with looping. The "sequence" and "seamless" part was resolved by using Sequencer Source. But the "loop" part is giving me headaches!
What I'm trying to do is capture the MEEndOfPresentation event, and when it's captured I do these steps:
*
*Pause Media Session;
*Grab the first segment ID;
*Call MFCreateSequencerSegmentOffset using step 2 result;
*Call Media Session Start using step 3 result.
And this works. Works if I set MF_TOPONODE_NOSHUTDOWN_ON_REMOVE on the output node to TRUE. However, this produces a HUGE memory leak that reaches 2gb in minutes!
If I set MF_TOPONODE_NOSHUTDOWN_ON_REMOVE to FALSE, then the steps presented don't work. Is the strategy I'm using correct?
I logged the events to see what I'm receiving after play. Here they are in each case:
MF_TOPONODE_NOSHUTDOWN_ON_REMOVE = FALSE
MENewPresentation, Event Status: S_OK
# then I queue the next segment
MESessionTopologyStatus, Event Status: S_OK, Topology Status: StartedSource
MESessionTopologyStatus, Event Status: S_OK, Topology Status: Ended
MESessionTopologyStatus, Event Status: S_OK, Topology Status: SinkSwitched
MESessionTopologyStatus, Event Status: S_OK, Topology Status: Ready
MESessionTopologyStatus, Event Status: S_OK, Topology Status: StartedSource
MEEndOfPresentation, Event Status: S_OK, Canceled: 0
# then I do the steps mentioned
MENewPresentation, Event Status: S_OK
# then I queue the next segment
MESessionTopologyStatus, Event Status: S_OK, Topology Status: Ended
MF_TOPONODE_NOSHUTDOWN_ON_REMOVE = TRUE
MENewPresentation, Event Status: S_OK
# then I queue the next segment
MESessionTopologyStatus, Event Status: S_OK, Topology Status: StartedSource
MESessionTopologyStatus, Event Status: S_OK, Topology Status: Ended
MESessionTopologyStatus, Event Status: S_OK, Topology Status: SinkSwitched
MESessionTopologyStatus, Event Status: S_OK, Topology Status: Ready
MESessionTopologyStatus, Event Status: S_OK, Topology Status: StartedSource
MEEndOfPresentation, Event Status: S_OK, Canceled: 0
# then I do the steps mentioned
MENewPresentation, Event Status: S_OK
# then I queue the next segment
MESessionTopologyStatus, Event Status: S_OK, Topology Status: Ended
MESessionTopologyStatus, Event Status: S_OK, Topology Status: SinkSwitched
MESessionTopologyStatus, Event Status: S_OK, Topology Status: Ready
MESessionTopologyStatus, Event Status: S_OK, Topology Status: StartedSource
MESessionTopologyStatus, Event Status: S_OK, Topology Status: Ended
MESessionTopologyStatus, Event Status: S_OK, Topology Status: SinkSwitched
...
P.S. I haven't added the code because it's very large. But if you need, I can edit my question.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43529913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why is Controller.View returning null? I'm unit testing someone else's ASP.Net MVC4 Controller action method. Its last line is:
return this.View("ConfirmAddress", addressModel);
This returns null in my unit test. The Controller.View documentation says the first parameter is a view name but I can't step into this method to find out why null is returned. A ConfirmAddress.cshtml exists in the Views folder but there's also a ConfirmAddress(AddressModel am) action in the controller.
Can anyone tell from this what it should be doing (e.g. perhaps use RedirectToAction instead???) Have tried to keep this short but could provide more info if needed...
A: I have looked at the official source code of the Controller class to see what happens when View is called. It turns out, all the different View method overloads ultimately call the following method:
protected internal virtual ViewResult View(string viewName, string masterName, object model)
{
if (model != null)
{
ViewData.Model = model;
}
return new ViewResult
{
ViewName = viewName,
MasterName = masterName,
ViewData = ViewData,
TempData = TempData,
ViewEngineCollection = ViewEngineCollection
};
}
This method (and thus all the other overloads) will never return NULL, although it could throw an exception. It is virtual though, which means that the code your are calling might override it with a custom implementation and return NULL. Could you check if the View method is overridden anywhere?
A: It's possible that the View method is overridden. Try removing the this quantifier.
return View("ConfirmAddress", addressModel);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15947533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: D3 tickValues not working I have following D3 axis:
var x = d3.scale.ordinal()
.domain(["A", "B", "C", "D", "E"])
.rangePoints([0, width]);
var xAxis = d3.svg.axis()
.scale(x)
.tickValues(["a", "b", "c", "d", "e"])
.orient("bottom");
working fiddle here: https://jsfiddle.net/akshayKhot/1vusrdvc/
The tickValues are not showing other than the first one. Am I missing something?
A: You need a range value for every one of your ordinal values:
var x = d3.scale.ordinal()
.domain(["A", "B", "C", "D", "E"])
.range([0, 1/4 * width, 2/4 * width, 3/4 * width, width]);
https://jsfiddle.net/39xy8nwd/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37738113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: doing a simple SSIS-style data flow in c# without any external libraries I'm looking for an example of a simple data flow in C# without relying on SSIS or external libraries such as Rhino-ETL (which is a very good library, BTW).
Requirements:
*
*One arbitrary ADO .Net data source
*One arbitrary ADO .Net data destination
*Does not require entire dataset to be loaded into memory at once, so that it can handle arbitrarily large data sets. It would need to rely on a buffer of some sort, or "yield return" like Rhino ETL takes advantage of.
*Uses bulk insert (i.e. SqlBulkCopy)
*Minimal transformation. No lookups, no merge joins.
*Multi-threaded is not necessary if single threaded can do the job.
Another way of stating the question ... how does Rhino ETL do this, but without all the abstractions and inherited classes, and without the quacking dictionary? I would like to see it in a simple non-abstract class.
And yet another rephrasing of the question: I'm looking for the fundamental example of taking a data flow output of a "select" query, and bulk inserting it at 10,000 or 50,000 records at a time to a destination without loading the entire result into memory, which could potentially exceed available RAM.
A: It looks like you want to learn how an etl program works to increase your knowledge of programming.
Rhino ETL is an open source project, so you can get the source here:
https://github.com/ayende/rhino-etl
and see exactly how they do it. There are also other ETL packages that are Open Source so you can see the way that they do things differently. For example talend source can be found at:
http://www.talend.com/resources/source-code.php
Of course, if you are trying to write your own code for commercial use, you will not want to see the source code of others, so you will need to come up with your process on your own.
Hope this helps you!
A: Far from a complete answer I'm afraid.
You can "page" the results of an arbitrary select query within .Net using one or more of the techniques outlined here.
http://msdn.microsoft.com/en-us/library/ff650700.aspx
This should allow you to chunk up the data and avoid RAM concerns.
Alternatively - if your existing SSIS packages are simple / similar enough, then it could be worth while to have a look at generating the SSIS packages automatically based on a template. For example I'm maintaining 100+ packages that are automatically generated by a small c# application using the EzAPI API for SSIS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8764426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ThenInclude with many to many in EF Core I have the following tables:
public class Parent
{
[Key]
public long Id { get; set; }
[ForeignKey("ParentId")]
public List<Person> Persons { get; set; }
}
public class Person
{
[Key]
public long Id { get; set; }
public long ParentId { get; set; }
[ForeignKey("PersonId")]
public List<Friend> Friends { get; set; }
}
public class Friend
{
public long PersonId { get; set; }
public long FriendId { get; set; }
[ForeignKey("FriendId")]
public Person Friend { get; set; }
}
The Friend table is a many-to-many relationship between two rows of the Person table. It has a PK composed from the PersonId and the FriendId, declared like this:
modelBuilder.Entity<Friend>(entity =>
{
entity.HasKey(e => new { e.PersonId, e.FriendId });
});
modelBuilder.Entity<Friend>()
.HasOne(e => e.Friend)
.WithMany()
.OnDelete(DeleteBehavior.Restrict);
I want to get all parents with all persons and all their friends, which would look like this:
var entities = context.Parents
.AsNoTracking()
.Include(c => c.Persons)
.ThenInclude(i => i.Friends)
.ToList();
However this does not get the data from the Friends table.
If I inlcude the friends in a person query without the parent it works:
var entities = context.Persons
.AsNoTracking()
.Include(i => i.Friends)
.ToList();
I am using EF Core version 2.2 .
How can I make the first query to retrieve the firends of a person as well and what is causing this behavior?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59506237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Where to find jquery UI Tabs widget API document I find someone write the jquery codes as below:
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#tabs").tabs();
$("#tabs").bind("tabsselect", function (e, tab) {
alert("The tab at index " + tab.index + " was selected");
});
});
</script>
He binds the 'tabsselect' event.
I try to find more detail about tabselect event.So I visit the URL:http://api.jqueryui.com/tabs/
But I didn't find the tabselect event. Did I visit the wrong URL?
or anything I was misleaded?
A: The select event was renamed to activate in 1.9: http://api.jqueryui.com/tabs/#event-activate
There's documentation for 1.8 as well, including the select event: http://api.jqueryui.com/1.8/tabs/#event-select
The select event was deprecated, so it still works in 1.9, unless you set $.uiBackCompat = false. More info in the 1.9 upgrade guide: http://jqueryui.com/upgrade-guide/1.9/#preparing-for-jquery-ui-1-10
A: Before jQueryUI changed their site a few months ago, the documentation existed. You can also use:
$("#tabs").tabs({
select:function(eventt,ui){
alert("The tab at index " + ui.index + " was selected");
}
});
If you want to see more detail as to what is available in the ui object ( or tab in your code), log it to a console.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13504409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Syntax Error with Foreign Key in `` Quotes Need your small help here, I was trying to do a join which is showing syntax Error.
syntaxError: invalid syntax
df_results = df_tempTable2.join(df_parent, df_tempTable2.`entity_key|inv.entity|entity_id|entity_key|FK` == df_parent.enterprise_id,"inner")
Not sure how to use FK with ``, or how, as this might be the cause here- df_tempTable2.entity_key|inv.entity|entity_id|entity_key|FK
where as entity_key|inv.entity|entity_id|entity_key|FK is a Foreign Key.
A: This worked-
df_tempTable2.join(df_parent, on = [df_tempTable2["`entity_key|inv.entity|entity_id|entity_key|FK`"] == df_parent["enterprise_id"]], how = "inner")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74388984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: nodejs route.get to SEND a post request The get to this route works fine.
But how do I take my route.get() and make it do a post?
If the post is written in jquery, or express, or something else I don't care. Below I just used the jquery as an example.
router.get('/', function (req, res, next) {
var url = 'blabla'
$.post('anotherBlaBla'
, { app: url }
);
});
A: You can use http client axios
Performing a POST request
var axios = require('axios');
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
A: const request = require('request');
var url = 'blabla';
request.post(
url
, { json: { api: url } }
, function (err, res, bdy) {
if (!err && res.statusCode == 200)
console.log(bdy)
}
);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43157227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Mega-menu for Modern team site I started a modern team site in SPO and added lots of pages and link to them in the quick link.
Now the users want Mega-Menu instead of the quick link.
I tried to copy the pages to a new communication sites that has mega-menu but there is a difference in the site template that does not let me do it.
I also tried to get the rest call to create the menu with jQuery.
https://{mydomain}.sharepoint.com/{musite}/_api/contextinfo tells me:
Access denied. You do not have permission to perform this action or access this resource
Is there a way to query the quick link and build a mega-menu?
Any good we to transform a team site to communication site?
Thanks in advance
A: If your team site is a classic team site then no, you can't have a megamenu unless you make a custom one.
IF your team site is a modern team site then you inherit the megamenu from a hub site I believe.
I have a feeling you have a classic team site with modern pages in it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57793811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: sleep function will abort when received a signal? #include <signal.h>
#include <stdio.h>
void ints(int i )
{
printf("ints \n");
}
int main(void)
{
signal(SIGINT, ints);
sleep(10);
}
input Ctrl+C , the program will terminate immediately with output:
^ints
I was wondering why,in my opinion,the program should terminate after 10 seconds no matter how many times Ctrl+C is input.
A: sleep() is one of those functions that is never re-started when interrupted.
interestingly, it also does not return a EINT as one would expect.
It instead returns success with the time remaining to sleep.
See:
http://www.kernel.org/doc/man-pages/online/pages/man7/signal.7.html
for details on other APIs that do not restart when interrupted
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9661419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jQuery UI Layout and Constraining Dialogs to the Central Pane I am trying to create a full page interface using the excellent jQuery UI Layout plugin.
I want the central pane to hold multiple dialogs and allow them to be contained within that pane. So far so good. However, I also want to be able to drag the dialogs "out of the way", and move them to the right or bottom so that the central pane develops scroll bars and allows the central pane to act as a scrollable desktop for dialog boxes. I want the other pane(s) to be always there for other UI purposes.
HTML:
<div class="ui-layout-center">
<div id="dialog1">dialog 1</div>
<div id="dialog2">dialog 2</div>
</div>
<div class="ui-layout-north">North</div>
<div class="ui-layout-south">South</div>
<div class="ui-layout-west">West</div>
jQuery:
$('body').layout(
{
applyDemoStyles: true,
livePaneResizing : true
});
var dialog1 = $("#dialog1")
.dialog({})
.parent().appendTo( $(".ui-layout-center") );
dialog1.draggable( "option", "containment", $(".ui-layout-center") );
$("#dialog2")
.dialog({})
.parent().appendTo( $(".ui-layout-center") );
As you can see, it almost works, but the scrolling doesn't work horizontally. I've experimented with containing dialog1 but this makes things worse! Perhaps it's just a CSS issue or that combined with a setting. Any ideas?
jsFiddle
A: The solution turned out to me a case of manipulating the underlying draggable of the dialog box:
$("#dialog2").dialog("widget").draggable(
{
containment : [ 0, 0, 10000, 10000 ],
scroll: true,
scrollSensitivity : 100
});
Obviously, these values can be played with to achieve different results. I hope this helps anyone else in the same position!
jsFiddle
A: I looked over the documentation and apparently you are able to achieve this with using CSS and changing the overflow value.
http://jsfiddle.net/vnVhE/1/embedded/result/
As you can see the CSS applied is:
// disable scrolling in the other panes
.ui-layout-pane-north ,
.ui-layout-pane-west,
.ui-layout-pane-south {
overflow: hidden !important;
}
.ui-layout-layout-center {
overflow: auto
}
NOTE: Please keep in mind while this allows horizontal scrolling it is a bit tricky and hackish at best in my opinion. Under Chrome I could scroll just fine if I held the mouse near the edge of the vertical scroll bar and it moved properly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23226555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to post a jsf data in Android Can I post a jsf form data in Android?For example this jsf page ;
<h:form>
<h:panelGrid columns="2" border="0">
<h:outputLabel value="Adınız : "/>
<h:inputText value="#{pd.ad}"/>
<h:outputLabel value=""/>
<h:commandButton value="Gönder" action="#{pd.kontrol()}"/>
</h:panelGrid>
</h:form>
<h:outputText value="#{pd.sonuc}" />
I want to post "ad" data in Android.Here is my Android codes;
private TextView postData;
private String url = "http://localhost:8084/AndroidIc_nPOSTsayfa";
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
postData = (TextView)findViewById(R.id.postData);
try {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("#{pd.sonuc}", "Mesut Emre"));
httpPost.setEntity(new UrlEncodedFormEntity(pairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpClient.execute(httpPost,responseHandler);
System.out.println(response);
postData.setText("Alınan veri:"+response);
} catch (Exception e) {
e.printStackTrace();
}
}
When I runt the app there is no error but I cant see my sended data on textview.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19291557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to launch an app from another app in my app i have to launch another app, only if it is not yet launched.
To launch an app what i do is:
PackageManager pm = getPackageManager();
Intent intent = pm.getLaunchIntentForPackage("package.of.app.to.launch");
startActivity(intent);
My problem is that if app is already launched, it will bring the app to the front. How can i launch app only if is not present in active and launched apps? thanks!
A: You can get a list of all running or active apps and then check if the App you want to start is in it.
ActivityManager activityManager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> runningProcInfo = activityManager.getRunningAppProcesses();
for(int i = 0; i < runningProcInfo.size(); i++){
if(runningProcInfo.get(i).processName.equals("package.of.app.to.launch")) {
Log.i(TAG, "XXXX is running");
} else {
// RUN THE CODE TO START THE ACTIVITY
}
}
A: You can use ActivityManager to get Currently running Applications and to get recent task executed on Device as:
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> recentTasks = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (int i = 0; i < recentTasks.size(); i++)
{
// Here you can put your logic for executing new task
}
A: If you want to know whether an app is running or not, you should have a look at getRunningTasks
Also this post might help you.
A: you can get that which activity is running
List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);
String currentActivity=taskInfo.get(0).topActivity.getPackageName();
then check
if(currentActivity!=(your activity))
{
**your intent**
}
else{
"app already running"
}
hope it helps.
thank you
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13378628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Custom UIView from Interface Builder I'm trying to keep things organized and create hierarchy of views for my app.
So for instance I want to create a custom view to display some text, another custom view to display progress and then use all those views in the main view created with View-Based Application template.
I know how to create it programmatically - you create UIView subclass, implement drawRect method, place an empty UIView in Interface Builder and chance it's Class to my custom class. My problem is that I want to create those custom view's in Interface Builder instead programmatically.
So far I've created UIViewController controller with XIB file and in viewDidLoad method of view controller from the template I create that custom view controller instance and add it's view as a subview of that empty UIView added in Interface Builder (the same you would change Class in programmatic approach).
It works, but it's more of a hack for me and it's hard for me to believe that there isn't a better method where I could add those custom views in interface builder without having to implement viewDidLoad method and create controllers and add their views inside of that method.
A: For this to work, you have to create a plug-in for Interface Builder that uses your custom control's class. As soon as you create and install your plug-in, you will be able to add by drag and drop, instances of your view onto another window or view in Interface Builder. To learn about creating IB Plugins, see the Interface Builder Plug-In Programming Guide and the chapter on creating your own IB Palette controls from Aaron Hillegass's book, Cocoa Programming for Mac OS X.
Here is the link to the original author of the accepted answer to a similar question.
A: This was originally a comment in Ratinho's thread, but grew too large.
Although my own experience concurs with everything mentioned here and above, there are some things that might ease your pain, or at least make things feel a little less hack-ish.
Derive all of your custom UIView classes from a common class, say EmbeddableView. Wrap all of the initWithCoder logic in this base class, using the Class identity (or an overloadable method) to determine the NIB to initialize from. This is still a hack, but your at least formalizing the interface rules and hiding the machinery.
Additionally, you could further enhance your Interface Builder experience by using "micro controller" classes that pair with your custom views to handle their delegate/action methods and bridge the gap with the main UIViewController through it's own delegation protocol. All of this can be wired together using connectors within Interface Builder.
The underlying UIViewController only needs to implement enough functionality to satisfy the "micro controller" delegation pattern.
You already have the details for adding the custom views by changing the class name and handling the nib loading. The "micro controllers" (if used) can just be NSObject derived classes added to the NIB as suggested here.
Although I've done all of these steps in isolated cases, I've never taken it all the way to this sort of formal solution, but with some planning it should be fairly reliable and robust.
A: Maybe i didnt understand u?
you have library in the Interface builder u can move every component u want and place it on your view. (u can add another view by adding UIView and change its class name in the 4th tab).
then u declare vars with IBOutlet and connect them from the 2nd tab of ur file's owners to their components...another question?
A: Unfortunately, you can't do what you want to do with UIKit. IB Plugins only work for OS X, and Apple explicitly doesn't allow them for use with iOS development. Something to do with them not being static libraries. Who knows, they may change this someday, but I wouldn't hold your breath.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4869424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Why is the containsKey() function not detecting the repeated char as the key in Dart in the problem below? The containsKey() function is not detecting the repeated value in my test 'current' string, where it just replaces the original value of the key 'r' with 3, when it should go through the containsKey() function, as see that there is a value at 2, and then replace that key with a new one.
void main(){
Map<String, String> split = new Map();
var word = 'current ';
for (int i = 0; i < word.length; i++) {
String temp = word[i];
if (split.containsKey([temp])) {
split[temp] = split[temp]! + ' ' + i.toString();
} else {
split[temp] = i.toString();
}
}
print(split.toString());
}
The output produces
{c: 0, u: 1, r: 3, e: 4, n: 5, t: 6}
while I want it to produce {c: 0, u: 1, r: 2 3, e: 4, n: 5, t: 6}
A: It is because you are doing split.containsKey([temp]) instead of split.containsKey(temp).
In your snippet, you are checking whether the map split has the array [temp] as a key, (in the case of 'r': ['r']), which is false, it has 'r' as a key, not ['r'].
Change your code to
void main(){
Map<String, String> split = new Map();
var word = 'current ';
for (int i = 0; i < word.length; i++) {
String temp = word[i];
if (split.containsKey(temp)) { // <- Change here.
split[temp] = split[temp]! + ' ' + i.toString();
} else {
split[temp] = i.toString();
}
}
print(split.toString());
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73808439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Loop through groups of spans in JQuery <td style="display:none;">
<span class="runId">4</span><span class="processName">Get End-Of-Day Reuters Feed Rates</span>
<span class="runId">130</span><span class="processName">Get End-Of-Day Bloomberg Feed Rates</span>
<span class="runId">133</span><span class="processName">CapVolsCalibration AllCurrencies EOD</span>
<span class="runId">228</span><span class="processName">GBP Basis Adjustment</span>
</td>
Hey guys, how would I loop through this <td> in JQuery and for each group of two span elements, get the text() of the runId and the processName elements.
A: $("span.runId").each(function(){
var runId = $(this).text(),
processname = $(this).next("span.processName").text();
});
A: Functional programming to the rescue:
var data = $td.children('span.runId').map(function() {
return {runId: $(this).text(), processName: $(this).next().text()};
}).get();
Structure the data how ever you want to.
A: To be honest, I would suggest that if they have that type of correlation that they are wrapped together in another tag, or better yet combined as they are not even displayed. This, of course, does not apply to parsing code you do not have write/modify access to.
Suggested html:
<table>
<tr>
<td style="display:none;">
<span data-runid='4' class="processName">Get End-Of-Day Reuters Feed Rates</span>
<span data-runid='130' class="processName">Get End-Of-Day Bloomberg Feed Rates</span>
<span data-runid='133' class="processName">CapVolsCalibration AllCurrencies EOD</span>
<span data-runid='228' class="processName">GBP Basis Adjustment</span>
</td>
</tr>
</table>
jQuery:
$("td span.processName").each(function() {
var runid, processName, $this = $(this);
runid = $this.data('runid');
processName = $this.text();
});
I'm not exactly sure what your needs are, but I'd even get rid of the class processName as well. Since the data isn't displayed, it's not really needed at this level assuming you don't need to access this for other purposes. This minimizes down to:
html:
<table id='someId'>
<tr>
<td style="display:none;">
<span data-runid='4'>Get End-Of-Day Reuters Feed Rates</span>
<span data-runid='130'>Get End-Of-Day Bloomberg Feed Rates</span>
<span data-runid='133'>CapVolsCalibration AllCurrencies EOD</span>
<span data-runid='228'>GBP Basis Adjustment</span>
</td>
</tr>
</table>
jQuery:
$("#someId").find('td span').each(function() {
var runid, processName, $this = $(this);
runId = $this.data('runid');
processName = $this.text();
});
Technically, you can't have a span outside of a td in a table, so it could be reduced further:
$("#someId").find('span').each(function() {
var runid, processName, $this = $(this);
runId = $this.data('runid');
processName = $this.text();
});
A: So many ways to do things with jQuery:
$('td > span:nth-child(2n-1)').text(function(i,txt) {
alert(txt + $(this).next().text());
});
Example: http://jsfiddle.net/vqs38/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6427490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unexpected value 'DecoratorFactory' imported by the module 'DynamicTestModule' - karma-jasmine I'm getting error during creating Test component instance.
let comp: TaskviewComponent;
let fixture: ComponentFixture;
let deTaskTitle: DebugElement;
let elSub: HTMLElement;
describe('TaskviewComponent', () => {
beforeEach( () => {
TestBed.configureTestingModule({
declarations: [
TaskviewComponent
],
imports: [
NgModule,
RouterTestingModule,
TranslateModule.forRoot(),
],
providers: [
RestDataService,
Restangular,
{provide: OAuthService, useClass: OAuthServicMock},
{provide: ComponentFixtureAutoDetect, useValue: true},
{provide: UserInfoService, useClass: UserInfoServiceMock},
{
provide: LocalStorageService, //provide: LOCAL_STORAGE_SERVICE_CONFIG,
useValue: {
prefix: ApplicationConstants.ANGULAR2_LOCAL_STORAGE_ID,
storageType: 'sessionStorage'
}
}],,
})
fixture = TestBed.createComponent(TaskviewComponent);
comp = fixture.componentInstance;
deTaskTitle = fixture.debugElement.query((By.css('.Subject')));
elSub = deTaskTitle.nativeElement;
});
it('should have a subject', () => {
expect(elSub.textContent).toContain('Client Data Maintenance2 ');
});
});
I'm getting Error: Unexpected value 'DecoratorFactory' imported by the module 'DynamicTestModule' error. I notice that if I remove "fixture = TestBed.createComponent(TaskviewComponent);" error would be resolved. but this will not create the Test Component. Also, I notice that if I don't include NgModule in imports[], elements like Ngmodel, datepicker etc.are not recognized.
A: You can't import "NgModule" as it is a decorator and not a module.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41277642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: JS Replace text in between unique expression in parentheses (i) My intention is to build a parsing function which searches within a string (think blog post) for any substrings wrapped around unique identifiers in parentheses, like (i).
My current implementation isnt working. Would truly appreciate any help!
let text = "Hello there (i)Sir(i)";
let italics = /\(i\)(.?*)\(i\)/gi;
let italicsText = text.match(italics);
// text.replace(italics, <i>)
A: You can use replace here with regex as:
\((.*?)\)/g
Second argument to replace is a replacer function.
replace(regexp, replacerFunction)
A function to be invoked to create the new substring to be used to
replace the matches to the given regexp or substr.
How arguments are passed to replacer function
let text = 'Hello there (i)Sir(i)';
let italics = text.replace(/\((.*?)\)/g, (_, match) => `<${match}>`);
console.log(italics);
let text2 = 'Hello there (test)Sir(test)';
let italics2 = text2.replace(/\((.*?)\)/g, (_, match) => `<${match}>`);
console.log(italics2);
A: Use the JavaScript "replaceAll" function:
let text = "Hello there (i)Sir(i)";
console.log(text.replaceAll("(i)", "<i>"));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72967685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Import numpy raise import error numba needs numpy 1.21 or less I tried to import numpy and I recieved the following error: "raise ImportError("Numba needs NumPy 1.21 or less")
ImportError: Numba needs NumPy 1.21 or less" we already downloaded numba 0.48 and numpy 1.18.1 and it still asks to use numpy 1.21 or less. can anyone helps me on this issue? I attached 2 screenshots, one is the code and the other one is the error message.Thanks
A: if you are not using virtual enivrements, i suggest you install and use ANACONDA.
Solution:
for this error i think using Numpy==1.21.4 and Numba==0.53.0 will solve your problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71626701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: MySQL multi source replication Can somebody write me step by step how to make multi source replication. I read a lot of info about it but i have a problem with gtid-mode. I turn on gtid-mode in my.ini file on the master computer but when i make dump on databases i got error with gtid executed need to be empty.
A: Try to execute:
slave> reset master;
slave> source dump.sql;
slave> start slave;
slave> show slave statusG
[...]
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
[...]
A: 10:53:52 Restoring C:\Users\KasiSTD\Desktop\master3-1.sql Running: mysql.exe --defaults-file="c:\users\kasistd\appdata\local\temp\tmpmw0avv.cnf" --protocol=tcp --host=localhost --user=root --port=3306 --default-character-set=utf8 --comments < "C:\Users\KasiSTD\Desktop\master3-1.sql" ERROR 1840 (HY000) at line 26: @@GLOBAL.GTID_PURGED can only be set when @@GLOBAL.GTID_EXECUTED is empty. Operation failed with exitcode 1 10:53:53 Import of C:\Users\KasiSTD\Desktop\master3-1.sql has finished with 1 errors
This is error from mysql server 5.7 when i try to make import backup file
This is my.ini file only changes in [mysqld] log-bin=mysql-bin binlog-do-db=master3 auto_increment_increment = 2 gtid-mode = on enforce-gtid-consistency = 1 Server Id server-id=4
A: mysql> show slave status for channel 'master-joro'\G
*************************** 1. row ***************************
Slave_IO_State: Connecting to master
Master_Host: 192.168.1.62
Master_User: joro
Master_Port: 3306
Connect_Retry: 60
Master_Log_File: mysql-bin.000003
Read_Master_Log_Pos: 1066
Relay_Log_File: [email protected]
Relay_Log_Pos: 4
Relay_Master_Log_File: mysql-bin.000003
Slave_IO_Running: Connecting
Slave_SQL_Running: Yes
Replicate_Do_DB: id,master2,final_repl
Replicate_Ignore_DB:
Replicate_Do_Table:
Replicate_Ignore_Table:
Replicate_Wild_Do_Table:
Replicate_Wild_Ignore_Table:
Last_Errno: 0
Last_Error:
Skip_Counter: 0
Exec_Master_Log_Pos: 1066
Relay_Log_Space: 154
Until_Condition: None
Until_Log_File:
Until_Log_Pos: 0
Master_SSL_Allowed: No
Master_SSL_CA_File:
Master_SSL_CA_Path:
Master_SSL_Cert:
Master_SSL_Cipher:
Master_SSL_Key:
Seconds_Behind_Master: NULL
Master_SSL_Verify_Server_Cert: No
Last_IO_Errno: 0
Last_IO_Error:
Last_SQL_Errno: 0
Last_SQL_Error:
Replicate_Ignore_Server_Ids:
Master_Server_Id: 0
Master_UUID:
Master_Info_File: mysql.slave_master_info
SQL_Delay: 0
SQL_Remaining_Delay: NULL
Slave_SQL_Running_State: Slave has read all relay log; waiting for more up
dates
Master_Retry_Count: 86400
Master_Bind:
Last_IO_Error_Timestamp:
Last_SQL_Error_Timestamp:
Master_SSL_Crl:
Master_SSL_Crlpath:
Retrieved_Gtid_Set:
Executed_Gtid_Set: 2069dbc8-2c85-11e6-b4ce-0027136c5f75:1
Auto_Position: 0
Replicate_Rewrite_DB:
Channel_Name: master-joro
Master_TLS_Version:
1 row in set (0.00 sec)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37781879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Python loop through single cell and column in a csv I have just picked up python and I am trying to use the module fuzzwuzzy in tandem with pandas to assist in matching names from PLACEMENT and CREATIVE_NAME columns.
I have figured out how to test the first row of PLACEMENT against all rows of CREATIVE_NAME; however, I cannot figure out how to move to the next row of PLACEMENT and test against the CREATIVE_NAME column.
My eventual goal of the project is for the top match(s) for each PLACEMENT value to be printed out for further analysis.
df = pd.read_csv(filepath)
fp = df["PLACEMENT"]
tp = df["CREATIVE_NAME"]
score = 0
x=0
y=0
import csv
with open(filepath, 'r') as f:
reader = csv.DictReader(f)
for column in reader:
if score == 0:
score += fuzz.ratio(fp[x],tp[y])
if score > 95:
print "The score is %d"", We have a match!" %(score)
elif score > 70:
print "The score is %d"", We have a high likelihood of a match!" %(score)
elif score > 50:
print "The score is %d"", The match is not likely!" %(score)
else:
print "The score is only %d"", This is not a match!" %(score)
y += 1
score = 0
A: You basically need to match all entries in the placement column against all entries in the creative name column. This can be done by a nested loop: for each placement, for each creative name, compare the placement and the creative name.
The FuzzyWuzzy library has a convenience function that can be used to replace the inner loop by a single function call that extracts the best matches:
from fuzzywuzzy import process
for placement in fp:
best_matches = process.extract(placement, tp, limit=3)
print placement, best_matches
Be warned though that this will need n² comparisons, where n is the number of rows in your data set. Depending on the size of the data set, this might take a long time.
Note that you don't need to open the file after reading the data set into memory via pandas. Your loop over the reopened file doesn't make any use of the column loop variable (which should be called row, by the way).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32225088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: add different widgets to each wxnotebook tab permanently in a txt file or sqlite Please how can I add permanently different widgets in the tabs and save them permanently
<html>
<pre>
import wx
tabs = []
with open('test.txt','r') as file:
for element in file.readlines():
tabs.append(element)
class TabPanel(wx.Panel):
def __init__(self, parent, pageNum):
self.parent = parent
self.pageNum = pageNum
wx.Panel.__init__(self, parent=parent)
class DemoFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Notebook", size=(600,400))
panel = wx.Panel(self)
self.tab_num = len(tabs)
self.notebook = wx.Notebook(panel)
for tab in tabs:
name = "Page " + str(tab)
tab = TabPanel(self.notebook, 1)
self.notebook.AddPage(tab, name)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.notebook, 1, wx.ALL|wx.EXPAND, 5)
btn = wx.Button(panel, label="Add Page")
btn.Bind(wx.EVT_BUTTON, self.addPage)
sizer.Add(btn)
panel.SetSizer(sizer)
self.Layout()
self.Show()
def addPage(self, event):
self.tab_num += 1
new_tab = TabPanel(self.notebook, self.tab_num)
self.notebook.AddPage(new_tab, "Page %s" % self.tab_num)
tabs.append(self.tab_num)
print()
with open('test.txt','a+') as file:
file.write(str(self.tab_num))
file.write('\n')
if __name__ == "__main__":
app = wx.App(False)
frame = DemoFrame()
app.MainLoop()
</pre>
</html>
A: Something like this should get you started (sorry not readdly familiar with python):
class DemoFrame(wx.Frame):
def __init__(self):
self.tab_num = 1
wx.Frame.__init__(self, None, wx.ID_ANY, "Notebook", size=(600,400))
panel = wx.Panel(self)
with open( "test.txt", "r" as file:
self.tab_num = file.read()
self.notebook = wx.Notebook(panel)
for tab in [1..self.tab_num]:
name = "Page " + str(tab)
tab = TabPanel(self.notebook, 1)
self.notebook.AddPage(tab, name)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.notebook, 1, wx.ALL|wx.EXPAND, 5)
btn = wx.Button(panel, label="Add Page")
btn.Bind(wx.EVT_BUTTON, self.addPage)
sizer.Add(btn)
panel.SetSizer(sizer)
self.Layout()
self.Show()
def addPage(self, event):
self.tab_num += 1
new_tab = TabPanel(self.notebook, self.tab_num)
self.notebook.AddPage(new_tab, "Page %s" % self.tab_num)
tabs.append(self.tab_num)
print()
with open('test.txt','a+') as file:
file.write(str(self.tab_num))
file.write('\n')
if __name__ == "__main__":
app = wx.App(False)
frame = DemoFrame()
app.MainLoop()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61845435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why function argument evaluation cannot be ordered? As far as we know, the function argument evaluation order is not defined by c++ standard.
For example:
f(g(), h());
So we know it is undefined.
My question is, why cant c++ standard define the order of evaluation from left to right??
A: Because there is no good reason to do so.
The c++ standard generally only defines what is necessary and leaves the rest up to implementers.
This is why it produces fast code and can be compiled for many platforms.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50062906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to Manually Calculate Intercept (Beta 0) and Coefficient (Beta 1) in Logistic Regression? I'm currently studying about Logistic Regression. But i'm getting stuck at calculating Intercept (Beta 0) and Coefficient (Beta 1). I've been looking for it through the internet, but only get tutorials using Microsoft Excel or built-in function in R. I heard it can be solved by Maximum Likelihood, but i don't understand how to use it, because i don't have a statistical background. Is anyone can give me a brief explanation and simulation about calculating Intercept (Beta 0) and Coefficient (Beta 1)?
A: There are no closed form solutions for logistic regression, but there are many iterative methods to learn its parameters. One of the simplest ones is steepest descent method, which simply iteratively moves in the opposite direction to the gradient. For 1D logistic regression it would be:
beta1_t+1 = beta1_t - alpha * SUM_(x, y) x * (s(beta1_t*x + beta0_t) - y)
beta0_t+1 = beta0_t - alpha * SUM_(x, y) (s(beta1_t*x + beta0_t) - y)
where:
s(x) = 1 / (1 + exp(-x))
and
*
*alpha is learning rate, something small enough, like 0.01
*your model's prediction is s(beta1 * x + beta0)
*your data is of form {(x1, y1), ..., (xK, yK)}) and each yi is either 0 or 1
This is literally saying
beta_t+1 = beta_t - alpha * GRAD_theta J(beta_t)
where J is logistic loss
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40318763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CloudFormation, S3 bucket access to cross-acccount IAM role I have 2 accounts, s3_buck_acct and iam_acct. I want to provision IAM role from iam_acct to certain actions on the S3 bucket from s3_buck_acct.
Here is the CloudFormation template I came up with that ends up with error:
Resources:
S3BucketTest:
Type: AWS::S3::Bucket
Properties:
BucketName: "cross-acct-permission-demo"
LifecycleConfiguration:
Rules:
- Id: LifecycleExpRule
ExpirationInDays: '3650'
Status: Enabled
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
S3CURBucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket:
!Ref S3BucketTest
PolicyDocument:
Statement:
- Action:
- 's3:ListBucket'
- 's3:ListBucketMultipartUploads'
- 's3:PutObject'
- 's3:GetObject'
Effect: "Allow"
Resource:
- "arn:aws:s3:::cross-acct-perm-demo"
- "arn:aws:s3:::cross-acct-perm-demo/*"
Principal: "arn:aws:iam::1234567890:role/service-role/test-role-20190828T130835"
- Action: "*"
Resource: !Join [ '', ["arn:aws:s3:::", !Ref S3BucketTest, '/*']]
Principal: '*'
Effect: Deny
Condition:
Bool:
'aws:SecureTransport':
- 'false'
Error message:
Invalid policy syntax. (Service: Amazon S3; Status Code: 400; Error Code: MalformedPolicy; Request ID: 91BF8921047D9D3B; S3 Extended Request ID: ZOVOzmFZYN6yB1btOqMqgJjOpzfiUpP86c2XiVylzYkg37fGga8/eYDL7C4WzwhmcDGU7NJkL68=)
Not sure where I got this wrong. Can I provision S3 bucket access to cross-account IAM? From the console permissions section, I was able to do it.
A: Your bucket is called cross-acct-permission-demo but your policy specifies cross-acct-perm-demo. Also your indentation is not correct for the first Action (though it should not cause this issue). Also not sure if the service-role principle is correct in this context.
A: If you want IAM users in account A to be able to access resources in account B then you create an IAM role in account B that gives access to the relevant resources in account B, then you define account A as a trusted entity for the IAM role, then you permit access to that role to the relevant users in account A. Those users in account A can now assume the (cross-account) role in account B, and gain access to resources in account B.
See Tutorial: Delegate Access Across AWS Accounts Using IAM Roles
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60662142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: HTML - CSS for an image with radio button I would like to have an image with a radio button under it. The image should be get into a frame whenever the radio button is selected.
I achieved that behaviour but with the radio button must be on top of the image, and I would like to have it under the image.
/* IMAGE STYLES */
[type=radio] + img {
cursor: pointer;
}
/* CHECKED STYLES */
[type=radio]:checked + img {
outline: 2px solid #f00;
}
<table><tr>
<td>
<label>
<input id="Answer" name="Answer" type="radio" value="1" />
<img src="X.jpeg" />
</label>
</td>
<td>
<label>
<img src="X1.jpeg" /> // here the image does not get the frame
<input id="Answer" name="Answer" type="radio" value="2" />
</label>
</td>
</tr>
</table>
Any idea which CSS would match for the second cell of the table?
A: you can do it with jquery but if you want to use pure css you can do something like this:
[type=radio]:checked ~ .[CLASS_OF_THE_IMAGE] {
outline: 2px solid #f00;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64725661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to understand the print in GDB? I have an assembly code,
.section .data
value1:
.int 1
value2:
.short 2
value3:
.byte 3
.global _start
_start:
nop
movl value1,%ecx
movw value1,%bx
movw value2,%bx
movb value3,%cl
movl $1, %eax
movl $0, %ebx
int $0x80
I use as and ld to get the executable binary file.
But in GDB, I cannot print the value2.
enter image description here
Why? I'm confused.
I found the address is out of the data section.
A: A few issues ...
*
*You should have .section .text before .global _start so that _start ends up in the .text section
*Add -g to get debug infomation
Unfortunately, adding -g to a .c compilation would be fine. But, it doesn't work too well for a .s file
Here's a simple C program, similar to yours:
int value1;
short value2;
unsigned char value3;
We can compile this with -S to get a .s file. We can do this with and without -g. Without -g the .s file is 7 lines. Adding -g increases this to 150 lines.
The debug information has to be added with special asm directives (e.g. .loc and .section .debug_info,"",@progbits).
Then, gdb has enough information to allow p (or x) to work.
To get p to work without debug information, we have to cast the values to the correct type. For example, in your program:
p (int) value1
p (short) value2
p (char) value3
Here is the .s output for the sample .c file without -g:
.file "short.c"
.text
.comm value1,4,4
.comm value2,2,2
.comm value3,1,1
.ident "GCC: (GNU) 8.3.1 20190223 (Red Hat 8.3.1-2)"
.section .note.GNU-stack,"",@progbits
Here is the .s output with -g:
.file "short.c"
.text
.Ltext0:
.comm value1,4,4
.comm value2,2,2
.comm value3,1,1
.Letext0:
.file 1 "short.c"
.section .debug_info,"",@progbits
.Ldebug_info0:
.long 0x71
.value 0x4
.long .Ldebug_abbrev0
.byte 0x8
.uleb128 0x1
.long .LASF5
.byte 0xc
.long .LASF6
.long .LASF7
.long .Ldebug_line0
.uleb128 0x2
.long .LASF0
.byte 0x1
.byte 0x1
.byte 0x5
.long 0x33
.uleb128 0x9
.byte 0x3
.quad value1
.uleb128 0x3
.byte 0x4
.byte 0x5
.string "int"
.uleb128 0x2
.long .LASF1
.byte 0x1
.byte 0x2
.byte 0x7
.long 0x50
.uleb128 0x9
.byte 0x3
.quad value2
.uleb128 0x4
.byte 0x2
.byte 0x5
.long .LASF2
.uleb128 0x2
.long .LASF3
.byte 0x1
.byte 0x3
.byte 0xf
.long 0x6d
.uleb128 0x9
.byte 0x3
.quad value3
.uleb128 0x4
.byte 0x1
.byte 0x8
.long .LASF4
.byte 0
.section .debug_abbrev,"",@progbits
.Ldebug_abbrev0:
.uleb128 0x1
.uleb128 0x11
.byte 0x1
.uleb128 0x25
.uleb128 0xe
.uleb128 0x13
.uleb128 0xb
.uleb128 0x3
.uleb128 0xe
.uleb128 0x1b
.uleb128 0xe
.uleb128 0x10
.uleb128 0x17
.byte 0
.byte 0
.uleb128 0x2
.uleb128 0x34
.byte 0
.uleb128 0x3
.uleb128 0xe
.uleb128 0x3a
.uleb128 0xb
.uleb128 0x3b
.uleb128 0xb
.uleb128 0x39
.uleb128 0xb
.uleb128 0x49
.uleb128 0x13
.uleb128 0x3f
.uleb128 0x19
.uleb128 0x2
.uleb128 0x18
.byte 0
.byte 0
.uleb128 0x3
.uleb128 0x24
.byte 0
.uleb128 0xb
.uleb128 0xb
.uleb128 0x3e
.uleb128 0xb
.uleb128 0x3
.uleb128 0x8
.byte 0
.byte 0
.uleb128 0x4
.uleb128 0x24
.byte 0
.uleb128 0xb
.uleb128 0xb
.uleb128 0x3e
.uleb128 0xb
.uleb128 0x3
.uleb128 0xe
.byte 0
.byte 0
.byte 0
.section .debug_aranges,"",@progbits
.long 0x1c
.value 0x2
.long .Ldebug_info0
.byte 0x8
.byte 0
.value 0
.value 0
.quad 0
.quad 0
.section .debug_line,"",@progbits
.Ldebug_line0:
.section .debug_str,"MS",@progbits,1
.LASF1:
.string "value2"
.LASF5:
.string "GNU C17 8.3.1 20190223 (Red Hat 8.3.1-2) -mtune=generic -march=x86-64 -g"
.LASF0:
.string "value1"
.LASF6:
.string "short.c"
.LASF2:
.string "short int"
.LASF3:
.string "value3"
.LASF4:
.string "unsigned char"
.LASF7:
.string "/tmp/asm"
.ident "GCC: (GNU) 8.3.1 20190223 (Red Hat 8.3.1-2)"
.section .note.GNU-stack,"",@progbits
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75535365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to read multiple files in parallel? I have a number of text files that I need to open, then allocate certain fields to set strings inside PHP to eventually write into MySQL.
Each txt file does have the same unique value for app_id, eg
So text file 1 has
app_id
name
description
text file 2 has
app_id
category
text file 3 has
app_id
price
I want to get name, description, category and price for each record, and write that into mysql.
I can read the first one using code :
$fp = fopen('textfile1','r');
if (!$fp) {echo 'ERROR: Unable to open file.</table></body></html>'; exit;}
while (!feof($fp)) {
$line = stream_get_line($fp,4096,$eoldelimiter);
if ($line[0] === '#') continue; //Skip lines that start with #
$field[$loop] = explode ($delimiter, $line);
list($app_id, $name, $description) = explode($delimiter, $line);
$fp++;
}
fclose($fp);
?>
My question is how to read the 2nd and 3rd files? Can I somehow do it in parallel, or do I need to finish reading text file 1, write each line into mysql then open text file 2 and write category into mysql using replace on the app_id key, then do the same with text file 3 opening and ?
A: I would recommend the following approach:
*
*create a simple class containing the following fields: name, description, category, and price
*create an empty array that will be indexed with the app_id, each corresponding to an instance of the aforementioned class
*read each file and affect the result to the correct element in the array
if (!isset($array[$app_id])) $array[$app_id] = new MyClass();
array[$app_id]->name = $name;
array[$app_id]->description = $description;
*once you're done reading all files, you can iterate through the array and write each element to the SQL table.
A: Simply open all three files in sequence and then have three stream_get_line's in your while loop, one for each file:
$fp1 = fopen('textfile1','r');
$fp2 = fopen('textfile2','r');
$fp3 = fopen('textfile3','r');
while (!feof($fp1)) {
$line1 = stream_get_line($fp1...)
$line2 = stream_get_line($fp2...)
$line3 = stream_get_line($fp3...)
...
You'll have to take care that each file has exactly the same number of lines, though. Best
is probably to check for feof on each stream before reading a line from it, and aborting with an error message if one of the streams runs out of lines before the others.
A: Try this:
file1.txt contents:
id 13 category test description test
file2.txt:
id 13 name test description test
id 15 name test description test
id 17 name test description test
$files = array('file1.txt','file2.txt');
foreach($files as $file) {
flush();
preg_match_all("/id\s(?<id>\d+)\s(?:name|category|price)?\s(?<name>[\w]+)\sdescription\s(?<description>[^\n]+)/i",@file_get_contents($file),$match);
print_r($match);
}
returns:
Array
(
[0] => Array
(
[0] => id 13 category test description test
)
[id] => Array
(
[0] => 13
)
[1] => Array
(
[0] => 13
)
[name] => Array
(
[0] => test
)
[2] => Array
(
[0] => test
)
[description] => Array
(
[0] => test
)
[3] => Array
(
[0] => test
)
)
Array
(
[0] => Array
(
[0] => id 13 name test description test
[1] => id 15 name test description test
[2] => id 17 name test description test
)
[id] => Array
(
[0] => 13
[1] => 15
[2] => 17
)
[1] => Array
(
[0] => 13
[1] => 15
[2] => 17
)
[name] => Array
(
[0] => test
[1] => test
[2] => test
)
[2] => Array
(
[0] => test
[1] => test
[2] => test
)
[description] => Array
(
[0] => test
[1] => test
[2] => test
)
[3] => Array
(
[0] => test
[1] => test
[2] => test
)
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3281233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Get a list of files in a react web application I have a directory full of text files that I need to read in my react web app
-resources
|-file1.txt
|-file2.txt
|-file3.txt
I would like to store this resources directory somewhere in the app such that the contents of resources can be listed, and individual files can be iterated over on a line-by-line basis.
currently, I'm stuck on listing the files. I'm storing them like this
-node_modules
-public
|-resources
||-file1.txt
||-...
-src
But I really don't care where the resources directory is located. I tried using list-react-files based on this, but got Module not found: Error: Can't resolve 'fs'.
for further context, I was thinking the code to scan for files would be in in App.js, such that the scanned files could be used to populate certain components.
import React from "react"
import './App.css';
...
function App() {
//searching for files
var files = [...];
return(
//create components which can list and work with the files
...
);
}
export default App;
So, to summarize the question, how can I list files in reactJS?
p.s.:
*
*this project was made with create-react-app
*part of the point is that it should be easy to add new files to this directory, but I see no reason this process has to be "dynamic"
A: When people are using your react page, it is "running" on their computer and the software does not have access to all the files and data you'd like to use.
You will need to do this at "build time" when your service is being packaged up, or "on the server".
When you are building your react app, you can hook into processes that can find files and perform operations on them. Gatsby might be your best bet. Look at how people add "markup" files to their projects, built a menu from them and then render them as blog articles. NextJS, Vite, and other frameworks and tools will work, you may just need to learn a bit more.
The other approach, to do this "on the server" means when you are running code on the server you can do almost anything you like. So, your react app would make a call (e.g. rest request) to the server (e.g. NodeJS), and the code running on the server can use fs and other APIs to accomplish what you'd like.
From what you describe, doing this as part of your build step is probably the best route. A much easier route is to move this data into a JSON file and/or a database and not crawl the file system.
A: Looks like its a client side rendering app and not server side (node app). Resources folder you trying to list is residing in server and react app (javascript) running on browser can't access it directly.
A: To whom it may concern, I spent more time than I should have working on this. I highly recommend converting everything to JSON files and importing them. If you want to be able to scan for JSON files, make a JSON file that includes the names of all your files, then import that and use that for scanning. Doing things dynamically is a bare.
If you don't reformat, you'll likely need to use Fetch, which is asynchronous, which opens up a whole can of worms if you're using a framework like React.
If you're just importing json files, it's super easy:
import files from './resources/index.json';
where index.json looks like
{
"files":[
"file1.json",
"file2.json"
]
}
if you need to import the files more dynamically (not at the very beginning) you can use this:
var data = require('./resources/'+filename)
this will allow you to scan through your files using the index.json file, and load them dynamically as needed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70609856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Duplicate Rows dynamically jquery based on checkbox checked I am trying to dynamically add rows based in the checkbox checked. The idea here is to duplicate the selected row. For instance, initially there is only one row. On checking the checkbox corresponding to this row, it creates a duplicate of it. If i change the dropdown values in the newly added row , and duplicate it, its not able to do it because of my hardcodedness. How can i bring about this dynamicity?
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$("#DuplicateRow").click(function() {
var checkboxValues = [];
$('input[type="checkbox"]:checked').each(function() {
//alert('hi')
var row = document.getElementById("row"); // find row to copy
var table = document.getElementById("tabletomodify"); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = "row"; // change id or other attributes/contents
table.appendChild(clone); // add new row to end of table
});
});
});
</script>
</head>
<table cellpadding="10" style="border:2px solid black;" id="tabletomodify">
<tr bgcolor="#360584">
<td style="border:1px solid black;" colspan="15"><font face="Arial" size="4" color="white"><b><i>Records</i></b></font>
</td>
</tr>
<tr>
<td>
<button id="AddRow">Add Row</button>
</td>
<td>
<button id="DuplicateRow">Duplicate Row</button>
</td>
<td>
<button id="DeleteRow">Delete Row</button>
</td>
</tr>
<tr bgcolor="#360584">
<td><font face="Arial" size="2" color="white">Name </font>
</td>
<td><font face="Arial" size="2" color="white">Date of Birth</font>
</td>
<td><font face="Arial" size="2" color="white">City</font>
</td>
<td><font face="Arial" size="2" color="white">State</font>
</td>
<td><font face="Arial" size="2" color="white">Country</font>
</td>
<td><font face="Arial" size="2" color="white">Phone Number</font>
</td>
<td><font face="Arial" size="2" color="white">Mail ID</font>
</td>
<td><font face="Arial" size="2" color="white">Select</font>
</td>
<tr id="row">
<td>
<select><option>one</option><option>two</option></select>
</td>
<td>
<select><option>one</option><option>two</option></select>
</td>
<td>
<select><option>one</option><option>two</option></select>
</td>
<td>
<select><option>one</option><option>two</option></select>
</td>
<td>
<select><option>one</option><option>two</option></select>
</td>
<td>
<select><option>one</option><option>two</option></select>
</td>
<td>
<select><option>one</option><option>two</option></select>
</td>
<td>
<input type="checkbox" class="checkbox">
</td>
</tr>
</table>
A: How about this .. this works, you have manually copy all the changed/selected options from actual row to cloned row
$(document).ready(function(){
$("#DuplicateRow").click(function(){
var checkboxValues = [];
$('input[type="checkbox"]:checked').each(function(){
var $chkbox=$(this);
var $actualrow = $chkbox.closest('tr');
var $clonedRow = $actualrow.clone();
$clonedRow.find("select").each(function(i){
this.selectedIndex = $actualrow.find("select")[i].selectedIndex;
})
$chkbox.closest('#tabletomodify').append( $clonedRow );
});
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19722810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Populate labels in a loop I have 5 labels titled lblQuestion1, lblQuestion2, lblQuestion3... and as part of the loop below, when i=0, I want lblQuestion1.Text = reader["answer1"].ToString(); ...
i=1 --> lblQuestion2.Text = reader["answer1"].ToString(); ...
i=2 --> lblQuestion3.Text = reader["answer1"].ToString(); ......
However, this doesn't work so can someone suggest an alternative method.
for (int i = 0; i < 5; i++)
{
try
{
conn.Open();
string cmdText = "SELECT * FROM questions ORDER BY RAND() LIMIT 1";
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
reader = cmd.ExecuteReader();
if (reader.Read())
{
if (!(list.Contains(reader["question_id"].ToString())))
{
list.Add(reader["question_id"].ToString());
//lblQuestion[i+1].Text = reader["answer1"].ToString();
}
}
else
{
lblError.Text = "(no questions found)";
}
reader.Close();
}
catch
{
lblError.Text = "Database connection error - failed to insert record.";
}
finally
{
conn.Close();
}
}
A: You can put references to the labels in an array and access them with that. I put five labels on a form (leaving their names as the defaults) and used this code as an example:
private void SetLabelsText()
{
// Put references to the labels in an array
Label[] labelsArray = { label1, label2, label3, label4, label5 };
for (int i = 0; i < labelsArray.Count(); i++)
{
labelsArray[i].Text = "I am label " + (i + 1).ToString();
}
}
private void Form1_Load(object sender, EventArgs e)
{
SetLabelsText();
}
A: To answer your comment to my Comment. Since FindControl takes a string as an input you would just create the string with the component name you are looking for. Be aware that you have to use the FindControl Method of the container that your labels are in.
From Link(emphasis mine):
Use FindControl to access a control from a function in a code-behind page, to access a control that is inside another container, or in other circumstances where the target control is not directly accessible to the caller. This method will find a control only if the control is directly contained by the specified container; that is, the method does not search throughout a hierarchy of controls within controls. For information about how to find a control when you do not know its immediate container, see How to: Access Server Controls by ID.
so something like this should work for you.
((Label) this.FindControl("lblQuestion" + (i+1))).Text = reader["answer" + (i+1)].ToString();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24588779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: AWS Http connection I observed the following behavior while working with AWS SDK.
Test Scenario 1:
Trying to download the multiple files of same size from S3 in sequential (back to back, no thread wait) calls using S3Client as singleton.(internally uses Http-core 4.3)
Result : First call to download the document takes more time(5000 ms). Since it involves Singleton Initialization etc. The rest of the calls are very fast (around 100-200 ms).
Test Scenario 2:
Trying to download the multiple files of same size from S3 in sequential with thread wait of (10 second) between calls using S3Client as singleton.(internally uses Http-core 4.3)
Result : First call to download the document takes more time(5000 ms). The rest of the calls are not as fast as Scenario 1 (taking around 800 - 1500 ms).
Can someone suggest what is happening the background ? Is this something to do with the setting of http connection? Internally AWS SDK uses apache httpcore and httpclient libraries.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26937455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a way to instantiate a child class with parent object in java? I have a base class say
class A {
private String name;
private String age;
//setters and getters for same
}
and a child class say
class B extends A {
private String phone;
private String address;
//setters and getters for same
}
now I've an instance of A and besides this I have to set the fields in B as well, so code would be like,
A instanceOfA = gotAFromSomewhere();
B instanceOfB = constructBFrom(instanceOfA);
instanceOfB.setPhone(getPhoneFromSomewhere());
instanceOfB.setAddress(getAddressFromSomewhere());
can I instantiate B with given A, but I don't want to do this way,
B constructBFrom(A instanceOfA) {
final B instanceOfB = new B();
instanceOfB.setName(instanceOfA.getName());
instanceOfB.setPhone(instanceOfA.getAge());
return B;
}
rather what I'd love to have some utility with function which is generic enough to construct object as in,
public class SomeUtility {
public static <T1, T2> T2 constructFrom(T1 instanceOfT1, Class<T2> className) {
T2 instatnceOfT2 = null;
try {
instatnceOfT2 = className.newInstance();
/*
* Identifies the fields in instanceOfT1 which has same name in T2
* and sets only these fields and leaves the other fields as it is.
*/
} catch (InstantiationException | IllegalAccessException e) {
// handle exception
}
return instatnceOfT2;
}
}
so that I can use it as,
B constructBFrom(A instanceOfA) {
return SomeUtility.constructFrom(instanceOfA, B.class);
}
Moreover, use case will not be only limited to parent-child classes, rather this utility function can be used for adapter use cases.
PS- A and B are third party classes I've to use these classes only so I can't do any modifications
in A and B.
A: In my opinion the way you want to avoid is very appropriate. There must be a piece of such code somewhere.
If you can't put that method in the target class just put it somewhere else (some factory). You should additionaly make your method static.
Take a look at Factory method pattern.
2nd option would be extending B and place this method as factory static method in that new class. But this solution seems to be more complicated for me. Then you could call NewB.fromA(A). You should be able then use your NewB instead of B then.
A: The good practice is to have a factory class which "produces" the instances of B.
public class BFactory {
public B createBFromA(A a) { ... }
}
You have to write the code of the factory method as there is no standard way of creating a child class based on its parent class. It's always specific and depends on the logic of your classes.
However, consider if it is really what you need. There are not many smart use cases for instantiating a class based on the instance of its parent. One good example is ArrayList(Collection c) - constructs a specific list ("child") containing the elements of the generic collection ("base").
Actually, for many situation there is a pattern to avoid such strange constructs. I am aware it's probably not applicable to your specific case as you wrote that your Base and Child are 3rd party classes. However your question title was generic enough so I think you may find the following useful.
*
*Create an interface IBase
*Let the class Base implement the interface
*Use composition instead of inheritance - let Child use Base instead of inheriting it
*Let Child implement IBase and delegate all the methods from IBase to the instance of Base
Your code will look like this:
public interface IBase {
String getName();
int getAge();
}
public class Base implements IBase {
private String name;
private int age;
// getters implementing IBase
}
public class Child implements IBase {
// composition:
final private IBase base;
public Child(IBase base) {
this.base = base;
}
// delegation:
public String getName() {
return base.getName();
}
public int getAge() {
return base.getAge();
}
}
After you edited your question, I doubt even stronger that what you want is good. Your question looks more like an attempt of a hack, of violating (or not understanding) the principles of class-based object oriented concept. Sounds to me like someone coming from the JavaScript word and trying to keep the JavaScript programming style and just use a different syntax of Java, instead of adopting a different language philosophy.
Fun-fact: Instantiating a child object with parent object is possible in prototype-based languages, see the example in JavaScript 1.8.5:
var base = {one: 1, two: 2};
var child = Object.create(base);
child.three = 3;
child.one; // 1
child.two; // 2
child.three; // 3
A: You could do it via reflection:
public static void copyFields(Object source, Object target) {
Field[] fieldsSource = source.getClass().getFields();
Field[] fieldsTarget = target.getClass().getFields();
for (Field fieldTarget : fieldsTarget)
{
for (Field fieldSource : fieldsSource)
{
if (fieldTarget.getName().equals(fieldSource.getName()))
{
try
{
fieldTarget.set(target, fieldSource.get(source));
}
catch (SecurityException e)
{
}
catch (IllegalArgumentException e)
{
}
catch (IllegalAccessException e)
{
}
break;
}
}
}
}
*Above code copied from online tutorial
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24616381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Neural Networks works worse than RandomForest I have a classification problem that target contains 5 classes, 15 features(all continuous)
and have 1 million for training data, 0.5 million for validation data.
e.g.,
shape of X_train = (1000000,15)
shape of X_validation = (500000,15)
First, I used Random Forest that can get 88% Avg. Accuracy.
After that I tried many Neural Network architecture, the best one got ~80% Avg. Accuracy both on training and validation data, which was worse than Random forest.
(I don't know much about designing Neural Network architecture)
Following is the best one of my NN architecture. (~80% Avg.Accuracy)
model = Sequential()
model.add(Dense(1000, input_dim=15, activation='relu'))
model.add(Dropout(0.1))
model.add(Dense(900, activation='relu'))
model.add(Dropout(0.1))
model.add(Dense(800, activation='relu'))
model.add(Dropout(0.1))
model.add(Dense(700, activation='relu'))
model.add(Dropout(0.1))
model.add(Dense(600, activation='relu'))
model.add(Dense(5, activation='softmax'))#output layer
adadelta = Adadelta()
model.compile(loss='categorical_crossentropy', optimizer=adadelta, metrics=['accuracy'])
Batch Size = 128 and epochs = 100
I have read this question. The answer point out that NN needs amount of data and some regulization. I think my data size is good enough and I have also tried higer Dropout rate and L2 regulization but still not working.
What could the problem be?
This is biological data that I have no domain knowledge so sorry about that I can't explain it. I've plot the feature distribution as below, all features are between 0 to 3
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53063116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to set default selected value for Rails SimpleForm select box I'm trying to figure out how to set the selected option of a select box generated by SimpleForm. My code is along the lines of:
<%= simple_form_for(@user) do |f| %>
<%= f.association :store, default: 1 %>
Of course the default: 1 part does not work.
TIA
A: You can now use the following:
<%= f.association :store, selected: 1 %>
A: Use the following:
selected: 1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10441061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "39"
}
|
Q: Dockerfile: pass argument to RUN npm run build I have a dockerfile with these lines:
ARG ENVIRONMENT
ENV ENVIRONMENT $ENVIRONMENT
RUN npm run ng build --configuration=${ENVIRONMENT}
I cant get the "RUN npm run ng build --configuration= to pass the value of $ENVIRONMENT to the npm command.
What is the syntax for this?
A: Per the Dockerfile ARG docs,
The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg = flag.
in order to accept an argument as part of the build, we use --build-arg.
Dockerfile ENV docs:
The ENV instruction sets the environment variable to the value .
We also need to include an ENV statement because the CMD will be executed after the build is complete, and the ARG will not be available.
FROM busybox
ARG ENVIRONMENT
ENV ENVIRONMENT $ENVIRONMENT
CMD echo $ENVIRONMENT
will cause an environment variable to be set in the image, so that it is available during a docker run command.
docker build -t test --build-arg ENVIRONMENT=awesome_environment .
docker run -it test
This will echo awesome_environment.
A: Try changing your RUN command do this:
RUN npm run ng build --configuration=$ENVIRONMENT
This should work. Check here
Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58461912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iPhone app crashes only in Release mode on 3G I have an app I'm writing that crashes when I call addSubview on a UIScrollView with "EXC_BAD_ACCESS". It only does this on iPhone 3G in release mode and only on the device. I works fine in all these other configurations:
iPhone 3G - Debug mode
iPhone 3GS - Debug AND Release Mode
iPhone 4 - Debug AND Release Mode
Simulator - all.
Furthermore, there is no rational reason why this should be happening. My object is not released by any of my code.
A: I recommend you to use NSZombieEnabled to find out what is causing a bad access to memory.
*
*Do you use DEBUG / RELEASE defines to branch your code?
*Do you use SDK version checkers to branch your code?
Otherwise I can't see how your app can behave diferently on different devices/configurations.
A: I had the exact same problem recently, however I am not entirely sure the cause is the same. What I can tell you though is what resolved the issue for me (although I'm still not entirely satisfied with the solution).
In the end, it seems like a compiler issue, and this might confirm what others have said about compiler optimization.
I am using Xcode 4.0 (build 4A304a). The issue was with LLVM compiler 2.0 Code Generation. One key in particular: "Optimization Level"
Debug was set to "None".
Release was set to "Fastest, Smallest"
Changing Release to "None" fixed the crash (and similarly changing Debug to "Fastest, Smallest" caused the app the crash on launch).
A: I can propose to change optimization level of release settings to "None".
I met the same problem few times (with different apps) and solved it in this way.
A: I never "solved" this but I did track down the offending code. I suspect that something in this segment of Quartz code was causing a buffer overrun somewhere deep inside the core - and it only caused a problem on 3G. Some of the setup for this segment is not included but this is definitely where it is happening:
gradient = CGGradientCreateWithColors(space, (CFArrayRef)colors, locations);
CGContextAddPath(context, path);
CGContextSaveGState(context);
CGContextEOClip(context);
transform = CGAffineTransformMakeRotation(1.571f);
tempPath = CGPathCreateMutable();
CGPathAddPath(tempPath, &transform, path);
pathBounds = CGPathGetPathBoundingBox(tempPath);
point = pathBounds.origin;
point2 = CGPointMake(CGRectGetMaxX(pathBounds), CGRectGetMinY(pathBounds));
transform = CGAffineTransformInvert(transform);
point = CGPointApplyAffineTransform(point, transform);
point2 = CGPointApplyAffineTransform(point2, transform);
CGPathRelease(tempPath);
CGContextDrawLinearGradient(context, gradient, point, point2, (kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation));
CGContextRestoreGState(context);
CGGradientRelease(gradient);
A: You say "My object is not released by any of my code". I've found that it's not uncommon in Objective-C to run into situations where your code has not explicitly released an object yet the object has been released all the same. For example, off the top of my head, let's say that you have an object #1 with retain count of 1 and you release it but then autorelease it accidentally. Then, before the autorelease pool is actually drained, you allocate a new object #2 -- it's not inconceivable that this new object #2 could be allocated at the same address as object #1. So when the autorelease pool is subsequently drained, it will release object #2 accidentally.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4149960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Populate future dates in oracle table I have a script to populate previous(2016), current(2017) and complete next year(2018). The script is intended to be run initially to populate table. It can be run only once since it populates prior dates. How do I populate future dates (2019)?
insert into my_date
SELECT TO_NUMBER (TO_CHAR (mydate, 'yyyymmdd')) AS my_date_id,
mydate AS datetime_start,
mydate + 1 - 1/86400 AS datetime_end,
TO_CHAR (mydate, 'dd-MON-yyyy') AS date_value,
TO_NUMBER (TO_CHAR (mydate, 'D')) AS day_of_week,
TO_CHAR (mydate, 'Day') AS day_of_week_name,
TO_CHAR (mydate, 'DY') AS day_of_week_name_short,
TO_NUMBER (TO_CHAR (mydate, 'DD')) AS day_of_month,
TRUNC (mydate) - TRUNC (mydate, 'Q') + 1 AS day_of_quarter,
TO_NUMBER (TO_CHAR (mydate, 'DDD')) AS day_of_year,
CASE WHEN TO_NUMBER (TO_CHAR (mydate, 'D')) IN (1, 7) THEN 1
ELSE 0
END AS weekend_flag,
TO_NUMBER (TO_CHAR (mydate, 'W')) AS week_in_month,
TO_NUMBER (TO_CHAR (mydate, 'WW')) AS week_in_year,
TRUNC(mydate, 'w') AS week_start_date,
TRUNC(mydate, 'w') + 7 - 1/86400 AS week_end_date,
TO_CHAR (mydate, 'MM') AS month_value,
TO_CHAR (mydate, 'Month') AS month_name,
TO_CHAR (mydate, 'MON') AS month_name_short,
TRUNC (mydate, 'mm') AS month_start_date,
LAST_DAY (TRUNC (mydate, 'mm')) + 1 - 1/86400 AS month_end_date,
TO_NUMBER ( TO_CHAR( LAST_DAY (TRUNC (mydate, 'mm')), 'DD')) AS days_in_month,
CASE WHEN mydate = LAST_DAY (TRUNC (mydate, 'mm')) THEN 1
ELSE 0
END AS last_day_of_month_flag,
TO_CHAR (mydate, 'yyyy') AS year_value,
'YR' || TO_CHAR (mydate, 'yyyy') AS year_name,
'YR' || TO_CHAR (mydate, 'yy') AS year_name_short,
TRUNC (mydate, 'Y') AS year_start_date,
ADD_MONTHS (TRUNC (mydate, 'Y'), 12) - 1/86400 AS year_end_date,
ADD_MONTHS (TRUNC (mydate, 'Y'), 12) - TRUNC (mydate, 'Y') AS days_in_year
FROM ( SELECT TRUNC (ADD_MONTHS (SYSDATE, -12), 'yy') - 1 + LEVEL AS mydate
FROM dual
CONNECT BY LEVEL <= (SELECT TRUNC (ADD_MONTHS (SYSDATE, 24), 'yy')
- TRUNC (ADD_MONTHS (SYSDATE, -12), 'yy')
FROM DUAL
)
);
A change will be required within FROM clause to avoid existing records. How do I achieve that?
A: A pipelined function might help you here.
*
*Create a table type that will match the results your function will return.
*Create a function which returns exactly the dates you want. It can run queries to make sure the date isn't already in your table, is within your desired date range, etc.
*Return the values one by one stopping once you hit your criteria.
*Select from the function using the TABLE() function to turn the results into a table you can query. Use the OBJECT_VALUE to access the actual value being returned (since it doesn't really have a column name).
create or replace type date_tbl_t as table of date;
/
create or replace function all_dates ( max_year_in in integer )
return date_tbl_t
pipelined
as
date_l date;
offset_l pls_integer := 0;
year_l integer;
begin
if date_l is null
then
date_l := sysdate;
end if;
year_l := extract ( year from date_l );
while year_l <= max_year_in
loop
pipe row(date_l);
date_l := date_l + 1;
year_l := extract ( year from date_l );
end loop;
return;
end all_dates;
/
select
to_char(x.object_value, 'yyyymmdd') as my_date_id,
x.object_value as datetime_start
from table ( all_dates (2019) ) x;
/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53289070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HTML::DOM stops forks module from working I have encountered a strange error. When I use HTML::DOM and forks module at the same time, the forks module doesn't work properly.
Strange thing is, this occurs only at some machines, not on others. Example:
use forks;
use HTML::DOM;
$|=1;
print "before\n";
threads->new( sub {
$|=1;
print "inside\n";
} );
print "after\n";
sleep(3600);
I see only before and after, never inside on standard output. It works with standard threads, but I don't want to use it.
If I comment out the use HTML::DOM; line, it suddenly starts working. So, my questions are,
*
*Is it really a bug?
*If it is a bug, where to report it? Is it a bug of HTML::DOM, forks, both...?
edit: it happens only with 5.8.8 perl, not with 5.10.0.
A: Given that forks is claiming to provide the same interface as threads I'd be more inclined to report it against forks over HTML::DOM. Especially since the forks is the one doing the deep magic, whereas HTML::DOM is just a normal everyday module. Its not likely the HTML::DOM authors will have any idea what you're on about.
A: Problem "solved".
I had a weird settings in $PERLLIB and $PERL5LIB, that linked to non-existing directories or directories with outdated libraries. Once I fixed that, forks started working as it should.
So, if you have similar troubles with forks, check your $PERLLIB and $PERL5LIB, if it links where it should link.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4484798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android BLE connect to device by Name I'm developing an app that has to connect to a hardware device via bluetooth low energy. The code I'm working with right now enables me to connect just fine, but through the device's address through mBluetoothLeService.connect(String deviceAddress) (where deviceAddress = "F8:AF:BE:04:19:03").
I am looking for a way to allow me to connect to that device by its name and not by its address. If you look at the sample project provided by Google, they use that method to connect to the device, but in the screen where they are scanning for new devices the name of the device does appear. So this field is visible to me, but there is no direct method that I can see which can allow me to do this.
Any help would be appreciated, thanks!
A: I think there can't be such a method because the name of the device is likely to be ambigious.
E.g. all BLE beacons from estimote are called 'Estimote' and so this name is not unique but the mac adresss is.
If you are sure that all device names are unique, you could use a map to store device names and macs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24402179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Using if else blocks getting missing right parenthesis error I'm new to Oracle and having knowledge of MS SQL. I'm trying to get a phone number depending upon the user_id from Table2 and here is the business logic:
*
*Case1: if a single match is found in Table1 then get it's respective toll free number from Table2
*Case2: if no match is found in Table1 then get the default toll free number from Table2
*Case3: if an multiple match is found in Table1 then for all those assigned_care_levels get the Care value from Table2 ordered by asc or desc and select the top row phone number.
I wrote the following query which works fine when I run it individually. However, when I cobine it using the if else statements I'm getting the following error ERROR: ORA-00907: missing right parenthesis. Here is my code:
if ((select count(distinct care_level) from Table1 where user_id = '100') > 0)
select phone from Table2 where care_level in (select distinct care_level from Table1 where user_id = '100')
and rownum = 1
order by care_level asc
else if((select count(distinct care_level) from Table1 where user_id = '100') = 0)
select phone from Table2 where care_level = 'default'
A: SET SERVEROUTPUT ON;
DECLARE
v_CARE_COUNT NUMBER := 0;
v_PHONE VARCHAr2(40) := NULL;
BEGIN
select count(distinct care_level)
into v_CARE_COUNT
from Table1
where user_id = '100';
IF(v_CARE_COUNT > 0) THEN
select phone into v_PHONE
from Table2
where care_level in
(select distinct care_level from Table1 where user_id = '100')
and rownum = 1;
ELSE
select phone into v_PHONE
from Table2
where care_level = 'default';
END IF;
DBMS_OUTPUT.PUT_LINE('PHONE is <'||v_PHONE||'>');
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Exception : '||SQLERRM);
END;
/
EDIT: ( AS SIngle SQL)
SELECT PHONE
FROM TABLE2
WHERE CARE_LEVEL in
(
SELECT CARE_LEVEL FROM TABLE1 WHERE USER_ID='100'
UNION
SELECT CARE_LEVEL FROM TABLE1 WHERE CARE_LEVEL='default'
AND NOT EXISTS
(SELECT 'X' FROM TABLE1 WHERE USER_ID='100')
)
AND ROWNUM = 1;
A: The 'else if' syntax is wrong. In Oracle you need to use 'ELSIF' and complete the whole conditional statement with an 'END IF'. The SQL statements within should also be followed with a ;
Try:
IF ((select count(distinct care_level) from Table1 where user_id = '100') > 0) THEN
select phone from Table2 where care_level in (select distinct care_level from Table1 where user_id = '100')
and rownum = 1
order by care_level asc;
ELSIF ((select count(distinct care_level) from Table1 where user_id = '100') = 0) THEN
select phone from Table2 where care_level = 'default'; END IF
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20712398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Pagination in endless recycler view with firebase I am working on Q/A app . I have successfully loaded questions from firebase . But I am not able to apply pagination from Firebase like database . And how to recognize that we have reached end of recycler view so that next few questions can loaded .
A: To recognize that we have reached end of RecyclerView you can use this class EndlessRecyclerOnScrollListener.java
To load more next question, you should define one more field in Question class like number
public class Question {
private int number; // it must unique and auto increase when you add new question
...
}
Then when you load questions from FireBase you can do like
public class MainActivity extends AppCompatActivity {
private static final int TOTAL_ITEM_EACH_LOAD = 10;
private DatabaseReference mDatabase;
final List<Question> questionList = new ArrayList<>();
private int currentPage = 0;
private RecyclerView recyclerView;
private RecyclerViewAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
...
// init and set layout manager for your RecyclerView
...
mAdapter = new RecyclerViewAdapter(questionList);
recyclerView.setAdapter(mAdapter);
recyclerView.setOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) {
@Override
public void onLoadMore(int current_page) { // when we have reached end of RecyclerView this event fired
loadMoreData();
}
});
loadData(); // load data here for first time launch app
}
private void loadData() {
// example
// at first load : currentPage = 0 -> we startAt(0 * 10 = 0)
// at second load (first loadmore) : currentPage = 1 -> we startAt(1 * 10 = 10)
mDatabase.child("questions")
.limitToFirst(TOTAL_ITEM_EACH_LOAD)
.startAt(currentPage*TOTAL_ITEM_EACH_LOAD)
.orderByChild("number")
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChildren()){
Toast.makeText(MainActivity.this, "No more questions", Toast.LENGTH_SHORT).show();
currentPage--;
}
for (DataSnapshot data : dataSnapshot.getChildren()) {
Question question = data.getValue(Question.class);
questionList.add(question);
mAdapter.notifyDataSetChanged();
}
}
@Override public void onCancelled(DatabaseError databaseError) {}});
}
private void loadMoreData(){
currentPage++;
loadData();
}
}
Here is my DEMO project
A: To check whether you have reached the bottom of the RecyclerView, you can use the onScrolled listener as below, the if condition here is important and it is defining when a user has reached to the bottom.
mRV.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
mTotalItemCount = mLayoutManager.getItemCount();
mLastVisibleItemPosition = mLayoutManager.findLastVisibleItemPosition();
if (!mIsLoading && mTotalItemCount <= (mLastVisibleItemPosition + mPostsPerPage)) {
getUsers(mAdapter.getLastItemId());
mIsLoading = true;
}
}
});
Secondly, you can use startAt and limitToFirst methods to get questions in batches as shown below:
query = FirebaseDatabase.getInstance().getReference()
.child(Consts.FIREBASE_DATABASE_LOCATION_USERS)
.orderByKey()
.startAt(nodeId)
.limitToFirst(mPostsPerPage);
I have created an open source app that shows exactly how it is done. Please have a look: https://blog.shajeelafzal.com/2017/12/13/firebase-realtime-database-pagination-guide-using-recyclerview/
A:
You can create Firebase Queries to your FirebaseRecyclerAdapter, using startAt and limitToFirst to download records in batches.
The limitToFirst page size would be increased by and event, such as a click or a pull to refresh.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43289731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Detailed Initialization Procedure class variable initializer I saw many confusing answers about the following point :
Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
does class variable initializer include instance initliazer blocks ? and static initalizers include static block ? or does it only include variables ?
if not where does the order of intiliaztion come in the following :
https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4.2
eg. :
static {
...
} // can we consider this static initializer ?
{
}// variable initalizer ?
public static String x="test"; // static initializer ?
public String y; // variable initializer ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57169969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Schedule a SQL-query to move data from one table to another with Azure SQL-db I have a simple query that takes old data from a table and inserts the data into another table for archiving.
DELETE FROM Events
OUTPUT DELETED.*
INTO ArchiveEvents
WHERE GETDATE()-90 > Events.event_time
I want this query to run daily.
As i currently understand, there is no SQL Server Agent when using Azure SQL-db. Thus SQL Server agent does not seem like the solution here.
What is the easiest/best solution to this using Azure SQL-db?
A: There are multiple ways to run automated scripts on Azure SQL Database as below:
*
*Using Automation Account Runbooks.
*Using Elastic Database Jobs in Azure
*Using Azure Data factory.
As you are running just one script, I would suggest you to take a look into Automation Account Runbooks. As an example below, a PowerShell Runbook to execute the statement.
$database = @{
'ServerInstance' = 'servername.database.windows.net'
'Database' = 'databasename'
'Username' = 'uname'
'Password' = 'password'
'Query' = 'DELETE FROM Events OUTPUT DELETED.* INTO archieveevents'
}
Invoke -Sqlcmd @database
Then, it can be scheduled as needed:
A: You asked in part for a comparison of Elastic Jobs to Runbooks.
*
*Elastic Jobs will also run a pre-determined SQL script against a
target set of servers/databases.
-Elastic jobs were built
internally for Azure SQL by Azure SQL engineers, so the technology is
supported at the same level of Azure SQL.
*Elastic jobs can be defined and managed entirely through PowerShell scripts. However, they also support setup/configuration through TSQL.
*Elastic Jobs are handy if you want to target many databases, as you set up the job one time, and set the targets and it will run everywhere at once. If you have many databases on a given server that would be good targets, you only need to specify the target
server, and all of the databases on the server are automatically targeted.
*If you are adding/removing databases from a given server, and want to have the job dynamically adjust to this change, elastic jobs
is designed to do this seamlessly. You just have to configure
the job to the server, and every time it is run it will target
all (non excluded) databases on the server.
For reference, I am a Microsoft Employee who works in this space.
I have written a walkthrough and fuller explanation of elastic jobs in a blog series. Here is a link to the entry point of the series:https://techcommunity.microsoft.com/t5/azure-sql/elastic-jobs-in-azure-sql-database-what-and-why/ba-p/1177902
A: You can use Azure data factory, create a pipeline to execute SQL query and trigger it run every day. Azure data factory is used to move and transform data from Azure SQL or other storage.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64537270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a way to set numberOfLines to 1 of each entry in the dropdown picker? (react-native-dropdown-picker)
Code:
<DropDownPicker
//code here
style={styles.dropdown_container}
textStyle={styles.dropdown_itemstyle}
props={{style: styles.dropdown_container}}
itemProps={{
style: {
height: 30,
paddingHorizontal: '3%',
flexDirection: 'row',
},
}}
showTickIcon={false}
flatListProps={{
style: {
backgroundColor: COLORS.dirty_white,
borderRadius: 6,
borderColor: COLORS.gray_filter,
borderWidth: 1,
paddingTop: '2%',
},
}}
dropDownContainerStyle={{
borderWidth: 0,
}}
zIndex={5001}
/>
//code here
<View style={styles.bottomContainer}>
<Text numberOfLines={1}>
'Personal - I have problem in my birth certificate, my passport, my
criminal case, etc.'
</Text>
<Button
buttonStyle={[styles.clientBtnStyle, {backgroundColor: '#5E1B89'}]}>
<Text style={{color: 'white', fontWeight: 'bold', fontSize: 12}}>
Submit
</Text>
</Button>
</View>
The result that is wanted for each item in the dropdown picker is the one above the submit button. I have tried numberOfLines in labelProps but unfortunately it doesn't work. Is there any way to fix this?
A: Have you tried to truncate text using ellipsizeMode
A: There are at least two different solutions.
*
*Render custom list item
https://github.com/hossein-zare/react-native-dropdown-picker/issues/460
*Following pull gets merged or you make such changes manually before it happends
https://github.com/hossein-zare/react-native-dropdown-picker/pull/542
As I'm aware of labelProps with numberOfLines: 1 should work when picker is not open so that text would not wrap. But for it to work in list items there is no prop yet to easily achieve this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73616424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Change color of caption text in toctree Is there a way to change the color of captions on a sphinx webpage? I'm using the :caption: directive with toctree, but the caption comes out almost the same color as the sidebar. For reference here is the link to the page with the hard to see captions and here is my index file:
Contents
============
.. toctree::
:caption: User Documentation
:maxdepth: 2
overview
installation
tutorial
.. toctree::
:maxdepth: 2
:caption: Developer Documentation
dev/conventions
dev/enviroment
dev/docs
dev/site
doc/modules
* :ref:`genindex`
* :ref:`modindex`
.. toctree::
:maxdepth: 2
:caption: Support
trouble/faq
trouble/issuetracker
trouble/contact
A: You could add a color attribut to span.caption-text? For example in your source/_static/custom.cssput:
@import url("default.css");
span.caption-text {
color: red;
}
A: @aflp91 will indeed change caption text in the side bar, but also the caption text in the toctree as well.
If you want the caption color to change in side bar - and side bar only - you should add this
.wy-menu > .caption > span.caption-text {
color: #ffffff;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31326830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Stored Procedure while using variable return value becoming zero Please check the stored procedure - what is my mistake? I am trying to assign the calculated value to variable.
Alter Proc [dbo].[FindAnnualLeave1]
@Empid varchar(20)
as
Declare @AnnualPending int
Select
@AnnualPending = (select (0.0821917808219178) * DATEDIFF(d, e.doj,GETDATE())- l.Leaves
where l.EmpLeaveCode = 'Annual')
From
EmployeeLeaves l
inner join
EmployeeMaster e on l.EmpID = e.EmpID
where
l.EmpID = e.EmpID
return @AnnualPending
Go
Nothing is returned by this query. I want to show this variable to asp.net label once the command button clicks. If I am not using variable I mean only select statement its returns the value. I tried both asp and sql.
A: The return type from stored procedure is used to return exit code, which is int
Your computation is resulting in value between 0 and 1
You need to define output variable of type float or numeric(10,4) and return that value
Alter Proc [dbo].[FindAnnualLeave1]
@Empid varchar(20),
@AnnualPending numeric(10,4) OUTPUT
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26830940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android Gradle Plugin Error. Gradle DSL method not found: 'compile()' This is the exact error I'm getting while making a build in release Variant.
Error:(57, 0) Gradle DSL method not found: 'compile()'
Possible causes:
*The project 'spot' may be using a version of the Android Gradle plug-in that does not contain the method (e.g. 'testCompile' was added in 1.1.0).
Fix plugin version and sync project
*The project 'spot' may be using a version of Gradle that does not contain the method.
Open Gradle wrapper file
*The build file may be missing a Gradle plugin.
Apply Gradle plugin
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41319749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can I build a loop function that automatically creates multiple data-frames at one go? I have been struggling to try to nail down this coding dilemma. I have built a program that models and forecasts individual stock symbols. It works great, but I'm ready to take it to the next level where a user like myself can forecast multiple stock symbols at one go, instead of running the application multiples time for different stocks. It's a time-consuming process running my program for 10+ different stocks individually, for efficiency reasons, I would much rather create a list of stocks for my program to run on.
Below is my code which pulls stock data from yfinance and converts it to a dataframe.
#stock symbol
ticker = "FB"
# mm-dd-yy formate
start_date = "01-01-2014"
end_date = "11-20-2019"
#the code to pull data from yfinance
df = pdr.get_data_yahoo(ticker, start=start_date, end=end_date )
The problem I keep running into is, I don't know how to automate the creation of data-frames properly with each having a unique name that I can pass through in a list into my model. (is that even possible, setting up a list of data frames for my model to pass through?)
This is what I have in mind:
#stock symbols (I want to insert as many symbols as I can to automate my workflow. this example uses 4 stocks, but one day I might test 10 or 15)
tickers = ["FB","D","COF","WING"]
# mm-dd-yy formate
start_date = "01-01-2014"
end_date = "11-20-2019"
#the code to pull data from yfinance
for stock in tickers:
df = pdr.get_data_yahoo(tickers, start=start_date, end=end_date)
return df
I struggle with advanced loops. I do not know how to pass multiple strings of tickers into the pdr.get_data_yahoo() with a DF as each individual outcome for each stock. The Dataframes needs to be uniquely named, nothing too complex, and homogeneous. For example, I would need this application to work if I wanted to test for 1 stock, or 20 at a time, while I pass multiple data frames in a loop for my model to evaluate.
I would greatly appreciate some guidance here.
A: This answer might help: Create new dataframe in pandas with dynamic names also add new column
The approach suggested in the post would be to create a dictionary that would store the dataframe as the value and the stock ticker as the key.
df_dict = {}
for stock in tickers:
df = pdr.get_data_yahoo(tickers, start=start_date,end=end_date)
df_dict[stock] = df
Then you can iterate over the dictionary using the stock tickers as keys.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59020355",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: django filter on APIView I have a APIView class for showing all the rents and posting and delete etc. Now i want search feature so i tried to use DjangoFilterBackend but it is not working. I see in documentation, it has been used with ListAPIView but how can i use it in APIView.
class Rent(APIView):
"""
List all the rents if token is not provided else a token specific rent
"""
serializer_class = RentSerializer
filter_backends = (DjangoFilterBackend,)
filter_fields = ('city', 'place', 'property_category',)
search_fields = ('=city', '=place')
def get(self, request, token=None, format=None):
reply={}
try:
rents = Rental.objects.all()
if token:
rent = Rental.objects.get(token=token)
reply['data'] = self.serializer_class(rent).data
else:
reply['data'] = self.serializer_class(rents, many=True).data
except Rental.DoesNotExist:
return error.RequestedResourceNotFound().as_response()
except:
return error.UnknownError().as_response()
else:
return Response(reply, status.HTTP_200_OK)
when i search the rent with the following parameters in the url, i get all the rents, instead i should get only those rents that lies in city Kathmandu and place koteshwor
http://localhost:8000/api/v1/rents?city=Kathmandu&place=Koteshwor
A: In case someone is wondering how can we integrate django_filters filter_class with api_views:
@api_view(['GET'])
@permission_classes([permissions.IsAuthenticated])
def filter_data(request, format=None):
qs = models.YourModal.objects.all()
filtered_data = filters.YourFilter(request.GET, queryset=qs)
filtered_qs = filtered_data.qs
....
return response.Ok(yourData)
A: Adding to @ChidG's answer. All you need to do is override the DjangoFilterBackend's filter_queryset method, which is the entry point for the filter, and pass it the instance of your APIView. The important point to note here is you must declare filter_fields or filter_class on the view in order to get the filter to work. Otherwise it just return your queryset unfiltered.
If you're more curious about how this works, the class is located at django_filters.rest_framework.backends.py
In this example, the url would look something like {base_url}/foo?is_active=true
from django_filters.rest_framework import DjangoFilterBackend
class FooFilter(DjangoFilterBackend):
def filter_queryset(self, request, queryset, view):
filter_class = self.get_filter_class(view, queryset)
if filter_class:
return filter_class(request.query_params, queryset=queryset, request=request).qs
return queryset
class Foo(APIView):
permission_classes = (AllowAny,)
filter_fields = ('name', 'is_active')
def get(self, request, format=None):
queryset = Foo.objects.all()
ff = FooFilter()
filtered_queryset = ff.filter_queryset(request, queryset, self)
if filtered_queryset.exists():
serializer = FooSerializer(queryset, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response([], status=status.HTTP_200_OK)
A: To use the functionality of DjangoFilterBackend, you could incorporate the filter_queryset method from GenericViewSet, which is the DRF class that inherits from APIView and leads to all specific 'generic' view classes in DRF. It looks like this:
def filter_queryset(self, queryset):
"""
Given a queryset, filter it with whichever filter backend is in use.
You are unlikely to want to override this method, although you may need
to call it either from a list view, or from a custom `get_object`
method if you want to apply the configured filtering backend to the
default queryset.
"""
for backend in list(self.filter_backends):
queryset = backend().filter_queryset(self.request, queryset, self)
return queryset
https://github.com/encode/django-rest-framework/blob/master/rest_framework/generics.py
A: Here If you are using APIView, There is nothing to do with filters.So you have to do like
get_data = request.query_params #or request.GET check both
Then
Rental.objects.filter(city=get_data['city'], place=get_data['place'])
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43906253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: How to find online android app hidden API? I want to scrape an online android app data, so first of all I'm searching for the API, I have tried Mitmproxy, but when I changed my wifi proxy setting then my internet connection won't work and due to this my app is not working or not sending the data because it's an online app and without internet it's not possible, can anyone tell me what's the best way to find the hidden API of an online android app?
Thanks in Advance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73200179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Finding a non-consecutive number pair in an array Given an array with a minimum length of 3 and a maximum length of 5, which always contains uniquely occurring integers from 0 to 4 in ascending order, I need to pick out two non-consecutive numbers from it. Non-consecutive refers to their numeric value, not their position in the array.
To clarify, here are examples of valid arrays:
*
*[ 1, 2, 3 ]
*[ 0, 1, 2, 4 ]
*[ 0, 3, 4 ]
For the arrays above, valid answers could be, respectively:
*
*[ 1, 3 ]
*[ 0, 2 ], [ 0, 4 ] or [ 1, 4 ]
*[ 0, 3 ] or [ 0, 4 ]
Furthermore, in those cases where there is more than one valid answer, I need it to be selected at random, if at all possible (for instance I don't want to favor sequences that begin with the lowest number, which is what would occur if I always began checking from left to right and stopped checking as soon as I found one valid solution).
What would be the most efficient way of tackling this problem in Javascript?
A: You could use two nested iterations and build an new array for choosing as random result.
function getNonConsecutives(array) {
return array.reduce((r, a, i, aa) => r.concat(aa.slice(i + 2).map(b => [a, b])), []);
}
console.log(getNonConsecutives([ 0, 1, 2, 4 ]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
According to Bee157's answer, you could use a random choice with a constraint, like length for the first index and add the needed space for the second index.
The problem is, due to the nature of choosing the first number first, the distribution of the result is not equal.
function getNonConsecutives(array) {
var i = Math.floor(Math.random() * (array.length - 2));
return [
array[i],
array[Math.floor(Math.random() * (array.length - 2 - i)) + 2 + i]
];
}
console.log(getNonConsecutives([ 0, 1, 2, 4 ]));
A: since you state that the array ellemnts are all unique, and that they are sorted.
It should suffice to take an random element
var index1=Math.floor(Math.random()*arr.length)
now any other element (except maybe the elemnts on position (index1 +/- 1) are not consecutive
So a new random element can be chosen excluding the first index.
var index2=Math.floor(Math.random()*arr.length);
if(index2==index1){
index2+=((index2<arr.length-1)?1:-1);
}
if(Math.abs(arr[index1]-arr[index2])<=1){
if(index2==0 && arr.length<4){
//set index2 to arr.length-1 and do check again, if not ok=> no result
if(!(arr[index1]-arr[arr.length-1]>=-1)){
return [arr[arr.length-1],arr[index1]];
}
}
else if(index2==arr.length-1 && arr.length<4){
//set index2 to 0 and do check again, if not ok=> no result
if(!(arr[index1]-arr[0]<=1)){
return [arr[0],arr[index1]];
}
}
else{
//if index2>index1 index2++
//else index2--
//always OK so no further check needed
index2+=(index2>index1?1:-1);
return [arr[index1],arr[index2]];
}
}
else{
//ok
return [arr[index1,arr[index2]];
}
return false;
if speed is not important, you can use a filter on the array to calculate a new array with all elements differing more then 1 unit of arr[index1]. and randomly select a new number from this new array.
Other attempt
function getNonConsecutive(arr){
var index1,index2,arr2;
index1=Math.floor(Math.random()*arr.length);
arr2=[].concat(arr);
arr2.splice((index1!==0?index1-1:index1),(index!==0?3:2));
if(arr2.length){
index2=Math.floor(Math.random()*arr2.length);
return [arr[index1],arr2[index2]];
}
else{
//original array has length 3 or less
arr2=[].concat(arr);
arr2.splice(index1),1);
for (var j=0,len=arr.length;j<len;j++){
if(Math.abs(arr1[index1]-arr2[j])>1){
return [arr[index1],arr2[j]];
}
}
}
return false
}
A: Something like this should do it:
const pick = nums => {
// Pick a random number
const val = nums[Math.floor(Math.random() * nums.length) + 0];
// Filter out any numbers that are numerically consecutive
const pool = nums.filter(n => Math.abs(n - val) > 1);
// Pick another random number from the remainer
const other = pool[Math.floor(Math.random() * pool.length) + 0];
// Sort + return them
return [val, other].sort();
};
console.log(pick([0, 1, 2, 4]));
A: demoFn(array) {
var i,j, y =[];
for (i=0; i<=array.length;i++) {
for (j = i + 1; j <= array.length; j++) {
if (array[j] && array[i]) {
if (array[j] !== array[i] + 1) {
y.push([array[i], array[j]]);
}
}
}
}
}
Take a random array and check it.
A: You can create a function using recursion that will pick random number in each iteration and loop all other elements and if condition is met add to array.
function findN(data) {
data = data.slice();
var r = []
function repeat(data) {
if (data.length < 2) return r;
var n = parseInt(Math.random() * data.length);
data.forEach(function(e, i) {
if (i != n) {
var a = data[n];
if (Math.abs(a - e) != 1 && r.length < 2) r.push(n < i ? [a, e] : [e, a])
}
})
data.splice(n, 1);
repeat(data)
return r;
}
return repeat(data)
}
console.log(findN([1, 2, 3]))
console.log(findN([0, 1, 2, 4]))
console.log(findN([0, 3, 4]))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45371282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Uninstall AFNetworking from Xcode Workspace Can somebody help me uninstall/remove AFNetworking from my xcode project? I have tried deleting the files, but then I recieve an error message.
A: I've tried to delete all thing on Podfile archive and then install the pod again with the command "pod install" on the worksapce path.
It worked to me.
A: If you're using Cocoapods,
1. Remove the line pod 'AFNetworking' from Podfile.
2. Open terminal, go to project directory, & do pod install
That should work.
And,
If you're not using Cocoapods, just remove the AFNetworking framework from XcodeProject file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30540183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Wait Cursor issue - Need help I have been searching in the net as well here to get some help/info on wait cursors, but couldn't find direct answer.
I am having web project built in vs 2008 c#. As usual I have master page and child pages as well some user controls placed on some of the child pages. As child pages or user controls will not have or I am little confusion on how to use wait cursor on the following scenarios
1) Page load. Wait cursor automatically coming in google chrome, but not in IE when page is loading. There is some database functionality attached in each child page directly or through user controls.
2) Button click on either child page or in user control
Once the processing is over, the cursor should come back to normal.
Any help with some sample would be greatly appreciated, as I am working on this since 4 days without any proper solutions so far.
I have created sample web project to replicate the problem, I can send for reproducing.
A: Use css to set cursor of body as "Wait" when button is clicked. And when page is processed, set them to "Default". Wait cursor over entire html page
A: Have you already checked with some tool (like fiddler) whether loading of the page is really done? If youre not using CSS for changing the cursor, the problem might be that some request is still running: this would then be the point for further investigation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6623016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to block iOS screen capture on intune I use Microsoft Teams.
Currently, we used the app policy using intune. When using Android's device, screen capture is blocked.
However, if you use Teams app on iOS devices, you cannot block screen capture.
I want to block screen capture when I use Teams app on iOS devices.
Please let me know when the update will be made.
Also, please let me know if there is a good way to solve my problem.
Please.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63500961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Building a routine to generate CREATE TRIGGER code in Postgres I haven't found a straightforward way to retrieve trigger definition code. I mean the trigger/binding declaration, not the trigger function. I figured I'd use some of the system catalogs to build up a script. The following, incomplete, version produces sensible output:
CREATE OR REPLACE FUNCTION dba.ddl_get_build_trigger_code(trigger_id oid) -- I starting from having the OID.
RETURNS text
AS $BODY$
DECLARE
trigger_name_in text;
code text;
BEGIN
/*
What the original declaration looks like:
CREATE TRIGGER trigger_hsys_after_delete
AFTER DELETE
ON data.hsys
REFERENCING OLD TABLE AS deleted_rows
FOR EACH STATEMENT
EXECUTE PROCEDURE data.trigger_function_log_deletion_count();
*/
SELECT tgname FROM pg_trigger WHERE oid = trigger_id INTO trigger_name_in; -- information_schema tables don't use PG OIDs.
RETURN
'CREATE TRIGGER ' || trigger_name || chr(10) ||
chr(9) || action_timing || ' ' || event_manipulation || chr(10) ||
chr(9) || 'ON ' || event_object_schema || '.' || event_object_table ||
CASE WHEN action_reference_old_table IS NOT NULL THEN
chr(10) || chr(9) || 'REFERENCING OLD TABLE AS ' || action_reference_old_table || chr(10) END ||
-- CASE WHEN action_reference_new_table IS NOT NULL THEN
-- chr(10) || chr(9) || 'REFERENCING NEW TABLE AS ' || action_reference_new_table || chr(10) END ||
chr(9) || 'FOR EACH ' || action_orientation || chr(10) ||
chr(9) || action_statement || ';' as create_trigger_code
FROM information_schema.triggers
WHERE trigger_name = trigger_name_in;
END;
$BODY$
LANGUAGE plpgsql;
Here's a sample, matching my actual case:
CREATE TRIGGER trigger_hsys_after_delete
AFTER DELETE
ON data.hsys
REFERENCING OLD TABLE AS deleted_rows
FOR EACH STATEMENT
EXECUTE PROCEDURE trigger_function_log_deletion_count();
There are several more attributes in information_schema.triggers that may have values, such as action_reference_new_table. When I enable the lines below and action_reference_new_table is NULL, the the script returns NULL:
CASE WHEN action_reference_new_table IS NOT NULL THEN
chr(10) || chr(9) || 'REFERENCING NEW TABLE AS ' || action_reference_new_table || chr(10) END ||
I don't understand why the NULL value for action_reference_new_table blows up my concatenation code and makes the entire result NULL.
Apart from help on this specific question, feel free to point out whatever I should do to write more sensible PL/PgSQL code. It's proving to be harder for me to master than I would have guessed.
A: Simply use
SELECT pg_get_triggerdef(oid)
FROM pg_trigger
WHERE tgname = trigger_name_in;
Besides, never use string concatenation when composing SQL code. The danger of SQL injection is too great. Use the format() function with the %I placeholder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60160781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: delete duplication in my db with 4 columns I have 4 columns with different numbers, each row is a different combination, my objective is to remove remove the duplicates in the table.
As these are combinations where the order of the digits is swapped, i want to remove the swapped rows and keep only 1 (i'm guessing each 4 numbers set will have 24 different options in the table, so i'll need to delete 23 and keep only 1)
Table name: "4_numbers"
-------------------------
|id | e1 | e2 | e3 | e4 |
-------------------------
| 1 | 1 | 5 | 3 | 7 |
| 2 | 1 | 5 | 7 | 9 |
| 3 | 5 | 1 | 7 | 3 |
-------------------------
so i need to delete one of the row that has a duplicate combination. for example one of the rows 1 or 3
here is what i tried, but its going into a infinite loop, i am sure something is wrong with my query.
<?php
$sql = mysql_connect("localhost", "root", "mysql");
if (!$sql) {
die("Could not connect: " . mysql_error());
}
mysql_select_db("combs");
$result = mysql_query("delete b from 4_even a join 4_even b on (a.e1 = b.e2 and a.e2 = b.e2 and a.e3 = b.e4 and a.e4 = b.e4) or (a.e2 = b.e1 and a.e1 = b.e2 and a.e4 = b.e3 and a.e3 = b.e4) where a.id < b.id;");
echo "success";
if (!$result) {
die("Could not delete. " . mysql_error());
}
?>
my query is an adaptation of another query i used earlier to remove duplicates from a table of 2 columns and not 4, it worked perfectly with it. so i just need to adapt it to support 4 columns.
mysql_query("delete b from 4_numbers a join 4_numbers b on (a.e1 = b.e2 and a.e2 = b.e2) or (a.e2 = b.e1 and a.e1 = b.e2) where a.id < b.id;")
A: you can do with a query like this.
1) create a temp table
2) insert all unique row in temp
3) rename table ( is atomic) so the application not fails
CREATE TABLE tmp_4_even LIKE 4_even;
INSERT INTO tmp_4_even
SELECT e2.* FROM (
SELECT id FROM (
SELECT min(id) AS id, GROUP_CONCAT(e1 SEPARATOR '-') AS g
FROM ( SELECT id,e1 FROM 4_even UNION ALL SELECT id,e2 FROM 4_even UNION ALL SELECT id,e3 FROM 4_even UNION ALL SELECT id,e4 FROM 4_even
ORDER BY id,e1
) AS res
GROUP BY id
) res2
GROUP BY g
) e1
LEFT JOIN 4_even e2 ON e1.id = e2.id;
RENAME TABLE 4_even TO 4_even_org, tmp_4_even TO 4_even;
sample inner query
mysql> SELECT * FROM (
-> SELECT min(id) AS id, GROUP_CONCAT(e1 SEPARATOR '-') AS g
-> FROM ( SELECT id,e1 FROM 4_even UNION ALL SELECT id,e2 FROM 4_even UNION ALL SELECT id,e3 FROM 4_even UNION ALL SELECT id,e4 FROM 4_even
-> ORDER BY id,e1
-> ) AS res
-> GROUP BY id
-> ) res2
-> GROUP BY g ;
+------+---------+
| id | g |
+------+---------+
| 1 | 1-3-5-7 |
| 4 | 5-7-1-5 |
+------+---------+
2 rows in set, 1 warning (0,00 sec)
mysql>
sample
mysql> select * from 4_even;
+----+------+------+------+------+
| id | e1 | e2 | e3 | e4 |
+----+------+------+------+------+
| 1 | 1 | 5 | 3 | 7 |
| 2 | 1 | 5 | 7 | 3 |
| 3 | 5 | 1 | 7 | 3 |
| 4 | 5 | 1 | 7 | 5 |
+----+------+------+------+------+
4 rows in set (0,00 sec)
mysql> CREATE TABLE tmp_4_even LIKE 4_even;
Query OK, 0 rows affected (0,02 sec)
mysql>
mysql> INSERT INTO tmp_4_even
-> SELECT e2.* FROM (
-> SELECT id FROM (
-> SELECT min(id) AS id, GROUP_CONCAT(e1 SEPARATOR '-') AS g
-> FROM ( SELECT id,e1 FROM 4_even UNION ALL SELECT id,e2 FROM 4_even UNION ALL SELECT id,e3 FROM 4_even UNION ALL SELECT id,e4 FROM 4_even
-> ORDER BY id,e1
-> ) AS res
-> GROUP BY id
-> ) res2
-> GROUP BY g
-> ) e1
-> LEFT JOIN 4_even e2 ON e1.id = e2.id;
Query OK, 2 rows affected, 1 warning (0,00 sec)
Records: 2 Duplicates: 0 Warnings: 1
mysql>
mysql> RENAME TABLE 4_even TO 4_even_org, tmp_4_even TO 4_even;
Query OK, 0 rows affected (0,00 sec)
mysql> select * from 4_even;
+----+------+------+------+------+
| id | e1 | e2 | e3 | e4 |
+----+------+------+------+------+
| 1 | 1 | 5 | 3 | 7 |
| 4 | 5 | 1 | 7 | 5 |
+----+------+------+------+------+
2 rows in set (0,00 sec)
mysql>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42976421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: My app crashes when opening navigation drawer i am making navigation drawer but it crashes with following error:
Error inflating class android.support.design.widget.NavigationView
here is my code
mainactivity
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
class MainActivity : AppCompatActivity() {
lateinit var mdrawerlayout:DrawerLayout
lateinit var mToggle:ActionBarDrawerToggle
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mdrawerlayout = findViewById(R.id.DrawerId)
mToggle = ActionBarDrawerToggle(this,mdrawerlayout,R.string.open,R.string.close)
mdrawerlayout.addDrawerListener(mToggle)
mToggle.syncState()
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
}
}
my xml layout
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/DrawerId"
tools:context="com.bird.play.MainActivity">
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:menu="@menu/menu"
/>
</android.support.v4.widget.DrawerLayout>
here is the error cant post full error
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bird.play/com.bird.play.MainActivity}: android.view.InflateException: Binary XML file line #0: Error inflating class android.support.design.widget.NavigationView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3168)
at com.bird.play.MainActivity.onCreate(MainActivity.kt:18)
both of my support design and app compact library have the same version
26.1.0
build gradle
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.bird.play"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:design:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
A: Try changing Navigation view like this
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/menu"
/>
A: DrawerLayout must contains 2 children (not more than 2). Can you please try this layout
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/DrawerId"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.bird.play.MainActivity">
<!-- The main content view -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<android.support.design.widget.NavigationView
android:id="@+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/menu" />
</android.support.v4.widget.DrawerLayout>
Please check the doc
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48060620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I get the selected text from a WordEditor Object and change it's color? I'm trying to use the WordEditor object to modify the color of the selected text (Outlook VBA) but i'm unable to find documentation or examples on how to do it. Any ideas?
I don't want to use the HTML editor, i need a solution for WordEditor.
I tried debuging the code and using OutlookSpy, but everytime i go into WordEditor.Content my outlook freezes and restarts :(.
Using Outlook 2010 on Windows 7
A: OK - I found something that works. Ugly, but works:
Sub EmphesizeSelectedText(color As Long)
Dim msg As Outlook.MailItem
Dim insp As Outlook.Inspector
Set insp = Application.ActiveInspector
If insp.CurrentItem.Class = olMail Then
Set msg = insp.CurrentItem
If insp.EditorType = olEditorWord Then
Set document = msg.GetInspector.WordEditor
Set rng = document.Application.Selection
With rng.font
.Bold = True
.color = color
End With
End If
End If
Set insp = Nothing
Set rng = Nothing
Set hed = Nothing
Set msg = Nothing
End Sub
Eventually I found a reference that WordEditor returns a Document object. From there it was 2 hrs of going over MSDN's very slow web-help to find out that to get the selected text i needed to go up one level to the Application.
Important note - changing rng.Style.Font did not do what i wanted it to do, it changed the entire document, when i started using the with rng.font my problem was solved (Thanks to Excel's marco recording abilities for showing me the correct syntax)
A: Annotations are in German
Option Explicit
'Sub EmphesizeSelectedText(color As Long)
Sub EmphesizeSelectedText()
Dim om_msg As Outlook.MailItem
Dim oi_insp As Outlook.Inspector
Dim ws_selec As Word.Selection
Dim wd_Document As Word.Document
Dim str_test As String
Dim lng_color As Long
lng_color = 255
'Zugriff auf aktive E-Mail
Set oi_insp = Application.ActiveInspector()
'Überprüft ob es sich wirklich um eine E-Mail handelt
If oi_insp.CurrentItem.Class = olMail Then
Set om_msg = oi_insp.CurrentItem
If oi_insp.EditorType = olEditorWord Then
' es gibt noch "olEditorHTML", "olEditorRTF", "olEditorText" und "olEditorWord"
' ist bei mir aber immer "olEditorWord" (= 4) - egal was ich im E-Mail Editor auswähle
' Set wd_Document = om_msg.Getinspector.WordEditor ' macht das gleiche wie nächste Zeile
Set wd_Document = oi_insp.WordEditor
Set ws_selec = wd_Document.Application.Selection
str_test = ws_selec.Text
Debug.Print ws_selec.Text
ws_selec.Text = "foo bar"
If om_msg.BodyFormat <> olFormatPlain Then
' auch wenn om_msg.BodyFormat = olFormatPlain ist, kann oi_insp.EditorType = olEditorWord sein
' doch dann gehen Formatierungen nicht -> Error !!!
With ws_selec.Font
.Bold = True
.color = lng_color ' = 255 = red
.color = wdColorBlue
End With
End If
ws_selec.Text = str_test
End If
End If
Set oi_insp = Nothing
Set ws_selec = Nothing
Set om_msg = Nothing
Set wd_Document = Nothing
End Sub
Verweise: (I do not know how it is called in the english version)
*
*Visual Basic for Applications
*Microsoft Outlook 15.0 Object Library
*OLE Automation
*Microsoft Office 15.0 Object Library
*Microsoft Word 15.0 Object Library
Gruz $3v|\|
A: an other example:
Option Explicit
Private Sub Test_It()
Dim om_Item As Outlook.MailItem
Dim oi_Inspector As Outlook.Inspector
Dim wd_Doc As Word.Document
Dim wd_Selection As Word.Selection
Dim wr_Range As Word.Range
Dim b_return As Boolean
Dim str_Text As String
str_Text = "Hello World"
'Zugriff auf aktive E-Mail
Set oi_Inspector = Application.ActiveInspector()
Set om_Item = oi_Inspector.CurrentItem
Set wd_Doc = oi_Inspector.WordEditor
'Zugriff auf Textmarkierung in E-Mail
Set wd_Selection = wd_Doc.Application.Selection
wd_Selection.InsertBefore str_Text
'Zugriff auf 'virtuelle' Markierung
'wr_Range muss auf das ganze Dokument gesetzt werden !
Set wr_Range = wd_Doc.Content
'Suche in E-Mail Text
With wr_Range.Find
.Forward = True
.ClearFormatting
.MatchWholeWord = True
.MatchCase = False
.Wrap = wdFindStop
.MatchWildcards = True
.Text = "#%*%#"
End With
b_return = True
Do While b_return
b_return = wr_Range.Find.Execute
If b_return Then
' Es wurde gefunden
str_Text = wr_Range.Text
'schneide den Anfangstext und das Ende ab
'str_TextID = Mid$(str_TextID, 11, Len(str_TextID) - 12)
MsgBox ("Es wurde noch folgender Schlüssel gefunden:" & vbCrLf & str_Text)
End If
Loop
'aktiv Range ändern
'wr_Range muss auf das ganze Dokument gesetzt werden !
Set wr_Range = wd_Doc.Content
wr_Range.Start = wr_Range.Start + 20
wr_Range.End = wr_Range.End - 20
'Text formatieren
With wr_Range.Font
.ColorIndex = wdBlue
.Bold = True
.Italic = True
.Underline = wdUnderlineDotDashHeavy
End With
'Freigeben der verwendeten Variablen
Set oi_Inspector = Nothing
Set om_Item = Nothing
Set wd_Doc = Nothing
Set wd_Selection = Nothing
Set wr_Range = Nothing
End Sub
Gruz $3v|\|
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4361293",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: removing apostrophes for plotting of matplotlib graph i am trying to plot a graph on matplotlib but it will not work properly as the values are returned with apostrophes, here is my code,
import matplotlib.pyplot as plt
emp_data_list=[]
def read_file():
infile = open ('emp_data.txt', 'r')
for row in infile:
if not row.startswith('#'):
row = row.rstrip('\n').split(', ')
emp_data_list.append(row)
infile.close()
read_file()
for item in range(len(emp_data_list)):
salaries = [stuff[4] for stuff in emp_data_list]
print salaries
i also used this for salaries aswell:
salaries = [salary for emp_no, name, age, pos, salary, yrs_emp in emp_data_list]
when salaries is printed it returns:
['29000', '24000', '42000', '21000', '53000', '42000', '50000', '33000', '38000', '22000', '19000', '23000', '44000', '32000', '28000']
i believe this is why my graph isn't working
A: Try casting the strings to integers in the code below
salaries = [int(salary) for emp_no, name, age, pos, salary, yrs_emp in emp_data_list]
Also, welcome to Stack Overflow! Mark this as the answer if it works for you :)
A: The apostrophes which you see in your print output show up there to indicate that the values are strings. I guess you need to convert your variables to integers before plotting:
salaries = list(map(int, salaries))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53772075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Memory-optimized Gauss-Seidel iteration on a tridiagonal matrix in Octave I'm trying to write a program in Octave that will solve a tridiagonal linear equation system. The specific part is that my data is not saved in a usual nxn matrix, but in a nx3 matrix where each column represents the lower, main and upper diagonal respectively.
I already developed a functional iterative process for usual matrices, but in this case, I somehow can't get the indexing right (I assume, since the code is more or less the same). A(1,1) and A(n,3) are always empty.
A = [ 0, 1, 1;
1, 1, 1;
1, 1, 0 ]
# represents M = [ 1, 1, 0;
# 1, 1, 1;
# 0, 1, 1 ]
b = [ 3, 2, 1 ]
n = 3
x_new = [2 2 2]
x_old = [2 2 2]
for iter = 1:16
disp(iter)
for i = 1:n
if i == 1
# disp(A(i,:))
# disp("first")
x_new(i) = (1 / A(i, 2)) * ( b(i) - A(i, 3)*x_old(i+1) );
elseif i == n
# disp(A(i,:))
# disp("last")
x_new(i) = (1 / A(i, 2)) * ( b(i) - A(i, 1)*x_new(i-1) );
else
x_new(i) = (1 / A(i, 2)) * ( b(i) - A(i, 1)*x_new(i-1) - A(i, 3)*x_old(i+1) );
end
x_old = x_new;
end
end
disp(x_old)
Any tips? I'm new to octave and algebra.
A: M is not diagonally dominant nor positive definite. Use function chol() for positive definite test.
The assignment x_old = x_new should not be in the inner loop:
while it < maxit
x_old = x_new;
x_new(1) = (1 / A(1, 2)) * ( b(1) - A(1, 3) * x_old(2) );
for i = 2 : n - 1
x_new(i) = (1 / A(i, 2)) * ( b(i) - A(i, 1) * x_new(i - 1) - A(i, 3) * x_old(i + 1) );
end
x_new(n) = (1 / A(n, 2)) * ( b(n) - A(n, 1) * x_new(n - 1) );
if norm(x_new - x_old, 'inf') <= max_error
break
end
it = it + 1;
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47514861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Auto screen orientation is not working one user ser screen orientation android I have create a custom media player.In which there is a button for landscape and portrait mode. When player opens media player,its all feature works fine.But on click fullscreen button, i set media player to landscape mode. After this button click auto screen orientation is not working, only user can change orientation by clicking button(button to change landscape/portrait). Is there any method to work both auto screen orientation with button(button to change landscape/portrait)?
Thanks.
A: In your manifest file, you have given permisssion for potrait and landscape, So you have avoid that, instead of that do it in your activity.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18056664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Accessing Java byte[] in C++ I have a Java application that persists byte[] structures to a DB (using Hibernate). I'm writing a C++ application that reads these structures at a later time.
As you might expect, I'm having problems.... The byte[] structure written to the DB is longer than the original number of bytes - 27 bytes, by the looks of things.
Is there a way of determining (in C++) the byte[] header structure to properly find the beginning of the true data?
I spent some time looking at the JNI source code (GetArrayLength(jbytearray), etc.) to determine how that works, but got quickly mired in the vagaries of JVM code. yuck...
Ideas?
A: The object is probably being serialized using the Java Object Serialization Protocol. You can verify this by looking for the magic number 0xACED at the beginning. If this is the case, it's just wrapped with some meta information about the class and length, and you can easily parse the actual byte values off the end.
In particular, you would see 0xAC 0xED 0x00 0x05 for the header followed by a classDesc element that would be 0x75 ...bytes... 0x70, followed by a 4 byte length, and the then the bytes themselves. Java serializes the length and other multibyte values in big-endian format.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6299145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: C# Read Block Implementation I am writing a program which is parsing large, non-predictable files. No problem with this part. I have been using the code below, looping through ReadLine until the end of the document to keep the memory footprint low. My problem being is an OutOfMemoryException when a line is simply too long.
System.IO.StreamReader casereader = new System.IO.StreamReader(dumplocation);
string line;
while ((line = casereader.ReadLine()) != null)
{
foreach (Match m in linkParser.Matches(line))
{
Console.Write(displaytext);
Console.WriteLine(m.Value);
XMLWrite.Start(m.Value, displaytext, dumplocation, line);
}
}
XMLWrite is just writing any strings that match my Regex Function to an XML Document. The Regex function is a simple email search. The issue occurs when ReadLine is called and the application finds an extremely long line in the file I am reading(I can see this as the memory usage in task manger climbs and climbs as it populates the string 'line'). Eventually it runs out of memory and crashes. What I want to do is read pre defined blocks (e.g 8,000 characters) and then run these one at a time through the same process. This means that I will then always know the length of string line (8,000 chars) and should not receive and out of memory exception. Does my logic seem logic!? I am looking for the best way to implement ReadBlock as currently I am unable to get it working.
Any help much appreciated!
A: You can try with this code
using (StreamReader sr = new StreamReader(yourPath))
{
//This is an arbitrary size for this example.
char[] c = null;
while (sr.Peek() >= 0)
{
c = new char[5];//Read block of 5 characters
sr.Read(c, 0, c.Length);
Console.WriteLine(c); //print block
}
}
Link : http://msdn.microsoft.com/en-us/library/9kstw824.aspx
A: line = buffer.ToString();
This statement should be to blame. buffer is a char array, and its ToString() methods just return System.char[].
A: Use: line= new string(buffer);
Instead
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11849355",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Call docker command line to remove all containers from python I am trying to port:
https://coderwall.com/p/ewk0mq/stop-remove-all-docker-containers
to a python script. So far I have:
def remove_all_containers():
subprocess.call(['docker', 'stop','$(docker ps -a -q)'])
subprocess.call(['docker', 'rm','$(docker ps -a -q)'])
return;
But get:
Error response from daemon: No such container: $(docker ps -a -q)
I have also tried:
def remove_all_containers():
subprocess.call(['docker', 'stop',$(docker ps -a -q)])
subprocess.call(['docker', 'rm',$(docker ps -a -q)])
return;
But that gives:
subprocess.call(['docker', 'stop',$(docker ps -a -q)])
SyntaxError: invalid syntax
it seems I need to nest another subprocess call into the parent subprocess call. Or is there a simpler way to do this?
A: TL;DR: Command substitution $(...) is a shell feature, therefore you must run your commands on a shell:
subprocess.call('docker stop $(docker ps -a -q)', shell=True)
subprocess.call('docker rm $(docker ps -a -q)', shell=True)
Additional improvements:
It's not required, but I would suggest using check_call (or run(..., check=True), see below) instead of call(), so that if an error occurs it doesn't go unnoticed:
subprocess.check_call('docker stop $(docker ps -a -q)', shell=True)
subprocess.check_call('docker rm $(docker ps -a -q)', shell=True)
You can also go another route: parse the output of docker ps -a -q and then pass to stop and rm:
container_ids = subprocess.check_output(['docker', 'ps', '-aq'], encoding='ascii')
container_ids = container_ids.strip().split()
if container_ids:
subprocess.check_call(['docker', 'stop'] + container_ids])
subprocess.check_call(['docker', 'rm'] + container_ids])
If you're using Python 3.5+, you can also use the newer run() function:
# With shell
subprocess.run('docker stop $(docker ps -a -q)', shell=True, check=True)
subprocess.run('docker rm $(docker ps -a -q)', shell=True, check=True)
# Without shell
proc = subprocess.run(['docker', 'ps', '-aq'], check=True, stdout=PIPE, encoding='ascii')
container_ids = proc.stdout.strip().split()
if container_ids:
subprocess.run(['docker', 'stop'] + container_ids], check=True)
subprocess.run(['docker', 'rm'] + container_ids], check=True)
A: There is nice official library for python, that helps with Docker.
https://docker-py.readthedocs.io/en/stable/index.html
import docker
client = docker.DockerClient(Config.DOCKER_BASE_URL)
docker_containers = client.containers.list(all=True)
for dc in docker_containers:
dc.remove(force=True)
We've received all containers and remove them all doesn't matter container status is 'started' or not.
The library could be useful if you can import it into code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48481138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Creating TextView by for loop, only the first created working I am trying to create a brunch of TextView and show them on the screen by a for loop.
But only the first TextView shows the value "123" assigned.
There are still many TextView created but only the first one shows value.
I think I missed something, but do you have idea that what I had missed?
Thanks.
onCreate():
LinearLayout busStopLinearLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
// skipped
busStopLinearLayout = (LinearLayout) findViewById(R.id.bus_stop_linear_layout);
// skipped
}
The for loop I am asking for:
for (int i = 0; i < closestStop.size(); i++) {
TextView dummyTxt = new TextView(MainActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
dummyTxt.setLayoutParams(params);
dummyTxt.setText("123");
busStopLinearLayout.addView(dummyTxt);
busStopTextArray.add(dummyTxt);
}
activity.xml
<LinearLayout
android:id="@+id/bus_stop_linear_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:orientation="horizontal">
A: Try This out
LinearLayout busStopLinearLayout = (LinearLayout) findViewById(R.id.busStopLinearLayout);
for(int i=0; i<closestStop.size(); i++){
TextView text = new TextView(this);
text.setText("123");
text.setTextSize(12);
text.setGravity(Gravity.LEFT);
text.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
busStopLinearLayout.addView(text);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67455291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: pandas: how to get the percentage for each row When I use pandas value_count method, I get the data below:
new_df['mark'].value_counts()
1 1349110
2 1606640
3 175629
4 790062
5 330978
How can I get the percentage for each row like this?
1 1349110 31.7%
2 1606640 37.8%
3 175629 4.1%
4 790062 18.6%
5 330978 7.8%
I need to divide each row by the sum of these data.
A: np.random.seed([3,1415])
s = pd.Series(np.random.choice(list('ABCDEFGHIJ'), 1000, p=np.arange(1, 11) / 55.))
s.value_counts()
I 176
J 167
H 136
F 128
G 111
E 85
D 83
C 52
B 38
A 24
dtype: int64
As percent
s.value_counts(normalize=True)
I 0.176
J 0.167
H 0.136
F 0.128
G 0.111
E 0.085
D 0.083
C 0.052
B 0.038
A 0.024
dtype: float64
counts = s.value_counts()
percent = counts / counts.sum()
fmt = '{:.1%}'.format
pd.DataFrame({'counts': counts, 'per': percent.map(fmt)})
counts per
I 176 17.6%
J 167 16.7%
H 136 13.6%
F 128 12.8%
G 111 11.1%
E 85 8.5%
D 83 8.3%
C 52 5.2%
B 38 3.8%
A 24 2.4%
A: I think you need:
#if output is Series, convert it to DataFrame
df = df.rename('a').to_frame()
df['per'] = (df.a * 100 / df.a.sum()).round(1).astype(str) + '%'
print (df)
a per
1 1349110 31.7%
2 1606640 37.8%
3 175629 4.1%
4 790062 18.6%
5 330978 7.8%
Timings:
It seems faster is use sum as twice value_counts:
In [184]: %timeit (jez(s))
10 loops, best of 3: 38.9 ms per loop
In [185]: %timeit (pir(s))
10 loops, best of 3: 76 ms per loop
Code for timings:
np.random.seed([3,1415])
s = pd.Series(np.random.choice(list('ABCDEFGHIJ'), 1000, p=np.arange(1, 11) / 55.))
s = pd.concat([s]*1000)#.reset_index(drop=True)
def jez(s):
df = s.value_counts()
df = df.rename('a').to_frame()
df['per'] = (df.a * 100 / df.a.sum()).round(1).astype(str) + '%'
return df
def pir(s):
return pd.DataFrame({'a':s.value_counts(),
'per':s.value_counts(normalize=True).mul(100).round(1).astype(str) + '%'})
print (jez(s))
print (pir(s))
A: Here's a more pythonic snippet than what is proposed above I think
def aspercent(column,decimals=2):
assert decimals >= 0
return (round(column*100,decimals).astype(str) + "%")
aspercent(df['mark'].value_counts(normalize=True),decimals=1)
This will output:
1 1349110 31.7%
2 1606640 37.8%
3 175629 4.1%
4 790062 18.6%
5 330978 7.8%
This also allows to adjust the number of decimals
A: Create two series, first one with absolute values and a second one with percentages, and concatenate them:
import pandas
d = {'mark': ['pos', 'pos', 'pos', 'pos', 'pos',
'neg', 'neg', 'neg', 'neg',
'neutral', 'neutral' ]}
df = pd.DataFrame(d)
absolute = df['mark'].value_counts(normalize=False)
absolute.name = 'value'
percentage = df['mark'].value_counts(normalize=True)
percentage.name = '%'
percentage = (percentage*100).round(2)
pd.concat([absolute, percentage], axis=1)
Output:
value %
pos 5 45.45
neg 4 36.36
neutral 2 18.18
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39243649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to create Windows Server Failover Cluster using Terraform Hoping someone is able to assist with being able to create / automate a Windows Server Failover Cluster, on Windows Server 2019 DataCenter Edition VM/s (without SQL installed, and not on SQL Managed Instances) using Terraform, in Azure.
There does not appear to be a way to have this process automated. All instructions are either to create WSFC manually in Windows (add Features, format disks etc etc), or using PowerShell. I'm happy with PowerShell, but have been unable to build one script that can create the cluster that can be injected using Terraform Custom Script Extension. I have got an unattended Azure DevOps pipeline deploying the Windows 2019 VMs (and disks etc), adding them to the corporate domain, but just unable to create the WSFC, since creating the cluster requires domain credentials, and yet the pipeline runs with SYSTEM credentials, and Microsoft prohibits impersonating a domain user from a script running as SYSTEM account.
Note1:- SQL will be installed after the WSFC exists (using a Terraform CSE to run a PowerShell script)
Note2:- this is not on SQL Managed Instances. Purely IaaS VMs
Any assistance/guidance would be appreciated. Thank you
(Using: Terraform >=1.1.0, AzureRM Provider >=3.0.0)
A:
The azurerm_sql_failover_group resource is deprecated in version 3.0 of the AzureRM provider and will be removed in version 4.0. Please use the azurerm_mssql_failover_group resource instead.
*
*Here is the Sample code of SQL Fail over group using Terraform.
resource "azurerm_resource_group" "example" {
name = "example-resources"
location = "West Europe"
}
resource "azurerm_sql_server" "primary" {
name = "sql-primary"
resource_group_name = azurerm_resource_group.example.name
location = azurerm_resource_group.example.location
version = "12.0"
administrator_login = "sqladmin"
administrator_login_password = "pa$$w0rd"
}
resource "azurerm_sql_server" "secondary" {
name = "sql-secondary"
resource_group_name = azurerm_resource_group.example.name
location = "northeurope"
version = "12.0"
administrator_login = "sqladmin"
administrator_login_password = "pa$$w0rd"
}
resource "azurerm_sql_database" "db1" {
name = "db1"
resource_group_name = azurerm_sql_server.primary.resource_group_name
location = azurerm_sql_server.primary.location
server_name = azurerm_sql_server.primary.name
}
resource "azurerm_sql_failover_group" "example" {
name = "example-failover-group"
resource_group_name = azurerm_sql_server.primary.resource_group_name
server_name = azurerm_sql_server.primary.name
databases = [azurerm_sql_database.db1.id]
partner_servers {
id = azurerm_sql_server.secondary.id
}
read_write_endpoint_failover_policy {
mode = "Automatic"
grace_minutes = 60
}
}
*
*You can go through this reference for complete information.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72099016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: first time in phpMyAdmin, error #1064 pops up this is my first time using phpMyAdmin and I was trying to import a sample database when this line of text happened,
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use
near 'source load_departments.dump' at line 1
as I went and checked the error it was in this line
SELECT 'LOADING departments' as 'INFO';
source load_departments.dump ;
how do I fix this?
A: I believe you aren't able to SOURCE — that is, import other arbitrary files — from within phpMyAdmin. You could use the MySQL command line client or rename load_departments.dump to load_departments.sql and import that file through the phpMyAdmin interface manually.
If I recall correctly, the source command is a construct of the MySQL command line client and isn't actually a valid SQL command.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74105142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: angularJs filter nested object Track by I created a custom filter, but its giving me an error
I created a fiddle here:
Fiddle
I have this user data:
data: [{
profile: {
firstName: 'John',
lastName: 'OConner'
}
}, {
profile: {
firstName: 'Smith',
lastName: 'OConner'
}
}, {
profile: {
firstName: 'James',
lastName: 'Bond'
}
}]
And I need to filter by the nested obj - profile by this
data: [{
column: {
label: 'firstName',
}
}, {
column: {
label: 'lastName',
}
}]
I can filter but is giving me this error:
this is my filter:
myApp.filter('testFilter', ['$filter',
function($filter) {
return function(items, selectedFilter) {
var returnArray = items;
var filtered = [];
var process = {};
process.filtered = [];
process.loop = function(obj, key) {
var filtered = [];
this.obj = obj;
this.key = key;
// console.log('obj--> ', obj);
// console.log('key--> ', key);
filtered = filtered.concat($filter('filter')(items, process.superFilter));
if (filtered.length > 0) {
process.filtered = filtered;
}
};
process.superFilter = function(value) {
var returnMe;
var originalValue = value.profile[process.key];
if (typeof(value) === 'String') {
originalValue = originalValue.toLowerCase();
}
if (originalValue === process.obj) {
console.log('found');
returnMe = value;
return returnMe;
}
};
if (Object.getOwnPropertyNames(selectedFilter).length !== 0) {
angular.forEach(selectedFilter, function(obj) {
filtered = filtered.concat($filter('filter')(items, obj));
});
returnArray = filtered;
// console.log('selectedFilter ', selectedFilter);
}
return returnArray;
};
}
]);
Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. How can I solve this issue?
A: You need to use track by as the error suggests. If you don't have a unique key to use you can use $index.
ng-repeat='talent in talents.data | testFilter:filterInput track by $index'
Here is a working example with your code: http://jsfiddle.net/hwT4P/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25044228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how to intersect a list and a dataframe in pandas? I have a list that looks like this:
set(['loc. 08652', 'loc. 14331', 'loc. 08650', 'loc.06045', 'loc.10160', 'loc. 08656']
I have a data frame that looks like this:
lung heart kidney
asx1.1_ox1.0.loc.08652 32.406993 51.709692 15.883315
asx1.1_ox1.0.loc.14331 5.255465 86.048540 8.695995
asx1.1_ox1.0.loc.12124 34.730648 39.070967 26.198384
asx1.1_ox1.0.loc.06045 50.992902 28.701922 20.305177
asx1.1_ox1.0.loc.10160 27.619962 63.702141 8.677896
asx1.1_ox1.0.loc.20210 45.148668 43.700587 11.150744
How can I conveniently produce intersect the two files, and output a data frame like that below:
lung heart kidney
asx1.1_ox1.0.loc.08652 32.406993 51.709692 15.883315
asx1.1_ox1.0.loc.14331 5.255465 86.048540 8.695995
asx1.1_ox1.0.loc.06045 50.992902 28.701922 20.305177
asx1.1_ox1.0.loc.10160 27.619962 63.702141 8.677896
A: You can clean your index, i.e. remove extra strings before loc, and then use isin method as suggested by @not_a_robot:
s = set(['loc.08652', 'loc.14331', 'loc.08650', 'loc.06045', 'loc.10160', 'loc. 08656']
# the set has been cleaned here so that it doesn't contain spaces
df[df.index.str.replace(".*(?=loc)", "").isin(s)]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41744060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Auth::user Trying to get property of non-object I'm using laravel 5.3 and using Multi-Auth Hesto Package.
I used view composers to pass my current Auth::user to Welcome.blade
I already logged in my Customer/Home.blade but when I go to Welcome.blade and accessing the current Auth::useran error says "Trying to get property of non-object"
Here's my Viewmcomposers/AuthComposer.php
class AuthComposer
{
public $currentUser;
public function __construct()
{
$this->currentUser = Auth::User();
View::share([ 'currentUser' => $this->currentUser ]);
}
public function compose(View $view)
{
$view->with('currentUser', Auth::user()->name);
}
}
App/Providers/ComposerServiceProvider.php
public function boot()
{
view()->composer('welcome', function ($view)
{
$currentUser = Customer::where('name', Auth::user()->name);
$view->with('welcome', $currentUser );
});
}
Config/App.php
App\Providers\ComposerServiceProvider::class,
My routes for customer
Route::get('/home', function () {
$users[] = Auth::user();
$users[] = Auth::guard()->user();
$users[] = Auth::guard('customer')->user();
return view('customer.home');
})->name('home');
And I just call this in my routes/web.php for my welcome.blade
Route::get('/', 'WelcomeController@showWelcome');
A: Use Auth;
in top of page it may help you.
Show me complete error .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41497940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to deserialize child nodes of xml file I've created an app using Xamarin Android. Plan is for it to open a read-only copy of Clients.xml from the Assets folder and create a copy in internal storage for future editing. The default file has a root node of clients and half a dozen child nodes of client.
I've got it to the point where it reads the asset and creates a local file but only with the first child node in it. I can't quite get it to an array of child nodes.
What do I need to do to read all the child nodes?
Reading of the asset and creating a local file.
// Get storage path
path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
// Create clients file on first build
string filename = System.IO.Path.Combine(path, "Clients.xml");
if (!File.Exists(filename))
{
clients clients;
// Load read-only asset from file
var xmlSerialSettings = new XmlSerializer(typeof(clients));
using (StreamReader sr = new StreamReader(Android.App.Application.Context.Assets.Open("Clients.xml"), true))
{
clients = (clients)xmlSerialSettings.Deserialize(sr);
}
// Save local version to edit
var xsw = new XmlSerializer(typeof(clients));
using (StreamWriter sw = new StreamWriter(filename, false))
{
xsw.Serialize(sw, clients);
}
}
Clients.xml
<?xml version="1.0" encoding="utf-8" ?>
<clients>
<client id="1">
<name>Bob</name>
<address>Home</address>
<postcode>CO1</postcode>
<email>[email protected]</email>
<landline></landline>
<mobile>07784</mobile>
</client>
<client id="2">
<name>...</name>
<address>...</address>
<postcode>...</postcode>
<email>...</email>
<landline>...</landline>
<mobile>...</mobile>
</client>
....
</clients>
Clients.cs
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace QuoteBuilder
{
[Serializable, XmlRoot("clients")]
public class clients
{
[XmlElement("client")]
public client client { get; set; }
public clients()
{
}
public clients(client client)
{
this.client = client;
}
}
public class client
{
public string name { get; set; }
public string address { get; set; }
public string postcode { get; set; }
public string email { get; set; }
public string landline { get; set; }
public string mobile { get; set; }
public client()
{
}
public client(string name, string address, string postcode, string email, string landline, string mobile)
{
this.name = name;
this.address = address;
this.postcode = postcode;
this.email = email;
this.landline = landline;
this.mobile = mobile;
}
}
}
A: Inside your clients class you defined a member - client. It is not a collection, and when you deserialize xml file to clients class it deserialize only one node (first).
Use List or other collections inside:
[Serializable, XmlRoot("clients")]
public class Clients
{
[XmlElement("client")]
public List<Client> client { get; set; } // Collection
public Clients()
{
}
public Clients(List<Client> client)
{
this.client = client;
}
}
Also use CamelCase naming for classes, and lowerCase naming for variables - it is more readable
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67252714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: oAuth 1.0 Authentication using Karate Framework I see no examples or documentation available in karate framework for 0auth 1.0 authentication testing.
I am providing authorization details in the header as following and facing issues.
Given url 'https://api.twitter.com/1.1/statuses/update.json'
And header Content-Type = 'application/json'
And header Authorization = 'OAuth oauth_consumer_key="********",oauth_consumer_Secret="**********",oauth_token="********",oauth_token_secret="*********"'
And form field status = 'I am tweeting using karate'
When method post
Then status 201
A: There was one added recently: commit
The meat is in the Java code:
package demo.oauth;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static org.apache.commons.codec.digest.DigestUtils.md5Hex;
import static org.apache.commons.codec.digest.DigestUtils.sha256Hex;
public class Signer {
public static void sign(String token, Map<String, String> params) {
List<String> list = new ArrayList();
String tokenClientSlat = "";
for (String key : params.keySet()) {
if (key.equals("token_client_salt")) {
tokenClientSlat = params.get(key);
}
String paramString = key + "=" + params.get(key);
list.add(paramString);
}
Collections.sort(list);
StringBuilder sb = new StringBuilder();
for (String s : list) {
sb.append(s);
}
sb.append(token);
String sig = md5Hex(sb.toString());
String tokenSig = sha256Hex(sig + tokenClientSlat);
params.put("sig", sig);
params.put("__NStokensig", tokenSig);
}
}
And then the feature:
* def Signer = Java.type('demo.oauth.Signer')
* def params =
"""
{
'userId': '399645532',
'os':'android',
'client_key': '3c2cd3f3',
'token': '141a649988c946ae9b5356049c316c5d-838424771',
'token_client_salt': 'd340a54c43d5642e21289f7ede858995'
}
"""
* eval Signer.sign('382700b563f4', params)
* path 'echo'
* form fields params
* method post
* status 200
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52824283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: In Rails 4 Guard is not updating the test count I just upgraded to Guard 2 and it is is telling me there are 7 examples and 7 failures.
Here's the spec file i'm working on:
# == Schema Information
#
# Table name: awardunits
#
# id :integer not null, primary key
# nyaaid :string(255)
# name :string(255)
# address :string(255)
# district :string(255)
# contact :string(255)
# email :string(255)
# insthead :string(255)
# instheadcontact :string(255)
# datestarted :date
# allowedmem :integer
# remarks :text
# disabled :boolean
# created_at :datetime
# updated_at :datetime
#
require 'spec_helper'
describe Awardunit do
before { @awardunit = Awardunit.new(nyaaid: "NYAA/N/WP0001", name: "Test Unit", address: "No. 50, Kalpitiya Road, Maradana", district: "Colombo", contact: "23232223", email: "[email protected]", insthead: "Namal Kaluaarachchi", instheadcontact: "324234234", datestarted: "1/10/2013", allowedmem: "5", remarks: "" ) }
it { should respond_to(:nyaaid) }
it { should respond_to(:name) }
it { should respond_to(:address) }
it { should respond_to(:district) }
it { should respond_to(:contact) }
it { should respond_to(:email) }
it { should respond_to(:insthead) }
it { should respond_to(:instheadcontact) }
it { should respond_to(:datestarted) }
it { should respond_to(:allowedmem) }
it { should respond_to(:remarks) }
it { should respond_to(:disabled) }
it { should be_valid }
describe "when nyaaid is not present" do
before { @awardunit.nyaaid = " " }
it { should_not be_valid }
end
describe "when name is not present" do
before { @awardunit.name = " " }
it { should_not be_valid }
end
describe "when district is not present" do
before { @awardunit.district = " " }
it { should_not be_valid }
end
describe "when contact is not present" do
before { @awardunit.contact = " " }
it { should_not be_valid }
end
describe "when datestarted is not present" do
before { @awardunit.datestarted = " " }
it { should_not be_valid }
end
describe "when email format is invalid" do
it "should be invalid" do
addresses = %w[user@foo,com user_at_foo.org example.user@foo. foo@bar_baz.com foo@bar+baz.com]
addresses.each do |invalid_address|
@authentication.email = invalid_address
expect(@authentication.save).to be_false
end
end
end
describe "when email format is valid" do
it "should be valid" do
addresses = %w[[email protected] [email protected] [email protected] [email protected]]
addresses.each do |valid_address|
@authentication.email = valid_address
expect(@authentication.save).to be_true
end
end
end
end
Its not including the top tests into the 7 examples! One problem, When I add a new describe block to a spec file and save, normally the count should go to 8 examples. But guard is still showing 7! If I go to a different spec file and save it, guard still say 7 examples and 7 failures according to the old file! How can I fix this issue?
Guardfile :
require 'active_support/inflector'
notification :libnotify
guard :rspec, notification: true, all_on_start: true, cmd: 'spring rspec' do
watch(%r{^spec/.+_spec\.rb$})
watch(%r{^lib/(.+)\.rb$}) { |m| "spec/lib/#{m[1]}_spec.rb" }
watch('spec/spec_helper.rb') { "spec" }
# Rails example
watch(%r{^app/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
watch(%r{^app/(.*)(\.erb|\.haml|\.slim)$}) { |m| "spec/#{m[1]}#{m[2]}_spec.rb" }
watch(%r{^app/controllers/(.+)_(controller)\.rb$}) { |m| ["spec/routing/#{m[1]}_routing_spec.rb", "spec/#{m[2]}s/#{m[1]}_#{m[2]}_spec.rb", "spec/acceptance/#{m[1]}_spec.rb"] }
watch(%r{^spec/support/(.+)\.rb$}) { "spec" }
watch('config/routes.rb') { "spec/routing" }
watch('app/controllers/application_controller.rb') { "spec/controllers" }
# Capybara features specs
watch(%r{^app/views/(.+)/.*\.(erb|haml|slim)$}) { |m| "spec/features/#{m[1]}_spec.rb" }
# Turnip features and steps
watch(%r{^spec/acceptance/(.+)\.feature$})
watch(%r{^spec/acceptance/steps/(.+)_steps\.rb$}) { |m| Dir[File.join("**/#{m[1]}.feature")][0] || 'spec/acceptance' }
# Custom Rails Tutorial specs
watch(%r{^app/controllers/(.+)_(controller)\.rb$}) do |m|
["spec/routing/#{m[1]}_routing_spec.rb",
"spec/#{m[2]}s/#{m[1]}_#{m[2]}_spec.rb",
"spec/acceptance/#{m[1]}_spec.rb",
(m[1][/_pages/] ? "spec/requests/#{m[1]}_spec.rb" :
"spec/requests/#{m[1].singularize}_pages_spec.rb")]
end
watch(%r{^app/views/(.+)/}) do |m|
(m[1][/_pages/] ? "spec/requests/#{m[1]}_spec.rb" :
"spec/requests/#{m[1].singularize}_pages_spec.rb")
end
watch(%r{^app/controllers/sessions_controller\.rb$}) do |m|
"spec/requests/authentication_pages_spec.rb"
end
end
Gemfile.lock :
GEM
remote: https://rubygems.org/
specs:
actionmailer (4.0.0)
actionpack (= 4.0.0)
mail (~> 2.5.3)
actionpack (4.0.0)
activesupport (= 4.0.0)
builder (~> 3.1.0)
erubis (~> 2.7.0)
rack (~> 1.5.2)
rack-test (~> 0.6.2)
activemodel (4.0.0)
activesupport (= 4.0.0)
builder (~> 3.1.0)
activerecord (4.0.0)
activemodel (= 4.0.0)
activerecord-deprecated_finders (~> 1.0.2)
activesupport (= 4.0.0)
arel (~> 4.0.0)
activerecord-deprecated_finders (1.0.3)
activesupport (4.0.0)
i18n (~> 0.6, >= 0.6.4)
minitest (~> 4.2)
multi_json (~> 1.3)
thread_safe (~> 0.1)
tzinfo (~> 0.3.37)
annotate (2.5.0)
rake
arel (4.0.1)
atomic (1.1.14)
bcrypt-ruby (3.0.1)
better_errors (1.0.1)
coderay (>= 1.0.0)
erubis (>= 2.6.6)
binding_of_caller (0.7.2)
debug_inspector (>= 0.0.1)
bootstrap-sass (2.3.2.2)
sass (~> 3.2)
builder (3.1.4)
capybara (2.1.0)
mime-types (>= 1.16)
nokogiri (>= 1.3.3)
rack (>= 1.0.0)
rack-test (>= 0.5.4)
xpath (~> 2.0)
celluloid (0.15.2)
timers (~> 1.1.0)
childprocess (0.3.9)
ffi (~> 1.0, >= 1.0.11)
coderay (1.0.9)
coffee-rails (4.0.1)
coffee-script (>= 2.2.0)
railties (>= 4.0.0, < 5.0)
coffee-script (2.2.0)
coffee-script-source
execjs
coffee-script-source (1.6.3)
debug_inspector (0.0.2)
diff-lcs (1.2.4)
erubis (2.7.0)
execjs (2.0.2)
factory_girl (4.2.0)
activesupport (>= 3.0.0)
factory_girl_rails (4.2.1)
factory_girl (~> 4.2.0)
railties (>= 3.0.0)
faker (1.2.0)
i18n (~> 0.5)
ffi (1.9.0)
font-awesome-rails (4.0.0.0)
railties (>= 3.2, < 5.0)
formatador (0.2.4)
guard (2.1.1)
formatador (>= 0.2.4)
listen (~> 2.1)
lumberjack (~> 1.0)
pry (>= 0.9.12)
thor (>= 0.18.1)
guard-rspec (4.0.3)
guard (>= 2.1.1)
rspec (~> 2.14)
hike (1.2.3)
i18n (0.6.5)
jbuilder (1.5.2)
activesupport (>= 3.0.0)
multi_json (>= 1.2.0)
jquery-rails (3.0.4)
railties (>= 3.0, < 5.0)
thor (>= 0.14, < 2.0)
json (1.8.1)
libnotify (0.8.2)
ffi (>= 1.0.11)
listen (2.1.1)
celluloid (>= 0.15.2)
rb-fsevent (>= 0.9.3)
rb-inotify (>= 0.9)
lumberjack (1.0.4)
mail (2.5.4)
mime-types (~> 1.16)
treetop (~> 1.4.8)
method_source (0.8.2)
mime-types (1.25)
mini_portile (0.5.2)
minitest (4.7.5)
modernizr-rails (2.6.2.3)
multi_json (1.8.2)
nokogiri (1.6.0)
mini_portile (~> 0.5.0)
pg (0.17.0)
polyglot (0.3.3)
pry (0.9.12.2)
coderay (~> 1.0.5)
method_source (~> 0.8)
slop (~> 3.4)
rack (1.5.2)
rack-test (0.6.2)
rack (>= 1.0)
rails (4.0.0)
actionmailer (= 4.0.0)
actionpack (= 4.0.0)
activerecord (= 4.0.0)
activesupport (= 4.0.0)
bundler (>= 1.3.0, < 2.0)
railties (= 4.0.0)
sprockets-rails (~> 2.0.0)
rails_12factor (0.0.2)
rails_serve_static_assets
rails_stdout_logging
rails_serve_static_assets (0.0.1)
rails_stdout_logging (0.0.3)
railties (4.0.0)
actionpack (= 4.0.0)
activesupport (= 4.0.0)
rake (>= 0.8.7)
thor (>= 0.18.1, < 2.0)
rake (10.1.0)
rb-fsevent (0.9.3)
rb-inotify (0.9.2)
ffi (>= 0.5.0)
rdoc (3.12.2)
json (~> 1.4)
rspec (2.14.1)
rspec-core (~> 2.14.0)
rspec-expectations (~> 2.14.0)
rspec-mocks (~> 2.14.0)
rspec-core (2.14.6)
rspec-expectations (2.14.3)
diff-lcs (>= 1.1.3, < 2.0)
rspec-mocks (2.14.4)
rspec-rails (2.14.0)
actionpack (>= 3.0)
activesupport (>= 3.0)
railties (>= 3.0)
rspec-core (~> 2.14.0)
rspec-expectations (~> 2.14.0)
rspec-mocks (~> 2.14.0)
sass (3.2.12)
sass-rails (4.0.1)
railties (>= 4.0.0, < 5.0)
sass (>= 3.1.10)
sprockets-rails (~> 2.0.0)
sdoc (0.3.20)
json (>= 1.1.3)
rdoc (~> 3.10)
slop (3.4.6)
spring (0.0.11)
sprockets (2.10.0)
hike (~> 1.2)
multi_json (~> 1.0)
rack (~> 1.0)
tilt (~> 1.1, != 1.3.0)
sprockets-rails (2.0.1)
actionpack (>= 3.0)
activesupport (>= 3.0)
sprockets (~> 2.8)
thor (0.18.1)
thread_safe (0.1.3)
atomic
tilt (1.4.1)
timers (1.1.0)
treetop (1.4.15)
polyglot
polyglot (>= 0.3.1)
turbolinks (1.3.0)
coffee-rails
tzinfo (0.3.38)
uglifier (2.2.1)
execjs (>= 0.3.0)
multi_json (~> 1.0, >= 1.0.2)
xpath (2.0.0)
nokogiri (~> 1.3)
PLATFORMS
ruby
DEPENDENCIES
annotate
bcrypt-ruby (~> 3.0.0)
better_errors
binding_of_caller
bootstrap-sass
capybara
childprocess
coffee-rails (~> 4.0.0)
factory_girl_rails
faker
font-awesome-rails
guard (~> 2.1.1)
guard-rspec (~> 4.0.3)
jbuilder (~> 1.2)
jquery-rails
libnotify
modernizr-rails
pg
rails (= 4.0.0)
rails_12factor
rb-inotify
rspec (~> 2.14.0)
rspec-rails
sass-rails (~> 4.0.0)
sdoc
spring
turbolinks
uglifier (>= 1.3.0)
A: The problem is, Guard is adding focus_on_failed: true by default. In the Guard file, you have to add focus_on_failed: false. Here's how it will look like :
guard :rspec, notification: true, all_on_start: true, focus_on_failed: false, cmd: 'spring rspec' do
Solution : https://github.com/guard/guard/issues/511
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19616145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Wix deployment with oracle dlls I'm very new with .net applications and I'm trying to deploy a winforms app to many machines (32 and 64 bits) without having to install oracle client in each one.
I'm using oracle 11g with Oracle.DataAccess.dll.
I created two wix projects in my solution (setup and bootstrapper).
My solution has another 4 projects: MyMainForm project, MyService project, MyDAO project and MyDataModel project.
In MyDAO project I have a reference to Oracle.DataAccess.dll.
First question:
Where should I put the Oracle.DataAccess.dll file in my solution to add the reference?
I put in bin\Release folder of MyMainForm project.
Along with oci.dll, oramts.dll, oramts11.dll, orannzsbb11.dll, oraocci11.dll, oraociei11.dll and OraOps11w.dll files.
It worked on my machine but I not sure if this is the right place to put them.
Second question:
When I install it on my machine (64 bits) works. But when I install on another machine (also 64 bits) it did not work.
I received the following error:
System.IO.FileNotFoundException was unhandled Message: An unhandled
exception of type 'System.IO.FileNotFoundException' occurred in
MyService.dll Additional information: Could not load file or assembly
'Oracle.DataAccess, Version=4.112.3.0, Culture=neutral,
PublicKeyToken=89b483f429c47342' or one of its dependencies. The
system cannot find the file specified.
I believe this is releated to the first question. Maybe the file is in the wrong place.
Third question:
I read about Oracle.ManagedDataAccess.dll. For what I read I would use only this dll and not all others dlls and I should not worried about 32/64 bits.
But could I use it with oracle 11g?
I read a lot of things about it on foruns but did not find a good tutorial or similar to make this work.
I being struggling with this for about 3 days now.
Any help would be appreciated.
A: I fix it, but I'm not sure what was the exact error.
Three things I did:
1 - Two of the six projects were configured to "Any CPU" and the others to "x86", I change the ones with "Any CPU" to "x86" (can't remember which ones were, I believe it was MyService project and MyDAO project, but not sure).
2 - In the .csproj file of MyDAO project, the oracle reference was like this:
<Reference Include="Oracle.DataAccess, Version=2.112.3.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=x86" />
<SpecificVersion>False</SpecificVersion>
<HintPath>..\MyMainForm\bin\Release\Oracle.DataAccess.dll</HintPath>
</Reference>
But the .dll file version I'm using is 4.112.3.0, so I change it to:
<Reference Include="Oracle.DataAccess />
<SpecificVersion>False</SpecificVersion>
<Private>False</Private>
<HintPath>..\MyMainForm\bin\Release\Oracle.DataAccess.dll</HintPath>
</Reference>
3 - I change my Product.wxs to include the oracle dlls, like this:
<!-- Oracle libraries -->
<Component Guid="*">
<File Source="$(var.MyMainForm.TargetDir)\Oracle.DataAccess.dll" KeyPath="yes" />
</Component>
<Component Guid="*">
<File Source="$(var.MyMainForm.TargetDir)\oci.dll" KeyPath="yes" />
</Component>
<Component Guid="*">
<File Source="$(var.MyMainForm.TargetDir)\oramts.dll" KeyPath="yes" />
</Component>
<Component Guid="*">
<File Source="$(var.MyMainForm.TargetDir)\oramts11.dll" KeyPath="yes" />
</Component>
<Component Guid="*">
<File Source="$(var.MyMainForm.TargetDir)\orannzsbb11.dll" KeyPath="yes" />
</Component>
<Component Guid="*">
<File Source="$(var.MyMainForm.TargetDir)\oraocci11.dll" KeyPath="yes" />
</Component>
<Component Guid="*">
<File Source="$(var.MyMainForm.TargetDir)\oraociei11.dll" KeyPath="yes" />
</Component>
<Component Guid="*">
<File Source="$(var.MyMainForm.TargetDir)\OraOps11w.dll" KeyPath="yes" />
</Component>
This way I don't have to install Oracle Client on each machine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33921063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: File Chooser inside DialogFragment (re-using code) In this tutorial : http://www.dreamincode.net/forums/topic/190013-creating-simple-file-chooser/
they are using a class that extends ListActivity, they show the results thanks to the next sentence: this.setListAdapter(adapter); ( whith a custom FileArrayAdapter) but I cant use it because I want to show the file chooser inside a DialogFragment (extends DialogFragment).
I appreciate any help or explanation of how I should proceed, thanks in advance.
Here is my code:
DialogFragment:
public class Dialogo extends DialogFragment {
private File currentDir;
private FileArrayAdapter adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_browser, container);
Context c = getActivity();
currentDir = c.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
Toast.makeText(c, "Current Dir: "+currentDir.getName(), Toast.LENGTH_SHORT).show();
fill(currentDir);
Button button = (Button)view.findViewById(R.id.Btnparavolver);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
getDialog().dismiss();
}
});
return view;
} //oncreateview
private void fill(File f)
{
File[]dirs = f.listFiles();
getDialog().setTitle("Directorio actual: "+f.getName());
List<Option>dir = new ArrayList<Option>();
List<Option>fls = new ArrayList<Option>();
try{
for(File ff: dirs)
{
if(ff.isDirectory())
dir.add(new Option(ff.getName(),"Folder",ff.getAbsolutePath()));
else
{
fls.add(new Option(ff.getName(),"File Size: "+ff.length(),ff.getAbsolutePath()));
}
}
}catch(Exception e)
{
}
Collections.sort(dir);
Collections.sort(fls);
dir.addAll(fls);
if(!f.getName().equalsIgnoreCase("sdcard"))
dir.add(0,new Option("..","Parent Directory",f.getParent()));
adapter = new FileArrayAdapter(getActivity(),R.layout.activity_browser,dir);
this.setListAdapter(adapter); <-- ERROR
}
}
here the FileArrayAdapter:
public class FileArrayAdapter extends ArrayAdapter<Option>{
private Context c;
private int id;
private List<Option>items;
public FileArrayAdapter(Context context, int textViewResourceId,
List<Option> objects) {
super(context, textViewResourceId, objects);
c = context;
id = textViewResourceId;
items = objects;
}
public Option getItem(int i)
{
return items.get(i);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(id, null);
}
final Option o = items.get(position);
if (o != null) {
TextView t1 = (TextView) v.findViewById(R.id.TextView01);
TextView t2 = (TextView) v.findViewById(R.id.TextView02);
if(t1!=null)
t1.setText(o.getName());
if(t2!=null)
t2.setText(o.getData());
}
return v;
}
}
Options.java:
public class Option implements Comparable<Option>{
private String name;
private String data;
private String path;
public Option(String n,String d,String p)
{
name = n;
data = d;
path = p;
}
public String getName()
{
return name;
}
public String getData()
{
return data;
}
public String getPath()
{
return path;
}
@Override
public int compareTo(Option o) {
if(this.name != null)
return this.name.toLowerCase().compareTo(o.getName().toLowerCase());
else
throw new IllegalArgumentException();
}
}
and activity_browser.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" android:orientation="vertical" android:layout_width="fill_parent">
<TextView android:text="@+id/TextView01"
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textStyle="bold"
android:layout_marginTop="5dip"
android:layout_marginLeft="5dip">
</TextView>
<TextView android:text="@+id/TextView02"
android:id="@+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip">
</TextView>
<Button
android:id="@+id/Btnparavolver"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#EEEEEE"
android:layout_marginTop="15dip"
android:text="@string/volver"
android:textSize="14sp"
android:textColor="#38B0DE" />
</LinearLayout>
A: Because you're not using ListFragment or ListActivity, you cannot use a built in ListView because there isn't one. In order to have access to a ListView, you must have on in your xml layout as well as instantiate it in your onCreateView() method.
The following is a quick fix to give you an idea of how you should implement:
public class Dialogo extends DialogFragment {
private File currentDir;
private FileArrayAdapter adapter;
private ListView list;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//you don't want to use the same layout as your list view!
View view = inflater.inflate(R.layout.new_layout, container);
//New stuff
list = (ListView)view.findViewById(R.id.your_list);
Context c = getActivity();
currentDir = c.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
Toast.makeText(c, "Current Dir: "+currentDir.getName(), Toast.LENGTH_SHORT).show();
fill(currentDir);
return view;
} //oncreateview
private void fill(File f)
{
File[]dirs = f.listFiles();
getDialog().setTitle("Directorio actual: "+f.getName());
List<Option>dir = new ArrayList<Option>();
List<Option>fls = new ArrayList<Option>();
try{
for(File ff: dirs)
{
if(ff.isDirectory())
dir.add(new Option(ff.getName(),"Folder",ff.getAbsolutePath()));
else
{
fls.add(new Option(ff.getName(),"File Size: "+ff.length(),ff.getAbsolutePath()));
}
}
}catch(Exception e)
{
}
Collections.sort(dir);
Collections.sort(fls);
dir.addAll(fls);
if(!f.getName().equalsIgnoreCase("sdcard"))
dir.add(0,new Option("..","Parent Directory",f.getParent()));
adapter = new FileArrayAdapter(getActivity(),R.layout.activity_browser,dir);
list.setAdapter(adapter); <--- No More Error
}
}
Here's the code for your new layout to the DialogFragment
new_layout.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_width="fill_parent">
<ListView
android:id="@+id/your_list"
android:layout_height="wrap_content"
android:layout_width="match_parent"/>
</LinearLayout>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19665123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Learning rate adjustment in tensorflow import tensorflow as tf
slim = tf.contrib.slim
def create_learning_rate(curr_step, lr_config):
base_lr = lr_config.get('base_lr', 0.1)
decay_steps = lr_config.get('decay_steps', [])
decay_rate = lr_config.get('decay_rate', 0.1)
scale_rates = [
lambda: tf.constant(decay_rate**i, dtype=tf.float32)
for i in range(len(decay_steps) + 1)
]
conds = []
prev = -1
for decay_step in decay_steps:
conds.append(tf.logical_and(curr_step > prev, curr_step <= decay_step))
prev = decay_step
conds.append(curr_step > decay_steps[-1])
learning_rate_scale = tf.case(
list(zip(conds, scale_rates)), lambda: 0.0, exclusive=True)
return learning_rate_scale * base_lr
global_step = slim.create_global_step()
train_op = tf.assign_add(global_step, 1)
lr = create_learning_rate(
global_step, {"base_lr": 0.1,
"decay_steps": [10, 20],
"decay_rate": 0.1})
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
for i in range(30):
curr_lr, step, _ = sess.run([lr, global_step, train_op])
print(curr_lr, step)
I want to decay the learning rate at certain times. However, it is always 0.001. Any ideas? Or is there a better method to adjust learning rate?
Thanks for your help.
A: It is because lambda function captures variable by reference instead of value.
So the correct manner is
def create_learning_rate(global_step, lr_config):
base_lr = lr_config.get('base_lr', 0.1)
decay_steps = lr_config.get('decay_steps', [])
decay_rate = lr_config.get('decay_rate', 0.1)
prev = -1
scale_rate = 1.0
cases = []
for decay_step in decay_steps:
cases.append((tf.logical_and(global_step > prev,
global_step <= decay_step),
lambda v=scale_rate: v))
scale_rate *= decay_rate
prev = decay_step
cases.append((global_step > decay_step, lambda v=scale_rate: v))
learning_rate_scale = tf.case(cases, lambda: 0.0, exclusive=True)
return learning_rate_scale * base_lr
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46100786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JS counter continuously updating How to implement a live and persistent number counter on a site
So I was looking at this question (^) and I want to do the exact same thing except a little different.
I need one of these that counts up 15.8 cents per second from the numb $138,276,343
Preferably I would like to have the commas like a normal dollar amount.
Any way I could get this working? I'm stumped. Like the poster of the above question, I don't have much JS knowledge.
A: This took me quite a long time to answer since I had to create my own format currency function.
A live demo can be found here: http://jsfiddle.net/dm6LL/
The basic updating each second is very easy and will be done through JavaScript's setInterval command.
setInterval(function(){
current += .158;
update();
},1000);
The update() function you see in the above code is just a simple updater referencing an object with the amount id to put the formatted current amount into a div on the page.
function update() {
amount.innerText = formatMoney(current);
}
Amount and current that you see in the update() function are predefined:
var amount = document.getElementById('amount');
var current = 138276343;
Then all that's left is my formatMoney() function which takes a number and converts it into a currency string.
function formatMoney(amount) {
var dollars = Math.floor(amount).toString().split('');
var cents = (Math.round((amount%1)*100)/100).toString().split('.')[1];
if(typeof cents == 'undefined'){
cents = '00';
}else if(cents.length == 1){
cents = cents + '0';
}
var str = '';
for(i=dollars.length-1; i>=0; i--){
str += dollars.splice(0,1);
if(i%3 == 0 && i != 0) str += ',';
}
return '$' + str + '.' + cents;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11965561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: C++ Template Singletons in a dll In dll A I have a template singleton:
template <class T>
class Singleton
{
public:
static T &instance()
{
static T _instance;
return _instance;
}
private:
//All constructors are here
};
In Dll B I define a class Logger. Dlls C,D and E use the Logger and it is accessed like this:
Singleton<Logger>::instance();
The problem is that each dll instantiates its own copy of
Singleton<Logger>.
instead of using the same singleton instance. I understand that the solution to this problem is using extern templates. That is dlls C,D and E have to include
extern template class Singleton<Logger>;
and dll B must include:
template class Singleton<Logger>;
This still cause more than one template instance to be created. I tried putting the extern in all the dlls and it still didn't work I tried removing the extern from all the dlls and it still didn't work. Is this not the standard way to implement template singletons? What is the correct way to do this?
A: The "correct" way to do this is...not to use a singleton.
If you want all other code to use the same instance of some type, then give that code a reference to that instance - as a parameter to a function or a constructor.
Using a singleton (non-template) would be exactly the same as using a global variable, a practice you should avoid.
Using a template means the compiler decides how to instantiate the code, and how to access the "instance". The problem you're experiencing is a combination of this and using a static in a DLL.
There are many reasons why singletons are bad, including lifetime issues (when, exactly, would it be safe to delete a singleton?), thread-safety issues, global shared access issues and more.
In summary, if you only want one instance of a thing, only create one instance of it, and pass it around to code that needs it.
A: The trick that works for me is to add __declspec(dllexport) to the singleton's template definition; split the template implementation from the class definition and only include the implementation in the A DLL; and finally, force the template to be instantiated in the A DLL by creating a dummy function that calls Singleton<Logger>::instance().
So in your A DLL's header file, you define the Singleton template like this:
template <class T>
class __declspec(dllexport) Singleton {
public:
static T &instance();
};
Then in your A DLL's cpp file you define the template implementation, and force an instantiation of Singleton<Logger> like this:
template <class T>
T &Singleton<T>::instance() {
static T _instance;
return _instance;
};
void instantiate_logger() {
Singleton<Logger>::instance();
}
With my compiler at least, I don't need to call instantiate_logger from anywhere. Just having it exist forces the code to be generated. So if you dump the A DLL's export table at this point, you should see an entry for Singleton<Logger>::instance().
Now in your C DLL and D DLL, you can include the header file with the template definition for Singleton, but because there is no template implementation, the compiler won't be able to create any code for that template. This means the linker will end up complaining about unresolved externals for Singleton<Logger>::instance(), but you just have to link in the A DLL's export library to fix that.
The bottom line is that the code for Singleton<Logger>::instance() is only ever implemented in DLL A, so you can never have more than one instance.
A: MSDN says that
Win32 DLLs are mapped into the address space of the calling process.
By default, each process using a DLL has its own instance of all the
DLLs global and static variables. If your DLL needs to share data with
other instances of it loaded by other applications, you can use either
of the following approaches:
Create named data sections using the data_seg pragma.
Use memory mapped files. See the Win32 documentation about memory mapped files.
http://msdn.microsoft.com/en-us/library/h90dkhs0%28v=vs.80%29.aspx
A: Here's a really sketchy solution that you might be able to build from. Multiple templates will be instantiated but they will all share the same instance objects.
Some additional code would be needed to avoid the memory leak (e.g. replace void * with boost::any of shared_ptr or something).
In singleton.h
#if defined(DLL_EXPORTS)
#define DLL_API __declspec(dllexport)
#else
#define DLL_API __declspec(dllimport)
#endif
template <class T>
class Singleton
{
public:
static T &instance()
{
T *instance = reinterpret_cast<T *>(details::getInstance(typeid(T)));
if (instance == NULL)
{
instance = new T();
details::setInstance(typeid(T), instance);
}
return *instance;
}
};
namespace details
{
DLL_API void setInstance(const type_info &type, void *singleton);
DLL_API void *getInstance(const type_info &type);
}
In singleton.cpp.
#include <map>
#include <string>
namespace details
{
namespace
{
std::map<std::string, void *> singletons;
}
void setInstance(const type_info &type, void *singleton)
{
singletons[type.name()] = singleton;
}
void *getInstance(const type_info &type)
{
std::map<std::string, void *>::const_iterator iter = singletons.find(type.name());
if (iter == singletons.end())
return NULL;
return iter->second;
}
}
I can't think of a better way right now. The instances have to be stored in a common location.
A: I recommend to combine a refcounted class and an exported api in your Logger class:
class Logger
{
public:
Logger()
{
nRefCount = 1;
return;
};
~Logger()
{
lpPtr = NULL;
return;
};
VOID AddRef()
{
InterLockedIncrement(&nRefCount);
return;
};
VOID Release()
{
if (InterLockedDecrement(&nRefCount) == 0)
delete this;
return;
};
static Logger* Get()
{
if (lpPtr == NULL)
{
//singleton creation lock should be here
lpPtr = new Logger();
}
return lpPtr;
};
private:
LONG volatile nRefCount;
static Logger *lpPtr = NULL;
};
__declspec(dllexport) Logger* GetLogger()
{
return Logger::Get();
};
The code needs some fixing but I try to give you the basic idea.
A: I think your problem in your implementation:
static T _instance;
I assume that static modifier causes compiler to create code in which your T class instances one for each dll.
Try different implementations of a singletone.
You can try to make static T field in Singletone class. Or maybe Singletone with static pointer inside class should work. I'd recommend you to use second approach, and in your B dll you will specify
Singletone<Logger>::instance = nullptr;
Than on first call for instance() this pointer will be initialized. And I think this will fix your problem.
PS. Don't forget manually handle mutlithreading instancing
A: Make some condition like
instance()
{
if ( _instance == NULL ) {
_instance = new Singleton();
}
return _instance;
}
This will create only single instance and when it got calls for 2nd time it will just return older instance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17614172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Delete Firebase entries onclick in a button from a insertAdjacentHTML I am trying to delete some entries in FirebaseDatabase and I am having problems. The console returns the error Uncaught SyntaxError: Invalid or unexpected token only in the first entry, and for the others returns Uncaught ReferenceError: MXcLdklS39mrnk7PQEe is not defined at HTMLButtonElement.onclick.
The code is the following:
const database = firebase.database();
var imagenBanner, count;
div = document.getElementById( 'accordion' );
database.ref(`/marketing/banners`).once('value').then(function (snap) {
count = 1;
snap.forEach(function (childSnapshot) {
console.log(childSnapshot.val().titulo)
var str =`
<div class="card">
<div class="card-header" id="heading${count}">
<h5 class="mb-0">
<button class="btn btn-link" data-toggle="collapse" data-target="#collapse${count}" aria-expanded="true" aria-controls="collapse${count}">
${childSnapshot.val().titulo}
</button>
</h5>
</div>
<div id="collapse${count}" class="collapse show" aria-labelledby="heading${count}" data-parent="#accordion">
<div class="card-body">
Introduce el banner que se mostrara al iniciar la aplicación. Especifique las imágenes y la descripción de la página.
<div style="margin: 20px 50px;">
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon1">Titulo</span>
<input id="bannerTit${childSnapshot.key}" type="text" class="form-control" placeholder="Titulo" aria-label="Titulo" aria-describedby="Titulo" value="${childSnapshot.val().titulo}">
</div>
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon1">Descripción</span>
<input id="bannerDes${childSnapshot.key}" type="text" class="form-control" placeholder="Descripción" aria-label="Descripción" aria-describedby="Descripción" value="${childSnapshot.val().descripcion}">
</div>
<div style="width:auto; margin:0 auto; text-align: center;">
<img src="${childSnapshot.val().imagen}" class="d-inline-block align-middle d-lg-none" style="max-width:100%; align-self: center; display: inline-block!important;" alt="">
</div>
<div class="custom-file" style="margin: auto; text-align: center;">
<input type="file" class="form-control" id="inputImage${childSnapshot.key}" accept="image/*">
</div>
<p style="margin: 15px 0px; text-align: end;">
<button class="btn btn-dark" id="guardarButton${childSnapshot.key}" class="btn btn-sm btn-outline-secondary" onclick="saveBanner(${childSnapshot.key})">Guardar Banner</button>
<button class="btn btn-danger" id="eliminarButton${childSnapshot.key}" class="btn btn-sm btn-outline-secondary" onclick="deleteBanner(${childSnapshot.key})">Eliminar Banner</button>
</p>
</div>
</div>
</div>
</div>
`;
div.insertAdjacentHTML( 'beforeend', str );
document.getElementById('inputImage'+childSnapshot.key).addEventListener('change', handleFileSelect, false);
++count;
});
});
var storageRef = firebase.storage().ref();
function handleFileSelect(evt) {
console.log("handleFileSelect(evt)");
evt.stopPropagation();
evt.preventDefault();
file = evt.target.files[0];
metadata = {
'contentType': file.type
};
storageRef.child('banners/' + file.name).put(file, metadata).then(function(snapshot) {
// Let's get a download URL for the file.
snapshot.ref.getDownloadURL().then(function(url) {
imagenBanner = url;
});
}).catch(function(error) {
console.error('Upload failed:', error);
});
}
function deleteBanner(banner) {
console.log(banner);
var result = confirm("Se borrara el banner de marketing. ¿Desea continuar?");
if (result) {
database.ref('/marketing/banners/' + banner).remove();
location.reload();
}
}
function saveBanner(banner) {
console.log(banner);
if (imagenBanner == null){
imagenBanner = "";
}
database.ref('/marketing/banners/' + banner).set({
titulo: document.getElementById("bannerTit"+banner).value,
descripcion: document.getElementById("bannerDes"+banner).value,
imagen: imagenBanner
});
location.reload();
}
function createBanner() {
if (imagenBanner == null){
imagenBanner = "";
}
database.ref('/marketing/banners/').push().set({
titulo: document.getElementById("bannerTitNew").value,
descripcion: document.getElementById("bannerDesNew").value,
imagen: imagenBanner
});
location.reload();
}
function newBanner() {
var str =`
<div class="card">
<div class="card-header" id="headingNew">
<h5 class="mb-0">
<button class="btn btn-link" data-toggle="collapse" data-target="#collapseNew" aria-expanded="true" aria-controls="collapseNew">
Nuevo Banner
</button>
</h5>
</div>
<div id="collapseNew" class="collapse show" aria-labelledby="headingNew" data-parent="#accordion">
<div class="card-body">
Introduce el banner que se mostrara al iniciar la aplicación. Especifique las imágenes y la descripción de la página.
<div style="margin: 20px 50px;">
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon1">Titulo</span>
<input id="bannerTitNew" type="text" class="form-control" placeholder="Titulo" aria-label="Titulo" aria-describedby="Titulo">
</div>
<div class="input-group mb-3">
<span class="input-group-text" id="basic-addon1">Descripción</span>
<input id="bannerDesNew" type="text" class="form-control" placeholder="Descripción" aria-label="Descripción" aria-describedby="Descripción">
</div>
<div class="custom-file" style="margin: auto; text-align: center;">
<input type="file" class="form-control" id="inputImageNew" accept="image/*">
</div>
<p style="margin: 15px 0px; text-align: end;">
<button class="btn btn-dark" id="guardarButtonNew" class="btn btn-sm btn-outline-secondary" onclick="createBanner()">Guardar Banner</button>
</p>
</div>
</div>
</div>
</div>
`;
div.insertAdjacentHTML( 'afterbegin', str );
document.getElementById('inputImageNew').addEventListener('change', handleFileSelect, false);
}
When I click the delete button from an entry, an alert is supposed to be opened, but nothing happens.
I have checked the ids of the buttons elements and all are correct and exists in the database.
I hope that someone can help me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66981934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Finding a subset of `n` distinct vectors with minimum distance of `d` I have a set of vectors V (say a 64 dimension vector like [1,2,...64]). From vector set V, I want to find a subset of n (n is any number > 0) distinct vectors, V1, where
*
*any two vectors in subset V1 has a minimum distance of d and also;
*for any element w in vector set V, there exists an element w' in subset V1 that can reach w with a distance that is less than d.
What would be an effective algorithm to determine one subset of n distinct vectors, where the value of n is minimum?
The distance can either be Euclidean Distance or Cosine Similarity (of course there is no mixture of both).
A: Let's think of your problem this way: You have a set of balls in 64-dimension space each with radius d, representing the space around each of your input vectors. (Note, I'm assuming that by "distance" you mean Euclidean distance).
Now, you want to find the smallest subset of balls that will cover each of your original points, meaning that you need each point to be inside at least one ball in the subset, with the additional restriction that the balls in the cover must have centers also distance d apart.
Without this additional restriction, you have an instance of a hard but well-studied one called Geometric set cover, which in turn is a special case of the more famous Set cover problem. It seems intuitively that the additional restriction makes the problem harder, but I don't have a proof for that.
The bad news is, the (geometric) set cover problem is NP-hard, meaning that you won't be able to quickly find the exact minimum if there may be many points in the original set.
The good news is, there are good algorithms that find approximate solutions, which will give you a set which isn't necessarily as small as possible, but which is close to the smallest possible.
Here is Python code for a simple greedy algorithm which will not always find a minimum-size cover, but will always return a valid one:
def greedy(V, d):
cover = set()
uncovered = set(V)
# invariant: all(distance(x,y) > d for x in cover for y in uncovered)
while uncovered:
x = uncovered.pop()
cover.add(x)
uncovered = {y for y in uncovered if distance(x,y) > d}
Note, you could make this greedy solution a little better by replacing the uncovered.pop() call with a smarter choice, for example choosing a vector which would "cover" the most number of remaining points.
A: First, we can derive an undirected graph where vertices are the vectors of v and edges are the pairs of points that are no farther apart than r. This doesn't require the distances to be a proper metric: it doesn't have to satisfy the triangle inequality, only that it is symmetrical (dist(a,b) == dist(b,a)) and that it is 0 iff two points are equal.
After that step, we can forget about the distances altogether and focus entirely on partitioning the graph. As others have noted, that partition is a Vertex Cover problem. However, it has a twist: we require all the vertices in the cover to be disjoint (i.e.: no vectors in v1 can be within distance r of each other).
To obtain the graph, we can use the efficient KDTree to compute just once the nearest-neighbor structure. In particular, we'll use kd.sparse_distance_matrix(kd, r) to obtain all pairs of points separated by r or less:
from scipy.spatial import KDTree
def get_graph(v, r):
kd = KDTree(v)
sm = kd.sparse_distance_matrix(kd, r)
graph = {i: {i} for i, _ in sm.keys()}
for i, j in sm.keys():
graph[i] |= {j}
return graph
(note: .sparse_distance_matrix() has a parameter p if we want other distances than Euclidean).
The partitioning of the graph can be done in various ways. @DanR shows a greedy approach that is very fast, but often suboptimal in the size of v1 that it finds.
The following shows instead a brute-force approach that is guaranteed to find a minimal solution if there is one. It is adequate for relatively small number of vectors and can provide a ground-truth for the optimal solution, when researching other heuristics.
To speed up the combinatorial search, we first observe that often some points are not within distance r of any other (i.e. the graph found above doesn't represent all the points of v). We can leave those other points aside, since they will necessarily be part of v1 but don't interfere with the rest of the search (below, we call them "singletons"). Second, we cut unpromising "leads" (prefixes in the combinatorial expansion) if they are not fully disjoint. This speeds up considerably the full search, by cutting down entire swathes of search space. If no prefix is cut, the full search is time-exponential.
What is the speed of this? It depends on the distribution of the v vectors and (strongly) on the distance r. In fact, it depends on the number of clusters found. To give an idea, with v 20 vectors picked in uniform in 2D, I observe roughly 30ms. For 40 vectors, typically around 100ms, but it can jump to over 2 seconds for certain values of r.
We implement a variation of combinations that has a check function to cut down unpromising prefixes:
from itertools import combinations
def _okall(tup, *args, **kwargs):
return True
def combinations_all(iterable, n0=1, n1=None, check=None, *args, **kwargs):
pool = tuple(iterable)
n = len(pool)
if n0 > n:
return
n1 = n if n1 is None else n1
check = _okall if check is None else check
if n0 < 1:
yield ()
n0 = 1
seed = list(combinations(range(n), n0-1))
for r in range(n0, n1+1):
prev_seed = seed
seed = []
for prefix in prev_seed:
for j in range(max(prefix, default=-1)+1, n):
indices = prefix + (j,)
tup = tuple(pool[i] for i in indices)
if check(tup, *args, **kwargs):
seed.append(indices)
yield tup
Example:
# list all combinations of [0,1,2,3] (of all sizes), excluding those starting
# by (0,1)
>>> list(combinations_all(range(4), check=lambda tup: tup[:2] != (0,1)))
[(0,),
(1,),
(2,),
(3,),
(0, 2),
(0, 3),
(1, 2),
(1, 3),
(2, 3),
(0, 2, 3),
(1, 2, 3)]
Now, we use that to find the minimal disjoint cover and return the indices of v1:
def check(tup, graph):
# refuses tup if any one is within reach of another
# optimization: tup[:-1] has already passed this test, so just check the last one
if len(tup) < 2:
return True
reach_of_last = graph[tup[-1]]
prefix = set(tup[:-1])
return prefix.isdisjoint(reach_of_last)
def brute_vq(v, r):
n = v.shape[0]
graph = get_graph(v, r)
to_part = set(graph)
singletons = set(range(n)).difference(to_part)
if not to_part:
return sorted(singletons)
for tup in combinations_all(to_part, check=check, graph=graph):
# here tup are indices that are far apart enough (guaranteed disjoint in reach)
# check if they fully cover to_part
cover = {j for i in tup for j in graph[i]}
if cover == to_part:
v1_idx = sorted(singletons.union(tup))
return v1_idx
Examples:
v = np.random.uniform(size=(20, 2))
r_s = [[0.2, 0.3], [0.4, 0.5]]
fig, axes = plt.subplots(nrows=len(r_s), ncols=len(r_s[0]),
figsize=(12,12), sharex=True, sharey=True)
for r, ax in zip(np.ravel(r_s), np.ravel(axes)):
idx = brute_vq(v, r)
ax.set_aspect('equal')
ax.scatter(v[:, 0], v[:, 1])
for i, p in enumerate(v):
ax.text(*p, str(i))
for i in idx:
circ = plt.Circle(v[i], radius=r, color='g', fill=False)
ax.add_patch(circ)
plt.show();
A: My 5c:
Create a distance matrix (this is an O*O operation, obviously):
A B C D | min,max
A 0 3 2 1 | 1,3
B 3 0 5 4 | 3,5
C 2 5 0 6 | 2,6
D 1 4 6 0 | 1,6 # note: D-C violates the triangle inequality
Distance matrix, relabelled:
A D B C | min,max
A 0 1 3 2 | 1,3
D 1 0 4 6 | 1,6
B 3 4 0 5 | 3,5
C 2 6 5 0 | 2,6
Now, per row (or column) take tha max() of the min() (or the min() of the max()...)
With a distance of 3, the NW-part is fully connected and the rest is still partially connected
(with d=4, B would enter the subset, too)
A D | B C | min,max
A 0 1 | 3 2 | 1,3
D 1 0 | 4 6 | 1,6
----+ ----------
B 3 4 | 0 5 | 3,5
C 2 6 | 5 0 | 2,6
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65580197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.