id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23533800
|
I am calculating the inactive by comparing session.getLastAccessedTime() and current time . It is working fine in the single server.
But in a clustered environment ( 3 jboss servers with load balancer ) it is not working . We are using Basic authentication mechanism.
How to implement automatically logging out the user after certain inactive time in the cluster as mentioned above?
| |
doc_23533801
|
library(ggplot2)
df <- data.frame(
group = c("Male", "Female"),
value = c(15000, 10000))
head(df)
p <- ggplot(df, aes(x="", y = value, fill=group)) +
geom_bar(width = 1, stat = "identity") + coord_polar("y", start=0)
require(scales)
p + scale_fill_brewer("Blues") + blank_theme +
geom_text(aes(y = value/2 + c(0, cumsum(value)[-length(value)]),
label = percent(value/100)), size=5)
But unfortunately these lines of code don’t give me percentage numbers. So can anybody help me how to solve this problem and get real percentages of 60% for male and 40% for female.
A: Use just sum to count both genders. Example: percent(1000 / sum(df$value)) will return "4%".
library(tidyverse)
library(scales)
#>
#> Attaching package: 'scales'
#> The following object is masked from 'package:purrr':
#>
#> discard
#> The following object is masked from 'package:readr':
#>
#> col_factor
df <- data.frame(
group = c("Male", "Female"),
value = c(15000, 10000)
)
df
#> group value
#> 1 Male 15000
#> 2 Female 10000
ggplot(df, aes(x = "", y = value, fill = group)) +
geom_bar(width = 1, stat = "identity") +
coord_polar("y", start = 0) +
scale_fill_brewer("Blues") +
theme_void() +
geom_text(aes(
y = value / 2 + c(0, cumsum(value)[-length(value)]),
label = percent(value / sum(value))
), size = 5)
Created on 2021-09-22 by the reprex package (v2.0.1)
| |
doc_23533802
|
I tried to follow the examples at Spring Security 4.2 and various questions and responses on Stackoverflow.
Here is my code :
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and()
.csrf().disable()
.anonymous().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/signup").permitAll()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/fapi/**").authenticated()
.and()
.httpBasic()
.realmName("MY_REALM");
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://example.com"));
configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH", "OPTIONS"));
configuration.addAllowedHeader("*");
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
............
}
And here is the request from Chrome
General Headers
Request URL: http://api.example.com/oauth/token
Request Method: OPTIONS
Status Code: 401
Remote Address: 127.65.43.21:80
Referrer Policy: no-referrer-when-downgrade
Request headers
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Access-Control-Request-Headers: authorization
Access-Control-Request-Method: POST
Cache-Control: no-cache
Connection: keep-alive
Host: api.example.com
Origin: http://example.com
Pragma: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36
Response:
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Language: en
Content-Length: 1111
Content-Type: text/html;charset=utf-8
Date: Mon, 07 May 2018 03:23:15 GMT
Expires: 0
Pragma: no-cache
WWW-Authenticate: Basic realm="MY_REALM"
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
And the error in console:
Failed to load http://api.example.com/oauth/token: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com' is therefore not allowed access. The response had HTTP status code 401.
A: I could not make it work with the CorsFilter provided by Spring.
The work around here helped.
Spring security, cors error when enable Oauth2
The part of final code
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@WebFilter("/*")
public class SimpleCORSFilter implements Filter {
public SimpleCORSFilter() {
}
@Override
public void init(FilterConfig fc) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
System.out.println("doFilter");
HttpServletResponse response = (HttpServletResponse) resp;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, origin, x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, resp);
}
}
@Override
public void destroy() {
}
}
In the security configuration:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(HttpMethod.OPTIONS, "/oauth/token");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
//.cors().and()
.csrf().disable()
.anonymous().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/signup").permitAll()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/fapi/**").authenticated()
.and()
.httpBasic()
.realmName("MY_REALM");
}
/*
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://example.com"));
configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH", "OPTIONS"));
configuration.addAllowedHeader("*");
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}*/
............
}
I am still waiting for an example that makes it work with Spring Security's CorsFilter.
A: Instead of what you have done, write a custom cors filter like the following
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN);
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
}
And modify your configure(HttpSecurity http) override to
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.and()
.csrf().disable()
.anonymous().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/signup").permitAll()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/fapi/**").authenticated()
.and()
.httpBasic()
.realmName("MY_REALM");
}
| |
doc_23533803
|
COL 1 | COL 2 | COL 3
ABCD | ABC(D) | CDA
AB CD | ABC D | C D - (B)
A B C D | (ABCD) | ABCD
ABC D | ABDC | ABC D
A(BC ) D | AD B - C| AB CD
I want to compare every column with every other column and want to print similarities and differences between columns.
for example :
*
*comparing COL 1 and COL 2
similarities :
None
differences :
ABCD
AB CD
A B C D
A(BC ) D
ABC(D)
ABC D
(ABCD)
ABDC
AD B - C
then comparing COL 2 and COL 3 and then comparing COL 1 and COL 3.
Need only exact string match, even a whitespace considered as mismatch.
It may be possible that column number may increase and comparison starts from 2nd row of the column.
How can I implement such recursive comparison in Python which gives me fast processing output?
A: You can use xlrd. First of all, read content from your file. Second, save three columns into three dictionaries, since dict works faster in comparison. Third, do comparison work and output the result.
I suggest you check API of xlrd and write code by yourself. Here is link.
Any questions, feel free to ask.
EDIT:
Here is an example.
#!/usr/bin/python
#-*- coding:utf-8 -*-
name = {1:'a', 2:'b', 3:'c'}
lname = {1:'g', 2:'b', 3:'v'}
common = {}
diff_name = {}
diff_lname = {}
for key in name.keys():
if name[key] == lname[key]:
common[key] = name[key]
else:
diff_name[key] = name[key]
diff_lname[key] = lname[key]
print 'common part is:', common
print 'diff_name is: ', diff_name
print 'diff_lname is: ', diff_lname
A: An algorithm might be
for colA in range(0, N):
for colB in range (colA + 1, N - 1):
compare(colA, colB)
| |
doc_23533804
|
web application to use all languages. I want to understand Unicode for the process of internationalization, so I learnt about Unicode from here and there.
I am able to understand about Unicode that how a charset set in encoded to bytes and again bytes decoded to charset. But I don't know how to move forward further. I want to learn how to compare strings and I need to know how to implement internationalization in my web application. Any Suggestions Please? Please guide me.
My Objective:
My main objective is to develop a Web Application for Translation (English to Arabic & vice versa). I want to follow Internationalization. I wish to run my web Application for translation in all the three browsers namely FF, Chrome, IE. How do I achieve this?
A: In addition to what BalusC said, you have to take care about directionality (since English is written Left-To-Right and Arabic the other way round). The easiest way would be to add dir attribute to html element of your JSP web page and externalize it, so the value comes from properties file (just like with other elements or attributes):
<html dir="${direction}">
...
</html>
Also, there are few issues with styling such application - you should to say the least avoid absolute positioning. If you cannot avoid that for some reason, you could either use different stylesheets per (each?) language or do something that is verboten, that is use tables for managing layout. If you want to use div elements, I'd suggest to use relative positioning with "symmetric" left and right style attributes (both having the same value), since this is what makes switching directionality work.
You could find more about Bi-Directional websites here.
A: In case of a basic JSP/Servlet webapplication, the basic approach would be using JSTL fmt taglib in combination with resource bundles. Resource bundles contain key-value pairs where the key is a constant which is the same for all languages and the value differs per language. Resource bundles are usually properties files which are loaded by ResourceBundle API. This can however be customized so that you can load the key-value pairs from for example a database.
Here's an example how to internationalize the login form of your webapplication with properties file based resource bundles.
*
*Create the following files and put them in some package, e.g. com.example.i18n (in case of Maven, put them in the package structure inside src/main/resources).
text.properties (contains key-value pairs in the default language, usually English)
login.label.username = Username
login.label.password = Password
login.button.submit = Sign in
text_nl.properties (contains Dutch (nl) key-value pairs)
login.label.username = Gebruikersnaam
login.label.password = Wachtwoord
login.button.submit = Inloggen
text_es.properties (contains Spanish (es) key-value pairs)
login.label.username = Nombre de usuario
login.label.password = Contraseña
login.button.submit = Acceder
The resource bundle filename should adhere the following pattern name_ll_CC.properties. The _ll part should be the lowercase ISO 693-1 language code. It is optional and only required whenever the _CC part is present. The _CC part should be the uppercase ISO 3166-1 Alpha-2 country code. It is optional and often only used to distinguish between country-specific language dialects, like American English (_en_US) and British English (_en_GB).
*If not done yet, install JSTL as per instructions in this answer: How to install JSTL? The absolute uri: http://java.sun.com/jstl/core cannot be resolved.
*Create the following example JSP file and put it in web content folder.
login.jsp
<%@ page pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<c:set var="language" value="${not empty param.language ? param.language : not empty language ? language : pageContext.request.locale}" scope="session" />
<fmt:setLocale value="${language}" />
<fmt:setBundle basename="com.example.i18n.text" />
<!DOCTYPE html>
<html lang="${language}">
<head>
<title>JSP/JSTL i18n demo</title>
</head>
<body>
<form>
<select id="language" name="language" onchange="submit()">
<option value="en" ${language == 'en' ? 'selected' : ''}>English</option>
<option value="nl" ${language == 'nl' ? 'selected' : ''}>Nederlands</option>
<option value="es" ${language == 'es' ? 'selected' : ''}>Español</option>
</select>
</form>
<form method="post">
<label for="username"><fmt:message key="login.label.username" />:</label>
<input type="text" id="username" name="username">
<br>
<label for="password"><fmt:message key="login.label.password" />:</label>
<input type="password" id="password" name="password">
<br>
<fmt:message key="login.button.submit" var="buttonValue" />
<input type="submit" name="submit" value="${buttonValue}">
</form>
</body>
</html>
The <c:set var="language"> manages the current language. If the language was supplied as request parameter (by language dropdown), then it will be set. Else if the language was already previously set in the session, then stick to it instead. Else use the user supplied locale in the request header.
The <fmt:setLocale> sets the locale for resource bundle. It's important that this line is before the <fmt:setBundle>.
The <fmt:setBundle> initializes the resource bundle by its base name (that is, the full qualified package name until with the sole name without the _ll_CC specifier).
The <fmt:message> retrieves the message value by the specified bundle key.
The <html lang="${language}"> informs the searchbots what language the page is in so that it won't be marked as duplicate content (thus, good for SEO).
The language dropdown will immediately submit by JavaScript when another language is chosen and the page will be refreshed with the newly chosen language.
You however need to keep in mind that properties files are by default read using ISO-8859-1 character encoding. You would need to escape them by unicode escapes. This can be done using the JDK-supplied native2ascii.exe tool. See also this article section for more detail.
A theoretical alternative would be to supply a bundle with a custom Control to load those files as UTF-8, but that's unfortunately not supported by the basic JSTL fmt taglib. You would need to manage it all yourself with help of a Filter. There are (MVC) frameworks which can handle this in a more transparent manner, like JSF, see also this article.
A: based on this tutorial, I am using the following on GAE - Google's App Engine:
A jsp file as follows:
<%@ page import="java.io.* %>
<%
String lang = "fr"; //Assign the correct language either by page or user-selected or browser language etc.
ResourceBundle RB = ResourceBundle.getBundle("app", new Locale(lang));
%>
<!DOCTYPE html>
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<head>
</head>
<body>
<p>
<%= RB.getString("greeting") %>
</p>
</body>
And adding the files named: app.properties (default) and app_fr.properties (and so on for every language). Each of these files should contain the strings you need as follows: key:value_in_language, e.g. app_fr.properties contains:
greeting=Bonjour!
app.properties contains:
greeting=Hello!
That's all
| |
doc_23533805
|
Sub Transfer()
Dim cs As Workbook
Dim wrd As Word.Application
Dim pc As Word.Document
Dim CC As ContentControl
Dim CCTag As String
Dim CStxt As String
Set cs = ThisWorkbook
Set wrd = CreateObject("Word.Application")
Set pc = wrd.Documents.Open("Template Source")
For Each CC In pc.ContentControls
On Error Resume Next
CCTag = CC.Tag
If CCTag <> "" Then
CStxt = Range(CCTag)
If CC.Type = wdContentControlRichText Or CC.Type = wdContentControlText Then
CC.Range.Text = CStxt
ElseIf CC.Type = wdContentControlComboBox Or CC.Type = wdContentControlDropdownList Then
CC.SetPlaceholderText , , CStxt
ElseIf CC.Type = wdContentControlCheckBox Then
CC.Checked = False
If CStxt = "True" Then
CC.Checked = True
ElseIf CStxt = "False" Then
CC.Checked = False
Else
CC.Checked = False
End If
End If
End If
Next CC
End Sub
A: Firstly, I recommend that you refer to your range directly by referencing the workbook/worksheet you have declared in your variable cs This will ensure your subroutine executes on the correct workbook and correct worksheet.
If I have understood your question correctly - you would like to transfer a set of values in an Excel range over to the matching MS Word content control box - the issue would appear to be your use of
CStxt = Range(CCTag)
You cannot assign a variable of type string (CStxt) to an entire range of cells. This would generate a "Runtime error 13: Type mismatch" when executing your code.
In order to get this line to work, I had to change it to a single value/cell reference. See example below;
CStxt = cs.Sheets(1).Range("A1")
In this example, cell A1 has the value you want to transfer over to the relevant MS Word content control. This has the effect of giving the content control a display value equal to the Excel value, but is not added to the list to allow you to select it.
You can change the reference to A1 so that your named range is a single cell.
A: Your code works for me - assuming each Excel range refers to a single cell. Your code could, however, be both improved and simplified:
Sub Transfer()
Dim wdApp As Word.Application, wdDoc As Word.Document, wdCC As Word.ContentControl
Dim CStxt As String
Set wdApp = CreateObject("Word.Application")
Set wdDoc = wdApp.Documents.Open("Template Source")
For Each wdCC In wdDoc.ContentControls
With wdCC
If .Tag <> "" Then
CStxt = ThisWorkbook.Names(.Tag).RefersToRange.Text
Select Case .Type
Case wdContentControlRichText, wdContentControlText
.Range.Text = CStxt
Case wdContentControlDropdownList, wdContentControlComboBox
.Type = wdContentControlText
.Range.Text = CStxt
.Type = wdContentControlDropdownList
'.SetPlaceholderText Text:=CStxt
Case wdContentControlCheckBox
If CStxt = "True" Then
.Checked = True
Else
.Checked = False
End If
End Select
End If
End With
Next
End Sub
I do have to wonder, though, why you'd be modifying the placeholder text rather than selecting a combobox/dropdown item corresponding to CStxt. See code modification for a simple way to update the combobox/dropdown. For comboboxes, even that isn't needed - you could simply move ', wdContentControlComboBox' to follow 'wdContentControlText'.
| |
doc_23533806
|
list 1:
Company A <companya@companya.com>
Company B <companyb@companyb.com>
Company C <companyc@companyc.com>
list 2:
firstname lastname <firstname@gmail.com>
Fake Person <companyb@companyb.com>
Joe lastnanme <joe@gmail.com>
the current output is
Company A <companya@companya.com>
Company B <companyb@companyb.com>
Company C <companyc@companyc.com>
firstname lastname <firstname@gmail.com>
Fake Person <companyb@companyb.com>
Joe lastnanme <joe@gmail.com>
the desired output would be
Company A <companya@companya.com>
Company B <companyb@companyb.com>
Company C <companyc@companyc.com>
firstname lastname <firstname@gmail.com>
Joe lastnanme <joe@gmail.com>
(as companyb@companyb.com is listed in both)
How can I do that?
A: given your file format
$ awk -F'[<>]' '!a[$2]++' files
will print the first instance of duplicate content in angled brackets. Or if there is no content after the email, you don't need to un-wrap the angled brackets
$ awk '!a[$NF]++' files
Same can be done with sort as well
$ sort -t'<' -k2,2 -u files
side-effect is output will be sorted which can be desired (or not).
N.B. For both alternatives the assumption is angled brackets don't appear anywhere else than the email wrappers.
A: Here is one in awk:
$ awk '
match($0,/[a-z0-9.]+@[a-z.]+/) { # look for emailish string *
a[substr($0,RSTART,RLENGTH)]=$0 # and hash the record using the address as key
}
END { # after all are processed
for(i in a) # output them in no particular order
print a[i]
}' file2 file1 # switch order to see how it affects output
Output
Company A <companya@companya.com>
Company B <companyb@companyb.com>
Company C <companyc@companyc.com>
Joe lastnanme <joe@gmail.com>
firstname lastname <firstname@gmail.com>
Script looks for very simple emailish string (* see the regex in the script and tune it to your liking) which it uses to hash the whole records,last instance wins as the earlier onse are overwritten.
A: uniq has an -f option to ignore a number of blank-delimited fields, so we can sort on the third field and then ignore the first two:
$ sort -k 3,3 infile | uniq -f 2
Company A <companya@companya.com>
Company B <companyb@companyb.com>
Company C <companyc@companyc.com>
firstname lastname <firstname@gmail.com>
Joe lastnanme <joe@gmail.com>
However, this isn't very robust: it breaks as soon as there aren't exactly two fields before the email address as the sorting will be on the wrong field and uniq will compare the wrong fields.
Check karakfa's answer to see how uniq isn't even required here.
Alternatively, just checking for uniqueness of the last field:
awk '!e[$NF] {print; ++e[$NF]}' infile
or even shorter, stealing from karakfa, awk '!e[$NF]++' infile
A: Could you please try following.
awk '
{
match($0,/<.*>/)
val=substr($0,RSTART,RLENGTH)
}
FNR==NR{
a[val]=$0
print
next
}
!(val in a)
' list1 list2
Explanation: Adding explanation of above code.
awk ' ##Starting awk program here.
{ ##Starting BLOCK which will be executed for both of the Input_files.
match($0,/<.*>/) ##Using match function of awk where giving regex to match everything from < to till >
val=substr($0,RSTART,RLENGTH) ##Creating variable named val whose value is substring of current line starting from RSTART to value of RLENGTH, basically matched string.
} ##Closing above BLOCK here.
FNR==NR{ ##Checking condition FNR==NR which will be TRUE when 1st Input_file named list1 will be read.
a[val]=$0 ##Creating an array named a whose index is val and value is current line.
print $0 ##Printing current line here.
next ##next will skip all further statements from here.
}
!(val in a) ##Checking condition if variable val is NOT present in array a if it is NOT present then do printing of current line.
' list1 list2 ##Mentioning Input_file names here.
Output will be as follows.
Company A <companya@companya.com>
Company B <companyb@companyb.com>
Company C <companyc@companyc.com>
firstname lastname <firstname@gmail.com>
Joe lastnanme <joe@gmail.com>
A: Perhaps I don't understand the question !
but you can try this awk :
awk 'NR!=FNR && $3 in a{next}{a[$3]}1' list1 list2
| |
doc_23533807
|
If my resource class looks like this, where "filter" is a POJO that I would map the JSON body to - should there be a body, how can I also accept and empty body - resulting in my data variable being null - and then call my getChecksheets method with null or the filter object?
@POST
@Path("/checksheets")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public listOfChecksheetsResponse getChecksheets(filter data){
return service.getChecksheets(data);
}
| |
doc_23533808
|
I have Visual Studio 2012 and SQL Server Compact Edition 4.0 installed on my pc. I think there's an error in my Connection String but that's just my opinion, it looks something like this :
"Data Source=\"C:\\Users\\MyUser\\Documents\\Visual Studio 2012\\Databases\\Database.sdf\";Password=MyPassword;Persist Security Info=True"
But honestly if even I get the connection string right, I'm kind of in the dark on where to go after that, so if you would have any tips or even good tutorials on that, it would help a bunch.
If the problem isn't my ConnectionString then it must be somewhere else or I'm just not doing it right so here's the rest of my code :
sqlDataSourceDB.SelectCommand = "SELECT * FROM quote";
DataView dv = (DataView)sqlDataSourceDB.Select(DataSourceSelectArguments.Empty);
String resultat = (String)dv.Table.Rows[0][0];
The two last lines were taken from an msdn mini walkthrough
Une erreur liée au réseau ou spécifique à l'instance s'est produite lors de l'établissement d'une connexion à SQL Server. Le serveur est introuvable ou n'est pas accessible. Vérifiez que le nom de l'instance est correct et que SQL Server est configuré pour autoriser les connexions distantes. (provider: SQL Network Interfaces, error: 26 - Erreur lors de la localisation du serveur/de l'instance spécifiés)
The error looks like that (it is translated from french) :
An error liked to the network or the instance happened when establishing a connection to SQL Server.
The server is not found or cannot be accessed.
Check that the instance name is correct and that the SQL Server is correctly configured to allow distant connection.
(provider: SQL Network Interfaces, error 26 - Error when locating the server/instance)
RESOLVED : Alright, I realized that in Design View when I added the SqlDataSource it was working but not when I was coding it so I checked the full line and just saw my own stupidity; I had to specify the ProviderName -.- everything worked after that. Story lesson here, always overcheck everything instead of making stupid post. Thanks for the help though!
A: You add in your connection string to the config file which is included with every new project in visual studio like so:
<connectionStrings>
<add name="main" connectionString="Data Source=\"C:\\Users\\MyUser\\Documents\\Visual Studio 2012\\Databases\\Database.sdf\";Password=MyPassword;Persist Security Info=True" />
</connectionStrings>
The tutorial below makes use of something slightly different so it's up to you how you implement depending on your environment.
And your code behind file: (You will need to import SqlServerCe namespace)
string sql = "select * from blah";
SqlCeCommand cmd = new SqlCeCommand(sql, ConfigurationManager.ConnectionStrings["main"].ConnectionString);
SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
foreach(DataRow r in dt.Rows)
{
Console.WriteLine(r["something"].ToString());
}
Full tutorial on Sql Compact Edition at dotnetperls: http://www.dotnetperls.com/sqlce. The tutorial uses a reader to print the data out to the console, but you can just fill a DataTable like I have above quite as easily.
| |
doc_23533809
|
Class Person
Interface Address
Class EmailAddress
Class HomeAddress
Class OfficeAddress
The annotation for class Person
@Entity
@Table(name = "Persson")
there are property -- address in Person
@OneToOne(targetEntity = Address.class, mappedBy = "person")
private Address address
and for Interface Address. address is an interface. I don't want to create a table in db. and I hope it's sub class has it's own table
the annotation in class is
@MappedSuperclass
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
and the property-- person is
@ManyToOne(targetEntity = Person.class, cascade = CascadeType.ALL)
private Person person;
but it don't work.
when I change the address annotation to
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
it work, but it will create a new table.
My question is how can make it work without creating a table of Address? I only need three table, EmailAddress, officeAddress and homeAddress, and I don't want person know three class?
A: Given you are trying to use InheritanceType.TABLE_PER_CLASS I am guessing the issue is that you are trying to use Inheritance when there is no relationship at the Database level, viz. in the database there is no relationship between Home Address and Office Address.
https://en.wikibooks.org/wiki/Java_Persistence/Inheritance#Mapped_Superclasses
Mapped superclass inheritance allows inheritance to be used in the
object model, when it does not exist in the data model. It is similar
to table per class inheritance, but does not allow querying,
persisting, or relationships to the superclass. Its main purpose is to
allow mappings information to be inherited by its subclasses.
In this case then you would need to use only the @MappedSuperclass annotation on Address and remove all @Inheritance annotations. As noted above, @MappedSuperclass cannot be the target of an association. so you cannot have:
@OneToOne(mappedBy = "person")
private Address address
but would need to do
@OneToOne(mappedBy = "person")
private HomeAddress homeAddress
@OneToOne(mappedBy = "person")
private OfficeAddress homeAddress
With regard to interfaces, the JPA spec notes that:
The entity class must be a top-level class. An enum or interface must
not be designated as an entity
| |
doc_23533810
|
A: “Dead tuples” are not visible. Since pg_dump gets its data by running a SELECT statement against the table to be dumped, it won't see those deat tuples either, so it won't dump them.
| |
doc_23533811
|
https://domainname.com/wp-admin/options-general.php?page=sabai/settings&q=%2Fcron
| |
doc_23533812
|
data = [ ['A',1,200,200],
['A',2,-30,],
['A',3,500,],
['A',4,10,],
['A',5,-45,],
['B',1,30,500],
['B',2,12,],
['B',3,50,]]
df = pd.DataFrame(data, columns = ['batch','idx','op_sum', 'var3'])
I am trying to get the following result:
batch idx op_sum var3
A 1 200 200
A 2 -30 -30
A 3 500 -30
A 4 10 -30
A 5 -45 -45
B 1 30 500
B 2 12 12
B 3 50 12
Logic being:
If cur row(op_sum) < previous row(var3) then
cur row(var3) = cur row(op_sum)
else cur row(var3) = previous row(var3)
Note: I can achieve using iterrows and iloc but its not practical for millions of rows.
I have gotten this far with the vectorization:
#(a)
df.var3.ix[(df.op_sum<df.var3.shift()) | (df.var3.shift().isnull())] = df.op_sum.ix[(df.op_sum<df.var3.shift()) | (df.var3.shift().isnull())]
#(b)
df.var3.ix[(df.op_sum>df.var3.shift())] = df.var3.shift().ix[(df.op_sum>df.var3.shift())]
This yields the following:
batch idx op_sum var3
A 1 200 200
A 2 -30 -30
A 3 500 -30
A 4 10 -10 #Not Good
A 5 -45 -45
B 1 30 -45 #Not Good
B 2 12 12
B 3 50 12
When op_sum = 10 > var3.shift() = -30 it should give me var3 = -30 and similarly for the other not good value!
Also when I try to perform this operation (a) and (b) by doing df.groupby('batch') first, it gives me AttributeError: Cannot access callable attribute 'ix' of 'SeriesGroupby' objects, try using 'apply' method !
Please help me get over the finish line. Much appreciated.
A: I believe you need GroupBy.cummin:
df['var3'] = df.groupby('batch')['op_sum'].cummin()
print (df)
batch idx op_sum var3
0 A 1 200 200
1 A 2 -30 -30
2 A 3 500 -30
3 A 4 10 -30
4 A 5 -45 -45
5 B 1 30 30
6 B 2 12 12
7 B 3 50 12
| |
doc_23533813
|
I need user to pick from and to date so he can export order details within these two dates.
A: To add up to user10305897, in case you have issues with the date picker not showing, check the input mask property to ensure it is blank. Having an input mask prevents the date picker from showing
| |
doc_23533814
|
What is the reason for this and can I use any parameter to get a detailed graphical view in the SQL tab?
My spark version: 2.3
EDIT:17 Jan 2020
I found a JIRA https://issues.apache.org/jira/browse/SPARK-30064, but I am not sure if it's related since that is mentioning jdbc datasource which I am not using.
A: Check out https://spark.apache.org/docs/2.3.4/configuration.html#spark-ui
specifically I suspect for this issue you may have
spark.ui.retainedStages (default 1000) and/or spark.ui.retainedTasks (default 100k)
set too low.
If your job has 150 stages, and for example, each stage has 1000 tasks on average,
then your whole job would have 150*1000 = 150k tasks, which is over default 100k limit. So you would not see in Spark UI those older tasks / stages etc.
PS.
Also for Spark with such large number of stages (e.g. when you have a lot of dataframes etc chained in iteratively), we often find that creating checkpoints helps a lot. E.g. you could checkpoint for example every 20-50 iterations (if there is a loop that creates that huge lineage; play with the number that works best for your case), so you essentially split up that huge job with 150 stages into chunks of 20-50 stages. Spark Optimizer may have hard time going through a DAG of 150 dataframes to create an optimal plan etc.
https://jaceklaskowski.gitbooks.io/mastering-spark-sql/spark-sql-checkpointing.html
| |
doc_23533815
|
To isolate and understand the issue. I had created a simple project which it displays 100 sprites at random position when program is load, and do absolutely nothing afterwards, in the HellowWorld layer :
// on "init" you need to initialize your instance
-(id) init
{
if( (self=[super init])) {
CCTexture2D *vlo_Texture = [[CCTexture2D alloc] initWithImage:[UIImage imageNamed:@"Icon-72.png"]];
CCSprite *vlo_Temp[100];
NSInteger vli_X, vli_Y;
for (NSInteger vli_Counter=0; vli_Counter<100; vli_Counter++)
{
vli_X = arc4random()%480;
vli_Y = arc4random()%320;
vlo_Temp[vli_Counter] = [CCSprite spriteWithTexture:vlo_Texture]; //[CCSprite spriteWithFile:@"Icon-72.png"];
vlo_Temp[vli_Counter].position = ccp(vli_X, vli_Y);
[self addChild:vlo_Temp[vli_Counter]];
}
}
return self;
}
The fact that the code above runs only 30fps shocks me. I do not have a timer to refresh these sprites. I believe the system should just draw all the sprites and do nothing (I assume ?)
I had tried to apply :
[CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA4444];
and
if( ! [CCDirector setDirectorType:kCCDirectorTypeDisplayLink] )
[CCDirector setDirectorType:kCCDirectorTypeMainLoop];
however they do not improve the performance at all. Is there anything else I can do?
Thanks in advance.
Alex
A: You say:
After days of googling and trying different solutions...
but what have you tried?
Try putting all of your sprites that are using the same texture into a CCSpriteBatchNode. This allows these sprites to be rendered with just one glBindTexture call, a call which is quite slow.
CCSpriteBatchNode *batchNode = [CCSpriteBatchNode batchNodeWithFile:@"Icon-72.png"];
for (NSInteger vli_Counter=0; vli_Counter<100; vli_Counter++)
{
vli_X = arc4random()%480;
vli_Y = arc4random()%320;
vlo_Temp[vli_Counter] = [CCSprite spriteWithTexture:vlo_Texture]; //[CCSprite spriteWithFile:@"Icon-72.png"];
vlo_Temp[vli_Counter].position = ccp(vli_X, vli_Y);
[batchNode addChild:vlo_Temp[vli_Counter]];
}
[self addChild batchNode];
A: When it comes to performance ... have you tried running on a device ? the simulator falls very short of actual 'iSomething' performance, especially when dealing with HD pics and numerous sprites.
A: To compare the time it takes to run two different blocks of code, I recommend using BNRTimeBlock, as described on this Big Nerd Racn Weblog post.
| |
doc_23533816
|
File structure
- src
- pages
- Homepage.js
- helpers
- customFetch.js
Homepage.js
import React, { useEffect } from 'react'
import customFetch from '../helpers/customFetch'
export default function Homepage() {
useEffect(()=>{
setInterval(() => {
customFetch('/my-endpoint').then((result)=> {
// Do something...
})
}, 5000);
}, [])
return (
<div>
Homepage content here
</div>
)
}
customFetch.js
export default function customFetch(path) {
const apiURL = 'https://api.mysite.com'
// Do something fancy here...
return fetch(`${apiURL}${path}`)
}
What I want to do is to bring apiURL from a .env.* file instead of hard coding it. How could I do it the Gatsby way? Thanks!
PS.: I know that doing this inside a page is trivial (https://www.gatsbyjs.org/docs/environment-variables/) but that's a bit different than what I want to do.
A: First of all, you need to set up your environment in your build and develop command like this (in your package.json):
"build": "GATSBY_ACTIVE_ENV=yourEnvironment gatsby build",
"develop": "GATSBY_ACTIVE_ENV=yourEnvironment gatsby develop",
The snippet above will get the configuration from .env.yourEnvironment file. Then, you need to create your environment file and define your desired variables, such as (.env.yourEnvironment):
API_URL=https://api.mysite.com
Then, in your gatsby-config.js (outside module.exports) you need to require that environment file:
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
})
According to Gatsby documentation, this is because:
Project environment variables that you defined in the .env.* files
will NOT be immediately available in your Node.js scripts. To use
those variables, use NPM package dotenv to examine the active .env.*
file and attach those values. dotenv is already a dependency of
Gatsby, so you can require it in your gatsby-config.js or
gatsby-node.js like this:
The last step is to get your variable in your component using:
const apiURL = process.env.API_URL
In your case:
export default function customFetch(path) {
const apiURL = process.env.API_URL
// Do something fancy here...
return fetch(`${apiURL}${path}`)
}
That allows you to separate the logic and token and environment variables to implement a multisite (multidomain) project for example.
| |
doc_23533817
|
A: I believe this will reset your settings to their factory state:
devenv.exe /resetsettings
In the future, you might want to consider exporting your settings (after you get them where you want them) using the "Tools/Import and Export Settings ..." wizard in Visual Studio.
If you reset in the future, you can then either use the wizard, or use the command
devenv /resetsettings {SettingsFile}
Where {SettingsFile} is your previously exported settings
| |
doc_23533818
|
public static void main(String[] args) throws IOException, FileNotFoundException {
// TODO Auto-generated method stub
//calls method which checks that the file exists
checkForDocument();
// declares String name
String name = null;
//Sets button text to "Search by first name" for the first button and "Search by last name" for the second button
Object[] options = {"Search by first name", "Search by last name"};
//creates frame
Component frame = null;
// displays the following message above the options within the dialog box
int n = JOptionPane.showOptionDialog(frame,
"Presidents of The United States ",
//
null, JOptionPane.YES_NO_CANCEL_OPTION,
//
JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
// if the user clicks search by first name
if (n == JOptionPane.YES_OPTION) {
//firstNameSearch method is called
firstNameSearch();
//if user clicks search by last name
} else if (n == JOptionPane.NO_OPTION) {
//prompts the user to enter a name and assigns it to lastName
String lastName = JOptionPane.showInputDialog("Enter a last name");
//calls the LastNameSearch method
lastNameSearch(lastName);
}
// trailing else
else
{
//
JOptionPane.showMessageDialog (null, "You must choose an option");
}
}
//method for searching by first name
public static void firstNameSearch () throws IOException {
File file = new File ("USPres.txt");
Scanner inputFile = new Scanner(file);
//declares count
int count;
//user is prompted to enter a first name
String firstName = JOptionPane.showInputDialog("Enter a first name");
for ( count = 1; inputFile.hasNext(); ++count)
{
// assigns string line to inputFile's Next line
String line = inputFile.nextLine();
//assigns string firstWord to first word in line
String firstWord = line.split(" ")[0];
//if firstWord equals firstNem
if (firstWord.compareToIgnoreCase(firstName)==0)
{
//prints the line
JOptionPane.showMessageDialog(null,line);
}
if ( count > 44)
if (firstWord.compareToIgnoreCase(firstName)!=0)
JOptionPane.showInternalMessageDialog(null, "Name not found");
}
}
//method for searching by last name
public static void lastNameSearch(String lastName) throws IOException
{
//checks that document exists
checkForDocument();
// declares String lastWord
String lastWord = null;
File file = new File ("USPres.txt");
Scanner inputFile = new Scanner(file);
// declares the string line
String line = null;
//while file has another line
while(inputFile.hasNext()) {
//assigns variable line to next line of input file
line = inputFile.nextLine();
//assigns last word of a line to lastWord
lastWord = line.substring(line.lastIndexOf(" ")+1);
//if lastWord is equal to the last name input by the user
if(lastWord.compareToIgnoreCase(lastName)==0) {
//prints the line
JOptionPane.showInternalMessageDialog(null,line);
}
}
}
// Checks that file exists
public static void checkForDocument() throws IOException
{
// checks that USPres.txt exists
try
{
//assigns file to USPres.txt
File file = new File ("USPres.txt");
Scanner inputFile = new Scanner(file);
}
// deals with FileNotFoundException
catch (FileNotFoundException e)
{
//message which displays if file does not exist
JOptionPane.showMessageDialog(null, "Error. File not found");
//terminates program
System.exit(0);
}
}
//displayMessage method header
public static void displayMessage() throws IOException{
//displays message
JOptionPane.showMessageDialog(null, "Name not found");
//terminates program
System.exit(0);
}
A: You can only say that a name could not found if you iterate through all names with the for/while loop. If a name has found you can take the result and break the loop with a return.
If every iteration of the loop was not successful, you can be sure the name could not found. You can also add conditions after the loop. For example for different dialog messages.
for (int i=0; i<maxCount && inputFile.hasNext(); i++) {
...
if (firstWord.compareToIgnoreCase(firstName) == 0) {
JOptionPane.showMessageDialog(null, line);
return;
}
}
displayMessage();
Hint for the next step: Try to extract duplicate code and use the methods with arguments. For example the file path. ;)
| |
doc_23533819
|
window.App = Ember.Application.create(
{ rootElement: '#container' }
);
App.WindowDetail = Ember.Object.create({
ID: "",
Title: "",
InteriorFinishesDescription: ""
});
Currently, we are getting JSON data via an AJAX call in this manner:
$(window).load(function () {
//Call the page method
$.ajax({
type: "POST",
url: "TestController.aspx",
//contentType: "application/json; charset=utf-8",
data: "asaw",
dataType: "json",
success: function (r) {
App.WindowDetail.InteriorFinishesDescription = r.InteriorFinishesDescription;
alert(App.WindowDetail.InteriorFinishesDescription);
}
});
});
In this sample, the JSON data comes back fine -- "App.WindowDetail.InteriorFinishesDescription" gets populated.
The problem is that the template doesn't get populated. And, I don't think this is exactly the correct way to get JSON data back when using Ember JS.
Here's a sample of what the handlebars template looks like:
<script type="text/x-handlebars">
<div class="two columns">
{{App.WindowDetail.InteriorFinishesDescription}}
</div>
</script>
A: In order to trigger Ember's bindings, you'll need to use set():
App.WindowDetail.set("InteriorFinishesDescription", r.InteriorFinishesDescription);
BTW, I'm glad you found my other answer helpful. There are definitely a few different persistence options out there. In terms of complexity and capability, I'd say they go from jQuery.ajax() to Ember REST to Ember Resource to Ember Data.
| |
doc_23533820
|
Below is a portion of my code which contains bother errHandlers:
Range("T1").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 10498160
.TintAndShade = 0
.PatternTintAndShade = 0
End With
With Selection.Font
.Color = -16711681
.TintAndShade = 0
End With
With Selection
.HorizontalAlignment = xlGeneral
.VerticalAlignment = xlBottom
.WrapText = True
.Orientation = 0
.AddIndent = False
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
ActiveCell.FormulaR1C1 = "OK or DELETE"
Rows("1:1").Select
Selection.AutoFilter
Range("T2").Select
ActiveCell.FormulaR1C1 = _
"=IF(AND(RC[-19]<>R[-1]C[-19],RC[-10]<>R[-1]C[-10]),""OK"",IF(AND(RC[-19]=R[-1]C[-19],RC[-10]<>R[-1]C[-10]),""OK"",IF(AND(RC[-19]=R[-1]C[-19],RC[-10]=R[-1]C[-10],RC[-7]=""T""),""OK"",""DELETE"")))"
Selection.AutoFill Destination:=Range("T2:T" & Cells(Rows.Count, 1).End(xlUp).Row)
Range("T2:T" & Cells(Rows.Count, 1).End(xlUp).Row).Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
ActiveSheet.Range("$A$1:$T" & Cells(Rows.Count, 1).End(xlUp).Row).AutoFilter Field:=20, Criteria1:="DELETE"
On Error GoTo errHandler:
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.EntireRow.Delete
errHandler:
ActiveSheet.Range("$A$1:$T" & Cells(Rows.Count, 1).End(xlUp).Row).AutoFilter Field:=20
Columns("E:G").Select
Selection.ColumnWidth = 11
Range("G2").Select
ActiveCell.FormulaR1C1 = _
"=IF(RC[6]=""T"",""DELETE"",IF(AND(RC[-6]=R[1]C[-6],RC[3]=R[1]C[3],R[1]C[6]=""T""),R[1]C[-1],IF(RC[-6]=R[1]C[-6],R[1]C[-1]-1,VALUE(""06/30/2017""))))"
Selection.AutoFill Destination:=Range("G2:G" & Cells(Rows.Count, 1).End(xlUp).Row)
Range("G2:G" & Cells(Rows.Count, 1).End(xlUp).Row).Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
ActiveSheet.Range("$A$1:$T" & Cells(Rows.Count, 1).End(xlUp).Row).AutoFilter Field:=7, Criteria1:="DELETE"
On Error GoTo errHandler2:
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.EntireRow.Delete
errHandler2:
ActiveSheet.Range("$A$1:$T" & Cells(Rows.Count, 1).End(xlUp).Row).AutoFilter Field:=7
Range("D2").Select
ActiveWorkbook.Save
End Sub
Any help would be greatly appreciated.
A: You've entered Spaghetti Lane, and you want to get out of there before you dig yourself any deeper.
Your procedure is doing too many things. Doing too many things is the single reason for ever needing more than a single error-handling subroutine in a procedure scope. Break. Things. Down.
An On Error statement has no effect whatsoever if it's executed while VBA is already in an error state - thus, no error-handling subroutine should ever have any On Error statements.
Start by pulling that "delete all visible rows" code into its own procedure scope:
Private Sub DeleteVisibleRows(ByVal source As Range)
On Error Resume Next
source.SpecialCells(xlCellTypeVisible).EntireRow.Delete
On Error GoTo 0
End Sub
Note how Selection is irrelevant in that code, and how no Range needs to be Selected.
Second, an error-handling subroutine should only ever run while VBA is in an error state; not doing that causes the "happy execution path" and the "error execution path" to get intertwined, and that never ends well.
Starting at On Error GoTo errHandler:, your code should look like this:
DeleteVisibleRows Selection 'TODO: work out what Range object this is, use it instead
Dim entireTable As Range
Set entireTable = ActiveSheet.Range("$A$1:$T" & ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row)
entireTable.AutoFilter Field:=20
ActiveSheet.Columns("E:G").ColumnWidth = 11
Dim columnG As Range 'TODO: use meaningful name
Set columnG = ActiveSheet.Range("G2:G" & ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row)
'NOTE: no need to AutoFill if we write the whole column at once..
columnG.FormulaR1C1 = "=IF(RC[6]=""T"",""DELETE"",IF(...))"
'NOTE: no clipboard gets involved
columnG.Value = columnG.Value ' overwrites formulas with their values
entireTable.AutoFilter Field:=7, Criteria1:="DELETE"
DeleteVisibleRows entireTable
ActiveSheet.Range("D2").Select ' <~ this is the only legit use of Range.Select!!
ActiveWorkbook.Save
| |
doc_23533821
|
My parent document has a file parent.js.
I need to call a function that is in parent.js, from a function that is in iframe.js.
I tried doing window.parent.myfunction() this function is in the parent.js file.
But, it didn't work. Only when I put the function on the parent page (I mean in the HTML), then it worked.
Any idea how to get this to work?
A: Try just parent.myfunction(). Also be 100% sure that the parent.js is included in your parent document.
A: I know this is an old question, but in case the accepted answer doesn't work (it didn't work for me) you could do this inside parent.js
window.myfunction = function () {
alert("I was called from a child iframe");
}
Now from the iframe you can call myfunction() like you initially wanted
window.parent.myfunction();
A: Window.postMessage() method safely enables cross-origin communication.
If you have access to parent page then any data can be passed as well as any parent method can be called directly from Iframe.
Parent page:
if (window.addEventListener) {
window.addEventListener("message", onMessage, false);
} else if (window.attachEvent) {
window.attachEvent("onmessage", onMessage, false);
}
function onMessage(event) {
// Check sender origin to be trusted
if (event.origin !== "http://example.com") return;
var data = event.data;
if (typeof(window[data.func]) == "function") {
window[data.func].call(null, data.message);
}
}
// Function to be called from iframe
function parentFuncName(message) {
alert(message);
}
Iframe code:
window.parent.postMessage({
'func': 'parentFuncName',
'message': 'Message text from iframe.'
}, "*");
References:
*
*Cross-document messaging (https://html.spec.whatwg.org/multipage/comms.html#web-messaging)
*Window.postMessage method (https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage)
*Can I Use (http://caniuse.com/#search=postMessage)
| |
doc_23533822
|
React Native: 0.66.4
React Navigation: v6
Current Situation
*
*Test push notifications through AWS Pinpoint work (they are successfully sent to a device), but will redirect a user to the wrong route (the initial route / home screen) of the application even when using a deep link. The deep link I am passing through AWS Pinpoint is in the form 'appName://ScreenName' (without the quotes).
*The deep link to the page I want the user to go to works, but not as a push notification. For example, if I open Notes on my phone and type 'appName://ScreenName' and press the link I will be redirected to the deep link in my app. This convinces me that deep linking is set up properly, maybe I am wrong here?
*If I hardcode the url scheme I want to use into my app.js file (running in development on a physical device) I am directed to the proper screen.
It appears that deep linking is working but Linking.getInitialURL() is not returning the url scheme from a push notifications. The url scheme works, but not as a push notification, whether the app is running in the background or not.
App.js
const config = {
screens: {
'ScreenName': "ScreenName",
},
}
const linking = {
prefixes: ['https://appName.com', 'appName://'],
config,
};
const handleOpenUrl = (event) => {
if (event && event.url) {
const route = event.url.replace(/.*?:\/\//g, "")
if (route?.includes("setmpin")) {
let { hostname, path, queryParams } = Linking.parse(route)
const params = path.split("/")[1]
const listener = Linking.addEventListener(
"url",
handleURL(path.split("/")[0], params)
)
}
}
}
useEffect(() => {
Linking.getInitialURL().then((url) => {
const supported = Linking.canOpenURL(url)
if (supported) {
Linking.openURL(url)
}
})
Linking.addEventListener("url", handleOpenUrl);
return () => {
Linking.removeAllListeners("url");
};
}, [])
Questions...
*
*Am I missing anything glaring here, I have read several stackoverflow and similar posts and am not sure what I have missed.
*Am I right to believe that deep linking is setup properly since I can test deep links in my Notes app or by hardcoding the url scheme in my App.js file?
*Is there a way to validate what url is being passed by Pinpoint? I believe this is what is driving the issue but do not know how I can check this since push notifications only work on my physical device in production.
Thanks! Happy to share any additional information as well...
| |
doc_23533823
|
Now take this example:
print"<center><Table cellspacing=0 cellpadding=0 border=1 style=\"width:680px;border:1px solid blue\">";
print"<tr><td>";
print "<table cellspacing=0 cellpadding=0 border=1 style=\"width:220px;border:1px solid blue;\">";
print "<tr><td>";
print "testing testing";
print "</tr></td>";
print "<tr><td>";
print "testing it";
print "<tr></td>";
print "<tr><td>";
print "testing it";
print "<tr></td>";
print "</table><br>";
print "<table cellspacing=0 cellpadding=0 border=1 style=\"width:220px;border:1px solid blue;\">";
print "<tr><td>";
print "testing testing";
print "</tr></td>";
print "<tr><td>";
print "testing it";
print "<tr></td>";
print "<tr><td>";
print "testing it";
print "<tr></td>";
print "</table>";
print"</tr></td>";
print "</table></center>";
This outputs like so in the browser (which is fine):
Now the problem is I want the inner tables to float to the left so they appear next to each other, instead of beneath each other. Obviously floats don't work in Outlook, so how else could I do something like that?
A: Nest them inside another table:
<table>
<tr>
<td>
TABLE 1 GOES HERE
</td>
<td>
TABLE 2 GOES HERE
</td>
</tr>
</table>
A: All CSS Properties not supported in email clients(outlook), so create your table structure properly.
DEMO
HTML
<table style="border:1px solid #00F;" width="500" border="0" cellspacing="0" cellpadding="0">
<tr>
<td style="border-bottom:1px solid #00F;" align="left" valign="top">Table One</td>
<td style="border-bottom:1px solid #00F; border-left:1px solid #00F;" align="left" valign="top">Option 1</td>
<td style="border-bottom:1px solid #00F; border-left:1px solid #00F;" align="left" valign="top">Option 2</td>
</tr>
<tr>
<td align="left" valign="top">Table Two</td>
<td style="border-left:1px solid #00F;" align="left" valign="top">Option 1</td>
<td style="border-left:1px solid #00F;" align="left" valign="top">Option 2</td>
</tr>
</table>
<br/>
<table style="border:1px solid #00F;" width="500" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="left" valign="top"><table width="250" border="0" cellspacing="0" cellpadding="0">
<tr>
<td style="border-bottom:1px solid #00F;" align="left" valign="top">Table Two</td>
</tr>
<tr>
<td style="border-bottom:1px solid #00F;" align="left" valign="top">Option 1</td>
</tr>
<tr>
<td align="left" valign="top">Option 2</td>
</tr>
</table></td>
<td style="border-left:1px solid #00F;" align="left" valign="top"><table width="250" border="0" cellspacing="0" cellpadding="0">
<tr>
<td style="border-bottom:1px solid #00F;" align="left" valign="top">Table One</td>
</tr>
<tr>
<td style="border-bottom:1px solid #00F;" align="left" valign="top">Option 1</td>
</tr>
<tr>
<td align="left" valign="top">Option 2</td>
</tr>
</table></td>
</tr>
</table>
A: Andy's answer will place the table cells next to each other - that is the most consistent technique. However, you were asking for a float equivalent. For html email that is align="left".
Example:
<table width="90%" border="0" cellpadding="0" cellspacing="0" bgcolor="#bbbbbb">
<tr>
<td align="left">
<table width="150" align="left" border="0" cellpadding="0" cellspacing="0" bgcolor="#333333">
<tr>
<td height="100">
...
</td>
</tr>
</table>
<table width="150" align="left" border="0" cellpadding="0" cellspacing="0" bgcolor="#555555">
<tr>
<td height="100">
...
</td>
</tr>
</table>
<table width="150" align="left" border="0" cellpadding="0" cellspacing="0" bgcolor="#777777">
<tr>
<td height="100">
...
</td>
</tr>
</table>
</td>
</tr>
</table>
When viewed in an email client, the tables will bump down when there isn't enough room (mobile for example). This is the behavior that float has, while Andy's solution is fixed, meaning your tables (td's) will always be next to each other.
| |
doc_23533824
|
https://chrome.google.com/webstore/detail/save-emails-and-attachmen/nflmnfjphdbeagnilbihcodcophecebc?hl=en
The email account only receives excel sheets as attachments, and those are saved to a specific folder automatically.
Is it possible to have those sheets converted automatically to google sheets upon save (or after save). Currently, I have to open the file with google sheets to convert it.
I have tried setting the folder to Convert uploaded files to Google Docs editor format, but that doesn't work for this.
Any suggestions would be greatly appreciated.
Eric
A: if you're wishing to do this with the Drive API, then you can do so using the examples given in Upload Files, see the section headed Importing to Google Docs types. Essentially, by setting the source file MIME type to application/vnd.openxmlformats-officedocument.spreadsheetml.sheet and that of the new file to application/vnd.google-apps.spreadsheet, this indicates that the conversion is required on upload.
| |
doc_23533825
|
SKU ID SERIAL CODE
A 0 10 aa
B 4 20 bb
C 5 30 cc
D 8 40 dd
E 8 50 ee
F 7 60 rr
I want to update it to this using SQL UPDATE command:
SKU ID SERIAL CODE
A 0 10 aa
B 1 20 bb
C 1 30 cc
D 8 40 dd
E 1 50 ee
F 1 60 rr
Lets say I have 3000 rows and I want to update 100 SKU and set the ID to 1.
A: If I understand correctly, you can just us in:
update t
set id = 1
where sku in (sku1, sku2, sku3, . . .);
| |
doc_23533826
|
library(gapminder); library(tidyverse); library(tidymodels)
gapminder %>%
recipe(lifeExp ~ .) %>%
step_discretize(all_numeric(), -all_outcomes(), options = list(cuts = 10)) %>%
prep() %>%
juice()
In the above code I loose the original values from the pop and gdpPercap as they are replaced with their respective discretized verions. How can I keep both: original numeric values as well as discretised variables?
Secondly, instead of bin01, bin02, isn't there a way to get the [0-100], [101-150], etc. kind of bins so I know which bin has what values?
A: Not sure how to do this using step_discretize with left_joining the data again, but there is a discretize function from arules package that renders bins with values. Here is the what worked for me.
gapminder %>%
mutate(across(where(is.numeric),
~arules::discretize(x = .x, method = "interval", breaks = 10),
.names = "bin_{col}"))
In case, you know how to do this within recipe, do let me know.
| |
doc_23533827
|
When the user installs the App for the first time, i catch the fresh and new token at MessagingService.java:
@Override
public void onNewToken(@NonNull String tkn) {
super.onNewToken(tkn);
sendTokenToServer(tkn);
}
Here comes the problem, when the user closes session (without uninstalling the app), SharedPreferences are deleted. A new session is started; but onNewToken() is not called. So, i must manually retrieve the Token inside my MainActivity in order to send it to the server. I am getting the updated token with this piece of code:
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(MainActivity.this, new OnSuccessListener<InstanceIdResult>() {
@Override
public void onSuccess(InstanceIdResult instanceIdResult) {
sendTokenToServer(instanceIdResult.getToken());
}
});
As you know, that code is deprecated and should be avoided. Instead, i tried to replace it with this piece of code with no success:
FirebaseInstallations.getInstance().getToken(true).addOnCompleteListener(new OnCompleteListener<InstallationTokenResult>() {
@Override
public void onComplete(@NonNull Task<InstallationTokenResult> task) {
if(task.isSuccessful()) {
String token = task.getResult().getToken();
}
}
});
The Token length obtained at onNewToken() is 163.
The token length obtained at deprecated call is 163 (perfect, but deprtecated).
The token length obtained at FirebaseInstallations is 316.
My firebase API at server side fails to send a notification using the code of 316 length.
Any one knows what i am doing wrong? Or why i get those different length tokens?
Update:
Server side python, retrieves token from database and sends the notification like this. Please note this code is working when token len is 163.
from pyfcm import FCMNotification
push_service = FCMNotification(api_key=" ... ")
push_service.notify_single_device(registration_id=token, data_message=datamessage, time_to_live=1296000)
When trying to send a notification with long token this is the message I get:
{'multicast_ids': [8149274412512777031], 'success': 0, 'failure': 1, 'canonical_ids': 0, 'results': [{'error': 'InvalidRegistration'}], 'topic_message_id': None}
A: From the documentation for FirebaseInstanceId:
This class is deprecated. Firebase Instance ID has been replaced with
FirebaseInstallations for app instance identifiers and
FirebaseMessaging.getToken() for FCM registration tokens.
Looks like you need FirebaseMessaging.getToken() not FirebaseInstallations.getInstance().getToken(true) as you want a FCM registration token.
These APIs provide different tokens for different purposes.
So in your example it would be:
FirebaseMessaging.getInstance()
.getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
@Override public void onComplete(@NonNull Task<String> token) {
}
}
);
| |
doc_23533828
|
using namespace std;
int main(){
float arithmetic_operation = (4+5)+9*2-4+2/5+1-13;
cout<< arithmetic_operation << " <--The Result." << endl;
return 0;
}
I am getting 11 <--The Result. But actually the result is 11.4, Can someone please help me to understand the point please.
A: You are doing integer arithmetic. All operands are integers, which meand all operations will be done using integer operations. And for integer division 2/5 is equal to zero.
Use floating point value all over instead:
double arithmetic_operation = (4.+5.)+9.*2.-4.+2./5.+1.-13.;
| |
doc_23533829
|
defmodule Launch do
@moduledoc """
Documentation for `Launch`.
"""
@doc """
"""
def start() do
children = [
%{
id: Print,
start: {Print, :print, []}
},
%{
id: Proc1,
start: {Proc1, :proc1, []}
},
%{
id: Proc2,
start: {Proc2, :proc2, []}
}
]
Supervisor.start_link(children, strategy: :one_for_one)
end
end
defmodule Print do
def print() do
num =
IO.gets("Input number: ")
|> String.trim()
|> String.to_integer()
if num >= 0 do
send(Proc1, {self(), num})
else
send(Proc2, {self(), num})
end
receive do
num -> IO.puts(num)
after
500 ->
print()
end
print()
end
end
defmodule Proc1 do
def proc1() do
receive do
{pid, num} ->
send(pid, 100/num)
proc1()
_e ->
IO.puts("Error")
end
end
end
defmodule Proc2 do
def proc2() do
receive do
{pid, num} ->
send(pid, 1000/num)
proc2()
_e ->
IO.puts("Error")
end
end
end
I am trying to run all processes under the supervision of a single Supervisor. But there is a problem-only the first "child" is started, the other "children" are not started. In the example above, the Print process will start, but Proc1 and Proc2 will not start. How do I run all processes under one Supervisor? Important note: the Print process must get the addresses of the Proc1 and Proc2 processes for communication.
A: There are many issues with the code you’ve posted.
Registered processes
To be able to use process name as Process.dest() in a call to Kernel.send/2, one should start the named process.
Supervisor.start_link/2
Supervisor.start_link/2 expects a list of tuples, with modules and functions that immediately return, having the process started as a side effect. These functions are called, and there would not be any magic: if this is an infinitely recursive function, the execution flow would be deadlocked inside, waiting for the message in receive/1.
Supervisor performs some magic by automatically monitoring and restarting children for you, but it does nothing to spawn the separate processes. GenServer encapsulates this functionality and provides a handy way to not bother about spawning processes.
Solution
What you might do, is to spawn all three processes, manually monitor them, and react on {:DOWN, ref, :process, pid, reason} message respawning the died process. This is exactly what Supervisor effectively does under the hood for children.
Launch
defmodule Launch do
def start() do
proc1 = spawn(&Proc1.proc1/0)
proc2 = spawn(&Proc2.proc2/0)
print = spawn(fn -> Print.print(proc1, proc2) end)
Process.monitor(proc1)
Process.monitor(proc2)
Process.monitor(print)
receive do
msg -> IO.inspect(msg)
end
end
end
Print
defmodule Print do
def print(pid1, pid2) do
num =
IO.gets("Input number: ")
|> String.trim()
|> String.to_integer()
if num >= 0 do
send(pid1, {self(), num})
else
send(pid2, {self(), num})
end
receive do
num -> IO.puts(num)
end
print(pid1, pid2)
end
end
The other two modules are fine.
Here is how it will look like in iex
iex|1 ▶ c "/tmp/test.ex"
#⇒ [Launch, Print, Proc1, Proc2]
iex|2 ▶ Launch.start
Input number: 10
10.0
Input number: 1000
0.1
Input number: a
#⇒ {:DOWN, #Reference<0.3632020665.3980394506.95298>,
# :process, #PID<0.137.0>,
# {:badarg,
# [
# {:erlang, :binary_to_integer, ["a"], []},
# {Print, :print, 2, [file: '/tmp/test.ex', line: 22]}
# ]}}
Now instead of printing this out, respawn the failed process, and you will get a bare implementation of the supervised intercommunicating processes. For all_for_one strategy that could be achieved with:
receive do
{:DOWN, _, _, _, _} ->
Process.exit(print, :normal)
Process.exit(proc1, :normal)
Process.exit(proc2, :normal)
start()
end
| |
doc_23533830
|
kernel void filter(texture2d<float, access::read> inTexture [[texture(0)]],
texture2d<float, access::write> outTexture [[texture(1)]],
uint2 gridPos [[ thread_position_in_grid ]]) {
float4 color = inTexture.read(gridPos);
outTexture.write(color, gridPos);
}
Measuring the execution time
[self.timer start];
[commandBuffer commit];
[commandBuffer waitUntilCompleted];
CGFloat ms = [self.timer elapse];
Timer class works like this:
- (void)start {
self.startMach = mach_absolute_time();
}
- (CGFloat)elapse {
uint64_t end = mach_absolute_time();
uint64_t elapsed = end - self.startMach;
uint64_t nanosecs = elapsed * self.info.numer / self.info.denom;
uint64_t millisecs = nanosecs / 1000000;
return millisecs;
}
Dispatch call:
static const NSUInteger kGroupSize = 16;
- (MTLSize)threadGroupSize {
return MTLSizeMake(kGroupSize, kGroupSize, 1);
}
- (MTLSize)threadGroupsCount:(MTLSize)threadGroupSize {
return MTLSizeMake(self.provider.texture.width / kGroupSize,
self.provider.texture.height / kGroupSize, 1);
}
[commandEncoder dispatchThreadgroups:threadgroups
threadsPerThreadgroup:threadgroupSize];
gives me 13 ms on 512x512 rgba image and it grows lineary if I perform more passes.
Is this correct? It seems too much overhead for real time application.
A: Compute kernels are known to have rather high overhead on A7 processors. One thing to consider, though, is that this is basically the least flattering test you can run: a one-shot threadgroup dispatch might take ~2ms to get scheduled, but scheduling of subsequent dispatches can be up to an order of magnitude faster. Additionally there's little chance for latency hiding here. In practice, a much more complex kernel probably wouldn't take substantially longer to execute, and if you can interleave it with whatever rendering you might be doing, you might find performance to be acceptable.
| |
doc_23533831
|
A: It depends on exactly what your needs are.
While not exactly what you are looking for, you can deploy an Action to Alpha test status. This lets you make it available to up to 20 users without going through the review process.
Additionally, you can deploy it to up to 200 users if you deploy to Beta. However, this still will require a review by the Action review team.
If you need more than this (and probably a wise idea even in other use cases), you'll need to use Google Sign in for Assistant or other identity methods to get the identity of the user and then determine if this is an authorized user as part of your Action. This will require review by the Action review team.
| |
doc_23533832
|
By the coommand
yowsup-cli -a --interactive <PHONE_NUMBER_HERE> --wait --autoack --keepalive --config yowsup-master/src/yowsup-cli.config
I can interactively send or receive messages.
Once executed the command you get a prompt like
MY_PHONE_NUMBER@s.whatsapp.net [27-12-2014 18:33]:THIS IS MY MESSAGE,TYPED ON MY PHONE. OPEN DOOR GARAGE
Enter Message or command: (/available, /lastseen, /unavailable)
I'm a totally beginner, but I would like to redirect this content that gets printed on terminal to a file,to further analyze it or to write a script that search into this file keyword as "OPEN GARAGE DOOR", so i could automate something.
This file obviously has to sync with the program output,but I don't know how to do.
yowsup-cli -a --interactive <PHONE_NUMBER_HERE> --wait --autoack --keepalive --config yowsup-master/src/yowsup-cli.config > /path/to/my_file
doesn't work
Running Ubuntu 12.04.
I know yowsup is a python library, but i don't know this language. I'm beginning learniing C and I would like to do that in BASH, or if not possible in C.
Thanks
A: Pipe the output into tee instead of redirecting it into a file:
yowsup-cli -a --interactive <PHONE_NUMBER_HERE> --wait --autoack --keepalive --config yowsup-master/src/yowsup-cli.config 2>&1 | tee -a /path/to/my_file
The reason: With redirection you don't see the command's output which makes interacting with it hard.
Piping into the tee command will echo all output the the terminal and append it to given file.
Interestingly, in your command line (using redirection) you can still type blindly or even according to the yowsup-cli ouptut you read in another terminal with:
tail -f /path/to/my_file
Tail with the -f option prints the last 10 lines of the file as well as any new ouptut from the yowsup-cli command.
| |
doc_23533833
|
class Name_pairs
{
public:
Name_pairs();
void read_names(string nameOfPerson, vector <string> names);
void read_ages(vector <double> ages, double ageOfPerson, vector <string>& names);
void print();
private:
string nameOfPerson;
double ageOfPerson;
vector <string> names;
vector <double> ages;
};`
Name_pairs::Name_pairs()
{
}
Name_pairs::read_names(nameOfPerson, names)
{
while(true)
{
cout << "Please enter a name: (enter q to end) " << endl;
cin >> nameOfPerson;
if(nameOfPerson == q)
{
names.push_back(nameOfPerson);
break;
}else{
names.push_back(nameOfPerson);
}
}
}
Name_pairs::read_ages(ages,ageOfPerson, names)
{
int z =0;
while(true)
{
cout << "Please enter " << names[a] << "'s age: "
cin >> ageOfPerson;
ages.push_back(ageOfPerson);
z++;
if(ages.size()== names.size() )
{
break;
}
}
}
And then where the problem occurs is in the main function.
int main()
{
Name_pairs identifier;
identifier.read_names(string nameOfPerson, vector <string> names);
identifier.read_ages(vector <double> ages, double ageOfPerson, vector <string> names);
return 0;
}
Any help will be appreciated
A: There are numerous errors in your code. Most obvious ones are that the return type and argument types are missing in the definition of Name_pairs::read_names:
void Name_pairs::read_names(string nameOfPerson, vector <string> names) {
// ...
}
and the parameters should probably be passed by reference as correctly noticed by @Neil Kirk.
Same for read_ages.
Also you shouldn't specify types in the calls to these methods:
string nameOfPerson;
vector <string> names;
identifier.read_names(nameOfPerson, names);
| |
doc_23533834
|
Table: PATIENT_DETAIL
PATIENT_NAME(varchar),
DISEASE(varchar),
SICK_DEGREE(number),
START_TIME(date),
END_TIME(date)
There are 1000 patients in the table and each may have different diseases. Some have disease A, some have disease B and some have disease C.
Now I want to insert an record for each patient that they have a new disease D, but I want them to have different degree of sickness. The number could be ranged from 1 to 1000.
I would like to do this but they all have the some degree:
INSERT INTO PATIENT_DETAIL
SELECT PATIENT_NAME,
'DISEASE D',
(select dbms_random.value(1,1000) num from dual),
sysdate,
sysdate
1000 rows inserted.
if the code (select dbms_random.value(1,1000) num from dual) generate 500, then all patient will have sickness degree of 500, but I want them to be different.
A: You don't need to put dbms_random.value(1,1000) into a subselect. If you do, then the subselect is executed first and applied to all subsequent rows.
INSERT INTO PATIENT_DETAIL
SELECT PATIENT_NAME,
'DISEASE D',
dbms_random.value(1,1000),
sysdate,
sysdate
FROM PATIENT_DETAIL
| |
doc_23533835
|
A: You tagged your question with "Linux". Therefore I don't know if your question is Linux-specific or if you want to know a "generic" answer.
The "generic" answer:
Theoretically you can send all IPv4 messages to the Ethernet broadcast address (FF:FF:FF:FF:FF:FF) - even unicast packets.
It might be possible to send some unicast packet (such as a "ping" request) as broadcast ethernet frame (but the "destination address" in the IP packet set correctly). Then you can read out the "source MAC address" from the answer's ethernet frame.
However the receiver of the "ping" packet will probably send an ARP request to query for your IP address. So the computer querying for the MAC address has to implement ARP answers anyway.
I just tried to send a "ping" request to my WLAN router using the way I described above. The WLAN router does send an ARP request...
| |
doc_23533836
|
I'm using the last stable php version, and I want to "jail" php scripts. (I tried to chroot, but it is boring.
I would like to use open_basedir directive on php.ini, but I don't know with it's deprecated or not. I searched on Google and 99% times the page redirect to http://php.net/manual/en/features.safe-mode.php (DEPRECATED).
So my question is, Can I use this directive or not? is it sure?
Thank you really much
A: PHP Safe Mode is deprecated. open_basedir is NOT deprecated. There is a lot of overlap between what these constructs address.
A: From http://www.php.net/manual/en/ini.core.php#ini.open-basedir, so this feature doesn't rely on safe_mode.
This directive is NOT affected by
whether Safe Mode is turned On or Off.
A:
http://php.net/manual/en/ini.core.php#ini.open-basedir
There is nothing about this directive being deprecated. But restricting directory access with this does not prevent other people to see someone else code (ex using shell_exec and cat). So I would suggest to disable all functions that allows external program execution or use patch for php to allow only trusted executables from specified directory http://www.kyberdigi.cz/projects/execdir/english.html
On a side note, jail chroot is not boring, it's exciting considering how much work it requires to get all running ;)
| |
doc_23533837
|
function btnGenerate_onclick()
{
// assign textbox elements to variables for easier access
var outputTextbox = document.getElementById("txtOutput");
for(var i = 0; i < 10; i++)
{
System.out.println(Math.pow(2, Math.floor(Math.random() * 32 + 1); ));
}
outputTextbox.value = ;
}
A: Following code generates random number between 50 and 100 (Both inclusive).
final int MAX = 100;
final int MIN = 50;
.
.
.
Random r = new Random();
// nextInt is normally exclusive of the MAX value,
// so add 1 to make it inclusive
int randomNumber = r.nextInt((MAX-MIN) + 1) + MIN;
A: Math.random() gives a number between 0.0 and 1.0. If you multiply it by 32, you get a number between 0.0 and 32.0. If you want something between 8 and 32, you should do Math.random() * 24 + 8. That will give you something between 8.0 and 32.0.
A: In plain english:
Math.random returns a number between 0 and 1.
http://www.w3schools.com/jsref/jsref_random.asp
Multiply that by the range between the numbers number2-number1 to get a number that is between 0 and greatest range-1. We can call it range.
Add the lower bound number number1 to get a number that is between number1 and number2
Here is the program in plunker http://plnkr.co/edit/gXSxTl03BFTFDMVFd0YC?p=preview
var random = Math.random();
var number1 = 5.0;
var number2 = 12;
var range = number2-number1;
var rangedRandom = range*random;
var rangedRandomPlusLeast = number1+rangedRandom;
var rangedRandomPlusLeastAsInteger = Math.round(rangedRandomPlusLeast);
| |
doc_23533838
|
A: They are shown in the second page automatically.
| |
doc_23533839
|
Something like, models.py:
class Report(Document):
date_created = DateTimeField(default=datetime.utcnow())
And then in reports.py:
...
report = models.Report.objects(id=report_id).first()
report.new_attr = "New"
resp = render_template(('report.html'), report=report)
return resp
...
I want to be able to use {{ new_attr }} in the template but not .save() it to the object. So far the new attribute is not showing up in the object even when printed.
A: That should work, but why do this? Why not send the value directly to the template as a separate variable?
resp = render_template(('report.html') ,new_attr = "New", report=report)
| |
doc_23533840
|
ERROR: Caused by: The property "sonar.cs.fxcop.assembly" must be set
and the pro ject must have been built to execute FxCop rules. This
property can be automatic ally set by the Analysis Bootstrapper for
Visual Studio Projects plugin, see: http://docs.codehaus.org/x/TAA1Dg. If you wish to skip the analysis of
not built pr ojects, set the property
"sonar.visualstudio.skipIfNotBuilt".
Console log states that this property will be automatically set by Analysis Bootstrapper for Visual Studio plugin . But I am unable to find and install this plugin in sonar.
I also tried setting up the below properties in sonar . But still getting the same error
sonar.cs.fxcop.fxCopCmdPath=C:\Program Files (x86)\Microsoft Fxcop 10.0\FxCopCmd.exe
sonar.fxcop.installDirector=C:\Program Files (x86)\Microsoft Fxcop 10.0
Why the Analysis Bootstrapper plugin is not coming in the sonar plugins area?
A: If you are facing this issue, Please follow the below steps
*
*Download the package from the below URL
Analysis Bootstrapper Pluggin for Visual Studio
*Copy the sonar-visual-studio-plugin-1.2.jar file to your Sonar \extensions\plugins folder
*Restart the server and you will see the plugin in installed plugin section
A: This error also occurs if you are launching your commands from a prompt which is not a "Command Prompt for Visual Studio 2013 or higher" (http://docs.sonarqube.org/display/SONAR/Analyzing+with+SonarQube+Scanner+for+MSBuild).
| |
doc_23533841
|
<form action="update" method="post" name="update-email">
<input name="addr-0.ord" value="0" type="hidden" tabindex="3">
<input name="addr-1.ord" value="1" type="hidden" tabindex="4">
<input name="addr-2.ord" value="2" type="hidden" tabindex="5">
<tr>
<input type="submit" name="addr-0.delete" value="Delete" style="None" tabindex="8">
</tr>
<tr>
<input type="submit" name="addr-1.delete" value="Delete" style="None" tabindex="10">
</tr>
<tr>
<input type="submit" name="addr-2.delete" value="Delete" style="None" tabindex="12">
</tr>
</form>
How can I submit form with jquery.
$("update-email").submit()
This works if I use for edit button but not delete...
Any idea?
A: inside your button click event you can submit your form by its name.
try this:
$("form[name='update-email']").submit();
A: you can use buttons in form and instead of click event of each buttons submit your form via jquery.
$("input[name="addr-0.delete"]").click(function(){
submitForm('addr-0.delete')
})
$("input[name="addr-1.delete"]").click(function(){
submitForm('addr-1.delete')
})
$("input[name="addr-2.delete"]").click(function(){
submitForm('addr-2.delete')
})
function submitForm(button){
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone ;
dataString += '&button='+ button
$.ajax({
type: "POST",
url: "your_url",
data: dataStrings,
success: function() {
//success
}
});
}
A: You have one form and 3 submit button, the 3 buttons use the same action? I think the easiest way is make 3 form, with 3 differents actions, and the respective hidden input and submit button.
But, you can use simple buttons instead of submit button then attach event to all of it.
<tr>
<form action="update-0" method="post" name="update-email-0">
<input name="addr-0.ord" value="0" type="hidden" tabindex="3">
<input type="submit" name="addr-0.delete" value="Delete" tabindex="8">
</form>
</tr>
<tr>
<form action="update-1" method="post" name="update-email-1">
<input name="addr-1.ord" value="1" type="hidden" tabindex="4">
<input type="submit" name="addr-1.delete" value="Delete" tabindex="10">
</form>
</tr>
<tr>
<form action="update-2" method="post" name="update-email-2">
<input name="addr-2.ord" value="2" type="hidden" tabindex="5">
<input type="submit" name="addr-2.delete" value="Delete" tabindex="12">
</form>
</tr>
$("update-email-0").submit()
$("update-email-1").submit()
$("update-email-2").submit()
If you want to alter the submit event for any of this form you can do the next and make you custom submit from jquery:
$("form[name='update-email-0']").submit(function (e) {
e.preventDefault();
var $this = $(this);
$.ajax({
url: $this.prop("action"),
data: $this.serialize(),
type: "POST",
dataType: "html"
}).done(function (data) {
// Done here.
});
});
| |
doc_23533842
|
NSMutableArray array;
//Objective-C Code.
array = [dic valueForKey:@"Table"]; //"Table" is key in dictionary
How to write same code in Swift?
A: There is no more valueForKey: in Swift, but there is a way to use map to achieve a similar, if not same, result.
If the objects in the collection are dictionaries:
let array = dic.map { $0["table"] as? String }
If the objects in the collection are objects:
let array = dic.map{ $0.table }
If you are using Objective-C collection types like NSDictionary in your example, then like others have said, you can still continue to use valueForKey:.
let array = dic.valueForKey("table")
A: You can try this
let array: AnyObject? = dic["Table"]
A: Simple eg.
(dicDetail.valueForKey("name") as! String)
A: You can try this
var dict=NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: NSErrorPointer.null()) as NSDictionary
var temp=dict["contactname"] as String
var tem=dict.valueForKey("contactname") as String
A: You will better get the idea of how you can deal with Dictionaries in Swift
let employees = json["employees"]! as [[String : AnyObject]]
Next step is to loop the employees array and print the firstName and lastName.
Keep in mind that we are looping an array of dictionaries. Meaning that in order to get the String values from firstName and lastName we need to unwrap the optionals first:
for employee in employees {
let firstName = employee["firstName"]! as String
let lastName = employee["lastName"]! as String
println("employee: \(firstName) \(lastName)")
}
Build, run and you should see:
employee: John Doe
employee: Anna Smith
employee: Peter Jones
A: Please check this code. It might help in what you need.
var dictData = Dictionary <String,Any>()
var arrDictData = Array<Any>()
// Will store value for key in dictionary.
func storeData ( strName: String , strAge: String ) {
dictData["name"]=strName
dictData["age"]=strAge
println("dictData: \(dictData)")
storeInArray(dictData)
}
// Will store value of dictionary in array.
func storeInArray ( dict : Any ) {
arrDictData.append(dict)
println("arrDictData: \(arrDictData)")
}
// Will return count of array.
func resultArray() -> Int {
println(arrDictData.count)
return arrDictData.count
}
// This function will return value in label.
func arrDictResult( dictKey: String, rowIndex: Int) -> String {
var dataTemp = arrDictData[rowIndex] as Dictionary <String,Any>
var val = dataTemp[dictKey] as String
return val
}
| |
doc_23533843
|
Now when I open this file into 'DB Browser for SQLite', some fields are not showing properly. It contains bangle text.
This field working good
This field is not working, this is actually bangla text
| |
doc_23533844
|
Thanks.
A: Short answer: No. There is no such built-in functionality in gtest/gmock.
Long answer: There is no way to impose certain behavior on an arbitrary C++ class, especially those in C++ standard library (C++ equivalent of Ruby core library). These are two fundamentally different languages. Ruby is a "message oriented" language, all objects respond to messages. Such concept does not exist in C++, so there is not way to achieve the behavior you desire.
| |
doc_23533845
|
Below is the code:-
using UnityEngine;
using System.Collections;
using Vuforia;
public class CameraFocus : MonoBehaviour {
bool FocusModeSet;
void Awake()
{
//CameraDevice.Instance.SetFocusMode (CameraDevice.FocusMode.FOCUS_MODE_CONTINUOUSAUTO);
FocusModeSet = CameraDevice.Instance.SetFocusMode (
CameraDevice.FocusMode.FOCUS_MODE_CONTINUOUSAUTO);
if (FocusModeSet == false)
{
Debug.Log ("to set focus mode Failed (mode unsupported) ().");
}
}
}
Can someone help with this?
A: I had a similar problem. I created script, which is setting Camera Focus Mode in a specific Vuforia states. You can take a look on my sample code below:
public class CameraController : MonoBehaviour {
void Start() {
VuforiaBehaviour.Instance.RegisterVuforiaStartedCallback(OnVuforiaStarted);
VuforiaBehaviour.Instance.RegisterOnPauseCallback(OnVuforiaStarted);
}
private void OnVuforiaStarted() {
CameraDevice.Instance.SetFocusMode(
CameraDevice.FocusMode.FOCUS_MODE_CONTINUOUSAUTO);
}
I pin this script to the standard ARCamera object.
| |
doc_23533846
|
Files copied from FTP need to be "imported" into Kentico. If they were separated by folders/sub folders, you have to go to every single folder and "import" that folder's files.
I should not have to use Kentico API to do this simple task.
A: I am afraid but the search is looking into the current folder only. You can send a request to productmanagement@kentico.com as a feature request.
For the import - I see your point but there could be also the opposite need - what if someone wants to import only certain files from certain folder(s). It is the same as if you would upload the files through the UI - you need to do it per folder. But I hear what you are saying maybe there could be some setting for this. Again, you can send the feature request directly to the product managers.
| |
doc_23533847
|
Code:
productsTableAdapter pta = new productsTableAdapter();
pta.Fill(dataset.products);
productsDataTable pdta = pta.GetDataByInvoiceID(invoiceID);
InvoiceProductsDataGrid.ItemsSource = pdta.DefaultView;
InvoiceProductsDataGrid.Columns[0].Visibility = Visibility.Hidden;
InvoiceProductsDataGrid.Columns[4].Visibility = Visibility.Hidden;
InvoiceProductsDataGrid.Columns[5].Visibility = Visibility.Hidden;
InvoiceProductsDataGrid.Columns[6].Visibility = Visibility.Hidden;
InvoiceProductsDataGrid.Columns[7].Visibility = Visibility.Hidden;
InvoiceProductsDataGrid.Columns[8].Visibility = Visibility.Hidden;
InvoiceProductsDataGrid.Columns[10].Visibility = Visibility.Hidden;
InvoiceProductsDataGrid.Columns[11].Visibility = Visibility.Hidden;
InvoiceProductsDataGrid.Columns[12].Visibility = Visibility.Hidden;
InvoiceProductsDataGrid.Columns[13].Visibility = Visibility.Hidden;
A: As pointed out by @trapspring, it sounds like pdta comes back empty. In which case, something like this could come in handy.
int[] colsToHide = { 0, 4, 5, 6, 7, 8, 10, 11, 12, 13 };
int pointer = 0;
//Hide for as long as the desired column index exists
//Which means the order you put the indices in colsToHide
//DOES affect the results of the while loop.
while (colsToHide[pointer] < InvoiceProductsDataGrid.Columns.Count)
{
InvoiceProductsDataGrid.Columns[colsToHide[pointer]].Visibility = Visibility.Hidden;
}
A: So the answer was, that i was trying to hide something that i havd to remove and the code is this
productsTableAdapter pta = new productsTableAdapter();
pta.Fill(dataset.products);
productsDataTable pdta = pta.GetDataByInvoiceID(invoiceID);
pdta.Columns.Remove("client_id");
pdta.Columns.Remove("id1");
pdta.Columns.Remove("units");
pdta.Columns.Remove("provider");
pdta.Columns.Remove("sub_categorie");
pdta.Columns.Remove("id_invoice");
pdta.Columns.Remove("id_product");
pdta.Columns.Remove("invoice_date");
pdta.Columns.Remove("collection_method");
InvoiceProductsDataGrid.ItemsSource = pdta.DefaultView;
| |
doc_23533848
|
Code goes here!
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
margin: EdgeInsets.only(bottom: 200.0),
child: Center(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 10.0),
child: Text(
_text,
style: TextStyle(color: Colors.white),
),
),
),
),
A: reduce margin, margin takes much of space
Column( mainAxisAlignment: MainAxisAlignment.center,
children: [ Container( margin: EdgeInsets.only(bottom: 15.0),
child: Center(
child: Padding( padding: EdgeInsets.symmetric(horizontal: 10.0),
child: Text( _text, style: TextStyle(color: Colors.white), ), ), ), ),
| |
doc_23533849
|
public Task GetWaitingOrdersCount(string id, string clientId)
{
DateTime today = Util.getCurrentDateTime();
var data = 10
return Clients.Client(Context.ConnectionId).loadOrders(data);
//return data;
}
In the above code, I want to send 'data' to the 'clientId' passed to this method.
BUT I m having an error in this line
return Clients.Client(Context.ConnectionId).loadOrders(data);
And the error is
'System.Threading.Tasks.Task<object>' does not contain a definition for 'loadOrders'
the client side code
con.loadOrders = function (data) {
loadOrders(data);
};
function loadOrders(data) {
$('#totalOrders').html(data);
}
Any help about the error???
EDIT:
This is my full client code..
<script type="text/javascript">
var con;
$(document).ready(function () {
con = $.connection.messagingHub;
$.connection.hub.start(function () {
var myClientId = $.connection.hub.id;
con.getWaitingOrdersCount('<%:ViewBag.rid%>',myClientId).done(function (data) {
console.log(data);
});
});
con.client.loadOrders = function (data) {
loadOrders(data);
};
});
function loadOrders(data) {
$('#totalOrders').html(data);
A: I just tried out your code (slightly modified) and it works fine for me. What version of SignalR are you using? Judging by your server code I'd say 1.0Alpha1+ but your client code looks more like 0.5.3, that is unless your con object is assigned to $.connection.yourhub.client;
If you update to SignalR 1.0Alpha2 and change your client code to be:
var con = $.connection.myCon;// This is arbitrary and would change based on your naming
con.client.loadOrders = function (data) {
loadOrders(data);
};
function loadOrders(data) {
$('#totalOrders').html(data);
}
That being said I believe your issue has to do with the version of SignalR you are using, server side that is: since you're receiving a task oriented error. Another piece of information that might be beneficial would be to know how GetWaitingOrdersCount is being called. Aka is it being invoked from the client directly via: con.server.getWaitingOrdersCount or is it being called from within the hub.
Hope this info helps!
| |
doc_23533850
|
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:title="@string/DateTimePreferencesTitle">
<CheckBoxPreference android:key="cb_pref"
android:title="@string/cb_pref_title"
android:summaryOn="@string/summaryOn"
android:summaryOff="@string/summaryOff"
/>
.
.
.
<PreferenceScreen
android:fragment="com.trimble.ag.amaethon.preferences.ZonePicker"
android:key="timezone"
android:title="@string/date_time_set_timezone"
android:summary="GMT-8:00"
/>
</PreferenceScreen>
The ZonePicker fragment extends ListFragment. I am trying to find a way to get at the above PreferenceScreen element and change the android:summary value from within the ZonePicker fragment.
Any ideas?
| |
doc_23533851
|
These are emails received from the Ubuntu security mailing list. Somehow they produce weird  characters throughout the text, while reading the email with alpine seems to decode it just fine.
Here is one snippet from the email after it's been decoded:
 Felix Wilhelm, Fermin J. Serna, Gabriel Campana and Kevin Hamacher
 discovered that Dnsmasq incorrectly handled DNS requests. A remote
 attacker could use this issue to cause Dnsmasq to crash, resulting in
 a denial of service, or possibly execute arbitrary code.Â
 (CVE-2017-14491)`
Here is the code snippet I'm using for this:
use MIME::Parser;
use MIME::Entity;
use MIME::WordDecoder;
use MIME::Tools;
use MIME::Decoder;
use Email::MIME;
my $parser = MIME::Parser->new;
$parser->extract_uuencode(1);
$parser->extract_nested_messages(1);
$parser->output_to_core(1);
my $buf;
while(<STDIN> ){
$buf .= $_;
}
my $entity = $parser->parse_data($buf);
my $subject = $entity->head->get('Subject');
my $from = $entity->head->get('From');
my $AdvDate = $entity->head->get('Date');
my @mailData;
my $msg = Email::MIME->new($buf);
$msg->walk_parts(sub {
my ($part) = @_;
#warn($part->content_type . ": " . $part->subparts);
if (($part->content_type =~ /text\/plain$/i) && !@mailData) {
#print $part->body;
@mailData = split( '\n', $part->body);
}
elsif (($part->content_type =~ /text\/plain; charset=\"?utf-8\"?/i) && !@mailData) {
#print $part->body;
@mailData = split( '\n', $part->body);
}
elsif (($part->content_type =~ /text\/plain; charset=\"?us-ascii\"?/i) && !@mailData) {
#print $part->body;
@mailData = split( '\n', $part->body);
}
elsif (($part->content_type =~ /text\/plain; charset=\"?windows-1252\"?/i) && !@mailData) {
#print $part->body;
@mailData = split( '\n', $part->body);
}
elsif (($part->content_type =~ /text\/plain; charset=\"?iso-8859-1\"?/i) && !@mailData) {
#print $part->body;
@mailData = split( '\n', $part->body);
}
});
Later I do various operations on $buf before writing it to a database.
I've placed a copy of one of the emails that exhibit this problem here
https://pastebin.com/raw/2csUvWup
Please let me know what other information I can provide to properly decode this email.
A: Unfortunately, the example you link to does not match the example you embed in your question. Also, your code does not show where and how exactly the output is done, i.e. you don't provide a Minimal, Complete, and Verifiable example but instead only show fragments which might indicate what you are doing but don't actually show what you are doing.
Based on this I can only guess what the problem is but not verify this guess. My guess is that the problem lies in your use of Email::MIME::body instead of Email::MIME::body_str. As documented body "decodes and returns the body of the object as a byte string" while body_str "decodes both the Content-Transfer-Encoding layer of the body (like the body method) as well as the charset encoding of the body (unlike the body method), returning a Unicode string".
In other words, body provides you with the raw octets of the UTF-8 encoded message, body_str instead provides you with the characters. And the last one is probably what you actually want.
| |
doc_23533852
|
A: You can target the selected options css through the customization points.
...
const useStyles = makeStyles((theme) => ({
option: {
background: "white",
"&:hover": {
background: "red"
},
'&[aria-selected="true"]': {
background: "blue"
}
}
}));
<Autocomplete
...
classes={{
option: classes.root
}}
/>
Live Demo
A: <Autocomplete
...
classes={{
option: classes.root --> option
}}
/>
| |
doc_23533853
|
ChunkLoadError: Loading chunk dashboard-dashboard-module failed.
I have 2 Modules as below:
*
*dashboard module
*product module
Below is my app.routing.ts
const routes: Routes = [
{ path: 'product', loadChildren: () => import('./product/product.module').then(m => m.ProductModule),
canActivate: [LoggedInGuard] },
{ path: 'dashboard', loadChildren: () => import('./dashboard/dashboard.module').then(m =>
m.DashboardModule) }
];
My product module has it's own routing which is as below:
const routes: Routes = [{ path: 'test', component: TestProductComponent }];
If I click on the product navigation where the routerlink is: product/test, it correctly loads the testproduct component.
Note: the url for the above is: localhost:4200/product/test
However if I try to navigate back to the dashboard, it takes the path as:
localhost:4200/product/dashboard , instead of localhost:4200/dashboard.
Did I miss out anything from the above and how can I fix this?
A: How are you navigating back? If there is a back button the use of routerLink might be missing a backslash.
<a [routerLink]="['dashboard']">Back</a> // localhost:4200/product/dashboard
<a [routerLink]="['/dashboard']">Back</a> // localhost:4200/dashboard
| |
doc_23533854
|
https://github.com/fraywing/textAngular/wiki/Customising-The-Toolbar
It says that to change the TextAngular toolbar options you need to do the following:
<text-angular ta-toolbar="[['h1','h2','h3'],['bold','italics']]"></text-angular>
I thought that my environment is being strange, so I set up a Plunker, however over there it does the same:
http://plnkr.co/edit/VcLGzFRm9AGF4AC6S7Co?p=preview
Index.html Row 23 - This works properly.
Index.html Row 26 - This doesn't work even though the above documentation suggests it should.
Can someone please help me with this - how can I choose which options the toolbar will have? :/
A: It's working, you just need to remove that $interpolateProvider:
var app = angular.module('adminApp', ['textAngular'], function($interpolateProvider) {
$interpolateProvider.startSymbol('[[');
$interpolateProvider.endSymbol(']]');
});
becomes just this:
var app = angular.module('adminApp', ['textAngular']);
Then you can use:
<text-angular ta-toolbar="[['h1','h2','h3'],['bold','italics']]"></text-angular>
A snippet working:
var app = angular.module('adminApp', ['textAngular']);
<html ng-app="adminApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/textAngular/1.5.0/textAngular-rangy.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/textAngular/1.5.0/textAngular-sanitize.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/textAngular/1.5.0/textAngular.min.js'></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/textAngular/1.5.1/textAngular.css">
</head>
<body>
<text-angular ta-toolbar="[['h1','h2','h3'],['bold','italics']]"></text-angular>
</body>
</html>
| |
doc_23533855
|
Here is my Adapter:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return 500;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some
// attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(75, 75));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(R.drawable.sample_0);
return imageView;
}
}
A: In getCount you could divide the area of the screen by the area of the squares you're filling it with.
public int getCount() {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int area = size.x * size.y;
// TODO: you may want to pass in the square dimensions or make them constants
return area / (75 * 75);
}
Of course, this isn't right, since it uses the display and not the parent ViewGroup. Instead of trying to do this all in the adapter, have the constructor for this take in the dimensions of the parent and do the math there, saving an instance variable with the count:
private int numBoxes = 0;
private static final SQUARE_SIZE = 75;
public ImageAdapter(Context c, ViewGroup parent) {
mContext = c;
numBoxes = (parent.getWidth() * parent.getHeight()) / (SQUARE_SIZE * SQUARE_SIZE);
}
public int getCount() {
return numBoxes;
}
A: Expanding on the answer by Nick White, you need to make sure the parent layout has been laid out before you can get the height and width. If the parent width and/or height are "wrap_content" or "match_parent", the getHeight() and getWidth() will return zero in the adapter's constructor, if the adapter is being created in the Activity onCreate().
This answer gives a way to listen for onLayout events and handle sizing. I did try to do something similar, but I found the results in my case were less than perfect, as the grid would draw then redraw after I applied the size changes. So far the best results I've had with grid sizing is to use qualified resource values to size the image views inside the grid. The resource size value is then set according to the screen density or size by creating various values in values-xxx resource folders.
In my case, I was altering the size of the cell images to make a certain number fit the screen by applying something like:
Integer size = getResources().getInteger(R.int.image_size));
imageView.setLayoutParams(new GridView.LayoutParams(size, size));
It should be possible to do something similar to calculate the number of columns for the screen size.
| |
doc_23533856
|
The problem is that I don't know why one of my PHP variables is working while the other is not.
The problem I am running into is within the last if statement; the $check variable is not being printed, however when replaced it with another variable $pin, it worked.
Code
</header>
<head>
<h1> MD5 cracker</h1>
</head>
<body>
<p>This application takes an MD5 hash of a four digit pin and check all 10,000 possible four digit PINs to determine the PIN.</p><br/>
<p id='deb'>Debug Output:<br/></p>
<p id='pin'>PIN: Not found </p>
<form method='POST'>
<input type='text' name='md5' value="">
<input type='submit' value='Crack MD5'>
</form>
<?php
$count=0;
$pin_list=array();
$pin_digits=array(0,1,2,3,4,5,6,7,8,9);
if (isset($_POST['md5'])) {
$md5= $_POST['md5'];
foreach ($pin_digits as $d1){
foreach ($pin_digits as $d2){
foreach ($pin_digits as $d3){
foreach ($pin_digits as $d4){
$pin= $d1 . $d2.$d3.$d4;
$check=hash('md5',$pin);
if ( $check==$md5){
echo "<script>
document.getElementById('pin').innerHTML='PIN: '+$pin;
</script>";
break;
}
if ($count<15) {
echo "<script>
document.getElementById('deb').innerHTML=$check;
</script>";
$count+=1;
}
}
}
}
}
}
?>
</body>
A: Try this, you forget quotes on .innerHTML='$check';
<body>
<p>This application takes an MD5 hash of a four digit pin and check all 10,000 possible four digit PINs to determine the PIN.</p><br/>
<p id='deb'>Debug Output:<br/></p>
<p id='pin'>PIN: Not found </p>
<form method='POST'>
<input type='text' name='md5' value="">
<input type='submit' value='Crack MD5'>
</form>
<?php
$count=0;
$pin_list=array();
$pin_digits=array(0,1,2,3,4,5,6,7,8,9);
if (isset($_POST['md5'])) {
$md5= $_POST['md5'];
foreach ($pin_digits as $d1){
foreach ($pin_digits as $d2){
foreach ($pin_digits as $d3){
foreach ($pin_digits as $d4){
$pin= $d1 . $d2.$d3.$d4;
$check=hash('md5',$pin);
if ( $check==$md5){
echo "<script>
document.getElementById('pin').innerHTML='PIN: '+$pin;
</script>";
break;
}
if ($count<15) {
echo "<script>
document.getElementById('deb').innerHTML='$check';
</script>";
$count+=1;
}
}
}
}
}
}
?>
</body>
A: JS code should be like document.getElementById('str').innerHTML = 'string';, so update your php source then everything ok. Like
echo "<script>document.getElementById('pin').innerHTML='PIN: {$pin}';</script>";
echo "<script>document.getElementById('deb').innerHTML='{$check}';</script>";
| |
doc_23533857
|
Our app currently forces the browser document mode to be IE7 using an IIS header, as we have some old code / Silverlight stuff, where the code looked odd if we didn't. This was implemented when IE7 went to IE8 and has never been turned off. I am trying to remove this IIS header, so that our application will run in the latest browsers.
When I removed the IIS header and started testing, I noticed that our tabs were not showing up anymore in IE9 (they were showing up in Chrome and Firefox fine though). At first I thought it was CSS, but taking the CSS out didn't help. So I took out the code for the tabstrip and put it in a new blank project. They still did not show up in IE9.
I changed the document mode in IE9 to be Quirks mode, IE7, IE8 and the tabs showed up fine in IE. I changed the document mode to IE9 and the tabs are just not showing up. They are in the page when I "view source" on the page, but do not display on screen.
Any one come across this and solve it? Any ideas?
Code from my test project below. In IE, press F12 switch to IE7 and tabs show, switch to IE9 and tabs no longer show up.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" inherits="WebControlsTestApp.WebForm1" %>
<%@ Register TagPrefix="tabs" Namespace="Microsoft.Web.UI.WebControls" Assembly="Microsoft.Web.UI.WebControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<p>This is before the tabs</p>
<div id="trTabs" runat="server">
<tabs:TabStrip id="ctrlTabs2" autopostback="true" runat="server"
TabSelectedStyle="padding:4px 12px 4px 12px;background-color:red;color:blue;font-family:Calibri,'Lucinda Grande',Helvetica,Sans-Serif;font-size:14px;font-weight:bold;border-right:2px solid #d9d9d9;border-top:2px solid #d9d9d9;border-bottom:2px solid #ffffff;text-decoration:none;"
TabDefaultStyle="padding:4px 12px 4px 12px;background-color:red;color:blue;font-family:Calibri,'Lucinda Grande',Helvetica,Sans-Serif;font-size:14px;font-weight:bold;border-right:2px solid #d9d9d9;border-top:2px solid #d9d9d9;border-bottom:2px solid #d9d9d9;text-decoration:none;" >
<tabs:Tab Text="To Review" />
<tabs:Tab Text="Past Reviews" />
<tabs:Tab Text="I Own" />
</tabs:TabStrip>
</div>
<p>This is after the tabs</p>
</form>
</body>
</html>
| |
doc_23533858
|
pub struct Gamepad {
str: String,
}
pub enum Player {
Human(Gamepad),
Computer,
}
pub struct PlayerData {
pub player: Player, /* actually this should be private */
}
struct Pong {
players: Vec<PlayerData>,
}
fn update_game(_pong: &mut Pong) {}
fn main() {
println!("Hello, world!");
let mut pong = Pong {
players: vec![
PlayerData {
player: Player::Computer,
},
PlayerData {
player: Player::Human(Gamepad {
str: "mydev".to_string(),
}),
},
],
};
game_loop(&mut pong);
}
fn game_loop(pong: &mut Pong) {
let mut vec: Vec<&Gamepad> = Vec::new();
{
for playerdata in pong.players.iter() {
match playerdata.player {
Player::Human(ref gp) => {
if gp.str == "mydev" {
vec.push(gp); //omitting this line of code fixes borrow checker issues
}
}
_ => {}
}
}
}
update_game(pong);
}
playground
This gives:
error[E0502]: cannot borrow `*pong` as mutable because `pong.players` is also borrowed as immutable
--> src/main.rs:52:17
|
41 | for playerdata in pong.players.iter() {
| ------------ immutable borrow occurs here
...
52 | update_game(pong);
| ^^^^ mutable borrow occurs here
53 | }
| - immutable borrow ends here
While I can understand the error to some extent, but coming from a C and Java background, I really struggle to get out of this problem. I am mainly confused why the immutable borrow is not released after the for loop ends. How would you write this in idiomatic Rust?
A: The error is a bit poorly worded, but I see your problem.
The error says the immutable borrow occurs in the for loop, which isn't quite correct. Instead, it occurs on the line you marked: vec.push(gp).
gp is an immutable reference to an object contained within pong.players. When you exit the loop, there is no immutable reference to pong.players itself, but there is a vector full of references to objects inside that vector.
pong.players : [ a, b, c, d, e]
^ ^ ^ ^ ^
vec : [&a, &b, &c, &d, &e]
Since you have outstanding immutable references to objects within pong.players, Rust has to consider pong.players as "implicitly" immutably borrowed, to ensure that none of its contents are mutated while there is still an immutable reference to that item. Since pong.players is a component of pong and is "implicitly" borrowed, pong itself has to be "implicitly" borrowed immutably as well.
In other words, the borrow of pong in game_loop lasts as such:
fn game_loop(pong: &mut Pong) {
let mut vec: Vec<&Gamepad> = Vec::new(); // <+ `vec`'s lifetime begins here
{ // |
for playerdata in pong.players.iter() { // <+ `pong.players.iter()` temporarily immutably borrows
// | `players` from `pong` for the iterator. `playerdata`
// | is a borrowed portion of `pong.players`.
// | As long as any `playerdata` exists, `pong.players`
// | is immutably borrowed by extension.
match playerdata.player { // <+ `playerdata.player` is a portion of `playerdata`.
Player::Human(ref gp) => { // <+ `gp` is a borrow of an element of `playerdata`.
if gp.str == "mydev" { // |
vec.push(gp); // <! At this point, `gp` is added to `vec`.
// | Since `gp` is inside `vec`, the reference to `gp`
// | is not dropped *until `vec` is dropped.
} // |
} // <- `gp`'s *lexical* lifetime ends here, but it may still
// | be inside `vec`. Any `gp` added to `vec` is still
// | considered borrowed.
_ => {} // |
} // <- `playerdata.player` is not longer lexically borrowed.
// | However, since `gp`, a portion of `playerdata.player`,
// | may still be borrowed, the compiler flags
// | `playerdata.player` as still borrowed.
} // <- `playerdata`'s borrow scope ends here, but since
// | `playerdata.player` may still be borrowed (due to the
// | fact that `vec` may contain references to elements of
// | playerdata.player), `playerdata` is still considered borrowed
} // <- the iterator over `pong.players` is dropped here. But since
// | `playerdata` might still be referenced in `vec`, `pong.players`
// | is still considered borrowed... and since `pong.players` is
// | implicitly borrowed, `pong` is implicitly borrowed.
update_game(pong); // <! When you reach this line, `pong` is implicitly borrowed because
// | there are references to something 'inside' it. Since you can't
// | have an immutable borrow and a mutable borrow at the same time
// | (to ensure you can't change something at the same time another
// | part of the program views it), `update_game(pong)` cannot accept
// | a mutable reference to `pong`.
} // <- At this point, `vec` is dropped, releasing all references to the
// | contents of `pong`. `pong` is also dropped here, because it is the
// | end of the function.
That explains the why. As for the how to solve it: Theoretically, the easiest solution would be to implement Clone on Gamepad (which can be easily done with #[derive(Clone)] if all of Gamepad's fields implement clone; the standard implementation is basically creating a new object by calling .clone on all of the fields of the original) and then use gp.clone() rather than just gp.
This has a (probably negligible) impact on the memory use of your program, but moreover, it can be infeasible if Gamepad uses external-library types that do not implement Clone - you can't implement Clone on those external types, because you don't define Clone or SomeExternalType in your project.
If impl Clone isn't available to you, you may need to refactor your code; reconsider why you need certain mutable or immutable borrows, and remove them if they're unnecessary. If that fails, you might need to look into other types of pointers like Cell, which I'm not qualified to give information about!
If you don't need to keep vec around and do stuff with it after update_game is called, consider this solution:
fn game_loop(pong: &mut Pong) {
{
let mut vec: Vec<&Gamepad> = Vec::new(); // <+ Vec is created
for playerdata in pong.players.iter() { // |
match playerdata.player { // |
Player::Human(ref gp) => { // |
if gp.str == "mydev" { // |
vec.push(gp); // |
} // |
} // |
_ => {} // |
} // |
} // |
for g_pad in vec { // |
// Do something with each gamepad // |
} // |
} // <- `vec` is dropped
// Since `vec` no longer exists, there are no more references
// to the contents of `pong`, and `update_game` can be called.
update_game(pong);
}
Hope this helps.
| |
doc_23533859
|
If I open a new tab, I get the behavior I expected on start:
Here are my profiles:
What keeps my real default from loading on start?
A: I had a similar problem and it was caused by an "Arrangement" setup that was loaded with iTerm. Once I removed that the default profile would load correctly =D
| |
doc_23533860
|
Invoke-WebRequest https://cakebuild.net/download/bootstrapper/windows -OutFile build.ps1
No changes of my own in that file. And my build.cake looks like this:
var configuration = "Release";
var buildPath = $"CakeEnvDemo/bin/{configuration}";
var buildDir = Directory(buildPath);
var solution = "CakeEnvDemo.sln";
Task("Clean")
.Does(() =>
{
Information("Running Clean ...");
CleanDirectory(buildDir);
});
Task("NuGetRestore")
.IsDependentOn("Clean")
.Does(() =>
{
Information("Running NuGetRestore ...");
NuGetRestore(solution);
});
Task("Build")
.IsDependentOn("NuGetRestore")
.Does(() =>
{
MSBuild(solution, settings => settings.SetConfiguration(configuration));
});
Task("AfterBuild")
.IsDependentOn("Build")
.Does(() =>
{
Information("Running After Build ...");
var cakeEnv = EnvironmentVariable("cake_env", "default value");
Information($"Got value of cake_env from environment: {cakeEnv}");
});
RunTarget("AfterBuild");
Take a look at the "AfterBuild" Task. Basically, I want to read an environment variable after the build is complete and do something with it. However, not matter what I do, cake doesn't seem to be able to pick it up and instead always uses the default value I provide.
Based on the docs here, I'm assuming that something like this:
$cake_env="actual env var value"
.\build.ps1
should work, but it never does. I always get the default value:
========================================
AfterBuild
========================================
Running After Build ...
Got value of cake_env from environment: default value
I do NOT want to use arguments, so please don't recommend ScriptArgs. I want environment variables.
A: This:
$cake_env="actual env var value"
Is setting a local PowerShell variable, not an environment variable.
You should be able to use:
$env:cake_env="actual env var value"
| |
doc_23533861
|
* Running VirtualBox in a Xen environment is not supported
EC2 uses xen virtualization. On the other hand, its working fine on Windows Azure Virtual Machines which uses a customized version of Hyper-V.
So,cant we use virtualbox in Xen but in Hyper-V?
A: Are you sure that HyperV allow you to start the VM, I don't think this is possible using current hardware VT technology without slow painful emulation instead of virtualization.
| |
doc_23533862
|
I have these tables:
Modules
- name (pk)
- status_id (fk references status(id))
Status
- id (pk)
- name
So in Module I declare relations:
public function relations()
{
return array(
'status'=>array( self::HAS_ONE, 'Status', 'status_id' ),
);
}
However this doesn't work, each status is NULL.
query executed by Yii:
SELECT `t`.`name` AS `t0_c0`, `t`.`status_id` AS `t0_c1`, `t`.`session_limit` AS `t0_c2`, `status`.`id` AS `t1_c0`, `status`.`name` AS `t1_c1` FROM `ss_module` `t` LEFT OUTER JOIN `ss_module_status` `status` ON (`status`.`id`=`t`.`name`)
+------------+-------+-------+-------+-------+
| t0_c0 | t0_c1 | t0_c2 | t1_c0 | t1_c1 |
+------------+-------+-------+-------+-------+
| digidoc | 2 | 0 | NULL | NULL |
| docusearch | 1 | 2 | NULL | NULL |
| printbox | 2 | 0 | NULL | NULL |
+------------+-------+-------+-------+-------+
I have a problem understanding if the constants apply to the relationed model or the current model, example Module HAS_ONE Status or if should be status BELONGS_TO a Module.
Note that BELONGS_TO does work, so maybe I am answering myself but I would like some advice on how to better understand relations, because in the YII Guide examples, a user HAS_ONE Profile, so isn't it the same as user HAS_ONE status?
http://www.yiiframework.com/doc/guide/1.1/en/database.arr#declaring-relationship
Thanks a lot.
A: You have declared the relation in both models incorrectly, then it has given the unexpected result. Currently what your code did is select all of records from parent table (Status) regardless whether it has children (Module) or not rather than versa.
While the FK was in Module, not Status, it should be
Module BELONG_TO Status
Status HAS_ONE Module (this is special case of HAS_MANY where Status has at most one Module)
I understood your confusing around, the answer that I think it would help you clear out your mind
http://www.yiiframework.com/wiki/181/relations-belongs_to-versus-has_one/
| |
doc_23533863
|
I've been building towards this and everything was going okay until I actually tried to retrieve the value in the column.
The problem occurs when I try to set @CurrentValue. The top 1 code is just temporary until I later extend the code but this is not the problem. In testing this I discovered that it errors when trying to make use of @TableName from the inner while loop.
Must declare the table variable "@TableName".
I'm not an expert with procedural Transact SQL. Is there a way I can access this variable from this location?
--Edit following config lines as necessary
USE mytable
DECLARE @SchemaName SYSNAME = 'dbo'
DECLARE @TableName SYSNAME
DECLARE TableCursor CURSOR FOR
SELECT t.name
FROM sys.tables AS t
INNER JOIN sys.schemas AS s
ON t.[schema_id] = s.[schema_id]
WHERE s.name = @SchemaName
and lower(t.name) like 'online%';
OPEN TableCursor
FETCH NEXT FROM TableCursor
INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT '-----'
PRINT @TableName
PRINT '-----'
DECLARE MatchingColumns CURSOR LOCAL FOR
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = @TableName
AND
DATA_TYPE in ('nvarchar', 'varchar', 'ntext', 'text', 'nchar', 'char');
DECLARE @ColumnName NVARCHAR(MAX)
OPEN MatchingColumns
FETCH NEXT FROM MatchingColumns
INTO @ColumnName
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE @CurrentValue NVARCHAR(MAX)
set @CurrentValue = (
select top 1 @ColumnName
from @TableName
)
PRINT @ColumnName
FETCH NEXT FROM MatchingColumns
INTO @ColumnName
END
CLOSE MatchingColumns
DEALLOCATE MatchingColumns
FETCH NEXT FROM TableCursor
INTO @TableName
END
CLOSE TableCursor
DEALLOCATE TableCursor
A: Replace
set @CurrentValue = (
select top 1 @ColumnName
from @TableName
)
ON
declare @cmd nvarchar(200)
set @cmd = N'SELECT TOP 1 @CurrentValue=' + @ColumnName + ' from ' + @TableName
EXECUTE @CurrentValue = sp_executesql @cmd, N'@CurrentValue VARCHAR(MAX)', @CurrentValue OUT
| |
doc_23533864
|
From my understanding this is to keep the fragments loosely coupled from each other. However,
*
*Is this also the case for nested fragments? I can imagine it might make sense for a nested fragment to report directly to it's parent fragment instead of the Activity.
*If a nested fragment has its parent fragment implement it's listener, how would one (or should one) require the parent fragment to do this. In other words, is a similar to the paradigm to the following but for Fragments:
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
A: If anyone wanted an example of an implementation that ensures parent context implements the callbacks while not caring whether it is an activity or fragment, the following worked for me:
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Callbacks) {
mCallbacks = (Callbacks) context;
} else {
if (getParentFragment() != null && getParentFragment() instanceof Callbacks) {
mCallbacks = (Callbacks) getParentFragment();
} else {
throw new RuntimeException(context.toString()
+ " must implement " + TAG + ".Callbacks");
}
}
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
Enjoy!
A: As long as you define an interface in the fragment, you can have the parent activity or parent fragment implementing it. There is no rule that says fragment should not implement interface of a child fragment. One example where this make sense is that fragment A has two children Fragments B, C. A implements B's interface, when A gets a call back, it might need to update fragment C. Exactly the same thing with activity, just different level.
A: You can implement the same pattern for child/parent interactions using getParentFragment(). The parent fragment refers to whichever fragment has this one added through its ChildFragmentManager. If this Fragment is attached directly to an Activity, this method returns null.
| |
doc_23533865
|
The Problem is, if I enter a wrong or no parameter I get a Syntax error instead of the Usage echo.
"-v" cannot be processed syntactically at this Point.
@ECHO OFF
SETLOCAL EnableDelayedExpansion
set v=False
set q=False
if %1 EQU -v (
set v=True
) else (
if %1 EQU -q (
set q=True
) else (
ECHO %DATE:~-4%%DATE:~-7,2%%DATE:~-10,2%_%Time% WARN False Parameter %1 >> C:\Users\Jeff\Desktop\%DATE:~-4%%DATE:~-7,2%%DATE:~-10,2%_Log_2.34.log
REM Usage
echo Usage [-v] for verbose mode
echo [-q] for quiet mode
echo.
pause
goto EOF
)
)
A: Ok, I found the answer.
@ECHO OFF
SETLOCAL EnableDelayedExpansion
set v=False
set q=False
if /i "%~1" EQU "-v" (
set v=True
) else (
if /i "%~1" EQU "-q" (
set q=True
) else (
ECHO %DATE:~-4%%DATE:~-7,2%%DATE:~-10,2%_%Time% WARN False Parameter %1 >> C:\Users\Jeff\Desktop\%DATE:~-4%%DATE:~-7,2%%DATE:~-10,2%_Log_2.34.log
REM Usage
echo Usage [-v] for verbose mode
echo [-q] for quiet mode
echo.
pause
goto EOF
)
)
/i will accept two words in %1 and will not fail if %1 is empty.
| |
doc_23533866
|
What is wrong?
$r = $db->parseAndExecute("SELECT USERSS.ID, USERNAME, PASSWORD, SCHVALENO"
. " FROM USERSS JOIN ZPATECNI ON ZPATECNI.ID_OSOBA = USERSS.ID WHERE ADMIN = 'NO'");
while (($row = oci_fetch_array($r, OCI_ASSOC + OCI_RETURN_LOBS)) != false) {
echo $row['ID'];
echo $row['USERNAME'];
echo $row['PASSWORD'];
echo $row['SCHVALENO'];
}
A: You can try the following:
SELECT USERSS.ID,
USERSS.USERNAME,
USERSS.PASSWORD,
USERSS.SCHVALENO
FROM USERSS
JOIN ZPATECNI ON ZPATECNI.ID_OSOBA = USERSS.ID
WHERE ADMIN = 'NO'"
| |
doc_23533867
|
Here is the code:
fdlg = wx.FileDialog(self.panel_settings, "Input setting file path", "", "", "CSV files(*.csv)|*.*", wx.FD_SAVE)
if fdlg.ShowModal() == wx.ID_OK:
self.save_path = fdlg.GetPath() + ".csv"
with open(self.save_path, "wb") as file:
writer = csv.writer(file, delimiter = ',')
When a dialog pops up, I simply type in test as the file name. As I click OK button, it directly save an empty test.csv file.
However, what I want to do is just keep the input path and file name, then write the content myself.
So, may I know how to work around this?
Thanks.
A: wx.FileDialog does not create the file, it returns the path. You are creating the file with this code:
with open(self.save_path, "wb") as file:
writer = csv.writer(file, delimiter = ',')
| |
doc_23533868
|
modelBuilder.Entity<SomeClass>().MapToStoredProcedures()
to generate stored procedures and altered SPs as per my need,now the problem is i am not able to use a custom SP (with some filter) for fetching the data for index action .
every suggestion will be appreciated
| |
doc_23533869
|
here is my code
import json
import urllib
results = json.load(urllib.urlopen("https://www.kimonolabs.com/api/adgmajn2?apikey=L63EvSC1x5vG8iSbm9Jon3784mkDp1Or"))
parse_result = json.loads(results)
print parse_result
And here is json data format
{
"name": "google_test",
"count": 20,
"frequency": "Manual Crawl",
"version": 1,
"newdata": true,
"lastrunstatus": "success",
"thisversionstatus": "success",
"thisversionrun": "Sun Jun 07 2015 17:19:33 GMT+0000 (UTC)",
"results": {
"collection1": [
{
"content": "Parse handles everything you need to store data securely and efficiently in the cloud. Store basic data types, including locations and photos, and query across ...",
"title": {
"href": "https://parse.com/products/core",
"text": "Parse Core | Everything your app needs to save data, be ..."
},
"index": 1,
"url": "https://www.google.com.tw/webhp?sourceid=chrome-instant&ion=1&espv=2&es_th=1&ie=UTF-8#/es_th=1&q=pase%20data"
},
{
"content": "Parsing or syntactic analysis is the process of analysing a string of symbols, either ... In order to parse natural language data, researchers must first agree on the ...",
"title": {
"href": "http://en.wikipedia.org/wiki/Parsing",
"text": "Parsing - Wikipedia, the free encyclopedia"
},
"index": 2,
"url": "https://www.google.com.tw/webhp?sourceid=chrome-instant&ion=1&espv=2&es_th=1&ie=UTF-8#/es_th=1&q=pase%20data"
},
{
"content": "In a data flow, Integration Services sources do the work of extracting data, parsing string data, and converting data to an Integration Services data type.",
"title": {
"href": "https://msdn.microsoft.com/en-us/ms141022.aspx",
"text": "Parsing Data - MSDN - Microsoft"
}
......
]
}
However, it show me some error. I can't understand what is it.
Traceback (most recent call last):
File "get_json_data_2.py", line 6, in
parse_result = json.loads(results)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/init.py",
line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py",
line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer
A: results already contains the parsed JSON tree. You don't need the loads part:
import json
import urllib
results = json.load(urllib.urlopen("https://www.kimonolabs.com/api/adgmajn2?apikey=L63EvSC1x5vG8iSbm9Jon3784mkDp1Or"))
print results
A: You could convert json to yaml using for example this: http://jsontoyaml.com/ . Yaml is python "version" of json.
import yaml
stram = open("test", "r")
print yaml.load(stram)
| |
doc_23533870
|
A: Optimizers (like gradient clipping) can be used in to different ways, first as is shown below:
julia> using Flux
julia> W = rand(2, 5)
2×5 Matrix{Float64}:
0.107144 0.643693 0.399019 0.764073 0.78122
0.367751 0.335326 0.442312 0.433656 0.443901
julia> b = rand(2)
2-element Vector{Float64}:
0.035723018492827885
0.9063968296104223
julia> predict(x) = (W * x) .+ b
predict (generic function with 1 method)
julia> loss(x, y) = sum((predict(x) .- y).^2)
loss (generic function with 1 method)
julia> x, y = rand(5), rand(2) # Dummy data
([0.4878962006153771, 0.1293768496171035, 0.4662237969593086, 0.43195747100830384, 0.10672368947541733], [0.864923828559593, 0.6643701281693306])
julia> l = loss(x, y) # ~ 3
0.8292492365517469
julia> θ = params(W, b)
Params([[0.10714416442012298 0.6436932411339433 … 0.7640730577168127 0.7812198182421601; 0.3677513353707582 0.3353255969566744 … 0.4336560750116858 0.44390077304165043], [0.035723018492827885, 0.9063968296104223]])
julia> grads = gradient(() -> loss(x, y), θ)
Grads(...)
julia> using Flux.Optimise
julia> opt = Optimiser(ClipValue(1e-3), ADAM(1e-3))
Optimiser(Any[ClipValue{Float64}(0.001), ADAM(0.001, (0.9, 0.999), IdDict{Any, Any}())])
julia> for p in (W, b)
update!(opt, p, grads[p])
end
# This is a somewhat bad example since there is no exploding gradients here but the mechanics would be the same if there was.
or you could pass the optimizer (opt = Optimiser(ClipValue(1e-3), ADAM(1e-3)) from here: https://fluxml.ai/Flux.jl/stable/training/optimisers/#Gradient-Clipping) into the training loop by doing something like:
for d in datapoints
# `d` should produce a collection of arguments
# to the loss function
# Calculate the gradients of the parameters
# with respect to the loss function
grads = Flux.gradient(parameters) do
loss(d...)
end
# Update the parameters based on the chosen
# optimiser (opt)
Flux.Optimise.update!(opt, parameters, grads)
end
# Example from here: https://fluxml.ai/Flux.jl/stable/training/training/#Training
where opt is defined per the example shown above.
| |
doc_23533871
|
My sample data points
col1 col2
1 92
9 45
7 22
2 14
5 10
So search algorithm I am looking is like this,
say if key = 2 then function should return index of 2 since its available, say for example I want to search 3, its not there in col1, since its not available, I need to search nearest value in both direction that is index of 2 and 5
in case of awk exact key can be searched using something like this
function search(Arr,key){
if((key in Arr))
return key
}
But I really don't know but to search nearest value in both upper and lower direction, in case of exact key not found
I hope my requirement is clear, in case of negative voting, please put your comment also, since my problem is because of less reputation(new to this forum), I am unable to vote up for useful answers, please co-operate.
A: Shell solution,
perl -lane'
BEGIN{ $k=pop }
push @r, [@F];
END {
for (sort{ $a->[0] <=> $b->[0] } @r) {
$v= $_->[0] <=> $k;
$h{$v} = $_->[1];
last if $v >0;
}
print join " ", ($h{0} or @h{-1,1});
}
' file 3
output
14 10
A: Because you are not sorted, the best is to search for the exact, lower and upper at the same time to iterate over the data only once.
#include <iostream>
#include <vector>
#include <utility>
using Samples = std::vector<std::pair<int,int>>;
Samples::const_iterator Find( Samples const & samp_, int val_, Samples::const_iterator & prev_, Samples::const_iterator & next_ ) {
auto end = std::end(samp_);
auto lower = end;
auto upper = end;
auto it = begin(samp_);
for( ; it!=end; ++it) {
if ( it->first == val_ )
return it;
if ( it->first < val_ && ( lower == end || lower->first < it->first ) )
lower = it;
else if ( it->first > val_ && ( upper == end || upper->first > it->first ) )
upper = it;
}
prev_ = lower;
next_ = upper;
return end;
}
std::ostream & operator<<( std::ostream & os, std::pair<int,int> const & p ) {
return os << "( " << p.first << ", " << p.second << " )";
}
int main() {
Samples samps { {1,92}, {9,45},{7,22},{2,14},{5,10} };
auto test = [&] ( int v ) {
Samples::const_iterator lower;
Samples::const_iterator upper;
auto result = Find( samps, v, lower, upper );
if ( result != end( samps ) ) {
std::cout << "found " << *result << std::endl;
} else {
std::cout << "not found ";
if ( lower != end( samps ) )
std::cout << "lower is " << *lower;
else
std::cout << "no lower";
if ( upper != end( samps ) )
std::cout << " upper is " << *upper;
else
std::cout << " no upper";
std::cout << std::endl;
}
};
test(2);
test(3);
test(12);
test(-1);
}
And the result :
found ( 2, 14 )
not found lower is ( 2, 14 ) upper is ( 5, 10 )
not found lower is ( 9, 45 ) no upper
not found no lower upper is ( 1, 92 )
A: In Gnu Awk version 4, you could use PROCINFO["sorted_in"] like:
gawk -vkey=7 -f a.awk file
where a.awk is:
{
a[$1]=$2
}
END {
if (key in a)
print "Found key "key" with value "a[key]
else {
PROCINFO["sorted_in"]="@ind_num_asc"
for (i in a) {
if (i+0>key) { k=i; break}
j=i
}
if (j)
print "Prev key: "j
if(k)
print "Next key: "k
}
}
Output:
$gawk -vkey=6 -f a.awk file
Prev key: 5
Next key: 7
$gawk -vkey=5 -f a.awk file
Found key 5 with value 10
| |
doc_23533872
|
-(void)updateMarkerImagePinSize {
NSLog(@"Update Marker Image called");
//[self.mapView clear];
UIImage *pinImage;
AtmLocations *atmLocations = [ATMLocatorManager sharedATMLocatorManager].atmLocations;
CLLocationCoordinate2D searchedAddressCoordinate = CLLocationCoordinate2DMake(atmLocations.locations.startLatitude, atmLocations.locations.startLongitude);
[self addSearchLocationMarkerToMap:searchedAddressCoordinate];
NSArray *locationArray = atmLocations.locations.location;
if (locationArray == nil || [locationArray count] == 0){
return;
}
for (Location *location in locationArray) {
CLLocationCoordinate2D markerCoordinate = CLLocationCoordinate2DMake([[[location attributes] latitude] doubleValue], [[[location attributes] longitude] doubleValue]);
GMSMarker *marker = [GMSMarker markerWithPosition:markerCoordinate];
if ([location.attributes.locationType isEqualToString:@"ATM"]) {
if (self.mapView.camera.zoom < kZoomThresoldForMarkerImageSizeChange) {
pinImage = [UIImage imageNamed:@"atm_pin_small"];
} else {
pinImage = [UIImage imageNamed:@"atm_pin"];
}
} else {
if (self.mapView.camera.zoom < kZoomThresoldForMarkerImageSizeChange) {
pinImage = [UIImage imageNamed:@"office_pin_small"];
} else {
pinImage = [UIImage imageNamed:@"office_pin"];
}
}
marker.map = nil;
marker.icon = pinImage;
marker.map = self.mapView;
}
}
However, the issue I'm facing is that both the marker icon images remain. How can I replace the marker image and not show both?
A: Actually, I figured out what the issue was:
GMSMarker *marker = [GMSMarker markerWithPosition:markerCoordinate];
I missed that markerWithPosition is a constructor and not simply returning the marker at that position if it exists. As a result it was creating new markers each time. Solved it by creating a NSMutableArray of markers and managing that array
| |
doc_23533873
|
<?php
$url ="http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false";
if (file_exists($url)) {
$xml = simplexml_load_file($url);
print_r($xml); # <-- Display in browser
} else {
exit('Failed!');
}
?>
A: You cannot use file_exists() with a URL. If you replace that with something like file_get_contents(), the rest of your code will work as expected.
| |
doc_23533874
|
<Button
android:layout_width="150dip"
android:id="@+id/button1"
android:layout_height="50dip"
android:text="@string/login"
android:layout_marginRight="10dip">
</Button>
I'd like to programmatically add an onclick() listener in it's Java file. How would I do this?
A: You just need something like this:
Button buttonOne = (Button) findViewById(R.id.button1);
buttonOne.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//Do stuff here
}
});
A: You can try this.
public class myNewClass extends Activity implements OnClickListener {
...................
...................
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(this);
public void onClick(View v) {
Intent i = new Intent();
Bundle extras = new Bundle();
// This will catch the button click
// Now do what you wanted to do as a
// result of the onClick
}
}
A: This answer comes from Five Ways to Wire Up an Event Listener. Please read that blog post for a fuller explanation from the author. See my other answer for these five ways reworked to add multiple onClick listeners.
1. Member Class
public class main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//attach an instance of HandleClick to the Button
findViewById(R.id.button1).setOnClickListener(new HandleClick());
}
private class HandleClick implements OnClickListener{
public void onClick(View arg0) {
Button btn = (Button)arg0; //cast view to a button
// get a reference to the TextView
TextView tv = (TextView) findViewById(R.id.textview1);
// update the TextView text
tv.setText("You pressed " + btn.getText());
}
}
}
2. Interface Type
public class main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//use the handleClick variable to attach the event listener
findViewById(R.id.button1).setOnClickListener(handleClick);
}
private OnClickListener handleClick = new OnClickListener(){
public void onClick(View arg0) {
Button btn = (Button)arg0;
TextView tv = (TextView) findViewById(R.id.textview1);
tv.setText("You pressed " + btn.getText());
}
};
}
3. Anonymous Inner Class
public class main extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.button1).setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
Button btn = (Button)arg0;
TextView tv = (TextView) findViewById(R.id.textview1);
tv.setText("You pressed " + btn.getText());
}
});
}
}
4. Implementation in Activity
public class main extends Activity implements OnClickListener{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.button1).setOnClickListener(this);
}
public void onClick(View arg0) {
Button btn = (Button)arg0;
TextView tv = (TextView) findViewById(R.id.textview1);
tv.setText("You pressed " + btn.getText());
}
}
5. Attribute in View Layout for OnClick Events
public class main extends Activity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void HandleClick(View arg0) {
Button btn = (Button)arg0;
TextView tv = (TextView) findViewById(R.id.textview1);
tv.setText("You pressed " + btn.getText());
}
}
xml:
<Button android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1"
android:onClick="HandleClick"/>
A: You can apply onClicklistner in Two way :
1. Under onCreate Method
2. Out side onCreate Method
if we will use under onCreate method then we will use like this:-
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_graphics1);
textview1 = (TextView) findViewById(R.id.textview1);
circleBtn = (Button) findViewById(R.id.circleBtn);
// Click Listner Under on Create Method
circleBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
if You want out side to onCreate Method then first register the onClickListner in onCreate Method like this :-
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_graphics1);
circleBtn = (Button) findViewById(R.id.circleBtn);
**// Register on click on button
circleBtn.setOnClickListener(new ClickMe());**
}
and then implement clicklistner outside of onCreate Method so full code will be like this :-
public class ActiononBtn extends AppCompatActivity {
private TextView textview1;
private Button circleBtn;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_graphics1);
textview1 = (TextView) findViewById(R.id.textview1);
circleBtn = (Button) findViewById(R.id.circleBtn);
// Register on click on button
circleBtn.setOnClickListener(new ClickMe());
} // Close onCreate Method
private class ClickMe implements View.OnClickListener {
public void onClick(View v) {
}
}
}//Close main Activity Class
A: 1.use findViewById(R.id.button1).setOnClickListener(this);
2.and activty implements OnClickListener
A: <Button
android:id="@+id/btnOk"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Ok"
android:layout_marginRight="50dp"
android:layout_marginLeft="50dp"/>
public class MainActivity extends AppCompatActivity {
Button btnOk;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOk = findViewById(R.id.btnOk);
btnOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "This button ok click.", Toast.LENGTH_SHORT).show();
}
});
}
}
| |
doc_23533875
|
A: Captions in default language (single available or English it seems):
To get captions of a YouTube video just use this Linux command (using curl and base64):
curl -s 'https://www.youtube.com/youtubei/v1/get_transcript?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8' -H 'Content-Type: application/json' --data-raw "{\"context\":{\"client\":{\"clientName\":\"WEB\",\"clientVersion\":\"2.2021111\"}},\"params\":\"$(printf '\n\x0bVIDEO_ID' | base64)\"}"
Change the VIDEO_ID parameter with the one interesting you.
Note: the key isn't a YouTube Data API v3 one, it is the first public (tested on some computers in different countries) one coming if you curl https://www.youtube.com/ | grep AIzaSy
Note: If interested in how I reverse-engineered this YouTube feature, say it in the comments and I would write a paragraph to explain
Captions in desired language if available:
YouTube made things tricky maybe to lose you at this step, so follow me: the only thing we have to change is the params value which is base64 encoded data which is in addition to weird characters also containing base64 data which also contains weird characters.
*
*Get the language initials like "ru" for russian
*Encode \n\x00\x12\x02LANGUAGE_INITIALS\x1a\x00 in base64 with for instance A=$(printf '\n\x00\x12\x02LANGUAGE_INITIALS\x1a\x00' | base64) (don't forget to change LANGUAGE_INITIALS to your language initials wanted ru for instance). The result for ru is CgASAnJ1GgA=
*Encode the result as a URL by replacing the = to %3D with for instance B=$(printf %s $A | jq -sRr @uri). The result for ru is CgASAnJ1GgA%3D
*Only if using shell commands: replace the single % to two % with for instance C=$(echo $B | sed 's/%/%%/'). The result for ru is CgASAnJ1GgA%%3D
*Encode \n\x0bVIDEO_ID\x12\x0e$C (don't forget to change VIDEO_ID to your video id, with $C the result of the previous step) with for instance D=$(printf "\n\x0bVIDEO_ID\x12\x0e$C" | base64). The result for ru and lo0X2ZdElQ4 is CgtsbzBYMlpkRWxRNBIOQ2dBU0FuSjFHZ0ElM0Q=
*Use this params value from the Captions in default language section: curl -s 'https://www.youtube.com/youtubei/v1/get_transcript?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8' -H 'Content-Type: application/json' --data-raw "{\"context\":{\"client\":{\"clientName\":\"WEB\",\"clientVersion\":\"2.2021111\"}},\"params\":\"$D\"}"
A: I recommend that anyone who uses python to try the module youtube_transcript_api. I used to send GET request to https://video.google.com/timedtext?lang=en&v={videoId}, but now the page is blank. The following is the code example. In addition, this method does not need api key.
from youtube_transcript_api import YouTubeTranscriptApi
srt = YouTubeTranscriptApi.get_transcript("videoId",languages=['en'])
A: The YouTube API change around captions caused me a lot of hassle, which I circumvented through use of youtube-dl, which has won GitHub legal support and is now again available for download/clone.
The software is available as source or binary download for all major platforms, details on their GitHub page, linked above.
Sample use is this simple:
youtube-dl --write-sub --sub-lang en --skip-download --sub-format vtt https://www.youtube.com/watch?v=E-lZ8lCG7WY
A: Old API currently returns 404 on every request. And YouTube right now uses new version of this API:
https://www.youtube.com/api/timedtext?v={youtubeVideoId}&asr_langs=de%2Cen%2Ces%2Cfr%2Cid%2Cit%2Cja%2Cko%2Cnl%2Cpt%2Cru%2Ctr%2Cvi&caps=asr&exp=xftt%2Cxctw&xoaf=5&hl=en&ip=0.0.0.0&ipbits=0&expire=1637102374&sparams=ip%2Cipbits%2Cexpire%2Cv%2Casr_langs%2Ccaps%2Cexp%2Cxoaf&signature=0BEBD68A2638D8A18A5BC78E1851D28300247F93.7D5E6D26397D8E8A93F65CCA97260D090C870462&key=yt8&kind=asr&lang=en&fmt=json3
The main problem with this API is to calculate the signature field of request. Unfortunately I couldn't find its algorithm. Maybe someone can reverse engineered it form YouTube player.
| |
doc_23533876
|
I tried the following, but it doesn't work:
SELECT *
FROM(
SELECT MAX(`Session`.acDateF) as MaxDateF
FROM `Session`
WHERE `Session`.acType='1'
) as AcDate
GROUP BY `Session`.userId)
WHERE YEAR(`Session`.acDateF) =YEAR(CURRENT_DATE())-1
If the User has a record in the Session table this year it doesn't appear in the result.
A: Your question is not very clear, but it sounds like you want something like this:
SELECT *
FROM `Session` s
INNER JOIN
(
SELECT MAX(`Session`.acDateF) as MaxDateF, `Session`.userId
FROM `Session`
WHERE `Session`.acType='1'
AND YEAR(s.acDateF) =YEAR(CURRENT_DATE())-1
GROUP `Session`.userId
) as AcDate
ON s.userId = AcDate.userId
AND s.acDateF = AcDate.MaxDateF;
Or if you want the user data:
SELECT *
FROM `user` u
INNER JOIN
(
SELECT MAX(`Session`.acDateF) as MaxDateF, `Session`.userId
FROM `Session`
WHERE `Session`.acType='1'
AND YEAR(s.acDateF) =YEAR(CURRENT_DATE())-1
GROUP `Session`.userId
) as AcDate
ON u.userId = AcDate.userId;
A: SELECT
MAX(`Session`.acDateF) as MaxDateF,
`Session`.userId
FROM `Session`
WHERE `Session`.acType='1'
GROUP BY `Session`.userId
having MAX(YEAR(`Session`.acDateF)) as MaxDateF =YEAR(CURRENT_DATE())-1
A: Here is a way. It uses a correlated subquery in the where clause to get the last date for the previous year:
select *
from session s
where s.acDatef = (select MAX(se.acDatef)
from session s2
where s2.userid = s.userid and
YEAR(`Session`.acDateF) =YEAR(CURRENT_DATE())-1
)
| |
doc_23533877
|
I want to allow the user to upload a profile-picture from their profile. On their edit profile view, I added the following XAML code
<Grid Grid.Row="10"
Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox MinWidth="150" HorizontalAlignment="Stretch"
Grid.Column="0"></TextBox>
<Button Content="Browse" Command="{Binding Path=UploadImage}"
Grid.Column="1"
Margin="0 0 5 0"></Button>
</Grid>
The UploadImage command will need to display a dialog to browse the user's PC for the pictures.
Using Prims and the MVVM, how can I correctly display a file-browser? Then how can I upload the selected file into the memory?
A: The usual way to display file open dialog in WPF and MVVM is to use a service, which represents a open file dialog. You should inject this service into your ViewModel, using usual IoC method in the Prism.
This service INTERFACE should not depend on any particular ui method (usually it is very easy to implement it in the command line test or unit test mock).
The IMPLEMENTATION of the service should be in the project which depends on WPF, and this implementation should then call OpenFileDialog to open file.
Your button command should call the instance of the service, passed to the ViewModel, and open the dialog.
There are many implementations of this idea, here's a simple one:
public interface IOpenFileService
{
/// <summary>
/// Open file
/// </summary>
/// <returns>True if file selected</returns>
bool? OpenFile();
/// <summary>
/// Full names of the selected files
/// </summary>
string[] FileNames { get; }
}
public class OpenFileService: IOpenFileService
{
OpenFileDialog _openFileDialog = new OpenFileDialog();
string[] _selectedFileNames;
public bool? OpenFile()
{
_openFileDialog.Multiselect = true;
var ofd = _openFileDialog.ShowDialog();
if (ofd.HasValue && ofd.Value)
{
_selectedFileNames = _openFileDialog.FileNames;
}
return ofd;
}
public string[] FileNames
{
get { return _selectedFileNames ; }
}
}
So you register the implementation of the service, and your ViewModel receives the implementation in the constructor:
public class SomeViewModel
{
public SomeViewModel(IFileOpenService fileOpen)
{
this._fileOpen = fileOpen;
}
public void FileOpenCommandExecute
{
if (this._fileOpen.OpenFile())
{
var selectedFiles = this._fileOpen.FileNames;
// .. do something with the selected files...
}
}
}
There are other implementations, which support many other dialog types, so you should look for them too, but this is a basic idea.
HTH, Tom
| |
doc_23533878
|
A: Wikipedia says
Parse trees concretely reflect the syntax of the input language, making them distinct from the abstract syntax trees used in computer programming.
An answer on Quora says
A parse tree is a record of the rules (and tokens) used to match some input text whereas a syntax tree records the structure of the input and is insensitive to the grammar that produced it.
Combining the above two definitions,
An Abstract Syntax Tree describes the parse tree logically. It does not need to contain all the syntactical constructs required to parse some source code (white spaces, braces, keywords, parenthesis etc). That's why Parse Tree is also called Concrete Syntax Tree while the AST is called Syntax Tree. The output of syntax analyser is, thus, syntax tree actually.
A: Take the pascal assignment
Age:= 42;
The syntax tree would look just like the source code. Below I am putting brackets around the nodes.
[Age][:=][42][;]
An abstract tree would look like this
[=][Age][42]
The assignment becomes a node with 2 elements, Age and 42. The idea is that you can execute the assignment.
Also note that the pascal syntax disappears. Thus it is possible to have more than one language generate the same AST. This is useful for cross language script engines.
A: Here's an explanation of parse trees (concrete syntax trees, CSTs) and abstract syntax trees (ASTs), in the context of compiler construction. They're similar data structures, but they're constructed differently and used for different tasks.
Parse trees
Parse trees are usually generated as the next step after lexical analysis (which turns the source code into a series of tokens that can be viewed as meaningful units, as opposed to just a sequence of characters).
They are tree-like data structures that shows how an input string of terminals (source code tokens) has been generated by the grammar of the language in question. The root of the parse tree is the most general symbol of the grammar - the start symbol (for example, statement), and the interior nodes represent nonterminal symbols that the start symbol expands to (can include the start symbol itself), such as expression, statement, term, function call. The leaves are the terminals of the grammar, the actual symbols which appear as identifiers, keywords, and constants in the language / input string, e.g. for, 9, if, etc.
While parsing the compiler also performs various checks to ensure the correctness of syntax - and and syntax error reports can be imbedded into parser code.
They can be used for syntax-directed translation via syntax-directed definitions or translation schemes, for simple tasks such as converting an infix expression to a postfix one.
Here's a graphical representation of a parse tree for the expression 9 - 5 + 2 (note the placement of the terminals in the tree and the actual symbols from the expression string):
Abstract syntax trees
ASTs represent the syntactic structure of the some code. The trees of programming constructs such as expressions, flow control statements, etc - grouped into operators (interior nodes) and operands (leaves). For example, the syntax tree for the expression i + 9 would have the operator + as root, the variable i as the operator's left child, and the number 9 as the right child.
The difference here is that nonterminals and terminals don't play a role, as ASTs don't deal with grammars and string generation, but programming constructs, and thus they represent relationships between such constructs, and not the ways they are generated by a grammar.
Note that the operators themselves are programming constructs in a given language, and don't have to be actual computational operators (like + is): for loops would also be treated in this way. For example, you could have a syntax tree such as for [ expr, expr, expr, stmnt ] (represented inline), where for is an operator, and the elements inside the square brackets are its children (representing C's for syntax) - also composed out of operators etc.
ASTs are usually generated by compilers in the syntax analysis (parsing) phase as well, and are used later for semantic analysis, intermediate representation, code generation, etc.
Here's a graphical representation of an AST:
A: In parse tree interior nodes are non terminal, leaves are terminal.
In syntax tree interior nodes are operator, leaves are operands.
A: From what I understand, the AST focuses more on the abstract relationships between the components of source code, while the parse tree focuses on the actual implementation of the grammar utilized by the language, including the nitpicky details. They are definitely not the same, since another term for "parse tree" is "concrete syntax tree".
A: The DSL book from Martin Fowler explains this nicely. The AST only contains all 'useful' elements that will be used for further processing, while the parse tree contains all the artifacts (spaces, brackets, ...) from the original document you parse
A: An AST describes the source code conceptually, it doesn't need to contain all the syntactical elements required to parse some source code (curly braces, keywords, parenthesis etc.).
A Parse tree represents the source code more closely.
In an AST the node for an IF statement could contain just three children:
*
*Condition
*If Case
*Else Case
For a C-like language the Parse Tree would need to contain nodes for the 'if' keyword, parenthesis, curly braces also.
A: This is based on the Expression Evaluator grammar by Terrence Parr.
The grammar for this example:
grammar Expr002;
options
{
output=AST;
ASTLabelType=CommonTree; // type of $stat.tree ref etc...
}
prog : ( stat )+ ;
stat : expr NEWLINE -> expr
| ID '=' expr NEWLINE -> ^('=' ID expr)
| NEWLINE ->
;
expr : multExpr (( '+'^ | '-'^ ) multExpr)*
;
multExpr
: atom ('*'^ atom)*
;
atom : INT
| ID
| '('! expr ')'!
;
ID : ('a'..'z' | 'A'..'Z' )+ ;
INT : '0'..'9'+ ;
NEWLINE : '\r'? '\n' ;
WS : ( ' ' | '\t' )+ { skip(); } ;
Input
x=1
y=2
3*(x+y)
Parse Tree
The parse tree is a concrete representation of the input. The parse tree retains all of the information of the input. The empty boxes represent whitespace, i.e. end of line.
AST
The AST is an abstract representation of the input. Notice that parens are not present in the AST because the associations are derivable from the tree structure.
For a more through explanation see Compilers and Compiler Generators pg. 23
or Abstract Syntax Trees on pg. 21 in Syntax and Semantics of Programming Languages
| |
doc_23533879
|
function Test() {}
Test.someProp = bigObject;
I'm wondering if bigObject will always be in memory or it will gc sometime?
A: It will never be collected as long as someProp is alive (has a reference). If you delete Test.someProp or delete or empty the whole Test then it will be gCollected
| |
doc_23533880
|
When an app is started by clicking on it, it becomes a child process of the explorer process. The same is true for all apps that are loaded when Windows starts up.
If you kill the explorer process using the "End Process Tree" context menu option in the task manager, it kills all child processes of the explorer process as well (a quick, brute force way to clean up memory without restarting).
I have two scripts - one that kills a bunch of specific processes, and another that restarts those processes.
Most of the processes/apps in my scripts are loaded at start-up thus they are children of the explorer process. When I kill the explorer process tree, all these process die, as explained earlier.
When I restart these apps using a script, they are no longer children of the explorer process. When I kill the kill the explorer process tree, the apps started by the script do not die.
Now, I know I can kill each process individually using a script. But it would be nice to just kill the explorer processes tree in a script without having to specify the individual apps I want to kill.
So, if I have one script that can start my apps as children of the explorer process, my other script just has to kill the explorer processes tree.
I have a script that does just that. It loops through and kills all the child processes of the explorer process. However it only works on apps that load at start up or are are clicked on.
Also, by preventing these apps from loading at start-up, Windows loads MUCH faster. Later, I click on my script icon to load my apps when needed.
That's why I want to create a script that can start apps as children of the explorer process.
An interesting side note: I have to postpone killing any command/console processes, otherwise the script may kill itself before getting the rest of the processes.
Any ideas how this can be done?
Below is my code that fails.
Option Explicit
dim wmi, rootProcessName, rootProcess, objStartup, objConfig, objProcess, strComputer, dropbox, itunes, skype
strComputer = "."
dropbox="C:\Program Files\Dropbox\Dropbox.exe"
itunes="C:\Program Files\iTunes\iTunes.exe"
skype="C:\Program Files\Skype\Phone\Skype.exe"
Const NORMAL = 32
Set wmi = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set objStartup = wmi.Get("Win32_ProcessStartup")
Set objConfig = objStartup.SpawnInstance_
objConfig.PriorityClass = NORMAL
rootProcessName = "'explorer.exe'"
set rootProcess = wmi.ExecQuery("Select * from Win32_Process Where Name = " & rootProcessName )
For Each objProcess in rootProcess
objProcess.Create dropbox, null, objConfig
objProcess.Create itunes, null, objConfig
objProcess.Create skype, null, objConfig
Next
WScript.Quit
A: A window's process keeps track of the Process ID of who created it, this is how the relationships are being managed. To get what you want, you either have to change the parent PID stored in the child process, or inject code into the process you want to be the parent and have it create the new child process. Neither of these are really doable.
The real solution is to use Job Objects, that way you can terminate all the processes which are associated with the job all at the same time. But you would have to migrate out of vbscript.
A: The use of JobObjects as proposed by @josh poley is standard practice for grouping processes, but does not work when a process is launched as a DCOM service.
Launching applications from VBScript has a serious downside when it comes to tracking the processes of things instantiated through CreateObject: Depending on what kind of object it is, the application's process may not become a child of the invoking process. Instead, it will start up under an svchost.exe process.
Say we're working in C/C++ and we want to launch Excel from a VB script. In C/C++ we might do the following:
*
*Call CreateJobObject()
*Create a suspended process that is to invoke the .VBS script
*Add the created process to the job with AssignProcessToJobObject()
*Call ResumeThread() to start the suspended process
Given the above, here's roughly what happens:
*
*The created process, P, starts running as a member of job, J.
*P launches the VBS file with script host, H (cscript or wscript.exe)
*H runs as a child of P, as expected
*H executes CreateObject("Excel.Application") starting Excel as a service
*Hence, Excel becomes a child of a service host process, not P
*This process (svchost.exe -k DcomLaunch) groups DLLs for DCOM execution
*The scripting complete, H terminates
*E continues on, but P has lost all trace of it
Line 4 is the culprit. Excel is run as a service, because registry entries indicate that it is a DCOM object. A way around this, is to create a shell object, and run the application through that.
dim shell = wscript.createObject("wscript.shell")
shell.run(<path-to-application>\excel.exe)
The downside is that the path to the application must be known.
| |
doc_23533881
|
I already created the smile dir in src/commands, with smile.c and Makefile, and added smile to src/commands/Makefile.
But after compiling I still get
# smile
smile: not found
Is there another file/header/script where I must add a reference to smile?
Thank you in advance!
A: You either need to specify the directory, or the directory must be part of the PATH environment variable.
Try
./smile
if the program is in the current directory.
or
export PATH=".:$PATH"
smile
to always check the current directory for commands during this bash session.
If the program is in a subdirectory (eg. src/commands/smile) relative to the current directory,
you can add that to the path instead. Either explicitly,
src/commands/smile/smile
or by adding to the search path
export PATH="src/commands/smile:$PATH"
smile
A: placing your executable in the /usr/bin folder will allow the shell to recognize it. you should be able to type #smile now
| |
doc_23533882
|
digikala.menu is ul in JSON
request.onload = function () {
var digikala = request.response;
for (var i = 0; i < digikala.menu.length; i++) {
var name = digikala.menu[0];
var ul = document.getElementById("navigation_item");
var li = document.createElement('li');
li.appendChild(document.createTextNode(name));
ul.appendChild(li);
}
}
| |
doc_23533883
|
Putting a simple expression language into java
But I now realise I need to use Rhino directly rather than ScriptEngine because I need to preserve Java 1.5 compatabiliy, I think I can run the evaluation as folllows
Context context = Context.enter();
try {
Scriptable scope = context.initStandardObjects();
String result = context.evaluateString(scope, expr, null, 0, null);
return result
} finally {
Context.exit();
}
but whats the alternative to
jsEngine.put(fieldname.getScriptVariable(), value);
to map values to variables
A: If you have to be java 1.5 compatible at least use BSF framework from Jakarta project. It is similar to java scripting framework introduced in java 1.6
A: I think what you need to do is the following:
Object wrappedObject = Context.javaToJS(yourObjectHere, scope);
ScriptableObject.putProperty(scope, "yourVariableNameHere", wrappedObject);
See the Expose Java APIs Rhino example.
| |
doc_23533884
|
val str = """ {"protectedBitcoinAddress":"moLM1zdPBSh81eykhfcoLZ3myqUSy9FRRG"} """
val request : JsValue = Json.parse(str)
println("Request: " + request.toString)
val result : Future[Result] = createUnsignedNLockTime()(FakeRequest().withJsonBody(request))
whenReady(result, timeout(19 seconds), interval(5 millis)) { res =>
println("==============================")
val e: play.api.libs.iteratee.Enumerator[Array[Byte]] = res.body
val bodyAsStr: scala.concurrent.Future[String] = e.run(play.api.libs.iteratee.Iteratee.fold("") { (memo, next) => memo + next })
println("Body as string: " + Await.result(bodyAsStr,5 seconds))
val bodyAsJsValue: scala.concurrent.Future[play.api.libs.json.JsValue] = e.map(play.api.libs.json.Json.parse)
println("body as js: " + Await.result(bodyAsJsValue, 5 seconds))
println("==============================")
}
How do I take something of type Enumerator[scala.Array[scala.Byte]] and convert that to a Json object in the Playframework?
A: Is this what you want ?
[info] Starting scala interpreter...
[info]
Welcome to Scala version 2.10.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_79).
Type in expressions to have them evaluated.
Type :help for more information.
scala>import play.api.mvc.{Result, Results}
import play.api.mvc.{Result, Results}
scala>import play.api.libs.iteratee.{Enumerator, Iteratee}
import play.api.libs.iteratee.{Enumerator, Iteratee}
scala>import play.api.libs.json.Json
import play.api.libs.json.Json
scala>import scala.concurrent.{Await, Future}
import scala.concurrent.{Await, Future}
scala>import scala.concurrent.duration._
import scala.concurrent.duration._
scala>import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.ExecutionContext.Implicits.global
scala>val result: Result = Results.Ok(Json.stringify(Json.toJson(Map("k" -> "v")))).as("application/json")
result: play.api.mvc.Result = Result(200, Map(Content-Type -> application/json))
scala>val enumerator: Enumerator[Array[Byte]] = result.body
enumerator: play.api.libs.iteratee.Enumerator[Array[Byte]] = play.api.libs.iteratee.Enumerator$$anon$18@70d59654
scala>val bodyAsBytesEventually: Future[Array[Byte]] = enumerator.run(Iteratee.fold(Array.empty[Byte]) { (memo, nextChunk) => memo ++ nextChunk })
bodyAsBytesEventually: scala.concurrent.Future[Array[Byte]] = scala.concurrent.impl.Promise$DefaultPromise@8786f46
scala>val bodyAsStrEventually = bodyAsBytesEventually.map(bytes => new String(bytes))
bodyAsStrEventually: scala.concurrent.Future[String] = scala.concurrent.impl.Promise$DefaultPromise@442b7dd6
scala>val bodyAsStr = Await.result(bodyAsStrEventually, 1.seconds)
bodyAsStr: String = {"k":"v"} // In general, do not block unless you know what you are doing.
A: I think you need Helpers.scala to convert your response of type byte array to string/json.
Ref: this and this
You can modify your code as:
val str = """ {"protectedBitcoinAddress":"moLM1zdPBSh81eykhfcoLZ3myqUSy9FRRG"} """
val request : JsValue = Json.parse(str)
println("Request: " + request.toString)
val result : Future[Result] = createUnsignedNLockTime()(FakeRequest().withJsonBody(request))
whenReady(result, timeout(19 seconds), interval(5 millis)) { res =>
println("==============================")
val bodyAsStr = contentAsString(result)
println("Body as string: " + bodyAsStr)
val bodyAsJsValue = contentAsJson
println("body as js: " + bodyAsJsValue)
println("==============================")
I hope this is what you are looking for.
| |
doc_23533885
|
A: You can do something like cd C:\a & winzip32.exe -min -a D:\a where the & separates commands so the that second one runs once the first has finished successfully. For example, you could run it like this:
Set oExec = WshShell.Exec("cmd /c cd C:\a & winzip32.exe -min -a D:\a")
Without the cmd /c in the beginning, you can't do things like cd because cmd.exe is responsible for processing the cd and &.
A: Depending on what you're doing, you could use WshShell.Exec "c:\a\winzip32.exe -min -a D:\a"
| |
doc_23533886
|
If you use a List, or other indexed collection, set the key column of
the foreign key to not null. Hibernate will manage the association
from the collections side to maintain the index of each element,
making the other side virtually inverse by setting update="false" and
insert="false"
If the underlying foreign key column is NOT NULL, it is important that
you define not-null="true" on the element of the collection
mapping. Do not only declare not-null="true" on a possible nested
element, but on the element.
I am going through the documentation to understand Hibernate but I am not clear on above statements. I have few doubts like:
1) If you use a List, or other indexed collection, set the key column of the foreign key to not null -- Why should I set the foreign key to not-null, is this mandatory?
2) making the other side virtually inverse by setting update="false" and insert="false" -- When should we set update="false" and insert="false" and what happens if I don't set them?
Also the purpose of insert and update as per documentation (section - 5.1.4.2. Property mapping with hbm.xml) is:
update, insert (optional - defaults to true): specifies that the
mapped columns should be included in SQL UPDATE and/or INSERT
statements. Setting both to false allows a pure "derived" property
whose value is initialized from some other property that maps to the
same column(s), or by a trigger or other application.
So if I don't have any other property that maps to same column or trigger then why do we need to set them as false?
3) What it means when the doc says: Do not only declare not-null="true" on a possible nested <column> element, but on the <key> element.
Please help me in understanding these. Thanks in advance.
| |
doc_23533887
|
Add Two Vertical Lines to LineChart
My question: How can I change different color of the series? I also want to change the background to be white.
The following is the chart that I create (it extends LineChart):
LineChartWithMarkers<Number, Number> chart = new LineChartWithMarkers<Number, Number>(xAxis, yAxis, dataset);
xAxis.setLabel("time(s)");
yAxis.setLabel("deg/s");
chart.setStyle(".chart-series-line { -fx-stroke-width: 2px; -fx-effect: null; ");
chart.setStyle(".default-color0.chart-series-line { -fx-stroke: blue; }");
chart.setStyle(".default-color1.chart-series-line { -fx-stroke: red; }");
chart.setStyle(".default-color0.chart-line-symbol { -fx-stroke: blue, blue; }");
chart.setStyle(".default-color1.chart-line-symbol { -fx-stroke: red, red; }");
chart.setStyle(".chart-legend { -fx-background-color: transparent; }");
For some reason, those codes won't apply to the chart. So I try to use a CSS file.
The following is the CSS file:
@CHARSET "ISO-8859-1";
.chart-series-line {
-fx-stroke-width: 1px;
-fx-effect: null;}
.default-color0.chart-series-line { -fx-stroke: blue; }
.default-color1.chart-series-line { -fx-stroke: red; }
.default-color0.chart-line-symbol { -fx-background-color: blue, blue; }
.default-color1.chart-line-symbol { -fx-background-color: red, red; }
.chart-legend {
-fx-background-color: transparent;
-fx-font-size: 0.75em;}
.chart-legend-item-symbol{
-fx-background-radius: 2;}
.chart-plot-background {
-fx-background-color: transparent;}
I try to follow Using JavaFX Charts: Styling Charts with CSS, but I get an error in the console is "WARNING: CSS Error parsing file : ... : Expected LBRACE at [1,9]"
I just switch from JDK 7 to JDK 8 today so I am not sure if it has anything to do with that...
Thanks for any help!
A: The @charset rule is not supported by JavaFX CSS, which is only a subset of full W3C CSS. Try removing it.
@ Rules
Beginning with JavaFX 8u20, the CSS @import is also partially
supported. Only unconditional import is supported. In other words, the
media‑type qualifier is not supported. Also, the JavaFX CSS parser is
non-compliant with regard to where an @import may appear within a
stylesheet (see At‑rules). Users are cautioned that this will be fixed
in a future release. Adherence to the W3C standard is strongly
advised.
| |
doc_23533888
|
Screen
Google map screen
A: You can read through the Official Google Documentation of API for Android. This guide introduces the features in the Google Places for Android and shows you how to configure your app to use the API.
The main entry points for the Google Places API for Android are the PlacePicker UI widget, the Autocomplete UI widget, the GeoDataApi, and the PlaceDetectionApi.
Using the Google API for Android, you can build location-aware apps that respond contextually to the local businesses and other places near the device. This means that you can build rich apps based on places that mean something to the user, to complement the straightforward geographic-based services offered by the [Android location services][6] you pass a general search term, Google Maps will attempt to find a location near the lat/lng you specified that matches your criteria. If no location is specified, Google Maps will try to find nearby listings. For example:
// Search for restaurants nearby
Uri gmmIntentUri = Uri.parse("geo:0,0?q=restaurants");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
// Search for restaurants in San Francisco
Uri gmmIntentUri = Uri.parse("geo:37.7749,-122.4194?q=restaurants");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
| |
doc_23533889
|
TypeError: '>=' not supported between instances of 'tuple' and 'int'
I checked my version on python, because i was working on Visual Studio, and turned out that i was using 3.7.7, the latest, from what i know
Then i tried on python ide that had 3.4.4 and turned the same error
First i thought was the version of python, 3.7.7, which is unstale, but then i switched to my Kali Linux and tried again and nothing changed, and i finally tried a online compiler, GDB,for those who knows it, it have 3.4.4
I don t know what i did wrong, please let me know
glory=10445
days=0
while glory>=7500:
glory*=0,99
days+=1
print(days)
A: Here's the problem:
glory*=0,99
It should be:
glory*=0.99
We use a dot . to separate decimals, not a comma , - a comma is used for separating elements in a list or a tuple, and that's what the error says.
| |
doc_23533890
|
I am applying a Facebook authentication to my Expo app . Android everything is working as expected while is ios ONLY getting this error
[Error: Unsuccessful debug_token response from Facebook:
{"error":{"message":"(#100) The App_id in the input_token did not
match the Viewing
App","type":"OAuthException","code":100,"fbtrace_id":"AatQy0aKnSRI8b_pOTa4txS"}}]
While I am searching everybody is pointing that means the AppID or AppSecret provided to firebase is wrong but I am 100% sure it's right as it's working well with android and the user is being authenticated and added to users so my expectations there is something wrong with ios config
Notes
App is directing to FB successfully and return token through ios
Again I am 100% sure of my AppID and AppSecret is correct as I copied paste them
Expo CLI 3.21.9 environment info:
System:
OS: Windows 10 10.0.18363
Binaries:
Node: 12.18.0 - C:\Program Files\nodejs\node.EXE
npm: 6.14.4 - C:\Program Files\nodejs\npm.CMD
IDEs:
Android Studio: Version 4.0.0.0 AI-193.6911.18.40.6514223
npmPackages:
expo: ~37.0.3 => 37.0.12
react: ~16.9.0 => 16.9.0
react-dom: ~16.9.0 => 16.9.0
react-native: https://github.com/expo/react-native/archive/sdk-37.0.1.tar.gz => 0.61.4
react-native-web: ~0.11.7 => 0.11.7
react-navigation: ^4.3.9 => 4.3.9
I will be very grateful if someone is willing to help me with this
Thanks in advance
A: Finally I got to know what is wrong. Everything is ok for the configuration and setting up the peoject.
The problem is the Expo doesn't support facebook authentication in development mode and as per docs it's supported only with standalone apps which with me not working as well
Waiting expo to update something so it could be used
A: I'm having the same issue, but working correctly on Adroid and not in IOS im not assuming is a problem of development mode; my current status is this:
Android Emulator -> clicking on 'login with facebook' it opens a popup to login using my app (FB App name is correct, icon is correct and so on)
IOS real device -> clicking on 'login with facebook' it opens facebook and want to login to Expo FB App (Expo name, Expo icon and so on) so, when i login, of course firebase get the wrong App id (the one passed is the Expo App ID, not mine)
i guess there's something on IOS Expo that intercept APP_ID from Facebook init and replace it with its own APP_ID
A: I had the exact same issue, and spent over 2 days debugging all the code. In the end, it all came down to the "App ID" and "App Secret Key" that I was so sure I copied from the FaceBook Dev page to the Firebase FaceBook Authentication page. Somehow, while copying the Secret Key, the words "App Secret" got prefixed to it.
Secondly, the "OAuth redirect URI" that you get from the Firebase screen where you enter the App ID/Key, needs to be copied back to the "Valid OAuth Redirect URIs" field in Facebook Dev Site (Application > Products > Facebook Login > Settings).
A: After several attempts, the problem was that if, for example, you have created an account with (email@example.com) and you log in with Facebook registered with the same email (email@example.com) account, it will not work until you delete account (email@example.com) manually from Firebase.
| |
doc_23533891
|
swagger-codegen-maven-plugin requires the path to the Swagger spec file as an argument. Is there a way to configure swagger-jersey2-jaxrs to store that spec file to disk? That way I could always generate the Java sources without having to download the spec file by hand and then starting the swagger-codegen-maven-plugin task.
I'm not sure if this is the way to go but I'm open to other approaches. The goal is to always have a Java client library that is in sync with the current state of implementation.
A: Probably the easiest thing to do is have your build script spin up the server and point directly to that.
| |
doc_23533892
|
I want to triggered another function when I click on the same <li> element (unclick).
<ul id="list">
<li>Option1</li>
<li>Option2</li>
<li>Option3</li>
<li>Option4</li>
<li>Option5</li>
<li>Option6</li>
</ul>
<script>
var elems = document.getElementsByTagName('li');
Array.from(elems).forEach(v => v.addEventListener("click", addToArray));
function addToArray() {
}
</script>
Please, I am looking for code with plain JavaScript that could do the trick.
Thank You
A: <script>
var elems = document.getElementsByTagName('li');
Array.from(elems).forEach(v => {
v.addEventListener("click", addToArray));
function addToArray(event) {
if (event.target.classList.includes('active')) {
event.target.classList.split("active").join("");
// unclick handler here
} else {
event.target.classList.push("active");
// click handler here
}
}
</script>
A: You can toggle a class value and do something based on whether it's present or not, e.g.
window.onload = function() {
[].forEach.call(document.querySelectorAll('li'), function(li) {
li.addEventListener('click',handleClick,false);
});
};
function handleClick(){
this.classList.toggle('selected');
if (this.classList.contains('selected')) {
console.log(this.textContent + ' is selected');
} else {
console.log(this.textContent + ' isn\'t selected');
}
}
.selected {
background-color: green;
}
<ol>
<li>First
<li>Second
<li>Third
</ol>
Note that classList requires IE 10 or greater. The same functionality can be coded fairly simply if older browsers need to be supported. The following uses a classList object to provide the same functionality and will work back to IE 6.
// Helper object to provide classList functionality
var classList = {
contains: function(el, className) {
var re = new RegExp('(^|\\s)' + className + '(\\s|$)');
return re.test(el.className);
},
add: function (el, className) {
if (!classList.contains(el, className)) {
el.className += ' ' + className;
}
},
remove: function(el, className) {
if (classList.contains(el, className)) {
var re = new RegExp('(^|\\s)' + className + '(\\s|$)');
el.className = el.className.replace(re, ' ');
}
},
toggle: function(el, className) {
if (classList.contains(el, className)) {
classList.remove(el, className);
} else {
classList.add(el, className);
}
}
};
window.onload = function() {
var lis = document.getElementsByTagName('li');
for (var i=0, iLen=lis.length; i<iLen; i++) {
lis[i].addEventListener('click', handleClick, false);
}
};
function handleClick(){
classList.toggle(this, 'selected');
if (classList.contains(this, 'selected')) {
console.log(this.innerHTML + ' is seleced');
} else {
console.log(this.innerHTML + ' is not seleced');
}
}
.selected {
background-color: red;
}
<ol>
<li>First
<li>Second
<li>Third
</ol>
A: var elems = document.getElementsByTagName('li');
Array.from(elems).forEach(v => v.addEventListener("click", addToArray));
function addToArray() {
this.classList.toggle('selected');
if ( this.classList.contains('selected') ) {
console.log('Selected item');
}
else {
//Do something else
}
}
| |
doc_23533893
|
A: you can add the bootstrap files to your source (if you want to edit the bootstrap docs this is recomended) or just use the online-versions and apply the tags in the head part of your html document.
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
and with this it should run no matter what IDE you use.
/S
| |
doc_23533894
|
It would be great if you could show me logical steps that i need to perform to complete the task before me.
Working with PHP here. I need to figure out how to send a GET request from one page/web application and process as well as display it in another.
A simple example:
there are 2 php pages, one to send the request - send.php, another to process and display it display.php
send.php contains a simple form to get some user input string and using get method to send it over to display.php
<form action="display.php" method="get">
<input type="text" name="userInput">
<input type="submit">
</form>
display.php receives the string and uses it as a parameter for some function and echoes it.
What logical steps do I need to perform to be able to open send.php in one window, display.php in another, type something in into the form, press submit and see the results in the display.php window instead of usual redirect to display.php from send.php? As far as I know, AJAX allows us to communicate with the server but the result is still returned to the same page. Forgive my ignorance, I seek the logical steps to the solution, maybe certain technologies or methods that I am currently unaware of,something to look into and find a way to accomplish this task.
Actual task is work with inventory management system: we need to be able to scan barcodes/id's etc. with one device, while seeing information about the items on another screen (think: scanning barcodes with an android app, sending it to the web based inventory system, which is open on a tablet computer or something like that and seeing the information about the item on said tablet).
Notes: we were explicitly told not to use java/scala, because the sys-admin doesnt want a jvm running on the same server as the inventory system(appearantly only one server dedicated to that), i assume node.js also falls into the same boat, although im uncertain.
Thank you for your patience dealing with a complete web development noob :)
A: you could use websockets, and a server that supports it like node.js
https://www.websocket.org/demos.html
through php by a long polling
http://webcooker.net/ajax-polling-requests-php-jquery/
its also possible by using postMessage
https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
A: Let's see if I got you.
What you want is to, when the user click on submit, he opens at the same page, the display.php file without redirecting, to add new info, and then return to the send.php page?
Well, the way I see it, you can do it with some javascript and CSS.
Here is my solution (I mean, the way would do it).
What you will need is to have a new <div> (or other tag) with an <iframe> inside of it, some JavaScript functions (they run at client side, not server side), and some CSS.
lets show ya how your display.php file should looks like:
<form action="display.php" method="get" target="display" onSubmit="load();">
<input type="text" name="userInput">
<input type="submit">
</form>
<div id="mydiv" class="hide">
<iframe name="display"></iframe>
</div>
Notice that I wrote the target of the form equals the name of the iframe, so it will always submit to the iframe. And, into the form it will make a javascript call when submitting. Also, I've added a class at the new div to hide the content with CSS.
The CSS would looks like:
body, html{ /*to fix the page css*/
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
#mydiv{ /*this is how it should work*/
position: fixed;
width: 100%;
height: 100%;
z-index: 1000; /*the position of the div relatively to other elements, to be always in front of them*/
background-color: rgba(0,0,0,0.3); /*this will add an artistic background effect when loading the submit*/
}
.hide{ /*this class hide the element*/
display: none;
}
And then your JavaScript:
function load()
{
var div = document.getElementById("mydiv");
div.className = "";
}
function finish() //this will be called later, don't forget to give it parameters
{
var div = document.getElementById("mydiv");
div.className = "hide";
//do what you need to show the final result here
}
now, at your send.php file, I believe you will have a form there, so you make a similar call at it. it should looks like:
<form onSubmit="submitForm">
--your form contents--
</form>
and it should have a new javascript function, like:
function submitForm()
{
parent.finish(); //this will call the iframe's parent function, don't forget to give it parameters and something to do.
return false; //this will stop the submit and the 'refresh page'
}
and, then, you have your stuff.
I hope it works for ya.
A: So after analyzing your OP(Original Post) more in depth, I believe what would work for you is the following:
In send.php: use Ajax to store each scanned barcode to the database. The reasoning for this is so that you dont redirect elsewhere. AJAX will just look for the php file that does all the storing work(which you can call process.php).
In display.php: retrieve all the barcodes from the database and render it. This can be done straight with embedded PHP or is you want to do this every so many times, use AJAX.
With this structure, you can see all the barcodes saved regardless of what window or device you are in.
A:
What logical steps do I need to perform to be able to open send.php in one window, display.php in another
Try this:
<form action="display.php" method="get" target="_blank" >
<input type="text" name="userInput">
<input type="submit">
</form>
| |
doc_23533895
|
I googled many examples and found many people used handshakes for their websocket channels, e.g. they let the client register the channel after the connection is upgraded to web socket and then got the client's identity information from the registration request.
My question is:
from the server side, the server is able to get registration information, such as userId, userName etc., from HTTP Header (before the connection is upgraded to websocket), the only thing to do is letting the client put the identity into into HTTP Headers. Why people don't do it this way, and instead they use the handshake which is much more troublesome?
update
The client is able to open many channels, so we have to register every channel to track their usage. And because we will use the channel to send multiple types of messages and they are distingushed by cmd field in the body, so though we are able to get id information from headers, we still need to get channel usage information from websocket data for all the other commucations except the initial registration. To keep constistency between all messages, we register the channel by websocket data other than http header. Is it that reason??
| |
doc_23533896
|
=SORT(FILTER('Base Sheet'!$A$2:$F, 'Base Sheet'!$A$2:$A <> ""),5,False)
in order to import and sort from a different sheet. I now want a sum at the bottom of the table but every time i add a new data set to the origional sheet it breaks the sorted table.
I figured i needed to work out the place i want the sum to show :
=CELL("address",INDEX(F1:F21,MATCH(TRUE,ISBLANK(F1:F21),0)))
to locate the first blank space
i want something to the affect of =
show sum in cell
=CELL("address",INDEX(F1:F21,MATCH(TRUE,ISBLANK(F1:F21),0))))
any ideas how this can be achieved
i cant find a display in cell (x) kinda function
A: this outputs 5 columns:
=SORT(FILTER('Base Sheet'!A2:F, 'Base Sheet'!A2:A <> ""), 5, 0)
you can wrap it into {} and add row on the bottom like:
={SORT(FILTER('Base Sheet'!A2:F, 'Base Sheet'!A2:A <> ""), 5, 0);
"×", "×", "×", "×", "×"}
every "×" can be exchanged to whatever you need so for example if you want to sum only B column from your formula output you can do:
={SORT(FILTER('Base Sheet'!A2:F, 'Base Sheet'!A2:A <> ""), 5, 0);
"×", SUM(INDEX(FILTER('Base Sheet'!A2:F, 'Base Sheet'!A2:A <> ""),,2)), "×", "×", "×"}
| |
doc_23533897
|
async function Formulario() {
const schema = Yup.object().shape({
nome: Yup.string().required("Obrigatório!"),
cpf: Yup.string().required("Obrigatório!"),
});
const submitvalue = () => {
const frmdetails = {
'Nome': nonce,
'Cpf': cpff
};
};
return (
<ModalContent>
<h2>Dados do assinante</h2>
<Form schema={schema}>
<Row>
<Col>
<Input
type="text"
placeholder="Nome"
onChange={e => setNome(e.target.value)}
/>
</Col>
</Row>
<Row hascols>
<Col>
<InputMask
type="text"
placeholder="Cpf"
onChange={e => setCpf(e.target.value)}
/>
</Col>
</Row>
<ModalFooter>
<Button
onClick={() => {
submitvalue();
aceitarTce();
}}
block
variant="tangerine"
>
Aceitar
</Button>
</ModalFooter>
</Form>
</ModalContent>
);
}
The button is in return for the export default function, where the async function is inserted.
return (
<Controles>
{showControlls && (
<>
<Button
variant="tangerine"
onClick={() => Formulario()}
loading={loading || undefined}
>
Li, concordo e aceito
</Button>
<Button onClick={recusarTce} loading={loading || undefined}>
Recusar o contrato
</Button>
</>
)}
I've tried several ways and I couldn't, I ask for someone's help. Code made in react.js and javascript, with backend in PHP and Slim framework.
| |
doc_23533898
|
const path = require("path")
const UglifyJsPlugin = require("uglifyjs-webpack-plugin")
const glob = require("glob")
module.exports = {
entry: {
"bundle.js": glob.sync("build/static/?(js|css)/*.?(js|css)").map(f => path.resolve(__dirname, f)),
},
output: {
filename: "release/bundle.min.js",
},
module: {
rules: [
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
],
},
plugins: [new UglifyJsPlugin()],
}
And, this is my index.html
<html>
<body id="root">
<script src="path-to-bundle.min.js"></script>
</html>
But, I dont see anything mounted inside #root. Basically the script does not fire. I tried the var and EntryPoint webpack config as well. In that case, EntryPoint is always an empty object.
UPDATE:
Package.json
"start": "react-scripts start",
"test": "react-scripts test",
"eject": "react-scripts eject",
"build": "npm run build:react && npm run build:bundle",
"build:react": "react-scripts build",
"build:bundle": "webpack --config webpack.config.js"
| |
doc_23533899
|
A: Expanding on Kent's correct answer
When disambiguating when which method will be called, I like to think of shadowing vs. overriding with the following
*
*Shadowing: The method called depends on the type of the reference at the point the call is made
*Overriding: The method called depends on the type of the object at the point the call is made.
A: Shadowing hides a method in a base class. Using the example in the question you linked:
class A
{
public int Foo(){ return 5;}
public virtual int Bar(){return 5;}
}
class B : A
{
public new int Foo() { return 1;}
public override int Bar() {return 1;}
}
Class B overrides the virtual method Bar. It hides (shadows) the non-virtual method Foo. Override uses the override keyword. Shadowing is done with the new keyword.
In the code above, if you didn't use the new keyword when defining the Foo method in class B, you would get this compiler warning:
'test.B.Foo()' hides inherited member 'test.A.Foo()'. Use the new keyword if hiding was intended.
A: *
*Overriding : redefining an existing method on a base class
*Shadowing : creating an entirely new method with the same signature as one in a base class
A: Here's an MSDN article on Shadowing. The language examples are in Visual Basic (unfortunately there is no equivalent C# page on MSDN), but it deals generally with the concepts and hopefully should help you understand anyway.
Edit: Seems like there is a C# article on shadowing, except that it's called hiding in C#. Also, this page offers a good overview.
A: Suppose I have a base class that implements a virtual method:
public class A
{
public virtual void M() { Console.WriteLine("In A.M()."); }
}
I also have a derived class that also defines a method M:
public class B : A
{
// could be either "new" or "override", "new" is default
public void M() { Console.WriteLine("In B.M()."); }
}
Now, suppose I write a program like this:
A alpha = new B(); // it's really a B but I cast it to an A
alpha.M();
I have two different choices for how I want that to be implemented. The default behavior is to call A's version of M. (This is identical to the behavior if you applied the "new" keyword to B.M().)
This is called "shadowing" when we have a method with the same name but a different behavior when called from the base class.
Alternately, we could have specified "override" on B.M(). In this case, alpha.M() would have called B's version of M.
A: If you want to hide Base class method , Use override in base [virtual method in base]
if you want to hide Child class method , Use new in base [nonvirtual method in base]->shadow
Base B=new Child()
B.VirtualMethod() -> Calls Child class method
B.NonVirtualMethod() -> Calls Base class method
A: Shadowing consist on hiding a base class method with a new definition in a child class.
The difference between hiding and overriding has to do with the way methods are invoked.
That way, when a virtual method is overridden, the call address for the method call table of the base class is replaced with the address of the child routine.
On the other hand, when a method is hidden, a new address is added to the method call table of the child class.
When a call is made to the method in question:
*
*The method call table class type is obtained, if we are invoking with a reference to the base class then the base class method table is obtained, if we have a reference to the child class, then the child class method table is obtained.
*The method is searched in the table, if it's found then the invocation takes place, otherwise the base class method table is searched.
If we invoke the method with a reference to the child class then the behavior is the same, if the method has been overridden, the method address will be found in the base class, if the method was hidden the method address will be found on the child class, and since it has been already found, base class table will not be searched.
If we invoke the method with a reference to the base class then behavior changes. When overriding, as the method address overwrites base class entry, we will call the child method, even when holding a reference to the base class. With shadowing, the base class method table (which is the only one visible as we hold a reference to the base class) contains the virtual method address, and therefore, the base class method will be called.
In general shadowing is a bad idea, as it introduces a difference on the behavior of an instance depending on the reference we have to it.
A: Overriding: same name and exactly the same parameters, implemented
differently in sub classes.
*
*If treated as DerivedClass or BaseClass, it used derived method.
Shadowing: same name and exactly the same parameters, implemented differently in sub classes.
*
*If treated as DerivedClass, it used derived method.
*if treated as BaseClass, it uses base method.
A: Hope this brief explanation helps.
Shadowing - Replaces the complete element of the parent class
class InventoryAndSales
{
public int InvoiceNumber { get; set; }
}
//if someone calls for this class then the InvoiceNumber type is now object
class NewInventoryAndSales : InventoryAndSales
{
public new object InvoiceNumber { get; set; }
}
Overriding - Only replaces the implementation. It doesn't replace the data type it doesn't replace like for example you have a variable it doesn't convert it into a method so if there is a method it will use that method and only changed the implementation
class InventoryAndSales
{
public virtual int GetTotalSales(int a, int b)
{
return a + b;
}
}
class NewInventoryAndSales : InventoryAndSales
{
//it replaces the implementation in parent class
public override int GetTotalSales(int a, int b)
{
return a * b;
}
}
A: private static int x = 10;
static void Main(string[] args)
{ int x = 20;
if (Program.x == 10)
{
Console.WriteLine(Program.x);
}
Console.WriteLine(x);}
Output:
10
20
A: Shadowing isn't something I'd be worried about understanding or implementing unless it "fits" the problem really well. I've seen it used improperly and cause weird logic bugs much more often than being used correctly. The big cause, I think, is when the programmer forgets to put overrides in a method signature then the compiler warning will suggest the new keyword. I've always felt that it should recommend using override instead.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.